popost 4.6.8 → 4.6.10

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.
package/dist/index.js CHANGED
@@ -85,9 +85,9 @@ var init_i18n = __esm({
85
85
  "src/i18n.ts"() {
86
86
  "use strict";
87
87
  LANG_ENV = ["POPOST_LANG", "LC_ALL", "LC_MESSAGES", "LANG"];
88
- resolveLang = (env) => {
88
+ resolveLang = (env2) => {
89
89
  for (const name of LANG_ENV) {
90
- const value = (env[name] ?? "").trim();
90
+ const value = (env2[name] ?? "").trim();
91
91
  if (value) return value.toLowerCase().startsWith("zh") ? "zh" : "en";
92
92
  }
93
93
  return "en";
@@ -260,7 +260,7 @@ var VERSION;
260
260
  var init_version = __esm({
261
261
  "src/version.ts"() {
262
262
  "use strict";
263
- VERSION = "4.6.8";
263
+ VERSION = "4.6.10";
264
264
  }
265
265
  });
266
266
 
@@ -948,8 +948,8 @@ var init_post_bundle = __esm({
948
948
  const blocker = await resourceBlocker(rt, res, baseDir);
949
949
  if (blocker) blockers.push(blocker);
950
950
  }
951
- const missing2 = Array.isArray(bundle.missing) ? bundle.missing : [];
952
- for (const item2 of missing2) blockers.push(msg(`the bundle still declares a missing item: ${plain(item2)}`, `bundle \u4ECD\u58F0\u660E\u7F3A\u9879: ${plain(item2)}`));
951
+ const missing3 = Array.isArray(bundle.missing) ? bundle.missing : [];
952
+ for (const item2 of missing3) blockers.push(msg(`the bundle still declares a missing item: ${plain(item2)}`, `bundle \u4ECD\u58F0\u660E\u7F3A\u9879: ${plain(item2)}`));
953
953
  return { buildable: blockers.length === 0, blockers };
954
954
  };
955
955
  }
@@ -1603,11 +1603,11 @@ var init_args = __esm({
1603
1603
  );
1604
1604
  values.set(keyOf(positional.name), positional.variadic ? raws : raws[0]);
1605
1605
  });
1606
- const missing2 = [
1606
+ const missing3 = [
1607
1607
  ...declared.filter((p) => p.required !== false && !values.has(keyOf(p.name))).map((p) => p.name),
1608
1608
  ...(spec8.options ?? []).filter((o) => o.required && !values.has(keyOf(o.flag))).map((o) => o.flag)
1609
1609
  ];
1610
- if (missing2.length) throw new UsageError(`the following arguments are required: ${missing2.join(", ")}`);
1610
+ if (missing3.length) throw new UsageError(`the following arguments are required: ${missing3.join(", ")}`);
1611
1611
  for (const option of spec8.options ?? []) {
1612
1612
  const key2 = keyOf(option.flag);
1613
1613
  if (!values.has(key2) && option.default !== void 0) values.set(key2, option.default);
@@ -2785,9 +2785,9 @@ var init_project_bundle = __esm({
2785
2785
  const roles = JSON.parse(await rt.fs.readText(palette)).roles ?? [];
2786
2786
  for (const role of roles) {
2787
2787
  const dir = rt.path.join(fontRoot, role.id);
2788
- const present2 = (await walkFiles(rt, dir)).filter((f) => rt.path.dirname(f) === dir);
2789
- if (!present2.some((f) => f.endsWith(".woff2"))) continue;
2790
- for (const file of [rt.path.join(fontRoot, role.cssPath), ...present2])
2788
+ const present3 = (await walkFiles(rt, dir)).filter((f) => rt.path.dirname(f) === dir);
2789
+ if (!present3.some((f) => f.endsWith(".woff2"))) continue;
2790
+ for (const file of [rt.path.join(fontRoot, role.cssPath), ...present3])
2791
2791
  if (await isFile(rt, file)) add2(file);
2792
2792
  }
2793
2793
  return files;
@@ -3800,12 +3800,12 @@ var init_api = __esm({
3800
3800
  // ---------- sending ----------
3801
3801
  /** Returns the envelope's `data`. See the file header for what throws `AmbiguousSubmitError`. */
3802
3802
  async request(method, path2, options = {}) {
3803
- const { body, query, ambiguous = false, hint = "" } = options;
3804
- const device = !this.bearer && this.keyEnv === DEFAULT_KEY_ENV && this.rt.deviceAccess;
3805
- const key2 = device ? await device(this.baseUrl) : this.key();
3803
+ const { body, query, ambiguous = false, hint = "", anonymous = false } = options;
3804
+ const device = !anonymous && !this.bearer && this.keyEnv === DEFAULT_KEY_ENV && this.rt.deviceAccess;
3805
+ const key2 = anonymous ? null : device ? await device(this.baseUrl) : this.key();
3806
3806
  const wait = Number(options.timeoutSec || this.timeoutSec);
3807
3807
  const headers = { ...this.headers(body !== void 0), ...await taskHeaders(this.rt) };
3808
- headers.Authorization = `Bearer ${key2}`;
3808
+ if (key2) headers.Authorization = `Bearer ${key2}`;
3809
3809
  const signal = timeoutSignal(this.rt, wait * 1e3);
3810
3810
  const url = this.url(path2, query);
3811
3811
  try {
@@ -3971,6 +3971,86 @@ var init_api = __esm({
3971
3971
  }
3972
3972
  });
3973
3973
 
3974
+ // src/install/agents.ts
3975
+ var env, sharedSkillsDir, configHome, shared, own, AGENTS, AGENT_IDS, agentLabel;
3976
+ var init_agents = __esm({
3977
+ "src/install/agents.ts"() {
3978
+ "use strict";
3979
+ env = (rt, name) => {
3980
+ const value = (rt.env[name] ?? "").trim();
3981
+ return value ? rt.path.resolve(rt.cwd, value) : null;
3982
+ };
3983
+ sharedSkillsDir = (rt, home) => rt.path.join(home, ".agents", "skills");
3984
+ configHome = (rt, home) => env(rt, "XDG_CONFIG_HOME") ?? rt.path.join(home, ".config");
3985
+ shared = (id2, label2, homes, vars) => ({
3986
+ id: id2,
3987
+ label: label2,
3988
+ homes,
3989
+ skillsDir: sharedSkillsDir,
3990
+ ...vars ? { env: vars } : {}
3991
+ });
3992
+ own = (id2, label2, dir, variable) => {
3993
+ const home = (rt, base) => (variable ? env(rt, variable) : null) ?? rt.path.join(base, dir);
3994
+ return { id: id2, label: label2, homes: (rt, base) => [home(rt, base)], skillsDir: (rt, base) => rt.path.join(home(rt, base), "skills") };
3995
+ };
3996
+ AGENTS = [
3997
+ { ...own("claude-code", "Claude Code", ".claude"), env: ["CLAUDECODE"] },
3998
+ shared("codex", "Codex", (rt, home) => [env(rt, "CODEX_HOME") ?? rt.path.join(home, ".codex")], ["CODEX_THREAD_ID"]),
3999
+ own("workbuddy", "WorkBuddy", ".workbuddy"),
4000
+ {
4001
+ id: "gemini",
4002
+ label: "Gemini CLI",
4003
+ homes: (rt, home) => [rt.path.join(env(rt, "GEMINI_CLI_HOME") ?? home, ".gemini")],
4004
+ skillsDir: (rt, home) => sharedSkillsDir(rt, env(rt, "GEMINI_CLI_HOME") ?? home),
4005
+ env: ["GEMINI_CLI"]
4006
+ },
4007
+ {
4008
+ id: "antigravity",
4009
+ label: "Antigravity",
4010
+ homes: (rt, home) => [rt.path.join(home, ".gemini", "antigravity"), rt.path.join(home, ".gemini", "antigravity-cli")],
4011
+ skillsDir: (rt, home) => rt.path.join(home, ".gemini", "config", "skills")
4012
+ },
4013
+ shared("opencode", "OpenCode", (rt, home) => [rt.path.join(configHome(rt, home), "opencode")], ["OPENCODE"]),
4014
+ shared("cursor", "Cursor", (rt, home) => [rt.path.join(home, ".cursor")]),
4015
+ shared("grok", "Grok", (rt, home) => [env(rt, "GROK_HOME") ?? rt.path.join(home, ".grok")]),
4016
+ shared("kimi", "Kimi Code", (rt, home) => [env(rt, "KIMI_CODE_HOME") ?? rt.path.join(home, ".kimi-code"), rt.path.join(home, ".kimi")], ["KIMI_CODE_SESSION_ID"]),
4017
+ shared("qwen", "Qwen Code", (rt, home) => [env(rt, "QWEN_HOME") ?? rt.path.join(home, ".qwen")], ["QWEN_CODE"]),
4018
+ shared("vibe-cli", "Mistral Vibe", (rt, home) => [env(rt, "VIBE_HOME") ?? rt.path.join(home, ".vibe")]),
4019
+ {
4020
+ id: "copilot",
4021
+ label: "Copilot CLI",
4022
+ homes: (rt, home) => [env(rt, "COPILOT_HOME") ?? rt.path.join(home, ".copilot")],
4023
+ skillsDir: (rt, home) => {
4024
+ const moved = env(rt, "COPILOT_HOME");
4025
+ return moved ? rt.path.join(moved, "skills") : sharedSkillsDir(rt, home);
4026
+ },
4027
+ env: ["COPILOT_CLI"]
4028
+ },
4029
+ shared("kilo", "Kilo Code", (rt, home) => [rt.path.join(home, ".kilo"), rt.path.join(home, ".kilocode"), rt.path.join(configHome(rt, home), "kilo")], ["KILO"]),
4030
+ shared("pi", "Pi", (rt, home) => [env(rt, "PI_CODING_AGENT_DIR") ?? rt.path.join(home, ".pi", "agent")], ["PI_CODING_AGENT"]),
4031
+ shared("devin", "Devin", (rt, home) => [rt.path.join(configHome(rt, home), "devin")]),
4032
+ {
4033
+ id: "deepseek-harness",
4034
+ label: "DeepSeek Harness",
4035
+ homes: (rt, home) => [env(rt, "DSH_HOME") ?? rt.path.join(home, ".dsh")],
4036
+ skillsDir: (rt, home) => {
4037
+ const moved = env(rt, "DSH_AGENTS_HOME");
4038
+ return moved ? rt.path.join(moved, "skills") : sharedSkillsDir(rt, home);
4039
+ },
4040
+ env: ["DSH_SHELL"]
4041
+ },
4042
+ shared("reasonix", "Reasonix", (rt, home) => [env(rt, "REASONIX_HOME") ?? rt.path.join(home, ".reasonix")]),
4043
+ own("hermes", "Hermes", ".hermes", "HERMES_HOME"),
4044
+ own("trae", "Trae", ".trae"),
4045
+ own("trae-cn", "Trae CN", ".trae-cn"),
4046
+ own("qoder", "Qoder", ".qoder"),
4047
+ own("kiro", "Kiro", ".kiro", "KIRO_HOME")
4048
+ ];
4049
+ AGENT_IDS = AGENTS.map((agent) => agent.id);
4050
+ agentLabel = (id2) => AGENTS.find((agent) => agent.id === id2)?.label ?? id2;
4051
+ }
4052
+ });
4053
+
3974
4054
  // src/profile.ts
3975
4055
  var PROFILE_NAME, profileNameHint;
3976
4056
  var init_profile = __esm({
@@ -3997,11 +4077,12 @@ var init_device_login = __esm({
3997
4077
  init_api();
3998
4078
  init_util();
3999
4079
  init_i18n();
4080
+ init_agents();
4000
4081
  init_profile();
4001
- profileName = (env) => {
4002
- const configured = env.POPOST_AGENT_PROFILE?.trim();
4082
+ profileName = (env2) => {
4083
+ const configured = env2.POPOST_AGENT_PROFILE?.trim();
4003
4084
  if (configured && !PROFILE_NAME.test(configured)) throw new UsageError(profileNameHint());
4004
- return configured || (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT ? "claude-code" : env.CODEX_THREAD_ID || env.CODEX_CI ? "codex" : "terminal");
4085
+ return configured || (env2.CLAUDECODE || env2.CLAUDE_CODE_ENTRYPOINT ? "claude-code" : env2.CODEX_THREAD_ID || env2.CODEX_CI ? "codex" : "terminal");
4005
4086
  };
4006
4087
  deviceLocation = (rt) => {
4007
4088
  const root = credentialsDir(rt);
@@ -4116,7 +4197,7 @@ var init_device_login = __esm({
4116
4197
  if (!pending3 || pending3.expiresAt <= Date.now()) {
4117
4198
  const pair4 = generateKeyPairSync("ed25519");
4118
4199
  const publicKey = pair4.publicKey.export({ format: "jwk" }).x;
4119
- const agent = { codex: "Codex", "claude-code": "Claude Code", terminal: "CLI" }[profile] || profile;
4200
+ const agent = profile === "terminal" ? "CLI" : agentLabel(profile);
4120
4201
  const label2 = [agent, rt.deviceName].filter(Boolean).join(" \xB7 ").slice(0, 80);
4121
4202
  const start = await deviceApi(rt.fetch, baseUrl, "start", { label: label2, publicKey });
4122
4203
  pending3 = {
@@ -4436,29 +4517,6 @@ Key \u4FDD\u5B58\u5728 <home>/.popost/credentials.json\uFF08\u76EE\u5F55\uFF1APO
4436
4517
  }
4437
4518
  });
4438
4519
 
4439
- // src/install/agents.ts
4440
- var AGENTS, AGENT_IDS;
4441
- var init_agents = __esm({
4442
- "src/install/agents.ts"() {
4443
- "use strict";
4444
- AGENTS = [
4445
- {
4446
- id: "claude-code",
4447
- label: "Claude Code",
4448
- home: (rt, home) => rt.path.join(home, ".claude"),
4449
- skillsDir: (rt, home) => rt.path.join(home, ".claude", "skills")
4450
- },
4451
- {
4452
- id: "codex",
4453
- label: "Codex",
4454
- home: (rt, home) => (rt.env.CODEX_HOME ?? "").trim() ? rt.path.resolve(rt.cwd, rt.env.CODEX_HOME.trim()) : rt.path.join(home, ".codex"),
4455
- skillsDir: (rt, home) => rt.path.join(home, ".agents", "skills")
4456
- }
4457
- ];
4458
- AGENT_IDS = AGENTS.map((agent) => agent.id);
4459
- }
4460
- });
4461
-
4462
4520
  // src/install/payload.ts
4463
4521
  var NOT_COPIED, ALWAYS, SKIP_NAMES, segmentPattern, compile, relate, readManifest, listPayload;
4464
4522
  var init_payload = __esm({
@@ -4511,7 +4569,7 @@ var init_payload = __esm({
4511
4569
 
4512
4570
  // src/install/skill-install.ts
4513
4571
  import { createHash as createHash5 } from "node:crypto";
4514
- var SKILL_DIR_NAME, installedVersion, decide, stage, swap, installSkill;
4572
+ var SKILL_DIR_NAME, installedVersion, installedProfile, decide, stage, swap, installSkill;
4515
4573
  var init_skill_install = __esm({
4516
4574
  "src/install/skill-install.ts"() {
4517
4575
  "use strict";
@@ -4526,6 +4584,13 @@ var init_skill_install = __esm({
4526
4584
  return null;
4527
4585
  }
4528
4586
  };
4587
+ installedProfile = async (rt, skillDir) => {
4588
+ try {
4589
+ return /popost --profile ([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(await rt.fs.readText(rt.path.join(skillDir, "SKILL.md")))?.[1] ?? null;
4590
+ } catch {
4591
+ return null;
4592
+ }
4593
+ };
4529
4594
  decide = (exists3, previous, manifest, force2, dryRun2) => {
4530
4595
  const same5 = exists3 && previous === manifest.version;
4531
4596
  if (same5 && !force2) return "up-to-date";
@@ -4567,7 +4632,7 @@ var init_skill_install = __esm({
4567
4632
  try {
4568
4633
  await stage(rt, root, files, staging);
4569
4634
  const entry2 = rt.path.join(staging, "SKILL.md");
4570
- const profile = options.agent && options.agent !== "custom" ? options.agent : "agent-" + createHash5("sha256").update(skillsDir).digest("hex").slice(0, 10);
4635
+ const profile = (stat ? await installedProfile(rt, skillDir) : null) ?? (options.agent && options.agent !== "custom" ? options.agent : "agent-" + createHash5("sha256").update(skillsDir).digest("hex").slice(0, 10));
4571
4636
  const instructions = await rt.fs.readText(entry2);
4572
4637
  await rt.fs.writeFile(entry2, instructions.replace(
4573
4638
  "<!-- installed-profile -->",
@@ -4587,7 +4652,7 @@ var install_exports = {};
4587
4652
  __export(install_exports, {
4588
4653
  main: () => main4
4589
4654
  });
4590
- var OUTPUT, description2, spec2, detect, plan2, nextStep, run, main4;
4655
+ var OUTPUT, description2, spec2, SHARED, present, absent, byDirectory, ownerOf, plan2, fallbackNote, nextStep, run, main4;
4591
4656
  var init_install2 = __esm({
4592
4657
  "src/commands/install.ts"() {
4593
4658
  "use strict";
@@ -4599,18 +4664,18 @@ var init_install2 = __esm({
4599
4664
  init_i18n();
4600
4665
  init_api();
4601
4666
  init_version();
4602
- OUTPUT = `output: {"ok": true, "version", "dryRun", "installed": [{"agent", "skillDir", "status": "installed|updated|reinstalled|up-to-date|would-...", "previousVersion", "files"}], "skipped": [{"agent", "reason"}], "next"}`;
4667
+ OUTPUT = `output: {"ok": true, "version", "dryRun", "installed": [{"agent", "skillDir", "status": "installed|updated|reinstalled|up-to-date|would-...", "previousVersion", "files", "alsoFor": [agents that read the same directory]}], "skipped": [{"agent", "reason"}], "note", "next"}`;
4603
4668
  description2 = () => {
4604
4669
  const ids3 = AGENTS.map((a) => a.id).join(", ");
4605
4670
  return msg(
4606
- `Install the popost Skill for coding agents. Without --agent it installs for every supported agent whose home directory exists on this machine (${ids3}) and lists the ones skipped; --agent all forces all supported agents. For any other agent pass its skills directory with --dir. An existing install is replaced (atomically) when its version differs or with --force; the same version is reported as up-to-date. --dry-run shows what would happen and writes nothing.
4671
+ `Install the popost Skill for coding agents. Without --agent it installs for every supported agent found on this machine (${ids3}) and lists the ones skipped; agents that read the shared directory ~/.agents/skills get one copy there. When none of them is found, the Skill still goes to ~/.agents/skills, which most agents read, and the output says how to point another agent at it. --agent all forces all supported agents. For any other agent pass its skills directory with --dir. An existing install is replaced (atomically) when its version differs or with --force and keeps its sign-in profile; the same version is reported as up-to-date. --dry-run shows what would happen and writes nothing.
4607
4672
 
4608
4673
  ${OUTPUT}
4609
- failure: {"ok": false, "error", ...} exit 1 when nothing could be installed, 2 for a usage error`,
4610
- `\u4E3A\u7F16\u7A0B Agent \u5B89\u88C5 popost Skill\u3002\u4E0D\u5E26 --agent \u65F6\uFF0C\u5B89\u88C5\u5230\u672C\u673A\u6240\u6709\u5DF2\u6709\u4E3B\u76EE\u5F55\u7684\u53D7\u652F\u6301 Agent\uFF08${ids3}\uFF09\uFF0C\u5E76\u5217\u51FA\u8DF3\u8FC7\u7684\uFF1B--agent all \u5F3A\u5236\u5B89\u88C5\u5230\u6240\u6709\u53D7\u652F\u6301\u7684 Agent\u3002\u5176\u4ED6 Agent \u7528 --dir \u6307\u5B9A\u5B83\u7684 skills \u76EE\u5F55\u3002\u5DF2\u6709\u5B89\u88C5\u5728\u7248\u672C\u4E0D\u540C\u6216\u5E26 --force \u65F6\uFF08\u539F\u5B50\u5730\uFF09\u66FF\u6362\uFF1B\u7248\u672C\u76F8\u540C\u65F6\u62A5\u544A\u4E3A up-to-date\u3002--dry-run \u53EA\u663E\u793A\u5C06\u8981\u505A\u4EC0\u4E48\uFF0C\u4E0D\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002
4674
+ failure: {"ok": false, "error", ...} exit 1 when a directory could not be written, 2 for a usage error`,
4675
+ `\u4E3A\u7F16\u7A0B Agent \u5B89\u88C5 popost Skill\u3002\u4E0D\u5E26 --agent \u65F6\uFF0C\u5B89\u88C5\u5230\u672C\u673A\u627E\u5230\u7684\u6240\u6709\u53D7\u652F\u6301 Agent\uFF08${ids3}\uFF09\uFF0C\u5E76\u5217\u51FA\u8DF3\u8FC7\u7684\uFF1B\u8BFB\u53D6\u5171\u4EAB\u76EE\u5F55 ~/.agents/skills \u7684 Agent \u5171\u7528\u90A3\u91CC\u7684\u4E00\u4EFD\u3002\u4E00\u4E2A\u90FD\u6CA1\u627E\u5230\u65F6\uFF0C\u4ECD\u4F1A\u88C5\u5230\u591A\u6570 Agent \u90FD\u8BFB\u53D6\u7684 ~/.agents/skills\uFF0C\u5E76\u5728\u8F93\u51FA\u91CC\u8BF4\u660E\u5176\u4ED6 Agent \u5982\u4F55\u6307\u5B9A\u76EE\u5F55\u3002--agent all \u5F3A\u5236\u5B89\u88C5\u5230\u6240\u6709\u53D7\u652F\u6301\u7684 Agent\u3002\u5176\u4ED6 Agent \u7528 --dir \u6307\u5B9A\u5B83\u7684 skills \u76EE\u5F55\u3002\u5DF2\u6709\u5B89\u88C5\u5728\u7248\u672C\u4E0D\u540C\u6216\u5E26 --force \u65F6\uFF08\u539F\u5B50\u5730\uFF09\u66FF\u6362\uFF0C\u5E76\u4FDD\u7559\u539F\u6765\u7684\u767B\u5F55\u6863\u6848\uFF1B\u7248\u672C\u76F8\u540C\u65F6\u62A5\u544A\u4E3A up-to-date\u3002--dry-run \u53EA\u663E\u793A\u5C06\u8981\u505A\u4EC0\u4E48\uFF0C\u4E0D\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002
4611
4676
 
4612
4677
  ${OUTPUT}
4613
- failure: {"ok": false, "error", ...} \u4E00\u4E2A\u90FD\u88C5\u4E0D\u4E0A\u65F6\u9000\u51FA\u7801 1\uFF0C\u7528\u6CD5\u9519\u8BEF\u4E3A 2`
4678
+ failure: {"ok": false, "error", ...} \u76EE\u5F55\u5199\u4E0D\u8FDB\u53BB\u65F6\u9000\u51FA\u7801 1\uFF0C\u7528\u6CD5\u9519\u8BEF\u4E3A 2`
4614
4679
  );
4615
4680
  };
4616
4681
  spec2 = () => ({
@@ -4634,14 +4699,30 @@ failure: {"ok": false, "error", ...} \u4E00\u4E2A\u90FD\u88C5\u4E0D\u4E0A\u65F6\
4634
4699
  { flag: "--dry-run", kind: "flag", help: msg("show what would be installed; write nothing", "\u53EA\u663E\u793A\u5C06\u8981\u5B89\u88C5\u4EC0\u4E48\uFF0C\u4E0D\u5199\u5165") }
4635
4700
  ]
4636
4701
  });
4637
- detect = async (rt, agent, homeDir2) => {
4638
- const home = agent.home(rt, homeDir2);
4639
- if ((await rt.fs.stat(home))?.isDirectory) return null;
4702
+ SHARED = "shared";
4703
+ present = async (rt, agent, homeDir2) => {
4704
+ if ((agent.env ?? []).some((name) => (rt.env[name] ?? "").trim())) return true;
4705
+ for (const home of agent.homes(rt, homeDir2)) if ((await rt.fs.stat(home))?.isDirectory) return true;
4706
+ return false;
4707
+ };
4708
+ absent = (rt, agent, homeDir2) => {
4709
+ const homes = agent.homes(rt, homeDir2).join(msg(" or ", " \u6216 "));
4640
4710
  return msg(
4641
- `${agent.label} is not installed here (${home} does not exist); use --agent ${agent.id} to install anyway`,
4642
- `\u672C\u673A\u6CA1\u6709\u5B89\u88C5 ${agent.label}\uFF08${home} \u4E0D\u5B58\u5728\uFF09\uFF1B\u4ECD\u8981\u5B89\u88C5\u8BF7\u7528 --agent ${agent.id}`
4711
+ `${agent.label} is not installed here (${homes} does not exist); use --agent ${agent.id} to install anyway`,
4712
+ `\u672C\u673A\u6CA1\u6709\u5B89\u88C5 ${agent.label}\uFF08${homes} \u4E0D\u5B58\u5728\uFF09\uFF1B\u4ECD\u8981\u5B89\u88C5\u8BF7\u7528 --agent ${agent.id}`
4643
4713
  );
4644
4714
  };
4715
+ byDirectory = (rt, agents, homeDir2) => {
4716
+ const dirs = [...new Set(agents.map((agent) => agent.skillsDir(rt, homeDir2)))];
4717
+ return dirs.map((skillsDir) => {
4718
+ const [first, ...rest] = agents.filter((agent) => agent.skillsDir(rt, homeDir2) === skillsDir).map((agent) => agent.id);
4719
+ return { agent: first, skillsDir, alsoFor: rest };
4720
+ });
4721
+ };
4722
+ ownerOf = (rt, homeDir2, skillsDir) => {
4723
+ const owners = homeDir2 === void 0 ? [] : AGENTS.filter((agent) => agent.skillsDir(rt, homeDir2) === skillsDir);
4724
+ return owners.length === 1 ? owners[0].id : "custom";
4725
+ };
4645
4726
  plan2 = async (rt, args, homeDir2) => {
4646
4727
  const dir = args.string("dir");
4647
4728
  const asked2 = args.list("agent");
@@ -4649,21 +4730,28 @@ failure: {"ok": false, "error", ...} \u4E00\u4E2A\u90FD\u88C5\u4E0D\u4E0A\u65F6\
4649
4730
  if (asked2.length)
4650
4731
  throw new UsageError(msg("--dir and --agent cannot be combined: --dir names the skills directory itself", "--dir \u548C --agent \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\uFF1A--dir \u76F4\u63A5\u6307\u5B9A skills \u76EE\u5F55"));
4651
4732
  if (!dir.trim()) throw new UsageError(msg("--dir is empty", "--dir \u4E3A\u7A7A"));
4652
- return { targets: [{ agent: "custom", skillsDir: rt.path.resolve(rt.cwd, dir) }], skipped: [] };
4733
+ const skillsDir = rt.path.resolve(rt.cwd, dir);
4734
+ return { targets: [{ agent: ownerOf(rt, homeDir2, skillsDir), skillsDir, alsoFor: [] }], skipped: [], fallback: false };
4653
4735
  }
4654
4736
  if (homeDir2 === void 0)
4655
4737
  throw new UsageError(msg("no user home directory in this environment: pass --dir <skills directory>", "\u5F53\u524D\u73AF\u5883\u6CA1\u6709\u7528\u6237\u4E3B\u76EE\u5F55\uFF1A\u8BF7\u4F20 --dir <skills \u76EE\u5F55>"));
4656
- const explicit = asked2.length > 0;
4657
- const wanted = asked2.includes("all") || !explicit ? AGENTS : AGENTS.filter((a) => asked2.includes(a.id));
4658
- const targets = [];
4738
+ if (asked2.length) {
4739
+ const wanted = asked2.includes("all") ? AGENTS : AGENTS.filter((a) => asked2.includes(a.id));
4740
+ return { targets: byDirectory(rt, wanted, homeDir2), skipped: [], fallback: false };
4741
+ }
4742
+ const found = [];
4659
4743
  const skipped2 = [];
4660
- for (const agent of wanted) {
4661
- const reason2 = explicit ? null : await detect(rt, agent, homeDir2);
4662
- if (reason2) skipped2.push({ agent: agent.id, reason: reason2 });
4663
- else targets.push({ agent: agent.id, skillsDir: agent.skillsDir(rt, homeDir2) });
4744
+ for (const agent of AGENTS) {
4745
+ if (await present(rt, agent, homeDir2)) found.push(agent);
4746
+ else skipped2.push({ agent: agent.id, reason: absent(rt, agent, homeDir2) });
4664
4747
  }
4665
- return { targets, skipped: skipped2 };
4748
+ if (!found.length) return { targets: [{ agent: SHARED, skillsDir: sharedSkillsDir(rt, homeDir2), alsoFor: [] }], skipped: skipped2, fallback: true };
4749
+ return { targets: byDirectory(rt, found, homeDir2), skipped: skipped2, fallback: false };
4666
4750
  };
4751
+ fallbackNote = (skillsDir) => msg(
4752
+ `No agent known to this installer was found on this machine, so the Skill was put in ${skillsDir}, the shared skills directory that Codex, Gemini CLI, Cursor, OpenCode, Copilot CLI and most other agents read. If your agent keeps skills somewhere else, run popost install --dir <its skills directory> (the Skill goes to <dir>/popost).`,
4753
+ `\u672C\u673A\u6CA1\u6709\u627E\u5230\u5B89\u88C5\u5668\u8BA4\u8BC6\u7684 Agent\uFF0C\u6240\u4EE5 Skill \u88C5\u5230\u4E86 ${skillsDir}\uFF1A\u8FD9\u662F Codex\u3001Gemini CLI\u3001Cursor\u3001OpenCode\u3001Copilot CLI \u7B49\u591A\u6570 Agent \u90FD\u4F1A\u8BFB\u53D6\u7684\u5171\u4EAB skills \u76EE\u5F55\u3002\u5982\u679C\u4F60\u7684 Agent \u628A skills \u653E\u5728\u522B\u5904\uFF0C\u8BF7\u8FD0\u884C popost install --dir <\u5B83\u7684 skills \u76EE\u5F55>\uFF08Skill \u4F1A\u88C5\u5230 <\u76EE\u5F55>/popost\uFF09\u3002`
4754
+ );
4667
4755
  nextStep = (page2) => msg(
4668
4756
  `Restart the agent only if it has not discovered the Skill; keep the supplied companion CLI when using a pinned build. How to use it, for example:
4669
4757
  Reproduce a video: Reference video: XX link. Use popost to reproduce its style, structure and hook; my content is: XX.
@@ -4681,29 +4769,22 @@ Popost cloud is the recommended integrated route for models and compute. Support
4681
4769
  \u9700\u8981\u4E91\u7AEF\u6A21\u578B\u6216\u7B97\u529B\u65F6\uFF0C\u4F18\u5148\u63A8\u8350 Popost\uFF1B\u4E5F\u53EF\u4F7F\u7528\u53D7\u652F\u6301\u7684\u81EA\u5E26\u670D\u52A1\u6216 Agent \u5DE5\u5177\uFF0C\u5E76\u4FDD\u7559\u5DF2\u6709\u9009\u62E9\u3002\u4F7F\u7528 Popost \u670D\u52A1\u65F6\uFF0C\u590D\u7528\u8D26\u53F7\u8FDE\u63A5\u6216\u8FD0\u884C popost auth login\uFF0C\u7531 CLI \u6253\u5F00\u72EC\u7ACB\u684C\u9762\u6D4F\u89C8\u5668\uFF0C\u628A\u8BBE\u5907\u7801\u53D1\u7ED9\u7528\u6237\uFF1B\u4E0D\u8981\u5728 Agent \u4FA7\u8FB9\u680F\u4E2D\u767B\u5F55\uFF0C\u7B49\u5F85\u6D4F\u89C8\u5668\u6388\u6743\u548C CLI \u9A8C\u8BC1\u6210\u529F\u3002\u5728 ${page2} \u7BA1\u7406\u8BBF\u95EE\u3002\u8FDE\u63A5\u8D26\u6237\u4E0D\u4EE3\u8868\u6388\u6743\u6D88\u8D39\uFF1B\u5DF2\u6709\u6388\u6743\u8986\u76D6\u7684\u4EFB\u52A1\uFF0C\u5728\u8303\u56F4\u548C\u9884\u7B97\u5185\u7EE7\u7EED\u6267\u884C\uFF0C\u4E0D\u91CD\u590D\u786E\u8BA4\u3002`
4682
4770
  );
4683
4771
  run = async (rt, args) => {
4684
- const { targets, skipped: skipped2 } = await plan2(rt, args, rt.homeDir);
4772
+ const { targets, skipped: skipped2, fallback } = await plan2(rt, args, rt.homeDir);
4685
4773
  const dryRun2 = args.flag("dry-run");
4686
4774
  const installed = [];
4687
4775
  const failed4 = [];
4688
4776
  for (const target2 of targets) {
4689
4777
  try {
4690
- installed.push({ agent: target2.agent, ...await installSkill(rt, target2.skillsDir, { force: args.flag("force"), dryRun: dryRun2, agent: target2.agent }) });
4778
+ const result = await installSkill(rt, target2.skillsDir, { force: args.flag("force"), dryRun: dryRun2, ...target2.agent === SHARED ? {} : { agent: target2.agent } });
4779
+ installed.push({ agent: target2.agent, ...result, ...target2.alsoFor.length ? { alsoFor: target2.alsoFor } : {} });
4691
4780
  } catch (error2) {
4692
4781
  failed4.push({ agent: target2.agent, error: errorText(error2) });
4693
4782
  }
4694
4783
  }
4695
4784
  const page2 = keyPageUrl((rt.env[BASE_URL_ENV] ?? "").trim() || DEFAULT_BASE_URL);
4696
- if (!installed.length)
4697
- return fail(
4698
- rt,
4699
- failed4.length ? msg("the Skill could not be installed", "Skill \u5B89\u88C5\u5931\u8D25") : msg(
4700
- "no supported agent found on this machine: use --agent all to install for every supported agent anyway, or --dir <skills directory> for another agent",
4701
- "\u672C\u673A\u6CA1\u6709\u627E\u5230\u53D7\u652F\u6301\u7684 Agent\uFF1A\u4ECD\u8981\u5B89\u88C5\u5230\u6240\u6709\u53D7\u652F\u6301\u7684 Agent \u8BF7\u7528 --agent all\uFF0C\u5176\u4ED6 Agent \u7528 --dir <skills \u76EE\u5F55>"
4702
- ),
4703
- 1,
4704
- { skipped: skipped2, ...failed4.length ? { failed: failed4 } : {} }
4705
- );
4706
- printJson(rt, { ok: failed4.length === 0, version: VERSION, dryRun: dryRun2, installed, skipped: skipped2, ...failed4.length ? { failed: failed4 } : {}, next: dryRun2 ? msg("Dry run: nothing was written.", "Dry run\uFF1A\u6CA1\u6709\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002") : nextStep(page2) }, true);
4785
+ if (!installed.length) return fail(rt, msg("the Skill could not be installed", "Skill \u5B89\u88C5\u5931\u8D25"), 1, { skipped: skipped2, failed: failed4 });
4786
+ const note = fallback ? { note: fallbackNote(targets[0].skillsDir) } : {};
4787
+ printJson(rt, { ok: failed4.length === 0, version: VERSION, dryRun: dryRun2, installed, skipped: skipped2, ...failed4.length ? { failed: failed4 } : {}, ...note, next: dryRun2 ? msg("Dry run: nothing was written.", "Dry run\uFF1A\u6CA1\u6709\u5199\u5165\u4EFB\u4F55\u6587\u4EF6\u3002") : nextStep(page2) }, true);
4707
4788
  return failed4.length ? 1 : 0;
4708
4789
  };
4709
4790
  main4 = (argv, rt) => withArgs(argv, spec2(), rt, async (args) => {
@@ -5402,7 +5483,7 @@ var init_paths = __esm({
5402
5483
  });
5403
5484
 
5404
5485
  // src/providers/popost-async.ts
5405
- var STATES, imageTaskOf, generationAnswer, routeMissing, fallbackNote, TRANSIENT_CODES, isTransient, failureText2, refundText;
5486
+ var STATES, imageTaskOf, generationAnswer, routeMissing, fallbackNote2, TRANSIENT_CODES, isTransient, failureText2, refundText;
5406
5487
  var init_popost_async = __esm({
5407
5488
  "src/providers/popost-async.ts"() {
5408
5489
  "use strict";
@@ -5431,7 +5512,7 @@ var init_popost_async = __esm({
5431
5512
  ...task.balance !== null ? { balance: task.balance } : {}
5432
5513
  });
5433
5514
  routeMissing = (error2) => error2 instanceof PopostApiError && (error2.status === 404 || error2.code === "NOT_FOUND");
5434
- fallbackNote = (rt) => rt.stderr(
5515
+ fallbackNote2 = (rt) => rt.stderr(
5435
5516
  msg(
5436
5517
  "note: popost.ai has no image task endpoint here yet; the picture is made with the synchronous call under the same idempotency key, and this call waits for it.\n",
5437
5518
  "\u63D0\u793A\uFF1Apopost.ai \u8FD9\u91CC\u8FD8\u6CA1\u6709\u751F\u56FE\u4EFB\u52A1\u63A5\u53E3\uFF1B\u6539\u7528\u540C\u6B65\u751F\u56FE\uFF08\u540C\u4E00\u5E42\u7B49\u952E\uFF09\uFF0C\u672C\u6B21\u4F1A\u7B49\u5230\u56FE\u51FA\u6765\u3002\n"
@@ -6018,7 +6099,7 @@ var init_popost = __esm({
6018
6099
  } catch (error2) {
6019
6100
  if (!(error2 instanceof AmbiguousSubmitError)) await this.rt.fs.rm(root);
6020
6101
  if (!routeMissing(error2)) throw error2;
6021
- fallbackNote(this.rt);
6102
+ fallbackNote2(this.rt);
6022
6103
  return this.generate(body, model, aspect, count5, idem);
6023
6104
  }
6024
6105
  const task = imageTaskOf(data);
@@ -8322,18 +8403,18 @@ var init_steps = __esm({
8322
8403
  };
8323
8404
  fontsStep = async (ctx) => {
8324
8405
  const project = projectOf(ctx);
8325
- const missing2 = [];
8326
- for (const role of ctx.spec.fonts) if (!await isInstalled(project, role)) missing2.push(role);
8327
- if (!missing2.length)
8406
+ const missing3 = [];
8407
+ for (const role of ctx.spec.fonts) if (!await isInstalled(project, role)) missing3.push(role);
8408
+ if (!missing3.length)
8328
8409
  return skipped(
8329
8410
  msg(`font roles already installed: ${ctx.spec.fonts.join(", ")}`, `\u5B57\u4F53\u89D2\u8272\u5DF2\u5B89\u88C5\uFF1A${ctx.spec.fonts.join(", ")}`) + linksNote(project)
8330
8411
  );
8331
- const { result, fontLinks } = await installFonts(ctx.rt, project, missing2.join(","), true);
8412
+ const { result, fontLinks } = await installFonts(ctx.rt, project, missing3.join(","), true);
8332
8413
  const { installed } = result;
8333
- const kept2 = ctx.spec.fonts.length - missing2.length;
8414
+ const kept2 = ctx.spec.fonts.length - missing3.length;
8334
8415
  const detail2 = msg(
8335
- `installed ${missing2.join(", ")}${kept2 ? `; ${kept2} already installed` : ""}`,
8336
- `\u5DF2\u5B89\u88C5 ${missing2.join(", ")}${kept2 ? `\uFF1B${kept2} \u4E2A\u6B64\u524D\u5DF2\u5B89\u88C5` : ""}`
8416
+ `installed ${missing3.join(", ")}${kept2 ? `; ${kept2} already installed` : ""}`,
8417
+ `\u5DF2\u5B89\u88C5 ${missing3.join(", ")}${kept2 ? `\uFF1B${kept2} \u4E2A\u6B64\u524D\u5DF2\u5B89\u88C5` : ""}`
8337
8418
  ) + linksNote(project);
8338
8419
  return done(detail2, [], cjkFontWarnings(project, installed.map((role) => role.id)), fontLinks);
8339
8420
  };
@@ -9836,7 +9917,7 @@ var init_service = __esm({
9836
9917
  });
9837
9918
 
9838
9919
  // src/editor/handoff.ts
9839
- var EDITOR_VERSION, editorInfo, resolveHost, editorHandoff, handoff, sleep2, probe, isLoopbackOrigin, saveHandoff, reusable, readLog, READY_TIMEOUT_MS, reportedCloud, presentLocal, presentCloud, WEB_HOST, present;
9920
+ var EDITOR_VERSION, serviceState, recordService, editorInfo, resolveHost, editorHandoff, handoff, sleep2, probe, isLoopbackOrigin, saveHandoff, reusable, readLog, READY_TIMEOUT_MS, reportedCloud, BACKGROUND_TASK_HOSTS, shellWord, startInBackground, presentLocal, presentCloud, WEB_HOST, present2;
9840
9921
  var init_handoff = __esm({
9841
9922
  "src/editor/handoff.ts"() {
9842
9923
  "use strict";
@@ -9850,6 +9931,11 @@ var init_handoff = __esm({
9850
9931
  init_i18n();
9851
9932
  init_canvas_state();
9852
9933
  EDITOR_VERSION = "4.1.3";
9934
+ serviceState = (rt, root) => rt.path.join(root, STATE_DIR, "service.json");
9935
+ recordService = async (rt, root, url, pid) => {
9936
+ await rt.fs.mkdir(rt.path.join(root, STATE_DIR));
9937
+ await writeJson(rt, serviceState(rt, root), { url, ...pid !== void 0 ? { pid } : {}, version: EDITOR_VERSION });
9938
+ };
9853
9939
  editorInfo = (project) => {
9854
9940
  const identity = sha256(project.rt.path.resolve(project.root));
9855
9941
  return {
@@ -9893,7 +9979,8 @@ var init_handoff = __esm({
9893
9979
  try {
9894
9980
  const response = await rt.fetch(`${url}/api/editor-info`, { signal: AbortSignal.timeout(700) });
9895
9981
  const info = await response.json();
9896
- return info.projectIdentity === expected2.projectIdentity && info.version === EDITOR_VERSION;
9982
+ if (info.projectIdentity !== expected2.projectIdentity || info.version !== EDITOR_VERSION) return false;
9983
+ return (await rt.fetch(`${url}/editor.html`, { method: "HEAD", signal: AbortSignal.timeout(2e3) })).ok;
9897
9984
  } catch {
9898
9985
  return false;
9899
9986
  }
@@ -9952,30 +10039,43 @@ var init_handoff = __esm({
9952
10039
  return { mode: "off", state: "idle" };
9953
10040
  }
9954
10041
  };
10042
+ BACKGROUND_TASK_HOSTS = /* @__PURE__ */ new Set(["workbuddy"]);
10043
+ shellWord = (word2) => /^[\w@%+=:,./-]+$/.test(word2) ? word2 : `'${word2.replace(/'/g, `'\\''`)}'`;
10044
+ startInBackground = (rt, host, argv) => ({
10045
+ ok: false,
10046
+ code: "START_SERVICE",
10047
+ host: resolveHost(rt, host),
10048
+ // --port as present got it: 0 (the default) lets the service pick a free port, which a stale service may still hold.
10049
+ startService: { argv, command: argv.map(shellWord).join(" "), background: true },
10050
+ next: msg(
10051
+ 'This host stops a service started inside an ordinary command once that command ends. Run startService.command as a background task of the host (one that keeps running after this call), wait for its {"listening": \u2026} line, then run this same present command again: it finds that service and prints open.url.',
10052
+ '\u8FD9\u4E2A\u5BBF\u4E3B\u4F1A\u5728\u666E\u901A\u547D\u4EE4\u7ED3\u675F\u540E\u5207\u65AD\u5B83\u542F\u52A8\u7684\u670D\u52A1\u3002\u8BF7\u628A startService.command \u4F5C\u4E3A\u5BBF\u4E3B\u7684\u540E\u53F0\u4EFB\u52A1\u8FD0\u884C\uFF08\u8C03\u7528\u7ED3\u675F\u540E\u4ECD\u6301\u7EED\u8FD0\u884C\uFF09\uFF0C\u7B49\u5B83\u8F93\u51FA {"listening": \u2026} \u8FD9\u4E00\u884C\uFF0C\u518D\u8FD0\u884C\u540C\u4E00\u6761 present \u547D\u4EE4\uFF1A\u5B83\u4F1A\u627E\u5230\u8FD9\u4E2A\u670D\u52A1\u5E76\u7ED9\u51FA open.url\u3002'
10053
+ )
10054
+ });
9955
10055
  presentLocal = async (rt, project, host, port, cloud = true, fallback) => {
9956
10056
  const processes = rt.processes;
9957
10057
  if (!processes) throw new Error(msg("the local editor service is not available in this host", "\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301\u672C\u5730\u7F16\u8F91\u5668\u670D\u52A1"));
9958
10058
  const info = editorInfo(project);
9959
10059
  const dir = rt.path.join(project.root, STATE_DIR);
9960
10060
  await rt.fs.mkdir(dir);
9961
- const state = rt.path.join(dir, "service.json");
9962
- const running = await reusable(rt, state, info, port);
10061
+ const running = await reusable(rt, serviceState(rt, project.root), info, port);
9963
10062
  const mode = resolveCloudMode(rt, cloud, Boolean(fallback));
9964
10063
  const localHandoff = (url, reused, status2) => saveHandoff(rt, project, handoff(rt, project, url, host, reused, { ...status2, ...fallback ? { error: fallback } : {} }));
9965
10064
  if (running) {
9966
10065
  const status2 = await reportedCloud(rt, running);
9967
10066
  if (mode === status2.mode) return localHandoff(running, true, status2);
9968
10067
  }
9969
- const log = rt.path.join(dir, `server-${rt.now().getTime()}.log`);
9970
10068
  const cloudArg = !cloud ? "off" : fallback ? "login" : "auto";
9971
10069
  const argv = [...processes.selfCommand, "serve", "--dir", project.root, "--port", String(port), "--cloud", cloudArg];
10070
+ if (BACKGROUND_TASK_HOSTS.has(resolveHost(rt, host))) return startInBackground(rt, host, argv);
10071
+ const log = rt.path.join(dir, `server-${rt.now().getTime()}.log`);
9972
10072
  const { pid } = await processes.spawnDetached(argv, { cwd: rt.cwd, logFile: log });
9973
10073
  const deadline2 = rt.now().getTime() + READY_TIMEOUT_MS;
9974
10074
  while (rt.now().getTime() < deadline2) {
9975
10075
  const { url, error: error2 } = await readLog(rt, log, info);
9976
10076
  if (error2) throw new Error(msg(`editor service did not start: ${error2}; inspect ${log}`, `\u7F16\u8F91\u5668\u670D\u52A1\u6CA1\u6709\u542F\u52A8\uFF1A${error2}\uFF1B\u8BF7\u67E5\u770B ${log}`));
9977
10077
  if (url) {
9978
- await writeJson(rt, state, { url, pid, version: EDITOR_VERSION });
10078
+ await recordService(rt, project.root, url, pid);
9979
10079
  return localHandoff(url, false, await reportedCloud(rt, url));
9980
10080
  }
9981
10081
  await sleep2(50);
@@ -9994,19 +10094,19 @@ var init_handoff = __esm({
9994
10094
  return editorHandoff(rt, project, url, host, "web-http", { mode: "keyed", state: "saved", deckId, webUrl });
9995
10095
  };
9996
10096
  WEB_HOST = "web";
9997
- present = async (rt, project, host, port, cloud = true) => {
9998
- const own2 = rt.editorHost;
9999
- if (host === WEB_HOST && !own2)
10097
+ present2 = async (rt, project, host, port, cloud = true) => {
10098
+ const own3 = rt.editorHost;
10099
+ if (host === WEB_HOST && !own3)
10000
10100
  throw new Error(
10001
10101
  msg(
10002
10102
  "--host web needs a host that shows projects itself (the popost.ai workbench); this one has none",
10003
10103
  "--host web \u9700\u8981\u4E00\u4E2A\u80FD\u81EA\u5DF1\u5C55\u793A\u5DE5\u7A0B\u7684\u5BBF\u4E3B\uFF08popost.ai \u5DE5\u4F5C\u53F0\uFF09\uFF1B\u5F53\u524D\u5BBF\u4E3B\u6CA1\u6709"
10004
10104
  )
10005
10105
  );
10006
- if (own2 && (host === WEB_HOST || host === "auto" || host === own2.id)) return own2.present(project.root);
10106
+ if (own3 && (host === WEB_HOST || host === "auto" || host === own3.id)) return own3.present(project.root);
10007
10107
  if (!rt.processes)
10008
10108
  throw new Error(
10009
- own2 ? msg(
10109
+ own3 ? msg(
10010
10110
  `host "${host}" is not available here: the project is shown by the host's own editor (--host ${WEB_HOST} or auto)`,
10011
10111
  `\u8FD9\u91CC\u4E0D\u80FD\u7528\u5BBF\u4E3B "${host}"\uFF1A\u5DE5\u7A0B\u7531\u5BBF\u4E3B\u81EA\u5E26\u7684\u7F16\u8F91\u5668\u5C55\u793A\uFF08--host ${WEB_HOST} \u6216 auto\uFF09`
10012
10112
  ) : msg(
@@ -10287,9 +10387,9 @@ var init_routes_get = __esm({
10287
10387
  const html2 = editorHtml(await ctx.load(), source2, ctx.req.rawQuery, ctx.state.cloud.mode());
10288
10388
  return noStoreResponse(html2, "text/html; charset=utf-8");
10289
10389
  };
10290
- staticFile = async (ctx, root, urlPath, missing2) => {
10390
+ staticFile = async (ctx, root, urlPath, missing3) => {
10291
10391
  const file = await readProjectFile(ctx.rt, root, urlPath);
10292
- return file ? fileResponse(file.data, mimeType(file.path)) : notFound(ctx, missing2);
10392
+ return file ? fileResponse(file.data, mimeType(file.path)) : notFound(ctx, missing3);
10293
10393
  };
10294
10394
  EXACT = {
10295
10395
  "/api/export-options": async (ctx) => {
@@ -10671,6 +10771,7 @@ var init_server = __esm({
10671
10771
  init_util();
10672
10772
  init_i18n();
10673
10773
  init_http_types();
10774
+ init_handoff();
10674
10775
  init_request_security();
10675
10776
  init_routes_get();
10676
10777
  init_routes_post();
@@ -10731,10 +10832,10 @@ var init_server = __esm({
10731
10832
  port
10732
10833
  };
10733
10834
  };
10734
- send = (res, response) => {
10835
+ send = (res, response, head = false) => {
10735
10836
  const body = typeof response.body === "string" ? encoder.encode(response.body) : response.body;
10736
10837
  res.writeHead(response.status, { ...response.headers, "Content-Length": String(body.byteLength) });
10737
- res.end(body);
10838
+ res.end(head ? void 0 : body);
10738
10839
  };
10739
10840
  createCtx = (rt, state, lock, req) => ({
10740
10841
  rt,
@@ -10745,7 +10846,7 @@ var init_server = __esm({
10745
10846
  });
10746
10847
  dispatch2 = async (rt, state, lock, req) => {
10747
10848
  const ctx = createCtx(rt, state, lock, req);
10748
- if (req.method === "GET") return handleGet(ctx);
10849
+ if (req.method === "GET" || req.method === "HEAD") return handleGet(ctx);
10749
10850
  if (req.method === "POST") return handlePost(ctx);
10750
10851
  return jsonResponse(req, 501, { ok: false, error: msg(`unsupported method ${req.method}`, `\u4E0D\u652F\u6301\u7684\u8BF7\u6C42\u65B9\u6CD5 ${req.method}`) });
10751
10852
  };
@@ -10759,7 +10860,7 @@ var init_server = __esm({
10759
10860
  const stub = toRequest(req, new Uint8Array(), port());
10760
10861
  return send(res, jsonResponse(stub, 413, { ok: false, error: msg("request body is too large", "\u8BF7\u6C42\u4F53\u8FC7\u5927") }));
10761
10862
  }
10762
- send(res, await dispatch2(rt, state, lock, toRequest(req, body, port())));
10863
+ send(res, await dispatch2(rt, state, lock, toRequest(req, body, port())), req.method === "HEAD");
10763
10864
  } catch (error2) {
10764
10865
  if (!res.headersSent) send(res, jsonResponse(toRequest(req, new Uint8Array(), port()), 500, { ok: false, error: errorMessage(error2) }));
10765
10866
  else res.destroy();
@@ -10790,7 +10891,9 @@ var init_server = __esm({
10790
10891
  });
10791
10892
  });
10792
10893
  listening = await listen(server, port);
10793
- printJson(rt, { ok: true, listening: `http://127.0.0.1:${listening}`, project: project.root });
10894
+ const url = `http://127.0.0.1:${listening}`;
10895
+ await recordService(rt, project.root, url);
10896
+ printJson(rt, { ok: true, listening: url, project: project.root });
10794
10897
  state.cloud.autoStart();
10795
10898
  await new Promise((resolve2) => {
10796
10899
  server.once("close", resolve2);
@@ -10940,7 +11043,7 @@ var init_render = __esm({
10940
11043
  run: async (args, rt) => {
10941
11044
  const project = await Project.load(rt, args.req("dir"));
10942
11045
  try {
10943
- const result = await present(rt, project, args.req("host"), args.number("port") ?? 0, args.req("cloud") !== "off");
11046
+ const result = await present2(rt, project, args.req("host"), args.number("port") ?? 0, args.req("cloud") !== "off");
10944
11047
  printJson(rt, result, true);
10945
11048
  return result.ok === false ? 2 : 0;
10946
11049
  } catch (error2) {
@@ -12582,8 +12685,8 @@ var init_inspiration_plan = __esm({
12582
12685
  const b = bundle;
12583
12686
  if (b.parseStatus !== "ready" && !options.allowIncomplete) {
12584
12687
  const errorsOf = b.errors ?? [];
12585
- const missing2 = (b.missing ?? []).map((m) => msg(`missing ${m}`, `\u7F3A ${m}`));
12586
- const detail2 = [...errorsOf, ...missing2].join(msg("; ", "\uFF1B")) || msg("no reason given", "\u672A\u8BF4\u660E");
12688
+ const missing3 = (b.missing ?? []).map((m) => msg(`missing ${m}`, `\u7F3A ${m}`));
12689
+ const detail2 = [...errorsOf, ...missing3].join(msg("; ", "\uFF1B")) || msg("no reason given", "\u672A\u8BF4\u660E");
12587
12690
  throw new InputError(
12588
12691
  msg(
12589
12692
  `PostBundle parseStatus=${String(b.parseStatus)}: the content is incomplete (${detail2}). Complete it from local screenshots or text and mark it ready first, or, to save only what is there, add --allow-incomplete`,
@@ -12727,7 +12830,7 @@ var init_inspiration = __esm({
12727
12830
  });
12728
12831
 
12729
12832
  // src/providers/link-bundle.ts
12730
- var text3, badResponse, tagsOf2, imageOf, validPublishedAt, planPost, remoteView, COMMON_RATIOS, gcd2, ratioOf, fileName, sizeOf, reason, downloadPictures, utcNow2, buildBundle;
12833
+ var text3, badResponse, tagsOf2, imageOf, validPublishedAt, planPost, remoteView, COMMON_RATIOS, gcd2, ratioOf, fileName, sizeOf, reason, downloadPictures, utcNow2, pictureResource, videoResource, buildBundle;
12731
12834
  var init_link_bundle = __esm({
12732
12835
  "src/providers/link-bundle.ts"() {
12733
12836
  "use strict";
@@ -12770,6 +12873,7 @@ var init_link_bundle = __esm({
12770
12873
  const serverNote = text3(post.note) || (note ?? "").trim();
12771
12874
  return {
12772
12875
  platform: post.platform,
12876
+ kind: post.kind === "images" || post.kind === "video" ? post.kind : null,
12773
12877
  sourceUrl,
12774
12878
  title: text3(post.title),
12775
12879
  text: text3(post.text),
@@ -12784,6 +12888,7 @@ var init_link_bundle = __esm({
12784
12888
  };
12785
12889
  remoteView = (plan4) => ({
12786
12890
  platform: plan4.platform,
12891
+ ...plan4.kind ? { kind: plan4.kind } : {},
12787
12892
  title: plan4.title,
12788
12893
  text: plan4.text,
12789
12894
  tags: plan4.tags,
@@ -12838,7 +12943,17 @@ var init_link_bundle = __esm({
12838
12943
  return { saved, failure: null };
12839
12944
  };
12840
12945
  utcNow2 = (rt) => `${rt.now().toISOString().slice(0, 19)}+00:00`;
12841
- buildBundle = (rt, plan4, saved) => {
12946
+ pictureResource = (s) => ({
12947
+ id: `img${s.index}`,
12948
+ kind: "image",
12949
+ path: s.file,
12950
+ mimeType: s.mimeType,
12951
+ sha256: s.sha256,
12952
+ ...s.width && s.height ? { width: s.width, height: s.height } : {},
12953
+ ...s.alt ? { alt: s.alt } : {}
12954
+ });
12955
+ videoResource = (v) => ({ id: "video", kind: "video", path: v.file, mimeType: v.mimeType, sha256: v.sha256, bytes: v.bytes });
12956
+ buildBundle = (rt, plan4, saved, video) => {
12842
12957
  const first = saved[0];
12843
12958
  const complete3 = saved.length > 0;
12844
12959
  return {
@@ -12851,15 +12966,7 @@ var init_link_bundle = __esm({
12851
12966
  music: { title: "", url: "" },
12852
12967
  pageOrder: saved.map((s) => s.index),
12853
12968
  ratio: first?.width && first.height ? ratioOf(first.width, first.height) : null,
12854
- resources: saved.map((s) => ({
12855
- id: `img${s.index}`,
12856
- kind: "image",
12857
- path: s.file,
12858
- mimeType: s.mimeType,
12859
- sha256: s.sha256,
12860
- ...s.width && s.height ? { width: s.width, height: s.height } : {},
12861
- ...s.alt ? { alt: s.alt } : {}
12862
- })),
12969
+ resources: [...saved.map(pictureResource), ...video ? [videoResource(video)] : []],
12863
12970
  parseStatus: complete3 ? "ready" : "missing_resources",
12864
12971
  auth: {
12865
12972
  required: false,
@@ -12878,6 +12985,71 @@ var init_link_bundle = __esm({
12878
12985
  }
12879
12986
  });
12880
12987
 
12988
+ // src/providers/link-video.ts
12989
+ var MAX_VIDEO_BYTES, REQUEST_TIMEOUT_SEC, DOWNLOAD_TIMEOUT_SEC, EXTENSIONS2, LEADING_BOXES, ascii4, sniffVideoMime, missing, videoLink, downloadVideo;
12990
+ var init_link_video = __esm({
12991
+ "src/providers/link-video.ts"() {
12992
+ "use strict";
12993
+ init_util();
12994
+ init_i18n();
12995
+ init_api();
12996
+ init_base();
12997
+ init_errors3();
12998
+ MAX_VIDEO_BYTES = 200 * 1024 * 1024;
12999
+ REQUEST_TIMEOUT_SEC = 300;
13000
+ DOWNLOAD_TIMEOUT_SEC = 600;
13001
+ EXTENSIONS2 = { "video/mp4": ".mp4", "video/quicktime": ".mov", "video/webm": ".webm" };
13002
+ LEADING_BOXES = ["moov", "mdat", "free", "wide", "skip"];
13003
+ ascii4 = (bytes, from, to) => String.fromCharCode(...bytes.subarray(from, to));
13004
+ sniffVideoMime = (head, claimed) => {
13005
+ if (head.length >= 4 && head[0] === 26 && head[1] === 69 && head[2] === 223 && head[3] === 163) return "video/webm";
13006
+ if (head.length < 12) return null;
13007
+ const box2 = ascii4(head, 4, 8);
13008
+ if (box2 === "ftyp") return ascii4(head, 8, 12) === "qt " ? "video/quicktime" : "video/mp4";
13009
+ if (LEADING_BOXES.includes(box2)) return claimed === "video/quicktime" ? "video/quicktime" : "video/mp4";
13010
+ return null;
13011
+ };
13012
+ missing = (code, error2) => ({ missing: { code, error: error2 } });
13013
+ videoLink = async (client2, inspirationId) => {
13014
+ let answer3;
13015
+ try {
13016
+ answer3 = await client2.request("GET", `/inspirations/${encodeURIComponent(inspirationId)}/video`, { timeoutSec: REQUEST_TIMEOUT_SEC });
13017
+ } catch (error2) {
13018
+ if (error2 instanceof PopostApiError && error2.code === "VIDEO_GENERATION_DISABLED") return { skipped: true };
13019
+ if (error2 instanceof PopostApiError) return missing(error2.code || "API_ERROR", error2.message);
13020
+ if (error2 instanceof ImageProviderError) return missing("API_ERROR", error2.message);
13021
+ throw error2;
13022
+ }
13023
+ if (!isRecord(answer3) || typeof answer3.url !== "string" || typeof answer3.mimeType !== "string" || !EXTENSIONS2[answer3.mimeType])
13024
+ return missing("BAD_RESPONSE", msg("the answer for the post video has no usable link", "\u5E16\u5B50\u89C6\u9891\u7684\u54CD\u5E94\u91CC\u6CA1\u6709\u53EF\u7528\u7684\u94FE\u63A5"));
13025
+ return { url: answer3.url, mimeType: answer3.mimeType };
13026
+ };
13027
+ downloadVideo = async (rt, client2, inspirationId, outDir2, retry) => {
13028
+ const link = await videoLink(client2, inspirationId);
13029
+ if (!("url" in link)) return link;
13030
+ const what = msg("the post video", "\u5E16\u5B50\u89C6\u9891");
13031
+ const tmp = rt.path.join(outDir2, "video.download");
13032
+ let raw;
13033
+ try {
13034
+ raw = await downloadResult(rt, link.url, tmp, MAX_VIDEO_BYTES, DOWNLOAD_TIMEOUT_SEC, { what, retry });
13035
+ } catch (error2) {
13036
+ await rt.fs.rm(tmp).catch(() => void 0);
13037
+ if (error2 instanceof PopostApiError) return missing(error2.code || "DOWNLOAD_FAILED", error2.message);
13038
+ throw error2;
13039
+ }
13040
+ const mimeType2 = sniffVideoMime(raw.subarray(0, 16), link.mimeType);
13041
+ if (!mimeType2) {
13042
+ await rt.fs.rm(tmp);
13043
+ return missing("BAD_RESPONSE", msg(`the download of ${what} is not an MP4/MOV/WebM video; ${retry}`, `${what}\u4E0B\u8F7D\u7684\u5185\u5BB9\u4E0D\u662F MP4/MOV/WebM \u89C6\u9891\uFF1B${retry}`));
13044
+ }
13045
+ const file = `video${EXTENSIONS2[mimeType2]}`;
13046
+ const path2 = rt.path.join(outDir2, file);
13047
+ await rt.fs.rename(tmp, path2);
13048
+ return { saved: { file, path: path2, mimeType: mimeType2, sha256: sha256(raw), bytes: raw.length } };
13049
+ };
13050
+ }
13051
+ });
13052
+
12881
13053
  // src/providers/link-task.ts
12882
13054
  var POLL_INTERVAL_MS, MAX_POLL_FAILURES, RATE_LIMIT_WAIT_MS, RATE_LIMIT_WAIT_MAX_MS, TASK_ID2, STATUSES, taskOf2, isTerminal, TRANSIENT_CODES2, isTransient2, rateLimitWaitMs, fetchTask, waitForTask2;
12883
13055
  var init_link_task = __esm({
@@ -12953,7 +13125,7 @@ var init_link_task = __esm({
12953
13125
  });
12954
13126
 
12955
13127
  // src/providers/link.ts
12956
- var NOTE_MAX, TIMEOUT_MAX_SEC, LOCAL_CODES, shellArg, resumeCommand, briefOf, badArgs, checkOptions, parseBody, outDirOf, makeClient, dryRunOf, createTask, codeText, failedOutcome, unfinishedOutcome, succeededOutcome, finish2, failureOf5, report, parseLink, linkStatus;
13128
+ var NOTE_MAX, TIMEOUT_MAX_SEC, LOCAL_CODES, shellArg, resumeCommand, briefOf, badArgs, checkOptions, parseBody, outDirOf, makeClient, dryRunOf, createTask, codeText, failedOutcome, unfinishedOutcome, videoPart, succeededOutcome, finish2, failureOf5, report, parseLink, linkStatus;
12957
13129
  var init_link = __esm({
12958
13130
  "src/providers/link.ts"() {
12959
13131
  "use strict";
@@ -12965,6 +13137,7 @@ var init_link = __esm({
12965
13137
  init_cli_config();
12966
13138
  init_errors3();
12967
13139
  init_link_bundle();
13140
+ init_link_video();
12968
13141
  init_link_task();
12969
13142
  init_paths();
12970
13143
  init_secrets();
@@ -13045,7 +13218,30 @@ var init_link = __esm({
13045
13218
  );
13046
13219
  return { exit: 1, body: { ok: false, code, error: error2, task: { id: id2, status: task?.status ?? null, chargedCredits: task?.chargedCredits ?? null }, resume } };
13047
13220
  };
13048
- succeededOutcome = async (rt, task, call2, fallback) => {
13221
+ videoPart = async (rt, client2, plan4, call2, outDir2, retry) => {
13222
+ if (plan4.kind !== "video" || call2.noVideo || !plan4.inspirationId) return { fields: {}, note: "" };
13223
+ const outcome = await downloadVideo(rt, client2, plan4.inspirationId, outDir2, retry);
13224
+ if ("skipped" in outcome) return { fields: {}, note: "" };
13225
+ if ("saved" in outcome) {
13226
+ const path2 = shellArg(outcome.saved.path);
13227
+ return {
13228
+ saved: outcome.saved,
13229
+ fields: { video: outcome.saved.path },
13230
+ note: msg(
13231
+ `; the post's original video is ${path2}: use it as the reference video (for example popost video replication init <project> --reference ${path2})`,
13232
+ `\uFF1B\u5E16\u5B50\u539F\u89C6\u9891\u5728 ${path2}\uFF1A\u7528\u5B83\u4F5C\u53C2\u8003\u89C6\u9891\uFF08\u4F8B\u5982 popost video replication init <\u9879\u76EE> --reference ${path2}\uFF09`
13233
+ )
13234
+ };
13235
+ }
13236
+ return {
13237
+ fields: { videoMissing: outcome.missing },
13238
+ note: msg(
13239
+ `; the original video could not be fetched (${outcome.missing.code}): the bundle has the cover and text only; for shot, subtitle or sound analysis ask the user for the video file or a screen recording`,
13240
+ `\uFF1B\u6CA1\u80FD\u53D6\u5230\u5E16\u5B50\u539F\u89C6\u9891\uFF08${outcome.missing.code}\uFF09\uFF1Abundle \u53EA\u6709\u5C01\u9762\u548C\u6587\u5B57\uFF1B\u8981\u505A\u5206\u955C\u3001\u5B57\u5E55\u6216\u58F0\u97F3\u5206\u6790\uFF0C\u8BF7\u7528\u6237\u63D0\u4F9B\u89C6\u9891\u6587\u4EF6\u6216\u5F55\u5C4F`
13241
+ )
13242
+ };
13243
+ };
13244
+ succeededOutcome = async (rt, client2, task, call2, fallback) => {
13049
13245
  if (!task.post) throw badResponse(msg("the task succeeded but the answer has no post", "\u4EFB\u52A1\u5DF2\u6210\u529F\uFF0C\u4F46\u54CD\u5E94\u91CC\u6CA1\u6709 post"));
13050
13246
  const plan4 = planPost(task.post, fallback.url, fallback.note);
13051
13247
  const info = { id: task.id, status: task.status, created: task.created, chargedCredits: task.chargedCredits };
@@ -13072,7 +13268,8 @@ var init_link = __esm({
13072
13268
  const { saved, failure: failure4 } = await downloadPictures(rt, plan4.images, outDir2, retry);
13073
13269
  const images = saved.map((s) => s.path);
13074
13270
  if (failure4) return { exit: 1, body: { ok: false, code: "DOWNLOAD_FAILED", error: failure4, task: { id: task.id, status: task.status, chargedCredits: task.chargedCredits }, images, resume: resumeCommand(task.id, call2) } };
13075
- const bundle = buildBundle(rt, plan4, saved);
13271
+ const video = await videoPart(rt, client2, plan4, call2, outDir2, retry);
13272
+ const bundle = buildBundle(rt, plan4, saved, video.saved);
13076
13273
  const [valid, errors] = validateBundle(bundle);
13077
13274
  if (!valid) throw badResponse(msg(`the parsed result does not make a valid PostBundle: ${errors.join("; ")}`, `\u89E3\u6790\u7ED3\u679C\u65E0\u6CD5\u7EC4\u6210\u5408\u6CD5\u7684 PostBundle\uFF1A${errors.join("\uFF1B")}`));
13078
13275
  const bundlePath = rt.path.join(outDir2, "postbundle.json");
@@ -13082,8 +13279,8 @@ var init_link = __esm({
13082
13279
  "the post has no pictures: the bundle is marked missing_resources and cannot be built directly; the platform saved this post to My Inspirations",
13083
13280
  "\u5E16\u5B50\u91CC\u6CA1\u6709\u56FE\u7247\uFF1Abundle \u6807\u4E3A missing_resources\uFF0C\u4E0D\u80FD\u76F4\u63A5 build\uFF1B\u5E73\u53F0\u5DF2\u628A\u8FD9\u6761\u5E16\u5B50\u5B58\u5165\u300C\u6211\u7684\u7075\u611F\u300D"
13084
13281
  );
13085
- const post = { platform: plan4.platform, title: plan4.title, sourceUrl: plan4.sourceUrl, imageCount: saved.length, ...plan4.inspirationId ? { inspirationId: plan4.inspirationId } : {} };
13086
- return { exit: 0, body: { ok: true, task: info, bundle: bundlePath, images, post, next: `popost validate --file ${file} && popost import --file ${file}`, note } };
13282
+ const post = { platform: plan4.platform, ...plan4.kind ? { kind: plan4.kind } : {}, title: plan4.title, sourceUrl: plan4.sourceUrl, imageCount: saved.length, ...plan4.inspirationId ? { inspirationId: plan4.inspirationId } : {} };
13283
+ return { exit: 0, body: { ok: true, task: info, bundle: bundlePath, images, ...video.fields, post, next: `popost validate --file ${file} && popost import --file ${file}`, note: note + video.note } };
13087
13284
  };
13088
13285
  finish2 = async (rt, client2, state, first, call2, fallback) => {
13089
13286
  const id2 = state.id;
@@ -13098,7 +13295,7 @@ var init_link = __esm({
13098
13295
  );
13099
13296
  return unfinishedOutcome("POLL_FAILED", what, id2, waited.task, call2);
13100
13297
  }
13101
- return waited.task.status === "failed" ? failedOutcome(waited.task) : succeededOutcome(rt, waited.task, call2, fallback);
13298
+ return waited.task.status === "failed" ? failedOutcome(waited.task) : succeededOutcome(rt, client2, waited.task, call2, fallback);
13102
13299
  };
13103
13300
  failureOf5 = (error2) => {
13104
13301
  if (error2 instanceof CliReject) return { code: "CONFIG", exit: error2.code, message: error2.message };
@@ -13180,7 +13377,7 @@ var init_link = __esm({
13180
13377
  });
13181
13378
 
13182
13379
  // src/providers/pricing.ts
13183
- var pricingClient, queryLinkPrice;
13380
+ var pricingClient, queryLinkPrice, queryLinkPlatforms;
13184
13381
  var init_pricing = __esm({
13185
13382
  "src/providers/pricing.ts"() {
13186
13383
  "use strict";
@@ -13204,6 +13401,14 @@ var init_pricing = __esm({
13204
13401
  );
13205
13402
  return { creditsPerRequest: link.creditsPerRequest, balance: body.balance, sufficient: body.balance >= Number(link.creditsPerRequest), unit: "credits", source: `${client2.baseUrl}/pricing` };
13206
13403
  };
13404
+ queryLinkPlatforms = async (client2) => {
13405
+ const body = await client2.request("GET", "/links/platforms", { anonymous: true });
13406
+ const list7 = isRecord(body) && Array.isArray(body.platforms) ? body.platforms : null;
13407
+ const valid = (p) => isRecord(p) && typeof p.id === "string" && typeof p.name === "string" && typeof p.video === "boolean";
13408
+ if (!list7 || !list7.length || !list7.every(valid))
13409
+ throw new PopostApiError(msg("popost.ai answered the platform list in an unexpected form", "popost.ai \u8FD4\u56DE\u7684\u5E73\u53F0\u5217\u8868\u683C\u5F0F\u4E0D\u5BF9"), { code: "BAD_RESPONSE" });
13410
+ return list7.map(({ id: id2, name, video }) => ({ id: id2, name, video }));
13411
+ };
13207
13412
  }
13208
13413
  });
13209
13414
 
@@ -13612,12 +13817,60 @@ var init_usage = __esm({
13612
13817
  }
13613
13818
  });
13614
13819
 
13820
+ // src/commands/link-platforms.ts
13821
+ var nameOf, listText, linkPlatforms;
13822
+ var init_link_platforms = __esm({
13823
+ "src/commands/link-platforms.ts"() {
13824
+ "use strict";
13825
+ init_util();
13826
+ init_i18n();
13827
+ init_errors3();
13828
+ init_pricing();
13829
+ init_post_bundle();
13830
+ nameOf = (p) => {
13831
+ const known2 = PLATFORMS.includes(p.id) ? PLATFORM_NAMES[p.id] : null;
13832
+ return known2 ? known2[currentLang()] : p.name;
13833
+ };
13834
+ listText = (names) => names.length < 2 ? names.join("") : msg(`${names.slice(0, -1).join(", ")} and ${names.at(-1)}`, `${names.slice(0, -1).join("\u3001")}\u548C${names.at(-1)}`);
13835
+ linkPlatforms = async (rt, config3) => {
13836
+ try {
13837
+ const platforms = await queryLinkPlatforms(await pricingClient(rt, config3));
13838
+ const coverOnly = platforms.filter((p) => !p.video).map(nameOf);
13839
+ printJson(rt, {
13840
+ ok: true,
13841
+ platforms,
13842
+ text: listText(platforms.map(nameOf)),
13843
+ ...coverOnly.length ? { coverOnly: listText(coverOnly) } : {},
13844
+ next: msg(
13845
+ "These are the platforms popost.ai parses now: name exactly these when you tell the user which links work, never a list from memory or a README. For the coverOnly ones a video post gives its cover and text, not the video file.",
13846
+ "\u8FD9\u662F popost.ai \u5F53\u524D\u80FD\u89E3\u6790\u7684\u5E73\u53F0\uFF1A\u544A\u8BC9\u7528\u6237\u652F\u6301\u54EA\u4E9B\u94FE\u63A5\u65F6\u5C31\u7528\u8FD9\u4EFD\u5217\u8868\uFF0C\u4E0D\u8981\u51ED\u8BB0\u5FC6\u6216 README \u91CC\u7684\u5217\u8868\u3002coverOnly \u91CC\u7684\u5E73\u53F0\uFF0C\u89C6\u9891\u5E16\u53EA\u80FD\u62FF\u5230\u5C01\u9762\u548C\u6587\u5B57\uFF0C\u62FF\u4E0D\u5230\u89C6\u9891\u6587\u4EF6\u3002"
13847
+ )
13848
+ }, true);
13849
+ return 0;
13850
+ } catch (error2) {
13851
+ if (!(error2 instanceof PopostApiError || error2 instanceof CliReject)) throw error2;
13852
+ printJson(rt, {
13853
+ ok: false,
13854
+ code: error2 instanceof PopostApiError ? error2.code : "CONFIG",
13855
+ error: error2.message,
13856
+ next: msg(
13857
+ "The live list could not be read. Do not name platforms from memory; if the user needs an answer now, give this CLI version's list (known) and say it may be out of date.",
13858
+ "\u6CA1\u80FD\u8BFB\u5230\u5B9E\u65F6\u5217\u8868\u3002\u4E0D\u8981\u51ED\u8BB0\u5FC6\u5217\u5E73\u53F0\uFF1B\u7528\u6237\u73B0\u5728\u5C31\u8981\u7B54\u6848\u65F6\uFF0C\u7ED9\u51FA\u8FD9\u4E2A CLI \u7248\u672C\u5DF2\u77E5\u7684\u5217\u8868\uFF08known\uFF09\uFF0C\u5E76\u8BF4\u660E\u5B83\u53EF\u80FD\u4E0D\u662F\u6700\u65B0\u7684\u3002"
13859
+ ),
13860
+ known: listText(PLATFORMS.map((p) => PLATFORM_NAMES[p][currentLang()]))
13861
+ }, true);
13862
+ return 1;
13863
+ }
13864
+ };
13865
+ }
13866
+ });
13867
+
13615
13868
  // src/commands/link.ts
13616
13869
  var link_exports = {};
13617
13870
  __export(link_exports, {
13618
13871
  main: () => main16
13619
13872
  });
13620
- var out, timeout, noDownload, config2, main16;
13873
+ var out, timeout, noDownload, noVideo, config2, main16;
13621
13874
  var init_link2 = __esm({
13622
13875
  "src/commands/link.ts"() {
13623
13876
  "use strict";
@@ -13625,6 +13878,7 @@ var init_link2 = __esm({
13625
13878
  init_i18n();
13626
13879
  init_post_bundle();
13627
13880
  init_link();
13881
+ init_link_platforms();
13628
13882
  init_cli_args();
13629
13883
  init_task();
13630
13884
  out = () => ({
@@ -13651,10 +13905,28 @@ var init_link2 = __esm({
13651
13905
  "\u4E0D\u4E0B\u8F7D\u56FE\u7247\uFF0C\u53EA\u6253\u5370\u5E16\u5B50\u5185\u5BB9\u548C\u56FE\u7247\u5730\u5740\uFF08\u5730\u5740\u662F\u77ED\u671F\u7B7E\u540D\u94FE\u63A5\uFF0C\u5F88\u5FEB\u5931\u6548\uFF09"
13652
13906
  )
13653
13907
  });
13908
+ noVideo = () => ({
13909
+ flag: "--no-video",
13910
+ kind: "flag",
13911
+ help: msg(
13912
+ "for a video post, keep the cover and text only: do not fetch the original video file",
13913
+ "\u89C6\u9891\u5E16\u53EA\u4FDD\u7559\u5C01\u9762\u548C\u6587\u5B57\uFF0C\u4E0D\u53D6\u539F\u89C6\u9891\u6587\u4EF6"
13914
+ )
13915
+ });
13654
13916
  config2 = () => ({ flag: "--config", help: msg("private config JSON (popost.baseUrl / popost.auth.envVar)", "\u79C1\u6709\u914D\u7F6E JSON\uFF08popost.baseUrl / popost.auth.envVar\uFF09") });
13655
13917
  main16 = (argv, rt) => runSubcommand2(
13656
13918
  "popost link",
13657
13919
  {
13920
+ platforms: {
13921
+ spec: {
13922
+ description: msg(
13923
+ "List the platforms whose links popost.ai parses now, read from popost.ai: name these when telling the user which links work. Free, no account needed.",
13924
+ "\u5217\u51FA popost.ai \u5F53\u524D\u80FD\u89E3\u6790\u94FE\u63A5\u7684\u5E73\u53F0\uFF08\u4ECE popost.ai \u5B9E\u65F6\u8BFB\u53D6\uFF09\uFF1A\u544A\u8BC9\u7528\u6237\u652F\u6301\u54EA\u4E9B\u94FE\u63A5\u65F6\u7528\u8FD9\u4EFD\u5217\u8868\u3002\u514D\u8D39\uFF0C\u4E0D\u9700\u8981\u8FDE\u63A5\u8D26\u6237\u3002"
13925
+ ),
13926
+ options: [config2()]
13927
+ },
13928
+ run: (a) => linkPlatforms(rt, a.string("config"))
13929
+ },
13658
13930
  quote: {
13659
13931
  spec: {
13660
13932
  description: msg("Read the live parsing tariff and balance without creating a task or charging.", "\u67E5\u8BE2\u5B9E\u65F6\u7684\u94FE\u63A5\u89E3\u6790\u4EF7\u683C\u548C\u4F59\u989D\uFF0C\u4E0D\u5EFA\u4EFB\u52A1\u3001\u4E0D\u6263\u79EF\u5206\u3002"),
@@ -13665,8 +13937,8 @@ var init_link2 = __esm({
13665
13937
  parse: {
13666
13938
  spec: {
13667
13939
  description: msg(
13668
- `Have popost.ai parse a social post link (${platformNameList("or")}; YouTube, Bilibili and WeChat Channels video links provide the cover and post details when available), wait for the result, download the pictures and write a PostBundle (postbundle.v1). Get the live price with link quote first, then submit with --confirm --max-credits N, the ceiling the user authorized; the actual net charge is task.chargedCredits; a link already saved is reused without a new charge. The parsed post is also saved to My Inspirations.`,
13669
- `\u8BA9 popost.ai \u89E3\u6790\u4E00\u6761\u793E\u5A92\u5E16\u5B50\u94FE\u63A5\uFF08${platformNameList("or")}\uFF1BYouTube\u3001\u54D4\u54E9\u54D4\u54E9\u548C\u5FAE\u4FE1\u89C6\u9891\u53F7\u94FE\u63A5\u53EF\u4FDD\u5B58\u53EF\u7528\u7684\u5C01\u9762\u548C\u5E16\u5B50\u4FE1\u606F\uFF09\uFF0C\u7B49\u5F85\u7ED3\u679C\uFF0C\u628A\u56FE\u7247\u4E0B\u8F7D\u5230\u672C\u5730\u5E76\u5199\u51FA PostBundle\uFF08postbundle.v1\uFF09\u3002\u5148 link quote \u67E5\u8BE2\u52A8\u6001\u4EF7\u683C\uFF0C\u518D\u5E26 --confirm --max-credits N \u6309\u5DF2\u6388\u6743\u4E0A\u9650\u63D0\u4EA4\uFF1B\u5B9E\u9645\u51C0\u6263\u89C1 task.chargedCredits\uFF1B\u5DF2\u4FDD\u5B58\u8FC7\u7684\u94FE\u63A5\u76F4\u63A5\u590D\u7528\u3001\u4E0D\u518D\u6263\u3002\u89E3\u6790\u7ED3\u679C\u540C\u65F6\u5B58\u5165\u300C\u6211\u7684\u7075\u611F\u300D\u3002`
13940
+ `Have popost.ai parse a social post link (${platformNameList("or")}), wait for the result, download the pictures and write a PostBundle (postbundle.v1). A video post also gets its original video file (video.mp4, free) for shot, subtitle and sound analysis; YouTube, Bilibili and WeChat Channels give the cover and post details only. Get the live price with link quote first, then submit with --confirm --max-credits N, the ceiling the user authorized; the actual net charge is task.chargedCredits; a link already saved is reused without a new charge. The parsed post is also saved to My Inspirations.`,
13941
+ `\u8BA9 popost.ai \u89E3\u6790\u4E00\u6761\u793E\u5A92\u5E16\u5B50\u94FE\u63A5\uFF08${platformNameList("or")}\uFF09\uFF0C\u7B49\u5F85\u7ED3\u679C\uFF0C\u628A\u56FE\u7247\u4E0B\u8F7D\u5230\u672C\u5730\u5E76\u5199\u51FA PostBundle\uFF08postbundle.v1\uFF09\u3002\u89C6\u9891\u5E16\u8FD8\u4F1A\u53D6\u56DE\u539F\u89C6\u9891\u6587\u4EF6\uFF08video.mp4\uFF0C\u4E0D\u53E6\u6263\u79EF\u5206\uFF09\uFF0C\u7528\u4E8E\u5206\u955C\u3001\u5B57\u5E55\u548C\u58F0\u97F3\u5206\u6790\uFF1BYouTube\u3001\u54D4\u54E9\u54D4\u54E9\u548C\u5FAE\u4FE1\u89C6\u9891\u53F7\u53EA\u6709\u5C01\u9762\u548C\u5E16\u5B50\u4FE1\u606F\u3002\u5148 link quote \u67E5\u8BE2\u52A8\u6001\u4EF7\u683C\uFF0C\u518D\u5E26 --confirm --max-credits N \u6309\u5DF2\u6388\u6743\u4E0A\u9650\u63D0\u4EA4\uFF1B\u5B9E\u9645\u51C0\u6263\u89C1 task.chargedCredits\uFF1B\u5DF2\u4FDD\u5B58\u8FC7\u7684\u94FE\u63A5\u76F4\u63A5\u590D\u7528\u3001\u4E0D\u518D\u6263\u3002\u89E3\u6790\u7ED3\u679C\u540C\u65F6\u5B58\u5165\u300C\u6211\u7684\u7075\u611F\u300D\u3002`
13670
13942
  ),
13671
13943
  positionals: [{ name: "url", help: msg("the post link (http/https)", "\u5E16\u5B50\u94FE\u63A5\uFF08http/https\uFF09") }],
13672
13944
  options: [
@@ -13676,12 +13948,13 @@ var init_link2 = __esm({
13676
13948
  out(),
13677
13949
  timeout(),
13678
13950
  noDownload(),
13951
+ noVideo(),
13679
13952
  { flag: "--dry-run", kind: "flag", help: msg("offline, no key, no charge: only show the requests that would be sent", "\u4E0D\u8054\u7F51\u3001\u4E0D\u9700\u8981\u5BC6\u94A5\u3001\u4E0D\u6263\u79EF\u5206\uFF0C\u53EA\u5C55\u793A\u5C06\u53D1\u51FA\u7684\u8BF7\u6C42") },
13680
13953
  config2()
13681
13954
  ]
13682
13955
  },
13683
13956
  // Into a project (--out inside one): the parse is charged under the project's task (providers/task.ts).
13684
- run: async (a) => parseLink(await aroundPath(rt, a.string("out")), { url: a.req("url"), note: a.string("note"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), dryRun: a.flag("dry-run"), confirm: a.flag("confirm"), maxCredits: a.number("max-credits"), config: a.string("config") })
13957
+ run: async (a) => parseLink(await aroundPath(rt, a.string("out")), { url: a.req("url"), note: a.string("note"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), noVideo: a.flag("no-video"), dryRun: a.flag("dry-run"), confirm: a.flag("confirm"), maxCredits: a.number("max-credits"), config: a.string("config") })
13685
13958
  },
13686
13959
  status: {
13687
13960
  spec: {
@@ -13690,9 +13963,9 @@ var init_link2 = __esm({
13690
13963
  "\u7EE7\u7EED\u7B49\u5F85\u4E00\u4E2A\u5DF2\u5B58\u5728\u7684\u89E3\u6790\u4EFB\u52A1\u5E76\u4E0B\u8F7D\u7ED3\u679C\uFF08\u7528\u4E8E link parse \u8D85\u65F6\u6216\u88AB\u6253\u65AD\u4E4B\u540E\uFF09\u3002\u4E0D\u65B0\u5EFA\u4EFB\u52A1\u3001\u4E0D\u6263\u79EF\u5206\u3002"
13691
13964
  ),
13692
13965
  positionals: [{ name: "task-id", help: msg("the task.id printed by link parse", "link parse \u8F93\u51FA\u7684 task.id") }],
13693
- options: [out(), timeout(), noDownload(), config2()]
13966
+ options: [out(), timeout(), noDownload(), noVideo(), config2()]
13694
13967
  },
13695
- run: (a) => linkStatus(rt, { taskId: a.req("task-id"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), config: a.string("config") })
13968
+ run: (a) => linkStatus(rt, { taskId: a.req("task-id"), out: a.string("out"), timeoutSec: a.number("timeout"), noDownload: a.flag("no-download"), noVideo: a.flag("no-video"), config: a.string("config") })
13696
13969
  }
13697
13970
  },
13698
13971
  argv,
@@ -13855,8 +14128,8 @@ var init_browser = __esm({
13855
14128
  "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
13856
14129
  "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe"
13857
14130
  ];
13858
- findChromium = (env) => {
13859
- const explicit = env.POPOST_CHROME || env.PLAYWRIGHT_CHROMIUM;
14131
+ findChromium = (env2) => {
14132
+ const explicit = env2.POPOST_CHROME || env2.PLAYWRIGHT_CHROMIUM;
13860
14133
  if (explicit) return existsSync(explicit) ? explicit : null;
13861
14134
  return [...SYSTEM_BROWSERS, ...playwrightCaches()].find((p) => existsSync(p)) ?? null;
13862
14135
  };
@@ -13899,8 +14172,8 @@ var init_browser = __esm({
13899
14172
  clearTimeout(timer);
13900
14173
  }
13901
14174
  };
13902
- launchChromium = async (env, profile = "pages", o = {}) => {
13903
- const executablePath = findChromium(env);
14175
+ launchChromium = async (env2, profile = "pages", o = {}) => {
14176
+ const executablePath = findChromium(env2);
13904
14177
  if (!executablePath)
13905
14178
  throw new BrowserUnavailableError(
13906
14179
  msg(
@@ -15597,9 +15870,9 @@ var init_check2 = __esm({
15597
15870
  const named = namedFiles(project);
15598
15871
  const all = [.../* @__PURE__ */ new Set([...named.files, ...named.scenes])];
15599
15872
  const found = await Promise.all(all.map(async (f) => await rt.fs.stat(rt.path.resolve(root, f)) !== null ? [f] : []));
15600
- const present2 = new Set(found.flat());
15601
- const scenes = await Promise.all([...new Set(named.scenes)].filter((f) => present2.has(f)).map(async (f) => [f, await rt.fs.readText(rt.path.resolve(root, f))]));
15602
- return { dir, present: present2, scenes: Object.fromEntries(scenes) };
15873
+ const present3 = new Set(found.flat());
15874
+ const scenes = await Promise.all([...new Set(named.scenes)].filter((f) => present3.has(f)).map(async (f) => [f, await rt.fs.readText(rt.path.resolve(root, f))]));
15875
+ return { dir, present: present3, scenes: Object.fromEntries(scenes) };
15603
15876
  };
15604
15877
  checkMaterialFiles = (project, files) => project.materials.flatMap((m, i) => ["file", "words"].flatMap((key2) => {
15605
15878
  const at7 = "materials[" + i + "]." + key2;
@@ -16249,10 +16522,10 @@ var init_footage2 = __esm({
16249
16522
  const { fs, path: path2 } = rt;
16250
16523
  await fs.mkdir(job.dir);
16251
16524
  const have = new Set(await fs.readdir(job.dir));
16252
- const missing2 = job.frames.filter((f) => !have.has(frameName(f)));
16253
- if (missing2.length === 0) return { extracted: 0, reused: job.frames.length };
16254
- const lo = missing2[0] ?? 0;
16255
- const hi = missing2[missing2.length - 1] ?? 0;
16525
+ const missing3 = job.frames.filter((f) => !have.has(frameName(f)));
16526
+ if (missing3.length === 0) return { extracted: 0, reused: job.frames.length };
16527
+ const lo = missing3[0] ?? 0;
16528
+ const hi = missing3[missing3.length - 1] ?? 0;
16256
16529
  const tmp = path2.join(job.dir, ".extract-" + rt.randomUUID());
16257
16530
  await fs.mkdir(tmp);
16258
16531
  try {
@@ -16279,11 +16552,11 @@ var init_footage2 = __esm({
16279
16552
  path2.join(tmp, "%0" + FRAME_DIGITS + "d.png")
16280
16553
  ]);
16281
16554
  const written2 = new Set(await fs.readdir(tmp));
16282
- const absent = missing2.filter((f) => !written2.has(frameName(f - lo)));
16283
- if (absent.length > 0)
16284
- throw new Error("Extracting frames " + lo + ".." + hi + " of " + job.file + " gave " + written2.size + " pictures; frame " + absent[0] + " is missing. The file may be damaged or shorter than its header says; re-encode it with ffmpeg.");
16285
- for (const f of missing2) await fs.rename(path2.join(tmp, frameName(f - lo)), path2.join(job.dir, frameName(f)));
16286
- return { extracted: missing2.length, reused: job.frames.length - missing2.length };
16555
+ const absent2 = missing3.filter((f) => !written2.has(frameName(f - lo)));
16556
+ if (absent2.length > 0)
16557
+ throw new Error("Extracting frames " + lo + ".." + hi + " of " + job.file + " gave " + written2.size + " pictures; frame " + absent2[0] + " is missing. The file may be damaged or shorter than its header says; re-encode it with ffmpeg.");
16558
+ for (const f of missing3) await fs.rename(path2.join(tmp, frameName(f - lo)), path2.join(job.dir, frameName(f)));
16559
+ return { extracted: missing3.length, reused: job.frames.length - missing3.length };
16287
16560
  } finally {
16288
16561
  await fs.rm(tmp);
16289
16562
  }
@@ -17464,10 +17737,10 @@ var init_fits = __esm({
17464
17737
  const isNew = mids.map((M) => sig.map((k) => blockDiff(M, B, k) < blockDiff(M, A, k)));
17465
17738
  const pure = mids.map((M) => sig.filter((k) => Math.min(blockDiff(M, A, k), blockDiff(M, B, k)) < 0.35 * dab[k]).length / sig.length);
17466
17739
  const share2 = isNew.map((v) => v.filter(Boolean).length / sig.length);
17467
- const shared2 = (i) => share2[i] > 0.15 && share2[i] < 0.85;
17468
- const central = pure.filter((_, i) => shared2(i));
17740
+ const shared3 = (i) => share2[i] > 0.15 && share2[i] < 0.85;
17741
+ const central = pure.filter((_, i) => shared3(i));
17469
17742
  if (!central.length) return void 0;
17470
- const left = mids.flatMap((M, i) => shared2(i) ? [sig.reduce((n, k) => n + Math.min(blockDiff(M, A, k), blockDiff(M, B, k)) / dab[k], 0) / sig.length] : []);
17743
+ const left = mids.flatMap((M, i) => shared3(i) ? [sig.reduce((n, k) => n + Math.min(blockDiff(M, A, k), blockDiff(M, B, k)) / dab[k], 0) / sig.length] : []);
17471
17744
  const purity = median2(central);
17472
17745
  if (purity < 0.5 || share2[share2.length - 1] - share2[0] < 0.3) return void 0;
17473
17746
  let flipsBack = 0;
@@ -20058,13 +20331,13 @@ var init_kind = __esm({
20058
20331
  textFacts = (s, cues, step2) => {
20059
20332
  if (!cues) return { page: void 0, design: void 0, filmed: void 0 };
20060
20333
  const mine = cues.filter((c) => shownIn(c, s, step2));
20061
- const own2 = mine.filter((c) => c.role === "in-picture");
20334
+ const own3 = mine.filter((c) => c.role === "in-picture");
20062
20335
  const laid = mine.filter((c) => c.role === "title" || c.role === "label");
20063
20336
  const largest2 = Math.max(0, ...laid.map((c) => c.size));
20064
20337
  return {
20065
- page: own2.length >= MANY_LINES ? plural2(own2.length, "small line", "small lines") + " of text, median height " + pct(median3(own2.map((c) => c.size))) : void 0,
20066
- design: laid.length >= 1 && laid.length <= FEW_LINES && largest2 >= LARGE && own2.length < MANY_LINES ? plural2(laid.length, "large line", "large lines") + " of text, up to " + pct(largest2) + " of the height" : void 0,
20067
- filmed: own2.length + laid.length <= 2 && largest2 < LARGE ? "little text (" + plural2(own2.length + laid.length, "line", "lines") + ")" : void 0
20338
+ page: own3.length >= MANY_LINES ? plural2(own3.length, "small line", "small lines") + " of text, median height " + pct(median3(own3.map((c) => c.size))) : void 0,
20339
+ design: laid.length >= 1 && laid.length <= FEW_LINES && largest2 >= LARGE && own3.length < MANY_LINES ? plural2(laid.length, "large line", "large lines") + " of text, up to " + pct(largest2) + " of the height" : void 0,
20340
+ filmed: own3.length + laid.length <= 2 && largest2 < LARGE ? "little text (" + plural2(own3.length + laid.length, "line", "lines") + ")" : void 0
20068
20341
  };
20069
20342
  };
20070
20343
  groundFacts = (s) => {
@@ -20362,14 +20635,14 @@ var init_check3 = __esm({
20362
20635
  measuredLabel = (b) => [b.kind, b.mode, b.direction, b.via ? "via " + b.via : ""].filter(Boolean).join(" ");
20363
20636
  coverageProblems = ({ r, m, at: at7 }) => {
20364
20637
  const fps = m.source.fps, s22 = (f) => (f / fps).toFixed(2);
20365
- const missing2 = m.shots.filter((s) => !r.present.includes(s.index + 1)).map((s) => error("shots", "Shot " + (s.index + 1) + " (" + s22(s.start) + "-" + s22(s.end) + " s) has no entry.", "Open " + shotSheetFile(s.index + 1) + ' and add {"shot": ' + (s.index + 1) + ', "time": [' + s22(s.start) + ", " + s22(s.end) + '], "layout": "...", "layers": [...]} for it.'));
20638
+ const missing3 = m.shots.filter((s) => !r.present.includes(s.index + 1)).map((s) => error("shots", "Shot " + (s.index + 1) + " (" + s22(s.start) + "-" + s22(s.end) + " s) has no entry.", "Open " + shotSheetFile(s.index + 1) + ' and add {"shot": ' + (s.index + 1) + ', "time": [' + s22(s.start) + ", " + s22(s.end) + '], "layout": "...", "layers": [...]} for it.'));
20366
20639
  const extra2 = r.present.filter((n) => n > m.shots.length).map((n) => error(at7(n) + ".shot", "There is no shot " + n + ": the measurement has " + m.shots.length + ".", "Remove the entry, or give it the number of the shot it describes."));
20367
20640
  const times = r.elements.shots.flatMap((s) => {
20368
20641
  const ms = m.shots[s.shot - 1];
20369
20642
  if (!ms || Math.abs(s.time[0] - ms.start / fps) <= TIME_SLACK && Math.abs(s.time[1] - ms.end / fps) <= TIME_SLACK) return [];
20370
20643
  return [warning(at7(s.shot) + ".time", "Shot " + s.shot + " is " + s22(ms.start) + "-" + s22(ms.end) + " s in the measurement; its entry says " + s.time[0] + "-" + s.time[1] + " s.", "Copy the measured time, [" + s22(ms.start) + ", " + s22(ms.end) + ']: entries go by the measured shots. Where the frames show a change the measurement missed, say so in "rebuild".')];
20371
20644
  });
20372
- return [...missing2, ...extra2, ...times];
20645
+ return [...missing3, ...extra2, ...times];
20373
20646
  };
20374
20647
  transitionProblems2 = ({ r, m, at: at7 }) => r.elements.shots.flatMap((s) => {
20375
20648
  const here = at7(s.shot) + ".transitionIn", t = s.transitionIn;
@@ -20446,9 +20719,9 @@ var init_check3 = __esm({
20446
20719
  if (byNumber(end)?.sameEffectAsNext)
20447
20720
  out2.push(warning(at7(end) + ".sameEffectAsNext", "Shot " + end + " is the last one re-made, and its entry says an animation runs on into the next.", 'Leave "sameEffectAsNext" out of the last shot.'));
20448
20721
  const last = byNumber(m.shots.length);
20449
- const own2 = last && !last.drop ? last.layers.filter((l) => l.kind !== "ground") : [];
20450
- const theirs = own2.filter((l) => isDropped(l.role));
20451
- if (last && own2.length && theirs.length * 2 > own2.length)
20722
+ const own3 = last && !last.drop ? last.layers.filter((l) => l.kind !== "ground") : [];
20723
+ const theirs = own3.filter((l) => isDropped(l.role));
20724
+ if (last && own3.length && theirs.length * 2 > own3.length)
20452
20725
  out2.push(warning(
20453
20726
  at7(last.shot),
20454
20727
  "The last shot (" + last.shot + ") is made mostly of the platform's or the author's layers (" + theirs.map((l) => l.id).join(", ") + "): an end card, which a re-make never copies.",
@@ -20723,9 +20996,9 @@ var init_tool = __esm({
20723
20996
  lastLines = (stderr, n) => stderr.trim().split("\n").slice(-n).join(" | ");
20724
20997
  TOOL_THREADS = 4;
20725
20998
  toolEnv = (rt, threads) => {
20726
- const own2 = rt.env.POPOST_TOOL_THREADS?.trim();
20999
+ const own3 = rt.env.POPOST_TOOL_THREADS?.trim();
20727
21000
  const n = threads ?? Math.min(TOOL_THREADS, cpuBudgetOf(rt).cpus);
20728
- const budget = own2 || String(Math.max(1, Math.floor(n)));
21001
+ const budget = own3 || String(Math.max(1, Math.floor(n)));
20729
21002
  return {
20730
21003
  POPOST_TOOL_THREADS: budget,
20731
21004
  ...Object.fromEntries(["OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"].map((name) => [name, rt.env[name]?.trim() || budget]))
@@ -21501,7 +21774,7 @@ var init_measure2 = __esm({
21501
21774
  envelopeRate = (rate) => rate / HOP;
21502
21775
  onsetEnvelope = (pcm) => {
21503
21776
  const frames = Math.max(0, Math.floor((pcm.length - FRAME) / HOP) + 1);
21504
- const env = new Float32Array(frames);
21777
+ const env2 = new Float32Array(frames);
21505
21778
  let prev = new Float64Array(FRAME / 2), cur = new Float64Array(FRAME / 2);
21506
21779
  for (let i = 0; i < frames; i++) {
21507
21780
  spectrum(pcm, i * HOP, cur);
@@ -21512,10 +21785,10 @@ var init_measure2 = __esm({
21512
21785
  const d = v - prev[k];
21513
21786
  if (d > 0) flux += d;
21514
21787
  }
21515
- env[i] = i === 0 ? 0 : flux;
21788
+ env2[i] = i === 0 ? 0 : flux;
21516
21789
  [prev, cur] = [cur, prev];
21517
21790
  }
21518
- return env;
21791
+ return env2;
21519
21792
  };
21520
21793
  ONSET_AT = 0.86;
21521
21794
  PEAK_HOPS = 3;
@@ -21529,19 +21802,19 @@ var init_measure2 = __esm({
21529
21802
  const sorted = Float32Array.from(values).sort();
21530
21803
  return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))] ?? 0;
21531
21804
  };
21532
- onsetsOf = (env, rate) => {
21533
- const fps = envelopeRate(rate), top2 = percentile(env, 0.995);
21805
+ onsetsOf = (env2, rate) => {
21806
+ const fps = envelopeRate(rate), top2 = percentile(env2, 0.995);
21534
21807
  if (!(top2 >= ONSET_FLOOR)) return [];
21535
21808
  const around3 = Math.max(1, Math.round(AROUND_SECONDS * fps));
21536
- const sums = new Float64Array(env.length + 1);
21537
- for (let i = 0; i < env.length; i++) sums[i + 1] = sums[i] + env[i];
21809
+ const sums = new Float64Array(env2.length + 1);
21810
+ for (let i = 0; i < env2.length; i++) sums[i + 1] = sums[i] + env2[i];
21538
21811
  const out2 = [];
21539
- for (let i = 1; i < env.length - 1; i++) {
21540
- const v = env[i];
21812
+ for (let i = 1; i < env2.length - 1; i++) {
21813
+ const v = env2[i];
21541
21814
  let peak = true;
21542
- for (let j = Math.max(0, i - PEAK_HOPS); j <= Math.min(env.length - 1, i + PEAK_HOPS) && peak; j++) if (env[j] > v || env[j] === v && j < i) peak = false;
21815
+ for (let j = Math.max(0, i - PEAK_HOPS); j <= Math.min(env2.length - 1, i + PEAK_HOPS) && peak; j++) if (env2[j] > v || env2[j] === v && j < i) peak = false;
21543
21816
  if (!peak) continue;
21544
- const a = Math.max(0, i - around3), b = Math.min(env.length, i + around3 + 1);
21817
+ const a = Math.max(0, i - around3), b = Math.min(env2.length, i + around3 + 1);
21545
21818
  const mean5 = (sums[b] - sums[a]) / (b - a);
21546
21819
  if (v < ONSET_FLOOR || v < LOCAL_FACTOR * mean5 + GLOBAL_SHARE * top2) continue;
21547
21820
  const t = (i * HOP + ONSET_AT * FRAME) / rate;
@@ -21554,13 +21827,13 @@ var init_measure2 = __esm({
21554
21827
  }
21555
21828
  return out2;
21556
21829
  };
21557
- tempoOf = (env, rate) => {
21830
+ tempoOf = (env2, rate) => {
21558
21831
  const fps = envelopeRate(rate);
21559
- if (env.length < 4 * fps) return void 0;
21832
+ if (env2.length < 4 * fps) return void 0;
21560
21833
  let mean5 = 0;
21561
- for (const v of env) mean5 += v;
21562
- mean5 /= env.length;
21563
- const sharp = Float64Array.from(env, (v) => v >= ONSET_FLOOR ? Math.max(0, v - mean5) : 0);
21834
+ for (const v of env2) mean5 += v;
21835
+ mean5 /= env2.length;
21836
+ const sharp = Float64Array.from(env2, (v) => v >= ONSET_FLOOR ? Math.max(0, v - mean5) : 0);
21564
21837
  const x = Float64Array.from(sharp, (_v, i) => ((sharp[i - 2] ?? 0) + 2 * (sharp[i - 1] ?? 0) + 3 * (sharp[i] ?? 0) + 2 * (sharp[i + 1] ?? 0) + (sharp[i + 2] ?? 0)) / 9);
21565
21838
  let zero = 0;
21566
21839
  for (const v of x) zero += v * v;
@@ -21630,9 +21903,9 @@ var init_measure2 = __esm({
21630
21903
  const seconds7 = pcm.length / rate;
21631
21904
  const db = levelCurve(pcm, rate);
21632
21905
  const silences = silencesOf(pcm, rate);
21633
- const env = onsetEnvelope(pcm);
21634
- const onsets = onsetsOf(env, rate);
21635
- const tempo2 = onsets.length >= 4 ? tempoOf(env, rate) : void 0;
21906
+ const env2 = onsetEnvelope(pcm);
21907
+ const onsets = onsetsOf(env2, rate);
21908
+ const tempo2 = onsets.length >= 4 ? tempoOf(env2, rate) : void 0;
21636
21909
  return {
21637
21910
  seconds: r23(seconds7),
21638
21911
  level: { step: 0.5, db, peakDb: db.length ? Math.max(...db) : FLOOR_DB, meanDb: r1(rmsDb(pcm)) },
@@ -25233,8 +25506,8 @@ var init_speech2 = __esm({
25233
25506
  const within = (c, m) => words.filter((_w, k) => (mids[k] ?? 0) >= c.start - m && (mids[k] ?? 0) < c.end + m);
25234
25507
  const marks = track.cues.filter((c) => c.role === "watermark").map((c) => letters(c.text));
25235
25508
  const likeMark = (c) => {
25236
- const own2 = letters(c.text);
25237
- return marks.some((m) => sameText(m, own2) && Math.min(m.length, own2.length) >= MARK_LENGTH * Math.max(m.length, own2.length));
25509
+ const own3 = letters(c.text);
25510
+ return marks.some((m) => sameText(m, own3) && Math.min(m.length, own3.length) >= MARK_LENGTH * Math.max(m.length, own3.length));
25238
25511
  };
25239
25512
  const seen = track.cues.map((c) => {
25240
25513
  const silent = !within(c, Math.round(QUIET_SECONDS * fps)).length;
@@ -26198,10 +26471,10 @@ var init_describe = __esm({
26198
26471
  const x0 = Math.min(...bar.map((c) => c.box[0])), x1 = Math.max(...bar.map((c) => c.box[0] + c.box[2])), y0 = Math.min(...bar.map((c) => c.box[1])), y1 = Math.max(...bar.map((c) => c.box[1] + c.box[3]));
26199
26472
  if (bar.length) L.push("- bar (through the video, REFERENCE.md) " + bar.map((c) => quote5(c.text)).join(" ") + ", " + where([x0, y0, x1 - x0, y1 - y0]) + ", height " + pct5(bar[0]?.size ?? 0) + (lit ? "; " + quote5(lit.text) + " is marked here" : ""));
26200
26473
  }
26201
- const own2 = mine.filter((c) => c.role === "in-picture").sort((a, b) => b.size - a.size);
26202
- if (own2.length) {
26203
- L.push("", "## Text that belongs to the footage (" + own2.length + " lines; the largest)", "");
26204
- for (const c of own2.slice(0, 8)) L.push("- " + quote5(c.text) + " " + where(c.box) + ", height " + pct5(c.size));
26474
+ const own3 = mine.filter((c) => c.role === "in-picture").sort((a, b) => b.size - a.size);
26475
+ if (own3.length) {
26476
+ L.push("", "## Text that belongs to the footage (" + own3.length + " lines; the largest)", "");
26477
+ for (const c of own3.slice(0, 8)) L.push("- " + quote5(c.text) + " " + where(c.box) + ", height " + pct5(c.size));
26205
26478
  }
26206
26479
  const curves = p.measure.curves?.find((c) => c.shot === k + 1);
26207
26480
  if (s.events.length || curves) {
@@ -26267,9 +26540,9 @@ var init_describe = __esm({
26267
26540
  const where3 = (k) => p.written ? transitionFile(k + 2) : "the change into shot " + two7(k + 2);
26268
26541
  const poor = m.boundaries.flatMap((b, k) => fitsPoorly(b) ? [where3(k) + " (" + [b.kind, b.mode, b.direction].filter(Boolean).join(" ") + ")"] : []);
26269
26542
  const joined = [...p.joined].map((k) => "shot " + two7(k + 1) + " with " + where3(k));
26270
- const own2 = p.tracks.filter(ownEffect).map((t) => (p.written ? transitionFile(t.shot) : "the change into shot " + two7(t.shot)) + " (" + trackBrief(t, m.source.fps).replace("path: ", "") + ")");
26543
+ const own3 = p.tracks.filter(ownEffect).map((t) => (p.written ? transitionFile(t.shot) : "the change into shot " + two7(t.shot)) + " (" + trackBrief(t, m.source.fps).replace("path: ", "") + ")");
26271
26544
  return [
26272
- ...own2.length ? ["- " + own2.length + " change" + (own2.length === 1 ? " is" : "s are") + " not a standard transition by " + (own2.length === 1 ? "its" : "their") + " measured path: " + own2.join(", ") + ". Re-make each as a scene set from the path in its shot's file."] : [],
26545
+ ...own3.length ? ["- " + own3.length + " change" + (own3.length === 1 ? " is" : "s are") + " not a standard transition by " + (own3.length === 1 ? "its" : "their") + " measured path: " + own3.join(", ") + ". Re-make each as a scene set from the path in its shot's file."] : [],
26273
26546
  ...poor.length ? ["- " + poor.length + " measured transition kind" + (poor.length === 1 ? " does" : "s do") + " not fit the frames well: " + poor.join(", ") + ". Each may be an effect of its own: look at it first."] : [],
26274
26547
  ...joined.length ? ["- Very short shots that are most likely part of the effect after them: " + joined.join(", ") + "."] : []
26275
26548
  ];
@@ -26303,8 +26576,8 @@ var init_describe = __esm({
26303
26576
  const marked2 = markedText(bar);
26304
26577
  L.push("- A bar laid on in the edit through the video (design text a re-make draws, not a watermark): " + bar.words.map((c) => quote5(c.text)).join(" ") + " at " + pct5((bar.words[0]?.box[1] ?? 0) + (bar.words[0]?.box[3] ?? 0) / 2) + " of the height" + (marked2 ? "; the marked word follows the shots: " + marked2 : ""));
26305
26578
  }
26306
- const own2 = text13.cues.filter((c) => c.role === "in-picture").length;
26307
- if (own2) L.push("- " + own2 + " lines of text belong to the footage itself (pages, interfaces, documents)");
26579
+ const own3 = text13.cues.filter((c) => c.role === "in-picture").length;
26580
+ if (own3) L.push("- " + own3 + " lines of text belong to the footage itself (pages, interfaces, documents)");
26308
26581
  } else L.push("- On-screen text was not read (no text reader was available)");
26309
26582
  if (transcript2 && transcript2.words.length) {
26310
26583
  const spoken = transcript2.words.reduce((n, w) => n + w.end - w.start, 0) / fps;
@@ -26513,8 +26786,8 @@ var init_marks = __esm({
26513
26786
  };
26514
26787
  highlightColour = (look2, letters2) => {
26515
26788
  if (look2?.highlight?.color) return look2.highlight.color;
26516
- const own2 = toLab(hexToRgb(letters2 ?? "#ffffff"));
26517
- return STAND_OUT.find((c) => deltaE(toLab(hexToRgb(c)), own2) >= 30) ?? STAND_OUT[0];
26789
+ const own3 = toLab(hexToRgb(letters2 ?? "#ffffff"));
26790
+ return STAND_OUT.find((c) => deltaE(toLab(hexToRgb(c)), own3) >= 30) ?? STAND_OUT[0];
26518
26791
  };
26519
26792
  markSpans = (marks, color2) => marks.map(([from, to]) => ({ from, to, color: color2 }));
26520
26793
  }
@@ -27501,8 +27774,8 @@ var init_main = __esm({
27501
27774
  const said = layers.flatMap((l) => {
27502
27775
  const isMain = main22 !== void 0 && l.box === main22.box && l.kind === main22.kind;
27503
27776
  const words = [l.moves, l.enters].filter((t) => typeof t === "string" && t.trim() !== "");
27504
- const own2 = l.kind === "pointer" ? l.moves ? [l.moves] : [] : isMain ? words.filter((t) => MOTION_WORDS.test(t)) : [];
27505
- return own2.map((t) => l.id + ": " + t.trim());
27777
+ const own3 = l.kind === "pointer" ? l.moves ? [l.moves] : [] : isMain ? words.filter((t) => MOTION_WORDS.test(t)) : [];
27778
+ return own3.map((t) => l.id + ": " + t.trim());
27506
27779
  });
27507
27780
  return said.length ? said.join("; ") : void 0;
27508
27781
  };
@@ -29334,19 +29607,19 @@ var init_read = __esm({
29334
29607
  const lost = unrecoveredOf2(raw.unrecovered);
29335
29608
  const problems2 = [...extraKeys(raw, ["shots", "unrecovered"], "(root)"), ...lost.problems];
29336
29609
  const shots2 = [];
29337
- const present2 = [];
29610
+ const present3 = [];
29338
29611
  const where3 = {};
29339
29612
  raw.shots.forEach((s, k) => {
29340
29613
  const r = shotOf2(s, k);
29341
29614
  problems2.push(...r.problems);
29342
- if (r.number !== void 0 && present2.includes(r.number)) problems2.push(error("shots[" + k + "].shot", "Shot " + r.number + " has two entries.", "Keep one entry per shot; merge what the two say."));
29615
+ if (r.number !== void 0 && present3.includes(r.number)) problems2.push(error("shots[" + k + "].shot", "Shot " + r.number + " has two entries.", "Keep one entry per shot; merge what the two say."));
29343
29616
  else if (r.number !== void 0) {
29344
- present2.push(r.number);
29617
+ present3.push(r.number);
29345
29618
  where3[r.number] = k;
29346
29619
  }
29347
29620
  if (r.shot && !shots2.some((x) => x.shot === r.number)) shots2.push(r.shot);
29348
29621
  });
29349
- return { elements: { shots: [...shots2].sort((a, b) => a.shot - b.shot), ...lost.unrecovered.length ? { unrecovered: lost.unrecovered } : {} }, present: [...present2].sort((a, b) => a - b), where: where3, problems: problems2 };
29622
+ return { elements: { shots: [...shots2].sort((a, b) => a.shot - b.shot), ...lost.unrecovered.length ? { unrecovered: lost.unrecovered } : {} }, present: [...present3].sort((a, b) => a - b), where: where3, problems: problems2 };
29350
29623
  };
29351
29624
  }
29352
29625
  });
@@ -29388,8 +29661,8 @@ var init_elements = __esm({
29388
29661
  };
29389
29662
  unrecoveredIn = async (rt, dir, elements) => {
29390
29663
  const reading = await optionalJson(rt, rt.path.join(dir, UNRECOVERED_FILE));
29391
- const own2 = elements ?? await optionalJson(rt, rt.path.join(dir, ELEMENTS_FILE)).then((raw) => raw === void 0 ? void 0 : readElements(raw).elements);
29392
- return [...Array.isArray(reading?.unrecovered) ? reading.unrecovered : [], ...own2?.unrecovered ?? []];
29664
+ const own3 = elements ?? await optionalJson(rt, rt.path.join(dir, ELEMENTS_FILE)).then((raw) => raw === void 0 ? void 0 : readElements(raw).elements);
29665
+ return [...Array.isArray(reading?.unrecovered) ? reading.unrecovered : [], ...own3?.unrecovered ?? []];
29393
29666
  };
29394
29667
  questions = command(
29395
29668
  'what the model that reads the frames is to do: the instructions (references/video-elements.md from "For the reader" on), the pictures to open in order, and every shot to describe with its time and its measured change; prompt holds it all as one text, to send with pictures to any model',
@@ -29402,9 +29675,9 @@ var init_elements = __esm({
29402
29675
  const guide = await readerGuide(rt);
29403
29676
  if (!guide) throw new VideoCommandError("The instructions for the reader are not in " + rt.path.join(rt.skillRoot, GUIDE_FILE) + ": the Skill is incomplete. Install the popost package again.");
29404
29677
  const candidates3 = [OPENING_FILE, ...questionShots(m).flatMap((s) => [s.frames, ...s.transition ? [s.transition] : []])];
29405
- const present2 = /* @__PURE__ */ new Set();
29406
- for (const f of candidates3) if ((await rt.fs.stat(rt.path.join(dir, f)))?.isFile) present2.add(f);
29407
- const q = videoQuestions(m, text13, (f) => present2.has(f));
29678
+ const present3 = /* @__PURE__ */ new Set();
29679
+ for (const f of candidates3) if ((await rt.fs.stat(rt.path.join(dir, f)))?.isFile) present3.add(f);
29680
+ const q = videoQuestions(m, text13, (f) => present3.has(f));
29408
29681
  if (!q.pictures.length) throw new VideoCommandError("There are no pictures in " + dir + " (opening.jpg, shots/NN-frames.jpg, transitions/NN.jpg). Describe the video again with this version: popost video describe <video> --out " + typed);
29409
29682
  printJson(rt, {
29410
29683
  ok: true,
@@ -29557,8 +29830,8 @@ var init_generate = __esm({
29557
29830
  name = "StillMaking";
29558
29831
  };
29559
29832
  PENDING_EXIT2 = 4;
29560
- run2 = async (rt, words, args, env = {}) => {
29561
- const r = await programsOf(rt).run([...words, ...args], { env: { ...toolEnv(rt), ...env }, lowPriority: true }).catch((e) => {
29833
+ run2 = async (rt, words, args, env2 = {}) => {
29834
+ const r = await programsOf(rt).run([...words, ...args], { env: { ...toolEnv(rt), ...env2 }, lowPriority: true }).catch((e) => {
29562
29835
  throw new Error("The generator could not be started (" + (e instanceof Error ? e.message : String(e)) + "). Check POPOST_GEN_CMD.");
29563
29836
  });
29564
29837
  return { code: r.code, stdout: new TextDecoder().decode(r.stdout).slice(-8e3), stderr: r.stderr.slice(-4e3) };
@@ -29577,10 +29850,10 @@ var init_generate = __esm({
29577
29850
  const words = toolCommand(rt, "POPOST_GEN_CMD");
29578
29851
  if (!words) return void 0;
29579
29852
  return {
29580
- make: (kind, request, out2, env) => withTempDir(rt, "popost-video-gen-", async (dir) => {
29853
+ make: (kind, request, out2, env2) => withTempDir(rt, "popost-video-gen-", async (dir) => {
29581
29854
  const file = rt.path.join(dir, "request.json");
29582
29855
  await rt.fs.writeFile(file, JSON.stringify(request));
29583
- const r = await run2(rt, words, [kind, file, out2], env);
29856
+ const r = await run2(rt, words, [kind, file, out2], env2);
29584
29857
  const said = lastObject(r.stdout);
29585
29858
  const why = r.stderr.trim().split("\n").slice(-2).join(" | ");
29586
29859
  if (r.code === CONFIRM_EXIT2 && isPrice(said.confirm)) throw new ConfirmNeeded(said.confirm, why || "It costs " + said.confirm.credits + " credits and needs the user's agreement first; nothing was charged.");
@@ -29854,7 +30127,7 @@ var init_generate = __esm({
29854
30127
  const anchorFile = first >= 0 ? o.requests[first].file : void 0;
29855
30128
  const source2 = o.picture ? o.picture.person ? "character" : "image" : fromClip ? "clip" : void 0;
29856
30129
  let picture3 = o.picture?.file;
29857
- const absent = /* @__PURE__ */ new Map();
30130
+ const absent2 = /* @__PURE__ */ new Map();
29858
30131
  for (const [i, original] of order.entries()) {
29859
30132
  const cast = locked.get(original.file);
29860
30133
  const voice = voices.get(original.file);
@@ -29900,19 +30173,19 @@ var init_generate = __esm({
29900
30173
  }
29901
30174
  }
29902
30175
  if (!await exists3(target2)) {
29903
- const failed5 = needs.find((f) => absent.get(f) === "failed");
30176
+ const failed5 = needs.find((f) => absent2.get(f) === "failed");
29904
30177
  if (failed5) {
29905
- absent.set(asked3.file, "failed");
30178
+ absent2.set(asked3.file, "failed");
29906
30179
  materials2.push({ ...entry2, waiting: true, waitsFor: failed5 });
29907
30180
  continue;
29908
30181
  }
29909
- const making2 = needs.find((f) => absent.get(f) === "pending");
30182
+ const making2 = needs.find((f) => absent2.get(f) === "pending");
29910
30183
  if (making2) {
29911
- absent.set(asked3.file, "pending");
30184
+ absent2.set(asked3.file, "pending");
29912
30185
  materials2.push({ ...entry2, queued: true, waitsFor: making2 });
29913
30186
  continue;
29914
30187
  }
29915
- const priced = needs.find((f) => absent.get(f) === "priced");
30188
+ const priced = needs.find((f) => absent2.get(f) === "priced");
29916
30189
  const priceOnly = priced !== void 0;
29917
30190
  await rt.fs.mkdir(rt.path.dirname(target2));
29918
30191
  const partial = target2 + ".partial" + rt.path.extname(target2);
@@ -29941,12 +30214,12 @@ var init_generate = __esm({
29941
30214
  await rt.fs.rm(partial);
29942
30215
  for (const ext of [".speech.wav", ".speech.json"]) await rt.fs.rm(partial + ext);
29943
30216
  if (e instanceof StillMaking) {
29944
- absent.set(asked3.file, "pending");
30217
+ absent2.set(asked3.file, "pending");
29945
30218
  const charged = e.pending.chargedCredits;
29946
30219
  materials2.push({ ...entry2, pending: true, ...e.pending.task ? { task: e.pending.task } : {}, ...charged !== void 0 ? { chargedCredits: charged } : {} });
29947
30220
  continue;
29948
30221
  }
29949
- absent.set(asked3.file, e instanceof ConfirmNeeded ? "priced" : "failed");
30222
+ absent2.set(asked3.file, e instanceof ConfirmNeeded ? "priced" : "failed");
29950
30223
  materials2.push({ ...entry2, error: e instanceof Error ? e.message : String(e), ...e instanceof ConfirmNeeded ? { confirm: e.confirm } : {}, ...priceOnly ? { waiting: true, waitsFor: priced } : {} });
29951
30224
  continue;
29952
30225
  }
@@ -29962,7 +30235,7 @@ var init_generate = __esm({
29962
30235
  const rel = rt.path.join(rt.path.dirname(asked3.file), ANCHOR_FILE);
29963
30236
  const got = await exists3(rt.path.resolve(o.dir, rel)) || await grabAnchor(rt, target2, rt.path.resolve(o.dir, rel)).then(() => true, () => false);
29964
30237
  if (got) picture3 = rel;
29965
- else absent.set(asked3.file, "failed");
30238
+ else absent2.set(asked3.file, "failed");
29966
30239
  entry2 = { ...entry2, anchor: true };
29967
30240
  }
29968
30241
  notes2[asked3.file] = asked3.note ?? asked3.prompt;
@@ -29971,7 +30244,7 @@ var init_generate = __esm({
29971
30244
  }
29972
30245
  const why = (m) => m.waitsFor === anchorFile && !o.requests.some((r) => r.file === m.file && r.continues === m.waitsFor) ? "a frame of it goes to this clip as a reference picture, so that the clips show the same person, product and place" : "this clip starts from its last frame";
29973
30246
  const failed4 = materials2.filter((m) => m.error).map(
29974
- (m) => m.confirm ? m.confirm.reason === "unplanned" ? error(m.file, "It was not made: it is outside the recorded clip plan and costs " + m.confirm.credits + " credits. Nothing was charged for it.", unplannedNext(m.confirm.clip?.key)) : error(m.file, "It was not made: it costs " + m.confirm.credits + " credits, and the user has not agreed to that price. Nothing was charged.", "Show the user the price (confirm has the total). Only after they agree, or when it fits what is left of the agreed budget, run again with --confirm --max-credits N.") : error(m.file, "It could not be made: " + m.error, afterFailure(m.error ?? "") + (source2 && m.file !== anchorFile && takesAnchor(o.requests.find((r) => r.file === m.file)) ? " It was sent with the anchor picture as a reference picture: a generator that takes none needs --no-anchor." : ""))
30247
+ (m) => m.confirm ? m.confirm.reason === "unplanned" ? error(m.file, "It was not made: it is outside the recorded clip plan and costs " + m.confirm.credits + " credits. Nothing was charged for it.", unplannedNext(m.confirm.clip?.key)) : error(m.file, "It was not made: it costs " + m.confirm.credits + " credits, and the user has not agreed to that price. Nothing was charged.", "Show the user the price with what it buys (confirm has the total and each clip's model, resolution, seconds and aspect ratio). Only after they agree, or when it fits what is left of the agreed budget, run again with --confirm --max-credits N.") : error(m.file, "It could not be made: " + m.error, afterFailure(m.error ?? "") + (source2 && m.file !== anchorFile && takesAnchor(o.requests.find((r) => r.file === m.file)) ? " It was sent with the anchor picture as a reference picture: a generator that takes none needs --no-anchor." : ""))
29975
30248
  );
29976
30249
  const held = materials2.filter((m) => m.waiting && !m.confirm && !m.queued).map((m) => error(
29977
30250
  m.file,
@@ -29988,7 +30261,7 @@ var init_generate = __esm({
29988
30261
  });
29989
30262
 
29990
30263
  // src/video/generate/cloud.ts
29991
- var GenerateError, MINUTE_MS, POLL_MS2, DEFAULT_WAIT_MIN, DEFAULT_SECONDS, CREATE_TRIES, CREATE_TIMEOUT_SEC, UPLOAD_TIMEOUT_MS, DOWNLOAD_TIMEOUT_SEC, MAX_CLIP_BYTES, RETRY_HINT, setting, numberSetting, keysOf, cloudSettings, agreeToPrice, requestKey, LISTS2, has, mediaType, readReference3, readReferences, recordFile, readRecord2, save2, keyOf4, stillValid, text6, putBytes, upload2, ensureUploads2, specOf, ensureQuote, taskOf3, createTask2, submit, getTask, findTask, ENDED, PASSING2, waitFor, NEXT_AFTER, ended, fetchClip, gateOf, modelFacts, wavSeconds, checkReferenceSounds, makeClip, listModels;
30264
+ var GenerateError, MINUTE_MS, POLL_MS2, DEFAULT_WAIT_MIN, DEFAULT_SECONDS, CREATE_TRIES, CREATE_TIMEOUT_SEC, UPLOAD_TIMEOUT_MS, DOWNLOAD_TIMEOUT_SEC2, MAX_CLIP_BYTES, RETRY_HINT, setting, numberSetting, keysOf, cloudSettings, agreeToPrice, requestKey, LISTS2, has, mediaType, readReference3, readReferences, recordFile, readRecord2, save2, keyOf4, stillValid, text6, putBytes, upload2, ensureUploads2, specOf, ensureQuote, taskOf3, createTask2, submit, getTask, findTask, ENDED, PASSING2, waitFor, NEXT_AFTER, ended, fetchClip, gateOf, modelFacts, wavSeconds, checkReferenceSounds, makeClip, listModels;
29992
30265
  var init_cloud2 = __esm({
29993
30266
  "src/video/generate/cloud.ts"() {
29994
30267
  "use strict";
@@ -30019,7 +30292,7 @@ var init_cloud2 = __esm({
30019
30292
  CREATE_TRIES = 3;
30020
30293
  CREATE_TIMEOUT_SEC = 120;
30021
30294
  UPLOAD_TIMEOUT_MS = 10 * MINUTE_MS;
30022
- DOWNLOAD_TIMEOUT_SEC = 900;
30295
+ DOWNLOAD_TIMEOUT_SEC2 = 900;
30023
30296
  MAX_CLIP_BYTES = 1024 * 1024 * 1024;
30024
30297
  RETRY_HINT = "Run the same command again: it sends the same idempotency key, so it is never paid twice.";
30025
30298
  setting = (rt, name) => rt.env[name]?.trim() || void 0;
@@ -30053,7 +30326,7 @@ var init_cloud2 = __esm({
30053
30326
  if (s.maxCredits !== void 0 ? price.credits <= s.maxCredits : s.yes) return;
30054
30327
  throw new ConfirmNeeded(
30055
30328
  price,
30056
- s.maxCredits !== void 0 ? "This costs " + price.credits + " credits, more than the budget of this call (" + s.maxCredits + " credits), so nothing was charged. Show the user the price; only if they agree, run again with --confirm --max-credits N (N: what is left of the agreed budget)." : "This costs " + price.credits + " credits and nothing was charged: show the user the price, and run again with --confirm --max-credits N only after they agree."
30329
+ s.maxCredits !== void 0 ? "This costs " + price.credits + " credits, more than the budget of this call (" + s.maxCredits + " credits), so nothing was charged. Show the user the price with what it buys (confirm: model, resolution, seconds, aspect ratio); only if they agree, run again with --confirm --max-credits N (N: what is left of the agreed budget)." : "This costs " + price.credits + " credits and nothing was charged: show the user the price with what it buys (confirm: model, resolution, seconds, aspect ratio), and run again with --confirm --max-credits N only after they agree."
30057
30330
  );
30058
30331
  };
30059
30332
  requestKey = (kind, fields2) => kind + "-" + sha256(JSON.stringify(fields2));
@@ -30250,7 +30523,7 @@ var init_cloud2 = __esm({
30250
30523
  const url = task.video?.url;
30251
30524
  if (typeof url !== "string") throw new GenerateError("popost.ai says the clip of task " + task.id + " is made but gives no link to it. Run the command again later.");
30252
30525
  try {
30253
- const data = await downloadResult(rt, url, out2, MAX_CLIP_BYTES, DOWNLOAD_TIMEOUT_SEC, labels);
30526
+ const data = await downloadResult(rt, url, out2, MAX_CLIP_BYTES, DOWNLOAD_TIMEOUT_SEC2, labels);
30254
30527
  const bytes = task.video?.bytes;
30255
30528
  if (typeof bytes === "number" && data.length !== bytes) {
30256
30529
  await rt.fs.rm(out2);
@@ -31391,9 +31664,9 @@ var init_letters = __esm({
31391
31664
  const lab = g.at[k], box2 = boxes2[k];
31392
31665
  if (!lab || !box2) return void 0;
31393
31666
  const mine = strokesOf(f, box2, lab, strokeMax(box2));
31394
- const own2 = { edges: noEdges(), thick: [], pairs: { v: [], h: [] }, beyond: { v: [], h: [] }, ground: groundOn(f, box2, lab) };
31395
- edgesFrom(f, mine, lab, Math.max(4, Math.round(0.3 * (box2.y1 - box2.y0))), own2.edges, own2.thick, own2.pairs, own2.beyond);
31396
- return { own: own2, mine };
31667
+ const own3 = { edges: noEdges(), thick: [], pairs: { v: [], h: [] }, beyond: { v: [], h: [] }, ground: groundOn(f, box2, lab) };
31668
+ edgesFrom(f, mine, lab, Math.max(4, Math.round(0.3 * (box2.y1 - box2.y0))), own3.edges, own3.thick, own3.pairs, own3.beyond);
31669
+ return { own: own3, mine };
31397
31670
  });
31398
31671
  const perLine = lines.map((l) => l?.own);
31399
31672
  return { ...aggregate(g, lines.map((l) => l?.mine ?? []), perLine), ground: perLine.filter((l) => l?.ground).length >= frames.length / 2 };
@@ -31438,13 +31711,13 @@ var init_letters = __esm({
31438
31711
  return lines.length >= Math.max(2, 0.2 * n) ? [{ ...aggregate(s.group, s.px, s.perLine, lines), ground: false, told: lines }] : [];
31439
31712
  });
31440
31713
  HUG_TIE = 0.1;
31441
- fillAmong = (frames, boxes2, first, own2, weight) => {
31714
+ fillAmong = (frames, boxes2, first, own3, weight) => {
31442
31715
  const mutual = (s) => along(first.group.lab, first.around, s.group.lab).t >= 0.5 && along(s.group.lab, s.around, first.group.lab).t >= 0.5;
31443
31716
  const within = (s) => s.enclosed >= ENCLOSED && (dEdge(s.around, first.around) <= 15 || (() => {
31444
31717
  const a = along(s.group.lab, first.around, s.around);
31445
31718
  return a.t >= 0.5 && a.off <= 15;
31446
31719
  })());
31447
- const rivals = own2.filter((s) => s === first || within(s) || mutual(s));
31720
+ const rivals = own3.filter((s) => s === first || within(s) || mutual(s));
31448
31721
  if (rivals.length < 2) return first;
31449
31722
  const told = rivals.flatMap((s) => s.told ? [s.told] : []);
31450
31723
  const hugs = rivals.map((s) => ({ s, hug: hugOf(frames, boxes2, s.px, s.group.at.map((l, k) => told.every((t) => t.includes(k)) ? l : void 0), s.around) }));
@@ -31466,21 +31739,21 @@ var init_letters = __esm({
31466
31739
  const a = along(core.group.lab, core.around, s.group.lab);
31467
31740
  return a.t > 0 && a.t < 0.85 && a.off <= 15;
31468
31741
  };
31469
- const own2 = candidates3.filter((s) => !plainCores.some((core) => core !== s && core.group.lines >= s.group.lines && strokesPerLine(core) > strokesPerLine(s) && dEdge(core.group.lab, s.around) <= 15 && fringeOf(s, core)));
31742
+ const own3 = candidates3.filter((s) => !plainCores.some((core) => core !== s && core.group.lines >= s.group.lines && strokesPerLine(core) > strokesPerLine(s) && dEdge(core.group.lab, s.around) <= 15 && fringeOf(s, core)));
31470
31743
  const lineHeight = median10(boxes2.map((b) => b.y1 - b.y0));
31471
- const enclosed = own2.filter((s) => s.enclosed >= ENCLOSED && !isPicture(aroundOf(s, around3), s.around) || off2.has(s)).sort((a, b) => b.enclosed * b.group.lines - a.enclosed * a.group.lines || strokesPerLine(b) - strokesPerLine(a));
31744
+ const enclosed = own3.filter((s) => s.enclosed >= ENCLOSED && !isPicture(aroundOf(s, around3), s.around) || off2.has(s)).sort((a, b) => b.enclosed * b.group.lines - a.enclosed * a.group.lines || strokesPerLine(b) - strokesPerLine(a));
31472
31745
  const fillSure = (s) => {
31473
31746
  const c = sureOf(s, n);
31474
31747
  return c >= SURE2 ? { color: hexOf(s), confidence: c } : { confidence: c };
31475
31748
  };
31476
31749
  const base = { samples: n };
31477
31750
  const top2 = enclosed[0];
31478
- const best = top2 && fillAmong(frames, boxes2, top2, own2, (s) => strokesPerLine(s) * s.group.lines);
31751
+ const best = top2 && fillAmong(frames, boxes2, top2, own3, (s) => strokesPerLine(s) * s.group.lines);
31479
31752
  const look2 = best ? outlineLook(frames, boxes2, best, all, n, fillSure(best), lineHeight, off2.get(best)) : void 0;
31480
31753
  const part = best ? off2.get(best) : void 0;
31481
31754
  if (best && look2) return { fill: best, look: look2, ...part ? { part } : {} };
31482
- const arounds = own2.filter((s) => s.enclosed >= ENCLOSED / 2).map((s) => s.around);
31483
- const fill4 = own2.filter((s) => !arounds.some((a) => dEdge(a, s.group.lab) < 15)).sort((a, b) => strokesPerLine(b) * b.group.lines - strokesPerLine(a) * a.group.lines)[0];
31755
+ const arounds = own3.filter((s) => s.enclosed >= ENCLOSED / 2).map((s) => s.around);
31756
+ const fill4 = own3.filter((s) => !arounds.some((a) => dEdge(a, s.group.lab) < 15)).sort((a, b) => strokesPerLine(b) * b.group.lines - strokesPerLine(a) * a.group.lines)[0];
31484
31757
  if (!fill4) return { look: { kind: "plain", ...base, confidence: 0, unsure: ["fill: no colour stayed the same inside the lines while the picture changed, so the letters' colour is not given"] } };
31485
31758
  const sure = fillSure(fill4);
31486
31759
  const unsure = sure.color ? {} : { unsure: ["fill: the letters' colour changed from line to line, so it is not given"] };
@@ -31850,7 +32123,7 @@ var init_shadow = __esm({
31850
32123
  });
31851
32124
 
31852
32125
  // src/video/text/look.ts
31853
- var MAX_SAMPLES3, MIN_SAMPLES, PLATE_SHARE2, FONT_OF_BOX2, edgeBeyond, cornerCut, rgbAt, edgePairs, plateOf, plateColour, plateLook, refined, shared, lookOf2, samplesOf, captionFrames, measureCaptionLook;
32126
+ var MAX_SAMPLES3, MIN_SAMPLES, PLATE_SHARE2, FONT_OF_BOX2, edgeBeyond, cornerCut, rgbAt, edgePairs, plateOf, plateColour, plateLook, refined, shared2, lookOf2, samplesOf, captionFrames, measureCaptionLook;
31854
32127
  var init_look = __esm({
31855
32128
  "src/video/text/look.ts"() {
31856
32129
  "use strict";
@@ -32009,7 +32282,7 @@ var init_look = __esm({
32009
32282
  ...weight ?? {}
32010
32283
  };
32011
32284
  };
32012
- shared = (h, n) => h ? { ...h, share: r210(h.lines / Math.max(1, n)) } : void 0;
32285
+ shared2 = (h, n) => h ? { ...h, share: r210(h.lines / Math.max(1, n)) } : void 0;
32013
32286
  lookOf2 = (frames, boxes2, texts = []) => {
32014
32287
  if (frames.length < MIN_SAMPLES) return void 0;
32015
32288
  const readings = frames.map((f, k) => plateOf(f, boxes2[k]));
@@ -32019,14 +32292,14 @@ var init_look = __esm({
32019
32292
  if (plates.length >= PLATE_SHARE2 * readings.length) {
32020
32293
  const look3 = plateLook(frames.length, plates);
32021
32294
  const fill5 = readings.map((r) => r.plate && r.letters ? toLab(r.letters) : void 0);
32022
- const highlight2 = shared(highlightOf(frames, boxes2, texts, { fill: fill5, around: labMedian(plates.map((p) => toLab(p.colour))) }, candidates3, around3), frames.length);
32295
+ const highlight2 = shared2(highlightOf(frames, boxes2, texts, { fill: fill5, around: labMedian(plates.map((p) => toLab(p.colour))) }, candidates3, around3), frames.length);
32023
32296
  return highlight2 ? { ...look3, highlight: highlight2 } : look3;
32024
32297
  }
32025
32298
  const letters2 = lettersOf(frames, boxes2, candidates3, around3);
32026
32299
  const { fill: fill4 } = letters2;
32027
32300
  const look2 = refined(frames, boxes2, letters2, around3);
32028
32301
  const ctx = fill4 ? { fill: fill4.group.at, px: fill4.px, ...look2.kind === "outline" || look2.kind === "plate" ? { around: fill4.around } : {} } : void 0;
32029
- const highlight = shared(ctx ? highlightOf(frames, boxes2, texts, ctx, candidates3, around3) : void 0, frames.length);
32302
+ const highlight = shared2(ctx ? highlightOf(frames, boxes2, texts, ctx, candidates3, around3) : void 0, frames.length);
32030
32303
  return highlight ? { ...look2, highlight } : look2;
32031
32304
  };
32032
32305
  samplesOf = (track) => {
@@ -32084,8 +32357,8 @@ var init_reader_command = __esm({
32084
32357
  jobs = (rt) => Math.max(1, Math.min(16, Math.round(Number(rt.env.POPOST_OCR_JOBS) || 1)));
32085
32358
  readerSplit = (rt, frames) => {
32086
32359
  const budget = cpuBudgetOf(rt).cpus;
32087
- const own2 = Math.floor(Number(rt.env.POPOST_TOOL_THREADS?.trim()));
32088
- const each = own2 >= 1 ? own2 : void 0;
32360
+ const own3 = Math.floor(Number(rt.env.POPOST_TOOL_THREADS?.trim()));
32361
+ const each = own3 >= 1 ? own3 : void 0;
32089
32362
  const processes = Math.max(1, Math.min(jobs(rt), Math.ceil(frames / 8), Math.floor(budget / (each ?? 1))));
32090
32363
  return { processes, threads: each ?? Math.max(1, Math.min(TOOL_THREADS, Math.floor(budget / processes))) };
32091
32364
  };
@@ -32287,9 +32560,9 @@ var init_readback_kept = __esm({
32287
32560
  const who = readerOf(rt);
32288
32561
  const [hashes2, kept2] = await Promise.all([Promise.all(frames.map(async (f) => sha256(await rt.fs.readFile(f.file)))), keptLines(rt, file, who)]);
32289
32562
  const old = hashes2.map((h) => Array.isArray(kept2[h]) ? kept2[h] : void 0);
32290
- const missing2 = frames.filter((_f, i) => old[i] === void 0);
32291
- onKept?.(frames.length - missing2.length, frames.length);
32292
- const read2 = new Map((missing2.length ? await reader.read(missing2) : []).map((s) => [s.frame, s.lines]));
32563
+ const missing3 = frames.filter((_f, i) => old[i] === void 0);
32564
+ onKept?.(frames.length - missing3.length, frames.length);
32565
+ const read2 = new Map((missing3.length ? await reader.read(missing3) : []).map((s) => [s.frame, s.lines]));
32293
32566
  const found = frames.flatMap((f, i) => {
32294
32567
  const lines = old[i] ?? read2.get(f.frame);
32295
32568
  return lines ? [{ hash: hashes2[i], sample: { frame: f.frame, lines } }] : [];
@@ -33084,23 +33357,23 @@ var init_findings = __esm({
33084
33357
  });
33085
33358
  effectProjectProblems = (rf, project) => rf.shots.flatMap((s, k) => {
33086
33359
  const e = s.effect, o = e?.by === "before" ? k - 1 : k;
33087
- const seg = project.segments[k], own2 = project.segments[o];
33088
- if (!e || !seg || !own2) return [];
33360
+ const seg = project.segments[k], own3 = project.segments[o];
33361
+ if (!e || !seg || !own3) return [];
33089
33362
  const out2 = [];
33090
33363
  if (seg.in && seg.in.transition !== "cut")
33091
33364
  out2.push(warning(
33092
33365
  "segments[" + k + "].in",
33093
33366
  'The change into segment "' + seg.id + '" is the preset "' + seg.in.transition + '"; the reading saw an effect of its own there: ' + effectText(e) + ". A preset does not make it.",
33094
- 'Remove "in" (a cut). ' + effectFix(e, 'segment "' + own2.id + '"', 'segment "' + seg.id + '"') + " Running template fill again does both."
33367
+ 'Remove "in" (a cut). ' + effectFix(e, 'segment "' + own3.id + '"', 'segment "' + seg.id + '"') + " Running template fill again does both."
33095
33368
  ));
33096
- if (!("scene" in own2.base))
33369
+ if (!("scene" in own3.base))
33097
33370
  out2.push(warning(
33098
33371
  "segments[" + o + "].base",
33099
- effectOwner(e, o + 1, k + 1, "Segment") + effectText(e) + '; segment "' + own2.id + '" is not a scene, so nothing draws it.',
33100
- 'Make segment "' + own2.id + '" a scene. ' + effectFix(e, 'segment "' + own2.id + '"', 'segment "' + seg.id + '"')
33372
+ effectOwner(e, o + 1, k + 1, "Segment") + effectText(e) + '; segment "' + own3.id + '" is not a scene, so nothing draws it.',
33373
+ 'Make segment "' + own3.id + '" a scene. ' + effectFix(e, 'segment "' + own3.id + '"', 'segment "' + seg.id + '"')
33101
33374
  ));
33102
- else if ((own2.frames ?? 0) < e.frames)
33103
- out2.push(warning("segments[" + o + "].frames", 'Segment "' + own2.id + '" draws an effect of ' + e.frames + " frames (" + effectText(e) + ") and is " + (own2.frames ?? 0) + " frames long.", "Run template fill again: it moves the cut so that the scene covers the effect."));
33375
+ else if ((own3.frames ?? 0) < e.frames)
33376
+ out2.push(warning("segments[" + o + "].frames", 'Segment "' + own3.id + '" draws an effect of ' + e.frames + " frames (" + effectText(e) + ") and is " + (own3.frames ?? 0) + " frames long.", "Run template fill again: it moves the cut so that the scene covers the effect."));
33104
33377
  return out2;
33105
33378
  });
33106
33379
  CJK3 = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu;
@@ -33136,7 +33409,7 @@ var init_findings = __esm({
33136
33409
  droppedFillProblems = (rf, fill4, scenes) => {
33137
33410
  const keys2 = rf.dropped.map(keysOf2);
33138
33411
  if (!keys2.length) return [];
33139
- const own2 = fillTexts(fill4).flatMap((t) => {
33412
+ const own3 = fillTexts(fill4).flatMap((t) => {
33140
33413
  const shown3 = shownOf(t.text, keys2);
33141
33414
  return shown3.length ? [droppedProblem(t.at, t.at + " " + quote12(t.text), shown3)] : [];
33142
33415
  });
@@ -33146,7 +33419,7 @@ var init_findings = __esm({
33146
33419
  const shown3 = file ? shownOf(pageText(scenes.get(file) ?? ""), keys2) : [];
33147
33420
  return file && shown3.length ? [droppedProblem("shots[" + k + "].scene", 'The scene "' + file + '"', shown3)] : [];
33148
33421
  });
33149
- return [...own2, ...drawn];
33422
+ return [...own3, ...drawn];
33150
33423
  };
33151
33424
  droppedProjectProblems = (rf, project, scenes) => {
33152
33425
  const keys2 = rf.dropped.map(keysOf2);
@@ -33513,7 +33786,7 @@ var init_check5 = __esm({
33513
33786
  fileProblems = async (rt, pkg, fill4, dir, lengths) => {
33514
33787
  const exists3 = async (p) => await rt.fs.stat(p) !== null;
33515
33788
  const out2 = [];
33516
- const missing2 = (at7, file) => error(at7, quote13(file) + " does not exist in " + dir + ".", "Put the file there, or correct the path (it is relative to the project directory).");
33789
+ const missing3 = (at7, file) => error(at7, quote13(file) + " does not exist in " + dir + ".", "Put the file there, or correct the path (it is relative to the project directory).");
33517
33790
  for (const [k, raw] of fill4.shots.entries()) {
33518
33791
  const s = raw;
33519
33792
  if (k >= pkg.template.shots.length || kindsOf2(s).length !== 1) continue;
@@ -33522,7 +33795,7 @@ var init_check5 = __esm({
33522
33795
  if (typeof file !== "string" || !file.trim() || isOutside(file)) continue;
33523
33796
  const full = rt.path.resolve(dir, file);
33524
33797
  if (!await exists3(full)) {
33525
- out2.push(missing2("shots[" + k + "]." + key2, file));
33798
+ out2.push(missing3("shots[" + k + "]." + key2, file));
33526
33799
  continue;
33527
33800
  }
33528
33801
  if (key2 === "picture" && !PICTURES3.includes(rt.path.extname(file).toLowerCase())) out2.push(error("shots[" + k + "].picture", quote13(file) + " is not a picture file (" + PICTURES3.join(", ") + ").", "Convert it to WebP or PNG."));
@@ -33532,8 +33805,8 @@ var init_check5 = __esm({
33532
33805
  }
33533
33806
  out2.push(...await itemFileProblems(rt, pkg, s, k, dir, lengths));
33534
33807
  }
33535
- if (typeof fill4.sound === "string" && !await exists3(rt.path.resolve(dir, fill4.sound))) out2.push(missing2("sound", fill4.sound));
33536
- for (const [i, bed] of (Array.isArray(fill4.beds) ? fill4.beds : []).entries()) if (typeof bed?.footage === "string" && !isOutside(bed.footage) && !await exists3(rt.path.resolve(dir, bed.footage))) out2.push(missing2("beds[" + i + "].footage", bed.footage));
33808
+ if (typeof fill4.sound === "string" && !await exists3(rt.path.resolve(dir, fill4.sound))) out2.push(missing3("sound", fill4.sound));
33809
+ for (const [i, bed] of (Array.isArray(fill4.beds) ? fill4.beds : []).entries()) if (typeof bed?.footage === "string" && !isOutside(bed.footage) && !await exists3(rt.path.resolve(dir, bed.footage))) out2.push(missing3("beds[" + i + "].footage", bed.footage));
33537
33810
  out2.push(...await stillProblems(rt, pkg, fill4, dir, lengths));
33538
33811
  for (const p of await slotPictures(rt, fill4, dir)) out2.push(...await slotPictureProblems(rt, p, dir));
33539
33812
  return out2;
@@ -34271,12 +34544,12 @@ var init_speak = __esm({
34271
34544
  const takes = takesOf(spoken);
34272
34545
  const clips = await speakLines(rt, { lines: takes.map((t) => t.text), dir: rt.path.join(o.outDir, "assets", "voice"), speaker: o.speaker, fps, name: "take", ...plan4.voice ? { voice: plan4.voice } : {}, ...plan4.speed ? { speed: plan4.speed } : {} });
34273
34546
  const said = [];
34274
- let own2 = true;
34547
+ let own3 = true;
34275
34548
  for (const [k, take] of takes.entries()) {
34276
34549
  const clip11 = clips[k], lines2 = take.lines.map((i) => spoken[i] ?? "");
34277
34550
  const got = await takeWords(rt, o, clip11, lines2, fps, notes2);
34278
34551
  const words2 = got.words;
34279
- own2 = own2 && got.own;
34552
+ own3 = own3 && got.own;
34280
34553
  const { spans, matched } = lineSpans(lines2, words2);
34281
34554
  if (matched < 0.6) notes2.push("Only " + Math.round(matched * 100) + "% of the words of the take of captions[" + take.lines[0] + ".." + take.lines[take.lines.length - 1] + "] were said as written: its lines are placed by the words around them.");
34282
34555
  said.push({ take, clip: clip11, words: words2, spans, pieces: piecesOf(take, spans, ref, fps, o.hold === true, o.keepPauses === true) });
@@ -34296,7 +34569,7 @@ var init_speak = __esm({
34296
34569
  await writeVoiceReceipt(rt, rt.path.join(o.outDir, VOICE_FILE), lines.filter((l) => l.file).length);
34297
34570
  const words = voiceWords({ lines: captions, starts: result.timing.starts, frames: flow.frames, fps, ...plan4.say ? { say: plan4.say } : {}, transcript: { language: "", fps, words: laid.words } });
34298
34571
  await rt.fs.writeFile(rt.path.join(o.outDir, WORDS_FILE), JSON.stringify({ fps: words.fps, tokens: words.tokens }, null, 1) + "\n");
34299
- notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (own2 ? " (the speaker's own word times)." : " (heard or spread over the takes, see above)."));
34572
+ notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (own3 ? " (the speaker's own word times)." : " (heard or spread over the takes, see above)."));
34300
34573
  return { result, lines, words, notes: notes2 };
34301
34574
  };
34302
34575
  speakRetarget = async (rt, o) => {
@@ -34324,11 +34597,11 @@ var init_speak = __esm({
34324
34597
  notes2.push(...overrunNotes({ lines: captions, slots: t.slots, spoken: lines.map((l) => l.frames), reference: t.reference, total: t.total, fps, ...plan4.speed ? { speed: plan4.speed } : {} }));
34325
34598
  await mixLines(rt, { lines, starts: result.timing.starts, fps, totalFrames: result.timing.total, out: rt.path.join(o.outDir, VOICE_FILE) });
34326
34599
  await writeVoiceReceipt(rt, rt.path.join(o.outDir, VOICE_FILE), lines.filter((l) => l.file).length);
34327
- const own2 = spokenTranscript(lines, result.timing.starts, fps);
34328
- const transcript2 = own2 ?? (o.transcriber ? await hear2(rt, rt.path.join(o.outDir, VOICE_FILE), fps, o.transcriber, o.language, notes2) : void 0);
34600
+ const own3 = spokenTranscript(lines, result.timing.starts, fps);
34601
+ const transcript2 = own3 ?? (o.transcriber ? await hear2(rt, rt.path.join(o.outDir, VOICE_FILE), fps, o.transcriber, o.language, notes2) : void 0);
34329
34602
  const words = voiceWords({ lines: captions, starts: result.timing.starts, frames: lines.map((l) => l.frames), fps, ...plan4.say ? { say: plan4.say } : {}, ...transcript2 ? { transcript: transcript2 } : {} });
34330
34603
  await rt.fs.writeFile(rt.path.join(o.outDir, WORDS_FILE), JSON.stringify({ fps: words.fps, tokens: words.tokens }, null, 1) + "\n");
34331
- notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (words.estimated ? " (estimated: no transcriber, so each line's time is shared evenly among its words)." : own2 ? " (the speaker's own word times)." : " (from a transcript of the voice)."));
34604
+ notes2.push(words.tokens.length + " word times written to " + WORDS_FILE + (words.estimated ? " (estimated: no transcriber, so each line's time is shared evenly among its words)." : own3 ? " (the speaker's own word times)." : " (from a transcript of the voice)."));
34332
34605
  return { result, lines, words, notes: notes2 };
34333
34606
  };
34334
34607
  }
@@ -35597,12 +35870,12 @@ var init_time2 = __esm({
35597
35870
  const offset = boundaryOffset(ref, other, tol);
35598
35871
  const byTime = pairBoundaries(ref, other, tol, offset);
35599
35872
  const byShare = 2 * byTime.length < ref.boundaries.length ? fillGaps(ref, other, pairCutsByShare(ref, other)) : [];
35600
- const shared2 = byShare.length > byTime.length;
35601
- const pairs = shared2 ? byShare : byTime;
35873
+ const shared3 = byShare.length > byTime.length;
35874
+ const pairs = shared3 ? byShare : byTime;
35602
35875
  const fr = fpsOf(ref), fo = fpsOf(other);
35603
35876
  const per = pairs.map((p) => {
35604
35877
  const a = ref.boundaries[p.r], b = other.boundaries[p.o];
35605
- const shift = shared2 ? a.frame / fr - b.frame / fo : -offset;
35878
+ const shift = shared3 ? a.frame / fr - b.frame / fo : -offset;
35606
35879
  const [b0, b1] = spanSeconds(b, fo);
35607
35880
  const overlap6 = a.kind === "cut" && b.kind === "cut" ? 1 : intervalIoU(spanSeconds(a, fr), [b0 + shift, b1 + shift]);
35608
35881
  const kind = kindCredit(a.kind, b.kind), pr = params(a, b);
@@ -35617,7 +35890,7 @@ var init_time2 = __esm({
35617
35890
  spanOverlap: r310(mean4(per.map((x) => x.overlap))),
35618
35891
  params: prs.length ? r310(mean4(prs)) : "-",
35619
35892
  exactKind: per.filter((x) => x.kind === 1).length,
35620
- ...shared2 ? { pairedBy: "share of the length" } : {}
35893
+ ...shared3 ? { pairedBy: "share of the length" } : {}
35621
35894
  }
35622
35895
  };
35623
35896
  };
@@ -36487,8 +36760,8 @@ var init_stage = __esm({
36487
36760
  return /^(header|footer|nav|main|aside|article|form|table)$/.test(p) && unique3(p) ? p : null;
36488
36761
  };
36489
36762
  const selectorOf = (el) => {
36490
- const own2 = anchor(el);
36491
- if (own2 && own2 !== "body") return own2;
36763
+ const own3 = anchor(el);
36764
+ if (own3 && own3 !== "body") return own3;
36492
36765
  const tag3 = el.tagName.toLowerCase();
36493
36766
  for (const attr2 of ["data-testid", "data-test", "aria-label", "name", "placeholder", "href"]) {
36494
36767
  const v = el.getAttribute(attr2);
@@ -37678,10 +37951,10 @@ var SHELL_BUNDLE;
37678
37951
  var init_shell_bundle = __esm({
37679
37952
  "src/video/preview/shell-bundle.ts"() {
37680
37953
  "use strict";
37681
- SHELL_BUNDLE = `"use strict";(()=>{var De="reload",je="render";var ao=new Set(["wipe","slide","whip"]),se=e=>e.resolved?.canvas.fps??e.measure?.measure.source.fps??e.referenceMeasure?.measure.source.fps??30,ye=(e,t,n)=>e*n/t,io=(e,t,n)=>Math.floor((e+.5)*n/t),W=e=>{if(e.resolved)return e.resolved.frames;let t=se(e),n=[e.measure,e.referenceMeasure].map(o=>o?Math.round(ye(o.measure.source.frames,o.measure.source.fps,t)):0);return Math.max(0,...n)},pe=(e,t)=>Math.min(Math.max(0,t-1),Math.max(0,Math.round(e))),Z=(e,t)=>e.segments.find(n=>t>=n.start&&t<n.end),fe=(e,t)=>e.items.filter(n=>t>=n.start&&t<n.end),Nt=e=>[e.kind,e.frames+"f",ao.has(e.kind)?e.direction:"",e.kind==="slide"?e.mode:"",e.kind==="fade"?"via "+e.via:"",e.side&&e.side!=="both"?e.side:"",e.strength!==void 0&&e.strength!==1?"x"+e.strength:""].filter(Boolean).join(" "),Te=e=>e.preset+" "+e.frames+"f"+(e.preset==="slide"||e.preset==="wipe"?" "+e.direction:""),It=e=>[e.kind,e.kind==="cut"?"":e.end-e.start-1+"f",e.direction??"",e.mode??"",e.via?"via "+e.via:"",e.confidence.toFixed(2)].filter(Boolean).join(" "),ze=e=>[e.kind,e.how??"",e.direction??""].filter(Boolean).join(" "),Ft=e=>e.shots.flatMap((t,n)=>t.events.map((o,r)=>({shot:n,index:r,event:o}))).sort((t,n)=>t.event.start-n.event.start||t.shot-n.shot),Dt=(e,t,n)=>{let o=io(t,n,e.source.fps);return e.shots.flatMap(r=>r.events.filter(s=>o>=s.start&&o<s.end))},mt=(e,t)=>{let n=[];return e.map(o=>{let r=n.findIndex(a=>a<=o.start),s=r>=0?r:Math.min(n.length,t-1);return n[s]=Math.max(n[s]??0,o.end),{row:s,...o}})},jt=(e,t)=>{let n=e/t,o=[.5,1,2,5,10,15,30,60,120,300].find(s=>n/s<=12)??600,r=Math.floor(n/o);return Array.from({length:r+1},(s,a)=>({frame:Math.round(a*o*t),label:String(Number((a*o).toFixed(1)))+"s"}))},zt=e=>e.height>e.width?[.06,.08,.82,.72]:[.05,.05,.9,.9],pt=(e,t)=>(e/t).toFixed(2)+" s",ge=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ht=(e,t)=>(t==="render"?e.measure:e.referenceMeasure)?.measure,Bt=(e,t)=>{switch(t.kind){case"slot":return;case"segment":return e.resolved?.segments.find(n=>n.id===t.id);case"item":return e.resolved?.items.find(n=>n.id===t.id);case"audio":return e.resolved?.audio.find(n=>n.id===t.id);case"boundary":return Ht(e,t.source)?.boundaries[t.index];case"event":return Ht(e,t.source)?.shots[t.shot]?.events[t.index]}},Vt=e=>{switch(e.kind){case"slot":return e.name;case"segment":case"item":case"audio":return e.kind+" "+e.id;case"boundary":return e.source+" boundary "+(e.index+1);case"event":return e.source+" event "+(e.shot+1)+"."+(e.index+1)}};var Ve={schema:null,status:null,problems:[],render:null,playRender:!1},_e=e=>{let t=e,n=[];return{get:()=>t,set:o=>{let r=t;t={...t,...o},n.forEach(s=>s(t,r))},subscribe:o=>(n.push(o),()=>{let r=n.indexOf(o);r>=0&&n.splice(r,1)})}},_t=[.25,.5,1],Be=e=>e.state?W(e.state):0,lo=e=>e.state?se(e.state):30,co=e=>{let t={frame:0,time:0},n=0,o=s=>{let a=e.get();if(!a.playing)return;let d=Math.max(0,Be(a)-1),i=Math.min(d,t.frame+Math.floor((s-t.time)/1e3*lo(a)*a.speed));if(i>=d)return e.set({frame:d,playing:!1});i!==a.frame&&e.set({frame:i}),n=requestAnimationFrame(o)},r=()=>{t={frame:e.get().frame,time:performance.now()}};return{reanchor:r,pause:()=>{cancelAnimationFrame(n),e.get().playing&&e.set({playing:!1})},play:()=>{let s=e.get();Be(s)<2||(s.frame>=Be(s)-1&&e.set({frame:0}),r(),e.set({playing:!0}),n=requestAnimationFrame(o))}}},Ke=e=>{let t=co(e),n=o=>{e.set({frame:pe(o,Be(e.get()))}),t.reanchor()};return{seek:n,step:o=>n(e.get().frame+o),togglePlay:()=>e.get().playing?t.pause():t.play(),pause:t.pause,setSpeed:o=>{e.set({speed:o}),t.reanchor()},pin:o=>e.set({pinned:o}),toggleOverlay:o=>{let r=e.get().overlays;e.set({overlays:{...r,[o]:!r[o]}})},setLang:o=>{document.documentElement.lang=o==="zh"?"zh-CN":"en",e.set({lang:o})}}};var m=(e,t={},n=[])=>{let o=document.createElement(e);t.class&&(o.className=t.class),t.id&&(o.id=t.id),t.text!==void 0&&(o.textContent=t.text),t.title&&(o.title=t.title),t.style&&(o.style.cssText=t.style);for(let[r,s]of Object.entries(t.attrs??{}))o.setAttribute(r,s);for(let[r,s]of Object.entries(t.data??{}))o.dataset[r]=s;for(let[r,s]of Object.entries(t.on??{}))s&&o.addEventListener(r,s);return o.append(...n),o},Kt="http://www.w3.org/2000/svg",uo={film:"M2 2h12v12H2zM5 2v12M11 2v12M2 6h3M2 10h3M11 6h3M11 10h3",media:"M2 2h12v12H2zM2 12l4-5 4 4 2-2 2 3M5 4h.1",text:"M2 3h12M8 3v11M5 14h6",layers:"M1 5l7-4 7 4-7 4-7-4M1 8l7 4 7-4M1 11l7 4 7-4",code:"M5 3 1 8l4 5M11 3l4 5-4 5M9 2 7 14",checks:"M8 1l6 2v5c0 4-6 7-6 7S2 12 2 8V3l6-2M5 8l2 2 4-4",first:"M4 3v10M12 3.5 6 8l6 4.5z",last:"M12 3v10M4 3.5 10 8l-6 4.5z",play:"M5 3l8 5-8 5z",pause:"M5.5 3v10M10.5 3v10",undo:"M6 3.5 3 6.5l3 3M3 6.5h6.5a3.5 3.5 0 0 1 0 7H7",redo:"M10 3.5l3 3-3 3M13 6.5H6.5a3.5 3.5 0 0 0 0 7H9",remove:"M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.7 8.5h5.6l.7-8.5M7 7v4M9 7v4",addText:"M2 3.5h7M5.5 3.5V12M11.5 8v5M9 10.5h5",duplicate:"M5.5 5.5h7v7h-7zM3.5 10.5v-7h7",render:"M2.5 3.5h11v9h-11zM7 6l3 2-3 2z",compare:"M2 2h12v12H2zM8 2v12M4 6h2M10 10h2",layout:"M2 2h12v12H2zM5.5 2v12M10.5 2v12",history:"M2 2v4h4M2 6a6 6 0 1 1 0 4M8 4v4l3 2",theme:"M8 1a7 7 0 1 0 7 7A5 5 0 0 1 8 1z",language:"M1 3h8M5 1v2M3 3c0 4 3 6 6 7M8 3c0 4-3 6-7 7M9 14l3-8 3 8M10 11h4",download:"M8 1v9M4 6l4 4 4-4M2 11v3h12v-3",external:"M9 2h5v5M14 2 7 9M6 2H2v12h12v-4",cloud:"M4 12a3 3 0 0 1-1-5.8A5 5 0 0 1 12 5a3.5 3.5 0 0 1 0 7M8 14V7M5.5 9.5 8 7l2.5 2.5",refresh:"M13 2v4H9M13 6a5.5 5.5 0 1 0 .2 5"},Y=e=>{let t=document.createElementNS(Kt,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","16"),t.setAttribute("height","16"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(Kt,"path");return n.setAttribute("d",uo[e]),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.5"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("stroke-linecap","round"),t.appendChild(n),t},Le=(e,t,n,o)=>{let r=Math.max(1,o);return e.style.left=Math.max(0,t)/r*100+"%",e.style.width=Math.max(0,Math.min(n,r)-Math.max(0,t))/r*100+"%",e},Q=(e,t,n)=>(e.style.left=Math.max(0,Math.min(t,n))/Math.max(1,n)*100+"%",e),le=(e,t)=>{let[n=0,o=0,r=0,s=0]=t;return e.style.left=n*100+"%",e.style.top=o*100+"%",e.style.width=r*100+"%",e.style.height=s*100+"%",e};var ft={title:"Video preview",readOnly:"read-only",live:"live",offline:"offline, retrying",language:"\\u4E2D\\u6587",languageTitle:"Switch the interface to Chinese",currentVideo:"Current video",render:"Render",reference:"Reference",seekNote:"A browser video seek is near, not frame-exact.",noReference:"No reference video. Start with --reference <video> to show one here.",errorsOnStage:"The project has errors; the stage lists them.",imageFailed:"A picture failed to load",first:"First frame (Home)",last:"Last frame (End)",back10:"Back 10 frames (Shift+Left)",back1:"Back 1 frame (Left)",fwd1:"Forward 1 frame (Right)",fwd10:"Forward 10 frames (Shift+Right)",play:"Play (Space)",pause:"Pause (Space)",frame:"Frame",time:"Time",speed:"Speed",jump:"Go to frame",jumpHint:"Frame number, then Enter",ruler:"Seconds",segments:"Segments",audio:"Audio",words:"Words",renderBoundaries:"Render: boundaries",renderEvents:"Render: events",referenceBoundaries:"Reference: boundaries",referenceEvents:"Reference: events",boxes:"Item boxes",events:"Measured events",safe:"Safe area",selection:"Selection",underPlayhead:"under the playhead",pinned:"clicked",follow:"Follow the playhead",onScreen:"On screen",nothing:"Nothing here.",problems:"Problems",noProblems:"No problems.",allowed:"Allowed",fix:"Fix",error:"error",warning:"warning",score:"Score",noScore:"No score: it needs a measurement of the render and one of the reference.",dimension:"Dimension",value:"Score",compared:"Compared",detail:"Detail",composite:"composite",measurements:"Measurements",renderMeasure:"Render",referenceMeasure:"Reference",none:"none",notes:"Draft notes",structure:"structure",transitions:"transitions",camera:"camera",motion:"motion",rhythm:"rhythm",colour:"colour",picture:"picture",editing:"editing",undo:"Undo (Ctrl+Z)",redo:"Redo (Shift+Ctrl+Z)",addText:"Add a text at the playhead",duplicate:"Duplicate the selection",remove:"Delete the selection (Delete)",renderTool:"Render the project to out.mp4",newText:"New text",saved:"Saved",added:"Added",removed:"Deleted",moved:"Moved",outside:"an edit made outside the page",undone:"Undone",redone:"Redone",notSaved:"Not saved",phraseSpan:"This item is placed on spoken words, so it is not dragged: change its lead and hold in the panel.",offlineEdit:"The preview server cannot be reached; nothing was saved.",rendering:"Rendering",rendered:"Rendered",framesIn:"frames in",renderFailed:"The render failed",playRender:"Play it beside the stage",showReference:"Show the reference again",renderFile:"Render",editHint:"Click an item on the stage, a bar in the lanes or a segment to edit it. Escape clears the selection.",resolvedTitle:"What the timeline plays (the default, or the value after resolving)",snapped:"snapped to",snapPlayhead:"the playhead",snapSegment:"a segment border",snapReference:"a boundary of the reference",framesWord:"frames",videoLength:"video",onFrames:"On frames",fDefault:"(default)",fCustom:"own values",fStyle:"Style",fNamed:"Style",fSize:"Size",fColour:"Colour",fWeight:"Weight",fAlign:"Align",fPreset:"Preset",fNone:"(none)",fFrames:"Frames",fDirection:"Direction",fEase:"Ease",fEnter:"Entrance",fExit:"Exit",fBox:"Box (fractions of the canvas)",fX:"x",fY:"y",fW:"width",fH:"height",fRotate:"Rotate",fOpacity:"Opacity",fZ:"Layer (z)",fLook:"Look",fRadius:"Corners",fShape:"Shape",fGradient:"A gradient: edit it in video.json.",fMaterial:"Material",fFit:"Fit",fMask:"Mask",fIn:"First frame",fSpeed:"Speed",fFootage:"Footage",fPicture:"Picture",fText:"Text",fStart:"Starts in",fWhole:"(the whole video)",fFrom:"From",fAudio:"Sound",fGain:"Gain (dB)",fSourceAudio:"Source audio dB (empty = automatic: on when the video has no audio track)",fSegment:"Segment",fWhen:"When",fPhrase:"Phrase",fOccurrence:"Occurrence",fLead:"Lead",fHold:"Hold",fTo:"To",fCue:"Cue",fCues:"Cues",fKind:"Kind",fHardCut:"(hard cut)",fMode:"Mode",fVia:"Via",fSide:"Side",fStrength:"Strength",fTransition:"Transition into it",fBase:"Base",fBaseColor:"colour",fBaseMaterial:"material",fBaseScene:"Scene content",fLength:"Length in frames",fCamera:"The camera: edit it in video.json."},mo={title:"\\u89C6\\u9891\\u9884\\u89C8",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u4E2D\\u65AD\\uFF0C\\u6B63\\u5728\\u91CD\\u8BD5",language:"English",languageTitle:"\\u628A\\u754C\\u9762\\u5207\\u6362\\u4E3A\\u82F1\\u6587",currentVideo:"\\u5F53\\u524D\\u4F5C\\u54C1",render:"\\u6E32\\u67D3",reference:"\\u53C2\\u8003\\u89C6\\u9891",seekNote:"\\u6D4F\\u89C8\\u5668\\u7684\\u89C6\\u9891\\u8DF3\\u8F6C\\u53EA\\u662F\\u63A5\\u8FD1\\uFF0C\\u4E0D\\u662F\\u9010\\u5E27\\u7CBE\\u786E\\u3002",noReference:"\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002\\u7528 --reference <\\u89C6\\u9891> \\u542F\\u52A8\\u5373\\u53EF\\u5728\\u6B64\\u663E\\u793A\\u3002",errorsOnStage:"\\u9879\\u76EE\\u6709\\u9519\\u8BEF\\uFF0C\\u753B\\u9762\\u533A\\u5217\\u51FA\\u4E86\\u5B83\\u4EEC\\u3002",imageFailed:"\\u6709\\u56FE\\u7247\\u52A0\\u8F7D\\u5931\\u8D25",first:"\\u7B2C\\u4E00\\u5E27 (Home)",last:"\\u6700\\u540E\\u4E00\\u5E27 (End)",back10:"\\u540E\\u9000 10 \\u5E27 (Shift+\\u2190)",back1:"\\u540E\\u9000 1 \\u5E27 (\\u2190)",fwd1:"\\u524D\\u8FDB 1 \\u5E27 (\\u2192)",fwd10:"\\u524D\\u8FDB 10 \\u5E27 (Shift+\\u2192)",play:"\\u64AD\\u653E (\\u7A7A\\u683C)",pause:"\\u6682\\u505C (\\u7A7A\\u683C)",frame:"\\u5E27",time:"\\u65F6\\u95F4",speed:"\\u901F\\u5EA6",jump:"\\u8DF3\\u5230\\u5E27",jumpHint:"\\u8F93\\u5165\\u5E27\\u53F7\\u540E\\u6309\\u56DE\\u8F66",ruler:"\\u79D2",segments:"\\u5206\\u6BB5",audio:"\\u97F3\\u9891",words:"\\u5B57\\u8BCD",renderBoundaries:"\\u6E32\\u67D3\\uFF1A\\u8FB9\\u754C",renderEvents:"\\u6E32\\u67D3\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",referenceBoundaries:"\\u53C2\\u8003\\uFF1A\\u8FB9\\u754C",referenceEvents:"\\u53C2\\u8003\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",boxes:"\\u5143\\u7D20\\u6846",events:"\\u6D4B\\u5F97\\u7684\\u4E8B\\u4EF6",safe:"\\u5B89\\u5168\\u533A",selection:"\\u9009\\u4E2D",underPlayhead:"\\u64AD\\u653E\\u5934\\u6240\\u5728\\u5904",pinned:"\\u5DF2\\u70B9\\u9009",follow:"\\u8DDF\\u968F\\u64AD\\u653E\\u5934",onScreen:"\\u753B\\u9762\\u4E2D",nothing:"\\u8FD9\\u91CC\\u6CA1\\u6709\\u5185\\u5BB9\\u3002",problems:"\\u95EE\\u9898",noProblems:"\\u6CA1\\u6709\\u95EE\\u9898\\u3002",allowed:"\\u5141\\u8BB8\\u7684\\u503C",fix:"\\u4FEE\\u6B63",error:"\\u9519\\u8BEF",warning:"\\u8B66\\u544A",score:"\\u8BC4\\u5206",noScore:"\\u6CA1\\u6709\\u8BC4\\u5206\\uFF1A\\u9700\\u8981\\u6E32\\u67D3\\u548C\\u53C2\\u8003\\u89C6\\u9891\\u5404\\u81EA\\u7684\\u6D4B\\u91CF\\u7ED3\\u679C\\u3002",dimension:"\\u7EF4\\u5EA6",value:"\\u5206\\u6570",compared:"\\u6BD4\\u8F83\\u6570",detail:"\\u7EC6\\u8282",composite:"\\u7EFC\\u5408",measurements:"\\u6D4B\\u91CF\\u7ED3\\u679C",renderMeasure:"\\u6E32\\u67D3",referenceMeasure:"\\u53C2\\u8003",none:"\\u65E0",notes:"\\u8349\\u7A3F\\u5907\\u6CE8",structure:"\\u7ED3\\u6784",transitions:"\\u8F6C\\u573A",camera:"\\u955C\\u5934\\u8FD0\\u52A8",motion:"\\u5143\\u7D20\\u52A8\\u6548",rhythm:"\\u8282\\u594F",colour:"\\u8272\\u5F69",picture:"\\u753B\\u9762",editing:"\\u7F16\\u8F91\\u4E2D",undo:"\\u64A4\\u9500 (Ctrl+Z)",redo:"\\u91CD\\u505A (Shift+Ctrl+Z)",addText:"\\u5728\\u64AD\\u653E\\u5934\\u5904\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236\\u6240\\u9009\\u5185\\u5BB9",remove:"\\u5220\\u9664\\u6240\\u9009\\u5185\\u5BB9 (Delete)",renderTool:"\\u628A\\u9879\\u76EE\\u6E32\\u67D3\\u4E3A out.mp4",newText:"\\u65B0\\u6587\\u5B57",saved:"\\u5DF2\\u4FDD\\u5B58",added:"\\u5DF2\\u6DFB\\u52A0",removed:"\\u5DF2\\u5220\\u9664",moved:"\\u5DF2\\u79FB\\u52A8",outside:"\\u9875\\u9762\\u5916\\u7684\\u4FEE\\u6539",undone:"\\u5DF2\\u64A4\\u9500",redone:"\\u5DF2\\u91CD\\u505A",notSaved:"\\u672A\\u4FDD\\u5B58",phraseSpan:"\\u8FD9\\u4E2A\\u5143\\u7D20\\u6309\\u8BF4\\u51FA\\u7684\\u5B57\\u8BCD\\u5B9A\\u4F4D\\uFF0C\\u4E0D\\u80FD\\u62D6\\u52A8\\uFF1A\\u8BF7\\u5728\\u9762\\u677F\\u91CC\\u4FEE\\u6539\\u5B83\\u7684\\u63D0\\u524D\\u91CF\\u548C\\u5EF6\\u540E\\u91CF\\u3002",offlineEdit:"\\u8FDE\\u4E0D\\u4E0A\\u9884\\u89C8\\u670D\\u52A1\\u5668\\uFF0C\\u6CA1\\u6709\\u4FDD\\u5B58\\u4EFB\\u4F55\\u4FEE\\u6539\\u3002",rendering:"\\u6E32\\u67D3\\u4E2D",rendered:"\\u5DF2\\u6E32\\u67D3",framesIn:"\\u5E27\\uFF0C\\u7528\\u65F6",renderFailed:"\\u6E32\\u67D3\\u5931\\u8D25",playRender:"\\u5728\\u753B\\u9762\\u65C1\\u64AD\\u653E",showReference:"\\u6539\\u56DE\\u663E\\u793A\\u53C2\\u8003\\u89C6\\u9891",renderFile:"\\u6E32\\u67D3\\u7ED3\\u679C",editHint:"\\u70B9\\u51FB\\u753B\\u9762\\u4E2D\\u7684\\u5143\\u7D20\\u3001\\u8F68\\u9053\\u4E0A\\u7684\\u6761\\u5757\\u6216\\u5206\\u6BB5\\u5373\\u53EF\\u7F16\\u8F91\\u3002\\u6309 Esc \\u53D6\\u6D88\\u9009\\u4E2D\\u3002",resolvedTitle:"\\u65F6\\u95F4\\u7EBF\\u5B9E\\u9645\\u64AD\\u653E\\u7684\\u503C\\uFF08\\u9ED8\\u8BA4\\u503C\\uFF0C\\u6216\\u89E3\\u6790\\u540E\\u7684\\u503C\\uFF09",snapped:"\\u5DF2\\u5438\\u9644\\u5230",snapPlayhead:"\\u64AD\\u653E\\u5934",snapSegment:"\\u5206\\u6BB5\\u8FB9\\u754C",snapReference:"\\u53C2\\u8003\\u89C6\\u9891\\u7684\\u8FB9\\u754C",framesWord:"\\u5E27",videoLength:"\\u89C6\\u9891",onFrames:"\\u6240\\u5728\\u5E27",fDefault:"\\uFF08\\u9ED8\\u8BA4\\uFF09",fCustom:"\\u81EA\\u5B9A\\u4E49",fStyle:"\\u6837\\u5F0F",fNamed:"\\u6837\\u5F0F",fSize:"\\u5B57\\u53F7",fColour:"\\u989C\\u8272",fWeight:"\\u5B57\\u91CD",fAlign:"\\u5BF9\\u9F50",fPreset:"\\u9884\\u8BBE",fNone:"\\uFF08\\u65E0\\uFF09",fFrames:"\\u5E27\\u6570",fDirection:"\\u65B9\\u5411",fEase:"\\u7F13\\u52A8",fEnter:"\\u5165\\u573A",fExit:"\\u51FA\\u573A",fBox:"\\u6846\\uFF08\\u753B\\u5E03\\u7684\\u6BD4\\u4F8B\\uFF09",fX:"x",fY:"y",fW:"\\u5BBD",fH:"\\u9AD8",fRotate:"\\u65CB\\u8F6C",fOpacity:"\\u4E0D\\u900F\\u660E\\u5EA6",fZ:"\\u5C42\\u7EA7 (z)",fLook:"\\u5916\\u89C2",fRadius:"\\u5706\\u89D2",fShape:"\\u5F62\\u72B6",fGradient:"\\u6E10\\u53D8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002",fMaterial:"\\u7D20\\u6750",fFit:"\\u9002\\u914D",fMask:"\\u906E\\u7F69",fIn:"\\u8D77\\u59CB\\u5E27",fSpeed:"\\u901F\\u5EA6",fFootage:"\\u89C6\\u9891\\u7D20\\u6750",fPicture:"\\u56FE\\u7247",fText:"\\u6587\\u5B57",fStart:"\\u5F00\\u59CB\\u4E8E",fWhole:"\\uFF08\\u6574\\u4E2A\\u89C6\\u9891\\uFF09",fFrom:"\\u4ECE",fAudio:"\\u58F0\\u97F3",fGain:"\\u589E\\u76CA (dB)",fSourceAudio:"\\u7D20\\u6750\\u539F\\u58F0 dB\\uFF08\\u7559\\u7A7A\\u4E3A\\u81EA\\u52A8\\uFF1A\\u89C6\\u9891\\u6CA1\\u6709\\u97F3\\u8F68\\u65F6\\u4FDD\\u7559\\uFF09",fSegment:"\\u5206\\u6BB5",fWhen:"\\u51FA\\u73B0\\u65F6\\u95F4",fPhrase:"\\u5B57\\u8BCD",fOccurrence:"\\u7B2C\\u51E0\\u6B21",fLead:"\\u63D0\\u524D",fHold:"\\u5EF6\\u540E",fTo:"\\u5230",fCue:"\\u5B57\\u5E55",fCues:"\\u5B57\\u5E55\\u6761",fKind:"\\u7C7B\\u578B",fHardCut:"\\uFF08\\u786C\\u5207\\uFF09",fMode:"\\u6A21\\u5F0F",fVia:"\\u7ECF\\u8FC7",fSide:"\\u5355\\u4FA7",fStrength:"\\u5F3A\\u5EA6",fTransition:"\\u8FDB\\u5165\\u5B83\\u7684\\u8F6C\\u573A",fBase:"\\u5E95\\u56FE",fBaseColor:"\\u989C\\u8272",fBaseMaterial:"\\u7D20\\u6750",fBaseScene:"\\u573A\\u666F\\u5185\\u5BB9",fLength:"\\u957F\\u5EA6\\uFF08\\u5E27\\uFF09",fCamera:"\\u955C\\u5934\\u8FD0\\u52A8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002"},po={en:ft,zh:mo},Ue=e=>e?.toLowerCase().startsWith("zh")?"zh":"en",S=(e,t)=>po[e][t],Ut=e=>Object.hasOwn(ft,e),Jt=(e,t)=>t in ft?S(e,t):t;var T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t)=>T(e)&&Array.isArray(e[t])?e[t]:[],ee=e=>he(e.source,"tracks").filter(T),te=e=>he(e.source,"segments").filter(T),ve=(e,t)=>he(e.source,"materials").filter(T).filter(n=>t.includes(String(n.kind))).map(n=>String(n.id)),gt=(e,t)=>e.findIndex(n=>T(n)&&n.id===t),fo=(e,t)=>{let n=e.resolved?.items.find(r=>r.id===t);if(n)return n.cue;let o=t.match(/^(.+)#(\\d+)$/);return o?{track:o[1]??"",index:Number(o[2])}:void 0},q=(e,t)=>{if(!t||!T(e.source))return;let n=he(e.source,"tracks");if(t.kind==="segment"){let i=gt(he(e.source,"segments"),t.id),l=he(e.source,"segments")[i];return T(l)?{kind:"segment",index:i,segment:l}:void 0}if(t.kind!=="item"&&t.kind!=="audio")return;let o=gt(n,t.id),r=n[o];if(T(r)&&r.type!=="caption")return{kind:"track",index:o,track:r};let s=t.kind==="item"?fo(e,t.id):void 0,a=s?gt(n,s.track):-1,d=n[a];return s&&T(d)&&s.index<he(d,"cues").length?{kind:"cue",index:a,cue:s.index,track:d}:void 0},go=e=>e.kind==="segment"?["segments",e.index]:["tracks",e.index],ht=e=>{if(e.kind==="cue")return["tracks",e.index,"cues",e.cue,"during"];if(e.kind==="track"&&T(e.track.during))return["tracks",e.index,"during"]},bt=e=>e.kind!=="segment"&&Array.isArray(e.track.box)?["tracks",e.index,"box"]:void 0,oe=(e,t)=>t.reduce((n,o)=>Array.isArray(n)?n[o]:T(n)?n[String(o)]:void 0,e),Re=(e,t)=>{let n=bt(t),o=n?oe(e.source,n):void 0;return Array.isArray(o)&&o.length===4&&o.every(r=>typeof r=="number")?o:void 0},Wt=(e,t,n)=>{if(n===void 0)return oe(e,t)===void 0?void 0:{op:"remove",path:t};let o=t.length-1;for(;o>0&&!T(oe(e,t.slice(0,o)))&&!Array.isArray(oe(e,t.slice(0,o)));)o--;let r=t.slice(o+1).reduceRight((s,a)=>({[String(a)]:s}),n);return{op:"set",path:t.slice(0,o+1),value:r}},Se=(e,t)=>{if(!T(t)||t.phrase!==void 0||typeof t.segment!="string")return;let n=e.segments.find(s=>s.id===t.segment);if(!n)return;let o=typeof t.from=="number"?t.from:0,r=typeof t.to=="number"?t.to:n.end-n.start;return{start:n.start+o,end:n.start+r,segment:n}},yt=(e,t,n,o)=>{let r=e.segments.find(d=>d.id===t.segment),s=r&&n>=r.start&&n<r.end?r:Z(e,n)??r??e.segments[0],a=s?.start??0;return{...t,segment:s?.id??t.segment,from:n-a,to:o-a}},qt=(e,t,n=!0)=>{let o=e.resolved,r=o?.canvas.fps??30,s=e.referenceMeasure?.measure;return[{frame:t,kind:"playhead"},...n&&o?o.segments.flatMap(a=>[a.start,a.end]).map(a=>({frame:a,kind:"segment"})):[],...s?s.boundaries.map(a=>({frame:Math.round(ye(a.frame,s.source.fps,r)),kind:"reference"})):[]]},ho=4,Pe=(e,t,n)=>{let o=t.map(r=>({t:r,d:Math.abs(r.frame-e)*n})).filter(r=>r.d<=ho).sort((r,s)=>r.d-s.d)[0];return o?o.t:{frame:Math.round(e),kind:"frame"}},re=(e,t)=>{let n=new Set(e.map(r=>String(r.id))),o=t.replace(/-\\d+$/,"");if(!n.has(t))return t;for(let r=2;;r++)if(!n.has(o+"-"+r))return o+"-"+r},Gt=(e,t,n)=>{let o=e.resolved,r=o?Z(o,t)??o.segments[o.segments.length-1]:void 0;if(!o||!r)return;let s=ee(e),a=re(s,"text"),d=Math.max(0,t-r.start),i=Math.max(d+1,Math.min(r.end-r.start,d+2*o.canvas.fps)),l={id:a,type:"text",text:n,box:[.1,.42,.8,.12],during:{segment:r.id,from:d,to:i},style:"subtitle"};return{op:{op:"insert",path:["tracks",s.length],value:l},select:{kind:"item",id:a}}},bo=e=>Array.isArray(e)&&e.length===4?e.map((t,n)=>n<2&&typeof t=="number"?Math.round((t+.03)*1e5)/1e5:t):e,Yt=(e,t)=>{if(t.kind==="segment"){let r=re(te(e),String(t.segment.id));return{op:{op:"insert",path:["segments",t.index+1],value:{...t.segment,id:r}},select:{kind:"segment",id:r}}}if(t.kind==="cue"){let r=he(t.track,"cues")[t.cue],s=e.resolved,a=s&&T(r)?Se(s,r.during):void 0;if(!T(r)||!s||!a||!T(r.during))return;let d=yt(s,r.during,a.end,a.end+(a.end-a.start));return{op:{op:"insert",path:["tracks",t.index,"cues",t.cue+1],value:{...r,during:d}},select:{kind:"item",id:String(t.track.id)+"#"+(t.cue+1)}}}let n=re(ee(e),String(t.track.id)),o={...t.track,id:n,...Array.isArray(t.track.box)?{box:bo(t.track.box)}:{}};return{op:{op:"insert",path:["tracks",t.index+1],value:o},select:{kind:t.track.type==="audio"?"audio":"item",id:n}}},Xt=e=>e.kind==="cue"&&Array.isArray(e.track.cues)&&e.track.cues.length>1?{op:"remove",path:["tracks",e.index,"cues",e.cue]}:{op:"remove",path:go(e)},Zt=e=>e.map(t=>Math.round(t*1e5)/1e5);var Qt=(e,t)=>{if(!T(e.source))return;let n=te(e),o=n[t];if(!o)return;let r=re(n,String(o.id)),s=ee(e).map(i=>structuredClone(i)),a=i=>T(i)&&i.segment===o.id?{...i,segment:r}:i;for(let i of ee(e)){let l=Array.isArray(i.cues)?i.cues.filter(u=>T(u)&&T(u.during)&&u.during.segment===o.id):[];if(!l.length&&(!T(i.during)||i.during.segment!==o.id))continue;let c={...structuredClone(i),id:re(s,String(i.id)),...i.during?{during:a(i.during)}:{},...l.length?{cues:l.map(u=>({...u,during:a(u.during)}))}:{}};s.push(c)}let d=n.map(i=>structuredClone(i));return d.splice(t+1,0,{...structuredClone(o),id:r}),{source:{...e.source,segments:d,tracks:s},id:r}};var yo='"Noto Sans CJK SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif',we={font:yo,size:.045,weight:700,color:"#ffffff",align:"center",italic:!1};var vo={blur:.12,x:.04,y:.06},$t=["headline","subtitle","label","caption"],vt={headline:{...we,size:.065,weight:800,stroke:{color:"#000000",width:.12}},subtitle:{...we,size:.04,weight:700,stroke:{color:"#000000",width:.1}},label:{...we,size:.032,weight:700,color:"#111111",background:{color:"#ffffff",padding:.35,radius:.3}},caption:{...we,size:.036,weight:600,background:{color:"rgba(0, 0, 0, 0.6)",padding:.3,radius:.2}}},St=e=>$t.includes(e),So=(e,t)=>({color:e.color,blur:e.blur??t.blur,x:e.x??t.x,y:e.y??t.y}),en=e=>{if(e===void 0)return we;if(typeof e=="string"){if(!St(e))throw new Error('Unknown text style "'+e+'". Use one of: '+$t.join(", ")+".");return vt[e]}let{shadow:t,...n}=e;return{...we,...n,...t?{shadow:So(t,vo)}:{}}};var tn=(e,t)=>{if(!e?.resolved||t.op!=="set"||t.path[0]!=="tracks"||t.path[2]!=="text"||typeof t.value!="string")return t;let n=T(e.source)?e.source:{},o=Array.isArray(n.tracks)?n.tracks[Number(t.path[1])]:void 0;if(!T(o)||o.type!=="text")return t;let r=e.resolved.items.find(f=>f.id===o.id),a=document.querySelector("#page")?.contentDocument,d=a?.querySelector('[data-item="'+CSS.escape(String(o.id))+'"] > div');if(!a||!d||!r?.style)return t;let i=r.box[2]*e.resolved.canvas.width,l=r.box[3]*e.resolved.canvas.height,c=d.cloneNode(!1);c.textContent=t.value,Object.assign(c.style,{position:"fixed",left:"0",top:"0",width:i+"px",height:"auto",visibility:"hidden",transform:"none"}),a.body.append(c);let u=r.style.size*e.resolved.canvas.height,h=f=>(c.style.fontSize=f+"px",c.style.letterSpacing=(r.style.letterSpacing??0)*f+"px",c.scrollHeight<=l+.5&&c.scrollWidth<=i+.5);try{if(h(u))return t;let f=1,p=u;for(let v=0;v<16;v++){let E=(f+p)/2;h(E)?f=E:p=E}let{font:g,...b}=en(typeof o.style=="string"?o.style:void 0),y=T(o.style)?o.style:b;return{op:"set",path:["tracks",Number(t.path[1])],value:{...o,text:t.value,style:{...y,size:Math.floor(f*100)/100/e.resolved.canvas.height}}}}finally{c.remove()}};var Ae=(e,t,n)=>{let o=e?.resolved,r=t.kind==="item"?o?.items.find(d=>d.id===t.id):t.kind==="audio"?o?.audio.find(d=>d.id===t.id):t.kind==="segment"||t.kind==="slot"?o?.segments.find(d=>d.id===t.id):void 0;if(!r)return n;let s=r.end??o.frames,a="enter"in r?r.enter?.frames??0:0;return n>=r.start+a&&n<s&&t.kind!=="slot"?n:Math.min(s-1,Math.max(r.start+a,r.start+Math.floor((s-r.start)*.3)))};var nn=(e,t)=>{let n=e.resolved,o=te(e),r=n?.segments[t];if(!n||!r||o.length<2||!T(e.source))return;let s=structuredClone(e.source),a=o.filter((f,p)=>p!==t),d=r.end-r.start,i=String(a[0].id),l=f=>f<=r.start?f:f>=r.end?f-d:r.start,c=(f,p)=>({segment:i,from:l(f),to:l(p)}),u=ee(e),h=[];for(let f of u){let p=structuredClone(f);if(p.type==="caption"&&Array.isArray(p.cues)){let k=p.cues.flatMap((H,L)=>{if(!T(H))return[];let R=n.items.find(F=>F.cue?.track===p.id&&F.cue?.index===L);return!R||l(R.end)<=l(R.start)?[]:[{...H,during:c(R.start,R.end)}]});k.length&&h.push({...p,cues:k});continue}let g=p.type==="audio"?n.audio.find(k=>k.id===p.id):n.items.find(k=>k.id===p.id),b=Se(n,p.during),y=g?.start??b?.start??0,v=g?.end??b?.end??n.frames;if(l(v)<=l(y))continue;let E=p.type==="audio"||p.type==="video",M=E&&y<r.start&&v>r.end?[[y,r.start],[r.end,v]]:[[y<r.end&&y>=r.start?r.end:y,v>r.start&&v<=r.end?r.start:v]];for(let[k,H]of M){if(k===void 0||H===void 0||H<=k)continue;let L={...p,during:c(k,H)};if(h.some(R=>R.id===L.id)&&(L.id=re([...u,...h],String(L.id))),E&&k>y){let R=p.type==="video"?n.items.find(O=>O.id===p.id)?.play:void 0,F=R?(n.footage?.[R.material]?.fps??n.canvas.fps)/n.canvas.fps*R.speed:p.bed?(n.footage?.[String(p.material)]?.fps??n.canvas.fps)/n.canvas.fps:1;L.in=Number(p.in??0)+Math.round((k-y)*F)}k>y&&delete L.enter,H<v&&delete L.exit,h.push(L)}}return s.segments=a,s.tracks=h,s};var xt=(e,t,n)=>{let o=q(e,t),r=e.resolved;if(!o||!r||!T(e.source))return;let s=structuredClone(e.source);if(o.kind==="segment"){let g=r.segments[o.index];if(!g||n<=g.start||n>=g.end)return;let b=te(e).map(R=>structuredClone(R)),y=b[o.index],v=n-g.start,E=re(b,String(y.id)),M=T(y.base)?y.base:{},k={...M};M.scene&&(k.offset=Number(M.offset??0)+v/r.canvas.fps),M.material&&g.base.kind==="video"&&(k.in=g.base.play.in+Math.round(v*(r.footage?.[g.base.play.material]?.fps??r.canvas.fps)*g.base.play.speed/r.canvas.fps));let H={...y,id:E,frames:g.end-n,base:k};delete H.in;let L=R=>T(R)&&R.segment===y.id&&R.phrase===void 0&&R.to===void 0?{...R,to:g.end-g.start}:R;return s.tracks=ee(e).map(R=>({...R,...R.during?{during:L(R.during)}:{},...Array.isArray(R.cues)?{cues:R.cues.map(F=>T(F)?{...F,during:L(F.during)}:F)}:{}})),b.splice(o.index,1,{...y,frames:v},H),s.segments=b,{source:s,select:{kind:"segment",id:E}}}let a=structuredClone(o.track),d=o.kind==="cue"&&Array.isArray(a.cues)?a.cues[o.cue]:void 0,i=o.kind==="cue"?d:a;if(!T(i))return;if(!T(i.during)&&a.type==="audio"){let g=r.audio.find(b=>b.id===a.id);g&&(i.during={segment:r.segments[0]?.id,from:g.start,to:g.end??r.frames})}if(!T(i.during))return;let l=Se(r,i.during);if(!l||n<=l.start||n>=l.end)return;let c=i.during,u={...i,during:{...c,to:n-l.segment.start}},h={...i,during:{...c,from:n-l.segment.start}},f=ee(e).map(g=>structuredClone(g));if(o.kind==="cue")return a.cues.splice(o.cue,1,u,h),f[o.index]=a,s.tracks=f,{source:s,select:{kind:"item",id:String(a.id)+"#"+(o.cue+1)}};let p=re(f,String(a.id));if(h.id=p,a.type==="video"){let g=r.items.find(b=>b.id===a.id);g&&(h.in=Number(a.in??0)+Math.round((n-l.start)*Number(r.footage?.[g.play?.material??""]?.fps??r.canvas.fps)*Number(a.speed??1)/r.canvas.fps))}return a.type==="audio"&&(h.in=Number(a.in??0)+Math.round((n-l.start)*(a.bed?(r.footage?.[String(a.material)]?.fps??r.canvas.fps)/r.canvas.fps:1))),delete u.exit,delete h.enter,f.splice(o.index,1,u,h),s.tracks=f,{source:s,select:{kind:a.type==="audio"?"audio":"item",id:p}}};var Et=e=>"popost-preview-selection:"+e.project.dir,Je=e=>{try{let t=sessionStorage.getItem(Et(e));return t?JSON.parse(t):null}catch{return null}},We=e=>{e.subscribe((t,n)=>{if(!(t.pinned===n.pinned||!t.state))try{t.pinned?sessionStorage.setItem(Et(t.state),JSON.stringify(t.pinned)):sessionStorage.removeItem(Et(t.state))}catch{}})},xo=async(e,t)=>{try{return await(await fetch(e,{method:"POST",headers:{"content-type":"application/json"},...t===void 0?{}:{body:JSON.stringify(t)}})).json()}catch(n){return{ok:!1,problems:[{level:"error",at:"(request)",message:n instanceof Error?n.message:String(n),fix:""}]}}},qe=(e,t)=>{let n=f=>e.set({edit:{...e.get().edit,...f}}),o=new Set,r=Promise.resolve(!0),s=!0,a=f=>{f&&["item","slot","audio"].includes(f.kind)&&e.get().timeline&&!e.get().timeline?.layers&&e.set({timeline:{layers:!0,snapping:e.get().timeline?.snapping??!0}}),t.pin(f)},d=(f,p)=>{if(!f.ok){let y=f.problems.find(v=>v.level==="error")??f.problems[0];return n({status:y?{kind:"refused",problem:y}:null,problems:f.problems}),!1}let g=f.state;if(g.generation<(e.get().state?.generation??-1))return!0;if(e.set({state:g,frame:pe(e.get().frame,W(g)),edit:{...e.get().edit,status:{kind:"done",op:f.op,step:f.step,label:f.label},problems:[]}}),p!==void 0)a(p);else{let y=e.get().pinned;y&&y.kind!=="slot"&&!q(g,y)&&a(null)}let b=e.get().pinned;return b&&b.kind!=="slot"&&t.seek(Ae(g,b,e.get().frame)),!0},i=()=>{let f=e.get();return f.state?q(f.state,f.pinned):void 0},l=(f,p,g)=>{n({saving:!0});let b=r.then(()=>xo(f,typeof p=="function"?p():p)).then(y=>(s=d(y,g),s));return r=b.catch(()=>!1),o.add(b),b.finally(()=>{o.delete(b),o.size||n({saving:!1})}),b},c=(f,p)=>l("/api/edit",()=>tn(e.get().state,f),p),u=async()=>{for(;o.size;)await Promise.all([...o])},h=async f=>{if(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),await u(),!s)return;let p=e.get().state,g=i();p&&g&&await f(p,g)};return{send:c,reveal:(f,p)=>{t.pause(),t.seek(p??Ae(e.get().state,f,e.get().frame)),a(f)},flush:async()=>{for(document.activeElement instanceof HTMLElement&&document.activeElement.blur();o.size;)await Promise.all([...o]);return s},canSplit:()=>{let f=e.get();return!!(f.state&&xt(f.state,f.pinned,f.frame))},split:async()=>{let f=e.get(),p=f.state?xt(f.state,f.pinned,f.frame):void 0;p&&await l("/api/source",{source:p.source,base:f.state?.source})&&a(p.select)},replace:(f,p)=>l("/api/source",{source:f,base:p}),undo:async()=>{await u(),await l("/api/undo")},redo:async()=>{await u(),await l("/api/redo")},remove:()=>h(async(f,p)=>{if(p.kind==="segment"){let g=nn(f,p.index);g&&await l("/api/source",{source:g,base:f.source},null);return}await c(Xt(p),null)}),duplicate:()=>h(async(f,p)=>{if(p.kind==="segment"){let b=Qt(f,p.index);b&&await l("/api/source",{source:b.source,base:f.source},{kind:"segment",id:b.id});return}let g=Yt(f,p);g&&await c(g.op,g.select)}),addText:async()=>{let f=e.get(),p=f.state?Gt(f.state,f.frame,S(f.lang,"newText")):void 0;p&&await c(p.op,p.select)},render:async()=>{let p=await(await fetch("/api/render",{method:"POST"}).catch(()=>{}))?.json().catch(()=>{});p?.render?n({render:p.render}):p?.problems?.[0]&&n({status:{kind:"refused",problem:p.problems[0]}})},select:a,note:f=>n({status:{kind:"note",key:f}}),target:i,setRender:f=>n({render:f}),togglePlayRender:()=>n({playRender:!e.get().edit.playRender})}};var Eo={frame:null,playhead:"snapPlayhead",segment:"snapSegment",reference:"snapReference"},wo=(e,t,n,o)=>{let r=Pe(e.start+t,n,o),s=Pe(e.end+t,n,o),a=r.kind==="frame"?1/0:Math.abs(r.frame-(e.start+t)),d=s.kind==="frame"?1/0:Math.abs(s.frame-(e.end+t)),i=a<=d&&a!==1/0?r.frame-e.start:d!==1/0?s.frame-e.end:Math.round(t),l=a<=d&&a!==1/0?r:d!==1/0?s:{frame:e.start+i,kind:"frame"};return{start:e.start+i,end:e.end+i,snap:l}},ko=(e,t,n,o)=>{if(e.mode==="move")return wo(e,t,n,o);if(e.mode==="start"){let s=Pe(e.start+t,n,o);return{start:Math.min(s.frame,e.end-1),end:e.end,snap:s}}let r=Pe(e.end+t,n,o);return{start:e.start,end:Math.max(r.frame,e.start+1),snap:r}},Mo=(e,t,n,o)=>{let r=Eo[o.snap.kind],s=r?" \\xB7 "+S(e,"snapped")+" "+S(e,r):"";if(n.mode==="border"){let a=W(t),d=o.end-n.end;return(t.resolved?.segments.find(l=>l.end===n.end)?.id??"")+": "+(n.end-n.start)+" \\u2192 "+(o.end-n.start)+" "+S(e,"framesWord")+" \\xB7 "+S(e,"videoLength")+" "+a+" \\u2192 "+(a+d)+" ("+(d>=0?"+":"")+d+")"+s}return S(e,"onFrames")+" "+o.start+".."+(o.end-1)+s},To=(e,t,n)=>{let o=t.closest(".lane-track"),r=e.resolved;if(!o||!r)return;let s=t.closest(".seg-grip")?.dataset.border;if(s!==void 0){let p=r.segments[Number(s)];return p?{mode:"border",x0:n,track:o,start:p.start,end:p.end,border:Number(s),moved:!1}:void 0}let a=t.closest("[data-sel]")?.dataset.sel,d=a?JSON.parse(a):void 0;if(d?.kind!=="item"&&d?.kind!=="audio")return;let i=q(e,d),l=i?ht(i):void 0,c=d.kind==="audio"?r.audio.find(p=>p.id===d.id):void 0,u=(i&&l?on(i):void 0)??(c?{segment:r.segments[0]?.id,from:c.start,to:c.end??r.frames}:void 0);if(!i||!u)return;let h=Se(r,u);if(!h)return{mode:"move",x0:n,track:o,start:0,end:0,target:i,phrase:!0,moved:!1};let f=t.closest(".grip")?.dataset.grip;return{mode:f==="start"||f==="end"?f:"move",x0:n,track:o,start:h.start,end:h.end,target:i,span:u,moved:!1}},on=e=>{let t=e.kind==="cue"?e.track.cues[e.cue]:e.kind==="track"?e.track:void 0,n=t&&typeof t=="object"?t.during:void 0;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0},Lo=(e,t,n,o,r)=>{let s=o.state;if(!s||n.phrase)return;let a=W(s);if(!n.track.isConnected){let h=n.track.closest(".lane")?.id,f=h?e.querySelector("#"+CSS.escape(h)+" .lane-track"):null;if(!f)return;n.track=f}let d=n.track.getBoundingClientRect().width/Math.max(1,a);if(!Number.isFinite(d)||d<=0)return;let i=o.timeline?.snapping===!1?[]:qt(s,o.frame,n.mode!=="border"),l=ko(n.mode==="border"?{mode:"end",start:n.start,end:n.end}:n,(r-n.x0)/d,i,d);if(n.mode!=="border")if(n.mode==="move"){let h=Math.min(a,n.end-n.start);l.start=Math.max(0,Math.min(a-h,l.start)),l.end=l.start+h}else l.start=Math.max(0,l.start),l.end=Math.min(a,l.end);n.result=l,n.mode!=="border"&&n.track.append(Le(t.ghost,l.start,l.end,a));let c=e.querySelector(".playhead-layer");if(!c)return;let u=l.snap.kind!=="frame"?l.snap.frame:n.mode==="end"||n.mode==="border"?l.end:l.start;c.append(Q(t.guide,u,a)),t.guide.classList.toggle("snapped",l.snap.kind!=="frame"),t.label.textContent=Mo(o.lang,s,n,l),c.append(Q(t.label,Math.min(u,a*.6),a))},Ro=(e,t)=>{let n=t.resolved;if(!n||!e.result)return;if(e.mode==="border")return e.border!==void 0&&e.result.end!==e.end?{op:"set",path:["segments",e.border,"frames"],value:e.result.end-e.start}:void 0;let o=e.target?ht(e.target)??(e.target.kind==="track"&&e.target.track.type==="audio"?["tracks",e.target.index,"during"]:void 0):void 0,r=e.span??(e.target?on(e.target):void 0);if(!(!o||!r||e.result.start===e.start&&e.result.end===e.end))return{op:"set",path:o,value:yt(n,r,e.result.start,e.result.end)}},Ge=(e,t,n)=>{let o={ghost:m("div",{class:"drag-ghost",id:"drag-ghost"}),guide:m("div",{class:"snap-guide",id:"snap-guide"}),label:m("div",{class:"lane-readout",id:"lane-readout"})},r,s=!1,a;e.addEventListener("pointerdown",i=>{let l=t.get().state;if(i.button!==0||!l?.edit||t.get().edit.saving)return;document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let c=i.target.closest("[data-sel]")?.dataset.sel;c&&n.select(JSON.parse(c));let u=c?JSON.parse(c):void 0;if(u?.kind==="segment"&&!i.target.closest(".seg-grip")){let h=l.resolved?.segments.findIndex(p=>p.id===u.id)??-1,f=i.target.closest(".lane-track");if(h>=0&&f){a={index:h,to:h,x:i.clientX,moved:!1,track:f},e.setPointerCapture(i.pointerId),i.preventDefault();return}}r=To(l,i.target,i.clientX),r&&(e.setPointerCapture(i.pointerId),i.preventDefault())}),e.addEventListener("pointermove",i=>{if(a){if(!a.moved&&Math.abs(i.clientX-a.x)<4)return;a.moved=!0;let l=t.get().state?.resolved;if(!l)return;let c=a.track.getBoundingClientRect(),u=(i.clientX-c.left)/c.width*l.frames;a.to=Math.max(0,l.segments.findIndex(p=>u<p.end)),u>=l.frames&&(a.to=l.segments.length-1);let h=l.segments[a.to]?.start??0,f=e.querySelector(".playhead-layer");o.label.textContent=(t.get().lang==="zh"?"\\u79FB\\u52A8\\u955C\\u5934 ":"Move shot ")+(a.index+1)+" \\u2192 "+(a.to+1),f?.append(Q(o.guide,h,l.frames),Q(o.label,Math.min(h,l.frames*.6),l.frames));return}!r||!r.moved&&Math.abs(i.clientX-r.x0)<3||(r.moved=!0,Lo(e,o,r,t.get(),i.clientX))});let d=i=>{if(a){let h=a;a=void 0,[o.ghost,o.guide,o.label].forEach(f=>f.remove()),h.moved&&(s=!0,setTimeout(()=>{s=!1},0),i.type!=="pointercancel"&&h.index!==h.to&&n.send({op:"move",path:["segments",h.index],to:h.to}));return}let l=r;if(r=void 0,[o.ghost,o.guide,o.label].forEach(h=>h.remove()),!l?.moved)return;s=!0,setTimeout(()=>{s=!1},0);let c=t.get().state;if(l.phrase)return n.note("phraseSpan");let u=c?Ro(l,c):void 0;u&&i.type!=="pointercancel"&&n.send(u)};e.addEventListener("pointerup",d),e.addEventListener("pointercancel",d),e.addEventListener("click",i=>{s&&(s=!1,i.stopImmediatePropagation())},!0)};var Po=e=>e?.anyOf?.find(t=>t.type==="object")??e,j=(e,...t)=>t.reduce((n,o)=>Po(n)?.properties?.[o],e),X=e=>(e?.enum??e?.anyOf?.find(t=>t.enum)?.enum??[]).map(t=>String(t));var Ye=e=>e===void 0||Math.abs(e)>=9e15?void 0:e,xe=e=>({...Ye(e?.minimum??e?.exclusiveMinimum)===void 0?{}:{min:Ye(e?.minimum??e?.exclusiveMinimum)},...Ye(e?.maximum??e?.exclusiveMaximum)===void 0?{}:{max:Ye(e?.maximum??e?.exclusiveMaximum)},integer:e?.type==="integer"}),Xe=async()=>{let e=await fetch("/api/schema",{cache:"no-store"}).catch(()=>{});return e?.ok?await e.json():null};var Ao={noReference:"No reference video is available for this project.",shots:"Shots",media:"Media",script:"Script",elements:"Elements",code:"Code",checks:"Review",versions:"Versions",export:"Export",compare:"Compare",layout:"Layout",theme:"Theme",saved:"Saved locally",readOnly:"Read only",live:"Connected",offline:"Disconnected",preview:"Preview",current:"Current",add:"Add",upload:"Import",search:"Search",scene:"Animated scene",video:"Video",image:"Image",color:"Background",duration:"Duration",keepRhythm:"Keep reference rhythm",content:"Content",properties:"Properties",viewAll:"Fit timeline",assist:"Analysis",zoom:"Zoom",audio:"Project audio",onlyPreview:"Preview controls do not change exported audio",sourceTitle:"Draft JSON",autosave:"Valid JSON saves automatically",format:"Format JSON",download:"Download JSON",invalid:"Invalid JSON \\u2014 draft kept",saving:"Saving\\u2026",conflict:"The draft changed elsewhere. Reload before saving.",reload:"Reload JSON",choose:"Select an item to edit",text:"Text",audioTrack:"Audio",subtitles:"Subtitles",voice:"Voiceover",music:"Music / effects",addText:"Add text",duplicate:"Duplicate",remove:"Delete",undo:"Undo",redo:"Redo",time:"Time",wordBound:"Follows speech",original:"Original",resolution:"Resolution",dynamicRange:"Dynamic range",hdrUnavailable:"HDR is unavailable: this HTML renderer outputs SDR.",fps:"Frame rate",match:"Match timeline",bitrate:"Video bitrate",recommended:"Recommended",filename:"File name",includeAudio:"Include project audio",range:"Range",full:"Full video",start:"Start frame",end:"End frame (exclusive)",paid:"Paid benefit",paidInfo:"This feature is available with a paid plan.",unlock:"Unlock",refreshPlan:"Refresh plan",preparing:"Preparing",rendering:"Rendering",renderDone:"Export ready",stale:"The draft changed after this export",play:"Play",downloadVideo:"Download video",exportSnapshot:"Export uses the JSON snapshot at start. You can continue editing.",general:"General",effects:"Timing and motion",sourceFile:"Source file",missing:"Missing",replace:"Replace",apply:"Apply",applyShot:"Use in selected shot",addOverlay:"Add overlay",slot:"Scene field",noSlots:"This scene exposes no editable slots. Use JSON to change its source or replace the scene.",currentShot:"Current shot",selected:"Selected",noMedia:"No project media",importHint:"Images, video or audio up to 12 MB",scriptHint:"Editing captions does not regenerate voiceover.",pendingVoice:"Caption changed; review voiceover",all:"All",notes:"Notes",comment:"Add timed note",noteHint:"Describe the change at this frame\\u2026",resolved:"Resolved",resolve:"Resolve",reopen:"Reopen",copyNote:"Copy change request",noNotes:"No review notes yet",noProblems:"No structural problems found",unmeasured:"No comparison measurements for this version",saveVersion:"Save version",restore:"Restore",versionName:"Version name",noVersions:"No saved versions",defaultLayout:"Default layout",focusedPreview:"Focus preview",codeHint:"Changes update the same draft after validation. Invalid JSON never overwrites it.",sourceChanged:"Draft saved",quality:"Quality",loading:"Loading\\u2026",sameAsReference:"Reference / replica",toggleAnalysis:"Show analysis lanes",sceneFields:"Scene content",position:"Position",trackGain:"Gain (dB)",chooseMaterial:"Choose a material, then select where to use it.",unsupported:"Unavailable for this selection",refresh:"Refresh",inspect:"Inspect",seconds:"s",waveform:"Waveform",recheck:"Reload checks",sourceExport:"The source JSON is included separately; it is not an MP4.",goShot:"Go to shot",moveUp:"Move earlier",moveDown:"Move later",narrationUnavailable:"Voice generation is managed by the Agent. Copy the revised script to request updated narration.",copyScript:"Copy revised script",applyCaption:"Save caption",error:"Could not complete the operation",fileRange:"Whole timeline",frame:"Frame",newVersion:"Studio version",noSelection:"Select a shot, caption or overlay to edit.",segment:"Shot",previewQuality:"Fit preview",allChanges:"All changes saved",currentExport:"Export current draft",jsonDownload:"Download the saved video.json",imageSlot:"Replace image slot",selectedSlot:"Selected scene field",sceneOffset:"Scene element offset",fontSize:"Font size",textColor:"Text colour",versionSnapshot:"Saved versions preserve the draft JSON; assets are reused.",bitrateUnit:"Mbps",reviewOnly:"Review notes are local; sending to an Agent requires copying the request."},Co={noReference:"\\u6B64\\u9879\\u76EE\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002",shots:"\\u955C\\u5934",media:"\\u7D20\\u6750",script:"\\u6587\\u7A3F",elements:"\\u5143\\u7D20",code:"\\u4EE3\\u7801",checks:"\\u68C0\\u67E5",versions:"\\u7248\\u672C",export:"\\u5BFC\\u51FA",compare:"\\u5BF9\\u7167",layout:"\\u5E03\\u5C40",theme:"\\u4E3B\\u9898",saved:"\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u5DF2\\u65AD\\u5F00",preview:"\\u6210\\u7247\\u9884\\u89C8",current:"\\u5F53\\u524D",add:"\\u6DFB\\u52A0",upload:"\\u5BFC\\u5165\\u7D20\\u6750",search:"\\u641C\\u7D22",scene:"\\u52A8\\u6001\\u573A\\u666F",video:"\\u89C6\\u9891",image:"\\u56FE\\u7247",color:"\\u80CC\\u666F",duration:"\\u65F6\\u957F",keepRhythm:"\\u4FDD\\u6301\\u53C2\\u8003\\u8282\\u594F",content:"\\u5185\\u5BB9",properties:"\\u5C5E\\u6027",viewAll:"\\u9002\\u914D\\u65F6\\u95F4\\u7EBF",assist:"\\u8F85\\u52A9\\u4FE1\\u606F",zoom:"\\u7F29\\u653E",audio:"\\u9879\\u76EE\\u58F0\\u97F3",onlyPreview:"\\u8BD5\\u542C\\u63A7\\u5236\\u4E0D\\u4F1A\\u6539\\u53D8\\u5BFC\\u51FA\\u58F0\\u97F3",sourceTitle:"\\u8349\\u7A3F JSON",autosave:"\\u6709\\u6548 JSON \\u5C06\\u81EA\\u52A8\\u4FDD\\u5B58",format:"\\u683C\\u5F0F\\u5316",download:"\\u4E0B\\u8F7D JSON",invalid:"JSON \\u65E0\\u6548\\uFF0C\\u5DF2\\u4FDD\\u7559\\u8F93\\u5165",saving:"\\u4FDD\\u5B58\\u4E2D\\u2026",conflict:"\\u8349\\u7A3F\\u5DF2\\u5728\\u5176\\u4ED6\\u4F4D\\u7F6E\\u4FEE\\u6539\\uFF0C\\u8BF7\\u5148\\u91CD\\u65B0\\u8F7D\\u5165\\u3002",reload:"\\u91CD\\u65B0\\u8F7D\\u5165 JSON",choose:"\\u9009\\u62E9\\u5BF9\\u8C61\\u540E\\u7F16\\u8F91",text:"\\u6587\\u5B57",audioTrack:"\\u97F3\\u9891",subtitles:"\\u5B57\\u5E55",voice:"\\u914D\\u97F3",music:"\\u97F3\\u4E50 / \\u97F3\\u6548",addText:"\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236",remove:"\\u5220\\u9664",undo:"\\u64A4\\u9500",redo:"\\u91CD\\u505A",time:"\\u65F6\\u95F4",wordBound:"\\u8DDF\\u968F\\u914D\\u97F3",original:"\\u539F\\u59CB",resolution:"\\u5206\\u8FA8\\u7387",dynamicRange:"\\u52A8\\u6001\\u8303\\u56F4",hdrUnavailable:"\\u5F53\\u524D HTML \\u6E32\\u67D3\\u5668\\u8F93\\u51FA SDR\\uFF0C\\u6682\\u4E0D\\u652F\\u6301 HDR\\u3002",fps:"\\u5E27\\u7387",match:"\\u5339\\u914D\\u65F6\\u95F4\\u7EBF",bitrate:"\\u89C6\\u9891\\u7801\\u7387",recommended:"\\u63A8\\u8350",filename:"\\u6587\\u4EF6\\u540D",includeAudio:"\\u5305\\u542B\\u9879\\u76EE\\u58F0\\u97F3",range:"\\u5BFC\\u51FA\\u8303\\u56F4",full:"\\u5B8C\\u6574\\u89C6\\u9891",start:"\\u5F00\\u59CB\\u5E27",end:"\\u7ED3\\u675F\\u5E27\\uFF08\\u4E0D\\u542B\\uFF09",paid:"\\u4ED8\\u8D39\\u6743\\u76CA",paidInfo:"\\u8BE5\\u529F\\u80FD\\u4E3A\\u4ED8\\u8D39\\u6743\\u76CA\\uFF0C\\u4ED8\\u8D39\\u540E\\u53EF\\u4F7F\\u7528\\u3002",unlock:"\\u524D\\u5F80\\u89E3\\u9501",refreshPlan:"\\u5237\\u65B0\\u6743\\u76CA",preparing:"\\u51C6\\u5907\\u4E2D",rendering:"\\u6B63\\u5728\\u5BFC\\u51FA",renderDone:"\\u5BFC\\u51FA\\u5B8C\\u6210",stale:"\\u6B64\\u540E\\u8349\\u7A3F\\u5DF2\\u4FEE\\u6539\\uFF0C\\u9700\\u8981\\u91CD\\u65B0\\u5BFC\\u51FA",play:"\\u64AD\\u653E",downloadVideo:"\\u4E0B\\u8F7D\\u89C6\\u9891",exportSnapshot:"\\u5BFC\\u51FA\\u4F7F\\u7528\\u5F00\\u59CB\\u65F6\\u7684 JSON \\u5FEB\\u7167\\uFF0C\\u4F60\\u53EF\\u4EE5\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002",general:"\\u5E38\\u89C4",effects:"\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548",sourceFile:"\\u6E90\\u6587\\u4EF6",missing:"\\u7F3A\\u5931",replace:"\\u66FF\\u6362",apply:"\\u5E94\\u7528",applyShot:"\\u66FF\\u6362\\u5F53\\u524D\\u955C\\u5934\\u7D20\\u6750",addOverlay:"\\u6DFB\\u52A0\\u4E3A\\u53E0\\u52A0\\u5143\\u7D20",slot:"\\u573A\\u666F\\u5B57\\u6BB5",noSlots:"\\u8BE5\\u573A\\u666F\\u672A\\u516C\\u5F00\\u53EF\\u7F16\\u8F91\\u5B57\\u6BB5\\uFF0C\\u53EF\\u901A\\u8FC7\\u4EE3\\u7801\\u66F4\\u6362\\u573A\\u666F\\u6216\\u4EA4\\u7ED9 Agent \\u4FEE\\u6539\\u3002",currentShot:"\\u5F53\\u524D\\u955C\\u5934",selected:"\\u5DF2\\u9009\\u4E2D",noMedia:"\\u9879\\u76EE\\u6682\\u65E0\\u7D20\\u6750",importHint:"\\u652F\\u6301\\u56FE\\u7247\\u3001\\u89C6\\u9891\\u548C\\u97F3\\u9891\\uFF0C\\u5355\\u6587\\u4EF6\\u4E0D\\u8D85\\u8FC7 12 MB",scriptHint:"\\u4FEE\\u6539\\u5B57\\u5E55\\u4E0D\\u4F1A\\u81EA\\u52A8\\u91CD\\u505A\\u914D\\u97F3\\u3002",pendingVoice:"\\u5B57\\u5E55\\u5DF2\\u4FEE\\u6539\\uFF0C\\u8BF7\\u6838\\u5BF9\\u914D\\u97F3",all:"\\u5168\\u90E8",notes:"\\u4FEE\\u6539\\u610F\\u89C1",comment:"\\u6DFB\\u52A0\\u65F6\\u95F4\\u70B9\\u610F\\u89C1",noteHint:"\\u63CF\\u8FF0\\u5F53\\u524D\\u753B\\u9762\\u9700\\u8981\\u600E\\u6837\\u4FEE\\u6539\\u2026",resolved:"\\u5DF2\\u5904\\u7406",resolve:"\\u6807\\u8BB0\\u5DF2\\u5904\\u7406",reopen:"\\u91CD\\u65B0\\u6253\\u5F00",copyNote:"\\u590D\\u5236\\u7ED9 Agent \\u7684\\u4FEE\\u6539\\u8BF4\\u660E",noNotes:"\\u8FD8\\u6CA1\\u6709\\u4FEE\\u6539\\u610F\\u89C1",noProblems:"\\u672A\\u53D1\\u73B0\\u7ED3\\u6784\\u95EE\\u9898",unmeasured:"\\u5F53\\u524D\\u7248\\u672C\\u6682\\u65E0\\u5BF9\\u6BD4\\u6D4B\\u91CF\\u7ED3\\u679C",saveVersion:"\\u4FDD\\u5B58\\u4E00\\u4E2A\\u7248\\u672C",restore:"\\u6062\\u590D",versionName:"\\u7248\\u672C\\u540D\\u79F0",noVersions:"\\u8FD8\\u6CA1\\u6709\\u4FDD\\u5B58\\u7684\\u7248\\u672C",defaultLayout:"\\u9ED8\\u8BA4\\u5E03\\u5C40",focusedPreview:"\\u4E13\\u6CE8\\u9884\\u89C8",codeHint:"\\u7F16\\u8F91\\u540E\\u81EA\\u52A8\\u6821\\u9A8C\\u5E76\\u66F4\\u65B0\\u540C\\u4E00\\u4EFD\\u8349\\u7A3F\\uFF1B\\u65E0\\u6548 JSON \\u4E0D\\u4F1A\\u8986\\u76D6\\u539F\\u6587\\u4EF6\\u3002",sourceChanged:"\\u8349\\u7A3F\\u5DF2\\u4FDD\\u5B58",quality:"\\u753B\\u8D28",loading:"\\u52A0\\u8F7D\\u4E2D\\u2026",sameAsReference:"\\u53C2\\u8003 / \\u6210\\u7247",toggleAnalysis:"\\u663E\\u793A\\u5206\\u6790\\u8F68\\u9053",sceneFields:"\\u573A\\u666F\\u5185\\u5BB9",position:"\\u4F4D\\u7F6E",trackGain:"\\u589E\\u76CA\\uFF08dB\\uFF09",chooseMaterial:"\\u9009\\u62E9\\u7D20\\u6750\\u540E\\uFF0C\\u6307\\u5B9A\\u66FF\\u6362\\u955C\\u5934\\u6216\\u6DFB\\u52A0\\u53E0\\u52A0\\u5143\\u7D20\\u3002",unsupported:"\\u5F53\\u524D\\u9009\\u62E9\\u4E0D\\u652F\\u6301\\u6B64\\u64CD\\u4F5C",refresh:"\\u5237\\u65B0",inspect:"\\u67E5\\u770B",seconds:"\\u79D2",waveform:"\\u6CE2\\u5F62",recheck:"\\u5237\\u65B0\\u68C0\\u67E5",sourceExport:"JSON \\u5355\\u72EC\\u4E0B\\u8F7D\\uFF0C\\u89C6\\u9891\\u901A\\u8FC7\\u5BFC\\u51FA\\u9762\\u677F\\u751F\\u6210\\u3002",goShot:"\\u5B9A\\u4F4D\\u955C\\u5934",moveUp:"\\u5411\\u524D\\u79FB\\u52A8",moveDown:"\\u5411\\u540E\\u79FB\\u52A8",narrationUnavailable:"\\u914D\\u97F3\\u751F\\u6210\\u7531 Agent \\u5904\\u7406\\uFF0C\\u590D\\u5236\\u4FEE\\u6539\\u6587\\u7A3F\\u540E\\u53EF\\u8BF7\\u6C42\\u66F4\\u65B0\\u58F0\\u97F3\\u3002",copyScript:"\\u590D\\u5236\\u4FEE\\u6539\\u540E\\u7684\\u6587\\u7A3F",applyCaption:"\\u4FDD\\u5B58\\u5B57\\u5E55",error:"\\u64CD\\u4F5C\\u672A\\u5B8C\\u6210",fileRange:"\\u6574\\u6761\\u65F6\\u95F4\\u7EBF",frame:"\\u5E27",newVersion:"Studio \\u7248\\u672C",noSelection:"\\u9009\\u62E9\\u955C\\u5934\\u3001\\u5B57\\u5E55\\u6216\\u53E0\\u52A0\\u5143\\u7D20\\u5373\\u53EF\\u7F16\\u8F91\\u3002",segment:"\\u955C\\u5934",previewQuality:"\\u9002\\u914D\\u9884\\u89C8",allChanges:"\\u6240\\u6709\\u66F4\\u6539\\u5DF2\\u4FDD\\u5B58",currentExport:"\\u5BFC\\u51FA\\u5F53\\u524D\\u8349\\u7A3F",jsonDownload:"\\u4E0B\\u8F7D\\u5DF2\\u4FDD\\u5B58\\u7684 video.json",imageSlot:"\\u66FF\\u6362\\u56FE\\u7247\\u69FD",selectedSlot:"\\u5F53\\u524D\\u573A\\u666F\\u5B57\\u6BB5",sceneOffset:"\\u573A\\u666F\\u5143\\u7D20\\u504F\\u79FB",fontSize:"\\u5B57\\u53F7",textColor:"\\u6587\\u5B57\\u989C\\u8272",versionSnapshot:"\\u7248\\u672C\\u4FDD\\u5B58\\u8349\\u7A3F JSON\\uFF0C\\u5E76\\u7EE7\\u7EED\\u5F15\\u7528\\u539F\\u7D20\\u6750\\u3002",bitrateUnit:"Mbps",reviewOnly:"\\u610F\\u89C1\\u4FDD\\u5B58\\u5728\\u672C\\u673A\\uFF1B\\u590D\\u5236\\u540E\\u53EF\\u4EA4\\u7ED9 Agent \\u7EE7\\u7EED\\u4FEE\\u6539\\u3002"},x=(e,t)=>(e.get().lang==="zh"?Co:Ao)[t];var C=(e,t,n="")=>m("button",{class:"studio-btn "+n,text:e,attrs:{type:"button"},on:{click:t}}),ne=(e,t,n)=>m("button",{class:"studio-btn studio-icon-btn",attrs:{type:"button",title:e,"aria-label":e},on:{click:n}},[Y(t)]),U=(e,t)=>m("div",{class:"studio-heading"},[m("h2",{text:e}),...t?[m("small",{text:t})]:[]]),A=(e,t="")=>m("p",{class:"studio-note "+t,text:e}),Ce=e=>"/project/"+e.replace(/^\\.\\//,"").split("/").map(encodeURIComponent).join("/"),rn=(e,t)=>{let n=URL.createObjectURL(new Blob([e],{type:"application/json"}));m("a",{attrs:{href:n,download:t}}).click(),setTimeout(()=>URL.revokeObjectURL(n),1e3)},ce=(e,t)=>{let n=document.getElementById("studio-message");n?(n.textContent=t,n.classList.add("visible"),setTimeout(()=>n.classList.remove("visible"),6e3)):e.set({pageError:t})},J=async(e,t)=>{let n=await fetch(e,{...t===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)},cache:"no-store"}),o=await n.json();if(!n.ok||o.ok===!1)throw new Error(o.problems?.[0]?.message??"Request failed: "+n.status);return o},ke=async(e,t,n)=>{try{let o=await J(t,n);e.set({state:o.state})}catch(o){ce(e,o instanceof Error?o.message:x(e,"error"))}},G=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>Array.isArray(e)?e.map(G):[],Oe=(e,t,n)=>{let o=m("input",{attrs:{type:"text","aria-label":t},class:"studio-input"});return o.value=e,n&&o.addEventListener("change",()=>n(o.value)),o},wt=(e,t,n,o)=>{let r=m("select",{class:"studio-input",attrs:{"aria-label":n}},e.map(([s,a])=>m("option",{text:a,attrs:{value:s}})));return r.value=t,r.addEventListener("change",()=>o(r.value)),r},Me=(e,t)=>m("label",{class:"studio-field"},[m("span",{text:e}),t]),sn=(e,t)=>m("img",{class:"studio-thumb",attrs:{src:"/api/thumbnail?frame="+Math.floor(e)+"&g="+t,loading:"lazy",alt:""}}),Ze=(e,t)=>{let n=Math.floor(e/t);return[Math.floor(n/60),n%60,e%Math.round(t)].map(o=>Math.floor(o).toString().padStart(2,"0")).join(":")};var be=(e,t,n=t.get().frame)=>{let o=t.get(),r=o.state?.resolved;if(!r)return[];let s=Z(r,n);if(!s)return[];let a=e.contentDocument;if(!a)return[];let d=[];for(let i of Array.from(a.querySelectorAll("iframe"))){let l=i.contentDocument,c=i.contentWindow;if(!l||!c||i.parentElement?.dataset.segment!==s.id)continue;let u=i.getBoundingClientRect();if(!(!u.width||!u.height)&&c.getComputedStyle(i).visibility!=="hidden")for(let h of Array.from(l.querySelectorAll("[data-slot]"))){let f=!0,p=1;for(let y=h;y;y=y.parentElement){let v=c.getComputedStyle(y);p*=Number(v.opacity),(v.display==="none"||v.visibility==="hidden")&&(f=!1)}let g=h.getBoundingClientRect();if(!f||p<.1||!g.width||!g.height||g.right<=0||g.bottom<=0||g.left>=i.clientWidth||g.top>=i.clientHeight)continue;let b=h.dataset.slot;b&&d.push({selection:{kind:"slot",id:s.id,name:b},box:[(u.left+g.left*u.width/(i.clientWidth||r.canvas.width))/r.canvas.width,(u.top+g.top*u.height/(i.clientHeight||r.canvas.height))/r.canvas.height,g.width/r.canvas.width,g.height/r.canvas.height],value:h.tagName==="IMG"?h.getAttribute("src")??"":h.textContent??"",image:h.tagName==="IMG"})}}return d},an=new WeakMap,He=(e,t,n)=>{let o=t.get(),r=o.state?.resolved?.segments.find(u=>u.id===n),s=e?.contentWindow?.__popostVideo;if(!e||!r||!s||document.body.dataset.ready!=="1"||new URL(e.src).searchParams.get("g")!==String(o.state?.generation)||r.base.kind!=="scene")return;let a=e.contentDocument,d=a?.querySelector('[data-segment="'+CSS.escape(n)+'"] > iframe')?.contentDocument;if(!a||!d||d.URL==="about:blank"||d.readyState!=="complete")return;let i=an.get(e);(!i||i.generation!==o.state.generation||i.page!==a)&&(i={generation:o.state.generation,page:a,segments:new Map},an.set(e,i));let l=i.segments.get(n);if(l?.scene===d)return l.frames;let c=new Map;try{for(let u=0;u<=32;u++){let h=Math.min(r.end-1,r.start+Math.floor((r.end-r.start)*u/33));s.applyFrame(h);for(let f of be(e,t,h))c.has(f.selection.name)||c.set(f.selection.name,h)}}finally{s.applyFrame(o.frame)}return i.segments.set(n,{scene:d,frames:c}),c},Qe=(e,t,n)=>e&&be(e,t).some(o=>o.selection.id===n.id&&o.selection.name===n.name)?t.get().frame:He(e,t,n.id)?.get(n.name),dn=(e,t)=>{let n=e.get(),o=n.pinned,r=m("div",{class:"form",id:"slot-inspector"});if(o?.kind!=="slot")return r;let s=n.lang==="zh",a=G(n.state?.source),d=$(a.segments).findIndex(i=>i.id===o.id);return r.append(m("div",{class:"sel-title",text:s?"\\u573A\\u666F\\u5143\\u7D20":"Scene element"})),J("/api/studio").then(i=>{if(!r.isConnected)return;let l=i.slots.find(h=>h.segment===o.id&&h.name===o.name);if(!l)return;let c=l.kind==="image"?Oe(l.value,s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"):m("textarea",{class:"studio-input",attrs:{rows:"5","aria-label":s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content"}});c.value=l.value;let u=h=>{let f=G($(G(e.get().state?.source).segments)[d]?.base);t.send({op:"set",path:["segments",d,"base","slots"],value:{...G(f.slots),[l.name]:h}})};if(c.addEventListener("change",()=>u(c.value)),c.addEventListener("keydown",h=>{let f=h;(f.ctrlKey||f.metaKey)&&f.key==="Enter"&&c.blur()}),l.kind==="image"){let h=G($(a.segments)[d]?.base),f=String(h.scene??""),p=new URL(l.value,location.origin+"/project/"+f);p.origin===location.origin&&p.pathname.startsWith("/project/")&&r.append(m("img",{class:"studio-slot-preview",attrs:{src:p.href,alt:s?"\\u5F53\\u524D\\u56FE\\u7247":"Current image"}}));let g=$(a.materials).filter(b=>b.kind==="image");if(g.length){let b=m("select",{class:"studio-input",attrs:{"aria-label":s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image"}},[m("option",{text:s?"\\u9009\\u62E9\\u7D20\\u6750\\u4E2D\\u7684\\u56FE\\u7247":"Choose an image",attrs:{value:""}}),...g.map((y,v)=>m("option",{text:String(y.note??y.file??(s?"\\u56FE\\u7247 ":"Image ")+(v+1)),attrs:{value:String(y.id)}}))]);b.addEventListener("change",()=>{let y=g.find(v=>v.id===b.value);y&&u("../".repeat(f.split("/").length-1)+String(y.file))}),r.append(Me(s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image",b))}else r.append(A(s?"\\u5148\\u5728\\u7D20\\u6750\\u4E2D\\u5BFC\\u5165\\u56FE\\u7247\\uFF0C\\u518D\\u56DE\\u5230\\u8FD9\\u91CC\\u66FF\\u6362\\u3002":"Import an image in Media, then select it here."));r.append(m("details",{},[m("summary",{text:s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"}),c]))}else r.append(Me(s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content",c));r.append(A(s?"\\u4FEE\\u6539\\u4F1A\\u4FDD\\u5B58\\u5230\\u5F53\\u524D\\u5DE5\\u7A0B\\uFF0C\\u5E76\\u7528\\u4E8E\\u89C6\\u9891\\u5BFC\\u51FA\\u3002":"Changes are saved to this project and used in the exported video."))}).catch(i=>r.append(A(String(i),"bad"))),r};var ln=(e,t,n,o)=>{let r,s=a=>{let d=r;d&&(r=void 0,a&&d.dispatchEvent(new Event("commit")),d.remove())};e.addEventListener("studio:inline-edit",a=>{if(r)return;let d=n.get(),i=d.pinned;if(!i||!d.state||a.target.closest(".handle"))return;let l=q(d.state,i),c=i.kind==="item"?d.state.resolved?.items.find(g=>g.id===i.id):void 0,u=i.kind==="slot"?be(t,n).find(g=>g.selection.id===i.id&&g.selection.name===i.name):void 0;if(u?.image||l?.kind==="track"&&l.track.type==="image"){document.querySelector('#slot-inspector select, #edit-form select[data-path$=".material"]')?.focus();return}let h=u?.value??c?.text,f=u?.box??(l?Re(d.state,l):void 0);if(h===void 0||!f)return;s(!0),a.preventDefault(),a.stopPropagation();let p=m("textarea",{id:"stage-text-editor",class:"stage-text-editor",attrs:{"aria-label":d.lang==="zh"?"\\u76F4\\u63A5\\u7F16\\u8F91\\u6587\\u5B57":"Edit text on canvas"}});p.value=h,le(p,f),p.style.fontSize=Math.max(14,(c?.style?.size??.04)*(d.state.resolved?.canvas.height??1)*e.clientWidth/(d.state.resolved?.canvas.width??1))+"px",p.addEventListener("commit",()=>{if(!(p.value===h||!p.value.trim()))if(i.kind==="slot"){let g=n.get().state,b=$(G(g?.source).segments).findIndex(v=>v.id===i.id),y=G($(G(g?.source).segments)[b]?.base);o.send({op:"set",path:["segments",b,"base","slots"],value:{...G(y.slots),[i.name]:p.value}})}else l?.kind==="cue"?o.send({op:"set",path:["tracks",l.index,"cues",l.cue,"text"],value:p.value}):l?.kind==="track"&&o.send({op:"set",path:["tracks",l.index,"text"],value:p.value})}),p.addEventListener("blur",()=>s(!0)),p.addEventListener("pointerdown",g=>g.stopPropagation()),p.addEventListener("keydown",g=>{g.key==="Escape"?(g.preventDefault(),g.stopPropagation(),s(!1)):g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),s(!0))}),e.append(p),r=p,p.focus(),p.select()}),n.subscribe((a,d)=>{(a.pinned!==d.pinned||a.state!==d.state||a.frame!==d.frame)&&s(!1)})};var Oo=["nw","n","ne","e","se","s","sw","w"],Ho=(e,t)=>{if(t.kind==="segment")return[];let n=String(t.track.id);return(e.state?.resolved?.items??[]).filter(o=>o.id===n||o.cue?.track===n).map(o=>o.id)},No=(e,t)=>{let n=e.state?.resolved;if(!n||t.kind==="segment")return!1;let o=t.kind==="cue"?String(t.track.id)+"#"+t.cue:String(t.track.id);return fe(n,e.frame).some(r=>r.id===o)},Io=(e,t,n,o,r,s)=>{let[a,d,i,l]=e.box0,c=(E,M)=>Math.round(E*M)/M;if(e.mode==="move")return[c(a+t,o),c(d+n,r),i,l];let[u,h,f,p]=[a,d,a+i,d+l];if(e.mode.includes("w")&&(u+=t),e.mode.includes("e")&&(f+=t),e.mode.includes("n")&&(h+=n),e.mode.includes("s")&&(p+=n),s){let E=i*o/(l*r),M=f-u,k=p-h;if(e.mode.length===1?e.mode==="e"||e.mode==="w":Math.abs(M/i-1)>=Math.abs(k/l-1)){let L=M*o/E/r;e.mode.includes("n")?h=p-L:(e.mode.includes("s")||(h=d+l/2-L/2),p=h+L)}else{let L=k*r*E/o;e.mode.includes("w")?u=f-L:(e.mode.includes("e")||(u=a+i/2-L/2),f=u+L)}}let[g,b,y,v]=[c(u,o),c(h,r),c(f,o),c(p,r)];return[Math.min(g,y-1/o),Math.min(b,v-1/r),Math.max(1/o,y-g),Math.max(1/r,v-b)]},Fo=(e,t,n)=>{let o=(s,a)=>String(Math.round(s*a)),r=s=>s.toFixed(3);return"x "+o(e[0],t)+" y "+o(e[1],n)+" "+o(e[2],t)+"\\xD7"+o(e[3],n)+" px ("+[e[0],e[1],e[2],e[3]].map(r).join(", ")+")"},Do=(e,t)=>{let n=new Map;return{move:(o,r)=>{let s=e.contentDocument,{W:a,H:d}=$e(t.get());for(let i of Ho(t.get(),o)){let l=s?.querySelector('[data-item="'+CSS.escape(i)+'"]');l&&(n.has(l)||n.set(l,l.style.cssText),Object.assign(l.style,{left:r[0]*a+"px",top:r[1]*d+"px",width:r[2]*a+"px",height:r[3]*d+"px"}))}},restore:()=>{n.forEach((o,r)=>{r.style.cssText=o}),n=new Map},forget:()=>{n=new Map}}},$e=e=>({W:e.state?.resolved?.canvas.width??1,H:e.state?.resolved?.canvas.height??1}),jo=(e,t,n,o)=>{let r=t.state?.resolved;if(!r)return;let s=e.getBoundingClientRect(),a=(n-s.left)/s.width,d=(o-s.top)/s.height;return[...fe(r,t.frame)].reverse().find(i=>a>=i.box[0]&&a<=i.box[0]+i.box[2]&&d>=i.box[1]&&d<=i.box[1]+i.box[3])?.id},zo=(e,t,n)=>{let o=t.state?q(t.state,t.pinned):void 0,r=n??(o&&t.state?Re(t.state,o):void 0),s=!!(r&&o&&(n||No(t,o)));if(e.layer.classList.toggle("off",!t.state?.resolved),e.sel.hidden=!s,e.readout.hidden=!n,s&&r&&(le(e.sel,r),e.sel.classList.toggle("thin",e.sel.getBoundingClientRect().height<18)),n){let{W:a,H:d}=$e(t);e.readout.textContent=Fo(n,a,d)}},cn=e=>{let t=e.state?q(e.state,e.pinned):void 0,n=t&&e.state?Re(e.state,t):void 0;return t&&n?{t,box:n}:void 0},et=(e,t,n,o)=>{let r=m("div",{class:"sel-box",id:"sel-box"},Oo.map(v=>m("div",{class:"handle h-"+v,data:{h:v}}))),s=m("div",{class:"drag-readout",id:"drag-readout"}),a=m("div",{class:"studio-slot-outline",attrs:{hidden:""}},[m("span",{class:"studio-slot-name"})]),d={layer:m("div",{class:"edit-layer",id:"edit-layer"},[r,s]),sel:r,readout:s};d.layer.append(a),e.append(d.layer),ln(e,t,n,o);let i=Do(t,n),l,c,u,h,f=!0,p=()=>{let v=n.get();zo(d,v,l&&!l.moved?void 0:u?.box);let E=v.pinned,M=E?.kind==="slot"?be(t,n).find(k=>k.selection.id===E.id&&k.selection.name===E.name):void 0;if(E?.kind==="slot"&&f&&document.body.dataset.ready==="1"){f=!1;let k=Qe(t,n,E);if(k===void 0){o.select(null);return}if(k!==v.frame){o.reveal(E,k);return}}a.hidden=!M,M&&(le(a,M.box),a.firstElementChild.textContent=M.image?v.lang==="zh"?"\\u56FE\\u7247":"Image":M.value.slice(0,40))},g=(v,E)=>{let M=bt(v);M&&o.send({op:"set",path:M,value:Zt(E)}).then(k=>{k||i.restore(),u=void 0,p()})},b=(v,E)=>{u={box:E,target:v},i.move(v,E),p()};d.layer.addEventListener("pointerdown",v=>{if(v.button!==0||!n.get().state?.resolved||n.get().edit.saving||v.target.closest("#stage-text-editor"))return;let E=n.get().pinned;if((E?.kind==="slot"?be(t,n).some(L=>L.selection.id===E.id&&L.selection.name===E.name&&!L.image):E?.kind==="item"&&n.get().state?.resolved?.items.some(L=>L.id===E.id&&L.type==="text"))&&c&&performance.now()-c.time<450&&Math.hypot(v.clientX-c.x,v.clientY-c.y)<6&&!v.target.closest(".handle")){c=void 0,e.dispatchEvent(new Event("studio:inline-edit")),v.preventDefault();return}document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let k=v.target.closest(".handle")?.dataset.h;if(!k&&!v.target.closest(".sel-box")){let L=jo(e,n.get(),v.clientX,v.clientY);if(!L){let R=e.getBoundingClientRect(),F=(v.clientX-R.left)/R.width,O=(v.clientY-R.top)/R.height,D=be(t,n).reverse().find(w=>F>=w.box[0]&&F<=w.box[0]+w.box[2]&&O>=w.box[1]&&O<=w.box[1]+w.box[3]);if(D){o.select(D.selection),c={time:performance.now(),x:v.clientX,y:v.clientY},v.preventDefault();return}}if(o.select(L?{kind:"item",id:L}:null),!L)return}let H=cn(n.get());H&&(l={mode:k??"move",x0:v.clientX,y0:v.clientY,box0:u?.box??H.box,moved:!1,target:H.t},d.layer.setPointerCapture(v.pointerId),v.preventDefault())}),d.layer.addEventListener("pointermove",v=>{if(!l||!l.moved&&Math.hypot(v.clientX-l.x0,v.clientY-l.y0)<2)return;l.moved=!0;let E=e.getBoundingClientRect(),{W:M,H:k}=$e(n.get());b(l.target,Io(l,(v.clientX-l.x0)/E.width,(v.clientY-l.y0)/E.height,M,k,v.shiftKey))});let y=v=>{if(v.type==="pointercancel"){l=void 0,u=void 0,c=void 0,i.restore(),p();return}let E=l;l=void 0,E&&!E.moved&&(c={time:performance.now(),x:E.x0,y:E.y0}),E?.moved&&u&&(c=void 0,g(E.target,u.box)),p()};return d.layer.addEventListener("pointerup",y),d.layer.addEventListener("pointercancel",y),n.subscribe((v,E)=>{v.state!==E.state&&i.forget(),(v.pinned!==E.pinned||v.state!==E.state)&&(f=!0),!l&&(v.state!==E.state||v.pinned!==E.pinned||v.frame!==E.frame)&&p()}),t.addEventListener("frameapplied",p),new ResizeObserver(p).observe(e),p(),{nudge:(v,E)=>{let M=cn(n.get()),k=u?.box??M?.box;if(!M||!k||l)return!1;let{W:H,H:L}=$e(n.get()),R=[Math.round(k[0]*H+v)/H,Math.round(k[1]*L+E)/L,k[2],k[3]];return b(M.t,R),h&&clearTimeout(h),h=setTimeout(()=>g(M.t,R),400),!0}}};var tt=(e,t,n)=>{let r=[{id:"edit-undo",icon:"undo",title:"undo",run:()=>{n.undo()},enabled:d=>(d.state?.edit?.undo??0)>0},{id:"edit-redo",icon:"redo",title:"redo",run:()=>{n.redo()},enabled:d=>(d.state?.edit?.redo??0)>0},{id:"edit-add-text",icon:"addText",title:"addText",run:()=>{n.addText()},enabled:d=>!!d.state?.resolved},{id:"edit-duplicate",icon:"duplicate",title:"duplicate",run:()=>{n.duplicate()},enabled:()=>n.target()!==void 0},{id:"edit-delete",icon:"remove",title:"remove",run:()=>{n.remove()},enabled:d=>{let i=n.target();return!!(i&&(i.kind!=="segment"||(d.state?.resolved?.segments.length??0)>1))}},{id:"edit-render",icon:"render",title:"renderTool",run:()=>{n.render()},enabled:d=>!!d.state?.resolved&&d.edit.render?.state!=="running"}].map(d=>{let i=m("button",{id:d.id,class:"tbtn",attrs:{type:"button"}},[Y(d.icon)]);return["edit-add-text","edit-duplicate","edit-delete"].includes(d.id)&&i.append(m("span",{class:"tool-label"})),i.addEventListener("click",()=>{d.run(),i.blur()}),{tool:d,el:i}}),s=(d,i)=>m("span",{class:"tool-group"},r.slice(d,i).map(l=>l.el));e.append(m("span",{class:"edit-tools",id:"edit-tools"},[s(0,2),s(2,5),s(5,6)]));let a=d=>{for(let i of r){i.el.title=S(d.lang,i.tool.title);let l=i.el.querySelector(".tool-label");l&&(l.textContent=i.tool.id==="edit-add-text"?d.lang==="zh"?"\\u6587\\u5B57":"Text":i.tool.id==="edit-duplicate"?d.lang==="zh"?"\\u590D\\u5236":"Duplicate":d.lang==="zh"?"\\u5220\\u9664":"Delete"),i.el.setAttribute("aria-label",S(d.lang,i.tool.title)),i.el.disabled=!!d.edit.saving||!i.tool.enabled(d)}};a(t.get()),t.subscribe((d,i)=>{(d.state!==i.state||d.lang!==i.lang||d.pinned!==i.pinned||d.edit.render!==i.edit.render||d.edit.saving!==i.edit.saving)&&a(d)})},Bo={set:"saved",insert:"added",remove:"removed",move:"moved",outside:"outside"},Vo=e=>{let t=e.edit.status,n=e.lang;if(!t)return"";if(t.kind==="note")return S(n,t.key==="phraseSpan"?"phraseSpan":"offlineEdit");if(t.kind==="refused")return S(n,"notSaved")+": "+(t.problem.at.startsWith("(")?"":t.problem.at+": ")+t.problem.message+(t.problem.fix?" "+S(n,"fix")+": "+t.problem.fix:"");let o=t.step==="outside"?S(n,"outside"):t.label;return t.op==="undo"||t.op==="redo"?S(n,t.op==="undo"?"undone":"redone")+": "+o:S(n,Bo[t.op]??"saved")+": "+o},_o=(e,t,n)=>{let o=e.edit.render;if(!o||o.state==="idle")return[];if(o.state==="running")return[m("span",{text:S(n,"rendering")+": "+o.frame+" / "+(o.total||"?")})];if(o.state==="failed")return[m("span",{class:"bad",text:S(n,"renderFailed")+": "+o.message})];let r=m("button",{id:"play-render",class:"link",text:S(n,e.edit.playRender?"showReference":"playRender"),attrs:{type:"button"}});return r.addEventListener("click",()=>t.togglePlayRender()),[m("span",{text:S(n,"rendered")+": "+o.frames+" "+S(n,"framesIn")+" "+o.seconds+" s, ",title:o.file}),m("code",{text:o.file.split(/[\\\\/]/).pop()??o.file,title:o.file})," ",r]},nt=(e,t,n)=>{let o=m("div",{id:"edit-status",class:"status-line",attrs:{role:"status","aria-live":"polite"}}),r=m("div",{id:"render-status",class:"status-line render"});e.prepend(m("div",{class:"edit-status"},[o,r]));let s=a=>{o.textContent=Vo(a),o.classList.toggle("bad",a.edit.status?.kind==="refused"),r.replaceChildren(..._o(a,n,a.lang))};s(t.get()),t.subscribe((a,d)=>{(a.edit!==d.edit||a.lang!==d.lang)&&s(a)})},Ko=e=>e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLInputElement&&!["checkbox","range","button","color"].includes(e.type)||e instanceof HTMLElement&&e.isContentEditable,ot=(e,t,n)=>{document.addEventListener("keydown",o=>{if(document.querySelector('[role="dialog"]'))return;if(Ko(o.target)){if(o.target.id==="stage-text-editor")return;o.key==="Escape"&&o.target.blur();return}let r=o.ctrlKey||o.metaKey,s=o.key.toLowerCase(),a=c=>{o.preventDefault(),o.stopPropagation(),c()};if(r&&s==="z")return a(()=>{o.shiftKey?t.redo():t.undo()});if(r&&s==="y")return a(()=>{t.redo()});if(r&&s==="d")return a(()=>{t.duplicate()});if(r||o.altKey)return;if(s==="s")return a(()=>{t.split()});if(o.key==="Delete"||o.key==="Backspace")return a(()=>{t.remove()});if(o.key==="Escape")return a(()=>t.select(null));let i={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[o.key];if(!i||!e.get().pinned)return;let l=o.shiftKey?10:1;n(i[0]*l,i[1]*l)&&a(()=>{})},!0)};var un=(e,t,n)=>e.reduce((o,[r,s])=>Math.max(o,Math.min(1,Math.max(0,(n-(r-t))/t),Math.max(0,(s+t-n)/t))),0),mn=e=>Math.min(1,Math.max(0,e)),Uo=(e,t)=>{if(!e)return 0;let{out:n,in:o}=e;return e.spans.reduce((r,[s,a])=>Math.max(r,Math.min(mn((t-(s-n))/n),mn((a+o-t)/o))),0)},Jo=(e,t)=>{let n=Uo(e,t);return n<=0?0:n>=1?120:Math.min(120,-20*Math.log10(1-n))},pn=(e,t)=>e?e.db*un(e.spans,e.ramp,t)+(e.away?e.away.db*un(e.away.spans,e.away.ramp,t):0)+(e.gaps?Jo(e.gaps,t):0):0;var gn=e=>{let t=[],n,o=()=>{for(let s of t)s.audio.pause(),s.audio.removeAttribute("src"),s.gain.disconnect();t=[]},r=()=>{let s=e.get(),a=s.state?.resolved;if(!a)return;let d=a.audio;(d.length!==t.length||t.some((l,c)=>l.source!==d[c]?.src))&&(o(),n??=new AudioContext,t=d.map(l=>{let c=new Audio;c.crossOrigin="anonymous",c.preload="auto",c.src=Ce(l.src);let u=n.createGain();return n.createMediaElementSource(c).connect(u).connect(n.destination),{audio:c,gain:u,source:l.src}})),s.playing&&n?.state==="suspended"&&n.resume().catch(()=>{});let i=s.frame/a.canvas.fps;t.forEach((l,c)=>{let u=d[c];if(!u)return;l.gain.gain.value=s.muted?0:10**((u.gain-pn(u.duck,s.frame))/20);let h=s.frame>=u.start&&(u.end===void 0||s.frame<u.end),f=Math.max(0,(i-u.start/a.canvas.fps)*(u.speed??1)+(u.from?u.from.frame/u.from.fps:0));l.audio.playbackRate=s.speed*(u.speed??1),h&&!l.audio.seeking&&Math.abs(l.audio.currentTime-f)>.2&&(l.audio.currentTime=f),s.playing&&h&&!s.muted?l.audio.paused&&l.audio.play().catch(()=>{}):l.audio.pause()})};e.subscribe((s,a)=>{(s.state!==a.state||s.frame!==a.frame||s.playing!==a.playing||s.muted!==a.muted||s.speed!==a.speed)&&r()}),window.addEventListener("pagehide",()=>{o(),n?.close()})},fn=new Map,hn=e=>{let t=fn.get(e);if(t)return t;let n=(async()=>{let o=new AudioContext;try{let r=await fetch(Ce(e)),a=(await o.decodeAudioData(await r.arrayBuffer())).getChannelData(0),d=[];for(let i=0;i<500;i++){let l=Math.floor(i*a.length/500),c=Math.floor((i+1)*a.length/500),u=0;for(let h=l;h<c;h+=8)u=Math.max(u,Math.abs(a[h]??0));d.push(u)}return d}finally{await o.close()}})();return fn.set(e,n),n};var En=" \\xB7 ",Ne=e=>({sel:JSON.stringify(e)}),ue=(e,t,n,o={})=>m("div",{class:"lane "+(o.cls??""),id:"lane-"+e,...o.height?{style:"height:"+o.height+"px"}:{}},[m("div",{class:"lane-label",text:t,title:t,...o.labelSel?{data:Ne(o.labelSel)}:{}}),m("div",{class:"lane-track"},n)]),ae=(e,t,n,o,r,s,a)=>Le(m("div",{class:e,text:r,title:s,...a?{data:Ne(a)}:{}}),t,n,o),Wo=(e,t,n)=>ue("ruler",S(n,"ruler"),jt(e,t).map(o=>Q(m("div",{class:"rtick",text:o.label,title:"frame "+o.frame}),o.frame,e)),{cls:"ruler"}),qo=e=>e.segments.map(t=>Q(m("div",{class:"seg-grip",title:t.id+": "+(t.end-t.start)+" frames",data:{border:String(t.index)}}),t.end,e.frames)),bn=(e,t,n,o)=>{let r=e.frames,s=e.segments.flatMap(a=>{let d=a.base.kind==="color"?a.base.color:void 0,i=ae("blk seg",a.start,a.end,r,a.id,a.id+": frames "+a.start+".."+(a.end-1),{kind:"segment",id:a.id});i.textContent="",i.setAttribute("role","button"),i.tabIndex=0,i.setAttribute("aria-label",(t==="zh"?"\\u955C\\u5934 ":"Shot ")+(a.index+1)+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"),i.dataset.index=String(a.index),i.append(m("img",{attrs:{loading:"lazy",alt:"",src:"/api/thumbnail?frame="+Math.floor((a.start+a.end)/2)+"&g="+o}}),m("span",{class:"segment-name",text:String(a.index+1).padStart(2,"0")+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"})),d&&i.prepend(m("span",{class:"swatch",style:"background:"+d}));let l=a.transition;if(!l)return a.index===0?[i]:[i,Q(m("div",{class:"tick"}),a.start,r)];let c=Nt(l),u=ae("band",l.a,l.a+l.frames,r,"",c+": mixed frames "+l.a+".."+(l.a+l.frames-1)+", takes over at "+l.boundary,{kind:"segment",id:a.id});return u.append(m("span",{class:"band-label",text:c})),[i,u,Q(m("div",{class:"tick"}),a.start,r)]});return ue("segments",S(t,"segments"),n?[...s,...qo(e)]:s,{cls:"segments"})},yn=(e,t,n)=>{let o={kind:"item",id:e.id},r=[ae("blk item",e.start,e.end,t,"",e.id+" ("+e.type+"): frames "+e.start+".."+(e.end-1),o)];if(e.enter.frames>0&&r.push(ae("shade enter",e.start,e.start+e.enter.frames,t,Te(e.enter),"enter: "+Te(e.enter)+", "+e.enter.ease,o)),e.exit.frames>0&&r.push(ae("shade exit",e.end-e.exit.frames,e.end,t,Te(e.exit),"exit: "+Te(e.exit)+", "+e.exit.ease,o)),n)for(let[s,a]of[["start",e.start],["end",e.end]])r.push(Q(m("div",{class:"grip "+s,data:{grip:s,...Ne(o)}}),a,t));return ue("item-"+e.id,e.id+En+e.type,r,{labelSel:o})},vn=(e,t,n,o=!1)=>{let r={kind:"audio",id:e.id},s=n==="zh"?"\\u97F3\\u9891":"Audio",a=ae("blk audio",e.start,e.end??t,t,s,s,r);a.setAttribute("role","button"),a.tabIndex=0,a.setAttribute("aria-label",s),hn(e.src).then(i=>{let l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("viewBox","0 0 500 28"),l.setAttribute("preserveAspectRatio","none");let c=document.createElementNS(l.namespaceURI,"path");c.setAttribute("d",i.map((u,h)=>"M"+h+" "+(14-Math.max(1,u*13))+"v"+Math.max(2,u*26)).join("")),c.setAttribute("stroke","#69967c"),c.setAttribute("stroke-width","0.8"),l.append(c),a.append(l),a.classList.add("wave-ready")}).catch(()=>{});let d=["start","end"].map(i=>Q(m("div",{class:"grip "+i,data:{grip:i,...Ne(r)}}),i==="start"?e.start:e.end??t,t));return ue("audio-"+e.id,S(n,"audio"),[a,...o?d:[]],{labelSel:r})},Go=(e,t,n)=>ue("words-"+e.track,S(n,"words")+": "+e.track,e.tokens.map(o=>ae("blk audio word"+(o.confidence<.4?" unsure":""),o.start,o.end,t,o.text,o.text+": frames "+o.start+".."+(o.end-1)+En+"confidence "+o.confidence)),{cls:"words-lane"}),Yo=(e,t,n,o,r)=>{let s=e.measure,a=i=>ye(i,s.source.fps,o),d=s.boundaries.flatMap((i,l)=>{let c={kind:"boundary",source:t,index:l},u=It(i),h=u+": frames "+i.start+".."+i.end+" of the measured file, takes over at "+i.frame,f=Q(m("div",{class:"mark",title:h,data:Ne(c)},[m("span",{class:"mark-label",text:u})]),a(i.frame),n);return i.kind==="cut"?[f]:[ae("mband",a(i.start+1),a(i.end),n,"",h,c),f]});return ue(t+"-boundaries",S(r,t==="render"?"renderBoundaries":"referenceBoundaries"),d,{cls:"measure "+t})},Sn=14,Xo=4,Zo=(e,t,n,o,r)=>{let s=e.measure,a=Ft(s).map(c=>({start:ye(c.event.start,s.source.fps,o),end:ye(c.event.end,s.source.fps,o),value:c})),d=mt(a,Xo),i=d.map(c=>{let u=ze(c.value.event),h=ae("ev",c.start,c.end,n,u,u+": frames "+c.value.event.start+".."+(c.value.event.end-1)+" of the measured file",{kind:"event",source:t,shot:c.value.shot,index:c.value.index});return h.style.top=3+c.row*Sn+"px",h}),l=Math.max(1,...d.map(c=>c.row+1));return ue(t+"-events",S(r,t==="render"?"renderEvents":"referenceEvents"),i,{cls:"measure "+t,height:6+l*Sn})},Qo=(e,t,n)=>{let o=W(e),r=se(e),s=e.resolved,a=e.edit!==void 0,d=[Wo(o,r,t)];if(s)if(a){let i=bn(s,t,a,e.generation);i.querySelector(".lane-label").textContent=t==="zh"?"\\u955C\\u5934":"Shots",d.push(i);let l=[{id:"subtitles",label:t==="zh"?"\\u5B57\\u5E55":"Subtitles",items:s.items.filter(c=>c.cue),cls:"caption-lane"},{id:"text",label:t==="zh"?"\\u6587\\u5B57":"Text",items:s.items.filter(c=>!c.cue&&c.type==="text"),cls:"caption-lane"},{id:"media",label:t==="zh"?"\\u7D20\\u6750":"Media",items:s.items.filter(c=>!c.cue&&c.type!=="text"),cls:"media-lane"}];for(let c of n.timeline?.layers===!1?[]:l){let u=mt(c.items.map(f=>({start:f.start,end:f.end,value:f})).sort((f,p)=>f.start-p.start||p.value.z-f.value.z||f.value.id.localeCompare(p.value.id)),Math.max(1,c.items.length)),h=Math.max(0,...u.map(f=>f.row+1));for(let f=0;f<h;f++){let p=u.filter(g=>g.row===f).flatMap(({value:g})=>{let b=Array.from(yn(g,o,a).querySelector(".lane-track").children),y=b[0];if(y){let v=g.text??(t==="zh"?g.type==="video"?"\\u89C6\\u9891":g.type==="image"?"\\u56FE\\u7247":"\\u5F62\\u72B6":g.type);y.textContent=v,y.title=v,y.setAttribute("role","button"),y.setAttribute("tabindex","0"),y.setAttribute("aria-label",v)}return b});d.push(ue(c.id+"-"+f,c.label+(f?" "+(f+1):""),p,{cls:c.cls}))}}if(n.timeline?.layers!==!1)for(let c of n.slots??[]){let u=s.segments.find(g=>g.id===c.segment);if(!u)continue;let h={kind:"slot",id:c.segment,name:c.name},f=c.kind==="image"?t==="zh"?"\\u56FE\\u7247":"Image":c.value,p=ae("blk item scene-field",u.start,u.end,o,f,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A\\u65F6\\u95F4\\u7531\\u573A\\u666F\\u63A7\\u5236\\uFF0C\\u70B9\\u9009\\u540E\\u7F16\\u8F91\\u5185\\u5BB9":"Scene content: timing follows scene; select to edit",h);p.setAttribute("role","button"),p.tabIndex=0,p.setAttribute("aria-label",(t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A":"Scene field: ")+f),d.push(ue("slot-"+c.segment+"-"+c.name,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9":"Scene content",[p],{cls:"caption-lane"}))}d.push(...s.audio.map(c=>vn(c,o,t,!0)))}else d.push(bn(s,t,a,e.generation),...s.items.map(i=>yn(i,o,a)),...s.audio.map(i=>vn(i,o,t)),...(s.words??[]).map(i=>Go(i,o,t)));for(let[i,l]of[[e.measure,"render"],[e.referenceMeasure,"reference"]])i&&!a&&d.push(Yo(i,l,o,r,t),Zo(i,l,o,r,t));return d},xn=(e,t,n)=>{let o=e.getBoundingClientRect();return Math.floor((t-o.left)/Math.max(1,o.width)*n)},rt=(e,t,n)=>{let o=m("div",{class:"lanes",id:"lanes"}),r=m("div",{class:"playhead",id:"playhead"}),s=m("div",{class:"playhead-layer"},[r]);e.append(o);let a=c=>c.state?W(c.state):0,d=c=>{Le(r,c.frame,c.frame+1,a(c))},i=c=>{o.querySelectorAll("[data-sel]").forEach(u=>{u.setAttribute("aria-pressed",String(c.pinned!==null&&ge(JSON.parse(u.dataset.sel??"null"),c.pinned))),u.classList.toggle("selected",c.pinned!==null&&ge(JSON.parse(u.dataset.sel??"null"),c.pinned))})},l=c=>{o.replaceChildren(...c.state?Qo(c.state,c.lang,c):[],s),d(c),i(c)};o.addEventListener("click",c=>{let u=c.target,h=u.closest("[data-sel]")?.dataset.sel;if(h){let f=JSON.parse(h);n.pause();let p=t.get();p.timeline&&["item","slot","audio"].includes(f.kind)&&!p.timeline.layers&&t.set({timeline:{...p.timeline,layers:!0}}),n.pin(f);let g=u.closest(".lane-track");if(p.state?.edit)n.seek(Ae(t.get().state,f,t.get().frame));else if(g&&c.detail!==0)n.seek(xn(g,c.clientX,a(p)));else{let b=f.kind==="segment"?p.state?.resolved?.segments.find(y=>y.id===f.id):f.kind==="item"?p.state?.resolved?.items.find(y=>y.id===f.id):void 0;b&&(p.frame<b.start||p.frame>=b.end)&&n.seek(b.start)}}else{let f=u.closest(".lane-track");f&&(n.pin(null),c.detail!==0&&n.seek(xn(f,c.clientX,a(t.get()))))}}),o.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let u=c.target.closest("[data-sel]");u&&(c.preventDefault(),u.click())}),e.addEventListener("wheel",c=>{c.shiftKey&&!c.deltaX&&(e.scrollLeft+=c.deltaY,c.preventDefault())},{passive:!1}),l(t.get()),t.subscribe((c,u)=>{if(c.state!==u.state||c.lang!==u.lang||c.timeline?.layers!==u.timeline?.layers||c.slots!==u.slots?l(c):c.frame!==u.frame&&d(c),c.pinned!==u.pinned){i(c);let h=o.querySelector(".blk.selected");if(h){let f=h.getBoundingClientRect(),p=e.getBoundingClientRect(),g=o.querySelector(".lane-label")?.getBoundingClientRect().width??0;(f.left<p.left+g||f.right>p.right)&&(e.scrollLeft+=f.left-p.left-g-20);let b=(o.querySelector(".ruler")?.getBoundingClientRect().height??0)+(h.closest(".segments")?0:o.querySelector(".segments")?.getBoundingClientRect().height??0);(f.top<p.top+b||f.bottom>p.bottom)&&(e.scrollTop+=f.top-p.top-b-6)}}})};var wn=e=>e.reduce((t,n)=>typeof n=="number"?t+"["+n+"]":t?t+"."+n:n,""),$o=(e,t)=>Ut(t)?S(e,t):t,Mt=e=>typeof e=="number"?String(Number(e.toFixed(4))):typeof e=="string"?e:JSON.stringify(e)??"",kt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),er=(e,t)=>{let n=wn(t);return e.filter(o=>o.at===n||o.at.startsWith(n+".")||o.at.startsWith(n+"["))},tr=(e,t)=>{let n=m("input",{attrs:{type:"number",step:String(e.step??(e.range?.integer?1:"any")),...e.range?.min===void 0?{}:{min:String(e.range.min)},...e.range?.max===void 0?{}:{max:String(e.range.max)}}});return n.value=typeof e.value=="number"?Mt(e.value):"",typeof e.resolved=="number"&&e.value===void 0&&(n.placeholder=Mt(e.resolved)),n.addEventListener("change",()=>{let o=n.value.trim(),r=Number(o);if(o!==""&&!Number.isFinite(r))return void n.setAttribute("aria-invalid","true");t(o===""?void 0:r)}),n},kn=(e,t)=>{let n=typeof e.value=="string"?e.value:"";if(e.kind==="textarea"){let r=m("textarea",{attrs:{rows:String(Math.min(6,Math.max(2,n.split(\`
37682
- \`).length)))}});return r.value=n,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r.addEventListener("keydown",s=>{s.key==="Enter"&&(s.ctrlKey||s.metaKey)&&r.blur()}),r}let o=m("input",{attrs:{type:"text",autocomplete:"off",spellcheck:"false"}});return o.value=n,typeof e.resolved=="string"&&e.value===void 0&&(o.placeholder=e.resolved),o.addEventListener("change",()=>t(o.value.trim()===""?void 0:o.value.trim())),o},nr=(e,t,n)=>{let o=[...e.empty===null?[]:[m("option",{text:e.empty??S(n,"fDefault"),attrs:{value:""}})],...e.options.map(a=>m("option",{text:e.labels?.[a]??a,attrs:{value:a}}))],r=m("select",{},o),s=e.value===void 0?"":String(e.value);return s!==""&&!e.options.includes(s)&&r.append(m("option",{text:s,attrs:{value:s}})),r.value=s,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r},or=(e,t)=>{let n=kn(e,t),o=e.value??e.resolved,r=typeof o=="string"&&/^#[0-9a-f]{6}$/i.test(o)?o:"#000000",s=m("input",{class:"swatch-pick",attrs:{type:"color",tabindex:"-1"}});return s.value=r.toLowerCase(),s.addEventListener("change",()=>t(s.value)),m("span",{class:"colour"},[s,n])},rr=(e,t)=>{let n=e.commit??(l=>{kt(l,e.value)||t.commit(e.path,l)}),o=l=>{kt(l,e.value)||n(l)},r=e.kind==="number"?tr(e,o):e.kind==="select"?nr(e,o,t.lang):e.kind==="color"?or(e,o):kn(e,o),s=r.tagName==="SPAN"?r.querySelector("input[type=text]"):r;s.dataset.path=wn(e.path),e.disabled&&s.setAttribute("disabled","");let a=er(t.problems,e.path);a.length&&s.setAttribute("aria-invalid","true");let d=e.resolved!==void 0&&e.value!==void 0&&!kt(e.value,e.resolved),i=$o(t.lang,e.label);return m("label",{class:"fld"+(e.wide||e.kind==="textarea"?" wide":"")+(e.kind==="textarea"?" area":"")},[m("span",{class:"fl",text:i,title:i}),r,...d?[m("span",{class:"rv",text:"\\u2192 "+Mt(e.resolved),title:S(t.lang,"resolvedTitle")})]:[],...a.map(l=>m("span",{class:"fprob",text:l.message+(l.fix?" "+S(t.lang,"fix")+": "+l.fix:"")}))])},_=(e,t,n,o=[])=>m("fieldset",{class:"fs"},[m("legend",{text:e}),...t.map(r=>m("div",{class:"row"},r.filter(s=>s!==null).map(s=>s instanceof HTMLElement?s:rr(s,n)))),...o]);var Ln=["slide","whip"],Rn=["blur","zoom","shake","flash","whip","glitch","fade","spin"];var Pn=(e,t,n)=>m("div",{class:"hint",text:S(e.lang,"onFrames")+" "+t+".."+(n-1)}),Tt=(e,t,n,o,r=S(e.lang,"fWhen"))=>{let s=T(n)?n:{},a=e.state.resolved?.canvas.fps??30,d=e.state.resolved?.segments.find(h=>h.id===s.segment),i=h=>h==="from"?0:h==="to"&&d?d.end-d.start:void 0,l=(h,f)=>({kind:"number",label:S(e.lang,f)+(e.lang==="zh"?"\\uFF08\\u79D2\\uFF09":" (s)"),path:[...t,h],value:typeof(s[h]??i(h))=="number"?Number(s[h]??i(h))/a:void 0,step:.01,commit:p=>e.commit([...t,h],p===void 0?void 0:Math.round(Number(p)*a))}),c=o?[Pn(e,o.start,o.end)]:[];if(s.phrase!==void 0)return _(r,[[{kind:"text",label:"fPhrase",path:[...t,"phrase"],value:s.phrase,wide:!0}],[l("occurrence","fOccurrence"),l("lead","fLead"),l("hold","fHold")]],e,c);let u={kind:"select",label:"fSegment",path:[...t,"segment"],value:s.segment,options:te(e.state).map(h=>String(h.id)),labels:Object.fromEntries(te(e.state).map((h,f)=>[String(h.id),(e.lang==="zh"?"\\u753B\\u9762 ":"Scene ")+(f+1)])),empty:null};return _(r,[[u,l("from","fFrom"),l("to","fTo")]],e,c)},An=(e,t)=>{let n=Array.isArray(t.track.cues)?t.track.cues:[],o=String(t.track.id),r=n.flatMap((s,a)=>{if(t.kind==="cue"&&t.cue!==a)return[];let d=["tracks",t.index,"cues",a],i=e.state.resolved?.items.find(u=>u.id===o+"#"+a),l={kind:"textarea",label:S(e.lang,"fCue")+" "+a,path:[...d,"text"],value:T(s)?s.text:void 0},c=_("#"+a,[[l]],e,[Tt(e,[...d,"during"],T(s)?s.during:void 0,i,S(e.lang,"fWhen"))]);return c.classList.add("cue"),t.kind==="cue"&&t.cue===a&&c.classList.add("current"),c});return m("div",{class:"cues"},[m("h3",{text:S(e.lang,"fCues")+" ("+n.length+")"}),...r])},ar=(e,t)=>e==="wipe"?X(j(t.schema.transition,"direction")):Ln.includes(e)?X(j(t.schema.motion,"direction")):[],ir=(e,t,n,o)=>{let r=[...t,"in"],s=T(n)?n:void 0,a=String(s?.transition??""),d=e.schema.transition,i=o?.transition,l=(p,g,b,y)=>({kind:b,label:g,path:[...r,p],value:s?.[p],resolved:i?.[p==="transition"?"kind":p],range:xe(j(d,p)),options:y??X(j(d,p)),step:p==="strength"?.1:void 0}),c={kind:"select",label:"fKind",path:[...r,"transition"],value:s?.transition,options:X(j(d,"transition")),empty:S(e.lang,"fHardCut"),commit:p=>p===void 0?e.commit(r,void 0):e.commit([...r,"transition"],p)},u=ar(a,e),h=Rn.includes(a),f=[[c,s&&a!=="cut"?l("frames","fFrames","number"):null],[u.length?l("direction","fDirection","select",u):null,a==="slide"?l("mode","fMode","select"):null,a==="fade"?l("via","fVia","select"):null],[h?l("side","fSide","select"):null,s&&a!=="cut"?l("ease","fEase","select"):null,s&&a!=="cut"?l("strength","fStrength","number"):null]];return _(S(e.lang,"fTransition"),f.filter(p=>p.some(g=>g!==null)),e)},dr=(e,t,n)=>{let o=e.schema.base,r=ve(e.state,["image","video"]),s="material"in n?"material":"color"in n?"color":"scene",a={kind:"select",label:"fBase",path:t,value:s,options:s==="scene"?["scene","color","material"]:["color","material"],labels:{scene:S(e.lang,"fBaseScene"),color:S(e.lang,"fBaseColor"),material:S(e.lang,"fBaseMaterial")},empty:null,commit:l=>e.set(t,l==="scene"?n:l==="color"?{color:"#000000"}:{material:r[0]??""})};if(s==="scene"){let l=T(n.slots)?n.slots:{},c=Object.entries(l).filter(u=>typeof u[1]=="string").map(([u,h])=>[{kind:"textarea",label:u,path:[...t,"slots",u],value:h,wide:!0}]);return _(S(e.lang,"fBaseScene"),[[a],...c],e)}if(s!=="material"){let l=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,empty:null}:m("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fBase"),[[a,l]],e)}let d=ve(e.state,["video"]).includes(String(n.material)),i=(l,c,u)=>({kind:"number",label:c,path:[...t,l],value:n[l],range:xe(j(o,l)),...u?{step:u}:{}});return _(S(e.lang,"fBase"),[[a,{kind:"select",label:"fMaterial",path:[...t,"material"],value:n.material,options:r,empty:null,wide:!0}],[{kind:"select",label:"fFit",path:[...t,"fit"],value:n.fit,options:X(j(o,"fit"))},...d?[i("in","fIn"),i("speed","fSpeed",.05),i("audio","fSourceAudio")]:[]]],e,n.camera!==void 0?[m("div",{class:"hint",text:S(e.lang,"fCamera")})]:[])},Cn=(e,t)=>{let n=["segments",t.index],o=e.state.resolved?.segments[t.index],r=e.state.resolved?.canvas.fps??30,s={kind:"number",label:e.lang==="zh"?"\\u65F6\\u957F\\uFF08\\u79D2\\uFF09":"Duration (s)",path:[...n,"frames"],value:Number(oe(e.state.source,[...n,"frames"]))/r,step:.01,range:{min:1/r,integer:!1},commit:i=>e.commit([...n,"frames"],Math.max(1,Math.round(Number(i)*r)))},a=_(e.lang==="zh"?"\\u955C\\u5934\\u65F6\\u957F":"Shot duration",[[s]],e,o?[Pn(e,o.start,o.end)]:[]),d=t.segment;return[a,...t.index>0?[ir(e,n,d.in,o)]:[],...T(d.base)?[dr(e,[...n,"base"],d.base)]:[]]};var On=e=>{if(T(e))return e;if(typeof e!="string"||!St(e))return{};let{font:t,...n}=vt[e];return n},st="custom",Hn=(e,t,n,o)=>{let r=[...t,"style"],s=j(e.schema.text,"style"),a=X(s),d=T(n)?n:void 0,i=e.state.resolved?.canvas.height??1,l={kind:"number",label:e.lang==="zh"?"\\u5B57\\u53F7\\uFF08px\\uFF09":"Font size (px)",path:[...r,"size"],value:Math.round(Number(d?.size??o?.size??.05)*i),step:1,range:{min:1,max:i,integer:!0},commit:p=>c("size")(p===void 0?void 0:Number(p)/i)},c=p=>g=>{let b=Object.fromEntries(Object.entries({...On(n),[p]:g}).filter(([,y])=>y!==void 0));e.set(r,b)},u=(p,g,b={})=>({kind:g,label:"f"+p[0]?.toUpperCase()+p.slice(1),path:[...r,p],value:d?.[p],resolved:o?.[p],commit:c(p),range:xe(j(s,p)),options:X(j(s,p)),...b}),h={kind:"select",label:"fNamed",path:r,value:typeof n=="string"?n:d?st:void 0,options:[...a,st],labels:{[st]:S(e.lang,"fCustom"),...e.lang==="zh"?{headline:"\\u6807\\u9898",subtitle:"\\u526F\\u6807\\u9898",label:"\\u6807\\u7B7E",caption:"\\u5B57\\u5E55"}:{}},commit:p=>e.set(r,p===st?On(n):p)},f=u("font","select",{value:d?.font??o?.font,options:[...new Set([String(d?.font??o?.font??"sans-serif"),...ve(e.state,["font"]),"sans-serif","serif","monospace"])],label:e.lang==="zh"?"\\u5B57\\u4F53":"Font",wide:!0});return _(S(e.lang,"fStyle"),[[f],[h,l],[u("color","color",{label:"fColour"}),u("weight","number",{step:100}),u("align","select",{labels:e.lang==="zh"?{left:"\\u5DE6\\u5BF9\\u9F50",center:"\\u5C45\\u4E2D",right:"\\u53F3\\u5BF9\\u9F50"}:{}})]],e)},lr=new Set(["slide","wipe"]),at=(e,t,n,o,r)=>{let s=[...t,n],a=e.schema.motion,d=T(o)?o:void 0,i=(u,h,f)=>({kind:h,label:f,path:[...s,u],value:d?.[u],resolved:r?.[u],disabled:!d,range:xe(j(a,u)),options:X(j(a,u))}),l={kind:"select",label:"fPreset",path:[...s,"preset"],value:d?.preset,options:X(j(a,"preset")),empty:S(e.lang,"fNone"),commit:u=>u===void 0?e.commit(s,void 0):e.commit([...s,"preset"],u)},c=lr.has(String(d?.preset??""));return _(S(e.lang,n==="enter"?"fEnter":"fExit"),[[l,i("frames","number","fFrames")],[c?i("direction","select","fDirection"):null,i("ease","select","fEase")]],e)},ie=(e,t,n,o,r={})=>({kind:"number",label:n,path:t,value:oe(e.state.source,t),range:xe(o),...r}),Ie=(e,t,n,o,r={})=>({kind:"select",label:n,path:t,value:oe(e.state.source,t),options:o,...r}),Nn=(e,t,n)=>{let o=e.state.resolved?.canvas,r=n&&o?[n.box[0]*o.width,n.box[1]*o.height,n.box[2]*o.width,n.box[3]*o.height].map(a=>Math.round(a)).join(", ")+" px":"",s=["fX","fY","fW","fH"].map((a,d)=>{let i=[...t,"box",d],l=d%2===0?o?.width??1:o?.height??1;return ie(e,i,a,void 0,{step:1,value:Math.round(Number(oe(e.state.source,i)??0)*l),commit:c=>e.commit(i,Number(c)/l)})});return _(e.lang==="zh"?"\\u4F4D\\u7F6E\\u4E0E\\u5C3A\\u5BF8\\uFF08px\\uFF09":"Position and size (px)",[s],e,r?[m("div",{class:"hint",text:r})]:[])},cr=(e,t,n)=>_(S(e.lang,"fLook"),[[ie(e,[...t,"rotate"],"fRotate",j(n,"rotate")),ie(e,[...t,"opacity"],"fOpacity",j(n,"opacity"),{step:.05}),ie(e,[...t,"z"],"fZ",j(n,"z"))]],e),ur=(e,t,n,o)=>{let r=String(n.type),s=e.schema[r==="image"?"image":r==="video"?"video":"shape"],a=ie(e,[...t,"radius"],"fRadius",j(s,"radius"),{step:.01});if(r==="shape"){let u=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,resolved:o?.color}:m("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fShape"),[[Ie(e,[...t,"shape"],"fShape",X(j(s,"shape")),{empty:null}),u,a]],e)}if(r!=="image"&&r!=="video")return null;let d=Ie(e,[...t,"material"],"fMaterial",ve(e.state,[r]),{empty:null,wide:!0}),i=Ie(e,[...t,"fit"],"fFit",X(j(s,"fit")),{resolved:o?.fit}),l=Ie(e,[...t,"mask"],"fMask",X(j(s,"mask")),{empty:S(e.lang,"fNone")}),c=r==="video"?[ie(e,[...t,"in"],"fIn",j(s,"in")),ie(e,[...t,"speed"],"fSpeed",j(s,"speed"),{step:.05}),ie(e,[...t,"audio"],"fSourceAudio",j(s,"audio"))]:[];return _(S(e.lang,r==="video"?"fFootage":"fPicture"),[[d,i],[a,l,...c]],e)},mr=(e,t)=>{let n=_(S(e.lang,"fText"),[[{kind:"textarea",label:e.lang==="zh"?"\\u5185\\u5BB9":"Content",path:[...t,"text"],value:oe(e.state.source,[...t,"text"])}]],e);return n.querySelector("legend")?.remove(),n},pr=(e,t,n)=>{let o=T(n.during)?n.during:void 0,r={kind:"select",label:"fStart",path:[...t,"during","segment"],value:o?.segment,options:te(e.state).map(s=>String(s.id)),empty:S(e.lang,"fWhole"),commit:s=>s===void 0?e.commit([...t,"during"],void 0):e.set([...t,"during"],{...o??{},segment:s})};return _(S(e.lang,"fAudio"),[[Ie(e,[...t,"material"],"fMaterial",ve(e.state,["audio","voice","speech"]),{empty:null,wide:!0}),ie(e,[...t,"gain"],"fGain",j(e.schema.audio,"gain"))],[r,ie(e,[...t,"during","from"],"fFrom",void 0,{disabled:!o})]],e)},In=(e,t)=>e.resolved?.items.find(n=>n.id===t),fr=(e,t)=>{let n=["tracks",t.index],o=t.track,r=String(o.type);if(r==="audio")return[pr(e,n,o)];let s=String(o.id);if(r==="caption"){let i=In(e.state,s+"#"+(t.kind==="cue"?t.cue:0));return[An(e,t),Hn(e,n,o.style,i?.style),Nn(e,n,i),at(e,n,"enter",o.enter,i?.enter),at(e,n,"exit",o.exit,i?.exit)]}let a=In(e.state,s),d=e.schema[r==="text"?"text":r==="image"?"image":r==="video"?"video":"shape"];return[...r==="text"?[mr(e,n)]:[],...r==="text"?[Hn(e,n,o.style,a?.style)]:[ur(e,n,o,a)].filter(i=>i!==null),Tt(e,[...n,"during"],o.during,a),Nn(e,n,a),at(e,n,"enter",o.enter,a?.enter),at(e,n,"exit",o.exit,a?.exit),cr(e,n,d)]},Fn=(e,t)=>{let n=t.kind==="segment"?S(e.lang,"fSegment")+" "+String(t.segment.id):String(t.track.type)+" "+String(t.track.id)+(t.kind==="cue"?" #"+t.cue:""),o=t.kind==="segment"?Cn(e,t):fr(e,t),r=t.kind==="segment"?e.lang==="zh"?"\\u753B\\u9762 "+(t.index+1):"Scene "+(t.index+1):t.kind==="cue"?e.lang==="zh"?"\\u5B57\\u5E55 "+(t.cue+1):"Subtitle "+(t.cue+1):e.lang==="zh"?{text:"\\u6587\\u5B57",image:"\\u56FE\\u7247",video:"\\u89C6\\u9891",audio:"\\u97F3\\u9891",shape:"\\u5F62\\u72B6"}[String(t.track.type)]??"\\u5143\\u7D20":String(t.track.type),s=t.kind==="cue"?2:t.kind==="segment"?1:t.track.type==="text"?2:1;return m("div",{class:"form",id:"edit-form"},[m("div",{class:"sel-title",text:r,title:n}),...o.slice(0,s),...o.length>s?[m("details",{},[m("summary",{text:e.lang==="zh"?"\\u4F4D\\u7F6E\\u3001\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548":"Position, timing and motion"}),...o.slice(s)])]:[]])};var Fe=(e,t=[])=>m("h2",{},[m("span",{text:e}),...t]),Dn=e=>m("pre",{class:"json",text:JSON.stringify(e,null,2)??"undefined"}),gr=(e,t,n)=>{if(e.pinned){let a=Bt(t,e.pinned);return[m("div",{class:"sel-title",text:Vt(e.pinned)}),a===void 0?m("p",{class:"muted",text:S(e.lang,"nothing")}):Dn(a)]}let o=t.resolved?Z(t.resolved,e.frame):void 0,s=(t.resolved?fe(t.resolved,e.frame):[]).map(a=>m("button",{class:"chip",text:a.id,attrs:{type:"button"},on:{click:()=>n.pin({kind:"item",id:a.id})}}));return[...o?[m("div",{class:"sel-title",text:"segment "+o.id}),Dn(o)]:[m("p",{class:"muted",text:S(e.lang,"nothing")})],m("div",{class:"chips"},[m("span",{class:"muted",text:S(e.lang,"onScreen")+": "}),...s.length?s:[S(e.lang,"none")]])]},hr=(e,t,n,o)=>{let r=e.edit.schema;if(!t.edit)return;if(!r)return[m("p",{class:"muted",text:e.lang==="zh"?"\\u6B63\\u5728\\u8F7D\\u5165\\u7F16\\u8F91\\u5DE5\\u5177\\u2026":"Loading editing tools\\u2026"})];if(e.pinned?.kind==="slot")return[dn(o,n)];let s=q(t,e.pinned);if(s){let a={lang:e.lang,problems:e.edit.problems,state:t,schema:r,commit:(d,i)=>{let l=Wt(t.source,d,i);l&&n.send(l)},set:(d,i)=>{n.send({op:"set",path:d,value:i})}};return[Fn(a,s)]}if(!e.pinned)return[]},br=(e,t)=>m("li",{class:"problem "+e.level},[m("div",{},[m("b",{class:e.level,text:S(t,e.level)})," ",m("code",{text:e.at})]),m("div",{text:e.message}),...e.allowed?.length?[m("div",{class:"muted",text:S(t,"allowed")+": "+e.allowed.join(", ")})]:[],...e.fix?[m("div",{text:S(t,"fix")+": "+e.fix})]:[]]),yr=e=>Object.entries(e).map(([t,n])=>t+"="+(typeof n=="number"?Number(n.toFixed(3)):n)).join(", "),vr=(e,t)=>{let n=(r,s="")=>m("tr",{class:s},r.map(a=>m("td",{},[a]))),o=Object.entries(e.dimensions).map(([r,s])=>{let a=yr(s.detail);return n([Jt(t,r),s.n?s.score.toFixed(2):"-",String(s.n),m("span",{class:"detail",text:a,title:a})],s.n?"":"muted")});return m("table",{class:"score"},[m("thead",{},[m("tr",{},[S(t,"dimension"),S(t,"value"),S(t,"compared"),S(t,"detail")].map(r=>m("th",{text:r})))]),m("tbody",{},[...o,n([S(t,"composite"),e.composite.toFixed(2),"",""],"total")])])},Sr=(e,t)=>[m("div",{class:"kv"},[m("span",{class:"muted",text:S(t,"renderMeasure")+": "}),m("code",{text:e.measure?.file??S(t,"none"),title:e.measure?.file??""})]),m("div",{class:"kv"},[m("span",{class:"muted",text:S(t,"referenceMeasure")+": "}),m("code",{text:e.referenceMeasure?.file??S(t,"none"),title:e.referenceMeasure?.file??""})]),...e.messages.map(n=>m("p",{class:"message",text:n}))],it=(e,t,n,o)=>{let r=m("section",{id:"selection"}),s=m("section",{id:"problems"}),a=m("section",{id:"score"}),d=m("section",{id:"measures"}),i=m("section",{id:"notes"});e.append(r,s,a,d,i);let l="",c="",u=f=>{let p=f.state,g=p?.resolved&&!f.pinned?[Z(p.resolved,f.frame)?.id,fe(p.resolved,f.frame).map(H=>H.id)]:null,b=p?.edit?[f.edit.problems,f.edit.schema!==null]:null,y=JSON.stringify([f.lang,p?.generation,f.pinned,g,b]);if(y===l)return;let v=JSON.stringify(f.pinned)!==c;c=JSON.stringify(f.pinned),l=y;let E=r.contains(document.activeElement)?document.activeElement.dataset.path:void 0,M=f.pinned?[m("button",{class:"link",text:S(f.lang,"follow"),attrs:{type:"button"},on:{click:()=>n.pin(null)}})]:[],k=p?(o&&hr(f,p,o,t))??gr(f,p,n):[];r.replaceChildren(Fe(S(f.lang,"selection"),[m("span",{class:"muted",text:" ("+S(f.lang,f.pinned?"pinned":"underPlayhead")+")"}),...M]),...k),E&&r.querySelector('[data-path="'+CSS.escape(E)+'"]')?.focus(),v&&r.querySelector(".cue.current")?.scrollIntoView({block:"nearest"})},h=f=>{let p=f.state;if(!p)return;let g=f.lang;s.replaceChildren(Fe(S(g,"problems")+" ("+p.problems.length+")"),p.problems.length?m("ul",{},p.problems.map(b=>br(b,g))):m("p",{class:"muted",text:S(g,"noProblems")})),a.replaceChildren(Fe(S(g,"score")),p.score?vr(p.score,g):m("p",{class:"muted",text:S(g,"noScore")})),d.replaceChildren(Fe(S(g,"measurements")),...Sr(p,g)),i.hidden=!p.notes,i.replaceChildren(Fe(S(g,"notes")+" ("+(p.notes?.length??0)+")"),m("ul",{},(p.notes??[]).map(b=>m("li",{class:"note-item"},[m("code",{text:b.at})," ",m("b",{text:b.kind}),m("div",{text:b.message})]))))};h(t.get()),u(t.get()),t.subscribe((f,p)=>{(f.state!==p.state||f.lang!==p.lang)&&h(f),(f.state!==p.state||f.lang!==p.lang||f.pinned!==p.pinned||f.frame!==p.frame||f.edit.problems!==p.edit.problems||f.edit.schema!==p.edit.schema)&&u(f)})};var Lt=(e,t,n,o)=>{let r=Math.max(0,t.frames-1),s=o-e.start;return s<=0?Math.min(e.in,r):Math.min(r,e.in+Math.round(s*t.fps*e.speed/n))};var jn=(e,t)=>{let n=[],o=(d,i)=>{let l=e.querySelector(d+" > img");l&&n.push({img:l,play:i,active:!1})};t.segments.forEach(d=>{d.base.kind==="video"&&o('[data-segment="'+CSS.escape(d.id)+'"]',d.base.play)}),t.items.forEach(d=>{d.play&&o('[data-item="'+CSS.escape(d.id)+'"]',d.play)});let r=(d,i)=>{if(d.video)return;let l=t.footage?.[d.play.material],c=d.img.parentElement;if(!l||!c)return;let u=e.createElement("video");u.muted=!0,u.playsInline=!0,u.preload="auto",u.hidden=!0,u.style.display="none",u.dataset.previewVideo=d.play.material;let h=Lt(d.play,l,t.canvas.fps,Math.max(i,d.play.start))/l.fps;d.time=h,u.addEventListener("loadedmetadata",()=>{u.paused&&u.isConnected&&(u.currentTime=d.time??h)},{once:!0}),u.src=l.src.startsWith("project/")?"/"+l.src:"/project/"+l.src.split("/").map(encodeURIComponent).join("/");let f=()=>{!d.active||!u.isConnected||c.style.display==="none"||(u.style.cssText=d.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",u.hidden=!1,u.style.visibility="",d.img.style.visibility="hidden")};u.addEventListener("loadeddata",f),u.addEventListener("seeked",()=>{if(!d.playing&&d.active&&d.time!==void 0&&Math.abs(u.currentTime-d.time)>.5/l.fps){u.currentTime=d.time;return}f()}),c.append(u),d.video=u},s=d=>{d.video?.pause(),d.video?.removeAttribute("src"),d.video?.load(),d.video?.remove(),d.video=void 0,d.active=!1,d.img.style.visibility=""};return{sync:(d,i,l)=>{let c=n.filter(u=>u.play.start>d).sort((u,h)=>u.play.start-h.play.start).slice(0,2);for(let u of n)c.includes(u)||u.img.parentElement?.style.display!=="none"?r(u,d):u.video&&s(u);for(let u of n){let h=t.footage?.[u.play.material],f=u.img.parentElement;if(!((i||h?.dir===void 0)&&!!h&&!!f&&f.style.display!=="none")){u.video?.pause(),u.video&&(u.video.hidden=!0,u.video.style.display="none"),u.img.style.visibility="",u.active=!1;continue}if(!h||!f)continue;let g=u.video;g.hidden=!1,g.style.cssText=u.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",u.img.style.visibility=g.readyState>=2?"hidden":"",g.style.visibility=g.readyState>=2?"":"hidden";let b=Lt(u.play,h,t.canvas.fps,d)/h.fps;u.time=b,u.playing=i;let y=l*u.play.speed;g.playbackRate=Math.max(.0625,Math.min(16,y));let v=i&&u.active?.25:.5/h.fps;!g.seeking&&Math.abs(g.currentTime-b)>v&&(g.currentTime=b),d<u.play.start||b>=(h.frames-1)/h.fps||!i?g.pause():g.paused&&g.play().catch(()=>{}),u.active=!0}},needsPictures:()=>n.some(d=>!!(d.video?.error&&t.footage?.[d.play.material]?.dir&&d.img.parentElement?.style.display!=="none")),dispose:()=>{n.forEach(s)}}};var zn=(e,t)=>{let n=m("div",{class:"caption"}),o=m("div",{class:"note"}),r=m("div",{class:"overlay"}),s=m("div",{class:"frame-box"},[t,r]);return{root:m("div",{class:"viewer",id:e},[n,s,o]),caption:n,note:o,box:s,overlay:r}},Bn=(e,t,n,o)=>Math.max(.01,Math.min(n/e,o/t)),Rt=(e,t)=>{let n=e.reference.root.isConnected,o=getComputedStyle(e.root),r=e.root.classList.contains("comparing"),s=(e.root.clientWidth-parseFloat(o.paddingLeft)-parseFloat(o.paddingRight)-(n?parseFloat(o.gap)||16:0))/(n?2:1)-(r?18:0),a=e.root.clientHeight-parseFloat(o.paddingTop)-parseFloat(o.paddingBottom)-e.render.caption.offsetHeight-e.render.note.offsetHeight-(r?32:8),d=t.state?.resolved?.canvas;if(e.render.box.classList.toggle("problems",!d),d){let h=Bn(d.width,d.height,s,a);e.render.box.style.cssText="width:"+d.width*h+"px;height:"+d.height*h+"px;",e.scaler.style.cssText="width:"+d.width+"px;height:"+d.height+"px;transform:scale("+h+");"}else e.render.box.style.cssText="width:"+Math.max(0,s)+"px;height:"+Math.max(0,a)+"px;",e.scaler.style.cssText="width:100%;height:100%;";if(!n)return;let i=t.state?.referenceMeasure?.measure.source,l=e.video.videoWidth||i?.width||d?.width||16,c=e.video.videoHeight||i?.height||d?.height||9,u=Bn(l,c,s,a);e.reference.box.style.cssText="width:"+l*u+"px;height:"+c*u+"px;"},Vn=(e,t,n,o)=>{if(t)for(let r of Dt(t,n,o))e.append(le(m("div",{class:"ebox"},[m("span",{text:ze(r)})]),r.box))},xr=(e,t,n)=>{let o=t.state;if(e.render.overlay.replaceChildren(),e.reference.overlay.replaceChildren(),!o?.resolved)return;let r=se(o);if(t.overlays.safe)for(let s of[e.render.overlay,e.reference.overlay])s.append(le(m("div",{class:"safe"}),zt(o.resolved.canvas)));if(t.overlays.boxes)for(let s of fe(o.resolved,t.frame))e.render.overlay.append(le(m("div",{class:"ibox",title:s.id,on:{click:()=>n.pin({kind:"item",id:s.id})}},[m("span",{text:s.id})]),s.box));t.overlays.events&&(Vn(e.render.overlay,o.measure?.measure,t.frame,r),Vn(e.reference.overlay,o.referenceMeasure?.measure,t.frame,r))},Er=(e,t)=>{let n=t.state?.resolved?.canvas,o=!!(t.state&&!t.state.resolved);e.render.caption.textContent=S(t.lang,t.state?.edit?"currentVideo":"render")+(n?" "+n.width+"x"+n.height+", "+n.fps+" fps":""),e.render.note.textContent=o?S(t.lang,"errorsOnStage"):t.pageError?S(t.lang,"imageFailed")+": "+t.pageError:"",e.render.note.classList.toggle("error",o||!!t.pageError);let r=t.edit.playRender&&t.edit.render?.state==="done"?t.edit.render:void 0;e.reference.caption.textContent=r?S(t.lang,"renderFile")+" "+(r.file.split(/[\\\\/]/).pop()??""):S(t.lang,"reference")+(t.state?.reference?" "+t.state.reference.name:""),e.reference.note.textContent=S(t.lang,"seekNote")},_n=(e,t,n,o)=>{if(!t.state||!e.getAttribute("src"))return;let r=(t.frame+.25)/se(t.state);if(!t.playing){e.paused||e.pause(),(o||n.playing||Math.abs(e.currentTime-r)>.001)&&(e.currentTime=r);return}e.playbackRate=t.speed,o||!n.playing||n.speed!==t.speed?(e.currentTime=r,e.play().catch(()=>{})):!e.seeking&&Math.abs(e.currentTime-r)>.2&&(e.currentTime=r)},wr=(e,t)=>{let n,o=-1,r=0,s=0,a,d,i=()=>{let c=n;if(!c)return;let u=t.get(),h=u.frame,f=++s;(c.preparePreview?.(h)??Promise.resolve()).then(async()=>{f===s&&(u.playing&&c.previewFrame&&a&&!a.needsPictures()?c.previewFrame(h):c.applyFrame(h),a?.sync(h,u.playing,u.speed),await c.settle())}).then(()=>null,g=>g instanceof Error?g.message:String(g)).then(g=>{if(f!==s)return;g!==null&&g!==t.get().pageError&&t.set({pageError:g}),document.body.dataset.applied=String(h),e.dispatchEvent(new Event("frameapplied"));let b=t.get().state?.resolved,y=b?Z(b,h)?.id:void 0;g===null&&y!==d&&(d=y,document.dispatchEvent(new Event("studio:scene-ready")))})};return e.addEventListener("load",()=>{let c=++r,u=e.contentWindow?.__popostVideo;if(n=void 0,d=void 0,!u){document.body.dataset.ready="error";return}(u.preparePreview?.(t.get().frame)??u.prepare()).then(()=>null,f=>f instanceof Error?f.message:String(f)).then(f=>{if(c!==r)return;n=u;let p=t.get().state?.resolved;p&&e.contentDocument&&(a=jn(e.contentDocument,p)),f!==t.get().pageError&&t.set({pageError:f}),i(),document.body.dataset.ready="1",document.dispatchEvent(new Event("studio:page-ready"))})}),{load:c=>{o=c,s++,a?.dispose(),a=void 0,n=void 0,document.body.dataset.ready="",e.src="/page?g="+c},apply:i,loaded:()=>o}},kr=e=>{let t=e.edit.render;return e.edit.playRender&&t?.state==="done"?t.url:e.compare!==!1&&e.state?.reference?e.state.reference.url??"/reference":""},dt=(e,t,n)=>{let o=m("iframe",{id:"page",attrs:{title:"page",tabindex:"-1"}}),r=m("div",{class:"scaler"},[o]),s=m("video",{id:"reference-video",attrs:{preload:"auto",playsinline:"",tabindex:"-1"}});s.muted=!0;let a={root:e,render:zn("render-view",r),reference:zn("reference-view",s),iframe:o,scaler:r,video:s};e.append(a.render.root);let d=wr(o,t);new ResizeObserver(()=>Rt(a,t.get())).observe(e),s.addEventListener("loadedmetadata",()=>{Rt(a,t.get()),_n(s,t.get(),t.get(),!0)});let i="";return t.subscribe((l,c)=>{let u=kr(l);if(u!==i){i=u,u&&!a.reference.root.isConnected&&e.append(a.reference.root),u||a.reference.root.remove(),u?s.src=u:s.removeAttribute("src");let h=!!(u&&!l.edit.playRender);e.classList.toggle("comparing",h),a.reference.root.style.order=h?"-1":""}l.state&&l.state.generation!==d.loaded()&&d.load(l.state.generation),(l.frame!==c.frame||l.playing!==c.playing||l.speed!==c.speed)&&d.apply(),(l.frame!==c.frame||l.overlays!==c.overlays||l.state!==c.state)&&xr(a,l,n),(l.frame!==c.frame||l.playing!==c.playing||l.speed!==c.speed)&&_n(s,l,c,!1),(l.compare!==c.compare||l.lang!==c.lang||l.state!==c.state||l.pageError!==c.pageError||l.edit!==c.edit)&&(Er(a,l),Rt(a,l))}),{frameBox:a.render.box,iframe:o}};var Ee=(e,t,n,o,r)=>{let s=m("button",{id:t,class:"tbtn",attrs:{type:"button"}},[o]);return s.addEventListener("click",()=>{r(),s.blur()}),e.buttons.push({el:s,title:n}),s},Mr=e=>{let t=m("input",{id:"jump",attrs:{type:"text",inputmode:"numeric",autocomplete:"off"}});return t.addEventListener("keydown",n=>{if(n.key!=="Enter")return;let o=Number(t.value.trim()),r=t.value.trim()!==""&&Number.isInteger(o);t.setAttribute("aria-invalid",String(!r)),r&&(e.pause(),e.seek(o),t.value="",t.blur())}),t},Tr=e=>{let t=m("select",{id:"speed"},_t.map(n=>m("option",{text:n+"x",attrs:{value:String(n)}})));return t.value="1",t.addEventListener("change",()=>{e.setSpeed(Number(t.value)),t.blur()}),t},Lr=(e,t)=>{let n=[],o=d=>()=>{t.pause(),d()},r=m("span",{class:"icon"},[Y("play")]),s=m("input",{id:"slider",attrs:{type:"range",min:"0",max:"0",step:"1",value:"0","aria-label":"frame"}});s.addEventListener("input",()=>t.seek(Number(s.value)));let a={buttons:n,playIcon:r,slider:s,play:Ee({buttons:n},"play","play",r,()=>t.togglePlay()),frameLabel:m("span",{class:"muted"}),frameNo:m("span",{id:"frame-no",class:"num"}),frameOf:m("span",{class:"num muted"}),time:m("span",{id:"time",class:"num muted"}),speedLabel:m("label",{class:"muted",attrs:{for:"speed"}}),speed:Tr(t),jump:Mr(t)};return e.append(Ee(a,"first","first",Y("first"),o(()=>t.seek(0))),Ee(a,"back10","back10","\\u221210",o(()=>t.step(-10))),Ee(a,"back1","back1","\\u22121",o(()=>t.step(-1))),a.play,Ee(a,"fwd1","fwd1","+1",o(()=>t.step(1))),Ee(a,"fwd10","fwd10","+10",o(()=>t.step(10))),Ee(a,"last","last",Y("last"),o(()=>t.seek(Number.MAX_SAFE_INTEGER))),m("div",{class:"slider-wrap"},[s]),m("span",{class:"readout"},[m("span",{},[a.frameLabel,a.frameNo,a.frameOf]),a.time]),m("span",{class:"speed"},[a.speedLabel,a.speed]),a.jump),a},Kn=(e,t,n)=>{let o=t.state?W(t.state):0,r=t.state?se(t.state):30;e.slider.max=String(Math.max(0,o-1)),e.slider.value=String(t.frame),e.frameNo.textContent=String(t.frame),e.frameOf.textContent=" / "+Math.max(0,o-1),e.time.textContent=pt(t.frame,r)+" / "+pt(o,r),!(n&&t.playing===n.playing&&t.lang===n.lang)&&(e.playIcon.replaceChildren(Y(t.playing?"pause":"play")),e.buttons.forEach(s=>{s.el.title=S(t.lang,s.el===e.play?t.playing?"pause":"play":s.title)}),e.frameLabel.textContent=S(t.lang,"frame")+" ",e.speedLabel.textContent=S(t.lang,"speed")+" ",e.jump.placeholder=S(t.lang,"jump"),e.jump.title=S(t.lang,"jumpHint"))},Rr=(e,t)=>{let n=e.target;if(e.defaultPrevented||n?.tagName==="SELECT"||n?.tagName==="TEXTAREA"||n instanceof HTMLInputElement&&(n.type==="text"||n.type==="number")||e.altKey||e.ctrlKey||e.metaKey)return;let r={" ":()=>t.togglePlay(),ArrowLeft:()=>{t.pause(),t.step(e.shiftKey?-10:-1)},ArrowRight:()=>{t.pause(),t.step(e.shiftKey?10:1)},Home:()=>{t.pause(),t.seek(0)},End:()=>{t.pause(),t.seek(Number.MAX_SAFE_INTEGER)}}[e.key];r&&(e.preventDefault(),r())},lt=(e,t,n)=>{let o=Lr(e,n);Kn(o,t.get(),void 0),t.subscribe((r,s)=>{(r.frame!==s.frame||r.state!==s.state||r.playing!==s.playing||r.lang!==s.lang)&&Kn(o,r,s)}),document.addEventListener("keydown",r=>Rr(r,n))};var Pt=e=>{let t=e.store.get(),n=t.state?.resolved,o=t.pinned,r=o?.kind==="item"?n?.items.find(s=>s.id===o.id):void 0;return n?n.segments.find(s=>(o?.kind==="segment"||o?.kind==="slot")&&s.id===o.id)??(r?Z(n,r.start):void 0)??Z(n,t.frame):void 0},Jn=(e,t)=>{let n=e.store.get().state?.resolved?.segments.find(o=>o.id===t);n&&(e.actions.pause(),e.actions.seek(Math.min(n.end-1,n.start+Math.floor((n.end-n.start)*.3))),e.edit.select({kind:"segment",id:t}))},At=e=>{let{store:t,edit:n}=e,o=t.get().state,r=o?.resolved,s=m("div",{class:"studio-shot-list"});if(r)for(let d of r.segments){let i=d.base,l=i.kind==="scene"?x(t,"scene"):i.kind==="video"?x(t,"video"):i.kind==="image"?x(t,"image"):x(t,"color"),c=C("",()=>Jn(e,d.id),"studio-shot "+(ge(t.get().pinned,{kind:"segment",id:d.id})?"selected":""));c.append(sn(d.start+Math.floor((d.end-d.start)/2),o?.generation??0),m("span",{class:"studio-shot-copy"},[m("strong",{text:String(d.index+1).padStart(2,"0")+" "+d.id}),m("small",{text:l+" \\xB7 "+((d.end-d.start)/r.canvas.fps).toFixed(2)+"s"})])),c.dataset.selection=JSON.stringify({kind:"segment",id:d.id}),c.draggable=!!o?.edit,c.addEventListener("dragstart",u=>u.dataTransfer?.setData("application/x-popost-segment",String(d.index))),c.addEventListener("dragover",u=>u.preventDefault()),c.addEventListener("drop",u=>{u.preventDefault();let h=Number(u.dataTransfer?.getData("application/x-popost-segment"));Number.isInteger(h)&&h!==d.index&&n.send({op:"move",path:["segments",h],to:d.index})}),s.append(c)}let a=Oe("",x(t,"search"));return a.placeholder=x(t,"search"),a.addEventListener("input",()=>s.querySelectorAll(".studio-shot").forEach(d=>{d.hidden=!d.textContent?.toLowerCase().includes(a.value.toLowerCase())})),m("div",{class:"studio-side-body"},[U(x(t,"shots"),String(r?.segments.length??0)),a,s,A(x(t,"keepRhythm"))])},Un=async(e,t,n)=>{let{store:o,edit:r}=e,s=o.get().state,a=Pt(e);if(!s||!a)return;let d=t.kind,i=String(t.id);if(!n&&["image","video"].includes(String(d))){await r.send({op:"set",path:["segments",a.index,"base"],value:{material:i,fit:"cover"}});return}let l=$(G(s.source).tracks),c=["audio","voice","speech"].includes(String(d))?"audio":d;if(!["image","video","audio"].includes(String(c)))return;let u={id:"overlay-"+Date.now(),type:c,material:i,...c==="audio"?{gain:0}:{box:[.1,.1,.8,.6],fit:"contain"},during:{segment:a.id,from:0,to:a.end-a.start}};await r.send({op:"insert",path:["tracks",l.length],value:u},{kind:c==="audio"?"audio":"item",id:u.id})},Wn=e=>{let{store:t}=e,n=m("div",{class:"studio-resource-tabs"}),o=m("div"),r=()=>{n.replaceChildren(...["shots","files"].map(s=>C(x(t,s==="shots"?"shots":"sourceFile"),()=>{e.mediaView=s,r()},(e.mediaView??"shots")===s?"selected":""))),o.replaceChildren(n,(e.mediaView??"shots")==="shots"?At(e):Pr(e))};return r(),o},Pr=e=>{let{store:t}=e,n=t.get().state,o=m("input",{attrs:{type:"file",accept:"image/png,image/jpeg,image/webp,video/mp4,video/webm,video/quicktime,audio/*",hidden:""}});o.addEventListener("change",()=>{let s=o.files?.[0];if(!s)return;if(s.size>12*1024*1024){ce(t,x(t,"importHint"));return}let a=new FileReader;a.onload=()=>{ke(t,"/api/studio/import",{name:s.name,data:String(a.result).split(",")[1]})},a.readAsDataURL(s)});let r=m("div",{class:"studio-media-list"});for(let s of $(G(n?.source).materials)){let a=String(s.note??s.file??s.id),d=Ce(String(s.file??"")),i=s.kind==="image"?m("img",{attrs:{src:d,alt:a,loading:"lazy"}}):s.kind==="video"?m("video",{attrs:{src:d,controls:"",preload:"metadata"}}):m("audio",{attrs:{src:d,controls:"",preload:"none"}}),l=m("div",{class:"studio-actions"},[C(x(t,"addOverlay"),()=>{Un(e,s,!0)})]);["image","video"].includes(String(s.kind))&&l.prepend(C(x(t,"applyShot"),()=>{Un(e,s,!1)})),r.append(m("article",{class:"studio-media-card"},[i,m("strong",{text:a,title:a}),A(String(s.kind)),l]))}return r.children.length||r.append(A(x(t,"noMedia"))),m("div",{class:"studio-side-body"},[U(x(t,"media")),C(x(t,"upload"),()=>o.click(),"primary"),o,A(x(t,"importHint")),A(x(t,"chooseMaterial")),r])},qn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=m("div",{class:"studio-script-list"}),s=[];return $(G(o?.source).tracks).forEach((a,d)=>{a.type==="caption"&&$(a.cues).forEach((i,l)=>{s.push(String(i.text));let c=o?.resolved?.items.find(b=>b.cue?.track===a.id&&b.cue?.index===l),u=m("textarea",{class:"studio-input",attrs:{"aria-label":x(t,"subtitles")+" "+(l+1),rows:"2"}});u.value=String(i.text),u.addEventListener("change",()=>{n.send({op:"set",path:["tracks",d,"cues",l,"text"],value:u.value}),ce(t,x(t,"pendingVoice"))});let h=c?{kind:"item",id:c.id}:void 0,f=()=>{h&&n.reveal(h)};u.addEventListener("focus",f);let p=C(Ze(c?.start??0,o?.resolved?.canvas.fps??30),f),g=m("article",{class:"studio-sentence"+(h&&ge(h,t.get().pinned)?" selected":""),data:h?{selection:JSON.stringify(h)}:{}},[p,u]);g.addEventListener("click",f),r.append(g)})}),m("div",{class:"studio-side-body"},[U(x(t,"script")),A(x(t,"scriptHint"),"notice"),r,A(x(t,"narrationUnavailable")),C(x(t,"copyScript"),()=>{navigator.clipboard.writeText(s.join(\`
37683
- \`)).then(()=>ce(t,x(t,"sourceChanged")))})])},Gn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=Pt(e),s=m("div",{class:"studio-side-body"},[U(x(t,"elements"),r?.id)]);if(!o||!r)return s;s.append(C(x(t,"addText"),()=>{n.addText()}));for(let i of o.resolved?.items.filter(l=>l.end>r.start&&l.start<r.end)??[]){let l={kind:"item",id:i.id},c=C(i.text??x(t,i.type==="video"?"video":i.type==="image"?"image":i.type==="shape"?"color":"text"),()=>n.reveal(l),"studio-item"+(ge(l,t.get().pinned)?" selected":""));c.dataset.selection=JSON.stringify(l),s.append(c)}for(let i of o.resolved?.audio??[]){let l={kind:"audio",id:i.id},c=C(x(t,"audioTrack")+" \\xB7 "+i.id,()=>n.reveal(l),"studio-item"+(ge(l,t.get().pinned)?" selected":""));c.dataset.selection=JSON.stringify(l),s.append(c)}let a=He(document.querySelector("#page"),t,r.id),d=e.meta.slots.filter(i=>i.segment===r.id&&a?.has(i.name));s.append(U(x(t,"sceneFields")));for(let i of d){let l=t.get().pinned,c={kind:"slot",id:r.id,name:i.name},u=C("",()=>n.reveal(c,Qe(document.querySelector("#page"),t,c)),"studio-item "+(l?.kind==="slot"&&l.name===i.name?"selected":""));u.dataset.selection=JSON.stringify(c),u.append(m("span",{class:"studio-element-label",text:i.kind==="image"?x(t,"image"):i.value||i.name,title:i.value})),s.append(u)}return!d.length&&r.base.kind==="scene"&&s.append(A(x(t,"noSlots"))),s},Yn=e=>{let{store:t,actions:n}=e,o=t.get(),r=m("div",{class:"studio-side-body"},[U(x(t,"checks"))]);for(let a of o.state?.problems??[]){let d=m("article",{class:"studio-review-card"},[m("strong",{text:a.at}),A(a.message),A(a.fix??"")]),i=/^segments\\[(\\d+)\\]/.exec(a.at),l=i?o.state?.resolved?.segments[Number(i[1])]:void 0;l&&d.append(C(x(t,"goShot"),()=>Jn(e,l.id))),r.append(d)}o.state?.problems.length||r.append(A(x(t,"noProblems"))),r.append(A(o.state?.score?JSON.stringify(Object.fromEntries(Object.entries(o.state.score.dimensions).map(([a,d])=>[a,d.score.toFixed(2)]))):x(t,"unmeasured"))),r.append(U(x(t,"notes")));for(let a of e.meta.comments)r.append(m("article",{class:"studio-review-card"},[C(Ze(a.frame,o.state?.resolved?.canvas.fps??30),()=>{n.pause(),n.seek(a.frame)}),A(a.text),C(x(t,a.resolved?"reopen":"resolve"),()=>{ke(t,"/api/studio/comment",{id:a.id,resolved:!a.resolved}).then(e.refresh)})]));let s=m("textarea",{class:"studio-input",attrs:{rows:"3",placeholder:x(t,"noteHint")}});return r.append(s,C(x(t,"comment"),()=>{s.value.trim()&&ke(t,"/api/studio/comment",{text:s.value,frame:t.get().frame}).then(e.refresh)}),C(x(t,"copyNote"),()=>{navigator.clipboard.writeText(Ze(t.get().frame,o.state?.resolved?.canvas.fps??30)+" \\xB7 "+(Pt(e)?.id??"")+\`
37684
- \`+s.value)}),A(x(t,"reviewOnly"))),r},Xn=e=>{let{store:t}=e,n=m("div",{class:"studio-side-body"},[U(x(t,"versions"))]),o=Oe("",x(t,"versionName"));o.placeholder=x(t,"versionName"),n.append(o,C(x(t,"saveVersion"),()=>{ke(t,"/api/studio/version",{name:o.value||x(t,"newVersion")}).then(e.refresh)},"primary"),A(x(t,"versionSnapshot")));for(let r of e.meta.versions)n.append(m("article",{class:"studio-review-card"},[m("strong",{text:r.name}),A(new Date(r.created).toLocaleString()),...r.hash===e.meta.hash?[A(x(t,"current"))]:[C(x(t,"restore"),()=>{ke(t,"/api/studio/restore",{id:r.id,base:t.get().state?.source}).then(e.refresh)})]]));return e.meta.versions.length||n.append(A(x(t,"noVersions"))),n},Zn=()=>J("/api/studio");var Qn=(e,t)=>{let n=m("textarea",{id:"studio-json",class:"studio-json",attrs:{spellcheck:"false","aria-label":"video.json"}}),o=m("div",{class:"studio-code-status",attrs:{role:"status"}}),r,s,a=!1,d=!1,i,l=()=>{s=e.get().state?.source,n.value=JSON.stringify(s,null,2)??"",a=!1,o.textContent=x(e,"autosave")},c=async()=>{if(!a||d)return;let p;try{p=JSON.parse(n.value)}catch(y){o.textContent=x(e,"invalid")+": "+(y instanceof Error?y.message:"");return}d=!0,o.textContent=x(e,"saving");let g=n.value,b=await t.replace(p,s);d=!1,b?(s=e.get().state?.source,a=g!==n.value,o.textContent=x(e,"sourceChanged"),a&&setTimeout(()=>{u()},0)):o.textContent=e.get().edit.problems[0]?.message??x(e,"conflict")},u=()=>r??=c().finally(()=>{r=void 0});n.addEventListener("input",()=>{a=!0,i&&clearTimeout(i),i=setTimeout(()=>{u()},650)}),n.addEventListener("keydown",p=>{(p.ctrlKey||p.metaKey)&&p.key.toLowerCase()==="s"&&(p.preventDefault(),u()),p.key==="Tab"&&(p.preventDefault(),n.setRangeText(" ",n.selectionStart,n.selectionEnd,"end"),n.dispatchEvent(new Event("input")))}),window.addEventListener("beforeunload",p=>{a&&(p.preventDefault(),p.returnValue="")});let h=()=>{try{n.value=JSON.stringify(JSON.parse(n.value),null,2),n.dispatchEvent(new Event("input"))}catch{o.textContent=x(e,"invalid")}},f=m("div",{class:"studio-code-wrap"},[U(x(e,"sourceTitle"),"video.json"),A(x(e,"codeHint")),m("div",{class:"studio-actions"},[C(x(e,"format"),h),C(x(e,"download"),()=>rn(n.value,"video.json"))]),n,o,C(x(e,"reload"),l)]);return e.subscribe((p,g)=>{p.state?.source!==g.state?.source&&(!a&&!d?l():!d&&JSON.stringify(p.state?.source)!==JSON.stringify(s)&&(o.textContent=x(e,"conflict")))}),l(),{root:f,flush:async()=>(clearTimeout(i),r&&await r,a&&await u(),!a)}};var $n=(e,t,n)=>{let o=t.get().lang==="zh",r=(O,D)=>o?O:D,s=m("div",{class:"studio-cloud",id:"studio-cloud",attrs:{"aria-live":"polite"}});e.append(s);let a,d,i,l="push",c="",u="",h=!1,f=!1,p=!0,g,b=O=>({UNAUTHORIZED:r("\\u767B\\u5F55\\u5DF2\\u8FC7\\u671F\\u6216\\u5DF2\\u4F7F\\u7528\\uFF0C\\u8BF7\\u91CD\\u65B0\\u70B9\\u51FB\\u201C\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u201D\\u3002","The login expired or was already used. Save to Cloud again."),LOGIN_REQUIRED:r("\\u8BF7\\u5148\\u767B\\u5F55\\uFF0C\\u518D\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u3002","Sign in to save to cloud."),STORAGE_FULL:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),STORAGE_QUOTA_EXCEEDED:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),RATE_LIMITED:r("\\u4E0A\\u4F20\\u8FC7\\u4E8E\\u9891\\u7E41\\uFF0C\\u8BF7\\u7A0D\\u540E\\u518D\\u8BD5\\u3002","Too many uploads. Try again in a moment."),DECK_INVALID:r("\\u4E91\\u7AEF\\u65E0\\u6CD5\\u63A5\\u6536\\u8FD9\\u4E2A\\u4F5C\\u54C1\\u3002","The cloud could not accept this project."),NETWORK:r("\\u65E0\\u6CD5\\u8FDE\\u63A5 popost.ai\\u3002","Could not reach popost.ai."),LOCAL_SAVE_FAILED:r("\\u672C\\u5730\\u6539\\u52A8\\u4FDD\\u5B58\\u5931\\u8D25\\u3002\\u8BF7\\u5148\\u4FDD\\u5B58\\u4F5C\\u54C1\\uFF0C\\u518D\\u4E0A\\u4F20\\u5230\\u4E91\\u7AEF\\u3002","Could not save local edits. Save the project before uploading.")})[O??""]??r("\\u4E0A\\u4F20\\u5931\\u8D25\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","Upload failed. Try again."),y=(O,D=!1)=>m("span",{class:"studio-cloud-state"+(D?" bad":""),text:O,attrs:{role:"status"},title:d?.message??a?.error?.message??O}),v=()=>a?.webUrl?[m("a",{class:"studio-btn studio-icon-btn",attrs:{href:a.webUrl,target:"_blank",rel:"noopener noreferrer",title:r("\\u5728 popost \\u6253\\u5F00","Open in popost"),"aria-label":r("\\u5728 popost \\u6253\\u5F00","Open in popost")}},[Y("external")])]:[],E=O=>{d={code:"NETWORK",message:O instanceof Error?O.message:String(O)}},M=async()=>{try{a=await J("/api/cloud/status")}catch{}p&&(F(),clearTimeout(g),g=setTimeout(()=>{M()},i||a?.state==="waiting"||a?.state==="uploading"?2e3:5e3))},k=async()=>{if(i)return;let O=window.open("about:blank","_blank");l="start",d=void 0,f=!1,i="start",F();try{if(!await n()){O?.close(),d={code:"LOCAL_SAVE_FAILED",message:""};return}u=(await J("/api/studio/cloud/start",{lang:t.get().lang})).result.authorizeUrl,h=!O,O&&(O.opener=null,O.location.href=u),l="push",await M()}catch(D){O?.close(),E(D)}finally{i=void 0,await M()}},H=async(O=!1)=>{if(!i){l="push",d=void 0,i="push",F();try{if(!await n()){d={code:"LOCAL_SAVE_FAILED",message:""};return}a=(await J("/api/studio/cloud/push",{lang:t.get().lang,force:O})).result,!a.ok&&a.error?.code==="LOGIN_REQUIRED"&&(i=void 0,await k())}catch(D){E(D)}finally{i=void 0,await M()}}},L=async()=>{try{await navigator.clipboard.writeText(u),f=!0}catch{h=!0}F()},R=()=>{let O=d?.code??a?.error?.code;l==="start"||a?.mode==="anonymous"&&(O==="LOGIN_REQUIRED"||O==="UNAUTHORIZED")?k():H()},F=()=>{let O=JSON.stringify([a,d,i,u,h,f]);if(O===c||(c=O,s.hidden=a?.mode==="off",s.replaceChildren(),s.hidden))return;let D=i==="push"?"uploading":i==="start"?"starting":d?"failed":a?.state??"idle";if(D==="uploading"||D==="starting")s.append(y(D==="starting"?r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026"):a?.mode==="keyed"?r("\\u540C\\u6B65\\u4E2D\\u2026","Syncing\\u2026"):r("\\u4E0A\\u4F20\\u4E2D\\u2026","Uploading\\u2026")));else if(D==="waiting"){if(s.append(y(r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026")),ne(f?r("\\u94FE\\u63A5\\u5DF2\\u590D\\u5236","Link copied"):r("\\u590D\\u5236\\u94FE\\u63A5","Copy link"),"duplicate",()=>{L()})),h&&u){let w=m("input",{class:"studio-cloud-link",attrs:{readonly:"","aria-label":r("\\u767B\\u5F55\\u94FE\\u63A5","Login link")}});w.value=u,w.addEventListener("focus",()=>w.select()),s.append(w)}}else if(D==="saved")s.append(y(a?.mode==="keyed"?r("\\u5DF2\\u540C\\u6B65","Synced"):r("\\u5DF2\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Saved to cloud")),...v());else if(D==="failed")s.append(y(b(d?.code??a?.error?.code),!0),ne(r("\\u91CD\\u8BD5","Retry"),"refresh",R));else if(D==="conflict"){if(s.append(y(r("\\u7F51\\u9875\\u7AEF\\u5DF2\\u6709\\u4FEE\\u6539","Edited on the web"),!0),...v()),a?.mode==="keyed"){let w=ne(r("\\u8986\\u76D6","Overwrite"),"cloud",()=>{H(!0)});w.title=r("\\u7528\\u672C\\u5730\\u7248\\u672C\\u66FF\\u6362\\u7F51\\u9875\\u7AEF\\u7684\\u7248\\u672C","Replace the web copy with this local version"),s.append(w)}}else if(!a)s.append(y(r("\\u6B63\\u5728\\u68C0\\u67E5\\u8D26\\u53F7\\u2026","Checking account\\u2026")));else{let w=ne(a?.mode==="keyed"?r("\\u7ACB\\u5373\\u540C\\u6B65","Sync now"):a?.webUrl&&a.dirty?r("\\u672C\\u5730\\u6539\\u52A8\\u672A\\u4E0A\\u4F20","Local changes not uploaded"):r("\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Save to Cloud"),"cloud",()=>{a?.mode==="keyed"?H():k()});w.id="studio-cloud-save",w.disabled=!a,w.title=r("\\u5728 popost \\u7F51\\u9875\\u7AEF\\u7BA1\\u7406\\u4F60\\u7684\\u6240\\u6709\\u8D44\\u4EA7","Manage all your assets on the Popost website"),s.append(w)}};t.subscribe((O,D)=>{O.state?.source!==D.state?.source&&M()}),window.addEventListener("pagehide",()=>{p=!1,clearTimeout(g)}),F(),M()};var ct=(e,t,n)=>{if(t.kind==="segment"||t.track.type==="audio"||!T(e.source))return;let o=ee(e),r=o.map((p,g)=>({track:p,index:g})).filter(p=>p.track.type!=="audio").sort((p,g)=>Number(p.track.z??p.index)-Number(g.track.z??g.index)||p.index-g.index),s=e.resolved?.items.filter(p=>p.id===t.track.id||p.cue?.track===t.track.id)??[],a=new Set((e.resolved?.items??[]).filter(p=>s.some(g=>g.start<p.end&&g.end>p.start)).map(p=>p.cue?.track??p.id)),d=r.filter(p=>a.has(String(p.track.id))),i=d.findIndex(p=>p.index===t.index),l=d[i+n];if(!l)return;let c=r.findIndex(p=>p.index===t.index),u=r.indexOf(l);if(c<0||u<0||u>=r.length)return;let h=r.splice(c,1)[0];r.splice(u,0,h);let f=new Map(r.map((p,g)=>[p.index,g]));return{...e.source,tracks:o.map((p,g)=>f.has(g)?{...p,z:f.get(g)}:p)}};var eo=(e,t,n)=>{let o=m("input",{attrs:{type:"range",min:"100",max:"500",value:"100","aria-label":x(t,"zoom")}}),r=()=>e.parentElement?.style.setProperty("--timeline-zoom",String(Number(o.value)/100));o.addEventListener("input",r),r();let s=t.get().lang==="zh",a=(g,b)=>{let y=C(b,()=>{let v=t.get().timeline??{layers:!0,snapping:!0};t.set({timeline:{...v,[g]:!v[g]}})});return y.id="timeline-"+g,y},d=a("layers",s?"\\u56FE\\u5C42":"Layers");d.prepend(Y("layers"));let i=a("snapping",s?"\\u5438\\u9644":"Snap"),l=C(s?"\\u5206\\u5272":"Split",()=>{n.split()});l.id="edit-split";let c=g=>C(g<0?s?"\\u524D\\u79FB":"Earlier":s?"\\u540E\\u79FB":"Later",()=>{let b=n.target(),y=t.get().state;if(!(!y||!b))if(b.kind==="segment")n.send({op:"move",path:["segments",b.index],to:b.index+g});else{let v=ct(y,b,g);v&&n.replace(v,y.source)}}),u=c(-1),h=c(1);u.id="scene-earlier",h.id="scene-later";let f=m("span",{id:"timeline-selection",class:"timeline-selection"});e.append(m("span",{id:"edit-slot"}),l,u,h,m("span",{class:"timeline-divider"}),d,i,f,m("span",{class:"spacer"}),C(x(t,"viewAll"),()=>{o.value="100",r()}),o);let p=()=>{let g=t.get(),b=n.target();d.classList.toggle("selected",g.timeline?.layers!==!1),i.classList.toggle("selected",g.timeline?.snapping!==!1),d.setAttribute("aria-pressed",String(g.timeline?.layers!==!1)),i.setAttribute("aria-pressed",String(g.timeline?.snapping!==!1)),l.disabled=!!g.edit.saving||!n.canSplit(),u.hidden=h.hidden=!b||b.kind!=="segment"&&b.track.type==="audio",u.textContent=b?.kind==="segment"?s?"\\u524D\\u79FB":"Earlier":s?"\\u4E0B\\u79FB\\u56FE\\u5C42":"Send backward",h.textContent=b?.kind==="segment"?s?"\\u540E\\u79FB":"Later":s?"\\u4E0A\\u79FB\\u56FE\\u5C42":"Bring forward",u.disabled=b?.kind==="segment"?b.index===0:!(g.state&&b&&ct(g.state,b,-1)),h.disabled=b?.kind==="segment"?b.index>=(g.state?.resolved?.segments.length??0)-1:!(g.state&&b&&ct(g.state,b,1)),g.edit.saving&&(u.disabled=h.disabled=!0);let y=g.pinned,v=y?.kind==="slot"?g.slots?.find(M=>M.segment===y.id&&M.name===y.name):void 0,E=y?.kind==="item"?g.state?.resolved?.items.find(M=>M.id===y.id):void 0;f.textContent=y?y.kind==="slot"?v?.kind==="image"?s?"\\u56FE\\u7247":"Image":v?.value??x(t,"selected"):E?.text??(b?.kind==="segment"?(s?"\\u955C\\u5934 ":"Shot ")+(b.index+1):y.kind==="audio"?x(t,"audioTrack"):x(t,"selected")):s?"\\u70B9\\u9009\\u955C\\u5934\\u6216\\u753B\\u9762\\u5185\\u5BB9\\u8FDB\\u884C\\u7F16\\u8F91":"Select a shot or canvas element to edit",f.title=f.textContent};t.subscribe((g,b)=>{g.state!==b.state||g.pinned!==b.pinned||g.timeline!==b.timeline||g.slots!==b.slots||g.edit.saving!==b.edit.saving?p():g.frame!==b.frame&&(l.disabled=!!g.edit.saving||!n.canSplit())}),p()};var to=(e,t)=>{let n=e.get().lang==="zh",o=(g,b)=>n?g:b,r=t.target==="jianying"?o("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro"):"CapCut",s=!1,a=()=>{s||(i.remove(),d.remove(),document.getElementById("studio-export-open")?.focus())},d=m("div",{class:"studio-scrim",on:{click:a}}),i=m("aside",{class:"studio-export studio-draft-success",attrs:{role:"dialog","aria-modal":"true","aria-label":o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r}}),l=A(t.productRunning?o("\\u91CD\\u542F"+r+"\\u5373\\u53EF\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u770B\\u5230\\u300C"+t.name+"\\u300D\\u3002","Restart "+r+" to find \\u201C"+t.name+"\\u201D in local drafts."):o("\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u8349\\u7A3F\\uFF0C\\u6253\\u5F00"+r+"\\u5373\\u53EF\\u67E5\\u770B\\u300C"+t.name+"\\u300D\\u3002","Open "+r+" to find \\u201C"+t.name+"\\u201D in local drafts.")),c=m("div",{attrs:{role:"status"}}),u=C(o("\\u7A0D\\u540E","Later"),a),h=C("\\xD7",a);h.setAttribute("aria-label",o("\\u5173\\u95ED","Close"));let f=t.productRunning?o("\\u91CD\\u542F","Restart ")+r:o("\\u6253\\u5F00","Open ")+r,p=C(f,()=>{(async()=>{s=!0,p.disabled=u.disabled=h.disabled=!0,p.textContent=o("\\u6B63\\u5728\\u6253\\u5F00\\u2026","Opening\\u2026"),c.replaceChildren();try{let g=await J("/api/studio/draft-open",{receiptId:t.receiptId});if(!g.result.ok){c.replaceChildren(A(g.result.quitPending?o(r+"\\u8FD8\\u672A\\u9000\\u51FA\\uFF0C\\u8BF7\\u5148\\u5728\\u5E94\\u7528\\u4E2D\\u4FDD\\u5B58\\u6216\\u5173\\u95ED\\u5F39\\u7A97\\uFF0C\\u7136\\u540E\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002",r+" has not exited. Save your work or close its dialog, then retry. Your draft is already saved."):g.result.message??o("\\u5E94\\u7528\\u672A\\u80FD\\u6253\\u5F00\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002","The editor did not open. Retry; your draft is already saved."),"bad"));return}s=!1,a(),ce(e,g.result.restarted?o("\\u5DF2\\u91CD\\u542F","Restarted ")+r:o("\\u5DF2\\u6253\\u5F00","Opened ")+r)}catch(g){c.replaceChildren(A(String(g),"bad"))}finally{s=!1,p.disabled=u.disabled=h.disabled=!1,p.textContent=f}})()},"primary");t.canOpen||c.append(A(o("\\u672A\\u627E\\u5230\\u5E94\\u7528\\u5B89\\u88C5\\u4F4D\\u7F6E\\uFF0C\\u53EF\\u4EE5\\u7A0D\\u540E\\u624B\\u52A8\\u6253\\u5F00\\u3002\\u8349\\u7A3F\\u548C\\u7D20\\u6750\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u3002","The app location could not be found. Open it manually later; the draft and media are saved locally."))),i.append(m("div",{class:"studio-export-header"},[U(o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r),h]),l,c,m("div",{class:"studio-draft-actions"},[u,...t.canOpen?[p]:[]])),document.body.append(d,i),i.addEventListener("keydown",g=>{if(g.key==="Escape"&&a(),g.key!=="Tab")return;let b=Array.from(i.querySelectorAll("button:not(:disabled)")),y=b[0],v=b[b.length-1];g.shiftKey&&document.activeElement===y?(g.preventDefault(),v?.focus()):!g.shiftKey&&document.activeElement===v&&(g.preventDefault(),y?.focus())}),(t.canOpen?p:u).focus()};var Ct=(e,t)=>{if(document.getElementById("studio-export"))return;let n=e.get().state;if(!n?.resolved||!n.edit)return;let o=n.resolved,r=e.get().lang==="zh",s=(P,V)=>r?P:V,a="video",d="jianying",i="1080",l="",c="",u=!1,h=!1,f,p=!1,g,b,y=m("div",{class:"studio-export-result",attrs:{role:"status"}}),v=m("div",{class:"studio-paid-info"}),E,M=m("progress",{attrs:{max:"1",value:"0",hidden:""}}),k=m("fieldset",{class:"studio-export-fields"}),H=m("div",{class:"studio-segments export-tabs",attrs:{role:"tablist"}}),L=m("aside",{id:"studio-export",class:"studio-export",attrs:{role:"dialog","aria-modal":"true","aria-label":s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")}}),R=()=>{h||(document.removeEventListener("keydown",F,!0),so(),O.remove(),L.remove(),document.getElementById("studio-export-open")?.focus())},F=P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),R())},O=m("div",{class:"studio-scrim",on:{click:R}}),D=(P,V,I)=>m("div",{class:"studio-segments"},P.map(([me,de])=>{let Ot=C(de,()=>I(me),me===V?"selected":"");return Ot.setAttribute("aria-pressed",String(me===V)),Ot})),w=(P,V)=>(V.setAttribute("role","group"),V.setAttribute("aria-label",P),m("div",{class:"studio-field"},[m("span",{text:P}),V])),N=()=>{if(v.hidden=a!=="video",H.replaceChildren(...[["video",x(e,"video")],["draft",s("\\u526A\\u6620","Draft")]].map(([I,me])=>{let de=C(me,()=>{a=I,y.replaceChildren(),N(),B()},a===I?"selected":"");return de.setAttribute("role","tab"),de.setAttribute("aria-selected",String(a===I)),de})),a==="draft"){let I=m("details",{},[m("summary",{text:s("\\u90E8\\u5206\\u5185\\u5BB9\\u4E0D\\u652F\\u6301","Some content is flattened")}),A(s("\\u652F\\u6301\\uFF1A\\u5B57\\u5E55\\u6587\\u5B57\\u4E0E\\u65F6\\u95F4\\u3001\\u89C6\\u9891\\u7247\\u6BB5\\u3001\\u97F3\\u9891\\u7247\\u6BB5\\u3002\\u5B57\\u5E55\\u6837\\u5F0F\\u9700\\u5728\\u76EE\\u6807\\u7F16\\u8F91\\u5668\\u4E2D\\u91CD\\u65B0\\u8BBE\\u7F6E\\uFF1B\\u590D\\u6742\\u89C6\\u89C9\\u6548\\u679C\\u70D8\\u7119\\u5230\\u5404\\u4E2A\\u89C6\\u9891\\u7247\\u6BB5\\u3002","Supported: caption text/timing, video clips and audio clips. Reapply caption styles in the target editor. Complex visuals are baked per clip."))]),me=g?.find(de=>de.target===d);k.replaceChildren(A(s("\\u628A\\u5F53\\u524D\\u65F6\\u95F4\\u7EBF\\u76F4\\u63A5\\u4FDD\\u5B58\\u4E3A\\u672C\\u673A\\u5E94\\u7528\\u4E2D\\u53EF\\u7EE7\\u7EED\\u7F16\\u8F91\\u7684\\u8349\\u7A3F\\u3002","Save the current timeline directly into your desktop editor\\u2019s local drafts.")),A(s("\\u5BFC\\u51FA\\u6210\\u529F\\u540E\\u53EF\\u4E00\\u952E\\u91CD\\u542F\\u5E94\\u7528\\uFF0C\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u4E2D\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002","After export, restart the app with one click and continue editing from local drafts.")),w(s("\\u5E94\\u7528","Application"),D([["jianying",s("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro")],["capcut","CapCut"]],d,de=>{d=de,b=void 0,N(),B()})),I),g?me?.usable||k.append(A(me?.error??s("\\u8BF7\\u5728\\u8FD0\\u884C\\u6B64\\u7F16\\u8F91\\u5668\\u7684\\u7535\\u8111\\u4E0A\\u5B89\\u88C5\\u5E76\\u6253\\u5F00\\u6240\\u9009\\u5E94\\u7528\\uFF0C\\u518D\\u91CD\\u65B0\\u6253\\u5F00\\u5BFC\\u51FA\\u8BBE\\u7F6E\\u3002","Install and open the selected app on the computer running this editor, then reopen export settings."),"bad")):k.append(A(s("\\u6B63\\u5728\\u68C0\\u67E5\\u672C\\u673A\\u5E94\\u7528\\u2026","Checking desktop editors\\u2026")));return}let P=D([["480","480p"],["720","720p"],["1080","1080p"],["2160","4K"]],i,I=>{i=I,N(),B()}),V=m("button",{text:"HDR",attrs:{type:"button",disabled:"",title:x(e,"hdrUnavailable")}});if(k.replaceChildren(w(x(e,"dynamicRange"),m("div",{class:"studio-segments"},[C("SDR",()=>{},"selected"),V])),w(x(e,"resolution"),P),Me(x(e,"fps"),wt([["",x(e,"match")+" ("+o.canvas.fps+" fps)"],...[24,25,30,50,60].map(I=>[String(I),I+" fps"])],l,x(e,"fps"),I=>{l=I})),Me(s("\\u89C6\\u9891\\u7801\\u7387","Video bitrate"),wt([["",x(e,"recommended")],...[2,5,8,12,20,40].map(I=>[String(I),I+" Mbps"])],c,x(e,"bitrate"),I=>{c=I}))),v.replaceChildren(),!u){let I=P.lastElementChild;I&&I.append(m("span",{class:"export-pro",text:"PRO"}))}i==="2160"&&!u&&v.append(A(s("4K \\u4E3A\\u4ED8\\u8D39\\u5206\\u8FA8\\u7387\\u3002\\u5347\\u7EA7\\u5957\\u9910\\u540E\\u5373\\u53EF\\u5BFC\\u51FA\\uFF1B1080p \\u53CA\\u4EE5\\u4E0B\\u53EF\\u7EE7\\u7EED\\u4F7F\\u7528\\u3002","4K requires a paid plan. Upgrade to export in 4K, or choose 1080p or below.")),...E?[m("a",{class:"studio-btn",text:x(e,"unlock"),attrs:{href:E,target:"_blank",rel:"noopener"}})]:[A(x(e,"loading"))],C(x(e,"refreshPlan"),()=>{J("/api/export-options").then(I=>{u=I.premium,N(),B()})}))},z=C(s("\\u5BFC\\u51FA","Export"),()=>{(async()=>{try{if(a==="draft"){h=!0,B(),b??=crypto.randomUUID();let P=await J("/api/studio/draft",{target:d,requestId:b});h=!1,R(),to(e,P.result)}else{f=void 0,p=!1;let P=await J("/api/render",{name:"Popost-video",resolution:i,dynamicRange:"sdr",fps:l?Number(l):null,bitrate:c?Number(c):null,audio:!0});f=P.render.state==="running"?P.render.started:P.render.state==="done"||P.render.state==="failed"?P.render.finished:void 0,t.setRender(P.render)}}catch(P){y.replaceChildren(A(String(P),"bad"))}finally{h=!1,B()}})()},"primary"),B=()=>{let P=e.get().edit.render,V=h||a==="video"&&P?.state==="running";if(k.disabled=V,z.disabled=V||a==="video"&&i==="2160"&&!u||a==="draft"&&!g?.find(I=>I.target===d)?.usable,K.disabled=h,H.querySelectorAll("button").forEach(I=>{I.disabled=V}),M.hidden=!V,z.textContent=V?s("\\u6B63\\u5728\\u5BFC\\u51FA\\u2026","Exporting\\u2026"):s("\\u5BFC\\u51FA","Export"),a==="draft"){h&&M.removeAttribute("value");return}P?.state==="running"&&(M.value=P.total?P.frame/P.total:0,y.replaceChildren()),P?.state==="failed"&&y.replaceChildren(A(P.message,"bad")),P?.state==="done"&&f!==void 0&&P.finished>=f&&(f!==void 0&&P.finished>=f&&!p&&(p=!0,m("a",{attrs:{href:P.url,download:"Popost-video.mp4"}}).click()),y.replaceChildren(A(s("\\u5BFC\\u51FA\\u5B8C\\u6210\\uFF0C\\u89C6\\u9891\\u5DF2\\u4FDD\\u5B58\\u5E76\\u5F00\\u59CB\\u4E0B\\u8F7D\\u3002","Export complete. The video is saved and downloading."))))},K=C("\\xD7",R);L.append(m("div",{class:"studio-export-header"},[U(s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")),K]),H,k,v,M,z,y),document.body.append(O,L),N(),B(),J("/api/export-options").then(P=>{u=P.premium,E=P.pricingUrl??E,N(),B()}).catch(()=>{}),J("/api/studio/draft-targets",{}).then(P=>{g=P.result.applications,N(),B()}).catch(P=>{g=[],y.replaceChildren(A(String(P),"bad")),N(),B()});let so=e.subscribe((P,V)=>{L.isConnected&&P.edit.render!==V.edit.render&&B()});document.addEventListener("keydown",F,!0),z.focus()};var Ar=[["media","media","media"],["elements","elements","layers"],["script","subtitles","text"],["code","code","code"]],no=(e,t,n,o)=>{let r="media",s=m("nav",{class:"studio-rail",attrs:{"aria-label":"Studio"}}),a=m("aside",{id:"studio-content",class:"studio-content"}),d=Qn(t,o),i=d.root,l={store:t,actions:n,edit:o,meta:{hash:"",slots:[],versions:[],comments:[]},refresh:()=>{}},c=()=>{let w=document.querySelector("#page"),N=new Map([...new Set(l.meta.slots.map(K=>K.segment))].map(K=>[K,He(w,t,K)])),z=l.meta.slots.filter(K=>N.get(K.segment)?.has(K.name));if(JSON.stringify(z)!==JSON.stringify(t.get().slots)&&t.set({slots:z}),s.querySelectorAll("button").forEach(K=>{K.classList.toggle("active",K.dataset.panel===r),K.setAttribute("aria-pressed",String(K.dataset.panel===r))}),document.body.classList.toggle("panel-code",r==="code"),r==="code"){a.contains(i)||a.replaceChildren(i);return}let B={shots:At,media:Wn,script:qn,elements:Gn,checks:Yn,versions:Xn};a.replaceChildren(B[r](l))},u=w=>{r=w,c()};for(let[w,N,z]of Ar){let B=m("button",{data:{panel:w},attrs:{type:"button",title:x(t,N)},on:{click:()=>u(w)}},[Y(z),m("span",{text:x(t,N)})]);s.append(B)}let h=async()=>{let w=t.get().state?.generation;try{let N=await Zn();if(w!==t.get().state?.generation)return;l.meta=N,N.lastExport&&t.get().edit.render?.state!=="running"&&(!t.get().edit.render||t.get().edit.render?.state==="idle")&&o.setRender(N.lastExport),c()}catch{}};l.refresh=()=>{h()},e.prepend(s,a);let f=document.querySelector(".studio-topbar"),p=m("strong",{class:"studio-brand",text:"popost"}),g=m("span",{class:"studio-project"}),b=m("span",{class:"studio-save"}),y=m("span",{class:"studio-global-actions"}),v=ne(x(t,"compare"),"compare",()=>{if(!t.get().state?.reference){ce(t,x(t,"noReference"));return}t.get().edit.playRender&&o.togglePlayRender(),t.set({compare:!t.get().compare})});v.id="studio-compare";let E=ne(x(t,"layout"),"layout",()=>{let w=document.body.classList.toggle("focus-preview");E.setAttribute("aria-pressed",String(w))});E.setAttribute("aria-pressed","false");let M=ne(x(t,"theme"),"theme",()=>{let w=document.documentElement.classList.toggle("dark");M.setAttribute("aria-pressed",String(w)),localStorage.setItem("popost-studio-theme",w?"dark":"light")});M.setAttribute("aria-pressed",String(localStorage.getItem("popost-studio-theme")==="dark"));let k=ne(t.get().lang==="zh"?"English":"\\u4E2D\\u6587","language",()=>{let w=t.get().lang==="zh"?"en":"zh";localStorage.setItem("popost-studio-language",w),n.setLang(w),location.reload()});k.id="lang-toggle";let H=ne(x(t,"versions"),"history",()=>u("versions")),L=ne(x(t,"export"),"download",()=>Ct(t,o));L.id="studio-export-open",y.append(v,E,H,M,k),$n(y,t,async()=>await o.flush()?await d.flush()&&await o.flush():!1),y.append(L),f.append(p,g,b,y),document.documentElement.classList.toggle("dark",localStorage.getItem("popost-studio-theme")==="dark"),document.addEventListener("studio:export",()=>Ct(t,o));let R=document.getElementById("studio-stage-heading"),F=m("input",{attrs:{type:"checkbox","aria-label":x(t,"audio")}});F.checked=!0,F.addEventListener("change",()=>t.set({muted:!F.checked})),R.append(m("span",{text:x(t,"preview")}),m("label",{class:"studio-check",title:x(t,"onlyPreview")},[F,x(t,"audio")]));let O=document.querySelector(".panel");O.prepend(U(x(t,"properties")));let D=()=>{let w=t.get();document.body.setAttribute("aria-busy",String(!!w.edit.saving)),g.textContent=w.state?.project.name??"Popost Video Studio",b.textContent=w.connected?w.state?.edit?x(t,"saved"):x(t,"readOnly"):x(t,"offline"),w.edit.saving&&(b.textContent=x(t,"saving")),w.edit.status?.kind==="refused"&&(b.textContent=x(t,"error")),v.classList.toggle("selected",!!w.compare),v.setAttribute("aria-pressed",String(!!w.compare)),L.disabled=!w.state?.edit||!w.state.resolved,O.hidden=!w.pinned,document.body.classList.toggle("inspecting",!!w.pinned)};return t.subscribe((w,N)=>{if((w.state!==N.state||w.pinned!==N.pinned||w.compare!==N.compare||w.connected!==N.connected||w.edit.status!==N.edit.status||w.edit.saving!==N.edit.saving)&&D(),w.state!==N.state?(c(),h()):w.frame!==N.frame&&r==="elements"&&w.state?.resolved?.segments.find(z=>w.frame>=z.start&&w.frame<z.end)?.id!==N.state?.resolved?.segments.find(z=>N.frame>=z.start&&N.frame<z.end)?.id&&c(),w.pinned!==N.pinned&&w.pinned){let z=w.state?q(w.state,w.pinned):void 0,B=w.pinned.kind==="segment"?"media":z?.kind==="cue"?"script":"elements";B==="media"&&(l.mediaView="shots");let K=a.contains(document.activeElement);(r!==B||!K)&&(r=B,c())}w.pinned!==N.pinned&&a.querySelectorAll("[data-selection]").forEach(z=>{let B=z.dataset.selection===JSON.stringify(w.pinned);z.classList.toggle("selected",B),z.tagName==="BUTTON"&&z.setAttribute("aria-pressed",String(B)),B&&z.scrollIntoView({block:"nearest"})})}),document.addEventListener("studio:page-ready",c),document.addEventListener("studio:scene-ready",()=>{r==="elements"&&c()}),D(),c(),{refresh:h,choose:u,content:a,panel:()=>r}},oo=eo,ut=(e,t)=>{let n=t==="timeline",o=m("div",{class:"studio-handle "+(n?"horizontal":"vertical")+(t==="right"?" inspector-resize":""),attrs:{role:"separator",tabindex:"0","aria-orientation":n?"horizontal":"vertical"}});return n||(o.style.left=t==="left"?"calc(64px + var(--left-width) - 2px)":"calc(100% - var(--right-width) - 2px)"),o.addEventListener("pointerdown",r=>{o.setPointerCapture(r.pointerId);let s=n?r.clientY:r.clientX,a=n?"--timeline-height":t==="left"?"--left-width":"--right-width",d=parseFloat(getComputedStyle(document.documentElement).getPropertyValue(a)),i=c=>{let u=(n?c.clientY:c.clientX)-s,h=Math.min(n?innerHeight*.65:innerWidth*.4,Math.max(n?150:210,d+(t==="left"?u:-u)));document.documentElement.style.setProperty(a,h+"px")},l=()=>{o.removeEventListener("pointermove",i),o.removeEventListener("pointerup",l),localStorage.setItem("popost-studio-layout",document.documentElement.style.cssText)};o.addEventListener("pointermove",i),o.addEventListener("pointerup",l)}),e.append(o),o};var Cr=async()=>{let e=await fetch("/api/state",{cache:"no-store"});if(!e.ok)throw new Error("GET /api/state answered "+e.status);return await e.json()},Or=["boxes","events","safe"],Hr=(e,t)=>{let n=m("h1"),o=m("span",{class:"project",id:"project"}),r=m("span",{class:"status",id:"status"}),s=Or.map(i=>{let l=m("input",{id:"toggle-"+i,attrs:{type:"checkbox"}});l.addEventListener("change",()=>{t.toggleOverlay(i),l.blur()});let c=m("span");return{name:i,input:l,text:c,el:m("label",{class:"toggle"},[l,c])}}),a=m("button",{id:"lang-toggle",class:"tbtn",attrs:{type:"button"}});a.addEventListener("click",()=>{t.setLang(e.get().lang==="en"?"zh":"en"),a.blur()});let d=i=>{let l=i.state;n.textContent=S(i.lang,"title"),o.textContent=l?l.project.name+(l.resolved?" "+l.resolved.frames+"f, "+(l.resolved.frames/l.resolved.canvas.fps).toFixed(2)+" s":""):"",o.title=l?.project.dir??"",r.textContent=S(i.lang,l?.edit?"editing":"readOnly")+", "+S(i.lang,i.connected?"live":"offline"),r.classList.toggle("offline",!i.connected),s.forEach(c=>{c.text.textContent=S(i.lang,c.name),c.input.checked=i.overlays[c.name]}),a.textContent=S(i.lang,"language"),a.title=S(i.lang,"languageTitle")};return d(e.get()),e.subscribe((i,l)=>{(i.state!==l.state||i.lang!==l.lang||i.connected!==l.connected||i.overlays!==l.overlays)&&d(i)}),m("header",{},[n,o,...s.map(i=>i.el),m("span",{id:"edit-slot",class:"edit-slot"}),r,a])},Nr=(e,t)=>{document.body.classList.add("editing");let n=document.getElementById("edit-slot");n&&tt(n,e.store,e.edit),nt(e.panel,e.store,e.edit);let o=et(e.stage.frameBox,e.stage.iframe,e.store,e.edit);Ge(e.lanes,e.store,e.edit),ot(e.store,e.edit,o.nudge),We(e.store);let r=Je(t);r&&e.edit.select(r),t.edit&&t.edit.render.state!=="idle"&&e.edit.setRender(t.edit.render),e.events.addEventListener(je,s=>e.edit.setRender(JSON.parse(s.data))),Xe().then(s=>e.store.set({edit:{...e.store.get().edit,schema:s}}))},ro=()=>{let e=Ue(navigator.language);document.documentElement.lang=e==="zh"?"zh-CN":"en";let t=_e({state:null,frame:0,playing:!1,speed:1,lang:e,pinned:null,overlays:{boxes:!1,events:!0,safe:!1},connected:!0,pageError:null,edit:Ve}),n=Ke(t),o=qe(t,n),r=document.getElementById("app")??document.body,s=m("div",{class:"stage-area",id:"stage"}),a=m("div",{class:"transport",id:"transport"}),d=m("div",{class:"timeline",id:"timeline"}),i=m("aside",{class:"panel",id:"panel"});r.append(Hr(t,n),m("div",{class:"main"},[m("div",{class:"left"},[s,a,d]),i]));let l=dt(s,t,n);lt(a,t,n),rt(d,t,n),it(i,t,n,o);let c=new EventSource("/api/events"),u=!1,h=async()=>{try{let f=await Cr(),p=t.get();if(p.connected&&p.state&&f.generation<p.state.generation)return;t.set({state:f,frame:pe(t.get().frame,W(f)),connected:!0}),f.edit&&!u&&(u=!0,Nr({store:t,edit:o,stage:l,lanes:d.querySelector("#lanes")??d,panel:i,events:c},f))}catch{t.set({connected:!1})}};c.addEventListener(De,()=>{h()}),c.addEventListener("open",()=>{t.get().connected||h()}),c.addEventListener("error",()=>{t.get().connected&&t.set({connected:!1})}),h()};var Ir=()=>{let e=localStorage.getItem("popost-studio-language"),t=e==="zh"||e==="en"?e:Ue(navigator.language);document.documentElement.lang=t==="zh"?"zh-CN":"en",document.body.classList.add("studio");let n=localStorage.getItem("popost-studio-layout");n&&/^[-a-z0-9:;. %px]+$/i.test(n)&&(document.documentElement.style.cssText=n);let o=_e({state:null,frame:0,playing:!1,speed:1,lang:t,pinned:null,compare:!1,muted:!1,timeline:{layers:!1,snapping:!0},overlays:{boxes:!1,events:!1,safe:!1},connected:!0,pageError:null,edit:Ve}),r=Ke(o),s=qe(o,r),a=document.getElementById("app")??document.body,d=m("header",{class:"studio-topbar"}),i=m("div",{class:"stage-area",id:"stage"}),l=m("div",{class:"transport",id:"transport"}),c=m("div",{class:"timeline",id:"timeline"}),u=m("aside",{class:"panel",id:"panel"}),h=m("div",{class:"main"},[m("div",{class:"left"},[m("div",{id:"studio-stage-heading",class:"studio-stage-heading"}),i,l]),u]),f=m("div",{class:"studio-timeline-toolbar"}),p=m("div",{class:"studio-timeline-wrap"},[f,c]),g=m("footer",{class:"studio-footer"},["Popost Video Studio","video.json"]);a.append(d,h,p,g,m("div",{id:"studio-message",attrs:{role:"status"}})),no(h,o,r,s),oo(f,o,s),ut(h,"left"),ut(h,"right"),ut(p,"timeline");let b=dt(i,o,r);lt(l,o,r),rt(c,o,r),it(u,o,r,s),gn(o);let y=new EventSource("/api/events"),v=!1,E=async()=>{try{let M=await fetch("/api/state",{cache:"no-store"});if(!M.ok)throw new Error;let k=await M.json(),H=o.get();if(H.connected&&H.state&&k.generation<H.state.generation)return;if(o.set({state:k,frame:pe(H.frame,W(k)),connected:!0}),k.edit&&!v){v=!0,document.body.classList.add("editing"),tt(document.getElementById("edit-slot"),o,s),nt(u,o,s);let L=et(b.frameBox,b.iframe,o,s);Ge(c.querySelector("#lanes")??c,o,s),ot(o,s,L.nudge),We(o);let R=Je(k);R&&s.select(R),k.edit.render.state!=="idle"&&s.setRender(k.edit.render),Xe().then(F=>o.set({edit:{...o.get().edit,schema:F}}))}}catch{o.set({connected:!1})}};y.addEventListener(De,()=>{E()}),y.addEventListener(je,M=>s.setRender(JSON.parse(M.data))),y.addEventListener("open",()=>{o.get().connected||E()}),y.addEventListener("error",()=>{o.get().connected&&o.set({connected:!1})}),E()};document.documentElement.dataset.mode==="readonly"?ro():Ir();})();
37954
+ SHELL_BUNDLE = `"use strict";(()=>{var De="reload",je="render";var ao=new Set(["wipe","slide","whip"]),se=e=>e.resolved?.canvas.fps??e.measure?.measure.source.fps??e.referenceMeasure?.measure.source.fps??30,ye=(e,t,n)=>e*n/t,io=(e,t,n)=>Math.floor((e+.5)*n/t),W=e=>{if(e.resolved)return e.resolved.frames;let t=se(e),n=[e.measure,e.referenceMeasure].map(o=>o?Math.round(ye(o.measure.source.frames,o.measure.source.fps,t)):0);return Math.max(0,...n)},pe=(e,t)=>Math.min(Math.max(0,t-1),Math.max(0,Math.round(e))),Z=(e,t)=>e.segments.find(n=>t>=n.start&&t<n.end),fe=(e,t)=>e.items.filter(n=>t>=n.start&&t<n.end),Nt=e=>[e.kind,e.frames+"f",ao.has(e.kind)?e.direction:"",e.kind==="slide"?e.mode:"",e.kind==="fade"?"via "+e.via:"",e.side&&e.side!=="both"?e.side:"",e.strength!==void 0&&e.strength!==1?"x"+e.strength:""].filter(Boolean).join(" "),Te=e=>e.preset+" "+e.frames+"f"+(e.preset==="slide"||e.preset==="wipe"?" "+e.direction:""),It=e=>[e.kind,e.kind==="cut"?"":e.end-e.start-1+"f",e.direction??"",e.mode??"",e.via?"via "+e.via:"",e.confidence.toFixed(2)].filter(Boolean).join(" "),ze=e=>[e.kind,e.how??"",e.direction??""].filter(Boolean).join(" "),Ft=e=>e.shots.flatMap((t,n)=>t.events.map((o,r)=>({shot:n,index:r,event:o}))).sort((t,n)=>t.event.start-n.event.start||t.shot-n.shot),Dt=(e,t,n)=>{let o=io(t,n,e.source.fps);return e.shots.flatMap(r=>r.events.filter(s=>o>=s.start&&o<s.end))},mt=(e,t)=>{let n=[];return e.map(o=>{let r=n.findIndex(a=>a<=o.start),s=r>=0?r:Math.min(n.length,t-1);return n[s]=Math.max(n[s]??0,o.end),{row:s,...o}})},jt=(e,t)=>{let n=e/t,o=[.5,1,2,5,10,15,30,60,120,300].find(s=>n/s<=12)??600,r=Math.floor(n/o);return Array.from({length:r+1},(s,a)=>({frame:Math.round(a*o*t),label:String(Number((a*o).toFixed(1)))+"s"}))},zt=e=>e.height>e.width?[.06,.08,.82,.72]:[.05,.05,.9,.9],pt=(e,t)=>(e/t).toFixed(2)+" s",ge=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ht=(e,t)=>(t==="render"?e.measure:e.referenceMeasure)?.measure,Bt=(e,t)=>{switch(t.kind){case"slot":return;case"segment":return e.resolved?.segments.find(n=>n.id===t.id);case"item":return e.resolved?.items.find(n=>n.id===t.id);case"audio":return e.resolved?.audio.find(n=>n.id===t.id);case"boundary":return Ht(e,t.source)?.boundaries[t.index];case"event":return Ht(e,t.source)?.shots[t.shot]?.events[t.index]}},Vt=e=>{switch(e.kind){case"slot":return e.name;case"segment":case"item":case"audio":return e.kind+" "+e.id;case"boundary":return e.source+" boundary "+(e.index+1);case"event":return e.source+" event "+(e.shot+1)+"."+(e.index+1)}};var Ve={schema:null,status:null,problems:[],render:null,playRender:!1},_e=e=>{let t=e,n=[];return{get:()=>t,set:o=>{let r=t;t={...t,...o},n.forEach(s=>s(t,r))},subscribe:o=>(n.push(o),()=>{let r=n.indexOf(o);r>=0&&n.splice(r,1)})}},_t=[.25,.5,1],Be=e=>e.state?W(e.state):0,lo=e=>e.state?se(e.state):30,co=e=>{let t={frame:0,time:0},n=0,o=s=>{let a=e.get();if(!a.playing)return;let c=Math.max(0,Be(a)-1),i=Math.min(c,t.frame+Math.floor((s-t.time)/1e3*lo(a)*a.speed));if(i>=c)return e.set({frame:c,playing:!1});i!==a.frame&&e.set({frame:i}),n=requestAnimationFrame(o)},r=()=>{t={frame:e.get().frame,time:performance.now()}};return{reanchor:r,pause:()=>{cancelAnimationFrame(n),e.get().playing&&e.set({playing:!1})},play:()=>{let s=e.get();Be(s)<2||(s.frame>=Be(s)-1&&e.set({frame:0}),r(),e.set({playing:!0}),n=requestAnimationFrame(o))}}},Ke=e=>{let t=co(e),n=o=>{e.set({frame:pe(o,Be(e.get()))}),t.reanchor()};return{seek:n,step:o=>n(e.get().frame+o),togglePlay:()=>e.get().playing?t.pause():t.play(),pause:t.pause,setSpeed:o=>{e.set({speed:o}),t.reanchor()},pin:o=>e.set({pinned:o}),toggleOverlay:o=>{let r=e.get().overlays;e.set({overlays:{...r,[o]:!r[o]}})},setLang:o=>{document.documentElement.lang=o==="zh"?"zh-CN":"en",e.set({lang:o})}}};var u=(e,t={},n=[])=>{let o=document.createElement(e);t.class&&(o.className=t.class),t.id&&(o.id=t.id),t.text!==void 0&&(o.textContent=t.text),t.title&&(o.title=t.title),t.style&&(o.style.cssText=t.style);for(let[r,s]of Object.entries(t.attrs??{}))o.setAttribute(r,s);for(let[r,s]of Object.entries(t.data??{}))o.dataset[r]=s;for(let[r,s]of Object.entries(t.on??{}))s&&o.addEventListener(r,s);return o.append(...n),o},Kt="http://www.w3.org/2000/svg",uo={film:"M2 2h12v12H2zM5 2v12M11 2v12M2 6h3M2 10h3M11 6h3M11 10h3",media:"M2 2h12v12H2zM2 12l4-5 4 4 2-2 2 3M5 4h.1",text:"M2 3h12M8 3v11M5 14h6",layers:"M1 5l7-4 7 4-7 4-7-4M1 8l7 4 7-4M1 11l7 4 7-4",code:"M5 3 1 8l4 5M11 3l4 5-4 5M9 2 7 14",checks:"M8 1l6 2v5c0 4-6 7-6 7S2 12 2 8V3l6-2M5 8l2 2 4-4",first:"M4 3v10M12 3.5 6 8l6 4.5z",last:"M12 3v10M4 3.5 10 8l-6 4.5z",play:"M5 3l8 5-8 5z",pause:"M5.5 3v10M10.5 3v10",undo:"M6 3.5 3 6.5l3 3M3 6.5h6.5a3.5 3.5 0 0 1 0 7H7",redo:"M10 3.5l3 3-3 3M13 6.5H6.5a3.5 3.5 0 0 0 0 7H9",remove:"M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.7 8.5h5.6l.7-8.5M7 7v4M9 7v4",addText:"M2 3.5h7M5.5 3.5V12M11.5 8v5M9 10.5h5",duplicate:"M5.5 5.5h7v7h-7zM3.5 10.5v-7h7",render:"M2.5 3.5h11v9h-11zM7 6l3 2-3 2z",compare:"M2 2h12v12H2zM8 2v12M4 6h2M10 10h2",layout:"M2 2h12v12H2zM5.5 2v12M10.5 2v12",history:"M2 2v4h4M2 6a6 6 0 1 1 0 4M8 4v4l3 2",theme:"M8 1a7 7 0 1 0 7 7A5 5 0 0 1 8 1z",language:"M1 3h8M5 1v2M3 3c0 4 3 6 6 7M8 3c0 4-3 6-7 7M9 14l3-8 3 8M10 11h4",download:"M8 1v9M4 6l4 4 4-4M2 11v3h12v-3",external:"M9 2h5v5M14 2 7 9M6 2H2v12h12v-4",cloud:"M4 12a3 3 0 0 1-1-5.8A5 5 0 0 1 12 5a3.5 3.5 0 0 1 0 7M8 14V7M5.5 9.5 8 7l2.5 2.5",refresh:"M13 2v4H9M13 6a5.5 5.5 0 1 0 .2 5"},Y=e=>{let t=document.createElementNS(Kt,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","16"),t.setAttribute("height","16"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(Kt,"path");return n.setAttribute("d",uo[e]),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.5"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("stroke-linecap","round"),t.appendChild(n),t},Le=(e,t,n,o)=>{let r=Math.max(1,o);return e.style.left=Math.max(0,t)/r*100+"%",e.style.width=Math.max(0,Math.min(n,r)-Math.max(0,t))/r*100+"%",e},Q=(e,t,n)=>(e.style.left=Math.max(0,Math.min(t,n))/Math.max(1,n)*100+"%",e),le=(e,t)=>{let[n=0,o=0,r=0,s=0]=t;return e.style.left=n*100+"%",e.style.top=o*100+"%",e.style.width=r*100+"%",e.style.height=s*100+"%",e};var ft={title:"Video preview",readOnly:"read-only",live:"live",offline:"offline, retrying",language:"\\u4E2D\\u6587",languageTitle:"Switch the interface to Chinese",currentVideo:"Current video",render:"Render",reference:"Reference",seekNote:"A browser video seek is near, not frame-exact.",noReference:"No reference video. Start with --reference <video> to show one here.",errorsOnStage:"The project has errors; the stage lists them.",imageFailed:"A picture or video failed to load",first:"First frame (Home)",last:"Last frame (End)",back10:"Back 10 frames (Shift+Left)",back1:"Back 1 frame (Left)",fwd1:"Forward 1 frame (Right)",fwd10:"Forward 10 frames (Shift+Right)",play:"Play (Space)",pause:"Pause (Space)",frame:"Frame",time:"Time",speed:"Speed",jump:"Go to frame",jumpHint:"Frame number, then Enter",ruler:"Seconds",segments:"Segments",audio:"Audio",words:"Words",renderBoundaries:"Render: boundaries",renderEvents:"Render: events",referenceBoundaries:"Reference: boundaries",referenceEvents:"Reference: events",boxes:"Item boxes",events:"Measured events",safe:"Safe area",selection:"Selection",underPlayhead:"under the playhead",pinned:"clicked",follow:"Follow the playhead",onScreen:"On screen",nothing:"Nothing here.",problems:"Problems",noProblems:"No problems.",allowed:"Allowed",fix:"Fix",error:"error",warning:"warning",score:"Score",noScore:"No score: it needs a measurement of the render and one of the reference.",dimension:"Dimension",value:"Score",compared:"Compared",detail:"Detail",composite:"composite",measurements:"Measurements",renderMeasure:"Render",referenceMeasure:"Reference",none:"none",notes:"Draft notes",structure:"structure",transitions:"transitions",camera:"camera",motion:"motion",rhythm:"rhythm",colour:"colour",picture:"picture",editing:"editing",undo:"Undo (Ctrl+Z)",redo:"Redo (Shift+Ctrl+Z)",addText:"Add a text at the playhead",duplicate:"Duplicate the selection",remove:"Delete the selection (Delete)",renderTool:"Render the project to out.mp4",newText:"New text",saved:"Saved",added:"Added",removed:"Deleted",moved:"Moved",outside:"an edit made outside the page",undone:"Undone",redone:"Redone",notSaved:"Not saved",phraseSpan:"This item is placed on spoken words, so it is not dragged: change its lead and hold in the panel.",offlineEdit:"The preview server cannot be reached; nothing was saved.",rendering:"Rendering",rendered:"Rendered",framesIn:"frames in",renderFailed:"The render failed",playRender:"Play it beside the stage",showReference:"Show the reference again",renderFile:"Render",editHint:"Click an item on the stage, a bar in the lanes or a segment to edit it. Escape clears the selection.",resolvedTitle:"What the timeline plays (the default, or the value after resolving)",snapped:"snapped to",snapPlayhead:"the playhead",snapSegment:"a segment border",snapReference:"a boundary of the reference",framesWord:"frames",videoLength:"video",onFrames:"On frames",fDefault:"(default)",fCustom:"own values",fStyle:"Style",fNamed:"Style",fSize:"Size",fColour:"Colour",fWeight:"Weight",fAlign:"Align",fPreset:"Preset",fNone:"(none)",fFrames:"Frames",fDirection:"Direction",fEase:"Ease",fEnter:"Entrance",fExit:"Exit",fBox:"Box (fractions of the canvas)",fX:"x",fY:"y",fW:"width",fH:"height",fRotate:"Rotate",fOpacity:"Opacity",fZ:"Layer (z)",fLook:"Look",fRadius:"Corners",fShape:"Shape",fGradient:"A gradient: edit it in video.json.",fMaterial:"Material",fFit:"Fit",fMask:"Mask",fIn:"First frame",fSpeed:"Speed",fFootage:"Footage",fPicture:"Picture",fText:"Text",fStart:"Starts in",fWhole:"(the whole video)",fFrom:"From",fAudio:"Sound",fGain:"Gain (dB)",fSourceAudio:"Source audio dB (empty = automatic: on when the video has no audio track)",fSegment:"Segment",fWhen:"When",fPhrase:"Phrase",fOccurrence:"Occurrence",fLead:"Lead",fHold:"Hold",fTo:"To",fCue:"Cue",fCues:"Cues",fKind:"Kind",fHardCut:"(hard cut)",fMode:"Mode",fVia:"Via",fSide:"Side",fStrength:"Strength",fTransition:"Transition into it",fBase:"Base",fBaseColor:"colour",fBaseMaterial:"material",fBaseScene:"Scene content",fLength:"Length in frames",fCamera:"The camera: edit it in video.json."},mo={title:"\\u89C6\\u9891\\u9884\\u89C8",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u4E2D\\u65AD\\uFF0C\\u6B63\\u5728\\u91CD\\u8BD5",language:"English",languageTitle:"\\u628A\\u754C\\u9762\\u5207\\u6362\\u4E3A\\u82F1\\u6587",currentVideo:"\\u5F53\\u524D\\u4F5C\\u54C1",render:"\\u6E32\\u67D3",reference:"\\u53C2\\u8003\\u89C6\\u9891",seekNote:"\\u6D4F\\u89C8\\u5668\\u7684\\u89C6\\u9891\\u8DF3\\u8F6C\\u53EA\\u662F\\u63A5\\u8FD1\\uFF0C\\u4E0D\\u662F\\u9010\\u5E27\\u7CBE\\u786E\\u3002",noReference:"\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002\\u7528 --reference <\\u89C6\\u9891> \\u542F\\u52A8\\u5373\\u53EF\\u5728\\u6B64\\u663E\\u793A\\u3002",errorsOnStage:"\\u9879\\u76EE\\u6709\\u9519\\u8BEF\\uFF0C\\u753B\\u9762\\u533A\\u5217\\u51FA\\u4E86\\u5B83\\u4EEC\\u3002",imageFailed:"\\u6709\\u56FE\\u7247\\u6216\\u89C6\\u9891\\u52A0\\u8F7D\\u5931\\u8D25",first:"\\u7B2C\\u4E00\\u5E27 (Home)",last:"\\u6700\\u540E\\u4E00\\u5E27 (End)",back10:"\\u540E\\u9000 10 \\u5E27 (Shift+\\u2190)",back1:"\\u540E\\u9000 1 \\u5E27 (\\u2190)",fwd1:"\\u524D\\u8FDB 1 \\u5E27 (\\u2192)",fwd10:"\\u524D\\u8FDB 10 \\u5E27 (Shift+\\u2192)",play:"\\u64AD\\u653E (\\u7A7A\\u683C)",pause:"\\u6682\\u505C (\\u7A7A\\u683C)",frame:"\\u5E27",time:"\\u65F6\\u95F4",speed:"\\u901F\\u5EA6",jump:"\\u8DF3\\u5230\\u5E27",jumpHint:"\\u8F93\\u5165\\u5E27\\u53F7\\u540E\\u6309\\u56DE\\u8F66",ruler:"\\u79D2",segments:"\\u5206\\u6BB5",audio:"\\u97F3\\u9891",words:"\\u5B57\\u8BCD",renderBoundaries:"\\u6E32\\u67D3\\uFF1A\\u8FB9\\u754C",renderEvents:"\\u6E32\\u67D3\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",referenceBoundaries:"\\u53C2\\u8003\\uFF1A\\u8FB9\\u754C",referenceEvents:"\\u53C2\\u8003\\uFF1A\\u5143\\u7D20\\u4E8B\\u4EF6",boxes:"\\u5143\\u7D20\\u6846",events:"\\u6D4B\\u5F97\\u7684\\u4E8B\\u4EF6",safe:"\\u5B89\\u5168\\u533A",selection:"\\u9009\\u4E2D",underPlayhead:"\\u64AD\\u653E\\u5934\\u6240\\u5728\\u5904",pinned:"\\u5DF2\\u70B9\\u9009",follow:"\\u8DDF\\u968F\\u64AD\\u653E\\u5934",onScreen:"\\u753B\\u9762\\u4E2D",nothing:"\\u8FD9\\u91CC\\u6CA1\\u6709\\u5185\\u5BB9\\u3002",problems:"\\u95EE\\u9898",noProblems:"\\u6CA1\\u6709\\u95EE\\u9898\\u3002",allowed:"\\u5141\\u8BB8\\u7684\\u503C",fix:"\\u4FEE\\u6B63",error:"\\u9519\\u8BEF",warning:"\\u8B66\\u544A",score:"\\u8BC4\\u5206",noScore:"\\u6CA1\\u6709\\u8BC4\\u5206\\uFF1A\\u9700\\u8981\\u6E32\\u67D3\\u548C\\u53C2\\u8003\\u89C6\\u9891\\u5404\\u81EA\\u7684\\u6D4B\\u91CF\\u7ED3\\u679C\\u3002",dimension:"\\u7EF4\\u5EA6",value:"\\u5206\\u6570",compared:"\\u6BD4\\u8F83\\u6570",detail:"\\u7EC6\\u8282",composite:"\\u7EFC\\u5408",measurements:"\\u6D4B\\u91CF\\u7ED3\\u679C",renderMeasure:"\\u6E32\\u67D3",referenceMeasure:"\\u53C2\\u8003",none:"\\u65E0",notes:"\\u8349\\u7A3F\\u5907\\u6CE8",structure:"\\u7ED3\\u6784",transitions:"\\u8F6C\\u573A",camera:"\\u955C\\u5934\\u8FD0\\u52A8",motion:"\\u5143\\u7D20\\u52A8\\u6548",rhythm:"\\u8282\\u594F",colour:"\\u8272\\u5F69",picture:"\\u753B\\u9762",editing:"\\u7F16\\u8F91\\u4E2D",undo:"\\u64A4\\u9500 (Ctrl+Z)",redo:"\\u91CD\\u505A (Shift+Ctrl+Z)",addText:"\\u5728\\u64AD\\u653E\\u5934\\u5904\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236\\u6240\\u9009\\u5185\\u5BB9",remove:"\\u5220\\u9664\\u6240\\u9009\\u5185\\u5BB9 (Delete)",renderTool:"\\u628A\\u9879\\u76EE\\u6E32\\u67D3\\u4E3A out.mp4",newText:"\\u65B0\\u6587\\u5B57",saved:"\\u5DF2\\u4FDD\\u5B58",added:"\\u5DF2\\u6DFB\\u52A0",removed:"\\u5DF2\\u5220\\u9664",moved:"\\u5DF2\\u79FB\\u52A8",outside:"\\u9875\\u9762\\u5916\\u7684\\u4FEE\\u6539",undone:"\\u5DF2\\u64A4\\u9500",redone:"\\u5DF2\\u91CD\\u505A",notSaved:"\\u672A\\u4FDD\\u5B58",phraseSpan:"\\u8FD9\\u4E2A\\u5143\\u7D20\\u6309\\u8BF4\\u51FA\\u7684\\u5B57\\u8BCD\\u5B9A\\u4F4D\\uFF0C\\u4E0D\\u80FD\\u62D6\\u52A8\\uFF1A\\u8BF7\\u5728\\u9762\\u677F\\u91CC\\u4FEE\\u6539\\u5B83\\u7684\\u63D0\\u524D\\u91CF\\u548C\\u5EF6\\u540E\\u91CF\\u3002",offlineEdit:"\\u8FDE\\u4E0D\\u4E0A\\u9884\\u89C8\\u670D\\u52A1\\u5668\\uFF0C\\u6CA1\\u6709\\u4FDD\\u5B58\\u4EFB\\u4F55\\u4FEE\\u6539\\u3002",rendering:"\\u6E32\\u67D3\\u4E2D",rendered:"\\u5DF2\\u6E32\\u67D3",framesIn:"\\u5E27\\uFF0C\\u7528\\u65F6",renderFailed:"\\u6E32\\u67D3\\u5931\\u8D25",playRender:"\\u5728\\u753B\\u9762\\u65C1\\u64AD\\u653E",showReference:"\\u6539\\u56DE\\u663E\\u793A\\u53C2\\u8003\\u89C6\\u9891",renderFile:"\\u6E32\\u67D3\\u7ED3\\u679C",editHint:"\\u70B9\\u51FB\\u753B\\u9762\\u4E2D\\u7684\\u5143\\u7D20\\u3001\\u8F68\\u9053\\u4E0A\\u7684\\u6761\\u5757\\u6216\\u5206\\u6BB5\\u5373\\u53EF\\u7F16\\u8F91\\u3002\\u6309 Esc \\u53D6\\u6D88\\u9009\\u4E2D\\u3002",resolvedTitle:"\\u65F6\\u95F4\\u7EBF\\u5B9E\\u9645\\u64AD\\u653E\\u7684\\u503C\\uFF08\\u9ED8\\u8BA4\\u503C\\uFF0C\\u6216\\u89E3\\u6790\\u540E\\u7684\\u503C\\uFF09",snapped:"\\u5DF2\\u5438\\u9644\\u5230",snapPlayhead:"\\u64AD\\u653E\\u5934",snapSegment:"\\u5206\\u6BB5\\u8FB9\\u754C",snapReference:"\\u53C2\\u8003\\u89C6\\u9891\\u7684\\u8FB9\\u754C",framesWord:"\\u5E27",videoLength:"\\u89C6\\u9891",onFrames:"\\u6240\\u5728\\u5E27",fDefault:"\\uFF08\\u9ED8\\u8BA4\\uFF09",fCustom:"\\u81EA\\u5B9A\\u4E49",fStyle:"\\u6837\\u5F0F",fNamed:"\\u6837\\u5F0F",fSize:"\\u5B57\\u53F7",fColour:"\\u989C\\u8272",fWeight:"\\u5B57\\u91CD",fAlign:"\\u5BF9\\u9F50",fPreset:"\\u9884\\u8BBE",fNone:"\\uFF08\\u65E0\\uFF09",fFrames:"\\u5E27\\u6570",fDirection:"\\u65B9\\u5411",fEase:"\\u7F13\\u52A8",fEnter:"\\u5165\\u573A",fExit:"\\u51FA\\u573A",fBox:"\\u6846\\uFF08\\u753B\\u5E03\\u7684\\u6BD4\\u4F8B\\uFF09",fX:"x",fY:"y",fW:"\\u5BBD",fH:"\\u9AD8",fRotate:"\\u65CB\\u8F6C",fOpacity:"\\u4E0D\\u900F\\u660E\\u5EA6",fZ:"\\u5C42\\u7EA7 (z)",fLook:"\\u5916\\u89C2",fRadius:"\\u5706\\u89D2",fShape:"\\u5F62\\u72B6",fGradient:"\\u6E10\\u53D8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002",fMaterial:"\\u7D20\\u6750",fFit:"\\u9002\\u914D",fMask:"\\u906E\\u7F69",fIn:"\\u8D77\\u59CB\\u5E27",fSpeed:"\\u901F\\u5EA6",fFootage:"\\u89C6\\u9891\\u7D20\\u6750",fPicture:"\\u56FE\\u7247",fText:"\\u6587\\u5B57",fStart:"\\u5F00\\u59CB\\u4E8E",fWhole:"\\uFF08\\u6574\\u4E2A\\u89C6\\u9891\\uFF09",fFrom:"\\u4ECE",fAudio:"\\u58F0\\u97F3",fGain:"\\u589E\\u76CA (dB)",fSourceAudio:"\\u7D20\\u6750\\u539F\\u58F0 dB\\uFF08\\u7559\\u7A7A\\u4E3A\\u81EA\\u52A8\\uFF1A\\u89C6\\u9891\\u6CA1\\u6709\\u97F3\\u8F68\\u65F6\\u4FDD\\u7559\\uFF09",fSegment:"\\u5206\\u6BB5",fWhen:"\\u51FA\\u73B0\\u65F6\\u95F4",fPhrase:"\\u5B57\\u8BCD",fOccurrence:"\\u7B2C\\u51E0\\u6B21",fLead:"\\u63D0\\u524D",fHold:"\\u5EF6\\u540E",fTo:"\\u5230",fCue:"\\u5B57\\u5E55",fCues:"\\u5B57\\u5E55\\u6761",fKind:"\\u7C7B\\u578B",fHardCut:"\\uFF08\\u786C\\u5207\\uFF09",fMode:"\\u6A21\\u5F0F",fVia:"\\u7ECF\\u8FC7",fSide:"\\u5355\\u4FA7",fStrength:"\\u5F3A\\u5EA6",fTransition:"\\u8FDB\\u5165\\u5B83\\u7684\\u8F6C\\u573A",fBase:"\\u5E95\\u56FE",fBaseColor:"\\u989C\\u8272",fBaseMaterial:"\\u7D20\\u6750",fBaseScene:"\\u573A\\u666F\\u5185\\u5BB9",fLength:"\\u957F\\u5EA6\\uFF08\\u5E27\\uFF09",fCamera:"\\u955C\\u5934\\u8FD0\\u52A8\\uFF1A\\u8BF7\\u5728 video.json \\u91CC\\u4FEE\\u6539\\u3002"},po={en:ft,zh:mo},Ue=e=>e?.toLowerCase().startsWith("zh")?"zh":"en",S=(e,t)=>po[e][t],Ut=e=>Object.hasOwn(ft,e),Jt=(e,t)=>t in ft?S(e,t):t;var T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t)=>T(e)&&Array.isArray(e[t])?e[t]:[],ee=e=>he(e.source,"tracks").filter(T),te=e=>he(e.source,"segments").filter(T),ve=(e,t)=>he(e.source,"materials").filter(T).filter(n=>t.includes(String(n.kind))).map(n=>String(n.id)),gt=(e,t)=>e.findIndex(n=>T(n)&&n.id===t),fo=(e,t)=>{let n=e.resolved?.items.find(r=>r.id===t);if(n)return n.cue;let o=t.match(/^(.+)#(\\d+)$/);return o?{track:o[1]??"",index:Number(o[2])}:void 0},q=(e,t)=>{if(!t||!T(e.source))return;let n=he(e.source,"tracks");if(t.kind==="segment"){let i=gt(he(e.source,"segments"),t.id),d=he(e.source,"segments")[i];return T(d)?{kind:"segment",index:i,segment:d}:void 0}if(t.kind!=="item"&&t.kind!=="audio")return;let o=gt(n,t.id),r=n[o];if(T(r)&&r.type!=="caption")return{kind:"track",index:o,track:r};let s=t.kind==="item"?fo(e,t.id):void 0,a=s?gt(n,s.track):-1,c=n[a];return s&&T(c)&&s.index<he(c,"cues").length?{kind:"cue",index:a,cue:s.index,track:c}:void 0},go=e=>e.kind==="segment"?["segments",e.index]:["tracks",e.index],ht=e=>{if(e.kind==="cue")return["tracks",e.index,"cues",e.cue,"during"];if(e.kind==="track"&&T(e.track.during))return["tracks",e.index,"during"]},bt=e=>e.kind!=="segment"&&Array.isArray(e.track.box)?["tracks",e.index,"box"]:void 0,oe=(e,t)=>t.reduce((n,o)=>Array.isArray(n)?n[o]:T(n)?n[String(o)]:void 0,e),Re=(e,t)=>{let n=bt(t),o=n?oe(e.source,n):void 0;return Array.isArray(o)&&o.length===4&&o.every(r=>typeof r=="number")?o:void 0},Wt=(e,t,n)=>{if(n===void 0)return oe(e,t)===void 0?void 0:{op:"remove",path:t};let o=t.length-1;for(;o>0&&!T(oe(e,t.slice(0,o)))&&!Array.isArray(oe(e,t.slice(0,o)));)o--;let r=t.slice(o+1).reduceRight((s,a)=>({[String(a)]:s}),n);return{op:"set",path:t.slice(0,o+1),value:r}},Se=(e,t)=>{if(!T(t)||t.phrase!==void 0||typeof t.segment!="string")return;let n=e.segments.find(s=>s.id===t.segment);if(!n)return;let o=typeof t.from=="number"?t.from:0,r=typeof t.to=="number"?t.to:n.end-n.start;return{start:n.start+o,end:n.start+r,segment:n}},yt=(e,t,n,o)=>{let r=e.segments.find(c=>c.id===t.segment),s=r&&n>=r.start&&n<r.end?r:Z(e,n)??r??e.segments[0],a=s?.start??0;return{...t,segment:s?.id??t.segment,from:n-a,to:o-a}},qt=(e,t,n=!0)=>{let o=e.resolved,r=o?.canvas.fps??30,s=e.referenceMeasure?.measure;return[{frame:t,kind:"playhead"},...n&&o?o.segments.flatMap(a=>[a.start,a.end]).map(a=>({frame:a,kind:"segment"})):[],...s?s.boundaries.map(a=>({frame:Math.round(ye(a.frame,s.source.fps,r)),kind:"reference"})):[]]},ho=4,Pe=(e,t,n)=>{let o=t.map(r=>({t:r,d:Math.abs(r.frame-e)*n})).filter(r=>r.d<=ho).sort((r,s)=>r.d-s.d)[0];return o?o.t:{frame:Math.round(e),kind:"frame"}},re=(e,t)=>{let n=new Set(e.map(r=>String(r.id))),o=t.replace(/-\\d+$/,"");if(!n.has(t))return t;for(let r=2;;r++)if(!n.has(o+"-"+r))return o+"-"+r},Gt=(e,t,n)=>{let o=e.resolved,r=o?Z(o,t)??o.segments[o.segments.length-1]:void 0;if(!o||!r)return;let s=ee(e),a=re(s,"text"),c=Math.max(0,t-r.start),i=Math.max(c+1,Math.min(r.end-r.start,c+2*o.canvas.fps)),d={id:a,type:"text",text:n,box:[.1,.42,.8,.12],during:{segment:r.id,from:c,to:i},style:"subtitle"};return{op:{op:"insert",path:["tracks",s.length],value:d},select:{kind:"item",id:a}}},bo=e=>Array.isArray(e)&&e.length===4?e.map((t,n)=>n<2&&typeof t=="number"?Math.round((t+.03)*1e5)/1e5:t):e,Yt=(e,t)=>{if(t.kind==="segment"){let r=re(te(e),String(t.segment.id));return{op:{op:"insert",path:["segments",t.index+1],value:{...t.segment,id:r}},select:{kind:"segment",id:r}}}if(t.kind==="cue"){let r=he(t.track,"cues")[t.cue],s=e.resolved,a=s&&T(r)?Se(s,r.during):void 0;if(!T(r)||!s||!a||!T(r.during))return;let c=yt(s,r.during,a.end,a.end+(a.end-a.start));return{op:{op:"insert",path:["tracks",t.index,"cues",t.cue+1],value:{...r,during:c}},select:{kind:"item",id:String(t.track.id)+"#"+(t.cue+1)}}}let n=re(ee(e),String(t.track.id)),o={...t.track,id:n,...Array.isArray(t.track.box)?{box:bo(t.track.box)}:{}};return{op:{op:"insert",path:["tracks",t.index+1],value:o},select:{kind:t.track.type==="audio"?"audio":"item",id:n}}},Xt=e=>e.kind==="cue"&&Array.isArray(e.track.cues)&&e.track.cues.length>1?{op:"remove",path:["tracks",e.index,"cues",e.cue]}:{op:"remove",path:go(e)},Zt=e=>e.map(t=>Math.round(t*1e5)/1e5);var Qt=(e,t)=>{if(!T(e.source))return;let n=te(e),o=n[t];if(!o)return;let r=re(n,String(o.id)),s=ee(e).map(i=>structuredClone(i)),a=i=>T(i)&&i.segment===o.id?{...i,segment:r}:i;for(let i of ee(e)){let d=Array.isArray(i.cues)?i.cues.filter(f=>T(f)&&T(f.during)&&f.during.segment===o.id):[];if(!d.length&&(!T(i.during)||i.during.segment!==o.id))continue;let l={...structuredClone(i),id:re(s,String(i.id)),...i.during?{during:a(i.during)}:{},...d.length?{cues:d.map(f=>({...f,during:a(f.during)}))}:{}};s.push(l)}let c=n.map(i=>structuredClone(i));return c.splice(t+1,0,{...structuredClone(o),id:r}),{source:{...e.source,segments:c,tracks:s},id:r}};var yo='"Noto Sans CJK SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif',we={font:yo,size:.045,weight:700,color:"#ffffff",align:"center",italic:!1};var vo={blur:.12,x:.04,y:.06},$t=["headline","subtitle","label","caption"],vt={headline:{...we,size:.065,weight:800,stroke:{color:"#000000",width:.12}},subtitle:{...we,size:.04,weight:700,stroke:{color:"#000000",width:.1}},label:{...we,size:.032,weight:700,color:"#111111",background:{color:"#ffffff",padding:.35,radius:.3}},caption:{...we,size:.036,weight:600,background:{color:"rgba(0, 0, 0, 0.6)",padding:.3,radius:.2}}},St=e=>$t.includes(e),So=(e,t)=>({color:e.color,blur:e.blur??t.blur,x:e.x??t.x,y:e.y??t.y}),en=e=>{if(e===void 0)return we;if(typeof e=="string"){if(!St(e))throw new Error('Unknown text style "'+e+'". Use one of: '+$t.join(", ")+".");return vt[e]}let{shadow:t,...n}=e;return{...we,...n,...t?{shadow:So(t,vo)}:{}}};var tn=(e,t)=>{if(!e?.resolved||t.op!=="set"||t.path[0]!=="tracks"||t.path[2]!=="text"||typeof t.value!="string")return t;let n=T(e.source)?e.source:{},o=Array.isArray(n.tracks)?n.tracks[Number(t.path[1])]:void 0;if(!T(o)||o.type!=="text")return t;let r=e.resolved.items.find(p=>p.id===o.id),a=document.querySelector("#page")?.contentDocument,c=a?.querySelector('[data-item="'+CSS.escape(String(o.id))+'"] > div');if(!a||!c||!r?.style)return t;let i=r.box[2]*e.resolved.canvas.width,d=r.box[3]*e.resolved.canvas.height,l=c.cloneNode(!1);l.textContent=t.value,Object.assign(l.style,{position:"fixed",left:"0",top:"0",width:i+"px",height:"auto",visibility:"hidden",transform:"none"}),a.body.append(l);let f=r.style.size*e.resolved.canvas.height,g=p=>(l.style.fontSize=p+"px",l.style.letterSpacing=(r.style.letterSpacing??0)*p+"px",l.scrollHeight<=d+.5&&l.scrollWidth<=i+.5);try{if(g(f))return t;let p=1,m=f;for(let v=0;v<16;v++){let E=(p+m)/2;g(E)?p=E:m=E}let{font:h,...b}=en(typeof o.style=="string"?o.style:void 0),y=T(o.style)?o.style:b;return{op:"set",path:["tracks",Number(t.path[1])],value:{...o,text:t.value,style:{...y,size:Math.floor(p*100)/100/e.resolved.canvas.height}}}}finally{l.remove()}};var Ae=(e,t,n)=>{let o=e?.resolved,r=t.kind==="item"?o?.items.find(c=>c.id===t.id):t.kind==="audio"?o?.audio.find(c=>c.id===t.id):t.kind==="segment"||t.kind==="slot"?o?.segments.find(c=>c.id===t.id):void 0;if(!r)return n;let s=r.end??o.frames,a="enter"in r?r.enter?.frames??0:0;return n>=r.start+a&&n<s&&t.kind!=="slot"?n:Math.min(s-1,Math.max(r.start+a,r.start+Math.floor((s-r.start)*.3)))};var nn=(e,t)=>{let n=e.resolved,o=te(e),r=n?.segments[t];if(!n||!r||o.length<2||!T(e.source))return;let s=structuredClone(e.source),a=o.filter((p,m)=>m!==t),c=r.end-r.start,i=String(a[0].id),d=p=>p<=r.start?p:p>=r.end?p-c:r.start,l=(p,m)=>({segment:i,from:d(p),to:d(m)}),f=ee(e),g=[];for(let p of f){let m=structuredClone(p);if(m.type==="caption"&&Array.isArray(m.cues)){let k=m.cues.flatMap((H,L)=>{if(!T(H))return[];let R=n.items.find(F=>F.cue?.track===m.id&&F.cue?.index===L);return!R||d(R.end)<=d(R.start)?[]:[{...H,during:l(R.start,R.end)}]});k.length&&g.push({...m,cues:k});continue}let h=m.type==="audio"?n.audio.find(k=>k.id===m.id):n.items.find(k=>k.id===m.id),b=Se(n,m.during),y=h?.start??b?.start??0,v=h?.end??b?.end??n.frames;if(d(v)<=d(y))continue;let E=m.type==="audio"||m.type==="video",M=E&&y<r.start&&v>r.end?[[y,r.start],[r.end,v]]:[[y<r.end&&y>=r.start?r.end:y,v>r.start&&v<=r.end?r.start:v]];for(let[k,H]of M){if(k===void 0||H===void 0||H<=k)continue;let L={...m,during:l(k,H)};if(g.some(R=>R.id===L.id)&&(L.id=re([...f,...g],String(L.id))),E&&k>y){let R=m.type==="video"?n.items.find(O=>O.id===m.id)?.play:void 0,F=R?(n.footage?.[R.material]?.fps??n.canvas.fps)/n.canvas.fps*R.speed:m.bed?(n.footage?.[String(m.material)]?.fps??n.canvas.fps)/n.canvas.fps:1;L.in=Number(m.in??0)+Math.round((k-y)*F)}k>y&&delete L.enter,H<v&&delete L.exit,g.push(L)}}return s.segments=a,s.tracks=g,s};var xt=(e,t,n)=>{let o=q(e,t),r=e.resolved;if(!o||!r||!T(e.source))return;let s=structuredClone(e.source);if(o.kind==="segment"){let h=r.segments[o.index];if(!h||n<=h.start||n>=h.end)return;let b=te(e).map(R=>structuredClone(R)),y=b[o.index],v=n-h.start,E=re(b,String(y.id)),M=T(y.base)?y.base:{},k={...M};M.scene&&(k.offset=Number(M.offset??0)+v/r.canvas.fps),M.material&&h.base.kind==="video"&&(k.in=h.base.play.in+Math.round(v*(r.footage?.[h.base.play.material]?.fps??r.canvas.fps)*h.base.play.speed/r.canvas.fps));let H={...y,id:E,frames:h.end-n,base:k};delete H.in;let L=R=>T(R)&&R.segment===y.id&&R.phrase===void 0&&R.to===void 0?{...R,to:h.end-h.start}:R;return s.tracks=ee(e).map(R=>({...R,...R.during?{during:L(R.during)}:{},...Array.isArray(R.cues)?{cues:R.cues.map(F=>T(F)?{...F,during:L(F.during)}:F)}:{}})),b.splice(o.index,1,{...y,frames:v},H),s.segments=b,{source:s,select:{kind:"segment",id:E}}}let a=structuredClone(o.track),c=o.kind==="cue"&&Array.isArray(a.cues)?a.cues[o.cue]:void 0,i=o.kind==="cue"?c:a;if(!T(i))return;if(!T(i.during)&&a.type==="audio"){let h=r.audio.find(b=>b.id===a.id);h&&(i.during={segment:r.segments[0]?.id,from:h.start,to:h.end??r.frames})}if(!T(i.during))return;let d=Se(r,i.during);if(!d||n<=d.start||n>=d.end)return;let l=i.during,f={...i,during:{...l,to:n-d.segment.start}},g={...i,during:{...l,from:n-d.segment.start}},p=ee(e).map(h=>structuredClone(h));if(o.kind==="cue")return a.cues.splice(o.cue,1,f,g),p[o.index]=a,s.tracks=p,{source:s,select:{kind:"item",id:String(a.id)+"#"+(o.cue+1)}};let m=re(p,String(a.id));if(g.id=m,a.type==="video"){let h=r.items.find(b=>b.id===a.id);h&&(g.in=Number(a.in??0)+Math.round((n-d.start)*Number(r.footage?.[h.play?.material??""]?.fps??r.canvas.fps)*Number(a.speed??1)/r.canvas.fps))}return a.type==="audio"&&(g.in=Number(a.in??0)+Math.round((n-d.start)*(a.bed?(r.footage?.[String(a.material)]?.fps??r.canvas.fps)/r.canvas.fps:1))),delete f.exit,delete g.enter,p.splice(o.index,1,f,g),s.tracks=p,{source:s,select:{kind:a.type==="audio"?"audio":"item",id:m}}};var Et=e=>"popost-preview-selection:"+e.project.dir,Je=e=>{try{let t=sessionStorage.getItem(Et(e));return t?JSON.parse(t):null}catch{return null}},We=e=>{e.subscribe((t,n)=>{if(!(t.pinned===n.pinned||!t.state))try{t.pinned?sessionStorage.setItem(Et(t.state),JSON.stringify(t.pinned)):sessionStorage.removeItem(Et(t.state))}catch{}})},xo=async(e,t)=>{try{return await(await fetch(e,{method:"POST",headers:{"content-type":"application/json"},...t===void 0?{}:{body:JSON.stringify(t)}})).json()}catch(n){return{ok:!1,problems:[{level:"error",at:"(request)",message:n instanceof Error?n.message:String(n),fix:""}]}}},qe=(e,t)=>{let n=p=>e.set({edit:{...e.get().edit,...p}}),o=new Set,r=Promise.resolve(!0),s=!0,a=p=>{p&&["item","slot","audio"].includes(p.kind)&&e.get().timeline&&!e.get().timeline?.layers&&e.set({timeline:{layers:!0,snapping:e.get().timeline?.snapping??!0}}),t.pin(p)},c=(p,m)=>{if(!p.ok){let y=p.problems.find(v=>v.level==="error")??p.problems[0];return n({status:y?{kind:"refused",problem:y}:null,problems:p.problems}),!1}let h=p.state;if(h.generation<(e.get().state?.generation??-1))return!0;if(e.set({state:h,frame:pe(e.get().frame,W(h)),edit:{...e.get().edit,status:{kind:"done",op:p.op,step:p.step,label:p.label},problems:[]}}),m!==void 0)a(m);else{let y=e.get().pinned;y&&y.kind!=="slot"&&!q(h,y)&&a(null)}let b=e.get().pinned;return b&&b.kind!=="slot"&&t.seek(Ae(h,b,e.get().frame)),!0},i=()=>{let p=e.get();return p.state?q(p.state,p.pinned):void 0},d=(p,m,h)=>{n({saving:!0});let b=r.then(()=>xo(p,typeof m=="function"?m():m)).then(y=>(s=c(y,h),s));return r=b.catch(()=>!1),o.add(b),b.finally(()=>{o.delete(b),o.size||n({saving:!1})}),b},l=(p,m)=>d("/api/edit",()=>tn(e.get().state,p),m),f=async()=>{for(;o.size;)await Promise.all([...o])},g=async p=>{if(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),await f(),!s)return;let m=e.get().state,h=i();m&&h&&await p(m,h)};return{send:l,reveal:(p,m)=>{t.pause(),t.seek(m??Ae(e.get().state,p,e.get().frame)),a(p)},flush:async()=>{for(document.activeElement instanceof HTMLElement&&document.activeElement.blur();o.size;)await Promise.all([...o]);return s},canSplit:()=>{let p=e.get();return!!(p.state&&xt(p.state,p.pinned,p.frame))},split:async()=>{let p=e.get(),m=p.state?xt(p.state,p.pinned,p.frame):void 0;m&&await d("/api/source",{source:m.source,base:p.state?.source})&&a(m.select)},replace:(p,m)=>d("/api/source",{source:p,base:m}),undo:async()=>{await f(),await d("/api/undo")},redo:async()=>{await f(),await d("/api/redo")},remove:()=>g(async(p,m)=>{if(m.kind==="segment"){let h=nn(p,m.index);h&&await d("/api/source",{source:h,base:p.source},null);return}await l(Xt(m),null)}),duplicate:()=>g(async(p,m)=>{if(m.kind==="segment"){let b=Qt(p,m.index);b&&await d("/api/source",{source:b.source,base:p.source},{kind:"segment",id:b.id});return}let h=Yt(p,m);h&&await l(h.op,h.select)}),addText:async()=>{let p=e.get(),m=p.state?Gt(p.state,p.frame,S(p.lang,"newText")):void 0;m&&await l(m.op,m.select)},render:async()=>{let m=await(await fetch("/api/render",{method:"POST"}).catch(()=>{}))?.json().catch(()=>{});m?.render?n({render:m.render}):m?.problems?.[0]&&n({status:{kind:"refused",problem:m.problems[0]}})},select:a,note:p=>n({status:{kind:"note",key:p}}),target:i,setRender:p=>n({render:p}),togglePlayRender:()=>n({playRender:!e.get().edit.playRender})}};var Eo={frame:null,playhead:"snapPlayhead",segment:"snapSegment",reference:"snapReference"},wo=(e,t,n,o)=>{let r=Pe(e.start+t,n,o),s=Pe(e.end+t,n,o),a=r.kind==="frame"?1/0:Math.abs(r.frame-(e.start+t)),c=s.kind==="frame"?1/0:Math.abs(s.frame-(e.end+t)),i=a<=c&&a!==1/0?r.frame-e.start:c!==1/0?s.frame-e.end:Math.round(t),d=a<=c&&a!==1/0?r:c!==1/0?s:{frame:e.start+i,kind:"frame"};return{start:e.start+i,end:e.end+i,snap:d}},ko=(e,t,n,o)=>{if(e.mode==="move")return wo(e,t,n,o);if(e.mode==="start"){let s=Pe(e.start+t,n,o);return{start:Math.min(s.frame,e.end-1),end:e.end,snap:s}}let r=Pe(e.end+t,n,o);return{start:e.start,end:Math.max(r.frame,e.start+1),snap:r}},Mo=(e,t,n,o)=>{let r=Eo[o.snap.kind],s=r?" \\xB7 "+S(e,"snapped")+" "+S(e,r):"";if(n.mode==="border"){let a=W(t),c=o.end-n.end;return(t.resolved?.segments.find(d=>d.end===n.end)?.id??"")+": "+(n.end-n.start)+" \\u2192 "+(o.end-n.start)+" "+S(e,"framesWord")+" \\xB7 "+S(e,"videoLength")+" "+a+" \\u2192 "+(a+c)+" ("+(c>=0?"+":"")+c+")"+s}return S(e,"onFrames")+" "+o.start+".."+(o.end-1)+s},To=(e,t,n)=>{let o=t.closest(".lane-track"),r=e.resolved;if(!o||!r)return;let s=t.closest(".seg-grip")?.dataset.border;if(s!==void 0){let m=r.segments[Number(s)];return m?{mode:"border",x0:n,track:o,start:m.start,end:m.end,border:Number(s),moved:!1}:void 0}let a=t.closest("[data-sel]")?.dataset.sel,c=a?JSON.parse(a):void 0;if(c?.kind!=="item"&&c?.kind!=="audio")return;let i=q(e,c),d=i?ht(i):void 0,l=c.kind==="audio"?r.audio.find(m=>m.id===c.id):void 0,f=(i&&d?on(i):void 0)??(l?{segment:r.segments[0]?.id,from:l.start,to:l.end??r.frames}:void 0);if(!i||!f)return;let g=Se(r,f);if(!g)return{mode:"move",x0:n,track:o,start:0,end:0,target:i,phrase:!0,moved:!1};let p=t.closest(".grip")?.dataset.grip;return{mode:p==="start"||p==="end"?p:"move",x0:n,track:o,start:g.start,end:g.end,target:i,span:f,moved:!1}},on=e=>{let t=e.kind==="cue"?e.track.cues[e.cue]:e.kind==="track"?e.track:void 0,n=t&&typeof t=="object"?t.during:void 0;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0},Lo=(e,t,n,o,r)=>{let s=o.state;if(!s||n.phrase)return;let a=W(s);if(!n.track.isConnected){let g=n.track.closest(".lane")?.id,p=g?e.querySelector("#"+CSS.escape(g)+" .lane-track"):null;if(!p)return;n.track=p}let c=n.track.getBoundingClientRect().width/Math.max(1,a);if(!Number.isFinite(c)||c<=0)return;let i=o.timeline?.snapping===!1?[]:qt(s,o.frame,n.mode!=="border"),d=ko(n.mode==="border"?{mode:"end",start:n.start,end:n.end}:n,(r-n.x0)/c,i,c);if(n.mode!=="border")if(n.mode==="move"){let g=Math.min(a,n.end-n.start);d.start=Math.max(0,Math.min(a-g,d.start)),d.end=d.start+g}else d.start=Math.max(0,d.start),d.end=Math.min(a,d.end);n.result=d,n.mode!=="border"&&n.track.append(Le(t.ghost,d.start,d.end,a));let l=e.querySelector(".playhead-layer");if(!l)return;let f=d.snap.kind!=="frame"?d.snap.frame:n.mode==="end"||n.mode==="border"?d.end:d.start;l.append(Q(t.guide,f,a)),t.guide.classList.toggle("snapped",d.snap.kind!=="frame"),t.label.textContent=Mo(o.lang,s,n,d),l.append(Q(t.label,Math.min(f,a*.6),a))},Ro=(e,t)=>{let n=t.resolved;if(!n||!e.result)return;if(e.mode==="border")return e.border!==void 0&&e.result.end!==e.end?{op:"set",path:["segments",e.border,"frames"],value:e.result.end-e.start}:void 0;let o=e.target?ht(e.target)??(e.target.kind==="track"&&e.target.track.type==="audio"?["tracks",e.target.index,"during"]:void 0):void 0,r=e.span??(e.target?on(e.target):void 0);if(!(!o||!r||e.result.start===e.start&&e.result.end===e.end))return{op:"set",path:o,value:yt(n,r,e.result.start,e.result.end)}},Ge=(e,t,n)=>{let o={ghost:u("div",{class:"drag-ghost",id:"drag-ghost"}),guide:u("div",{class:"snap-guide",id:"snap-guide"}),label:u("div",{class:"lane-readout",id:"lane-readout"})},r,s=!1,a;e.addEventListener("pointerdown",i=>{let d=t.get().state;if(i.button!==0||!d?.edit||t.get().edit.saving)return;document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let l=i.target.closest("[data-sel]")?.dataset.sel;l&&n.select(JSON.parse(l));let f=l?JSON.parse(l):void 0;if(f?.kind==="segment"&&!i.target.closest(".seg-grip")){let g=d.resolved?.segments.findIndex(m=>m.id===f.id)??-1,p=i.target.closest(".lane-track");if(g>=0&&p){a={index:g,to:g,x:i.clientX,moved:!1,track:p},e.setPointerCapture(i.pointerId),i.preventDefault();return}}r=To(d,i.target,i.clientX),r&&(e.setPointerCapture(i.pointerId),i.preventDefault())}),e.addEventListener("pointermove",i=>{if(a){if(!a.moved&&Math.abs(i.clientX-a.x)<4)return;a.moved=!0;let d=t.get().state?.resolved;if(!d)return;let l=a.track.getBoundingClientRect(),f=(i.clientX-l.left)/l.width*d.frames;a.to=Math.max(0,d.segments.findIndex(m=>f<m.end)),f>=d.frames&&(a.to=d.segments.length-1);let g=d.segments[a.to]?.start??0,p=e.querySelector(".playhead-layer");o.label.textContent=(t.get().lang==="zh"?"\\u79FB\\u52A8\\u955C\\u5934 ":"Move shot ")+(a.index+1)+" \\u2192 "+(a.to+1),p?.append(Q(o.guide,g,d.frames),Q(o.label,Math.min(g,d.frames*.6),d.frames));return}!r||!r.moved&&Math.abs(i.clientX-r.x0)<3||(r.moved=!0,Lo(e,o,r,t.get(),i.clientX))});let c=i=>{if(a){let g=a;a=void 0,[o.ghost,o.guide,o.label].forEach(p=>p.remove()),g.moved&&(s=!0,setTimeout(()=>{s=!1},0),i.type!=="pointercancel"&&g.index!==g.to&&n.send({op:"move",path:["segments",g.index],to:g.to}));return}let d=r;if(r=void 0,[o.ghost,o.guide,o.label].forEach(g=>g.remove()),!d?.moved)return;s=!0,setTimeout(()=>{s=!1},0);let l=t.get().state;if(d.phrase)return n.note("phraseSpan");let f=l?Ro(d,l):void 0;f&&i.type!=="pointercancel"&&n.send(f)};e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c),e.addEventListener("click",i=>{s&&(s=!1,i.stopImmediatePropagation())},!0)};var Po=e=>e?.anyOf?.find(t=>t.type==="object")??e,j=(e,...t)=>t.reduce((n,o)=>Po(n)?.properties?.[o],e),X=e=>(e?.enum??e?.anyOf?.find(t=>t.enum)?.enum??[]).map(t=>String(t));var Ye=e=>e===void 0||Math.abs(e)>=9e15?void 0:e,xe=e=>({...Ye(e?.minimum??e?.exclusiveMinimum)===void 0?{}:{min:Ye(e?.minimum??e?.exclusiveMinimum)},...Ye(e?.maximum??e?.exclusiveMaximum)===void 0?{}:{max:Ye(e?.maximum??e?.exclusiveMaximum)},integer:e?.type==="integer"}),Xe=async()=>{let e=await fetch("/api/schema",{cache:"no-store"}).catch(()=>{});return e?.ok?await e.json():null};var Ao={noReference:"No reference video is available for this project.",shots:"Shots",media:"Media",script:"Script",elements:"Elements",code:"Code",checks:"Review",versions:"Versions",export:"Export",compare:"Compare",layout:"Layout",theme:"Theme",saved:"Saved locally",readOnly:"Read only",live:"Connected",offline:"Disconnected",preview:"Preview",current:"Current",add:"Add",upload:"Import",search:"Search",scene:"Animated scene",video:"Video",image:"Image",color:"Background",duration:"Duration",keepRhythm:"Keep reference rhythm",content:"Content",properties:"Properties",viewAll:"Fit timeline",assist:"Analysis",zoom:"Zoom",audio:"Project audio",onlyPreview:"Preview controls do not change exported audio",sourceTitle:"Draft JSON",autosave:"Valid JSON saves automatically",format:"Format JSON",download:"Download JSON",invalid:"Invalid JSON \\u2014 draft kept",saving:"Saving\\u2026",conflict:"The draft changed elsewhere. Reload before saving.",reload:"Reload JSON",choose:"Select an item to edit",text:"Text",audioTrack:"Audio",subtitles:"Subtitles",voice:"Voiceover",music:"Music / effects",addText:"Add text",duplicate:"Duplicate",remove:"Delete",undo:"Undo",redo:"Redo",time:"Time",wordBound:"Follows speech",original:"Original",resolution:"Resolution",dynamicRange:"Dynamic range",hdrUnavailable:"HDR is unavailable: this HTML renderer outputs SDR.",fps:"Frame rate",match:"Match timeline",bitrate:"Video bitrate",recommended:"Recommended",filename:"File name",includeAudio:"Include project audio",range:"Range",full:"Full video",start:"Start frame",end:"End frame (exclusive)",paid:"Paid benefit",paidInfo:"This feature is available with a paid plan.",unlock:"Unlock",refreshPlan:"Refresh plan",preparing:"Preparing",rendering:"Rendering",renderDone:"Export ready",stale:"The draft changed after this export",play:"Play",downloadVideo:"Download video",exportSnapshot:"Export uses the JSON snapshot at start. You can continue editing.",general:"General",effects:"Timing and motion",sourceFile:"Source file",missing:"Missing",replace:"Replace",apply:"Apply",applyShot:"Use in selected shot",addOverlay:"Add overlay",slot:"Scene field",noSlots:"This scene exposes no editable slots. Use JSON to change its source or replace the scene.",currentShot:"Current shot",selected:"Selected",noMedia:"No project media",importHint:"Images, video or audio up to 12 MB",scriptHint:"Editing captions does not regenerate voiceover.",pendingVoice:"Caption changed; review voiceover",all:"All",notes:"Notes",comment:"Add timed note",noteHint:"Describe the change at this frame\\u2026",resolved:"Resolved",resolve:"Resolve",reopen:"Reopen",copyNote:"Copy change request",noNotes:"No review notes yet",noProblems:"No structural problems found",unmeasured:"No comparison measurements for this version",saveVersion:"Save version",restore:"Restore",versionName:"Version name",noVersions:"No saved versions",defaultLayout:"Default layout",focusedPreview:"Focus preview",codeHint:"Changes update the same draft after validation. Invalid JSON never overwrites it.",sourceChanged:"Draft saved",quality:"Quality",loading:"Loading\\u2026",sameAsReference:"Reference / replica",toggleAnalysis:"Show analysis lanes",sceneFields:"Scene content",position:"Position",trackGain:"Gain (dB)",chooseMaterial:"Choose a material, then select where to use it.",unsupported:"Unavailable for this selection",refresh:"Refresh",inspect:"Inspect",seconds:"s",waveform:"Waveform",recheck:"Reload checks",sourceExport:"The source JSON is included separately; it is not an MP4.",goShot:"Go to shot",moveUp:"Move earlier",moveDown:"Move later",narrationUnavailable:"Voice generation is managed by the Agent. Copy the revised script to request updated narration.",copyScript:"Copy revised script",applyCaption:"Save caption",error:"Could not complete the operation",fileRange:"Whole timeline",frame:"Frame",newVersion:"Studio version",noSelection:"Select a shot, caption or overlay to edit.",segment:"Shot",previewQuality:"Fit preview",allChanges:"All changes saved",currentExport:"Export current draft",jsonDownload:"Download the saved video.json",imageSlot:"Replace image slot",selectedSlot:"Selected scene field",sceneOffset:"Scene element offset",fontSize:"Font size",textColor:"Text colour",versionSnapshot:"Saved versions preserve the draft JSON; assets are reused.",bitrateUnit:"Mbps",reviewOnly:"Review notes are local; sending to an Agent requires copying the request."},Co={noReference:"\\u6B64\\u9879\\u76EE\\u6CA1\\u6709\\u53C2\\u8003\\u89C6\\u9891\\u3002",shots:"\\u955C\\u5934",media:"\\u7D20\\u6750",script:"\\u6587\\u7A3F",elements:"\\u5143\\u7D20",code:"\\u4EE3\\u7801",checks:"\\u68C0\\u67E5",versions:"\\u7248\\u672C",export:"\\u5BFC\\u51FA",compare:"\\u5BF9\\u7167",layout:"\\u5E03\\u5C40",theme:"\\u4E3B\\u9898",saved:"\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A",readOnly:"\\u53EA\\u8BFB",live:"\\u5DF2\\u8FDE\\u63A5",offline:"\\u8FDE\\u63A5\\u5DF2\\u65AD\\u5F00",preview:"\\u6210\\u7247\\u9884\\u89C8",current:"\\u5F53\\u524D",add:"\\u6DFB\\u52A0",upload:"\\u5BFC\\u5165\\u7D20\\u6750",search:"\\u641C\\u7D22",scene:"\\u52A8\\u6001\\u573A\\u666F",video:"\\u89C6\\u9891",image:"\\u56FE\\u7247",color:"\\u80CC\\u666F",duration:"\\u65F6\\u957F",keepRhythm:"\\u4FDD\\u6301\\u53C2\\u8003\\u8282\\u594F",content:"\\u5185\\u5BB9",properties:"\\u5C5E\\u6027",viewAll:"\\u9002\\u914D\\u65F6\\u95F4\\u7EBF",assist:"\\u8F85\\u52A9\\u4FE1\\u606F",zoom:"\\u7F29\\u653E",audio:"\\u9879\\u76EE\\u58F0\\u97F3",onlyPreview:"\\u8BD5\\u542C\\u63A7\\u5236\\u4E0D\\u4F1A\\u6539\\u53D8\\u5BFC\\u51FA\\u58F0\\u97F3",sourceTitle:"\\u8349\\u7A3F JSON",autosave:"\\u6709\\u6548 JSON \\u5C06\\u81EA\\u52A8\\u4FDD\\u5B58",format:"\\u683C\\u5F0F\\u5316",download:"\\u4E0B\\u8F7D JSON",invalid:"JSON \\u65E0\\u6548\\uFF0C\\u5DF2\\u4FDD\\u7559\\u8F93\\u5165",saving:"\\u4FDD\\u5B58\\u4E2D\\u2026",conflict:"\\u8349\\u7A3F\\u5DF2\\u5728\\u5176\\u4ED6\\u4F4D\\u7F6E\\u4FEE\\u6539\\uFF0C\\u8BF7\\u5148\\u91CD\\u65B0\\u8F7D\\u5165\\u3002",reload:"\\u91CD\\u65B0\\u8F7D\\u5165 JSON",choose:"\\u9009\\u62E9\\u5BF9\\u8C61\\u540E\\u7F16\\u8F91",text:"\\u6587\\u5B57",audioTrack:"\\u97F3\\u9891",subtitles:"\\u5B57\\u5E55",voice:"\\u914D\\u97F3",music:"\\u97F3\\u4E50 / \\u97F3\\u6548",addText:"\\u6DFB\\u52A0\\u6587\\u5B57",duplicate:"\\u590D\\u5236",remove:"\\u5220\\u9664",undo:"\\u64A4\\u9500",redo:"\\u91CD\\u505A",time:"\\u65F6\\u95F4",wordBound:"\\u8DDF\\u968F\\u914D\\u97F3",original:"\\u539F\\u59CB",resolution:"\\u5206\\u8FA8\\u7387",dynamicRange:"\\u52A8\\u6001\\u8303\\u56F4",hdrUnavailable:"\\u5F53\\u524D HTML \\u6E32\\u67D3\\u5668\\u8F93\\u51FA SDR\\uFF0C\\u6682\\u4E0D\\u652F\\u6301 HDR\\u3002",fps:"\\u5E27\\u7387",match:"\\u5339\\u914D\\u65F6\\u95F4\\u7EBF",bitrate:"\\u89C6\\u9891\\u7801\\u7387",recommended:"\\u63A8\\u8350",filename:"\\u6587\\u4EF6\\u540D",includeAudio:"\\u5305\\u542B\\u9879\\u76EE\\u58F0\\u97F3",range:"\\u5BFC\\u51FA\\u8303\\u56F4",full:"\\u5B8C\\u6574\\u89C6\\u9891",start:"\\u5F00\\u59CB\\u5E27",end:"\\u7ED3\\u675F\\u5E27\\uFF08\\u4E0D\\u542B\\uFF09",paid:"\\u4ED8\\u8D39\\u6743\\u76CA",paidInfo:"\\u8BE5\\u529F\\u80FD\\u4E3A\\u4ED8\\u8D39\\u6743\\u76CA\\uFF0C\\u4ED8\\u8D39\\u540E\\u53EF\\u4F7F\\u7528\\u3002",unlock:"\\u524D\\u5F80\\u89E3\\u9501",refreshPlan:"\\u5237\\u65B0\\u6743\\u76CA",preparing:"\\u51C6\\u5907\\u4E2D",rendering:"\\u6B63\\u5728\\u5BFC\\u51FA",renderDone:"\\u5BFC\\u51FA\\u5B8C\\u6210",stale:"\\u6B64\\u540E\\u8349\\u7A3F\\u5DF2\\u4FEE\\u6539\\uFF0C\\u9700\\u8981\\u91CD\\u65B0\\u5BFC\\u51FA",play:"\\u64AD\\u653E",downloadVideo:"\\u4E0B\\u8F7D\\u89C6\\u9891",exportSnapshot:"\\u5BFC\\u51FA\\u4F7F\\u7528\\u5F00\\u59CB\\u65F6\\u7684 JSON \\u5FEB\\u7167\\uFF0C\\u4F60\\u53EF\\u4EE5\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002",general:"\\u5E38\\u89C4",effects:"\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548",sourceFile:"\\u6E90\\u6587\\u4EF6",missing:"\\u7F3A\\u5931",replace:"\\u66FF\\u6362",apply:"\\u5E94\\u7528",applyShot:"\\u66FF\\u6362\\u5F53\\u524D\\u955C\\u5934\\u7D20\\u6750",addOverlay:"\\u6DFB\\u52A0\\u4E3A\\u53E0\\u52A0\\u5143\\u7D20",slot:"\\u573A\\u666F\\u5B57\\u6BB5",noSlots:"\\u8BE5\\u573A\\u666F\\u672A\\u516C\\u5F00\\u53EF\\u7F16\\u8F91\\u5B57\\u6BB5\\uFF0C\\u53EF\\u901A\\u8FC7\\u4EE3\\u7801\\u66F4\\u6362\\u573A\\u666F\\u6216\\u4EA4\\u7ED9 Agent \\u4FEE\\u6539\\u3002",currentShot:"\\u5F53\\u524D\\u955C\\u5934",selected:"\\u5DF2\\u9009\\u4E2D",noMedia:"\\u9879\\u76EE\\u6682\\u65E0\\u7D20\\u6750",importHint:"\\u652F\\u6301\\u56FE\\u7247\\u3001\\u89C6\\u9891\\u548C\\u97F3\\u9891\\uFF0C\\u5355\\u6587\\u4EF6\\u4E0D\\u8D85\\u8FC7 12 MB",scriptHint:"\\u4FEE\\u6539\\u5B57\\u5E55\\u4E0D\\u4F1A\\u81EA\\u52A8\\u91CD\\u505A\\u914D\\u97F3\\u3002",pendingVoice:"\\u5B57\\u5E55\\u5DF2\\u4FEE\\u6539\\uFF0C\\u8BF7\\u6838\\u5BF9\\u914D\\u97F3",all:"\\u5168\\u90E8",notes:"\\u4FEE\\u6539\\u610F\\u89C1",comment:"\\u6DFB\\u52A0\\u65F6\\u95F4\\u70B9\\u610F\\u89C1",noteHint:"\\u63CF\\u8FF0\\u5F53\\u524D\\u753B\\u9762\\u9700\\u8981\\u600E\\u6837\\u4FEE\\u6539\\u2026",resolved:"\\u5DF2\\u5904\\u7406",resolve:"\\u6807\\u8BB0\\u5DF2\\u5904\\u7406",reopen:"\\u91CD\\u65B0\\u6253\\u5F00",copyNote:"\\u590D\\u5236\\u7ED9 Agent \\u7684\\u4FEE\\u6539\\u8BF4\\u660E",noNotes:"\\u8FD8\\u6CA1\\u6709\\u4FEE\\u6539\\u610F\\u89C1",noProblems:"\\u672A\\u53D1\\u73B0\\u7ED3\\u6784\\u95EE\\u9898",unmeasured:"\\u5F53\\u524D\\u7248\\u672C\\u6682\\u65E0\\u5BF9\\u6BD4\\u6D4B\\u91CF\\u7ED3\\u679C",saveVersion:"\\u4FDD\\u5B58\\u4E00\\u4E2A\\u7248\\u672C",restore:"\\u6062\\u590D",versionName:"\\u7248\\u672C\\u540D\\u79F0",noVersions:"\\u8FD8\\u6CA1\\u6709\\u4FDD\\u5B58\\u7684\\u7248\\u672C",defaultLayout:"\\u9ED8\\u8BA4\\u5E03\\u5C40",focusedPreview:"\\u4E13\\u6CE8\\u9884\\u89C8",codeHint:"\\u7F16\\u8F91\\u540E\\u81EA\\u52A8\\u6821\\u9A8C\\u5E76\\u66F4\\u65B0\\u540C\\u4E00\\u4EFD\\u8349\\u7A3F\\uFF1B\\u65E0\\u6548 JSON \\u4E0D\\u4F1A\\u8986\\u76D6\\u539F\\u6587\\u4EF6\\u3002",sourceChanged:"\\u8349\\u7A3F\\u5DF2\\u4FDD\\u5B58",quality:"\\u753B\\u8D28",loading:"\\u52A0\\u8F7D\\u4E2D\\u2026",sameAsReference:"\\u53C2\\u8003 / \\u6210\\u7247",toggleAnalysis:"\\u663E\\u793A\\u5206\\u6790\\u8F68\\u9053",sceneFields:"\\u573A\\u666F\\u5185\\u5BB9",position:"\\u4F4D\\u7F6E",trackGain:"\\u589E\\u76CA\\uFF08dB\\uFF09",chooseMaterial:"\\u9009\\u62E9\\u7D20\\u6750\\u540E\\uFF0C\\u6307\\u5B9A\\u66FF\\u6362\\u955C\\u5934\\u6216\\u6DFB\\u52A0\\u53E0\\u52A0\\u5143\\u7D20\\u3002",unsupported:"\\u5F53\\u524D\\u9009\\u62E9\\u4E0D\\u652F\\u6301\\u6B64\\u64CD\\u4F5C",refresh:"\\u5237\\u65B0",inspect:"\\u67E5\\u770B",seconds:"\\u79D2",waveform:"\\u6CE2\\u5F62",recheck:"\\u5237\\u65B0\\u68C0\\u67E5",sourceExport:"JSON \\u5355\\u72EC\\u4E0B\\u8F7D\\uFF0C\\u89C6\\u9891\\u901A\\u8FC7\\u5BFC\\u51FA\\u9762\\u677F\\u751F\\u6210\\u3002",goShot:"\\u5B9A\\u4F4D\\u955C\\u5934",moveUp:"\\u5411\\u524D\\u79FB\\u52A8",moveDown:"\\u5411\\u540E\\u79FB\\u52A8",narrationUnavailable:"\\u914D\\u97F3\\u751F\\u6210\\u7531 Agent \\u5904\\u7406\\uFF0C\\u590D\\u5236\\u4FEE\\u6539\\u6587\\u7A3F\\u540E\\u53EF\\u8BF7\\u6C42\\u66F4\\u65B0\\u58F0\\u97F3\\u3002",copyScript:"\\u590D\\u5236\\u4FEE\\u6539\\u540E\\u7684\\u6587\\u7A3F",applyCaption:"\\u4FDD\\u5B58\\u5B57\\u5E55",error:"\\u64CD\\u4F5C\\u672A\\u5B8C\\u6210",fileRange:"\\u6574\\u6761\\u65F6\\u95F4\\u7EBF",frame:"\\u5E27",newVersion:"Studio \\u7248\\u672C",noSelection:"\\u9009\\u62E9\\u955C\\u5934\\u3001\\u5B57\\u5E55\\u6216\\u53E0\\u52A0\\u5143\\u7D20\\u5373\\u53EF\\u7F16\\u8F91\\u3002",segment:"\\u955C\\u5934",previewQuality:"\\u9002\\u914D\\u9884\\u89C8",allChanges:"\\u6240\\u6709\\u66F4\\u6539\\u5DF2\\u4FDD\\u5B58",currentExport:"\\u5BFC\\u51FA\\u5F53\\u524D\\u8349\\u7A3F",jsonDownload:"\\u4E0B\\u8F7D\\u5DF2\\u4FDD\\u5B58\\u7684 video.json",imageSlot:"\\u66FF\\u6362\\u56FE\\u7247\\u69FD",selectedSlot:"\\u5F53\\u524D\\u573A\\u666F\\u5B57\\u6BB5",sceneOffset:"\\u573A\\u666F\\u5143\\u7D20\\u504F\\u79FB",fontSize:"\\u5B57\\u53F7",textColor:"\\u6587\\u5B57\\u989C\\u8272",versionSnapshot:"\\u7248\\u672C\\u4FDD\\u5B58\\u8349\\u7A3F JSON\\uFF0C\\u5E76\\u7EE7\\u7EED\\u5F15\\u7528\\u539F\\u7D20\\u6750\\u3002",bitrateUnit:"Mbps",reviewOnly:"\\u610F\\u89C1\\u4FDD\\u5B58\\u5728\\u672C\\u673A\\uFF1B\\u590D\\u5236\\u540E\\u53EF\\u4EA4\\u7ED9 Agent \\u7EE7\\u7EED\\u4FEE\\u6539\\u3002"},x=(e,t)=>(e.get().lang==="zh"?Co:Ao)[t];var C=(e,t,n="")=>u("button",{class:"studio-btn "+n,text:e,attrs:{type:"button"},on:{click:t}}),ne=(e,t,n)=>u("button",{class:"studio-btn studio-icon-btn",attrs:{type:"button",title:e,"aria-label":e},on:{click:n}},[Y(t)]),U=(e,t)=>u("div",{class:"studio-heading"},[u("h2",{text:e}),...t?[u("small",{text:t})]:[]]),A=(e,t="")=>u("p",{class:"studio-note "+t,text:e}),Ce=e=>"/project/"+e.replace(/^\\.\\//,"").split("/").map(encodeURIComponent).join("/"),rn=(e,t)=>{let n=URL.createObjectURL(new Blob([e],{type:"application/json"}));u("a",{attrs:{href:n,download:t}}).click(),setTimeout(()=>URL.revokeObjectURL(n),1e3)},ce=(e,t)=>{let n=document.getElementById("studio-message");n?(n.textContent=t,n.classList.add("visible"),setTimeout(()=>n.classList.remove("visible"),6e3)):e.set({pageError:t})},J=async(e,t)=>{let n=await fetch(e,{...t===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)},cache:"no-store"}),o=await n.json();if(!n.ok||o.ok===!1)throw new Error(o.problems?.[0]?.message??"Request failed: "+n.status);return o},ke=async(e,t,n)=>{try{let o=await J(t,n);e.set({state:o.state})}catch(o){ce(e,o instanceof Error?o.message:x(e,"error"))}},G=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>Array.isArray(e)?e.map(G):[],Oe=(e,t,n)=>{let o=u("input",{attrs:{type:"text","aria-label":t},class:"studio-input"});return o.value=e,n&&o.addEventListener("change",()=>n(o.value)),o},wt=(e,t,n,o)=>{let r=u("select",{class:"studio-input",attrs:{"aria-label":n}},e.map(([s,a])=>u("option",{text:a,attrs:{value:s}})));return r.value=t,r.addEventListener("change",()=>o(r.value)),r},Me=(e,t)=>u("label",{class:"studio-field"},[u("span",{text:e}),t]),sn=(e,t)=>u("img",{class:"studio-thumb",attrs:{src:"/api/thumbnail?frame="+Math.floor(e)+"&g="+t,loading:"lazy",alt:""}}),Ze=(e,t)=>{let n=Math.floor(e/t);return[Math.floor(n/60),n%60,e%Math.round(t)].map(o=>Math.floor(o).toString().padStart(2,"0")).join(":")};var be=(e,t,n=t.get().frame)=>{let o=t.get(),r=o.state?.resolved;if(!r)return[];let s=Z(r,n);if(!s)return[];let a=e.contentDocument;if(!a)return[];let c=[];for(let i of Array.from(a.querySelectorAll("iframe"))){let d=i.contentDocument,l=i.contentWindow;if(!d||!l||i.parentElement?.dataset.segment!==s.id)continue;let f=i.getBoundingClientRect();if(!(!f.width||!f.height)&&l.getComputedStyle(i).visibility!=="hidden")for(let g of Array.from(d.querySelectorAll("[data-slot]"))){let p=!0,m=1;for(let y=g;y;y=y.parentElement){let v=l.getComputedStyle(y);m*=Number(v.opacity),(v.display==="none"||v.visibility==="hidden")&&(p=!1)}let h=g.getBoundingClientRect();if(!p||m<.1||!h.width||!h.height||h.right<=0||h.bottom<=0||h.left>=i.clientWidth||h.top>=i.clientHeight)continue;let b=g.dataset.slot;b&&c.push({selection:{kind:"slot",id:s.id,name:b},box:[(f.left+h.left*f.width/(i.clientWidth||r.canvas.width))/r.canvas.width,(f.top+h.top*f.height/(i.clientHeight||r.canvas.height))/r.canvas.height,h.width/r.canvas.width,h.height/r.canvas.height],value:g.tagName==="IMG"?g.getAttribute("src")??"":g.textContent??"",image:g.tagName==="IMG"})}}return c},an=new WeakMap,He=(e,t,n)=>{let o=t.get(),r=o.state?.resolved?.segments.find(f=>f.id===n),s=e?.contentWindow?.__popostVideo;if(!e||!r||!s||document.body.dataset.ready!=="1"||new URL(e.src).searchParams.get("g")!==String(o.state?.generation)||r.base.kind!=="scene")return;let a=e.contentDocument,c=a?.querySelector('[data-segment="'+CSS.escape(n)+'"] > iframe')?.contentDocument;if(!a||!c||c.URL==="about:blank"||c.readyState!=="complete")return;let i=an.get(e);(!i||i.generation!==o.state.generation||i.page!==a)&&(i={generation:o.state.generation,page:a,segments:new Map},an.set(e,i));let d=i.segments.get(n);if(d?.scene===c)return d.frames;let l=new Map;try{for(let f=0;f<=32;f++){let g=Math.min(r.end-1,r.start+Math.floor((r.end-r.start)*f/33));s.applyFrame(g);for(let p of be(e,t,g))l.has(p.selection.name)||l.set(p.selection.name,g)}}finally{s.applyFrame(o.frame)}return i.segments.set(n,{scene:c,frames:l}),l},Qe=(e,t,n)=>e&&be(e,t).some(o=>o.selection.id===n.id&&o.selection.name===n.name)?t.get().frame:He(e,t,n.id)?.get(n.name),dn=(e,t)=>{let n=e.get(),o=n.pinned,r=u("div",{class:"form",id:"slot-inspector"});if(o?.kind!=="slot")return r;let s=n.lang==="zh",a=G(n.state?.source),c=$(a.segments).findIndex(i=>i.id===o.id);return r.append(u("div",{class:"sel-title",text:s?"\\u573A\\u666F\\u5143\\u7D20":"Scene element"})),J("/api/studio").then(i=>{if(!r.isConnected)return;let d=i.slots.find(g=>g.segment===o.id&&g.name===o.name);if(!d)return;let l=d.kind==="image"?Oe(d.value,s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"):u("textarea",{class:"studio-input",attrs:{rows:"5","aria-label":s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content"}});l.value=d.value;let f=g=>{let p=G($(G(e.get().state?.source).segments)[c]?.base);t.send({op:"set",path:["segments",c,"base","slots"],value:{...G(p.slots),[d.name]:g}})};if(l.addEventListener("change",()=>f(l.value)),l.addEventListener("keydown",g=>{let p=g;(p.ctrlKey||p.metaKey)&&p.key==="Enter"&&l.blur()}),d.kind==="image"){let g=G($(a.segments)[c]?.base),p=String(g.scene??""),m=new URL(d.value,location.origin+"/project/"+p);m.origin===location.origin&&m.pathname.startsWith("/project/")&&r.append(u("img",{class:"studio-slot-preview",attrs:{src:m.href,alt:s?"\\u5F53\\u524D\\u56FE\\u7247":"Current image"}}));let h=$(a.materials).filter(b=>b.kind==="image");if(h.length){let b=u("select",{class:"studio-input",attrs:{"aria-label":s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image"}},[u("option",{text:s?"\\u9009\\u62E9\\u7D20\\u6750\\u4E2D\\u7684\\u56FE\\u7247":"Choose an image",attrs:{value:""}}),...h.map((y,v)=>u("option",{text:String(y.note??y.file??(s?"\\u56FE\\u7247 ":"Image ")+(v+1)),attrs:{value:String(y.id)}}))]);b.addEventListener("change",()=>{let y=h.find(v=>v.id===b.value);y&&f("../".repeat(p.split("/").length-1)+String(y.file))}),r.append(Me(s?"\\u66FF\\u6362\\u56FE\\u7247":"Replace image",b))}else r.append(A(s?"\\u5148\\u5728\\u7D20\\u6750\\u4E2D\\u5BFC\\u5165\\u56FE\\u7247\\uFF0C\\u518D\\u56DE\\u5230\\u8FD9\\u91CC\\u66FF\\u6362\\u3002":"Import an image in Media, then select it here."));r.append(u("details",{},[u("summary",{text:s?"\\u56FE\\u7247\\u5730\\u5740":"Image path"}),l]))}else r.append(Me(s?"\\u6587\\u5B57\\u5185\\u5BB9":"Text content",l));r.append(A(s?"\\u4FEE\\u6539\\u4F1A\\u4FDD\\u5B58\\u5230\\u5F53\\u524D\\u5DE5\\u7A0B\\uFF0C\\u5E76\\u7528\\u4E8E\\u89C6\\u9891\\u5BFC\\u51FA\\u3002":"Changes are saved to this project and used in the exported video."))}).catch(i=>r.append(A(String(i),"bad"))),r};var ln=(e,t,n,o)=>{let r,s=a=>{let c=r;c&&(r=void 0,a&&c.dispatchEvent(new Event("commit")),c.remove())};e.addEventListener("studio:inline-edit",a=>{if(r)return;let c=n.get(),i=c.pinned;if(!i||!c.state||a.target.closest(".handle"))return;let d=q(c.state,i),l=i.kind==="item"?c.state.resolved?.items.find(h=>h.id===i.id):void 0,f=i.kind==="slot"?be(t,n).find(h=>h.selection.id===i.id&&h.selection.name===i.name):void 0;if(f?.image||d?.kind==="track"&&d.track.type==="image"){document.querySelector('#slot-inspector select, #edit-form select[data-path$=".material"]')?.focus();return}let g=f?.value??l?.text,p=f?.box??(d?Re(c.state,d):void 0);if(g===void 0||!p)return;s(!0),a.preventDefault(),a.stopPropagation();let m=u("textarea",{id:"stage-text-editor",class:"stage-text-editor",attrs:{"aria-label":c.lang==="zh"?"\\u76F4\\u63A5\\u7F16\\u8F91\\u6587\\u5B57":"Edit text on canvas"}});m.value=g,le(m,p),m.style.fontSize=Math.max(14,(l?.style?.size??.04)*(c.state.resolved?.canvas.height??1)*e.clientWidth/(c.state.resolved?.canvas.width??1))+"px",m.addEventListener("commit",()=>{if(!(m.value===g||!m.value.trim()))if(i.kind==="slot"){let h=n.get().state,b=$(G(h?.source).segments).findIndex(v=>v.id===i.id),y=G($(G(h?.source).segments)[b]?.base);o.send({op:"set",path:["segments",b,"base","slots"],value:{...G(y.slots),[i.name]:m.value}})}else d?.kind==="cue"?o.send({op:"set",path:["tracks",d.index,"cues",d.cue,"text"],value:m.value}):d?.kind==="track"&&o.send({op:"set",path:["tracks",d.index,"text"],value:m.value})}),m.addEventListener("blur",()=>s(!0)),m.addEventListener("pointerdown",h=>h.stopPropagation()),m.addEventListener("keydown",h=>{h.key==="Escape"?(h.preventDefault(),h.stopPropagation(),s(!1)):h.key==="Enter"&&(h.metaKey||h.ctrlKey)&&(h.preventDefault(),s(!0))}),e.append(m),r=m,m.focus(),m.select()}),n.subscribe((a,c)=>{(a.pinned!==c.pinned||a.state!==c.state||a.frame!==c.frame)&&s(!1)})};var Oo=["nw","n","ne","e","se","s","sw","w"],Ho=(e,t)=>{if(t.kind==="segment")return[];let n=String(t.track.id);return(e.state?.resolved?.items??[]).filter(o=>o.id===n||o.cue?.track===n).map(o=>o.id)},No=(e,t)=>{let n=e.state?.resolved;if(!n||t.kind==="segment")return!1;let o=t.kind==="cue"?String(t.track.id)+"#"+t.cue:String(t.track.id);return fe(n,e.frame).some(r=>r.id===o)},Io=(e,t,n,o,r,s)=>{let[a,c,i,d]=e.box0,l=(E,M)=>Math.round(E*M)/M;if(e.mode==="move")return[l(a+t,o),l(c+n,r),i,d];let[f,g,p,m]=[a,c,a+i,c+d];if(e.mode.includes("w")&&(f+=t),e.mode.includes("e")&&(p+=t),e.mode.includes("n")&&(g+=n),e.mode.includes("s")&&(m+=n),s){let E=i*o/(d*r),M=p-f,k=m-g;if(e.mode.length===1?e.mode==="e"||e.mode==="w":Math.abs(M/i-1)>=Math.abs(k/d-1)){let L=M*o/E/r;e.mode.includes("n")?g=m-L:(e.mode.includes("s")||(g=c+d/2-L/2),m=g+L)}else{let L=k*r*E/o;e.mode.includes("w")?f=p-L:(e.mode.includes("e")||(f=a+i/2-L/2),p=f+L)}}let[h,b,y,v]=[l(f,o),l(g,r),l(p,o),l(m,r)];return[Math.min(h,y-1/o),Math.min(b,v-1/r),Math.max(1/o,y-h),Math.max(1/r,v-b)]},Fo=(e,t,n)=>{let o=(s,a)=>String(Math.round(s*a)),r=s=>s.toFixed(3);return"x "+o(e[0],t)+" y "+o(e[1],n)+" "+o(e[2],t)+"\\xD7"+o(e[3],n)+" px ("+[e[0],e[1],e[2],e[3]].map(r).join(", ")+")"},Do=(e,t)=>{let n=new Map;return{move:(o,r)=>{let s=e.contentDocument,{W:a,H:c}=$e(t.get());for(let i of Ho(t.get(),o)){let d=s?.querySelector('[data-item="'+CSS.escape(i)+'"]');d&&(n.has(d)||n.set(d,d.style.cssText),Object.assign(d.style,{left:r[0]*a+"px",top:r[1]*c+"px",width:r[2]*a+"px",height:r[3]*c+"px"}))}},restore:()=>{n.forEach((o,r)=>{r.style.cssText=o}),n=new Map},forget:()=>{n=new Map}}},$e=e=>({W:e.state?.resolved?.canvas.width??1,H:e.state?.resolved?.canvas.height??1}),jo=(e,t,n,o)=>{let r=t.state?.resolved;if(!r)return;let s=e.getBoundingClientRect(),a=(n-s.left)/s.width,c=(o-s.top)/s.height;return[...fe(r,t.frame)].reverse().find(i=>a>=i.box[0]&&a<=i.box[0]+i.box[2]&&c>=i.box[1]&&c<=i.box[1]+i.box[3])?.id},zo=(e,t,n)=>{let o=t.state?q(t.state,t.pinned):void 0,r=n??(o&&t.state?Re(t.state,o):void 0),s=!!(r&&o&&(n||No(t,o)));if(e.layer.classList.toggle("off",!t.state?.resolved),e.sel.hidden=!s,e.readout.hidden=!n,s&&r&&(le(e.sel,r),e.sel.classList.toggle("thin",e.sel.getBoundingClientRect().height<18)),n){let{W:a,H:c}=$e(t);e.readout.textContent=Fo(n,a,c)}},cn=e=>{let t=e.state?q(e.state,e.pinned):void 0,n=t&&e.state?Re(e.state,t):void 0;return t&&n?{t,box:n}:void 0},et=(e,t,n,o)=>{let r=u("div",{class:"sel-box",id:"sel-box"},Oo.map(v=>u("div",{class:"handle h-"+v,data:{h:v}}))),s=u("div",{class:"drag-readout",id:"drag-readout"}),a=u("div",{class:"studio-slot-outline",attrs:{hidden:""}},[u("span",{class:"studio-slot-name"})]),c={layer:u("div",{class:"edit-layer",id:"edit-layer"},[r,s]),sel:r,readout:s};c.layer.append(a),e.append(c.layer),ln(e,t,n,o);let i=Do(t,n),d,l,f,g,p=!0,m=()=>{let v=n.get();zo(c,v,d&&!d.moved?void 0:f?.box);let E=v.pinned,M=E?.kind==="slot"?be(t,n).find(k=>k.selection.id===E.id&&k.selection.name===E.name):void 0;if(E?.kind==="slot"&&p&&document.body.dataset.ready==="1"){p=!1;let k=Qe(t,n,E);if(k===void 0){o.select(null);return}if(k!==v.frame){o.reveal(E,k);return}}a.hidden=!M,M&&(le(a,M.box),a.firstElementChild.textContent=M.image?v.lang==="zh"?"\\u56FE\\u7247":"Image":M.value.slice(0,40))},h=(v,E)=>{let M=bt(v);M&&o.send({op:"set",path:M,value:Zt(E)}).then(k=>{k||i.restore(),f=void 0,m()})},b=(v,E)=>{f={box:E,target:v},i.move(v,E),m()};c.layer.addEventListener("pointerdown",v=>{if(v.button!==0||!n.get().state?.resolved||n.get().edit.saving||v.target.closest("#stage-text-editor"))return;let E=n.get().pinned;if((E?.kind==="slot"?be(t,n).some(L=>L.selection.id===E.id&&L.selection.name===E.name&&!L.image):E?.kind==="item"&&n.get().state?.resolved?.items.some(L=>L.id===E.id&&L.type==="text"))&&l&&performance.now()-l.time<450&&Math.hypot(v.clientX-l.x,v.clientY-l.y)<6&&!v.target.closest(".handle")){l=void 0,e.dispatchEvent(new Event("studio:inline-edit")),v.preventDefault();return}document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let k=v.target.closest(".handle")?.dataset.h;if(!k&&!v.target.closest(".sel-box")){let L=jo(e,n.get(),v.clientX,v.clientY);if(!L){let R=e.getBoundingClientRect(),F=(v.clientX-R.left)/R.width,O=(v.clientY-R.top)/R.height,D=be(t,n).reverse().find(w=>F>=w.box[0]&&F<=w.box[0]+w.box[2]&&O>=w.box[1]&&O<=w.box[1]+w.box[3]);if(D){o.select(D.selection),l={time:performance.now(),x:v.clientX,y:v.clientY},v.preventDefault();return}}if(o.select(L?{kind:"item",id:L}:null),!L)return}let H=cn(n.get());H&&(d={mode:k??"move",x0:v.clientX,y0:v.clientY,box0:f?.box??H.box,moved:!1,target:H.t},c.layer.setPointerCapture(v.pointerId),v.preventDefault())}),c.layer.addEventListener("pointermove",v=>{if(!d||!d.moved&&Math.hypot(v.clientX-d.x0,v.clientY-d.y0)<2)return;d.moved=!0;let E=e.getBoundingClientRect(),{W:M,H:k}=$e(n.get());b(d.target,Io(d,(v.clientX-d.x0)/E.width,(v.clientY-d.y0)/E.height,M,k,v.shiftKey))});let y=v=>{if(v.type==="pointercancel"){d=void 0,f=void 0,l=void 0,i.restore(),m();return}let E=d;d=void 0,E&&!E.moved&&(l={time:performance.now(),x:E.x0,y:E.y0}),E?.moved&&f&&(l=void 0,h(E.target,f.box)),m()};return c.layer.addEventListener("pointerup",y),c.layer.addEventListener("pointercancel",y),n.subscribe((v,E)=>{v.state!==E.state&&i.forget(),(v.pinned!==E.pinned||v.state!==E.state)&&(p=!0),!d&&(v.state!==E.state||v.pinned!==E.pinned||v.frame!==E.frame)&&m()}),t.addEventListener("frameapplied",m),new ResizeObserver(m).observe(e),m(),{nudge:(v,E)=>{let M=cn(n.get()),k=f?.box??M?.box;if(!M||!k||d)return!1;let{W:H,H:L}=$e(n.get()),R=[Math.round(k[0]*H+v)/H,Math.round(k[1]*L+E)/L,k[2],k[3]];return b(M.t,R),g&&clearTimeout(g),g=setTimeout(()=>h(M.t,R),400),!0}}};var tt=(e,t,n)=>{let r=[{id:"edit-undo",icon:"undo",title:"undo",run:()=>{n.undo()},enabled:c=>(c.state?.edit?.undo??0)>0},{id:"edit-redo",icon:"redo",title:"redo",run:()=>{n.redo()},enabled:c=>(c.state?.edit?.redo??0)>0},{id:"edit-add-text",icon:"addText",title:"addText",run:()=>{n.addText()},enabled:c=>!!c.state?.resolved},{id:"edit-duplicate",icon:"duplicate",title:"duplicate",run:()=>{n.duplicate()},enabled:()=>n.target()!==void 0},{id:"edit-delete",icon:"remove",title:"remove",run:()=>{n.remove()},enabled:c=>{let i=n.target();return!!(i&&(i.kind!=="segment"||(c.state?.resolved?.segments.length??0)>1))}},{id:"edit-render",icon:"render",title:"renderTool",run:()=>{n.render()},enabled:c=>!!c.state?.resolved&&c.edit.render?.state!=="running"}].map(c=>{let i=u("button",{id:c.id,class:"tbtn",attrs:{type:"button"}},[Y(c.icon)]);return["edit-add-text","edit-duplicate","edit-delete"].includes(c.id)&&i.append(u("span",{class:"tool-label"})),i.addEventListener("click",()=>{c.run(),i.blur()}),{tool:c,el:i}}),s=(c,i)=>u("span",{class:"tool-group"},r.slice(c,i).map(d=>d.el));e.append(u("span",{class:"edit-tools",id:"edit-tools"},[s(0,2),s(2,5),s(5,6)]));let a=c=>{for(let i of r){i.el.title=S(c.lang,i.tool.title);let d=i.el.querySelector(".tool-label");d&&(d.textContent=i.tool.id==="edit-add-text"?c.lang==="zh"?"\\u6587\\u5B57":"Text":i.tool.id==="edit-duplicate"?c.lang==="zh"?"\\u590D\\u5236":"Duplicate":c.lang==="zh"?"\\u5220\\u9664":"Delete"),i.el.setAttribute("aria-label",S(c.lang,i.tool.title)),i.el.disabled=!!c.edit.saving||!i.tool.enabled(c)}};a(t.get()),t.subscribe((c,i)=>{(c.state!==i.state||c.lang!==i.lang||c.pinned!==i.pinned||c.edit.render!==i.edit.render||c.edit.saving!==i.edit.saving)&&a(c)})},Bo={set:"saved",insert:"added",remove:"removed",move:"moved",outside:"outside"},Vo=e=>{let t=e.edit.status,n=e.lang;if(!t)return"";if(t.kind==="note")return S(n,t.key==="phraseSpan"?"phraseSpan":"offlineEdit");if(t.kind==="refused")return S(n,"notSaved")+": "+(t.problem.at.startsWith("(")?"":t.problem.at+": ")+t.problem.message+(t.problem.fix?" "+S(n,"fix")+": "+t.problem.fix:"");let o=t.step==="outside"?S(n,"outside"):t.label;return t.op==="undo"||t.op==="redo"?S(n,t.op==="undo"?"undone":"redone")+": "+o:S(n,Bo[t.op]??"saved")+": "+o},_o=(e,t,n)=>{let o=e.edit.render;if(!o||o.state==="idle")return[];if(o.state==="running")return[u("span",{text:S(n,"rendering")+": "+o.frame+" / "+(o.total||"?")})];if(o.state==="failed")return[u("span",{class:"bad",text:S(n,"renderFailed")+": "+o.message})];let r=u("button",{id:"play-render",class:"link",text:S(n,e.edit.playRender?"showReference":"playRender"),attrs:{type:"button"}});return r.addEventListener("click",()=>t.togglePlayRender()),[u("span",{text:S(n,"rendered")+": "+o.frames+" "+S(n,"framesIn")+" "+o.seconds+" s, ",title:o.file}),u("code",{text:o.file.split(/[\\\\/]/).pop()??o.file,title:o.file})," ",r]},nt=(e,t,n)=>{let o=u("div",{id:"edit-status",class:"status-line",attrs:{role:"status","aria-live":"polite"}}),r=u("div",{id:"render-status",class:"status-line render"});e.prepend(u("div",{class:"edit-status"},[o,r]));let s=a=>{o.textContent=Vo(a),o.classList.toggle("bad",a.edit.status?.kind==="refused"),r.replaceChildren(..._o(a,n,a.lang))};s(t.get()),t.subscribe((a,c)=>{(a.edit!==c.edit||a.lang!==c.lang)&&s(a)})},Ko=e=>e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLInputElement&&!["checkbox","range","button","color"].includes(e.type)||e instanceof HTMLElement&&e.isContentEditable,ot=(e,t,n)=>{document.addEventListener("keydown",o=>{if(document.querySelector('[role="dialog"]'))return;if(Ko(o.target)){if(o.target.id==="stage-text-editor")return;o.key==="Escape"&&o.target.blur();return}let r=o.ctrlKey||o.metaKey,s=o.key.toLowerCase(),a=l=>{o.preventDefault(),o.stopPropagation(),l()};if(r&&s==="z")return a(()=>{o.shiftKey?t.redo():t.undo()});if(r&&s==="y")return a(()=>{t.redo()});if(r&&s==="d")return a(()=>{t.duplicate()});if(r||o.altKey)return;if(s==="s")return a(()=>{t.split()});if(o.key==="Delete"||o.key==="Backspace")return a(()=>{t.remove()});if(o.key==="Escape")return a(()=>t.select(null));let i={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[o.key];if(!i||!e.get().pinned)return;let d=o.shiftKey?10:1;n(i[0]*d,i[1]*d)&&a(()=>{})},!0)};var un=(e,t,n)=>e.reduce((o,[r,s])=>Math.max(o,Math.min(1,Math.max(0,(n-(r-t))/t),Math.max(0,(s+t-n)/t))),0),mn=e=>Math.min(1,Math.max(0,e)),Uo=(e,t)=>{if(!e)return 0;let{out:n,in:o}=e;return e.spans.reduce((r,[s,a])=>Math.max(r,Math.min(mn((t-(s-n))/n),mn((a+o-t)/o))),0)},Jo=(e,t)=>{let n=Uo(e,t);return n<=0?0:n>=1?120:Math.min(120,-20*Math.log10(1-n))},pn=(e,t)=>e?e.db*un(e.spans,e.ramp,t)+(e.away?e.away.db*un(e.away.spans,e.away.ramp,t):0)+(e.gaps?Jo(e.gaps,t):0):0;var gn=e=>{let t=[],n,o=()=>{for(let s of t)s.audio.pause(),s.audio.removeAttribute("src"),s.gain.disconnect();t=[]},r=()=>{let s=e.get(),a=s.state?.resolved;if(!a)return;let c=a.audio;(c.length!==t.length||t.some((d,l)=>d.source!==c[l]?.src))&&(o(),n??=new AudioContext,t=c.map(d=>{let l=new Audio;l.crossOrigin="anonymous",l.preload="auto",l.src=Ce(d.src);let f=n.createGain();return n.createMediaElementSource(l).connect(f).connect(n.destination),{audio:l,gain:f,source:d.src}})),s.playing&&n?.state==="suspended"&&n.resume().catch(()=>{});let i=s.frame/a.canvas.fps;t.forEach((d,l)=>{let f=c[l];if(!f)return;d.gain.gain.value=s.muted?0:10**((f.gain-pn(f.duck,s.frame))/20);let g=s.frame>=f.start&&(f.end===void 0||s.frame<f.end),p=Math.max(0,(i-f.start/a.canvas.fps)*(f.speed??1)+(f.from?f.from.frame/f.from.fps:0));d.audio.playbackRate=s.speed*(f.speed??1),g&&!d.audio.seeking&&Math.abs(d.audio.currentTime-p)>.2&&(d.audio.currentTime=p),s.playing&&g&&!s.muted?d.audio.paused&&d.audio.play().catch(()=>{}):d.audio.pause()})};e.subscribe((s,a)=>{(s.state!==a.state||s.frame!==a.frame||s.playing!==a.playing||s.muted!==a.muted||s.speed!==a.speed)&&r()}),window.addEventListener("pagehide",()=>{o(),n?.close()})},fn=new Map,hn=e=>{let t=fn.get(e);if(t)return t;let n=(async()=>{let o=new AudioContext;try{let r=await fetch(Ce(e)),a=(await o.decodeAudioData(await r.arrayBuffer())).getChannelData(0),c=[];for(let i=0;i<500;i++){let d=Math.floor(i*a.length/500),l=Math.floor((i+1)*a.length/500),f=0;for(let g=d;g<l;g+=8)f=Math.max(f,Math.abs(a[g]??0));c.push(f)}return c}finally{await o.close()}})();return fn.set(e,n),n};var En=" \\xB7 ",Ne=e=>({sel:JSON.stringify(e)}),ue=(e,t,n,o={})=>u("div",{class:"lane "+(o.cls??""),id:"lane-"+e,...o.height?{style:"height:"+o.height+"px"}:{}},[u("div",{class:"lane-label",text:t,title:t,...o.labelSel?{data:Ne(o.labelSel)}:{}}),u("div",{class:"lane-track"},n)]),ae=(e,t,n,o,r,s,a)=>Le(u("div",{class:e,text:r,title:s,...a?{data:Ne(a)}:{}}),t,n,o),Wo=(e,t,n)=>ue("ruler",S(n,"ruler"),jt(e,t).map(o=>Q(u("div",{class:"rtick",text:o.label,title:"frame "+o.frame}),o.frame,e)),{cls:"ruler"}),qo=e=>e.segments.map(t=>Q(u("div",{class:"seg-grip",title:t.id+": "+(t.end-t.start)+" frames",data:{border:String(t.index)}}),t.end,e.frames)),bn=(e,t,n,o)=>{let r=e.frames,s=e.segments.flatMap(a=>{let c=a.base.kind==="color"?a.base.color:void 0,i=ae("blk seg",a.start,a.end,r,a.id,a.id+": frames "+a.start+".."+(a.end-1),{kind:"segment",id:a.id});i.textContent="",i.setAttribute("role","button"),i.tabIndex=0,i.setAttribute("aria-label",(t==="zh"?"\\u955C\\u5934 ":"Shot ")+(a.index+1)+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"),i.dataset.index=String(a.index),i.append(u("img",{attrs:{loading:"lazy",alt:"",src:"/api/thumbnail?frame="+Math.floor((a.start+a.end)/2)+"&g="+o}}),u("span",{class:"segment-name",text:String(a.index+1).padStart(2,"0")+" \\xB7 "+((a.end-a.start)/e.canvas.fps).toFixed(2)+"s"})),c&&i.prepend(u("span",{class:"swatch",style:"background:"+c}));let d=a.transition;if(!d)return a.index===0?[i]:[i,Q(u("div",{class:"tick"}),a.start,r)];let l=Nt(d),f=ae("band",d.a,d.a+d.frames,r,"",l+": mixed frames "+d.a+".."+(d.a+d.frames-1)+", takes over at "+d.boundary,{kind:"segment",id:a.id});return f.append(u("span",{class:"band-label",text:l})),[i,f,Q(u("div",{class:"tick"}),a.start,r)]});return ue("segments",S(t,"segments"),n?[...s,...qo(e)]:s,{cls:"segments"})},yn=(e,t,n)=>{let o={kind:"item",id:e.id},r=[ae("blk item",e.start,e.end,t,"",e.id+" ("+e.type+"): frames "+e.start+".."+(e.end-1),o)];if(e.enter.frames>0&&r.push(ae("shade enter",e.start,e.start+e.enter.frames,t,Te(e.enter),"enter: "+Te(e.enter)+", "+e.enter.ease,o)),e.exit.frames>0&&r.push(ae("shade exit",e.end-e.exit.frames,e.end,t,Te(e.exit),"exit: "+Te(e.exit)+", "+e.exit.ease,o)),n)for(let[s,a]of[["start",e.start],["end",e.end]])r.push(Q(u("div",{class:"grip "+s,data:{grip:s,...Ne(o)}}),a,t));return ue("item-"+e.id,e.id+En+e.type,r,{labelSel:o})},vn=(e,t,n,o=!1)=>{let r={kind:"audio",id:e.id},s=n==="zh"?"\\u97F3\\u9891":"Audio",a=ae("blk audio",e.start,e.end??t,t,s,s,r);a.setAttribute("role","button"),a.tabIndex=0,a.setAttribute("aria-label",s),hn(e.src).then(i=>{let d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox","0 0 500 28"),d.setAttribute("preserveAspectRatio","none");let l=document.createElementNS(d.namespaceURI,"path");l.setAttribute("d",i.map((f,g)=>"M"+g+" "+(14-Math.max(1,f*13))+"v"+Math.max(2,f*26)).join("")),l.setAttribute("stroke","#69967c"),l.setAttribute("stroke-width","0.8"),d.append(l),a.append(d),a.classList.add("wave-ready")}).catch(()=>{});let c=["start","end"].map(i=>Q(u("div",{class:"grip "+i,data:{grip:i,...Ne(r)}}),i==="start"?e.start:e.end??t,t));return ue("audio-"+e.id,S(n,"audio"),[a,...o?c:[]],{labelSel:r})},Go=(e,t,n)=>ue("words-"+e.track,S(n,"words")+": "+e.track,e.tokens.map(o=>ae("blk audio word"+(o.confidence<.4?" unsure":""),o.start,o.end,t,o.text,o.text+": frames "+o.start+".."+(o.end-1)+En+"confidence "+o.confidence)),{cls:"words-lane"}),Yo=(e,t,n,o,r)=>{let s=e.measure,a=i=>ye(i,s.source.fps,o),c=s.boundaries.flatMap((i,d)=>{let l={kind:"boundary",source:t,index:d},f=It(i),g=f+": frames "+i.start+".."+i.end+" of the measured file, takes over at "+i.frame,p=Q(u("div",{class:"mark",title:g,data:Ne(l)},[u("span",{class:"mark-label",text:f})]),a(i.frame),n);return i.kind==="cut"?[p]:[ae("mband",a(i.start+1),a(i.end),n,"",g,l),p]});return ue(t+"-boundaries",S(r,t==="render"?"renderBoundaries":"referenceBoundaries"),c,{cls:"measure "+t})},Sn=14,Xo=4,Zo=(e,t,n,o,r)=>{let s=e.measure,a=Ft(s).map(l=>({start:ye(l.event.start,s.source.fps,o),end:ye(l.event.end,s.source.fps,o),value:l})),c=mt(a,Xo),i=c.map(l=>{let f=ze(l.value.event),g=ae("ev",l.start,l.end,n,f,f+": frames "+l.value.event.start+".."+(l.value.event.end-1)+" of the measured file",{kind:"event",source:t,shot:l.value.shot,index:l.value.index});return g.style.top=3+l.row*Sn+"px",g}),d=Math.max(1,...c.map(l=>l.row+1));return ue(t+"-events",S(r,t==="render"?"renderEvents":"referenceEvents"),i,{cls:"measure "+t,height:6+d*Sn})},Qo=(e,t,n)=>{let o=W(e),r=se(e),s=e.resolved,a=e.edit!==void 0,c=[Wo(o,r,t)];if(s)if(a){let i=bn(s,t,a,e.generation);i.querySelector(".lane-label").textContent=t==="zh"?"\\u955C\\u5934":"Shots",c.push(i);let d=[{id:"subtitles",label:t==="zh"?"\\u5B57\\u5E55":"Subtitles",items:s.items.filter(l=>l.cue),cls:"caption-lane"},{id:"text",label:t==="zh"?"\\u6587\\u5B57":"Text",items:s.items.filter(l=>!l.cue&&l.type==="text"),cls:"caption-lane"},{id:"media",label:t==="zh"?"\\u7D20\\u6750":"Media",items:s.items.filter(l=>!l.cue&&l.type!=="text"),cls:"media-lane"}];for(let l of n.timeline?.layers===!1?[]:d){let f=mt(l.items.map(p=>({start:p.start,end:p.end,value:p})).sort((p,m)=>p.start-m.start||m.value.z-p.value.z||p.value.id.localeCompare(m.value.id)),Math.max(1,l.items.length)),g=Math.max(0,...f.map(p=>p.row+1));for(let p=0;p<g;p++){let m=f.filter(h=>h.row===p).flatMap(({value:h})=>{let b=Array.from(yn(h,o,a).querySelector(".lane-track").children),y=b[0];if(y){let v=h.text??(t==="zh"?h.type==="video"?"\\u89C6\\u9891":h.type==="image"?"\\u56FE\\u7247":"\\u5F62\\u72B6":h.type);y.textContent=v,y.title=v,y.setAttribute("role","button"),y.setAttribute("tabindex","0"),y.setAttribute("aria-label",v)}return b});c.push(ue(l.id+"-"+p,l.label+(p?" "+(p+1):""),m,{cls:l.cls}))}}if(n.timeline?.layers!==!1)for(let l of n.slots??[]){let f=s.segments.find(h=>h.id===l.segment);if(!f)continue;let g={kind:"slot",id:l.segment,name:l.name},p=l.kind==="image"?t==="zh"?"\\u56FE\\u7247":"Image":l.value,m=ae("blk item scene-field",f.start,f.end,o,p,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A\\u65F6\\u95F4\\u7531\\u573A\\u666F\\u63A7\\u5236\\uFF0C\\u70B9\\u9009\\u540E\\u7F16\\u8F91\\u5185\\u5BB9":"Scene content: timing follows scene; select to edit",g);m.setAttribute("role","button"),m.tabIndex=0,m.setAttribute("aria-label",(t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9\\uFF1A":"Scene field: ")+p),c.push(ue("slot-"+l.segment+"-"+l.name,t==="zh"?"\\u573A\\u666F\\u5185\\u5BB9":"Scene content",[m],{cls:"caption-lane"}))}c.push(...s.audio.map(l=>vn(l,o,t,!0)))}else c.push(bn(s,t,a,e.generation),...s.items.map(i=>yn(i,o,a)),...s.audio.map(i=>vn(i,o,t)),...(s.words??[]).map(i=>Go(i,o,t)));for(let[i,d]of[[e.measure,"render"],[e.referenceMeasure,"reference"]])i&&!a&&c.push(Yo(i,d,o,r,t),Zo(i,d,o,r,t));return c},xn=(e,t,n)=>{let o=e.getBoundingClientRect();return Math.floor((t-o.left)/Math.max(1,o.width)*n)},rt=(e,t,n)=>{let o=u("div",{class:"lanes",id:"lanes"}),r=u("div",{class:"playhead",id:"playhead"}),s=u("div",{class:"playhead-layer"},[r]);e.append(o);let a=l=>l.state?W(l.state):0,c=l=>{Le(r,l.frame,l.frame+1,a(l))},i=l=>{o.querySelectorAll("[data-sel]").forEach(f=>{f.setAttribute("aria-pressed",String(l.pinned!==null&&ge(JSON.parse(f.dataset.sel??"null"),l.pinned))),f.classList.toggle("selected",l.pinned!==null&&ge(JSON.parse(f.dataset.sel??"null"),l.pinned))})},d=l=>{o.replaceChildren(...l.state?Qo(l.state,l.lang,l):[],s),c(l),i(l)};o.addEventListener("click",l=>{let f=l.target,g=f.closest("[data-sel]")?.dataset.sel;if(g){let p=JSON.parse(g);n.pause();let m=t.get();m.timeline&&["item","slot","audio"].includes(p.kind)&&!m.timeline.layers&&t.set({timeline:{...m.timeline,layers:!0}}),n.pin(p);let h=f.closest(".lane-track");if(m.state?.edit)n.seek(Ae(t.get().state,p,t.get().frame));else if(h&&l.detail!==0)n.seek(xn(h,l.clientX,a(m)));else{let b=p.kind==="segment"?m.state?.resolved?.segments.find(y=>y.id===p.id):p.kind==="item"?m.state?.resolved?.items.find(y=>y.id===p.id):void 0;b&&(m.frame<b.start||m.frame>=b.end)&&n.seek(b.start)}}else{let p=f.closest(".lane-track");p&&(n.pin(null),l.detail!==0&&n.seek(xn(p,l.clientX,a(t.get()))))}}),o.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target.closest("[data-sel]");f&&(l.preventDefault(),f.click())}),e.addEventListener("wheel",l=>{l.shiftKey&&!l.deltaX&&(e.scrollLeft+=l.deltaY,l.preventDefault())},{passive:!1}),d(t.get()),t.subscribe((l,f)=>{if(l.state!==f.state||l.lang!==f.lang||l.timeline?.layers!==f.timeline?.layers||l.slots!==f.slots?d(l):l.frame!==f.frame&&c(l),l.pinned!==f.pinned){i(l);let g=o.querySelector(".blk.selected");if(g){let p=g.getBoundingClientRect(),m=e.getBoundingClientRect(),h=o.querySelector(".lane-label")?.getBoundingClientRect().width??0;(p.left<m.left+h||p.right>m.right)&&(e.scrollLeft+=p.left-m.left-h-20);let b=(o.querySelector(".ruler")?.getBoundingClientRect().height??0)+(g.closest(".segments")?0:o.querySelector(".segments")?.getBoundingClientRect().height??0);(p.top<m.top+b||p.bottom>m.bottom)&&(e.scrollTop+=p.top-m.top-b-6)}}})};var wn=e=>e.reduce((t,n)=>typeof n=="number"?t+"["+n+"]":t?t+"."+n:n,""),$o=(e,t)=>Ut(t)?S(e,t):t,Mt=e=>typeof e=="number"?String(Number(e.toFixed(4))):typeof e=="string"?e:JSON.stringify(e)??"",kt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),er=(e,t)=>{let n=wn(t);return e.filter(o=>o.at===n||o.at.startsWith(n+".")||o.at.startsWith(n+"["))},tr=(e,t)=>{let n=u("input",{attrs:{type:"number",step:String(e.step??(e.range?.integer?1:"any")),...e.range?.min===void 0?{}:{min:String(e.range.min)},...e.range?.max===void 0?{}:{max:String(e.range.max)}}});return n.value=typeof e.value=="number"?Mt(e.value):"",typeof e.resolved=="number"&&e.value===void 0&&(n.placeholder=Mt(e.resolved)),n.addEventListener("change",()=>{let o=n.value.trim(),r=Number(o);if(o!==""&&!Number.isFinite(r))return void n.setAttribute("aria-invalid","true");t(o===""?void 0:r)}),n},kn=(e,t)=>{let n=typeof e.value=="string"?e.value:"";if(e.kind==="textarea"){let r=u("textarea",{attrs:{rows:String(Math.min(6,Math.max(2,n.split(\`
37955
+ \`).length)))}});return r.value=n,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r.addEventListener("keydown",s=>{s.key==="Enter"&&(s.ctrlKey||s.metaKey)&&r.blur()}),r}let o=u("input",{attrs:{type:"text",autocomplete:"off",spellcheck:"false"}});return o.value=n,typeof e.resolved=="string"&&e.value===void 0&&(o.placeholder=e.resolved),o.addEventListener("change",()=>t(o.value.trim()===""?void 0:o.value.trim())),o},nr=(e,t,n)=>{let o=[...e.empty===null?[]:[u("option",{text:e.empty??S(n,"fDefault"),attrs:{value:""}})],...e.options.map(a=>u("option",{text:e.labels?.[a]??a,attrs:{value:a}}))],r=u("select",{},o),s=e.value===void 0?"":String(e.value);return s!==""&&!e.options.includes(s)&&r.append(u("option",{text:s,attrs:{value:s}})),r.value=s,r.addEventListener("change",()=>t(r.value===""?void 0:r.value)),r},or=(e,t)=>{let n=kn(e,t),o=e.value??e.resolved,r=typeof o=="string"&&/^#[0-9a-f]{6}$/i.test(o)?o:"#000000",s=u("input",{class:"swatch-pick",attrs:{type:"color",tabindex:"-1"}});return s.value=r.toLowerCase(),s.addEventListener("change",()=>t(s.value)),u("span",{class:"colour"},[s,n])},rr=(e,t)=>{let n=e.commit??(d=>{kt(d,e.value)||t.commit(e.path,d)}),o=d=>{kt(d,e.value)||n(d)},r=e.kind==="number"?tr(e,o):e.kind==="select"?nr(e,o,t.lang):e.kind==="color"?or(e,o):kn(e,o),s=r.tagName==="SPAN"?r.querySelector("input[type=text]"):r;s.dataset.path=wn(e.path),e.disabled&&s.setAttribute("disabled","");let a=er(t.problems,e.path);a.length&&s.setAttribute("aria-invalid","true");let c=e.resolved!==void 0&&e.value!==void 0&&!kt(e.value,e.resolved),i=$o(t.lang,e.label);return u("label",{class:"fld"+(e.wide||e.kind==="textarea"?" wide":"")+(e.kind==="textarea"?" area":"")},[u("span",{class:"fl",text:i,title:i}),r,...c?[u("span",{class:"rv",text:"\\u2192 "+Mt(e.resolved),title:S(t.lang,"resolvedTitle")})]:[],...a.map(d=>u("span",{class:"fprob",text:d.message+(d.fix?" "+S(t.lang,"fix")+": "+d.fix:"")}))])},_=(e,t,n,o=[])=>u("fieldset",{class:"fs"},[u("legend",{text:e}),...t.map(r=>u("div",{class:"row"},r.filter(s=>s!==null).map(s=>s instanceof HTMLElement?s:rr(s,n)))),...o]);var Ln=["slide","whip"],Rn=["blur","zoom","shake","flash","whip","glitch","fade","spin"];var Pn=(e,t,n)=>u("div",{class:"hint",text:S(e.lang,"onFrames")+" "+t+".."+(n-1)}),Tt=(e,t,n,o,r=S(e.lang,"fWhen"))=>{let s=T(n)?n:{},a=e.state.resolved?.canvas.fps??30,c=e.state.resolved?.segments.find(g=>g.id===s.segment),i=g=>g==="from"?0:g==="to"&&c?c.end-c.start:void 0,d=(g,p)=>({kind:"number",label:S(e.lang,p)+(e.lang==="zh"?"\\uFF08\\u79D2\\uFF09":" (s)"),path:[...t,g],value:typeof(s[g]??i(g))=="number"?Number(s[g]??i(g))/a:void 0,step:.01,commit:m=>e.commit([...t,g],m===void 0?void 0:Math.round(Number(m)*a))}),l=o?[Pn(e,o.start,o.end)]:[];if(s.phrase!==void 0)return _(r,[[{kind:"text",label:"fPhrase",path:[...t,"phrase"],value:s.phrase,wide:!0}],[d("occurrence","fOccurrence"),d("lead","fLead"),d("hold","fHold")]],e,l);let f={kind:"select",label:"fSegment",path:[...t,"segment"],value:s.segment,options:te(e.state).map(g=>String(g.id)),labels:Object.fromEntries(te(e.state).map((g,p)=>[String(g.id),(e.lang==="zh"?"\\u753B\\u9762 ":"Scene ")+(p+1)])),empty:null};return _(r,[[f,d("from","fFrom"),d("to","fTo")]],e,l)},An=(e,t)=>{let n=Array.isArray(t.track.cues)?t.track.cues:[],o=String(t.track.id),r=n.flatMap((s,a)=>{if(t.kind==="cue"&&t.cue!==a)return[];let c=["tracks",t.index,"cues",a],i=e.state.resolved?.items.find(f=>f.id===o+"#"+a),d={kind:"textarea",label:S(e.lang,"fCue")+" "+a,path:[...c,"text"],value:T(s)?s.text:void 0},l=_("#"+a,[[d]],e,[Tt(e,[...c,"during"],T(s)?s.during:void 0,i,S(e.lang,"fWhen"))]);return l.classList.add("cue"),t.kind==="cue"&&t.cue===a&&l.classList.add("current"),l});return u("div",{class:"cues"},[u("h3",{text:S(e.lang,"fCues")+" ("+n.length+")"}),...r])},ar=(e,t)=>e==="wipe"?X(j(t.schema.transition,"direction")):Ln.includes(e)?X(j(t.schema.motion,"direction")):[],ir=(e,t,n,o)=>{let r=[...t,"in"],s=T(n)?n:void 0,a=String(s?.transition??""),c=e.schema.transition,i=o?.transition,d=(m,h,b,y)=>({kind:b,label:h,path:[...r,m],value:s?.[m],resolved:i?.[m==="transition"?"kind":m],range:xe(j(c,m)),options:y??X(j(c,m)),step:m==="strength"?.1:void 0}),l={kind:"select",label:"fKind",path:[...r,"transition"],value:s?.transition,options:X(j(c,"transition")),empty:S(e.lang,"fHardCut"),commit:m=>m===void 0?e.commit(r,void 0):e.commit([...r,"transition"],m)},f=ar(a,e),g=Rn.includes(a),p=[[l,s&&a!=="cut"?d("frames","fFrames","number"):null],[f.length?d("direction","fDirection","select",f):null,a==="slide"?d("mode","fMode","select"):null,a==="fade"?d("via","fVia","select"):null],[g?d("side","fSide","select"):null,s&&a!=="cut"?d("ease","fEase","select"):null,s&&a!=="cut"?d("strength","fStrength","number"):null]];return _(S(e.lang,"fTransition"),p.filter(m=>m.some(h=>h!==null)),e)},dr=(e,t,n)=>{let o=e.schema.base,r=ve(e.state,["image","video"]),s="material"in n?"material":"color"in n?"color":"scene",a={kind:"select",label:"fBase",path:t,value:s,options:s==="scene"?["scene","color","material"]:["color","material"],labels:{scene:S(e.lang,"fBaseScene"),color:S(e.lang,"fBaseColor"),material:S(e.lang,"fBaseMaterial")},empty:null,commit:d=>e.set(t,d==="scene"?n:d==="color"?{color:"#000000"}:{material:r[0]??""})};if(s==="scene"){let d=T(n.slots)?n.slots:{},l=Object.entries(d).filter(f=>typeof f[1]=="string").map(([f,g])=>[{kind:"textarea",label:f,path:[...t,"slots",f],value:g,wide:!0}]);return _(S(e.lang,"fBaseScene"),[[a],...l],e)}if(s!=="material"){let d=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,empty:null}:u("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fBase"),[[a,d]],e)}let c=ve(e.state,["video"]).includes(String(n.material)),i=(d,l,f)=>({kind:"number",label:l,path:[...t,d],value:n[d],range:xe(j(o,d)),...f?{step:f}:{}});return _(S(e.lang,"fBase"),[[a,{kind:"select",label:"fMaterial",path:[...t,"material"],value:n.material,options:r,empty:null,wide:!0}],[{kind:"select",label:"fFit",path:[...t,"fit"],value:n.fit,options:X(j(o,"fit"))},...c?[i("in","fIn"),i("speed","fSpeed",.05),i("audio","fSourceAudio")]:[]]],e,n.camera!==void 0?[u("div",{class:"hint",text:S(e.lang,"fCamera")})]:[])},Cn=(e,t)=>{let n=["segments",t.index],o=e.state.resolved?.segments[t.index],r=e.state.resolved?.canvas.fps??30,s={kind:"number",label:e.lang==="zh"?"\\u65F6\\u957F\\uFF08\\u79D2\\uFF09":"Duration (s)",path:[...n,"frames"],value:Number(oe(e.state.source,[...n,"frames"]))/r,step:.01,range:{min:1/r,integer:!1},commit:i=>e.commit([...n,"frames"],Math.max(1,Math.round(Number(i)*r)))},a=_(e.lang==="zh"?"\\u955C\\u5934\\u65F6\\u957F":"Shot duration",[[s]],e,o?[Pn(e,o.start,o.end)]:[]),c=t.segment;return[a,...t.index>0?[ir(e,n,c.in,o)]:[],...T(c.base)?[dr(e,[...n,"base"],c.base)]:[]]};var On=e=>{if(T(e))return e;if(typeof e!="string"||!St(e))return{};let{font:t,...n}=vt[e];return n},st="custom",Hn=(e,t,n,o)=>{let r=[...t,"style"],s=j(e.schema.text,"style"),a=X(s),c=T(n)?n:void 0,i=e.state.resolved?.canvas.height??1,d={kind:"number",label:e.lang==="zh"?"\\u5B57\\u53F7\\uFF08px\\uFF09":"Font size (px)",path:[...r,"size"],value:Math.round(Number(c?.size??o?.size??.05)*i),step:1,range:{min:1,max:i,integer:!0},commit:m=>l("size")(m===void 0?void 0:Number(m)/i)},l=m=>h=>{let b=Object.fromEntries(Object.entries({...On(n),[m]:h}).filter(([,y])=>y!==void 0));e.set(r,b)},f=(m,h,b={})=>({kind:h,label:"f"+m[0]?.toUpperCase()+m.slice(1),path:[...r,m],value:c?.[m],resolved:o?.[m],commit:l(m),range:xe(j(s,m)),options:X(j(s,m)),...b}),g={kind:"select",label:"fNamed",path:r,value:typeof n=="string"?n:c?st:void 0,options:[...a,st],labels:{[st]:S(e.lang,"fCustom"),...e.lang==="zh"?{headline:"\\u6807\\u9898",subtitle:"\\u526F\\u6807\\u9898",label:"\\u6807\\u7B7E",caption:"\\u5B57\\u5E55"}:{}},commit:m=>e.set(r,m===st?On(n):m)},p=f("font","select",{value:c?.font??o?.font,options:[...new Set([String(c?.font??o?.font??"sans-serif"),...ve(e.state,["font"]),"sans-serif","serif","monospace"])],label:e.lang==="zh"?"\\u5B57\\u4F53":"Font",wide:!0});return _(S(e.lang,"fStyle"),[[p],[g,d],[f("color","color",{label:"fColour"}),f("weight","number",{step:100}),f("align","select",{labels:e.lang==="zh"?{left:"\\u5DE6\\u5BF9\\u9F50",center:"\\u5C45\\u4E2D",right:"\\u53F3\\u5BF9\\u9F50"}:{}})]],e)},lr=new Set(["slide","wipe"]),at=(e,t,n,o,r)=>{let s=[...t,n],a=e.schema.motion,c=T(o)?o:void 0,i=(f,g,p)=>({kind:g,label:p,path:[...s,f],value:c?.[f],resolved:r?.[f],disabled:!c,range:xe(j(a,f)),options:X(j(a,f))}),d={kind:"select",label:"fPreset",path:[...s,"preset"],value:c?.preset,options:X(j(a,"preset")),empty:S(e.lang,"fNone"),commit:f=>f===void 0?e.commit(s,void 0):e.commit([...s,"preset"],f)},l=lr.has(String(c?.preset??""));return _(S(e.lang,n==="enter"?"fEnter":"fExit"),[[d,i("frames","number","fFrames")],[l?i("direction","select","fDirection"):null,i("ease","select","fEase")]],e)},ie=(e,t,n,o,r={})=>({kind:"number",label:n,path:t,value:oe(e.state.source,t),range:xe(o),...r}),Ie=(e,t,n,o,r={})=>({kind:"select",label:n,path:t,value:oe(e.state.source,t),options:o,...r}),Nn=(e,t,n)=>{let o=e.state.resolved?.canvas,r=n&&o?[n.box[0]*o.width,n.box[1]*o.height,n.box[2]*o.width,n.box[3]*o.height].map(a=>Math.round(a)).join(", ")+" px":"",s=["fX","fY","fW","fH"].map((a,c)=>{let i=[...t,"box",c],d=c%2===0?o?.width??1:o?.height??1;return ie(e,i,a,void 0,{step:1,value:Math.round(Number(oe(e.state.source,i)??0)*d),commit:l=>e.commit(i,Number(l)/d)})});return _(e.lang==="zh"?"\\u4F4D\\u7F6E\\u4E0E\\u5C3A\\u5BF8\\uFF08px\\uFF09":"Position and size (px)",[s],e,r?[u("div",{class:"hint",text:r})]:[])},cr=(e,t,n)=>_(S(e.lang,"fLook"),[[ie(e,[...t,"rotate"],"fRotate",j(n,"rotate")),ie(e,[...t,"opacity"],"fOpacity",j(n,"opacity"),{step:.05}),ie(e,[...t,"z"],"fZ",j(n,"z"))]],e),ur=(e,t,n,o)=>{let r=String(n.type),s=e.schema[r==="image"?"image":r==="video"?"video":"shape"],a=ie(e,[...t,"radius"],"fRadius",j(s,"radius"),{step:.01});if(r==="shape"){let f=typeof n.color=="string"?{kind:"color",label:"fColour",path:[...t,"color"],value:n.color,resolved:o?.color}:u("div",{class:"hint",text:S(e.lang,"fGradient")});return _(S(e.lang,"fShape"),[[Ie(e,[...t,"shape"],"fShape",X(j(s,"shape")),{empty:null}),f,a]],e)}if(r!=="image"&&r!=="video")return null;let c=Ie(e,[...t,"material"],"fMaterial",ve(e.state,[r]),{empty:null,wide:!0}),i=Ie(e,[...t,"fit"],"fFit",X(j(s,"fit")),{resolved:o?.fit}),d=Ie(e,[...t,"mask"],"fMask",X(j(s,"mask")),{empty:S(e.lang,"fNone")}),l=r==="video"?[ie(e,[...t,"in"],"fIn",j(s,"in")),ie(e,[...t,"speed"],"fSpeed",j(s,"speed"),{step:.05}),ie(e,[...t,"audio"],"fSourceAudio",j(s,"audio"))]:[];return _(S(e.lang,r==="video"?"fFootage":"fPicture"),[[c,i],[a,d,...l]],e)},mr=(e,t)=>{let n=_(S(e.lang,"fText"),[[{kind:"textarea",label:e.lang==="zh"?"\\u5185\\u5BB9":"Content",path:[...t,"text"],value:oe(e.state.source,[...t,"text"])}]],e);return n.querySelector("legend")?.remove(),n},pr=(e,t,n)=>{let o=T(n.during)?n.during:void 0,r={kind:"select",label:"fStart",path:[...t,"during","segment"],value:o?.segment,options:te(e.state).map(s=>String(s.id)),empty:S(e.lang,"fWhole"),commit:s=>s===void 0?e.commit([...t,"during"],void 0):e.set([...t,"during"],{...o??{},segment:s})};return _(S(e.lang,"fAudio"),[[Ie(e,[...t,"material"],"fMaterial",ve(e.state,["audio","voice","speech"]),{empty:null,wide:!0}),ie(e,[...t,"gain"],"fGain",j(e.schema.audio,"gain"))],[r,ie(e,[...t,"during","from"],"fFrom",void 0,{disabled:!o})]],e)},In=(e,t)=>e.resolved?.items.find(n=>n.id===t),fr=(e,t)=>{let n=["tracks",t.index],o=t.track,r=String(o.type);if(r==="audio")return[pr(e,n,o)];let s=String(o.id);if(r==="caption"){let i=In(e.state,s+"#"+(t.kind==="cue"?t.cue:0));return[An(e,t),Hn(e,n,o.style,i?.style),Nn(e,n,i),at(e,n,"enter",o.enter,i?.enter),at(e,n,"exit",o.exit,i?.exit)]}let a=In(e.state,s),c=e.schema[r==="text"?"text":r==="image"?"image":r==="video"?"video":"shape"];return[...r==="text"?[mr(e,n)]:[],...r==="text"?[Hn(e,n,o.style,a?.style)]:[ur(e,n,o,a)].filter(i=>i!==null),Tt(e,[...n,"during"],o.during,a),Nn(e,n,a),at(e,n,"enter",o.enter,a?.enter),at(e,n,"exit",o.exit,a?.exit),cr(e,n,c)]},Fn=(e,t)=>{let n=t.kind==="segment"?S(e.lang,"fSegment")+" "+String(t.segment.id):String(t.track.type)+" "+String(t.track.id)+(t.kind==="cue"?" #"+t.cue:""),o=t.kind==="segment"?Cn(e,t):fr(e,t),r=t.kind==="segment"?e.lang==="zh"?"\\u753B\\u9762 "+(t.index+1):"Scene "+(t.index+1):t.kind==="cue"?e.lang==="zh"?"\\u5B57\\u5E55 "+(t.cue+1):"Subtitle "+(t.cue+1):e.lang==="zh"?{text:"\\u6587\\u5B57",image:"\\u56FE\\u7247",video:"\\u89C6\\u9891",audio:"\\u97F3\\u9891",shape:"\\u5F62\\u72B6"}[String(t.track.type)]??"\\u5143\\u7D20":String(t.track.type),s=t.kind==="cue"?2:t.kind==="segment"?1:t.track.type==="text"?2:1;return u("div",{class:"form",id:"edit-form"},[u("div",{class:"sel-title",text:r,title:n}),...o.slice(0,s),...o.length>s?[u("details",{},[u("summary",{text:e.lang==="zh"?"\\u4F4D\\u7F6E\\u3001\\u65F6\\u95F4\\u4E0E\\u52A8\\u6548":"Position, timing and motion"}),...o.slice(s)])]:[]])};var Fe=(e,t=[])=>u("h2",{},[u("span",{text:e}),...t]),Dn=e=>u("pre",{class:"json",text:JSON.stringify(e,null,2)??"undefined"}),gr=(e,t,n)=>{if(e.pinned){let a=Bt(t,e.pinned);return[u("div",{class:"sel-title",text:Vt(e.pinned)}),a===void 0?u("p",{class:"muted",text:S(e.lang,"nothing")}):Dn(a)]}let o=t.resolved?Z(t.resolved,e.frame):void 0,s=(t.resolved?fe(t.resolved,e.frame):[]).map(a=>u("button",{class:"chip",text:a.id,attrs:{type:"button"},on:{click:()=>n.pin({kind:"item",id:a.id})}}));return[...o?[u("div",{class:"sel-title",text:"segment "+o.id}),Dn(o)]:[u("p",{class:"muted",text:S(e.lang,"nothing")})],u("div",{class:"chips"},[u("span",{class:"muted",text:S(e.lang,"onScreen")+": "}),...s.length?s:[S(e.lang,"none")]])]},hr=(e,t,n,o)=>{let r=e.edit.schema;if(!t.edit)return;if(!r)return[u("p",{class:"muted",text:e.lang==="zh"?"\\u6B63\\u5728\\u8F7D\\u5165\\u7F16\\u8F91\\u5DE5\\u5177\\u2026":"Loading editing tools\\u2026"})];if(e.pinned?.kind==="slot")return[dn(o,n)];let s=q(t,e.pinned);if(s){let a={lang:e.lang,problems:e.edit.problems,state:t,schema:r,commit:(c,i)=>{let d=Wt(t.source,c,i);d&&n.send(d)},set:(c,i)=>{n.send({op:"set",path:c,value:i})}};return[Fn(a,s)]}if(!e.pinned)return[]},br=(e,t)=>u("li",{class:"problem "+e.level},[u("div",{},[u("b",{class:e.level,text:S(t,e.level)})," ",u("code",{text:e.at})]),u("div",{text:e.message}),...e.allowed?.length?[u("div",{class:"muted",text:S(t,"allowed")+": "+e.allowed.join(", ")})]:[],...e.fix?[u("div",{text:S(t,"fix")+": "+e.fix})]:[]]),yr=e=>Object.entries(e).map(([t,n])=>t+"="+(typeof n=="number"?Number(n.toFixed(3)):n)).join(", "),vr=(e,t)=>{let n=(r,s="")=>u("tr",{class:s},r.map(a=>u("td",{},[a]))),o=Object.entries(e.dimensions).map(([r,s])=>{let a=yr(s.detail);return n([Jt(t,r),s.n?s.score.toFixed(2):"-",String(s.n),u("span",{class:"detail",text:a,title:a})],s.n?"":"muted")});return u("table",{class:"score"},[u("thead",{},[u("tr",{},[S(t,"dimension"),S(t,"value"),S(t,"compared"),S(t,"detail")].map(r=>u("th",{text:r})))]),u("tbody",{},[...o,n([S(t,"composite"),e.composite.toFixed(2),"",""],"total")])])},Sr=(e,t)=>[u("div",{class:"kv"},[u("span",{class:"muted",text:S(t,"renderMeasure")+": "}),u("code",{text:e.measure?.file??S(t,"none"),title:e.measure?.file??""})]),u("div",{class:"kv"},[u("span",{class:"muted",text:S(t,"referenceMeasure")+": "}),u("code",{text:e.referenceMeasure?.file??S(t,"none"),title:e.referenceMeasure?.file??""})]),...e.messages.map(n=>u("p",{class:"message",text:n}))],it=(e,t,n,o)=>{let r=u("section",{id:"selection"}),s=u("section",{id:"problems"}),a=u("section",{id:"score"}),c=u("section",{id:"measures"}),i=u("section",{id:"notes"});e.append(r,s,a,c,i);let d="",l="",f=p=>{let m=p.state,h=m?.resolved&&!p.pinned?[Z(m.resolved,p.frame)?.id,fe(m.resolved,p.frame).map(H=>H.id)]:null,b=m?.edit?[p.edit.problems,p.edit.schema!==null]:null,y=JSON.stringify([p.lang,m?.generation,p.pinned,h,b]);if(y===d)return;let v=JSON.stringify(p.pinned)!==l;l=JSON.stringify(p.pinned),d=y;let E=r.contains(document.activeElement)?document.activeElement.dataset.path:void 0,M=p.pinned?[u("button",{class:"link",text:S(p.lang,"follow"),attrs:{type:"button"},on:{click:()=>n.pin(null)}})]:[],k=m?(o&&hr(p,m,o,t))??gr(p,m,n):[];r.replaceChildren(Fe(S(p.lang,"selection"),[u("span",{class:"muted",text:" ("+S(p.lang,p.pinned?"pinned":"underPlayhead")+")"}),...M]),...k),E&&r.querySelector('[data-path="'+CSS.escape(E)+'"]')?.focus(),v&&r.querySelector(".cue.current")?.scrollIntoView({block:"nearest"})},g=p=>{let m=p.state;if(!m)return;let h=p.lang;s.replaceChildren(Fe(S(h,"problems")+" ("+m.problems.length+")"),m.problems.length?u("ul",{},m.problems.map(b=>br(b,h))):u("p",{class:"muted",text:S(h,"noProblems")})),a.replaceChildren(Fe(S(h,"score")),m.score?vr(m.score,h):u("p",{class:"muted",text:S(h,"noScore")})),c.replaceChildren(Fe(S(h,"measurements")),...Sr(m,h)),i.hidden=!m.notes,i.replaceChildren(Fe(S(h,"notes")+" ("+(m.notes?.length??0)+")"),u("ul",{},(m.notes??[]).map(b=>u("li",{class:"note-item"},[u("code",{text:b.at})," ",u("b",{text:b.kind}),u("div",{text:b.message})]))))};g(t.get()),f(t.get()),t.subscribe((p,m)=>{(p.state!==m.state||p.lang!==m.lang)&&g(p),(p.state!==m.state||p.lang!==m.lang||p.pinned!==m.pinned||p.frame!==m.frame||p.edit.problems!==m.edit.problems||p.edit.schema!==m.edit.schema)&&f(p)})};var Lt=(e,t,n,o)=>{let r=Math.max(0,t.frames-1),s=o-e.start;return s<=0?Math.min(e.in,r):Math.min(r,e.in+Math.round(s*t.fps*e.speed/n))};var jn=(e,t,n=()=>{})=>{let o=[],r=(i,d)=>{let l=e.querySelector(i+" > img");l&&o.push({img:l,play:d,active:!1})};t.segments.forEach(i=>{i.base.kind==="video"&&r('[data-segment="'+CSS.escape(i.id)+'"]',i.base.play)}),t.items.forEach(i=>{i.play&&r('[data-item="'+CSS.escape(i.id)+'"]',i.play)});let s=(i,d)=>{if(i.video)return;let l=t.footage?.[i.play.material],f=i.img.parentElement;if(!l||!f)return;let g=e.createElement("video");g.muted=!0,g.playsInline=!0,g.preload="auto",g.hidden=!0,g.style.display="none",g.dataset.previewVideo=i.play.material;let p=Lt(i.play,l,t.canvas.fps,Math.max(d,i.play.start))/l.fps;i.time=p,g.addEventListener("loadedmetadata",()=>{g.paused&&g.isConnected&&(g.currentTime=i.time??p)},{once:!0}),g.src=l.src.startsWith("project/")?"/"+l.src:"/project/"+l.src.split("/").map(encodeURIComponent).join("/");let m=()=>{!i.active||!g.isConnected||f.style.display==="none"||(g.style.cssText=i.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",g.hidden=!1,g.style.visibility="",i.img.style.visibility="hidden")};g.addEventListener("loadeddata",m),g.addEventListener("error",()=>{l.dir===void 0&&g.isConnected&&n(l.src.replace(/^project\\//,"").split("/").map(decodeURIComponent).join("/"))}),g.addEventListener("seeked",()=>{if(!i.playing&&i.active&&i.time!==void 0&&Math.abs(g.currentTime-i.time)>.5/l.fps){g.currentTime=i.time;return}m()}),f.append(g),i.video=g},a=i=>{i.video?.pause(),i.video?.removeAttribute("src"),i.video?.load(),i.video?.remove(),i.video=void 0,i.active=!1,i.img.style.visibility=""};return{sync:(i,d,l)=>{let f=o.filter(g=>g.play.start>i).sort((g,p)=>g.play.start-p.play.start).slice(0,2);for(let g of o)f.includes(g)||g.img.parentElement?.style.display!=="none"?s(g,i):g.video&&a(g);for(let g of o){let p=t.footage?.[g.play.material],m=g.img.parentElement;if(!((d||p?.dir===void 0)&&!!p&&!!m&&m.style.display!=="none")){g.video?.pause(),g.video&&(g.video.hidden=!0,g.video.style.display="none"),g.img.style.visibility="",g.active=!1;continue}if(!p||!m)continue;let b=g.video;b.hidden=!1,b.style.cssText=g.img.style.cssText+";position:absolute;inset:0;pointer-events:none;",g.img.style.visibility=b.readyState>=2?"hidden":"",b.style.visibility=b.readyState>=2?"":"hidden";let y=Lt(g.play,p,t.canvas.fps,i)/p.fps;g.time=y,g.playing=d;let v=l*g.play.speed;b.playbackRate=Math.max(.0625,Math.min(16,v));let E=d&&g.active?.25:.5/p.fps;!b.seeking&&Math.abs(b.currentTime-y)>E&&(b.currentTime=y),i<g.play.start||y>=(p.frames-1)/p.fps||!d?b.pause():b.paused&&b.play().catch(()=>{}),g.active=!0}},needsPictures:()=>o.some(i=>!!(i.video?.error&&t.footage?.[i.play.material]?.dir&&i.img.parentElement?.style.display!=="none")),dispose:()=>{o.forEach(a)}}};var zn=(e,t)=>{let n=u("div",{class:"caption"}),o=u("div",{class:"note"}),r=u("div",{class:"overlay"}),s=u("div",{class:"frame-box"},[t,r]);return{root:u("div",{class:"viewer",id:e},[n,s,o]),caption:n,note:o,box:s,overlay:r}},Bn=(e,t,n,o)=>Math.max(.01,Math.min(n/e,o/t)),Rt=(e,t)=>{let n=e.reference.root.isConnected,o=getComputedStyle(e.root),r=e.root.classList.contains("comparing"),s=(e.root.clientWidth-parseFloat(o.paddingLeft)-parseFloat(o.paddingRight)-(n?parseFloat(o.gap)||16:0))/(n?2:1)-(r?18:0),a=e.root.clientHeight-parseFloat(o.paddingTop)-parseFloat(o.paddingBottom)-e.render.caption.offsetHeight-e.render.note.offsetHeight-(r?32:8),c=t.state?.resolved?.canvas;if(e.render.box.classList.toggle("problems",!c),c){let g=Bn(c.width,c.height,s,a);e.render.box.style.cssText="width:"+c.width*g+"px;height:"+c.height*g+"px;",e.scaler.style.cssText="width:"+c.width+"px;height:"+c.height+"px;transform:scale("+g+");"}else e.render.box.style.cssText="width:"+Math.max(0,s)+"px;height:"+Math.max(0,a)+"px;",e.scaler.style.cssText="width:100%;height:100%;";if(!n)return;let i=t.state?.referenceMeasure?.measure.source,d=e.video.videoWidth||i?.width||c?.width||16,l=e.video.videoHeight||i?.height||c?.height||9,f=Bn(d,l,s,a);e.reference.box.style.cssText="width:"+d*f+"px;height:"+l*f+"px;"},Vn=(e,t,n,o)=>{if(t)for(let r of Dt(t,n,o))e.append(le(u("div",{class:"ebox"},[u("span",{text:ze(r)})]),r.box))},xr=(e,t,n)=>{let o=t.state;if(e.render.overlay.replaceChildren(),e.reference.overlay.replaceChildren(),!o?.resolved)return;let r=se(o);if(t.overlays.safe)for(let s of[e.render.overlay,e.reference.overlay])s.append(le(u("div",{class:"safe"}),zt(o.resolved.canvas)));if(t.overlays.boxes)for(let s of fe(o.resolved,t.frame))e.render.overlay.append(le(u("div",{class:"ibox",title:s.id,on:{click:()=>n.pin({kind:"item",id:s.id})}},[u("span",{text:s.id})]),s.box));t.overlays.events&&(Vn(e.render.overlay,o.measure?.measure,t.frame,r),Vn(e.reference.overlay,o.referenceMeasure?.measure,t.frame,r))},Er=(e,t)=>{let n=t.state?.resolved?.canvas,o=!!(t.state&&!t.state.resolved);e.render.caption.textContent=S(t.lang,t.state?.edit?"currentVideo":"render")+(n?" "+n.width+"x"+n.height+", "+n.fps+" fps":""),e.render.note.textContent=o?S(t.lang,"errorsOnStage"):t.pageError?S(t.lang,"imageFailed")+": "+t.pageError:"",e.render.note.classList.toggle("error",o||!!t.pageError);let r=t.edit.playRender&&t.edit.render?.state==="done"?t.edit.render:void 0;e.reference.caption.textContent=r?S(t.lang,"renderFile")+" "+(r.file.split(/[\\\\/]/).pop()??""):S(t.lang,"reference")+(t.state?.reference?" "+t.state.reference.name:""),e.reference.note.textContent=S(t.lang,"seekNote")},_n=(e,t,n,o)=>{if(!t.state||!e.getAttribute("src"))return;let r=(t.frame+.25)/se(t.state);if(!t.playing){e.paused||e.pause(),(o||n.playing||Math.abs(e.currentTime-r)>.001)&&(e.currentTime=r);return}e.playbackRate=t.speed,o||!n.playing||n.speed!==t.speed?(e.currentTime=r,e.play().catch(()=>{})):!e.seeking&&Math.abs(e.currentTime-r)>.2&&(e.currentTime=r)},wr=(e,t)=>{let n,o=-1,r=0,s=0,a,c,i=()=>{let l=n;if(!l)return;let f=t.get(),g=f.frame,p=++s;(l.preparePreview?.(g)??Promise.resolve()).then(async()=>{p===s&&(f.playing&&l.previewFrame&&a&&!a.needsPictures()?l.previewFrame(g):l.applyFrame(g),a?.sync(g,f.playing,f.speed),await l.settle())}).then(()=>null,h=>h instanceof Error?h.message:String(h)).then(h=>{if(p!==s)return;h!==null&&h!==t.get().pageError&&t.set({pageError:h}),document.body.dataset.applied=String(g),e.dispatchEvent(new Event("frameapplied"));let b=t.get().state?.resolved,y=b?Z(b,g)?.id:void 0;h===null&&y!==c&&(c=y,document.dispatchEvent(new Event("studio:scene-ready")))})};return e.addEventListener("load",()=>{let l=++r,f=e.contentWindow?.__popostVideo;if(n=void 0,c=void 0,!f){document.body.dataset.ready="error";return}(f.preparePreview?.(t.get().frame)??f.prepare()).then(()=>null,p=>p instanceof Error?p.message:String(p)).then(p=>{if(l!==r)return;n=f;let m=t.get().state?.resolved;p!==t.get().pageError&&t.set({pageError:p}),m&&e.contentDocument&&(a=jn(e.contentDocument,m,h=>{l===r&&t.set({pageError:h})})),i(),document.body.dataset.ready="1",document.dispatchEvent(new Event("studio:page-ready"))})}),{load:l=>{o=l,s++,a?.dispose(),a=void 0,n=void 0,document.body.dataset.ready="",e.src="/page?g="+l},apply:i,loaded:()=>o}},kr=e=>{let t=e.edit.render;return e.edit.playRender&&t?.state==="done"?t.url:e.compare!==!1&&e.state?.reference?e.state.reference.url??"/reference":""},dt=(e,t,n)=>{let o=u("iframe",{id:"page",attrs:{title:"page",tabindex:"-1"}}),r=u("div",{class:"scaler"},[o]),s=u("video",{id:"reference-video",attrs:{preload:"auto",playsinline:"",tabindex:"-1"}});s.muted=!0;let a={root:e,render:zn("render-view",r),reference:zn("reference-view",s),iframe:o,scaler:r,video:s};e.append(a.render.root);let c=wr(o,t);new ResizeObserver(()=>Rt(a,t.get())).observe(e),s.addEventListener("loadedmetadata",()=>{Rt(a,t.get()),_n(s,t.get(),t.get(),!0)});let i="";return t.subscribe((d,l)=>{let f=kr(d);if(f!==i){i=f,f&&!a.reference.root.isConnected&&e.append(a.reference.root),f||a.reference.root.remove(),f?s.src=f:s.removeAttribute("src");let g=!!(f&&!d.edit.playRender);e.classList.toggle("comparing",g),a.reference.root.style.order=g?"-1":""}d.state&&d.state.generation!==c.loaded()&&c.load(d.state.generation),(d.frame!==l.frame||d.playing!==l.playing||d.speed!==l.speed)&&c.apply(),(d.frame!==l.frame||d.overlays!==l.overlays||d.state!==l.state)&&xr(a,d,n),(d.frame!==l.frame||d.playing!==l.playing||d.speed!==l.speed)&&_n(s,d,l,!1),(d.compare!==l.compare||d.lang!==l.lang||d.state!==l.state||d.pageError!==l.pageError||d.edit!==l.edit)&&(Er(a,d),Rt(a,d))}),{frameBox:a.render.box,iframe:o}};var Ee=(e,t,n,o,r)=>{let s=u("button",{id:t,class:"tbtn",attrs:{type:"button"}},[o]);return s.addEventListener("click",()=>{r(),s.blur()}),e.buttons.push({el:s,title:n}),s},Mr=e=>{let t=u("input",{id:"jump",attrs:{type:"text",inputmode:"numeric",autocomplete:"off"}});return t.addEventListener("keydown",n=>{if(n.key!=="Enter")return;let o=Number(t.value.trim()),r=t.value.trim()!==""&&Number.isInteger(o);t.setAttribute("aria-invalid",String(!r)),r&&(e.pause(),e.seek(o),t.value="",t.blur())}),t},Tr=e=>{let t=u("select",{id:"speed"},_t.map(n=>u("option",{text:n+"x",attrs:{value:String(n)}})));return t.value="1",t.addEventListener("change",()=>{e.setSpeed(Number(t.value)),t.blur()}),t},Lr=(e,t)=>{let n=[],o=c=>()=>{t.pause(),c()},r=u("span",{class:"icon"},[Y("play")]),s=u("input",{id:"slider",attrs:{type:"range",min:"0",max:"0",step:"1",value:"0","aria-label":"frame"}});s.addEventListener("input",()=>t.seek(Number(s.value)));let a={buttons:n,playIcon:r,slider:s,play:Ee({buttons:n},"play","play",r,()=>t.togglePlay()),frameLabel:u("span",{class:"muted"}),frameNo:u("span",{id:"frame-no",class:"num"}),frameOf:u("span",{class:"num muted"}),time:u("span",{id:"time",class:"num muted"}),speedLabel:u("label",{class:"muted",attrs:{for:"speed"}}),speed:Tr(t),jump:Mr(t)};return e.append(Ee(a,"first","first",Y("first"),o(()=>t.seek(0))),Ee(a,"back10","back10","\\u221210",o(()=>t.step(-10))),Ee(a,"back1","back1","\\u22121",o(()=>t.step(-1))),a.play,Ee(a,"fwd1","fwd1","+1",o(()=>t.step(1))),Ee(a,"fwd10","fwd10","+10",o(()=>t.step(10))),Ee(a,"last","last",Y("last"),o(()=>t.seek(Number.MAX_SAFE_INTEGER))),u("div",{class:"slider-wrap"},[s]),u("span",{class:"readout"},[u("span",{},[a.frameLabel,a.frameNo,a.frameOf]),a.time]),u("span",{class:"speed"},[a.speedLabel,a.speed]),a.jump),a},Kn=(e,t,n)=>{let o=t.state?W(t.state):0,r=t.state?se(t.state):30;e.slider.max=String(Math.max(0,o-1)),e.slider.value=String(t.frame),e.frameNo.textContent=String(t.frame),e.frameOf.textContent=" / "+Math.max(0,o-1),e.time.textContent=pt(t.frame,r)+" / "+pt(o,r),!(n&&t.playing===n.playing&&t.lang===n.lang)&&(e.playIcon.replaceChildren(Y(t.playing?"pause":"play")),e.buttons.forEach(s=>{s.el.title=S(t.lang,s.el===e.play?t.playing?"pause":"play":s.title)}),e.frameLabel.textContent=S(t.lang,"frame")+" ",e.speedLabel.textContent=S(t.lang,"speed")+" ",e.jump.placeholder=S(t.lang,"jump"),e.jump.title=S(t.lang,"jumpHint"))},Rr=(e,t)=>{let n=e.target;if(e.defaultPrevented||n?.tagName==="SELECT"||n?.tagName==="TEXTAREA"||n instanceof HTMLInputElement&&(n.type==="text"||n.type==="number")||e.altKey||e.ctrlKey||e.metaKey)return;let r={" ":()=>t.togglePlay(),ArrowLeft:()=>{t.pause(),t.step(e.shiftKey?-10:-1)},ArrowRight:()=>{t.pause(),t.step(e.shiftKey?10:1)},Home:()=>{t.pause(),t.seek(0)},End:()=>{t.pause(),t.seek(Number.MAX_SAFE_INTEGER)}}[e.key];r&&(e.preventDefault(),r())},lt=(e,t,n)=>{let o=Lr(e,n);Kn(o,t.get(),void 0),t.subscribe((r,s)=>{(r.frame!==s.frame||r.state!==s.state||r.playing!==s.playing||r.lang!==s.lang)&&Kn(o,r,s)}),document.addEventListener("keydown",r=>Rr(r,n))};var Pt=e=>{let t=e.store.get(),n=t.state?.resolved,o=t.pinned,r=o?.kind==="item"?n?.items.find(s=>s.id===o.id):void 0;return n?n.segments.find(s=>(o?.kind==="segment"||o?.kind==="slot")&&s.id===o.id)??(r?Z(n,r.start):void 0)??Z(n,t.frame):void 0},Jn=(e,t)=>{let n=e.store.get().state?.resolved?.segments.find(o=>o.id===t);n&&(e.actions.pause(),e.actions.seek(Math.min(n.end-1,n.start+Math.floor((n.end-n.start)*.3))),e.edit.select({kind:"segment",id:t}))},At=e=>{let{store:t,edit:n}=e,o=t.get().state,r=o?.resolved,s=u("div",{class:"studio-shot-list"});if(r)for(let c of r.segments){let i=c.base,d=i.kind==="scene"?x(t,"scene"):i.kind==="video"?x(t,"video"):i.kind==="image"?x(t,"image"):x(t,"color"),l=C("",()=>Jn(e,c.id),"studio-shot "+(ge(t.get().pinned,{kind:"segment",id:c.id})?"selected":""));l.append(sn(c.start+Math.floor((c.end-c.start)/2),o?.generation??0),u("span",{class:"studio-shot-copy"},[u("strong",{text:String(c.index+1).padStart(2,"0")+" "+c.id}),u("small",{text:d+" \\xB7 "+((c.end-c.start)/r.canvas.fps).toFixed(2)+"s"})])),l.dataset.selection=JSON.stringify({kind:"segment",id:c.id}),l.draggable=!!o?.edit,l.addEventListener("dragstart",f=>f.dataTransfer?.setData("application/x-popost-segment",String(c.index))),l.addEventListener("dragover",f=>f.preventDefault()),l.addEventListener("drop",f=>{f.preventDefault();let g=Number(f.dataTransfer?.getData("application/x-popost-segment"));Number.isInteger(g)&&g!==c.index&&n.send({op:"move",path:["segments",g],to:c.index})}),s.append(l)}let a=Oe("",x(t,"search"));return a.placeholder=x(t,"search"),a.addEventListener("input",()=>s.querySelectorAll(".studio-shot").forEach(c=>{c.hidden=!c.textContent?.toLowerCase().includes(a.value.toLowerCase())})),u("div",{class:"studio-side-body"},[U(x(t,"shots"),String(r?.segments.length??0)),a,s,A(x(t,"keepRhythm"))])},Un=async(e,t,n)=>{let{store:o,edit:r}=e,s=o.get().state,a=Pt(e);if(!s||!a)return;let c=t.kind,i=String(t.id);if(!n&&["image","video"].includes(String(c))){await r.send({op:"set",path:["segments",a.index,"base"],value:{material:i,fit:"cover"}});return}let d=$(G(s.source).tracks),l=["audio","voice","speech"].includes(String(c))?"audio":c;if(!["image","video","audio"].includes(String(l)))return;let f={id:"overlay-"+Date.now(),type:l,material:i,...l==="audio"?{gain:0}:{box:[.1,.1,.8,.6],fit:"contain"},during:{segment:a.id,from:0,to:a.end-a.start}};await r.send({op:"insert",path:["tracks",d.length],value:f},{kind:l==="audio"?"audio":"item",id:f.id})},Wn=e=>{let{store:t}=e,n=u("div",{class:"studio-resource-tabs"}),o=u("div"),r=()=>{n.replaceChildren(...["shots","files"].map(s=>C(x(t,s==="shots"?"shots":"sourceFile"),()=>{e.mediaView=s,r()},(e.mediaView??"shots")===s?"selected":""))),o.replaceChildren(n,(e.mediaView??"shots")==="shots"?At(e):Pr(e))};return r(),o},Pr=e=>{let{store:t}=e,n=t.get().state,o=u("input",{attrs:{type:"file",accept:"image/png,image/jpeg,image/webp,video/mp4,video/webm,video/quicktime,audio/*",hidden:""}});o.addEventListener("change",()=>{let s=o.files?.[0];if(!s)return;if(s.size>12*1024*1024){ce(t,x(t,"importHint"));return}let a=new FileReader;a.onload=()=>{ke(t,"/api/studio/import",{name:s.name,data:String(a.result).split(",")[1]})},a.readAsDataURL(s)});let r=u("div",{class:"studio-media-list"});for(let s of $(G(n?.source).materials)){let a=String(s.note??s.file??s.id),c=Ce(String(s.file??"")),i=s.kind==="image"?u("img",{attrs:{src:c,alt:a,loading:"lazy"}}):s.kind==="video"?u("video",{attrs:{src:c,controls:"",preload:"metadata"}}):u("audio",{attrs:{src:c,controls:"",preload:"none"}}),d=u("div",{class:"studio-actions"},[C(x(t,"addOverlay"),()=>{Un(e,s,!0)})]);["image","video"].includes(String(s.kind))&&d.prepend(C(x(t,"applyShot"),()=>{Un(e,s,!1)})),r.append(u("article",{class:"studio-media-card"},[i,u("strong",{text:a,title:a}),A(String(s.kind)),d]))}return r.children.length||r.append(A(x(t,"noMedia"))),u("div",{class:"studio-side-body"},[U(x(t,"media")),C(x(t,"upload"),()=>o.click(),"primary"),o,A(x(t,"importHint")),A(x(t,"chooseMaterial")),r])},qn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=u("div",{class:"studio-script-list"}),s=[];return $(G(o?.source).tracks).forEach((a,c)=>{a.type==="caption"&&$(a.cues).forEach((i,d)=>{s.push(String(i.text));let l=o?.resolved?.items.find(b=>b.cue?.track===a.id&&b.cue?.index===d),f=u("textarea",{class:"studio-input",attrs:{"aria-label":x(t,"subtitles")+" "+(d+1),rows:"2"}});f.value=String(i.text),f.addEventListener("change",()=>{n.send({op:"set",path:["tracks",c,"cues",d,"text"],value:f.value}),ce(t,x(t,"pendingVoice"))});let g=l?{kind:"item",id:l.id}:void 0,p=()=>{g&&n.reveal(g)};f.addEventListener("focus",p);let m=C(Ze(l?.start??0,o?.resolved?.canvas.fps??30),p),h=u("article",{class:"studio-sentence"+(g&&ge(g,t.get().pinned)?" selected":""),data:g?{selection:JSON.stringify(g)}:{}},[m,f]);h.addEventListener("click",p),r.append(h)})}),u("div",{class:"studio-side-body"},[U(x(t,"script")),A(x(t,"scriptHint"),"notice"),r,A(x(t,"narrationUnavailable")),C(x(t,"copyScript"),()=>{navigator.clipboard.writeText(s.join(\`
37956
+ \`)).then(()=>ce(t,x(t,"sourceChanged")))})])},Gn=e=>{let{store:t,edit:n}=e,o=t.get().state,r=Pt(e),s=u("div",{class:"studio-side-body"},[U(x(t,"elements"),r?.id)]);if(!o||!r)return s;s.append(C(x(t,"addText"),()=>{n.addText()}));for(let i of o.resolved?.items.filter(d=>d.end>r.start&&d.start<r.end)??[]){let d={kind:"item",id:i.id},l=C(i.text??x(t,i.type==="video"?"video":i.type==="image"?"image":i.type==="shape"?"color":"text"),()=>n.reveal(d),"studio-item"+(ge(d,t.get().pinned)?" selected":""));l.dataset.selection=JSON.stringify(d),s.append(l)}for(let i of o.resolved?.audio??[]){let d={kind:"audio",id:i.id},l=C(x(t,"audioTrack")+" \\xB7 "+i.id,()=>n.reveal(d),"studio-item"+(ge(d,t.get().pinned)?" selected":""));l.dataset.selection=JSON.stringify(d),s.append(l)}let a=He(document.querySelector("#page"),t,r.id),c=e.meta.slots.filter(i=>i.segment===r.id&&a?.has(i.name));s.append(U(x(t,"sceneFields")));for(let i of c){let d=t.get().pinned,l={kind:"slot",id:r.id,name:i.name},f=C("",()=>n.reveal(l,Qe(document.querySelector("#page"),t,l)),"studio-item "+(d?.kind==="slot"&&d.name===i.name?"selected":""));f.dataset.selection=JSON.stringify(l),f.append(u("span",{class:"studio-element-label",text:i.kind==="image"?x(t,"image"):i.value||i.name,title:i.value})),s.append(f)}return!c.length&&r.base.kind==="scene"&&s.append(A(x(t,"noSlots"))),s},Yn=e=>{let{store:t,actions:n}=e,o=t.get(),r=u("div",{class:"studio-side-body"},[U(x(t,"checks"))]);for(let a of o.state?.problems??[]){let c=u("article",{class:"studio-review-card"},[u("strong",{text:a.at}),A(a.message),A(a.fix??"")]),i=/^segments\\[(\\d+)\\]/.exec(a.at),d=i?o.state?.resolved?.segments[Number(i[1])]:void 0;d&&c.append(C(x(t,"goShot"),()=>Jn(e,d.id))),r.append(c)}o.state?.problems.length||r.append(A(x(t,"noProblems"))),r.append(A(o.state?.score?JSON.stringify(Object.fromEntries(Object.entries(o.state.score.dimensions).map(([a,c])=>[a,c.score.toFixed(2)]))):x(t,"unmeasured"))),r.append(U(x(t,"notes")));for(let a of e.meta.comments)r.append(u("article",{class:"studio-review-card"},[C(Ze(a.frame,o.state?.resolved?.canvas.fps??30),()=>{n.pause(),n.seek(a.frame)}),A(a.text),C(x(t,a.resolved?"reopen":"resolve"),()=>{ke(t,"/api/studio/comment",{id:a.id,resolved:!a.resolved}).then(e.refresh)})]));let s=u("textarea",{class:"studio-input",attrs:{rows:"3",placeholder:x(t,"noteHint")}});return r.append(s,C(x(t,"comment"),()=>{s.value.trim()&&ke(t,"/api/studio/comment",{text:s.value,frame:t.get().frame}).then(e.refresh)}),C(x(t,"copyNote"),()=>{navigator.clipboard.writeText(Ze(t.get().frame,o.state?.resolved?.canvas.fps??30)+" \\xB7 "+(Pt(e)?.id??"")+\`
37957
+ \`+s.value)}),A(x(t,"reviewOnly"))),r},Xn=e=>{let{store:t}=e,n=u("div",{class:"studio-side-body"},[U(x(t,"versions"))]),o=Oe("",x(t,"versionName"));o.placeholder=x(t,"versionName"),n.append(o,C(x(t,"saveVersion"),()=>{ke(t,"/api/studio/version",{name:o.value||x(t,"newVersion")}).then(e.refresh)},"primary"),A(x(t,"versionSnapshot")));for(let r of e.meta.versions)n.append(u("article",{class:"studio-review-card"},[u("strong",{text:r.name}),A(new Date(r.created).toLocaleString()),...r.hash===e.meta.hash?[A(x(t,"current"))]:[C(x(t,"restore"),()=>{ke(t,"/api/studio/restore",{id:r.id,base:t.get().state?.source}).then(e.refresh)})]]));return e.meta.versions.length||n.append(A(x(t,"noVersions"))),n},Zn=()=>J("/api/studio");var Qn=(e,t)=>{let n=u("textarea",{id:"studio-json",class:"studio-json",attrs:{spellcheck:"false","aria-label":"video.json"}}),o=u("div",{class:"studio-code-status",attrs:{role:"status"}}),r,s,a=!1,c=!1,i,d=()=>{s=e.get().state?.source,n.value=JSON.stringify(s,null,2)??"",a=!1,o.textContent=x(e,"autosave")},l=async()=>{if(!a||c)return;let m;try{m=JSON.parse(n.value)}catch(y){o.textContent=x(e,"invalid")+": "+(y instanceof Error?y.message:"");return}c=!0,o.textContent=x(e,"saving");let h=n.value,b=await t.replace(m,s);c=!1,b?(s=e.get().state?.source,a=h!==n.value,o.textContent=x(e,"sourceChanged"),a&&setTimeout(()=>{f()},0)):o.textContent=e.get().edit.problems[0]?.message??x(e,"conflict")},f=()=>r??=l().finally(()=>{r=void 0});n.addEventListener("input",()=>{a=!0,i&&clearTimeout(i),i=setTimeout(()=>{f()},650)}),n.addEventListener("keydown",m=>{(m.ctrlKey||m.metaKey)&&m.key.toLowerCase()==="s"&&(m.preventDefault(),f()),m.key==="Tab"&&(m.preventDefault(),n.setRangeText(" ",n.selectionStart,n.selectionEnd,"end"),n.dispatchEvent(new Event("input")))}),window.addEventListener("beforeunload",m=>{a&&(m.preventDefault(),m.returnValue="")});let g=()=>{try{n.value=JSON.stringify(JSON.parse(n.value),null,2),n.dispatchEvent(new Event("input"))}catch{o.textContent=x(e,"invalid")}},p=u("div",{class:"studio-code-wrap"},[U(x(e,"sourceTitle"),"video.json"),A(x(e,"codeHint")),u("div",{class:"studio-actions"},[C(x(e,"format"),g),C(x(e,"download"),()=>rn(n.value,"video.json"))]),n,o,C(x(e,"reload"),d)]);return e.subscribe((m,h)=>{m.state?.source!==h.state?.source&&(!a&&!c?d():!c&&JSON.stringify(m.state?.source)!==JSON.stringify(s)&&(o.textContent=x(e,"conflict")))}),d(),{root:p,flush:async()=>(clearTimeout(i),r&&await r,a&&await f(),!a)}};var $n=(e,t,n)=>{let o=t.get().lang==="zh",r=(O,D)=>o?O:D,s=u("div",{class:"studio-cloud",id:"studio-cloud",attrs:{"aria-live":"polite"}});e.append(s);let a,c,i,d="push",l="",f="",g=!1,p=!1,m=!0,h,b=O=>({UNAUTHORIZED:r("\\u767B\\u5F55\\u5DF2\\u8FC7\\u671F\\u6216\\u5DF2\\u4F7F\\u7528\\uFF0C\\u8BF7\\u91CD\\u65B0\\u70B9\\u51FB\\u201C\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u201D\\u3002","The login expired or was already used. Save to Cloud again."),LOGIN_REQUIRED:r("\\u8BF7\\u5148\\u767B\\u5F55\\uFF0C\\u518D\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF\\u3002","Sign in to save to cloud."),STORAGE_FULL:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),STORAGE_QUOTA_EXCEEDED:r("\\u4E91\\u7AEF\\u5B58\\u50A8\\u7A7A\\u95F4\\u5DF2\\u6EE1\\u3002","Your cloud storage is full."),RATE_LIMITED:r("\\u4E0A\\u4F20\\u8FC7\\u4E8E\\u9891\\u7E41\\uFF0C\\u8BF7\\u7A0D\\u540E\\u518D\\u8BD5\\u3002","Too many uploads. Try again in a moment."),DECK_INVALID:r("\\u4E91\\u7AEF\\u65E0\\u6CD5\\u63A5\\u6536\\u8FD9\\u4E2A\\u4F5C\\u54C1\\u3002","The cloud could not accept this project."),NETWORK:r("\\u65E0\\u6CD5\\u8FDE\\u63A5 popost.ai\\u3002","Could not reach popost.ai."),LOCAL_SAVE_FAILED:r("\\u672C\\u5730\\u6539\\u52A8\\u4FDD\\u5B58\\u5931\\u8D25\\u3002\\u8BF7\\u5148\\u4FDD\\u5B58\\u4F5C\\u54C1\\uFF0C\\u518D\\u4E0A\\u4F20\\u5230\\u4E91\\u7AEF\\u3002","Could not save local edits. Save the project before uploading.")})[O??""]??r("\\u4E0A\\u4F20\\u5931\\u8D25\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002","Upload failed. Try again."),y=(O,D=!1)=>u("span",{class:"studio-cloud-state"+(D?" bad":""),text:O,attrs:{role:"status"},title:c?.message??a?.error?.message??O}),v=()=>a?.webUrl?[u("a",{class:"studio-btn studio-icon-btn",attrs:{href:a.webUrl,target:"_blank",rel:"noopener noreferrer",title:r("\\u5728 popost \\u6253\\u5F00","Open in popost"),"aria-label":r("\\u5728 popost \\u6253\\u5F00","Open in popost")}},[Y("external")])]:[],E=O=>{c={code:"NETWORK",message:O instanceof Error?O.message:String(O)}},M=async()=>{try{a=await J("/api/cloud/status")}catch{}m&&(F(),clearTimeout(h),h=setTimeout(()=>{M()},i||a?.state==="waiting"||a?.state==="uploading"?2e3:5e3))},k=async()=>{if(i)return;let O=window.open("about:blank","_blank");d="start",c=void 0,p=!1,i="start",F();try{if(!await n()){O?.close(),c={code:"LOCAL_SAVE_FAILED",message:""};return}f=(await J("/api/studio/cloud/start",{lang:t.get().lang})).result.authorizeUrl,g=!O,O&&(O.opener=null,O.location.href=f),d="push",await M()}catch(D){O?.close(),E(D)}finally{i=void 0,await M()}},H=async(O=!1)=>{if(!i){d="push",c=void 0,i="push",F();try{if(!await n()){c={code:"LOCAL_SAVE_FAILED",message:""};return}a=(await J("/api/studio/cloud/push",{lang:t.get().lang,force:O})).result,!a.ok&&a.error?.code==="LOGIN_REQUIRED"&&(i=void 0,await k())}catch(D){E(D)}finally{i=void 0,await M()}}},L=async()=>{try{await navigator.clipboard.writeText(f),p=!0}catch{g=!0}F()},R=()=>{let O=c?.code??a?.error?.code;d==="start"||a?.mode==="anonymous"&&(O==="LOGIN_REQUIRED"||O==="UNAUTHORIZED")?k():H()},F=()=>{let O=JSON.stringify([a,c,i,f,g,p]);if(O===l||(l=O,s.hidden=a?.mode==="off",s.replaceChildren(),s.hidden))return;let D=i==="push"?"uploading":i==="start"?"starting":c?"failed":a?.state??"idle";if(D==="uploading"||D==="starting")s.append(y(D==="starting"?r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026"):a?.mode==="keyed"?r("\\u540C\\u6B65\\u4E2D\\u2026","Syncing\\u2026"):r("\\u4E0A\\u4F20\\u4E2D\\u2026","Uploading\\u2026")));else if(D==="waiting"){if(s.append(y(r("\\u7B49\\u5F85\\u767B\\u5F55\\u2026","Waiting for login\\u2026")),ne(p?r("\\u94FE\\u63A5\\u5DF2\\u590D\\u5236","Link copied"):r("\\u590D\\u5236\\u94FE\\u63A5","Copy link"),"duplicate",()=>{L()})),g&&f){let w=u("input",{class:"studio-cloud-link",attrs:{readonly:"","aria-label":r("\\u767B\\u5F55\\u94FE\\u63A5","Login link")}});w.value=f,w.addEventListener("focus",()=>w.select()),s.append(w)}}else if(D==="saved")s.append(y(a?.mode==="keyed"?r("\\u5DF2\\u540C\\u6B65","Synced"):r("\\u5DF2\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Saved to cloud")),...v());else if(D==="failed")s.append(y(b(c?.code??a?.error?.code),!0),ne(r("\\u91CD\\u8BD5","Retry"),"refresh",R));else if(D==="conflict"){if(s.append(y(r("\\u7F51\\u9875\\u7AEF\\u5DF2\\u6709\\u4FEE\\u6539","Edited on the web"),!0),...v()),a?.mode==="keyed"){let w=ne(r("\\u8986\\u76D6","Overwrite"),"cloud",()=>{H(!0)});w.title=r("\\u7528\\u672C\\u5730\\u7248\\u672C\\u66FF\\u6362\\u7F51\\u9875\\u7AEF\\u7684\\u7248\\u672C","Replace the web copy with this local version"),s.append(w)}}else if(!a)s.append(y(r("\\u6B63\\u5728\\u68C0\\u67E5\\u8D26\\u53F7\\u2026","Checking account\\u2026")));else{let w=ne(a?.mode==="keyed"?r("\\u7ACB\\u5373\\u540C\\u6B65","Sync now"):a?.webUrl&&a.dirty?r("\\u672C\\u5730\\u6539\\u52A8\\u672A\\u4E0A\\u4F20","Local changes not uploaded"):r("\\u4FDD\\u5B58\\u5230\\u4E91\\u7AEF","Save to Cloud"),"cloud",()=>{a?.mode==="keyed"?H():k()});w.id="studio-cloud-save",w.disabled=!a,w.title=r("\\u5728 popost \\u7F51\\u9875\\u7AEF\\u7BA1\\u7406\\u4F60\\u7684\\u6240\\u6709\\u8D44\\u4EA7","Manage all your assets on the Popost website"),s.append(w)}};t.subscribe((O,D)=>{O.state?.source!==D.state?.source&&M()}),window.addEventListener("pagehide",()=>{m=!1,clearTimeout(h)}),F(),M()};var ct=(e,t,n)=>{if(t.kind==="segment"||t.track.type==="audio"||!T(e.source))return;let o=ee(e),r=o.map((m,h)=>({track:m,index:h})).filter(m=>m.track.type!=="audio").sort((m,h)=>Number(m.track.z??m.index)-Number(h.track.z??h.index)||m.index-h.index),s=e.resolved?.items.filter(m=>m.id===t.track.id||m.cue?.track===t.track.id)??[],a=new Set((e.resolved?.items??[]).filter(m=>s.some(h=>h.start<m.end&&h.end>m.start)).map(m=>m.cue?.track??m.id)),c=r.filter(m=>a.has(String(m.track.id))),i=c.findIndex(m=>m.index===t.index),d=c[i+n];if(!d)return;let l=r.findIndex(m=>m.index===t.index),f=r.indexOf(d);if(l<0||f<0||f>=r.length)return;let g=r.splice(l,1)[0];r.splice(f,0,g);let p=new Map(r.map((m,h)=>[m.index,h]));return{...e.source,tracks:o.map((m,h)=>p.has(h)?{...m,z:p.get(h)}:m)}};var eo=(e,t,n)=>{let o=u("input",{attrs:{type:"range",min:"100",max:"500",value:"100","aria-label":x(t,"zoom")}}),r=()=>e.parentElement?.style.setProperty("--timeline-zoom",String(Number(o.value)/100));o.addEventListener("input",r),r();let s=t.get().lang==="zh",a=(h,b)=>{let y=C(b,()=>{let v=t.get().timeline??{layers:!0,snapping:!0};t.set({timeline:{...v,[h]:!v[h]}})});return y.id="timeline-"+h,y},c=a("layers",s?"\\u56FE\\u5C42":"Layers");c.prepend(Y("layers"));let i=a("snapping",s?"\\u5438\\u9644":"Snap"),d=C(s?"\\u5206\\u5272":"Split",()=>{n.split()});d.id="edit-split";let l=h=>C(h<0?s?"\\u524D\\u79FB":"Earlier":s?"\\u540E\\u79FB":"Later",()=>{let b=n.target(),y=t.get().state;if(!(!y||!b))if(b.kind==="segment")n.send({op:"move",path:["segments",b.index],to:b.index+h});else{let v=ct(y,b,h);v&&n.replace(v,y.source)}}),f=l(-1),g=l(1);f.id="scene-earlier",g.id="scene-later";let p=u("span",{id:"timeline-selection",class:"timeline-selection"});e.append(u("span",{id:"edit-slot"}),d,f,g,u("span",{class:"timeline-divider"}),c,i,p,u("span",{class:"spacer"}),C(x(t,"viewAll"),()=>{o.value="100",r()}),o);let m=()=>{let h=t.get(),b=n.target();c.classList.toggle("selected",h.timeline?.layers!==!1),i.classList.toggle("selected",h.timeline?.snapping!==!1),c.setAttribute("aria-pressed",String(h.timeline?.layers!==!1)),i.setAttribute("aria-pressed",String(h.timeline?.snapping!==!1)),d.disabled=!!h.edit.saving||!n.canSplit(),f.hidden=g.hidden=!b||b.kind!=="segment"&&b.track.type==="audio",f.textContent=b?.kind==="segment"?s?"\\u524D\\u79FB":"Earlier":s?"\\u4E0B\\u79FB\\u56FE\\u5C42":"Send backward",g.textContent=b?.kind==="segment"?s?"\\u540E\\u79FB":"Later":s?"\\u4E0A\\u79FB\\u56FE\\u5C42":"Bring forward",f.disabled=b?.kind==="segment"?b.index===0:!(h.state&&b&&ct(h.state,b,-1)),g.disabled=b?.kind==="segment"?b.index>=(h.state?.resolved?.segments.length??0)-1:!(h.state&&b&&ct(h.state,b,1)),h.edit.saving&&(f.disabled=g.disabled=!0);let y=h.pinned,v=y?.kind==="slot"?h.slots?.find(M=>M.segment===y.id&&M.name===y.name):void 0,E=y?.kind==="item"?h.state?.resolved?.items.find(M=>M.id===y.id):void 0;p.textContent=y?y.kind==="slot"?v?.kind==="image"?s?"\\u56FE\\u7247":"Image":v?.value??x(t,"selected"):E?.text??(b?.kind==="segment"?(s?"\\u955C\\u5934 ":"Shot ")+(b.index+1):y.kind==="audio"?x(t,"audioTrack"):x(t,"selected")):s?"\\u70B9\\u9009\\u955C\\u5934\\u6216\\u753B\\u9762\\u5185\\u5BB9\\u8FDB\\u884C\\u7F16\\u8F91":"Select a shot or canvas element to edit",p.title=p.textContent};t.subscribe((h,b)=>{h.state!==b.state||h.pinned!==b.pinned||h.timeline!==b.timeline||h.slots!==b.slots||h.edit.saving!==b.edit.saving?m():h.frame!==b.frame&&(d.disabled=!!h.edit.saving||!n.canSplit())}),m()};var to=(e,t)=>{let n=e.get().lang==="zh",o=(h,b)=>n?h:b,r=t.target==="jianying"?o("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro"):"CapCut",s=!1,a=()=>{s||(i.remove(),c.remove(),document.getElementById("studio-export-open")?.focus())},c=u("div",{class:"studio-scrim",on:{click:a}}),i=u("aside",{class:"studio-export studio-draft-success",attrs:{role:"dialog","aria-modal":"true","aria-label":o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r}}),d=A(t.productRunning?o("\\u91CD\\u542F"+r+"\\u5373\\u53EF\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u770B\\u5230\\u300C"+t.name+"\\u300D\\u3002","Restart "+r+" to find \\u201C"+t.name+"\\u201D in local drafts."):o("\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u8349\\u7A3F\\uFF0C\\u6253\\u5F00"+r+"\\u5373\\u53EF\\u67E5\\u770B\\u300C"+t.name+"\\u300D\\u3002","Open "+r+" to find \\u201C"+t.name+"\\u201D in local drafts.")),l=u("div",{attrs:{role:"status"}}),f=C(o("\\u7A0D\\u540E","Later"),a),g=C("\\xD7",a);g.setAttribute("aria-label",o("\\u5173\\u95ED","Close"));let p=t.productRunning?o("\\u91CD\\u542F","Restart ")+r:o("\\u6253\\u5F00","Open ")+r,m=C(p,()=>{(async()=>{s=!0,m.disabled=f.disabled=g.disabled=!0,m.textContent=o("\\u6B63\\u5728\\u6253\\u5F00\\u2026","Opening\\u2026"),l.replaceChildren();try{let h=await J("/api/studio/draft-open",{receiptId:t.receiptId});if(!h.result.ok){l.replaceChildren(A(h.result.quitPending?o(r+"\\u8FD8\\u672A\\u9000\\u51FA\\uFF0C\\u8BF7\\u5148\\u5728\\u5E94\\u7528\\u4E2D\\u4FDD\\u5B58\\u6216\\u5173\\u95ED\\u5F39\\u7A97\\uFF0C\\u7136\\u540E\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002",r+" has not exited. Save your work or close its dialog, then retry. Your draft is already saved."):h.result.message??o("\\u5E94\\u7528\\u672A\\u80FD\\u6253\\u5F00\\uFF0C\\u8BF7\\u91CD\\u8BD5\\u3002\\u8349\\u7A3F\\u5DF2\\u7ECF\\u4FDD\\u5B58\\u3002","The editor did not open. Retry; your draft is already saved."),"bad"));return}s=!1,a(),ce(e,h.result.restarted?o("\\u5DF2\\u91CD\\u542F","Restarted ")+r:o("\\u5DF2\\u6253\\u5F00","Opened ")+r)}catch(h){l.replaceChildren(A(String(h),"bad"))}finally{s=!1,m.disabled=f.disabled=g.disabled=!1,m.textContent=p}})()},"primary");t.canOpen||l.append(A(o("\\u672A\\u627E\\u5230\\u5E94\\u7528\\u5B89\\u88C5\\u4F4D\\u7F6E\\uFF0C\\u53EF\\u4EE5\\u7A0D\\u540E\\u624B\\u52A8\\u6253\\u5F00\\u3002\\u8349\\u7A3F\\u548C\\u7D20\\u6750\\u5DF2\\u4FDD\\u5B58\\u5230\\u672C\\u673A\\u3002","The app location could not be found. Open it manually later; the draft and media are saved locally."))),i.append(u("div",{class:"studio-export-header"},[U(o("\\u5DF2\\u5BFC\\u5165","Imported into ")+r),g]),d,l,u("div",{class:"studio-draft-actions"},[f,...t.canOpen?[m]:[]])),document.body.append(c,i),i.addEventListener("keydown",h=>{if(h.key==="Escape"&&a(),h.key!=="Tab")return;let b=Array.from(i.querySelectorAll("button:not(:disabled)")),y=b[0],v=b[b.length-1];h.shiftKey&&document.activeElement===y?(h.preventDefault(),v?.focus()):!h.shiftKey&&document.activeElement===v&&(h.preventDefault(),y?.focus())}),(t.canOpen?m:f).focus()};var Ct=(e,t)=>{if(document.getElementById("studio-export"))return;let n=e.get().state;if(!n?.resolved||!n.edit)return;let o=n.resolved,r=e.get().lang==="zh",s=(P,V)=>r?P:V,a="video",c="jianying",i="1080",d="",l="",f=!1,g=!1,p,m=!1,h,b,y=u("div",{class:"studio-export-result",attrs:{role:"status"}}),v=u("div",{class:"studio-paid-info"}),E,M=u("progress",{attrs:{max:"1",value:"0",hidden:""}}),k=u("fieldset",{class:"studio-export-fields"}),H=u("div",{class:"studio-segments export-tabs",attrs:{role:"tablist"}}),L=u("aside",{id:"studio-export",class:"studio-export",attrs:{role:"dialog","aria-modal":"true","aria-label":s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")}}),R=()=>{g||(document.removeEventListener("keydown",F,!0),so(),O.remove(),L.remove(),document.getElementById("studio-export-open")?.focus())},F=P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),R())},O=u("div",{class:"studio-scrim",on:{click:R}}),D=(P,V,I)=>u("div",{class:"studio-segments"},P.map(([me,de])=>{let Ot=C(de,()=>I(me),me===V?"selected":"");return Ot.setAttribute("aria-pressed",String(me===V)),Ot})),w=(P,V)=>(V.setAttribute("role","group"),V.setAttribute("aria-label",P),u("div",{class:"studio-field"},[u("span",{text:P}),V])),N=()=>{if(v.hidden=a!=="video",H.replaceChildren(...[["video",x(e,"video")],["draft",s("\\u526A\\u6620","Draft")]].map(([I,me])=>{let de=C(me,()=>{a=I,y.replaceChildren(),N(),B()},a===I?"selected":"");return de.setAttribute("role","tab"),de.setAttribute("aria-selected",String(a===I)),de})),a==="draft"){let I=u("details",{},[u("summary",{text:s("\\u90E8\\u5206\\u5185\\u5BB9\\u4E0D\\u652F\\u6301","Some content is flattened")}),A(s("\\u652F\\u6301\\uFF1A\\u5B57\\u5E55\\u6587\\u5B57\\u4E0E\\u65F6\\u95F4\\u3001\\u89C6\\u9891\\u7247\\u6BB5\\u3001\\u97F3\\u9891\\u7247\\u6BB5\\u3002\\u5B57\\u5E55\\u6837\\u5F0F\\u9700\\u5728\\u76EE\\u6807\\u7F16\\u8F91\\u5668\\u4E2D\\u91CD\\u65B0\\u8BBE\\u7F6E\\uFF1B\\u590D\\u6742\\u89C6\\u89C9\\u6548\\u679C\\u70D8\\u7119\\u5230\\u5404\\u4E2A\\u89C6\\u9891\\u7247\\u6BB5\\u3002","Supported: caption text/timing, video clips and audio clips. Reapply caption styles in the target editor. Complex visuals are baked per clip."))]),me=h?.find(de=>de.target===c);k.replaceChildren(A(s("\\u628A\\u5F53\\u524D\\u65F6\\u95F4\\u7EBF\\u76F4\\u63A5\\u4FDD\\u5B58\\u4E3A\\u672C\\u673A\\u5E94\\u7528\\u4E2D\\u53EF\\u7EE7\\u7EED\\u7F16\\u8F91\\u7684\\u8349\\u7A3F\\u3002","Save the current timeline directly into your desktop editor\\u2019s local drafts.")),A(s("\\u5BFC\\u51FA\\u6210\\u529F\\u540E\\u53EF\\u4E00\\u952E\\u91CD\\u542F\\u5E94\\u7528\\uFF0C\\u5728\\u672C\\u5730\\u8349\\u7A3F\\u4E2D\\u7EE7\\u7EED\\u7F16\\u8F91\\u3002","After export, restart the app with one click and continue editing from local drafts.")),w(s("\\u5E94\\u7528","Application"),D([["jianying",s("\\u526A\\u6620\\u4E13\\u4E1A\\u7248","Jianying Pro")],["capcut","CapCut"]],c,de=>{c=de,b=void 0,N(),B()})),I),h?me?.usable||k.append(A(me?.error??s("\\u8BF7\\u5728\\u8FD0\\u884C\\u6B64\\u7F16\\u8F91\\u5668\\u7684\\u7535\\u8111\\u4E0A\\u5B89\\u88C5\\u5E76\\u6253\\u5F00\\u6240\\u9009\\u5E94\\u7528\\uFF0C\\u518D\\u91CD\\u65B0\\u6253\\u5F00\\u5BFC\\u51FA\\u8BBE\\u7F6E\\u3002","Install and open the selected app on the computer running this editor, then reopen export settings."),"bad")):k.append(A(s("\\u6B63\\u5728\\u68C0\\u67E5\\u672C\\u673A\\u5E94\\u7528\\u2026","Checking desktop editors\\u2026")));return}let P=D([["480","480p"],["720","720p"],["1080","1080p"],["2160","4K"]],i,I=>{i=I,N(),B()}),V=u("button",{text:"HDR",attrs:{type:"button",disabled:"",title:x(e,"hdrUnavailable")}});if(k.replaceChildren(w(x(e,"dynamicRange"),u("div",{class:"studio-segments"},[C("SDR",()=>{},"selected"),V])),w(x(e,"resolution"),P),Me(x(e,"fps"),wt([["",x(e,"match")+" ("+o.canvas.fps+" fps)"],...[24,25,30,50,60].map(I=>[String(I),I+" fps"])],d,x(e,"fps"),I=>{d=I})),Me(s("\\u89C6\\u9891\\u7801\\u7387","Video bitrate"),wt([["",x(e,"recommended")],...[2,5,8,12,20,40].map(I=>[String(I),I+" Mbps"])],l,x(e,"bitrate"),I=>{l=I}))),v.replaceChildren(),!f){let I=P.lastElementChild;I&&I.append(u("span",{class:"export-pro",text:"PRO"}))}i==="2160"&&!f&&v.append(A(s("4K \\u4E3A\\u4ED8\\u8D39\\u5206\\u8FA8\\u7387\\u3002\\u5347\\u7EA7\\u5957\\u9910\\u540E\\u5373\\u53EF\\u5BFC\\u51FA\\uFF1B1080p \\u53CA\\u4EE5\\u4E0B\\u53EF\\u7EE7\\u7EED\\u4F7F\\u7528\\u3002","4K requires a paid plan. Upgrade to export in 4K, or choose 1080p or below.")),...E?[u("a",{class:"studio-btn",text:x(e,"unlock"),attrs:{href:E,target:"_blank",rel:"noopener"}})]:[A(x(e,"loading"))],C(x(e,"refreshPlan"),()=>{J("/api/export-options").then(I=>{f=I.premium,N(),B()})}))},z=C(s("\\u5BFC\\u51FA","Export"),()=>{(async()=>{try{if(a==="draft"){g=!0,B(),b??=crypto.randomUUID();let P=await J("/api/studio/draft",{target:c,requestId:b});g=!1,R(),to(e,P.result)}else{p=void 0,m=!1;let P=await J("/api/render",{name:"Popost-video",resolution:i,dynamicRange:"sdr",fps:d?Number(d):null,bitrate:l?Number(l):null,audio:!0});p=P.render.state==="running"?P.render.started:P.render.state==="done"||P.render.state==="failed"?P.render.finished:void 0,t.setRender(P.render)}}catch(P){y.replaceChildren(A(String(P),"bad"))}finally{g=!1,B()}})()},"primary"),B=()=>{let P=e.get().edit.render,V=g||a==="video"&&P?.state==="running";if(k.disabled=V,z.disabled=V||a==="video"&&i==="2160"&&!f||a==="draft"&&!h?.find(I=>I.target===c)?.usable,K.disabled=g,H.querySelectorAll("button").forEach(I=>{I.disabled=V}),M.hidden=!V,z.textContent=V?s("\\u6B63\\u5728\\u5BFC\\u51FA\\u2026","Exporting\\u2026"):s("\\u5BFC\\u51FA","Export"),a==="draft"){g&&M.removeAttribute("value");return}P?.state==="running"&&(M.value=P.total?P.frame/P.total:0,y.replaceChildren()),P?.state==="failed"&&y.replaceChildren(A(P.message,"bad")),P?.state==="done"&&p!==void 0&&P.finished>=p&&(p!==void 0&&P.finished>=p&&!m&&(m=!0,u("a",{attrs:{href:P.url,download:"Popost-video.mp4"}}).click()),y.replaceChildren(A(s("\\u5BFC\\u51FA\\u5B8C\\u6210\\uFF0C\\u89C6\\u9891\\u5DF2\\u4FDD\\u5B58\\u5E76\\u5F00\\u59CB\\u4E0B\\u8F7D\\u3002","Export complete. The video is saved and downloading."))))},K=C("\\xD7",R);L.append(u("div",{class:"studio-export-header"},[U(s("\\u5BFC\\u51FA\\u8BBE\\u7F6E","Export settings")),K]),H,k,v,M,z,y),document.body.append(O,L),N(),B(),J("/api/export-options").then(P=>{f=P.premium,E=P.pricingUrl??E,N(),B()}).catch(()=>{}),J("/api/studio/draft-targets",{}).then(P=>{h=P.result.applications,N(),B()}).catch(P=>{h=[],y.replaceChildren(A(String(P),"bad")),N(),B()});let so=e.subscribe((P,V)=>{L.isConnected&&P.edit.render!==V.edit.render&&B()});document.addEventListener("keydown",F,!0),z.focus()};var Ar=[["media","media","media"],["elements","elements","layers"],["script","subtitles","text"],["code","code","code"]],no=(e,t,n,o)=>{let r="media",s=u("nav",{class:"studio-rail",attrs:{"aria-label":"Studio"}}),a=u("aside",{id:"studio-content",class:"studio-content"}),c=Qn(t,o),i=c.root,d={store:t,actions:n,edit:o,meta:{hash:"",slots:[],versions:[],comments:[]},refresh:()=>{}},l=()=>{let w=document.querySelector("#page"),N=new Map([...new Set(d.meta.slots.map(K=>K.segment))].map(K=>[K,He(w,t,K)])),z=d.meta.slots.filter(K=>N.get(K.segment)?.has(K.name));if(JSON.stringify(z)!==JSON.stringify(t.get().slots)&&t.set({slots:z}),s.querySelectorAll("button").forEach(K=>{K.classList.toggle("active",K.dataset.panel===r),K.setAttribute("aria-pressed",String(K.dataset.panel===r))}),document.body.classList.toggle("panel-code",r==="code"),r==="code"){a.contains(i)||a.replaceChildren(i);return}let B={shots:At,media:Wn,script:qn,elements:Gn,checks:Yn,versions:Xn};a.replaceChildren(B[r](d))},f=w=>{r=w,l()};for(let[w,N,z]of Ar){let B=u("button",{data:{panel:w},attrs:{type:"button",title:x(t,N)},on:{click:()=>f(w)}},[Y(z),u("span",{text:x(t,N)})]);s.append(B)}let g=async()=>{let w=t.get().state?.generation;try{let N=await Zn();if(w!==t.get().state?.generation)return;d.meta=N,N.lastExport&&t.get().edit.render?.state!=="running"&&(!t.get().edit.render||t.get().edit.render?.state==="idle")&&o.setRender(N.lastExport),l()}catch{}};d.refresh=()=>{g()},e.prepend(s,a);let p=document.querySelector(".studio-topbar"),m=u("strong",{class:"studio-brand",text:"popost"}),h=u("span",{class:"studio-project"}),b=u("span",{class:"studio-save"}),y=u("span",{class:"studio-global-actions"}),v=ne(x(t,"compare"),"compare",()=>{if(!t.get().state?.reference){ce(t,x(t,"noReference"));return}t.get().edit.playRender&&o.togglePlayRender(),t.set({compare:!t.get().compare})});v.id="studio-compare";let E=ne(x(t,"layout"),"layout",()=>{let w=document.body.classList.toggle("focus-preview");E.setAttribute("aria-pressed",String(w))});E.setAttribute("aria-pressed","false");let M=ne(x(t,"theme"),"theme",()=>{let w=document.documentElement.classList.toggle("dark");M.setAttribute("aria-pressed",String(w)),localStorage.setItem("popost-studio-theme",w?"dark":"light")});M.setAttribute("aria-pressed",String(localStorage.getItem("popost-studio-theme")==="dark"));let k=ne(t.get().lang==="zh"?"English":"\\u4E2D\\u6587","language",()=>{let w=t.get().lang==="zh"?"en":"zh";localStorage.setItem("popost-studio-language",w),n.setLang(w),location.reload()});k.id="lang-toggle";let H=ne(x(t,"versions"),"history",()=>f("versions")),L=ne(x(t,"export"),"download",()=>Ct(t,o));L.id="studio-export-open",y.append(v,E,H,M,k),$n(y,t,async()=>await o.flush()?await c.flush()&&await o.flush():!1),y.append(L),p.append(m,h,b,y),document.documentElement.classList.toggle("dark",localStorage.getItem("popost-studio-theme")==="dark"),document.addEventListener("studio:export",()=>Ct(t,o));let R=document.getElementById("studio-stage-heading"),F=u("input",{attrs:{type:"checkbox","aria-label":x(t,"audio")}});F.checked=!0,F.addEventListener("change",()=>t.set({muted:!F.checked})),R.append(u("span",{text:x(t,"preview")}),u("label",{class:"studio-check",title:x(t,"onlyPreview")},[F,x(t,"audio")]));let O=document.querySelector(".panel");O.prepend(U(x(t,"properties")));let D=()=>{let w=t.get();document.body.setAttribute("aria-busy",String(!!w.edit.saving)),h.textContent=w.state?.project.name??"Popost Video Studio",b.textContent=w.connected?w.state?.edit?x(t,"saved"):x(t,"readOnly"):x(t,"offline"),w.edit.saving&&(b.textContent=x(t,"saving")),w.edit.status?.kind==="refused"&&(b.textContent=x(t,"error")),v.classList.toggle("selected",!!w.compare),v.setAttribute("aria-pressed",String(!!w.compare)),L.disabled=!w.state?.edit||!w.state.resolved,O.hidden=!w.pinned,document.body.classList.toggle("inspecting",!!w.pinned)};return t.subscribe((w,N)=>{if((w.state!==N.state||w.pinned!==N.pinned||w.compare!==N.compare||w.connected!==N.connected||w.edit.status!==N.edit.status||w.edit.saving!==N.edit.saving)&&D(),w.state!==N.state?(l(),g()):w.frame!==N.frame&&r==="elements"&&w.state?.resolved?.segments.find(z=>w.frame>=z.start&&w.frame<z.end)?.id!==N.state?.resolved?.segments.find(z=>N.frame>=z.start&&N.frame<z.end)?.id&&l(),w.pinned!==N.pinned&&w.pinned){let z=w.state?q(w.state,w.pinned):void 0,B=w.pinned.kind==="segment"?"media":z?.kind==="cue"?"script":"elements";B==="media"&&(d.mediaView="shots");let K=a.contains(document.activeElement);(r!==B||!K)&&(r=B,l())}w.pinned!==N.pinned&&a.querySelectorAll("[data-selection]").forEach(z=>{let B=z.dataset.selection===JSON.stringify(w.pinned);z.classList.toggle("selected",B),z.tagName==="BUTTON"&&z.setAttribute("aria-pressed",String(B)),B&&z.scrollIntoView({block:"nearest"})})}),document.addEventListener("studio:page-ready",l),document.addEventListener("studio:scene-ready",()=>{r==="elements"&&l()}),D(),l(),{refresh:g,choose:f,content:a,panel:()=>r}},oo=eo,ut=(e,t)=>{let n=t==="timeline",o=u("div",{class:"studio-handle "+(n?"horizontal":"vertical")+(t==="right"?" inspector-resize":""),attrs:{role:"separator",tabindex:"0","aria-orientation":n?"horizontal":"vertical"}});return n||(o.style.left=t==="left"?"calc(64px + var(--left-width) - 2px)":"calc(100% - var(--right-width) - 2px)"),o.addEventListener("pointerdown",r=>{o.setPointerCapture(r.pointerId);let s=n?r.clientY:r.clientX,a=n?"--timeline-height":t==="left"?"--left-width":"--right-width",c=parseFloat(getComputedStyle(document.documentElement).getPropertyValue(a)),i=l=>{let f=(n?l.clientY:l.clientX)-s,g=Math.min(n?innerHeight*.65:innerWidth*.4,Math.max(n?150:210,c+(t==="left"?f:-f)));document.documentElement.style.setProperty(a,g+"px")},d=()=>{o.removeEventListener("pointermove",i),o.removeEventListener("pointerup",d),localStorage.setItem("popost-studio-layout",document.documentElement.style.cssText)};o.addEventListener("pointermove",i),o.addEventListener("pointerup",d)}),e.append(o),o};var Cr=async()=>{let e=await fetch("/api/state",{cache:"no-store"});if(!e.ok)throw new Error("GET /api/state answered "+e.status);return await e.json()},Or=["boxes","events","safe"],Hr=(e,t)=>{let n=u("h1"),o=u("span",{class:"project",id:"project"}),r=u("span",{class:"status",id:"status"}),s=Or.map(i=>{let d=u("input",{id:"toggle-"+i,attrs:{type:"checkbox"}});d.addEventListener("change",()=>{t.toggleOverlay(i),d.blur()});let l=u("span");return{name:i,input:d,text:l,el:u("label",{class:"toggle"},[d,l])}}),a=u("button",{id:"lang-toggle",class:"tbtn",attrs:{type:"button"}});a.addEventListener("click",()=>{t.setLang(e.get().lang==="en"?"zh":"en"),a.blur()});let c=i=>{let d=i.state;n.textContent=S(i.lang,"title"),o.textContent=d?d.project.name+(d.resolved?" "+d.resolved.frames+"f, "+(d.resolved.frames/d.resolved.canvas.fps).toFixed(2)+" s":""):"",o.title=d?.project.dir??"",r.textContent=S(i.lang,d?.edit?"editing":"readOnly")+", "+S(i.lang,i.connected?"live":"offline"),r.classList.toggle("offline",!i.connected),s.forEach(l=>{l.text.textContent=S(i.lang,l.name),l.input.checked=i.overlays[l.name]}),a.textContent=S(i.lang,"language"),a.title=S(i.lang,"languageTitle")};return c(e.get()),e.subscribe((i,d)=>{(i.state!==d.state||i.lang!==d.lang||i.connected!==d.connected||i.overlays!==d.overlays)&&c(i)}),u("header",{},[n,o,...s.map(i=>i.el),u("span",{id:"edit-slot",class:"edit-slot"}),r,a])},Nr=(e,t)=>{document.body.classList.add("editing");let n=document.getElementById("edit-slot");n&&tt(n,e.store,e.edit),nt(e.panel,e.store,e.edit);let o=et(e.stage.frameBox,e.stage.iframe,e.store,e.edit);Ge(e.lanes,e.store,e.edit),ot(e.store,e.edit,o.nudge),We(e.store);let r=Je(t);r&&e.edit.select(r),t.edit&&t.edit.render.state!=="idle"&&e.edit.setRender(t.edit.render),e.events.addEventListener(je,s=>e.edit.setRender(JSON.parse(s.data))),Xe().then(s=>e.store.set({edit:{...e.store.get().edit,schema:s}}))},ro=()=>{let e=Ue(navigator.language);document.documentElement.lang=e==="zh"?"zh-CN":"en";let t=_e({state:null,frame:0,playing:!1,speed:1,lang:e,pinned:null,overlays:{boxes:!1,events:!0,safe:!1},connected:!0,pageError:null,edit:Ve}),n=Ke(t),o=qe(t,n),r=document.getElementById("app")??document.body,s=u("div",{class:"stage-area",id:"stage"}),a=u("div",{class:"transport",id:"transport"}),c=u("div",{class:"timeline",id:"timeline"}),i=u("aside",{class:"panel",id:"panel"});r.append(Hr(t,n),u("div",{class:"main"},[u("div",{class:"left"},[s,a,c]),i]));let d=dt(s,t,n);lt(a,t,n),rt(c,t,n),it(i,t,n,o);let l=new EventSource("/api/events"),f=!1,g=async()=>{try{let p=await Cr(),m=t.get();if(m.connected&&m.state&&p.generation<m.state.generation)return;t.set({state:p,frame:pe(t.get().frame,W(p)),connected:!0}),p.edit&&!f&&(f=!0,Nr({store:t,edit:o,stage:d,lanes:c.querySelector("#lanes")??c,panel:i,events:l},p))}catch{t.set({connected:!1})}};l.addEventListener(De,()=>{g()}),l.addEventListener("open",()=>{t.get().connected||g()}),l.addEventListener("error",()=>{t.get().connected&&t.set({connected:!1})}),g()};var Ir=()=>{let e=localStorage.getItem("popost-studio-language"),t=e==="zh"||e==="en"?e:Ue(navigator.language);document.documentElement.lang=t==="zh"?"zh-CN":"en",document.body.classList.add("studio");let n=localStorage.getItem("popost-studio-layout");n&&/^[-a-z0-9:;. %px]+$/i.test(n)&&(document.documentElement.style.cssText=n);let o=_e({state:null,frame:0,playing:!1,speed:1,lang:t,pinned:null,compare:!1,muted:!1,timeline:{layers:!1,snapping:!0},overlays:{boxes:!1,events:!1,safe:!1},connected:!0,pageError:null,edit:Ve}),r=Ke(o),s=qe(o,r),a=document.getElementById("app")??document.body,c=u("header",{class:"studio-topbar"}),i=u("div",{class:"stage-area",id:"stage"}),d=u("div",{class:"transport",id:"transport"}),l=u("div",{class:"timeline",id:"timeline"}),f=u("aside",{class:"panel",id:"panel"}),g=u("div",{class:"main"},[u("div",{class:"left"},[u("div",{id:"studio-stage-heading",class:"studio-stage-heading"}),i,d]),f]),p=u("div",{class:"studio-timeline-toolbar"}),m=u("div",{class:"studio-timeline-wrap"},[p,l]),h=u("footer",{class:"studio-footer"},["Popost Video Studio","video.json"]);a.append(c,g,m,h,u("div",{id:"studio-message",attrs:{role:"status"}})),no(g,o,r,s),oo(p,o,s),ut(g,"left"),ut(g,"right"),ut(m,"timeline");let b=dt(i,o,r);lt(d,o,r),rt(l,o,r),it(f,o,r,s),gn(o);let y=new EventSource("/api/events"),v=!1,E=async()=>{try{let M=await fetch("/api/state",{cache:"no-store"});if(!M.ok)throw new Error;let k=await M.json(),H=o.get();if(H.connected&&H.state&&k.generation<H.state.generation)return;if(o.set({state:k,frame:pe(H.frame,W(k)),connected:!0}),k.edit&&!v){v=!0,document.body.classList.add("editing"),tt(document.getElementById("edit-slot"),o,s),nt(f,o,s);let L=et(b.frameBox,b.iframe,o,s);Ge(l.querySelector("#lanes")??l,o,s),ot(o,s,L.nudge),We(o);let R=Je(k);R&&s.select(R),k.edit.render.state!=="idle"&&s.setRender(k.edit.render),Xe().then(F=>o.set({edit:{...o.get().edit,schema:F}}))}}catch{o.set({connected:!1})}};y.addEventListener(De,()=>{E()}),y.addEventListener(je,M=>s.setRender(JSON.parse(M.data))),y.addEventListener("open",()=>{o.get().connected||E()}),y.addEventListener("error",()=>{o.get().connected&&o.set({connected:!1})}),E()};document.documentElement.dataset.mode==="readonly"?ro():Ir();})();
37685
37958
  `;
37686
37959
  }
37687
37960
  });
@@ -40708,11 +40981,11 @@ var init_findings2 = __esm({
40708
40981
  };
40709
40982
  unseenProblem = (shot, mine, longer, theirs, picture3) => {
40710
40983
  const shown3 = theirs.filter((t) => t.visible).map((t) => t.index);
40711
- const missing2 = outermost(mine.filter((t) => !t.visible && shown3.includes(t.index))).slice(0, 3);
40712
- if (!missing2.length) return void 0;
40984
+ const missing3 = outermost(mine.filter((t) => !t.visible && shown3.includes(t.index))).slice(0, 3);
40985
+ if (!missing3.length) return void 0;
40713
40986
  return warning(
40714
40987
  at4(shot.k),
40715
- "In " + where2(shot) + ", a shot of " + s2(shot.seconds) + ", " + quoted3(missing2.map((t) => t.text)) + (missing2.length > 1 ? " are" : " is") + " never visible (" + picture3 + '), though segment "' + longer.id + '" (' + s2(longer.seconds) + ") shows " + (missing2.length > 1 ? "them" : "it") + " with the same scene file: the entrance starts after this shorter shot has ended.",
40988
+ "In " + where2(shot) + ", a shot of " + s2(shot.seconds) + ", " + quoted3(missing3.map((t) => t.text)) + (missing3.length > 1 ? " are" : " is") + " never visible (" + picture3 + '), though segment "' + longer.id + '" (' + s2(longer.seconds) + ") shows " + (missing3.length > 1 ? "them" : "it") + " with the same scene file: the entrance starts after this shorter shot has ended.",
40716
40989
  'Time the entrances for the shortest shot that shows "' + shot.src + '": every text visible by ' + s2(readBy(shot.seconds)) + ", then held. Or give this segment a scene file of its own."
40717
40990
  );
40718
40991
  };
@@ -41016,8 +41289,8 @@ var init_check7 = __esm({
41016
41289
  if (!wanted.length) return { problems: built.problems, shots: [], scenes: [] };
41017
41290
  const shots2 = [];
41018
41291
  const scenes = [];
41019
- const absent = [...await missingScripts(rt, projectDir, wanted), ...await missingStylesheets(rt, projectDir, wanted)];
41020
- if (absent.length) return { problems: [...built.problems, ...absent], shots: shots2, scenes };
41292
+ const absent2 = [...await missingScripts(rt, projectDir, wanted), ...await missingStylesheets(rt, projectDir, wanted)];
41293
+ if (absent2.length) return { problems: [...built.problems, ...absent2], shots: shots2, scenes };
41021
41294
  const problems2 = [...built.problems];
41022
41295
  const session = await openSession(rt, projectDir, { reuse: false }).catch((e) => e);
41023
41296
  if (session instanceof SceneLoadError) return { problems: [...problems2, ...session.problems], shots: shots2, scenes };
@@ -41420,9 +41693,9 @@ var init_collect = __esm({
41420
41693
  }
41421
41694
  });
41422
41695
  const pictureHosts = pictures.flatMap((p) => isHttp(p.from) && p.kind === "img" ? [new URL(p.from).hostname] : []);
41423
- const own2 = ownHosts(links2.map((k) => k.host), { ...l.base ? { page: l.base.hostname } : {}, pictureHosts, names: namesOf(l) });
41696
+ const own3 = ownHosts(links2.map((k) => k.host), { ...l.base ? { page: l.base.hostname } : {}, pictureHosts, names: namesOf(l) });
41424
41697
  const once4 = /* @__PURE__ */ new Set();
41425
- const ownLinks = links2.filter((k) => own2.some((h) => siteOf(h) === siteOf(k.host)) && !once4.has(k.url) && once4.add(k.url)).slice(0, 30).map((k) => ({ url: k.url, text: k.text }));
41698
+ const ownLinks = links2.filter((k) => own3.some((h) => siteOf(h) === siteOf(k.host)) && !once4.has(k.url) && once4.add(k.url)).slice(0, 30).map((k) => ({ url: k.url, text: k.text }));
41426
41699
  const entry2 = {
41427
41700
  source: o.source,
41428
41701
  title: read2.title,
@@ -41430,8 +41703,8 @@ var init_collect = __esm({
41430
41703
  pictures,
41431
41704
  skipped: { ...skipped2, failed: skipped2.failed.slice(0, 20) },
41432
41705
  colours: colours.filter((c, i) => colours.findIndex((x) => x.hex === c.hex) === i),
41433
- site: { hosts: [...new Set(own2.map(siteOf))], links: ownLinks },
41434
- otherHosts: [...new Set(links2.map((k) => k.host))].filter((h) => !own2.some((x) => siteOf(x) === siteOf(h))).slice(0, 30)
41706
+ site: { hosts: [...new Set(own3.map(siteOf))], links: ownLinks },
41707
+ otherHosts: [...new Set(links2.map((k) => k.host))].filter((h) => !own3.some((x) => siteOf(x) === siteOf(h))).slice(0, 30)
41435
41708
  };
41436
41709
  await rt.fs.writeFile(rt.path.join(o.outDir, INVENTORY_FILE), JSON.stringify({ sources: [...others, entry2] }, null, 1) + "\n");
41437
41710
  return entry2;
@@ -42416,9 +42689,9 @@ var init_speech_check = __esm({
42416
42689
  const a = comparedWords(script), b = comparedWords(heard);
42417
42690
  const pairs = commonPairs(a, b);
42418
42691
  const saidA = new Set(pairs.map(([i]) => i)), saidB = new Set(pairs.map(([, j]) => j));
42419
- const missing2 = a.filter((_w, i) => !saidA.has(i)), extra2 = b.filter((_w, j) => !saidB.has(j));
42692
+ const missing3 = a.filter((_w, i) => !saidA.has(i)), extra2 = b.filter((_w, j) => !saidB.has(j));
42420
42693
  const n = a.length, matched = pairs.length;
42421
- return { script: n, heard: b.length, matched, share: n ? Math.round(matched / n * 100) / 100 : 1, missing: missing2.slice(0, 12), extra: extra2.slice(0, 12) };
42694
+ return { script: n, heard: b.length, matched, share: n ? Math.round(matched / n * 100) / 100 : 1, missing: missing3.slice(0, 12), extra: extra2.slice(0, 12) };
42422
42695
  };
42423
42696
  lineTimes = (lines, words) => {
42424
42697
  const perLine = lines.map((l) => comparedWords(l));
@@ -42612,7 +42885,7 @@ var init_speech_rules = __esm({
42612
42885
  });
42613
42886
 
42614
42887
  // src/video/commands/materials.ts
42615
- var errorsIn2, PICTURE_EXT, givenAnchor, characterOf, budgeted, payingPending, LOOK_AGAIN_MS, waitLimitMs, PENDING_NEXT, beingMade2, allRuns, PRICE_NEXT, toAgree, materials;
42888
+ var errorsIn2, PICTURE_EXT, givenAnchor, characterOf, budgeted, payingPending, LOOK_AGAIN_MS, waitLimitMs, PENDING_NEXT, beingMade2, allRuns, PRICE_NEXT, specOf2, toAgree, materials;
42616
42889
  var init_materials2 = __esm({
42617
42890
  "src/video/commands/materials.ts"() {
42618
42891
  "use strict";
@@ -42656,9 +42929,9 @@ var init_materials2 = __esm({
42656
42929
  }
42657
42930
  };
42658
42931
  budgeted = (generator, wallet, approve) => ({
42659
- make: async (kind, request, out2, env) => {
42932
+ make: async (kind, request, out2, env2) => {
42660
42933
  const made = await generator.make(kind, request, out2, {
42661
- ...env,
42934
+ ...env2,
42662
42935
  ...wallet ? { POPOST_GEN_MAX_CREDITS: String(wallet.left) } : {},
42663
42936
  ...approve.length ? { POPOST_GEN_APPROVE: approve.join(",") } : {}
42664
42937
  });
@@ -42667,7 +42940,7 @@ var init_materials2 = __esm({
42667
42940
  }
42668
42941
  });
42669
42942
  payingPending = (generator, wallet) => ({
42670
- make: (kind, request, out2, env) => generator.make(kind, request, out2, env).catch((e) => {
42943
+ make: (kind, request, out2, env2) => generator.make(kind, request, out2, env2).catch((e) => {
42671
42944
  if (e instanceof StillMaking) wallet?.pay(e.pending.chargedCredits ?? 0);
42672
42945
  throw e;
42673
42946
  })
@@ -42697,13 +42970,19 @@ var init_materials2 = __esm({
42697
42970
  }
42698
42971
  return { ...r, chargedCredits: charged, materials: r.materials.map((m) => made.has(m.file) && !m.made && !m.error ? { ...m, made: true } : m) };
42699
42972
  };
42700
- PRICE_NEXT = "Nothing was charged for these files. When the credits fit what is left of the budget the user agreed to for this video, run the same command again with --confirm --max-credits <what is left>; otherwise show the user the credits (and the balance) and run it so once they agree.";
42973
+ PRICE_NEXT = "Nothing was charged for these files. When the credits fit what is left of the budget the user agreed to for this video, run the same command again with --confirm --max-credits <what is left>; otherwise show the user the model, resolution, seconds, aspect ratio and credits of every item (and the balance) and run it so once they agree.";
42974
+ specOf2 = (c) => ({
42975
+ ...c?.model ? { model: c.model } : {},
42976
+ ...c?.resolution ? { resolution: c.resolution } : {},
42977
+ ...c?.seconds !== void 0 ? { seconds: c.seconds } : {},
42978
+ ...c?.aspectRatio ? { aspectRatio: c.aspectRatio } : {}
42979
+ });
42701
42980
  toAgree = (materials2, clipMusic = []) => {
42702
42981
  const asked2 = materials2.filter((m) => m.confirm);
42703
42982
  if (!asked2.length) return void 0;
42704
42983
  const sum = (list7) => list7.reduce((n, m) => n + (m.confirm?.credits ?? 0), 0);
42705
42984
  const balance = asked2.map((m) => m.confirm?.balance).find((b) => typeof b === "number");
42706
- const items = asked2.map((m) => ({ kind: m.kind, what: m.file, credits: m.confirm?.credits ?? 0, ...m.confirm?.seconds !== void 0 ? { seconds: m.confirm.seconds } : {} }));
42985
+ const items = asked2.map((m) => ({ kind: m.kind, what: m.file, credits: m.confirm?.credits ?? 0, ...specOf2(m.confirm) }));
42707
42986
  const unplanned = asked2.filter((m) => m.confirm?.reason === "unplanned");
42708
42987
  const clips = unplanned.map((m) => ({ ...m.confirm?.clip, credits: m.confirm?.credits ?? 0 }));
42709
42988
  const music = clipMusic.length ? { clipMusic } : {};
@@ -43666,8 +43945,8 @@ var init_loop2 = __esm({
43666
43945
  const prompt = { card: card2, slots: pkg.slots, brief: brief3, materials: materials2, ...language ? { language } : {}, ...generate2 ? { generate: { product: product !== void 0 } } : {}, ...shotNotes ? { shotNotes } : {}, ...budgets ? { budgets: budgets.max } : {} };
43667
43946
  const fillCommand = "popost video template fill " + dir + " --fill <fill.json> --out <project-dir>" + (assetsDir ? " --assets " + assetsDir : "");
43668
43947
  if (args.flag("dry")) {
43669
- const own2 = { ...prompt, ...voice ? { voice: { name: voice, ...speed ? { speed } : {} } } : {} };
43670
- const messages = planMessages(own2);
43948
+ const own3 = { ...prompt, ...voice ? { voice: { name: voice, ...speed ? { speed } : {} } } : {} };
43949
+ const messages = planMessages(own3);
43671
43950
  const lines = pkg.slots.captions?.lines ?? [];
43672
43951
  printJson(rt, {
43673
43952
  ok: true,
@@ -43678,7 +43957,7 @@ var init_loop2 = __esm({
43678
43957
  answer: { shots: pkg.slots.shots.length, captions: lines.length, ...voice ? { voice } : {}, ...voice && speed ? { speed } : {} },
43679
43958
  slots: pkg.slots,
43680
43959
  ...budgets ? { budgets: { pace: budgets.pace, ...budgets.tempo ? { tempo: budgets.tempo } : {}, slack: BUDGET_SLACK, lines: budgets.max.map((max, i) => ({ at: "captions[" + i + "]", seconds: lines[i]?.seconds, max })) } } : {},
43681
- rules: planRules(own2),
43960
+ rules: planRules(own3),
43682
43961
  forms: shotForms(generate2 !== void 0),
43683
43962
  materials: materials2,
43684
43963
  ...shotNotes ? { shotNotes: shotNotes.map((note, k) => ({ at: "shots[" + k + "]", note })) } : {},
@@ -44127,8 +44406,8 @@ var init_hosted3 = __esm({
44127
44406
  lengthOf = async (rt, o, known2) => {
44128
44407
  const had = known2 ?? await audioSeconds(rt, o.out).catch(() => void 0);
44129
44408
  if (had === void 0) return { seconds: null };
44130
- const seconds7 = round22(had), missing2 = round22((o.fit ?? o.seconds) - had);
44131
- return { seconds: seconds7, ...missing2 > SHORT_TOLERANCE ? { short: { seconds: seconds7, missing: missing2 } } : {} };
44409
+ const seconds7 = round22(had), missing3 = round22((o.fit ?? o.seconds) - had);
44410
+ return { seconds: seconds7, ...missing3 > SHORT_TOLERANCE ? { short: { seconds: seconds7, missing: missing3 } } : {} };
44132
44411
  };
44133
44412
  written = async (rt, o, receipt, job) => {
44134
44413
  if (job.state !== "ready" || !job.audioUrl) throw new ToolError("The popost.ai music is " + (job.state || "not ready") + "; run the same command again.");
@@ -44213,7 +44492,7 @@ var init_media = __esm({
44213
44492
  const account = connected(rt);
44214
44493
  const tools2 = { ...named, transcribe: named.transcribe ?? (account ? HOSTED : null), speak: named.speak ?? (account ? HOSTED : null), music: musicEnabled(rt) ? HOSTED : null };
44215
44494
  const offers = account ? { hosted: HOSTED_NOTE } : { connect: CONNECT };
44216
- const missing2 = [
44495
+ const missing3 = [
44217
44496
  ...rt.programs ? [] : ["this host cannot run local programs, so no video command works here"],
44218
44497
  ...rt.programs && version === null ? ['ffmpeg was not found: install it or set POPOST_FFMPEG (asked for "' + ffmpegPath(rt) + '")'] : [],
44219
44498
  ...browser === true ? [] : [browser]
@@ -44221,8 +44500,8 @@ var init_media = __esm({
44221
44500
  const budget = rt.programs ? cpuBudgetOf(rt) : void 0;
44222
44501
  const cpus = budget ? { budget: budget.cpus, from: budget.source } : null;
44223
44502
  const reading = named.readText !== null || named.transcribe !== null;
44224
- printJson(rt, { ok: missing2.length === 0, ffmpeg: version, browser: browser === true, cpus, tools: tools2, ...offers, ...reading ? { note: FIRST_RUN } : {}, ...missing2.length ? { missing: missing2 } : {} });
44225
- return missing2.length ? 2 : 0;
44503
+ printJson(rt, { ok: missing3.length === 0, ffmpeg: version, browser: browser === true, cpus, tools: tools2, ...offers, ...reading ? { note: FIRST_RUN } : {}, ...missing3.length ? { missing: missing3 } : {} });
44504
+ return missing3.length ? 2 : 0;
44226
44505
  }
44227
44506
  );
44228
44507
  soundOnly = async (rt, file, e) => {
@@ -44482,9 +44761,9 @@ var init_music_plan = __esm({
44482
44761
  if (args.string("music") !== void 0) return record(rt, args, project, kept2, reading);
44483
44762
  if (args.string("silent-end") !== void 0 || args.string("breaks") !== void 0) return amend(rt, args, project, kept2, reading);
44484
44763
  if (kept2) return answer2(rt, project, kept2, {}, void 0, reading);
44485
- const own2 = await ownFile(rt, project);
44486
- const offer = !own2 && reading?.facts.music === "yes" && !keepable(reading) ? await musicOffer(rt, musicSeconds(await lengthOf2(rt, project, reading))) : void 0;
44487
- const proposed = proposal({ ...reading ? { reading } : {}, ownFile: own2, ...offer ? { offer } : {} });
44764
+ const own3 = await ownFile(rt, project);
44765
+ const offer = !own3 && reading?.facts.music === "yes" && !keepable(reading) ? await musicOffer(rt, musicSeconds(await lengthOf2(rt, project, reading))) : void 0;
44766
+ const proposed = proposal({ ...reading ? { reading } : {}, ownFile: own3, ...offer ? { offer } : {} });
44488
44767
  const said = (proposed.music === "generated" || proposed.music === "own") && reading ? breaksSays(reading.facts.musicBreaks ?? [], reading.facts.dipsUnderSpeech) : void 0;
44489
44768
  const breaks = said ? [said] : [];
44490
44769
  printJson(rt, {
@@ -44502,7 +44781,7 @@ var init_music_plan = __esm({
44502
44781
  });
44503
44782
 
44504
44783
  // src/video/commands/music.ts
44505
- var REJECTED_FIX, videoSeconds, secondsOf2, lengthArgs, lengthNote, tooLong, LENGTH_OPTIONS, quote14, refused4, lengthLine, overLimit, make, own, musicCommands;
44784
+ var REJECTED_FIX, videoSeconds, secondsOf2, lengthArgs, lengthNote, tooLong, LENGTH_OPTIONS, quote14, refused4, lengthLine, overLimit, make, own2, musicCommands;
44506
44785
  var init_music = __esm({
44507
44786
  "src/video/commands/music.ts"() {
44508
44787
  "use strict";
@@ -44571,8 +44850,8 @@ var init_music = __esm({
44571
44850
  lengthLine = (made, file, of) => {
44572
44851
  if (made.seconds === null) return "The length of " + file + " could not be read here (ffmpeg): check it against the video's " + of.toFixed(2) + " s before the music is placed.\n";
44573
44852
  if (!made.short) return void 0;
44574
- const { seconds: seconds7, missing: missing2 } = made.short;
44575
- return "The music is " + seconds7.toFixed(2) + " s long, " + missing2.toFixed(2) + " s shorter than the " + of.toFixed(2) + " s it is for: the last " + missing2.toFixed(2) + " s of the video would have no music. Order a longer track (this command with --seconds " + musicSeconds(of + missing2 + MARGIN_SECONDS) + " is a new order, priced and agreed anew; the music is faded out at the end of the video), or end the video with the music (shorten its last scene by " + missing2.toFixed(2) + " s).\n";
44853
+ const { seconds: seconds7, missing: missing3 } = made.short;
44854
+ return "The music is " + seconds7.toFixed(2) + " s long, " + missing3.toFixed(2) + " s shorter than the " + of.toFixed(2) + " s it is for: the last " + missing3.toFixed(2) + " s of the video would have no music. Order a longer track (this command with --seconds " + musicSeconds(of + missing3 + MARGIN_SECONDS) + " is a new order, priced and agreed anew; the music is faded out at the end of the video), or end the video with the music (shorten its last scene by " + missing3.toFixed(2) + " s).\n";
44576
44855
  };
44577
44856
  overLimit = (e, items, max) => {
44578
44857
  if (!(e instanceof PopostApiError && e.code === "CREDIT_LIMIT_EXCEEDED")) throw e;
@@ -44643,7 +44922,7 @@ var init_music = __esm({
44643
44922
  },
44644
44923
  (args) => args.string("project")
44645
44924
  );
44646
- own = command(
44925
+ own2 = command(
44647
44926
  `take a sound file the user gave into the project as the video's "sound", with the record that says so (<out>.sound.json): the only sound a fill takes besides generated music. Never a file put together with other tools, a narration, or the sound of the reference or of another video`,
44648
44927
  {
44649
44928
  options: [
@@ -44661,7 +44940,7 @@ var init_music = __esm({
44661
44940
  printJson(rt, { ok: true, file: args.req("out"), receipt: args.req("out") + ".sound.json", given: receipt.given, next: 'Write the file into the fill as "sound" (its path from the project directory) and run template fill again with the options it had.' });
44662
44941
  }
44663
44942
  );
44664
- musicCommands = { quote: quote14, make, plan: musicPlan, own };
44943
+ musicCommands = { quote: quote14, make, plan: musicPlan, own: own2 };
44665
44944
  }
44666
44945
  });
44667
44946
 
@@ -45206,7 +45485,7 @@ var init_sfx = __esm({
45206
45485
  });
45207
45486
 
45208
45487
  // src/video/sound/analysis.ts
45209
- var MAX_ANALYSIS_SECONDS, MAX_ANALYSIS_BYTES, POLL_MS5, WAIT_LIMIT_MS3, heardSound, measureFile, missing, firstLine, planAnalysis, untilDone3, runAnalysis;
45488
+ var MAX_ANALYSIS_SECONDS, MAX_ANALYSIS_BYTES, POLL_MS5, WAIT_LIMIT_MS3, heardSound, measureFile, missing2, firstLine, planAnalysis, untilDone3, runAnalysis;
45210
45489
  var init_analysis = __esm({
45211
45490
  "src/video/sound/analysis.ts"() {
45212
45491
  "use strict";
@@ -45237,7 +45516,7 @@ var init_analysis = __esm({
45237
45516
  const m = measureSound(pcm, 22050, picture3);
45238
45517
  return loudness === void 0 ? m : { ...m, loudness };
45239
45518
  };
45240
- missing = (e) => e instanceof PopostApiError && (e.status === 404 || e.code === "NOT_FOUND");
45519
+ missing2 = (e) => e instanceof PopostApiError && (e.status === 404 || e.code === "NOT_FOUND");
45241
45520
  firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0] ?? "failed";
45242
45521
  planAnalysis = async (rt, sound2, o = {}) => {
45243
45522
  if (!sound2) return { kind: "none", record: { status: "silent" } };
@@ -45250,7 +45529,7 @@ var init_analysis = __esm({
45250
45529
  const credits = await quoteSoundAnalysis(rt, sound2.seconds);
45251
45530
  return { kind: "run", credits, item: { kind: "sound-analysis", what: o.what ?? "the sound of the reference (music, ambience, effects)", credits, seconds: sound2.seconds } };
45252
45531
  } catch (e) {
45253
- if (missing(e)) return { kind: "none", record: { status: "unavailable" } };
45532
+ if (missing2(e)) return { kind: "none", record: { status: "unavailable" } };
45254
45533
  if (e instanceof PopostApiError) return { kind: "none", record: { status: "failed", why: "its price could not be read: " + firstLine(e) } };
45255
45534
  throw e;
45256
45535
  }
@@ -45283,7 +45562,7 @@ var init_analysis = __esm({
45283
45562
  if (done2.state !== "ready" || !done2.result) return { status: "failed", id: done2.id, chargedCredits: 0, why: done2.failure ?? "the analysis ended " + (done2.state || "without a result") };
45284
45563
  return { status: "done", id: done2.id, chargedCredits: charged, result: done2.result };
45285
45564
  } catch (e) {
45286
- if (missing(e)) return { status: "unavailable" };
45565
+ if (missing2(e)) return { status: "unavailable" };
45287
45566
  if (e instanceof AmbiguousSubmitError || e instanceof ToolError || e instanceof PopostApiError) return { status: "failed", why: firstLine(e) };
45288
45567
  throw e;
45289
45568
  }
@@ -46733,11 +47012,11 @@ var init_review2 = __esm({
46733
47012
  const seconds7 = Math.round(v.frames / v.fps * 1e3) / 1e3;
46734
47013
  const audio = rebind(old?.audio, [{ kind: "observed", detail: "The sound of the final video, all " + seconds7 + " s: its voices, music and effects against the reference.", file: v.file, sha256: v.fingerprint, media: "video", at: [0, seconds7] }], v, old?.artifactFingerprint, changed2);
46735
47014
  const visual = rebind(old?.visual, o.visual.map((f) => frameEvidence(v, f, "its medium, finish and layout against the reference.")), v, old?.artifactFingerprint, changed2);
46736
- const missing2 = [];
47015
+ const missing3 = [];
46737
47016
  const events = c.events.map((e) => {
46738
47017
  const planned = o.plan?.events.find((p) => p.id === e.id);
46739
47018
  const frames = o.events[e.id] ?? (planned ? spanFrames2(planned.span, v.frames) : void 0);
46740
- if (!frames) missing2.push(e.id);
47019
+ if (!frames) missing3.push(e.id);
46741
47020
  const names = ["lead-in", "middle", "resolved state"];
46742
47021
  const bound = (frames ?? []).map((f, k, all) => frameEvidence(v, f, (all.length === 3 ? names[k] : "a state") + ' of "' + short(e.description) + '" (' + e.id + ")."));
46743
47022
  return { id: e.id, ...rebind(old?.events?.find((x) => x.id === e.id), bound, v, old?.artifactFingerprint, changed2), frames: frames ?? [] };
@@ -46753,7 +47032,7 @@ var init_review2 = __esm({
46753
47032
  events: events.map(({ frames: _frames, ...finding }) => finding),
46754
47033
  ...old?.audioUses ? { audioUses: old.audioUses } : o.audioUses ? { audioUses: o.audioUses } : {}
46755
47034
  };
46756
- return { review: review3, changed: changed2, missing: missing2, frames: [{ name: "audio", frames: [] }, { name: "visual", frames: o.visual }, ...events.map((e) => ({ name: e.id, frames: e.frames }))] };
47035
+ return { review: review3, changed: changed2, missing: missing3, frames: [{ name: "audio", frames: [] }, { name: "visual", frames: o.visual }, ...events.map((e) => ({ name: e.id, frames: e.frames }))] };
46757
47036
  };
46758
47037
  withVerdicts = (r, passed, failed4) => {
46759
47038
  const names = /* @__PURE__ */ new Set(["audio", "visual", ...(r.events ?? []).map((e) => e.id)]);