pixelkiln 0.131.0 → 0.133.0

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/cli.js CHANGED
@@ -5255,8 +5255,8 @@ function skeletonBones(set) {
5255
5255
  if (!set.rig) return SKELETON_BONES;
5256
5256
  return set.rig.flatMap((joint) => joint.parent ? [[joint.parent, joint.name]] : []);
5257
5257
  }
5258
- function parseSkeletonSet(json, file) {
5259
- const result = SkeletonSetSchema.safeParse(json);
5258
+ function parseSkeletonSet(json2, file) {
5259
+ const result = SkeletonSetSchema.safeParse(json2);
5260
5260
  if (!result.success) {
5261
5261
  const issues = result.error.issues.slice(0, 4).map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`).join("; ");
5262
5262
  throw new Error(`revision keypoints file ${file} does not match the expected shape: ${issues}`);
@@ -5295,8 +5295,8 @@ var AnchorsFileSchema = z3.object({
5295
5295
  version: z3.literal(1),
5296
5296
  frames: z3.record(z3.string().min(1), z3.record(z3.string().min(1), AnchorFrameSchema))
5297
5297
  }).strict();
5298
- function parseAnchorsFile(json, label) {
5299
- const parsed = AnchorsFileSchema.safeParse(json);
5298
+ function parseAnchorsFile(json2, label) {
5299
+ const parsed = AnchorsFileSchema.safeParse(json2);
5300
5300
  if (!parsed.success) {
5301
5301
  const issue = parsed.error.issues[0];
5302
5302
  throw new Error(`${label} is not an anchors file: ${issue.path.join(".") || "(root)"}: ${issue.message}`);
@@ -11008,9 +11008,9 @@ ${text.slice(0, 600)}`);
11008
11008
  function parseVfxRecipe(text) {
11009
11009
  const lines = text.split(/\r?\n/);
11010
11010
  const at2 = lines.findIndex((line) => line.trim() === "working recipe:");
11011
- const json = at2 >= 0 ? lines[at2 + 1]?.trim() : void 0;
11012
- if (!json?.startsWith("{")) return null;
11013
- return JSON.parse(json);
11011
+ const json2 = at2 >= 0 ? lines[at2 + 1]?.trim() : void 0;
11012
+ if (!json2?.startsWith("{")) return null;
11013
+ return JSON.parse(json2);
11014
11014
  }
11015
11015
  function parseVfxExport(text) {
11016
11016
  const effectId = new RegExp(`effect id (${UUID})`).exec(text)?.[1];
@@ -11812,13 +11812,13 @@ function heldFrames(spec, lock) {
11812
11812
  return frames;
11813
11813
  }
11814
11814
  async function readAnchorsFile(file) {
11815
- let json;
11815
+ let json2;
11816
11816
  try {
11817
- json = JSON.parse(await readFile9(file, "utf8"));
11817
+ json2 = JSON.parse(await readFile9(file, "utf8"));
11818
11818
  } catch (error) {
11819
11819
  throw new Error(`${file} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
11820
11820
  }
11821
- return parseAnchorsFile(json, file);
11821
+ return parseAnchorsFile(json2, file);
11822
11822
  }
11823
11823
  async function placeHeldFrames(spec, frames) {
11824
11824
  const layer = spec.character.layer;
@@ -17690,13 +17690,13 @@ async function optionalRevisionImage(file, label, requiredFormat) {
17690
17690
  async function optionalSkeletonSet(file) {
17691
17691
  if (!existsSync14(file)) return null;
17692
17692
  const bytes = await readFile10(file);
17693
- let json;
17693
+ let json2;
17694
17694
  try {
17695
- json = JSON.parse(bytes.toString("utf8"));
17695
+ json2 = JSON.parse(bytes.toString("utf8"));
17696
17696
  } catch (error) {
17697
17697
  throw new Error(`revision keypoints file ${file} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
17698
17698
  }
17699
- return { hash: sha256(bytes), skeleton: parseSkeletonSet(json, file) };
17699
+ return { hash: sha256(bytes), skeleton: parseSkeletonSet(json2, file) };
17700
17700
  }
17701
17701
  async function revisionSourceMembers(stem2, label) {
17702
17702
  if (existsSync14(stem2)) return null;
@@ -19634,6 +19634,32 @@ function defaultOpenCommand(platform = process.platform) {
19634
19634
  }
19635
19635
 
19636
19636
  // src/pick/review-server.ts
19637
+ async function readJsonBody(req, res) {
19638
+ const expectedOrigin = req.headers.host ? `http://${req.headers.host}` : null;
19639
+ if (req.headers.origin && req.headers.origin !== expectedOrigin) {
19640
+ res.writeHead(403, { "Content-Type": "text/plain" });
19641
+ res.end("cross-origin review submissions are not allowed");
19642
+ return { ok: false };
19643
+ }
19644
+ if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) {
19645
+ res.writeHead(415, { "Content-Type": "text/plain" });
19646
+ res.end("application/json is required");
19647
+ return { ok: false };
19648
+ }
19649
+ const chunks = [];
19650
+ let bytes = 0;
19651
+ for await (const c of req) {
19652
+ const chunk2 = c;
19653
+ bytes += chunk2.length;
19654
+ if (bytes > 64 * 1024) {
19655
+ res.writeHead(413, { "Content-Type": "text/plain" });
19656
+ res.end("review submission is too large");
19657
+ return { ok: false };
19658
+ }
19659
+ chunks.push(chunk2);
19660
+ }
19661
+ return { ok: true, body: JSON.parse(Buffer.concat(chunks).toString("utf8")) };
19662
+ }
19637
19663
  function serveReviewPage(opts) {
19638
19664
  const log2 = opts.onProgress ?? (() => {
19639
19665
  });
@@ -19645,7 +19671,9 @@ function serveReviewPage(opts) {
19645
19671
  const bytes = await readFile18(asset.path);
19646
19672
  res.writeHead(200, {
19647
19673
  "Content-Type": asset.contentType,
19648
- "Cache-Control": "no-store",
19674
+ // A frame route names one cached candidate for the life of this
19675
+ // server, so the browser may keep it; everything else is re-read.
19676
+ "Cache-Control": req.url.includes("/review-frame/") ? "private, max-age=86400, immutable" : "no-store",
19649
19677
  "X-Content-Type-Options": "nosniff"
19650
19678
  });
19651
19679
  res.end(bytes);
@@ -19657,39 +19685,38 @@ function serveReviewPage(opts) {
19657
19685
  }
19658
19686
  if (req.method === "GET" && (req.url === "/" || req.url?.startsWith("/?"))) {
19659
19687
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
19660
- res.end(opts.html);
19688
+ res.end(typeof opts.html === "function" ? opts.html() : opts.html);
19661
19689
  return;
19662
19690
  }
19663
- if (req.method === "POST" && req.url === "/apply") {
19664
- const expectedOrigin = req.headers.host ? `http://${req.headers.host}` : null;
19665
- if (req.headers.origin && req.headers.origin !== expectedOrigin) {
19666
- res.writeHead(403, { "Content-Type": "text/plain" });
19667
- res.end("cross-origin review submissions are not allowed");
19668
- return;
19669
- }
19670
- if (!req.headers["content-type"]?.toLowerCase().startsWith("application/json")) {
19671
- res.writeHead(415, { "Content-Type": "text/plain" });
19672
- res.end("application/json is required");
19691
+ if (opts.handleRequest && req.url && req.url !== "/apply" && (req.method === "GET" || req.method === "POST")) {
19692
+ try {
19693
+ let body = void 0;
19694
+ if (req.method === "POST") {
19695
+ const parsed = await readJsonBody(req, res);
19696
+ if (!parsed.ok) return;
19697
+ body = parsed.body;
19698
+ }
19699
+ const handled = await opts.handleRequest(req.method, req.url, body);
19700
+ if (handled) {
19701
+ res.writeHead(handled.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
19702
+ res.end(JSON.stringify(handled.body));
19703
+ return;
19704
+ }
19705
+ } catch (err) {
19706
+ res.writeHead(400, { "Content-Type": "text/plain" });
19707
+ res.end(err instanceof Error ? err.message : String(err));
19673
19708
  return;
19674
19709
  }
19710
+ }
19711
+ if (req.method === "POST" && req.url === "/apply") {
19675
19712
  try {
19676
- const chunks = [];
19677
- let bytes = 0;
19678
- for await (const c of req) {
19679
- const chunk2 = c;
19680
- bytes += chunk2.length;
19681
- if (bytes > 64 * 1024) {
19682
- res.writeHead(413, { "Content-Type": "text/plain" });
19683
- res.end("review submission is too large");
19684
- return;
19685
- }
19686
- chunks.push(chunk2);
19687
- }
19688
- const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
19689
- const result = await opts.handleApply(body);
19713
+ const parsed = await readJsonBody(req, res);
19714
+ if (!parsed.ok) return;
19715
+ const result = await opts.handleApply(parsed.body);
19690
19716
  res.writeHead(200, { "Content-Type": "application/json" });
19691
19717
  res.end(JSON.stringify(result));
19692
19718
  server.close(() => resolve(result));
19719
+ res.on("finish", () => server.closeIdleConnections?.());
19693
19720
  } catch (err) {
19694
19721
  const message6 = err instanceof Error ? err.message : String(err);
19695
19722
  log2(` apply failed: ${message6}`);
@@ -21398,7 +21425,7 @@ function parseGlb(bytes) {
21398
21425
  const total = view.getUint32(8, true);
21399
21426
  if (total > bytes.length) throw new Error(`invalid glb: header says ${total} bytes, the file has ${bytes.length}`);
21400
21427
  let offset = 12;
21401
- let json = null;
21428
+ let json2 = null;
21402
21429
  let bin = null;
21403
21430
  const extraChunks = [];
21404
21431
  while (offset + 8 <= total) {
@@ -21407,7 +21434,7 @@ function parseGlb(bytes) {
21407
21434
  const start = offset + 8;
21408
21435
  if (start + length > total) throw new Error("invalid glb: a chunk runs past the end of the file");
21409
21436
  const data = bytes.subarray(start, start + length);
21410
- if (type === CHUNK_JSON && !json) {
21437
+ if (type === CHUNK_JSON && !json2) {
21411
21438
  let parsed;
21412
21439
  try {
21413
21440
  parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(data));
@@ -21415,7 +21442,7 @@ function parseGlb(bytes) {
21415
21442
  throw new Error(`invalid glb: the JSON chunk does not parse (${error instanceof Error ? error.message : String(error)})`);
21416
21443
  }
21417
21444
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("invalid glb: the JSON chunk is not an object");
21418
- json = parsed;
21445
+ json2 = parsed;
21419
21446
  } else if (type === CHUNK_BIN && !bin) {
21420
21447
  bin = data;
21421
21448
  } else {
@@ -21423,15 +21450,15 @@ function parseGlb(bytes) {
21423
21450
  }
21424
21451
  offset = start + pad4(length);
21425
21452
  }
21426
- if (!json) throw new Error("invalid glb: no JSON chunk");
21427
- if (!json.asset || typeof json.asset.version !== "string") throw new Error("invalid glb: the JSON has no asset.version");
21428
- const declared = json.buffers?.[0]?.byteLength;
21453
+ if (!json2) throw new Error("invalid glb: no JSON chunk");
21454
+ if (!json2.asset || typeof json2.asset.version !== "string") throw new Error("invalid glb: the JSON has no asset.version");
21455
+ const declared = json2.buffers?.[0]?.byteLength;
21429
21456
  if (bin && typeof declared === "number") {
21430
21457
  if (declared > bin.length) throw new Error(`invalid glb: buffer 0 declares ${declared} bytes, the BIN chunk has ${bin.length}`);
21431
21458
  bin = bin.subarray(0, declared);
21432
21459
  }
21433
- const document = { json, bin: bin ?? new Uint8Array(0), extraChunks };
21434
- for (const [index, bufferView] of (json.bufferViews ?? []).entries()) {
21460
+ const document = { json: json2, bin: bin ?? new Uint8Array(0), extraChunks };
21461
+ for (const [index, bufferView] of (json2.bufferViews ?? []).entries()) {
21435
21462
  if (bufferView.buffer !== 0) continue;
21436
21463
  const start = bufferView.byteOffset ?? 0;
21437
21464
  if (start < 0 || bufferView.byteLength < 0 || start + bufferView.byteLength > document.bin.length) {
@@ -21441,8 +21468,8 @@ function parseGlb(bytes) {
21441
21468
  return document;
21442
21469
  }
21443
21470
  function serializeGlb(document) {
21444
- const json = new TextEncoder().encode(JSON.stringify(document.json));
21445
- const jsonLength = pad4(json.length);
21471
+ const json2 = new TextEncoder().encode(JSON.stringify(document.json));
21472
+ const jsonLength = pad4(json2.length);
21446
21473
  const hasBin = document.bin.length > 0;
21447
21474
  const binLength = pad4(document.bin.length);
21448
21475
  const extra = document.extraChunks.reduce((sum, chunk2) => sum + 8 + pad4(chunk2.data.length), 0);
@@ -21455,8 +21482,8 @@ function serializeGlb(document) {
21455
21482
  let offset = 12;
21456
21483
  view.setUint32(offset, jsonLength, true);
21457
21484
  view.setUint32(offset + 4, CHUNK_JSON, true);
21458
- out.set(json, offset + 8);
21459
- out.fill(32, offset + 8 + json.length, offset + 8 + jsonLength);
21485
+ out.set(json2, offset + 8);
21486
+ out.fill(32, offset + 8 + json2.length, offset + 8 + jsonLength);
21460
21487
  offset += 8 + jsonLength;
21461
21488
  if (hasBin) {
21462
21489
  view.setUint32(offset, binLength, true);
@@ -21517,9 +21544,9 @@ function replaceGlbImage(document, imageIndex, bytes, mimeType) {
21517
21544
  const source = document.json;
21518
21545
  const image = source.images?.[imageIndex];
21519
21546
  if (!image) throw new Error(`the model has no image ${imageIndex}`);
21520
- const json = structuredCloneJson(source);
21521
- const views = json.bufferViews ??= [];
21522
- const target = json.images[imageIndex];
21547
+ const json2 = structuredCloneJson(source);
21548
+ const views = json2.bufferViews ??= [];
21549
+ const target = json2.images[imageIndex];
21523
21550
  const viewIndex = typeof image.bufferView === "number" ? image.bufferView : -1;
21524
21551
  const old = viewIndex >= 0 ? source.bufferViews?.[viewIndex] : void 0;
21525
21552
  const usedElsewhere = viewIndex >= 0 && ((source.images ?? []).some((other, index) => index !== imageIndex && other.bufferView === viewIndex) || (source.accessors ?? []).some((accessor) => accessor.bufferView === viewIndex));
@@ -21560,9 +21587,9 @@ function replaceGlbImage(document, imageIndex, bytes, mimeType) {
21560
21587
  }
21561
21588
  }
21562
21589
  target.mimeType = mimeType;
21563
- json.buffers = json.buffers?.length ? json.buffers : [{ byteLength: 0 }];
21564
- json.buffers[0] = { ...json.buffers[0], byteLength: bin.length };
21565
- return { json, bin, extraChunks: document.extraChunks };
21590
+ json2.buffers = json2.buffers?.length ? json2.buffers : [{ byteLength: 0 }];
21591
+ json2.buffers[0] = { ...json2.buffers[0], byteLength: bin.length };
21592
+ return { json: json2, bin, extraChunks: document.extraChunks };
21566
21593
  }
21567
21594
  function structuredCloneJson(value) {
21568
21595
  return JSON.parse(JSON.stringify(value));
@@ -21620,8 +21647,8 @@ function readAccessor(document, accessorIndex) {
21620
21647
  return { data: out, size, count: accessor.count };
21621
21648
  }
21622
21649
  function describeGlb(document) {
21623
- const json = document.json;
21624
- const images = (json.images ?? []).map((image, index) => {
21650
+ const json2 = document.json;
21651
+ const images = (json2.images ?? []).map((image, index) => {
21625
21652
  let info = null;
21626
21653
  let bytes = null;
21627
21654
  const embedded = typeof image.bufferView === "number";
@@ -21645,9 +21672,9 @@ function describeGlb(document) {
21645
21672
  meshes: []
21646
21673
  };
21647
21674
  });
21648
- const imageOfTexture = (info) => info && typeof info.index === "number" ? json.textures?.[info.index]?.source : void 0;
21675
+ const imageOfTexture = (info) => info && typeof info.index === "number" ? json2.textures?.[info.index]?.source : void 0;
21649
21676
  const meshesOfMaterial = /* @__PURE__ */ new Map();
21650
- for (const [meshIndex, mesh] of (json.meshes ?? []).entries()) {
21677
+ for (const [meshIndex, mesh] of (json2.meshes ?? []).entries()) {
21651
21678
  for (const primitive of mesh.primitives ?? []) {
21652
21679
  if (typeof primitive.material !== "number") continue;
21653
21680
  const names = meshesOfMaterial.get(primitive.material) ?? [];
@@ -21656,7 +21683,7 @@ function describeGlb(document) {
21656
21683
  meshesOfMaterial.set(primitive.material, names);
21657
21684
  }
21658
21685
  }
21659
- for (const [materialIndex, material] of (json.materials ?? []).entries()) {
21686
+ for (const [materialIndex, material] of (json2.materials ?? []).entries()) {
21660
21687
  const uses = [
21661
21688
  ["baseColor", material.pbrMetallicRoughness?.baseColorTexture],
21662
21689
  ["normal", material.normalTexture],
@@ -21676,39 +21703,39 @@ function describeGlb(document) {
21676
21703
  }
21677
21704
  }
21678
21705
  const bones = [];
21679
- for (const skin of json.skins ?? []) {
21706
+ for (const skin of json2.skins ?? []) {
21680
21707
  for (const joint of skin.joints ?? []) {
21681
- const name = json.nodes?.[joint]?.name ?? `node ${joint}`;
21708
+ const name = json2.nodes?.[joint]?.name ?? `node ${joint}`;
21682
21709
  if (!bones.includes(name)) bones.push(name);
21683
21710
  }
21684
21711
  }
21685
- const meshes = (json.meshes ?? []).map((mesh, index) => {
21712
+ const meshes = (json2.meshes ?? []).map((mesh, index) => {
21686
21713
  let vertices = 0;
21687
21714
  let triangles = 0;
21688
21715
  for (const primitive of mesh.primitives ?? []) {
21689
- const position = json.accessors?.[primitive.attributes?.POSITION ?? -1];
21716
+ const position = json2.accessors?.[primitive.attributes?.POSITION ?? -1];
21690
21717
  const count = position?.count ?? 0;
21691
21718
  vertices += count;
21692
21719
  if ((primitive.mode ?? 4) === 4) {
21693
- triangles += Math.floor((typeof primitive.indices === "number" ? json.accessors?.[primitive.indices]?.count ?? 0 : count) / 3);
21720
+ triangles += Math.floor((typeof primitive.indices === "number" ? json2.accessors?.[primitive.indices]?.count ?? 0 : count) / 3);
21694
21721
  }
21695
21722
  }
21696
21723
  return { name: mesh.name ?? `mesh ${index}`, primitives: mesh.primitives?.length ?? 0, vertices, triangles };
21697
21724
  });
21698
21725
  return {
21699
- generator: typeof json.asset.generator === "string" ? json.asset.generator : null,
21726
+ generator: typeof json2.asset.generator === "string" ? json2.asset.generator : null,
21700
21727
  meshes,
21701
21728
  bones,
21702
- animations: (json.animations ?? []).map((animation, index) => animation.name ?? `animation ${index}`),
21729
+ animations: (json2.animations ?? []).map((animation, index) => animation.name ?? `animation ${index}`),
21703
21730
  images,
21704
- items: modelItems(json)
21731
+ items: modelItems(json2)
21705
21732
  };
21706
21733
  }
21707
21734
  function isBodyNode(node) {
21708
21735
  return Array.isArray(node.extras?.hiddenBy) || node.extras?.body === true;
21709
21736
  }
21710
- function modelItems(json) {
21711
- const meshNodes = (json.nodes ?? []).filter((node) => typeof node.mesh === "number");
21737
+ function modelItems(json2) {
21738
+ const meshNodes = (json2.nodes ?? []).filter((node) => typeof node.mesh === "number");
21712
21739
  if (!meshNodes.some(isBodyNode)) return meshNodes.length > 1 ? meshNodes.map((node, index) => node.name ?? `part ${index + 1}`) : [];
21713
21740
  return meshNodes.filter((node) => !isBodyNode(node)).map((node, index) => node.name ?? `part ${index + 1}`);
21714
21741
  }
@@ -21729,9 +21756,9 @@ function regionName(name) {
21729
21756
  const phrase = [side, ...words].filter(Boolean).join(" ") || name.trim() || "piece";
21730
21757
  return phrase.charAt(0).toUpperCase() + phrase.slice(1);
21731
21758
  }
21732
- function primitivesUsingImage(json, imageIndex) {
21759
+ function primitivesUsingImage(json2, imageIndex) {
21733
21760
  const materials = /* @__PURE__ */ new Set();
21734
- for (const [index, material] of (json.materials ?? []).entries()) {
21761
+ for (const [index, material] of (json2.materials ?? []).entries()) {
21735
21762
  const infos = [
21736
21763
  material.pbrMetallicRoughness?.baseColorTexture,
21737
21764
  material.pbrMetallicRoughness?.metallicRoughnessTexture,
@@ -21739,10 +21766,10 @@ function primitivesUsingImage(json, imageIndex) {
21739
21766
  material.occlusionTexture,
21740
21767
  material.emissiveTexture
21741
21768
  ];
21742
- if (infos.some((info) => info && json.textures?.[info.index]?.source === imageIndex)) materials.add(index);
21769
+ if (infos.some((info) => info && json2.textures?.[info.index]?.source === imageIndex)) materials.add(index);
21743
21770
  }
21744
21771
  const found = [];
21745
- for (const [meshIndex, mesh] of (json.meshes ?? []).entries()) {
21772
+ for (const [meshIndex, mesh] of (json2.meshes ?? []).entries()) {
21746
21773
  for (const [primitiveIndex, primitive] of (mesh.primitives ?? []).entries()) {
21747
21774
  if (typeof primitive.material === "number" && materials.has(primitive.material) && (primitive.mode ?? 4) === 4) {
21748
21775
  found.push({ mesh: meshIndex, primitive: primitiveIndex });
@@ -21753,7 +21780,7 @@ function primitivesUsingImage(json, imageIndex) {
21753
21780
  }
21754
21781
  var WELD = 1 << 16;
21755
21782
  function uvGuide(document, imageIndex) {
21756
- const json = document.json;
21783
+ const json2 = document.json;
21757
21784
  const pointOf = /* @__PURE__ */ new Map();
21758
21785
  const us = [];
21759
21786
  const vs = [];
@@ -21769,8 +21796,8 @@ function uvGuide(document, imageIndex) {
21769
21796
  return root;
21770
21797
  };
21771
21798
  const triangles = [];
21772
- for (const { mesh: meshIndex, primitive: primitiveIndex } of primitivesUsingImage(json, imageIndex)) {
21773
- const mesh = json.meshes[meshIndex];
21799
+ for (const { mesh: meshIndex, primitive: primitiveIndex } of primitivesUsingImage(json2, imageIndex)) {
21800
+ const mesh = json2.meshes[meshIndex];
21774
21801
  const primitive = mesh.primitives[primitiveIndex];
21775
21802
  const meshName = mesh.name ?? `mesh ${meshIndex}`;
21776
21803
  if (typeof primitive.attributes.TEXCOORD_0 !== "number") continue;
@@ -21780,11 +21807,11 @@ function uvGuide(document, imageIndex) {
21780
21807
  const joints = typeof primitive.attributes.JOINTS_0 === "number" ? readAccessor(document, primitive.attributes.JOINTS_0) : null;
21781
21808
  const weights = typeof primitive.attributes.WEIGHTS_0 === "number" ? readAccessor(document, primitive.attributes.WEIGHTS_0) : null;
21782
21809
  const normals = typeof primitive.attributes.NORMAL === "number" ? readAccessor(document, primitive.attributes.NORMAL) : null;
21783
- const node = (json.nodes ?? []).find((candidate) => candidate.mesh === meshIndex);
21784
- const skinJoints = typeof node?.skin === "number" ? json.skins?.[node.skin]?.joints ?? null : null;
21810
+ const node = (json2.nodes ?? []).find((candidate) => candidate.mesh === meshIndex);
21811
+ const skinJoints = typeof node?.skin === "number" ? json2.skins?.[node.skin]?.joints ?? null : null;
21785
21812
  const boneName = (joint) => {
21786
21813
  const nodeIndex = skinJoints?.[joint];
21787
- return nodeIndex === void 0 ? null : json.nodes?.[nodeIndex]?.name ?? `bone ${joint}`;
21814
+ return nodeIndex === void 0 ? null : json2.nodes?.[nodeIndex]?.name ?? `bone ${joint}`;
21788
21815
  };
21789
21816
  const local = new Int32Array(uv.count);
21790
21817
  for (let vertex = 0; vertex < uv.count; vertex++) {
@@ -22846,14 +22873,14 @@ function poseNodes(document, pose) {
22846
22873
  return posed;
22847
22874
  }
22848
22875
  function restPrimitives(document, pose) {
22849
- const json = document.json;
22876
+ const json2 = document.json;
22850
22877
  const world = worldMatrices(document, pose ? poseNodes(document, pose) : void 0);
22851
22878
  const out = [];
22852
- for (const [nodeIndex, node] of (json.nodes ?? []).entries()) {
22879
+ for (const [nodeIndex, node] of (json2.nodes ?? []).entries()) {
22853
22880
  if (typeof node.mesh !== "number") continue;
22854
- const mesh = json.meshes?.[node.mesh];
22881
+ const mesh = json2.meshes?.[node.mesh];
22855
22882
  if (!mesh) continue;
22856
- const skin = typeof node.skin === "number" ? json.skins?.[node.skin] : void 0;
22883
+ const skin = typeof node.skin === "number" ? json2.skins?.[node.skin] : void 0;
22857
22884
  let jointMatrices = null;
22858
22885
  if (skin) {
22859
22886
  const inverse = typeof skin.inverseBindMatrices === "number" ? readAccessor(document, skin.inverseBindMatrices) : null;
@@ -25474,7 +25501,7 @@ var EDITOR_CSP = [
25474
25501
  "connect-src 'self'",
25475
25502
  "frame-ancestors 'self'"
25476
25503
  ].join("; ");
25477
- async function readJsonBody(req) {
25504
+ async function readJsonBody2(req) {
25478
25505
  const chunks = [];
25479
25506
  let bytes = 0;
25480
25507
  for await (const chunk2 of req) {
@@ -25512,7 +25539,7 @@ async function serveGallery(opts) {
25512
25539
  res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8" });
25513
25540
  res.end(message6);
25514
25541
  };
25515
- const json = (status, value) => {
25542
+ const json2 = (status, value) => {
25516
25543
  res.writeHead(status, {
25517
25544
  "Content-Type": "application/json; charset=utf-8",
25518
25545
  "Cache-Control": "no-store",
@@ -25534,7 +25561,7 @@ async function serveGallery(opts) {
25534
25561
  fail(415, "application/json is required");
25535
25562
  return void 0;
25536
25563
  }
25537
- return readJsonBody(req);
25564
+ return readJsonBody2(req);
25538
25565
  };
25539
25566
  const reportError = (what, err) => {
25540
25567
  const status = typeof err?.status === "number" ? err.status : 500;
@@ -25549,7 +25576,7 @@ async function serveGallery(opts) {
25549
25576
  if (body === void 0) return;
25550
25577
  const build = await opts.edit(body);
25551
25578
  media = build.media;
25552
- json(200, build.snapshot);
25579
+ json2(200, build.snapshot);
25553
25580
  } catch (err) {
25554
25581
  reportError("edit", err);
25555
25582
  }
@@ -25560,7 +25587,7 @@ async function serveGallery(opts) {
25560
25587
  try {
25561
25588
  const body = await guardedBody("generation requests");
25562
25589
  if (body === void 0) return;
25563
- json(202, await opts.generate.start(body));
25590
+ json2(202, await opts.generate.start(body));
25564
25591
  } catch (err) {
25565
25592
  reportError("generate", err);
25566
25593
  }
@@ -25571,7 +25598,7 @@ async function serveGallery(opts) {
25571
25598
  try {
25572
25599
  const body = await guardedBody("price requests");
25573
25600
  if (body === void 0) return;
25574
- json(200, await opts.price(body));
25601
+ json2(200, await opts.price(body));
25575
25602
  } catch (err) {
25576
25603
  reportError("price", err);
25577
25604
  }
@@ -25582,7 +25609,7 @@ async function serveGallery(opts) {
25582
25609
  try {
25583
25610
  const body = await guardedBody("skeleton estimates");
25584
25611
  if (body === void 0) return;
25585
- json(200, await opts.skeleton.estimate(body));
25612
+ json2(200, await opts.skeleton.estimate(body));
25586
25613
  } catch (err) {
25587
25614
  reportError("skeleton estimate", err);
25588
25615
  }
@@ -25593,7 +25620,7 @@ async function serveGallery(opts) {
25593
25620
  try {
25594
25621
  const body = await guardedBody("editor installs");
25595
25622
  if (body === void 0) return;
25596
- json(202, await opts.editor.install());
25623
+ json2(202, await opts.editor.install());
25597
25624
  } catch (err) {
25598
25625
  reportError("editor install", err);
25599
25626
  }
@@ -25608,7 +25635,7 @@ async function serveGallery(opts) {
25608
25635
  if (body === void 0) return;
25609
25636
  const result = await opts.generate.applyReview(jobId, body);
25610
25637
  reviewAssets.delete(jobId);
25611
- json(200, result);
25638
+ json2(200, result);
25612
25639
  } catch (err) {
25613
25640
  reportError("review", err);
25614
25641
  }
@@ -25660,16 +25687,16 @@ async function serveGallery(opts) {
25660
25687
  if (req.method !== "GET" && req.method !== "HEAD") return fail(405, "the gallery is read-only");
25661
25688
  if (url2.pathname === "/api/skeleton") {
25662
25689
  if (!opts.skeleton) return fail(404, "skeleton estimates need the gallery started with --edit");
25663
- return json(200, opts.skeleton.status());
25690
+ return json2(200, opts.skeleton.status());
25664
25691
  }
25665
25692
  if (url2.pathname === "/api/jobs") {
25666
25693
  if (!opts.generate) return fail(404, "generation is off");
25667
- return json(200, opts.generate.status());
25694
+ return json2(200, opts.generate.status());
25668
25695
  }
25669
25696
  if (url2.pathname === "/api/editor") {
25670
25697
  if (!opts.editor) return fail(404, "the in-browser editor is off for this gallery");
25671
25698
  try {
25672
- return json(200, await opts.editor.status());
25699
+ return json2(200, await opts.editor.status());
25673
25700
  } catch (err) {
25674
25701
  return reportError("editor status", err);
25675
25702
  }
@@ -25808,6 +25835,10 @@ var ReviewAssetSchema = z15.object({
25808
25835
  status: z15.enum(["pending", "applied"]),
25809
25836
  /** The chosen candidate index, or null while nothing is chosen. */
25810
25837
  chosen: z15.number().int().nonnegative().nullable(),
25838
+ /** Frames (or candidates) the reviewer flagged as bad on the pick page. */
25839
+ flagged: z15.array(z15.number().int().nonnegative()).optional(),
25840
+ /** Set aside on the pick page to decide later. */
25841
+ later: z15.boolean().optional(),
25811
25842
  updatedAt: z15.string()
25812
25843
  });
25813
25844
  var ReviewStateSchema = z15.object({
@@ -25917,6 +25948,8 @@ async function cacheReviewCandidates(provider, key3, jobId, job, opts) {
25917
25948
  candidates,
25918
25949
  status: "pending",
25919
25950
  chosen: previous?.chosen ?? null,
25951
+ ...previous?.flagged?.length ? { flagged: previous.flagged } : {},
25952
+ ...previous?.later ? { later: true } : {},
25920
25953
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
25921
25954
  };
25922
25955
  const latest = await loadReviewState(opts.statePath);
@@ -26541,418 +26574,921 @@ async function writeManifestFile(target, manifest) {
26541
26574
 
26542
26575
  // src/pick/sheet.ts
26543
26576
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
26544
- function renderSheet(groups, options = {}) {
26545
- const safe = groups.map((g) => ({
26577
+ function renderableGroups(groups) {
26578
+ return groups.map((g) => ({
26546
26579
  ...g,
26547
26580
  styleId: escapeHtml3(g.styleId),
26548
26581
  assetId: escapeHtml3(g.assetId),
26549
26582
  prompt: escapeHtml3(g.prompt),
26550
- ...g.revision ? {
26551
- revision: {
26552
- ...g.revision,
26553
- sourceAssetId: escapeHtml3(g.revision.sourceAssetId)
26554
- }
26555
- } : {}
26583
+ ...g.revision ? { revision: { ...g.revision, sourceAssetId: escapeHtml3(g.revision.sourceAssetId) } } : {}
26556
26584
  }));
26557
- const data = JSON.stringify(safe).replace(/<\//g, "<\\/");
26558
- const apply = JSON.stringify({
26559
- url: options.applyUrl ?? "/apply",
26585
+ }
26586
+ var json = (value) => JSON.stringify(value).replace(/<\//g, "<\\/");
26587
+ function renderSheet(groups, options = {}) {
26588
+ const config = {
26589
+ applyUrl: options.applyUrl ?? "/apply",
26560
26590
  headers: options.applyHeaders ?? {},
26561
- embedded: options.embedded === true
26562
- }).replace(/<\//g, "<\\/");
26591
+ embedded: options.embedded === true,
26592
+ sessionUrl: options.sessionUrl ?? null,
26593
+ stateUrl: options.stateUrl ?? null,
26594
+ rerollUrl: options.rerollUrl ?? null
26595
+ };
26563
26596
  return `<!doctype html>
26564
26597
  <html lang="en">
26565
26598
  <head>
26566
26599
  <meta charset="utf-8">
26567
26600
  <meta name="viewport" content="width=device-width, initial-scale=1">
26568
- <title>pick candidates | pixelkiln</title>
26601
+ <title>Review candidates | pixelkiln</title>
26569
26602
  <style>
26603
+ /*
26604
+ * True-black flat, warmed for a kiln: elevation by lightness alone
26605
+ * (ground, surface, raised), no borders on panels, no shadows at rest.
26606
+ * The ember is the one hue and lives only on data: an accepted asset, the
26607
+ * chosen frame. Flagged frames take the negative pair. Buttons are neutral;
26608
+ * the one primary (Apply) is an inverted white pill.
26609
+ */
26570
26610
  :root {
26571
- --bg: #17150f; --panel: #201d17; --panel-deep: #100f0c;
26572
- --line: rgba(243,234,214,.16); --line-strong: rgba(243,234,214,.3);
26573
- --text: #f3ead6; --dim: #9b9384; --accent: #ff6b35;
26574
- --accent-soft: #ff9c5f; --ok: #b9f27c; --warn: #ff9c5f;
26575
- --content: 1440px; --preview: 560px;
26576
- }
26577
- * { box-sizing: border-box; }
26578
- body { margin:0; background:var(--bg); color:var(--text);
26579
- font:14px/1.5 ui-sans-serif,-apple-system,"SF Pro Text",Inter,system-ui,sans-serif; }
26580
- header { position:sticky; top:0; z-index:10; background:var(--panel);
26581
- border-bottom:1px solid var(--line-strong); }
26582
- .bar { width:min(100%,var(--content)); margin:0 auto; padding:15px 22px;
26583
- display:flex; align-items:center; gap:16px; flex-wrap:wrap; }
26584
- h1 { font:700 14px/1 ui-monospace,SFMono-Regular,Menlo,monospace;
26585
- margin:0; letter-spacing:-.02em; }
26586
- h1::before { content:'\u25C6'; color:var(--accent); margin-right:9px; font-size:11px; }
26587
- .count { color:var(--dim); font-variant-numeric:tabular-nums; }
26588
- button { font:inherit; font-weight:600; border-radius:0; padding:9px 16px;
26589
- border:1px solid var(--line); background:transparent; color:var(--text); cursor:pointer; }
26590
- button.primary { background:var(--accent); border-color:var(--accent); color:var(--bg); }
26591
- button:disabled { opacity:.45; cursor:not-allowed; }
26592
- main, footer { width:min(100%,var(--content)); margin-inline:auto; }
26593
- main { border-inline:1px solid var(--line); }
26594
- .group { border-bottom:1px solid var(--line); padding:22px; overflow:hidden; }
26595
- .group.done { background:rgba(185,242,124,.035); }
26596
- .ghead { display:flex; align-items:baseline; gap:12px; margin-bottom:16px; flex-wrap:wrap; }
26597
- .style { font-size:10.5px; font-weight:650; text-transform:uppercase; letter-spacing:.03em;
26598
- color:var(--accent-soft); border:1px solid var(--accent); border-radius:0; padding:2px 6px; }
26599
- .aid { font-weight:650; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; }
26600
- .prompt { flex:1; min-width:280px; color:var(--dim); font-size:12.5px; max-width:80ch; }
26601
- .review { display:grid; grid-template-columns:minmax(180px,280px) minmax(0,1fr); gap:16px;
26602
- align-items:start; }
26603
- .review.no-context { display:block; }
26604
- .context { border:1px solid var(--line); padding:8px; background:var(--panel-deep);
26605
- min-width:0; display:grid; gap:12px; align-content:start; }
26606
- .context-label { display:flex; justify-content:space-between; gap:8px; margin-bottom:7px;
26607
- color:var(--dim); font-size:10.5px; font-variant-numeric:tabular-nums; }
26608
- .context img { display:block; width:100%; height:auto; max-height:420px; object-fit:contain;
26609
- image-rendering:pixelated;
26610
- background-image:linear-gradient(45deg,#0000 25%,#7f7f7f22 25%,#7f7f7f22 75%,#0000 75%),
26611
- linear-gradient(45deg,#0000 25%,#7f7f7f22 25%,#7f7f7f22 75%,#0000 75%);
26612
- background-size:12px 12px; background-position:0 0,6px 6px; }
26613
- .frames { display:flex; flex-wrap:wrap; gap:10px; max-width:100%; overflow-x:auto; }
26614
- .loop { display:flex; align-items:flex-start; gap:12px; margin-bottom:12px; }
26615
- .loop img { image-rendering:pixelated; border:2px solid var(--accent); padding:7px;
26616
- background:var(--panel-deep); max-width:min(var(--preview),calc(100vw - 62px)); height:auto; }
26617
- .loop-copy { color:var(--dim); font-size:11px; max-width:32ch; display:flex;
26618
- flex-direction:column; gap:8px; }
26619
- .loop-copy p { margin:0; }
26620
- .loop-copy button { align-self:flex-start; padding:5px 9px; font-size:10.5px; }
26621
- .cand { border:2px solid var(--line-strong); border-radius:0; padding:7px; background:var(--panel-deep);
26622
- cursor:pointer; display:flex; flex:0 0 auto; flex-direction:column; align-items:center; gap:5px;
26623
- position:relative; max-width:100%; }
26624
- .cand:hover { border-color:var(--dim); }
26625
- .cand.active { border-color:var(--dim); box-shadow:0 0 0 2px color-mix(in srgb, var(--dim) 20%, transparent); }
26626
- .cand.sel { border-color:var(--ok); box-shadow:0 0 0 3px color-mix(in srgb, var(--ok) 22%, transparent); }
26627
- .cand.set-frame { cursor:pointer; }
26628
- .cand.recommended:not(.sel) { border-color:var(--accent); }
26629
- .cand.recommended .badge { position:absolute; top:-1px; left:-1px; font-size:9.5px; font-weight:650;
26630
- text-transform:uppercase; letter-spacing:.03em; color:var(--bg); background:var(--accent); padding:1px 5px; }
26631
- .cand img { image-rendering:pixelated; display:block;
26632
- background-image:
26633
- linear-gradient(45deg,#0000 25%,#7f7f7f22 25%,#7f7f7f22 75%,#0000 75%),
26634
- linear-gradient(45deg,#0000 25%,#7f7f7f22 25%,#7f7f7f22 75%,#0000 75%);
26635
- background-size:12px 12px; background-position:0 0,6px 6px; border-radius:0; }
26636
- .cand img.preview { max-width:min(var(--preview),calc(100vw - 62px)); height:auto; }
26637
- .idx { font-size:10.5px; color:var(--dim); font-variant-numeric:tabular-nums; }
26638
- .actual { position:absolute; right:-3px; bottom:-3px; image-rendering:pixelated;
26639
- border:1px solid var(--line); border-radius:0; background:var(--panel); }
26640
- .skip { align-self:center; color:var(--dim); font-size:12px; }
26641
- footer { padding:26px 20px 60px; color:var(--dim); }
26642
- kbd { border:1px solid var(--line); border-bottom-width:2px; border-radius:0;
26643
- padding:1px 5px; font-size:11px; font-family:ui-monospace,Menlo,monospace; }
26644
- #status { color:var(--warn); }
26645
- @media (max-width:640px) {
26646
- .bar, .group { padding-inline:14px; }
26647
- .prompt { min-width:100%; }
26648
- .cand img.preview { max-width:calc(100vw - 50px); }
26649
- }
26650
- @media (max-width:900px) {
26651
- .review { grid-template-columns:1fr; }
26652
- .context { max-width:280px; }
26611
+ --ground:#0e0d0c; --surface:#181716; --raised:#26241f; --hover:#1f1d1a; --rule:#22201d;
26612
+ --text:#ffffff; --muted:#b4b4b4; --faint:#949494; --control:#46423b;
26613
+ --ember:#ff6b35; --ember-bg:#2e1a10;
26614
+ --negative:#e5566f; --negative-bg:#2c1a20;
26615
+ --list:340px; --head:56px; --pad:22px; --gap:14px; --row:56px;
26616
+ --radius-card:14px; --radius-chip:6px;
26617
+ --font: ui-sans-serif, -apple-system, "SF Pro Text", "Segoe UI", system-ui, sans-serif;
26618
+ --mono: ui-monospace, SFMono-Regular, Menlo, monospace;
26619
+ color-scheme: dark;
26653
26620
  }
26621
+ * { box-sizing:border-box; }
26622
+ html, body { height:100%; }
26623
+ body { margin:0; background:var(--ground); color:var(--text); font:14px/1.45 var(--font);
26624
+ display:grid; grid-template-rows:auto minmax(0,1fr) auto; overflow:hidden; }
26625
+ button { font:inherit; color:inherit; background:none; border:0; cursor:pointer; }
26626
+ button:focus-visible, [tabindex]:focus-visible { outline:2px solid var(--text); outline-offset:2px; }
26627
+ .num { font-variant-numeric:tabular-nums; }
26628
+ .id { font-family:var(--mono); font-size:12px; }
26629
+
26630
+ /* Top bar */
26631
+ header { display:flex; align-items:center; gap:20px; min-height:var(--head); padding:0 var(--pad); border-bottom:1px solid var(--rule); min-width:0; }
26632
+ .break { display:none; }
26633
+ .mark { font-weight:600; display:flex; align-items:center; gap:8px; white-space:nowrap; }
26634
+ .mark svg { display:block; }
26635
+ .counter { color:var(--muted); white-space:nowrap; }
26636
+ .counter b { color:var(--text); font-weight:600; }
26637
+ .filters { display:flex; gap:2px; margin-left:8px; }
26638
+ .filters button { height:32px; padding:0 10px; border-radius:var(--radius-chip); color:#bbb; white-space:nowrap; }
26639
+ .filters button:hover { background:var(--hover); }
26640
+ .filters button[aria-pressed="true"] { color:var(--text); background:var(--raised); }
26641
+ .filters .n { color:var(--faint); margin-left:6px; }
26642
+ .grow { flex:1; }
26643
+ .batch { display:flex; gap:2px; }
26644
+ .batch button, .tool { height:32px; padding:0 10px; border-radius:var(--radius-chip); color:#bbb; white-space:nowrap; }
26645
+ .batch button:hover, .tool:hover { background:var(--hover); color:var(--text); }
26646
+ .primary { height:36px; padding:0 18px; border-radius:999px; background:var(--text); color:#000; font-weight:600; white-space:nowrap; }
26647
+ .primary:disabled { background:var(--raised); color:var(--faint); cursor:not-allowed; }
26648
+ #status { color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:28ch; }
26649
+ #status.error { color:var(--negative); }
26650
+
26651
+ /* Master list */
26652
+ main { display:grid; grid-template-columns:var(--list) minmax(0,1fr); min-height:0; }
26653
+ #list { overflow-y:auto; border-right:1px solid var(--rule); padding:8px; scroll-padding:8px; outline:none; }
26654
+ .row { display:grid; grid-template-columns:44px minmax(0,1fr) auto; align-items:center; gap:12px;
26655
+ width:100%; height:var(--row); padding:6px 10px 6px 6px; border-radius:10px; text-align:left; }
26656
+ .row:hover { background:var(--hover); }
26657
+ .row[aria-selected="true"] { background:var(--raised); }
26658
+ .thumb { width:44px; height:44px; border-radius:8px; background:var(--surface); display:grid; place-items:center; overflow:hidden; }
26659
+ .thumb canvas { image-rendering:pixelated; display:block; }
26660
+ .row .name { display:block; font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
26661
+ .row .meta { display:block; color:var(--faint); font-size:13px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
26662
+ .state { font-size:13px; color:var(--faint); white-space:nowrap; }
26663
+ .state.accepted { color:var(--ember); }
26664
+ .state.flagged { color:var(--negative); }
26665
+ .state.later, .state.rerolling { color:var(--muted); }
26666
+ .empty { color:var(--muted); padding:24px 12px; }
26667
+
26668
+ /* Stage */
26669
+ #stage { display:grid; grid-template-rows:auto minmax(0,1fr) auto auto; min-width:0; min-height:0; padding:18px var(--pad) 16px; gap:var(--gap); }
26670
+ .title { display:flex; align-items:baseline; gap:12px; min-width:0; }
26671
+ .title h1 { font-size:20px; font-weight:600; margin:0; white-space:nowrap; }
26672
+ .title .id { color:var(--faint); white-space:nowrap; }
26673
+ .title .pos { margin-left:auto; color:var(--faint); white-space:nowrap; }
26674
+ .prompt { color:var(--muted); margin:4px 0 0; max-width:90ch; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }
26675
+ .view { position:relative; min-height:0; border-radius:var(--radius-card); background-color:var(--surface);
26676
+ background-image:linear-gradient(45deg,#ffffff08 25%,transparent 25%,transparent 75%,#ffffff08 75%),
26677
+ linear-gradient(45deg,#ffffff08 25%,transparent 25%,transparent 75%,#ffffff08 75%);
26678
+ background-size:16px 16px; background-position:0 0,8px 8px;
26679
+ display:grid; place-items:center; overflow:hidden; }
26680
+ .view canvas { image-rendering:pixelated; display:block; }
26681
+ .view .tag { position:absolute; left:14px; top:12px; color:var(--muted); font-size:13px; }
26682
+ .view .tag b { color:var(--text); font-weight:500; }
26683
+ .view .scale { position:absolute; right:14px; top:12px; color:var(--faint); font-size:13px; }
26684
+ .view .notice { position:absolute; inset:auto 14px 12px 14px; color:var(--muted); font-size:13px; }
26685
+ .view.flipped .tag b { color:var(--ember); }
26686
+ .controls { display:flex; align-items:center; gap:4px; flex-wrap:wrap; }
26687
+ .tool[aria-pressed="true"] { color:var(--text); background:var(--raised); }
26688
+ .tool kbd, .act kbd { color:var(--faint); margin-left:6px; font:13px var(--font); }
26689
+ .tool:disabled { color:#8f8a82; cursor:default; background:none; }
26690
+ .actions { display:flex; gap:6px; margin-left:auto; }
26691
+ .act { height:36px; padding:0 14px; border-radius:999px; background:var(--raised); white-space:nowrap; }
26692
+ .act:hover { background:#34312b; }
26693
+ .act.on { background:var(--ember-bg); color:var(--ember); }
26694
+ .act.warn { background:var(--negative-bg); color:var(--negative); }
26695
+ .act:disabled { color:var(--faint); background:var(--surface); cursor:default; }
26696
+
26697
+ /* Frame strip */
26698
+ .strip { display:flex; gap:6px; overflow-x:auto; padding-bottom:4px; scroll-padding:8px; }
26699
+ .strip[hidden] { display:none; }
26700
+ .cell { flex:0 0 auto; display:flex; flex-direction:column; align-items:center; gap:4px; padding:6px; border-radius:10px; min-width:64px; }
26701
+ .cell:hover { background:var(--hover); }
26702
+ .cell .pic { display:grid; place-items:center; background:var(--surface); border-radius:6px; padding:4px; }
26703
+ .cell canvas { image-rendering:pixelated; display:block; }
26704
+ .cell .lab { font-size:13px; color:var(--faint); }
26705
+ .cell[aria-current="true"] { background:var(--raised); }
26706
+ .cell[aria-current="true"] .lab { color:var(--text); }
26707
+ .cell.chosen .pic { box-shadow:inset 0 -3px 0 var(--ember); }
26708
+ .cell.chosen .lab { color:var(--ember); }
26709
+ .cell.flag .pic { box-shadow:inset 0 0 0 2px var(--negative); }
26710
+ .cell.flag .lab { color:var(--negative); }
26711
+
26712
+ footer { display:flex; gap:18px; flex-wrap:wrap; padding:8px var(--pad); border-top:1px solid var(--rule); color:var(--faint); font-size:12px; }
26713
+ footer kbd { font:12px var(--font); color:var(--muted); }
26714
+ body.done main { opacity:.5; pointer-events:none; }
26715
+
26716
+ @media (max-width: 1240px) {
26717
+ header { flex-wrap:wrap; row-gap:4px; padding:8px var(--pad); }
26718
+ .break { display:block; flex-basis:100%; height:0; order:5; }
26719
+ .filters { order:6; margin-left:-10px; }
26720
+ .batch { order:7; margin-left:auto; }
26721
+ }
26722
+ @media (max-width: 900px) {
26723
+ body { overflow:auto; grid-template-rows:auto auto auto; height:auto; }
26724
+ header { flex-wrap:wrap; padding:10px 16px; gap:10px; }
26725
+ .filters { margin-left:0; overflow-x:auto; max-width:100%; }
26726
+ main { grid-template-columns:1fr; }
26727
+ #list { max-height:38vh; border-right:0; border-bottom:1px solid var(--rule); }
26728
+ #stage { padding:14px 16px; grid-template-rows:auto 56vh auto auto; }
26729
+ .actions { margin-left:0; flex-wrap:wrap; }
26730
+ }
26731
+ @media (prefers-reduced-motion: reduce) { * { scroll-behavior:auto !important; } }
26654
26732
  </style>
26655
26733
  </head>
26656
26734
  <body>
26657
26735
  <header>
26658
- <div class="bar">
26659
- <h1>pixelkiln</h1>
26660
- <span class="count"><span id="picked">0</span> of <span id="total">0</span> chosen</span>
26661
- <span id="status"></span>
26662
- <span style="flex:1"></span>
26663
- <button id="submit" class="primary" disabled>Apply selections</button>
26736
+ <span class="mark"><svg width="14" height="14" viewBox="0 0 7 7" aria-hidden="true" shape-rendering="crispEdges"><path fill="#ff6b35" d="M3 0h1v1h1v1h1v1h1v1H6v1H5v1H4v1H3V6H2V5H1V4H0V3h1V2h1V1h1z"/></svg>pixelkiln</span>
26737
+ <span class="counter num" id="counter" aria-live="polite"></span>
26738
+ <nav class="filters" id="filters" aria-label="Filter by status"></nav>
26739
+ <span class="grow"></span>
26740
+ <span id="status" role="status"></span>
26741
+ <div class="batch">
26742
+ <button type="button" id="select-all" title="Accept every asset in this view (Shift+S)">Select all</button>
26743
+ <button type="button" id="deselect-all" title="Clear every acceptance (Shift+D)">Deselect all</button>
26744
+ <button type="button" id="accept-unflagged" title="Accept every undecided asset with no flags (Shift+A)">Accept unflagged</button>
26664
26745
  </div>
26746
+ <button type="button" class="primary num" id="apply" disabled>Apply</button>
26747
+ <span class="break"></span>
26665
26748
  </header>
26666
- <main id="root"></main>
26749
+ <main>
26750
+ <div id="list" role="listbox" aria-label="Assets awaiting review" tabindex="0"></div>
26751
+ <section id="stage" aria-label="Current asset">
26752
+ <div>
26753
+ <div class="title"><h1 id="s-name"></h1><span class="id" id="s-key"></span><span class="pos num" id="s-pos"></span></div>
26754
+ <p class="prompt" id="s-prompt"></p>
26755
+ </div>
26756
+ <div class="view" id="view">
26757
+ <canvas id="s-canvas" aria-label="Animated frame-set preview"></canvas>
26758
+ <span class="tag" id="s-tag"></span>
26759
+ <span class="scale num" id="s-scale"></span>
26760
+ <span class="notice" id="s-notice"></span>
26761
+ </div>
26762
+ <div class="controls">
26763
+ <button type="button" class="tool" id="t-play" aria-pressed="false">Pause<kbd>Space</kbd></button>
26764
+ <button type="button" class="tool" id="t-flip" aria-pressed="false">Show current art<kbd>C</kbd></button>
26765
+ <button type="button" class="tool" id="t-strip" aria-pressed="false">Frames<kbd>X</kbd></button>
26766
+ <button type="button" class="tool" id="t-onion" aria-pressed="false">Onion skin<kbd>O</kbd></button>
26767
+ <button type="button" class="tool" id="t-pong" aria-pressed="false">Ping-pong<kbd>P</kbd></button>
26768
+ <div class="actions">
26769
+ <button type="button" class="act" id="a-flag">Flag frame<kbd>F</kbd></button>
26770
+ <button type="button" class="act" id="a-later">Later<kbd>L</kbd></button>
26771
+ <button type="button" class="act" id="a-reroll">Reroll<kbd>R</kbd></button>
26772
+ <button type="button" class="act" id="a-accept">Accept<kbd>A</kbd></button>
26773
+ </div>
26774
+ </div>
26775
+ <div class="strip" id="strip" role="listbox" aria-label="Frames" hidden></div>
26776
+ </section>
26777
+ </main>
26667
26778
  <footer>
26668
- Click a candidate to choose it, or any ordered frame to accept its whole set;
26669
- click again to undo. In the focused row,
26670
- <kbd>\u2190</kbd>/<kbd>\u2192</kbd> browses every candidate and <kbd>Enter</kbd> chooses;
26671
- <kbd>1</kbd>\u2013<kbd>9</kbd> picks directly, <kbd>0</kbd> skips, and
26672
- <kbd>\u2191</kbd>/<kbd>\u2193</kbd> changes rows. Unchosen rows stay in review; nothing is
26673
- discarded by closing this page.
26779
+ <span><kbd>\u2191</kbd> <kbd>\u2193</kbd> asset</span>
26780
+ <span><kbd>\u2190</kbd> <kbd>\u2192</kbd> frame or candidate</span>
26781
+ <span><kbd>A</kbd> accept</span>
26782
+ <span><kbd>F</kbd> flag frame</span>
26783
+ <span><kbd>L</kbd> later</span>
26784
+ <span><kbd>R</kbd> reroll</span>
26785
+ <span><kbd>X</kbd> frames</span>
26786
+ <span><kbd>C</kbd> compare</span>
26787
+ <span><kbd>1</kbd>\u2013<kbd>5</kbd> filter</span>
26788
+ <span><kbd>Shift</kbd>+<kbd>A</kbd> accept unflagged</span>
26789
+ <span><kbd>\u2318</kbd>/<kbd>Ctrl</kbd>+<kbd>Enter</kbd> apply</span>
26790
+ <span>Unaccepted assets stay in review; closing this page loses nothing.</span>
26674
26791
  </footer>
26675
26792
  <script>
26676
- const GROUPS = ${data};
26677
- const APPLY = ${apply};
26678
- const picks = new Map();
26679
- const root = document.getElementById('root');
26680
- document.getElementById('total').textContent = GROUPS.length;
26793
+ const CONFIG = ${json(config)};
26794
+ let GROUPS = ${json(renderableGroups(groups))};
26795
+ ${CLIENT}
26796
+ </script>
26797
+ </body>
26798
+ </html>`;
26799
+ }
26800
+ var CLIENT = String.raw`
26801
+ const $ = (id) => document.getElementById(id);
26802
+ const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
26803
+ const STORE = 'pixelkiln-pick:';
26804
+ const FILTERS = [
26805
+ ['all', 'All'], ['undecided', 'Undecided'], ['accepted', 'Accepted'], ['flagged', 'Flagged'], ['later', 'Later'],
26806
+ ];
26681
26807
 
26682
- GROUPS.forEach((g, gi) => {
26683
- const el = document.createElement('section');
26684
- el.className = 'group';
26685
- el.tabIndex = 0;
26686
- el.dataset.gi = String(gi);
26687
- const largestSide = Math.max(g.width, g.height);
26688
- const preferredScale = largestSide <= 48 ? 4 : largestSide <= 96 ? 3 : 2;
26689
- const scale = Math.min(preferredScale, 560 / largestSide);
26690
- const displayScale = scale >= 1 ? Math.floor(scale) : scale;
26691
- const displayWidth = Math.max(1, Math.round(g.width * displayScale));
26692
- const displayHeight = Math.max(1, Math.round(g.height * displayScale));
26693
- const scaleLabel = displayScale >= 1 ? displayScale + '\xD7' : 'fit';
26694
- el.innerHTML =
26695
- '<div class="ghead"><span class="style">' + g.styleId + '</span>' +
26696
- '<span class="aid">' + g.assetId + '</span>' +
26697
- '<span class="prompt">' + g.prompt + '</span></div>' +
26698
- '<div class="review' + (g.revision || g.current ? '' : ' no-context') + '">' +
26699
- '<div class="frames"></div></div>';
26700
- const review = el.querySelector('.review');
26701
- const frames = el.querySelector('.frames');
26702
- const contextPanel = (identityText, dimensionsText, url, alt) => {
26703
- const block = document.createElement('div');
26704
- const label = document.createElement('div');
26705
- label.className = 'context-label';
26706
- const identity = document.createElement('span');
26707
- identity.textContent = identityText;
26708
- const dimensions = document.createElement('span');
26709
- dimensions.textContent = dimensionsText;
26710
- label.append(identity, dimensions);
26711
- const img = document.createElement('img');
26808
+ let state = {}; // key -> { chosen, flagged, later }
26809
+ let rerolls = {}; // key -> { state, error }
26810
+ let canReroll = Boolean(CONFIG.rerollUrl);
26811
+ let filter = 'all';
26812
+ let currentKey = GROUPS[0] ? GROUPS[0].key : null;
26813
+ let cursor = {}; // key -> frame or candidate index on the stage
26814
+ let playing = !reduced;
26815
+ let flipped = 0; // 0 candidate, then each comparison the asset has
26816
+ let showStrip = false, onion = false, pingpong = false;
26817
+ let armedReroll = null, armedTimer = null;
26818
+ let applying = false;
26819
+
26820
+ // ---- one request per frame -------------------------------------------------
26821
+ const images = new Map();
26822
+ function image(url) {
26823
+ let entry = images.get(url);
26824
+ if (!entry) {
26825
+ const img = new Image();
26826
+ img.decoding = 'async';
26827
+ entry = { img, ready: false, failed: false };
26828
+ img.onload = () => { entry.ready = true; dirty = true; };
26829
+ img.onerror = () => { entry.failed = true; dirty = true; };
26712
26830
  img.src = url;
26713
- img.alt = alt;
26714
- block.append(label, img);
26715
- return block;
26716
- };
26717
- if (g.revision || g.current) {
26718
- const context = document.createElement('aside');
26719
- context.className = 'context';
26720
- if (g.revision) {
26721
- context.append(contextPanel(
26722
- g.revision.mode.toUpperCase() + ' \xB7 SOURCE ' + g.revision.sourceAssetId,
26723
- g.revision.width + '\xD7' + g.revision.height,
26724
- g.revision.sourceUrl, 'Revision source ' + g.revision.sourceAssetId));
26725
- }
26726
- if (g.current) {
26727
- context.append(contextPanel(
26728
- 'CURRENT ART \xB7 replaced if you choose',
26729
- g.current.width + '\xD7' + g.current.height,
26730
- g.current.url, 'Current ' + g.assetId));
26731
- }
26732
- review.insertBefore(context, frames);
26733
- }
26734
- if (g.mode === 'frame-set') {
26735
- const loop = document.createElement('div');
26736
- loop.className = 'loop';
26737
- const preview = document.createElement('img');
26738
- preview.src = g.frameUrls[0];
26739
- preview.width = displayWidth;
26740
- preview.height = displayHeight;
26741
- preview.alt = 'Animated frame-set preview';
26742
- const copy = document.createElement('div');
26743
- copy.className = 'loop-copy';
26744
- const copyText = document.createElement('p');
26745
- copyText.textContent = g.frameUrls.length + ' ordered frames \xB7 ' + (g.fps || 12) +
26746
- ' fps. Accepting keeps every frame; one bad frame means leave the set unchosen.';
26747
- const playback = document.createElement('button');
26748
- playback.type = 'button';
26749
- let userPaused = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
26750
- let loopVisible = true;
26751
- let pageVisible = !document.hidden;
26752
- let loopTimer = null;
26753
- let loopIndex = 0;
26754
- const stopLoop = () => {
26755
- if (loopTimer !== null) window.clearInterval(loopTimer);
26756
- loopTimer = null;
26757
- };
26758
- const syncLoop = () => {
26759
- stopLoop();
26760
- playback.textContent = userPaused ? 'Play preview' : 'Pause preview';
26761
- playback.setAttribute('aria-pressed', String(userPaused));
26762
- if (!userPaused && loopVisible && pageVisible) {
26763
- loopTimer = window.setInterval(() => {
26764
- loopIndex = (loopIndex + 1) % g.frameUrls.length;
26765
- preview.src = g.frameUrls[loopIndex];
26766
- }, Math.max(16, Math.round(1000 / (g.fps || 12))));
26767
- }
26768
- };
26769
- playback.addEventListener('click', () => {
26770
- userPaused = !userPaused;
26771
- syncLoop();
26772
- });
26773
- copy.append(copyText, playback);
26774
- loop.append(preview, copy);
26775
- review.insertBefore(loop, frames);
26776
- document.addEventListener('visibilitychange', () => {
26777
- pageVisible = !document.hidden;
26778
- syncLoop();
26779
- });
26780
- syncLoop();
26781
- if ('IntersectionObserver' in window) {
26782
- new IntersectionObserver((entries) => {
26783
- loopVisible = entries[0]?.isIntersecting ?? false;
26784
- syncLoop();
26785
- }).observe(loop);
26786
- }
26831
+ images.set(url, entry);
26787
26832
  }
26788
- const recommended = g.recommendedIndex ?? 0;
26789
- g.frameUrls.forEach((url, i) => {
26790
- const c = document.createElement('button');
26791
- c.type = 'button';
26792
- c.className = 'cand' + (g.mode === 'frame-set' ? ' set-frame' : '') +
26793
- (g.recommendedIndex != null && i === recommended ? ' recommended' : '');
26794
- c.tabIndex = -1;
26795
- c.setAttribute('aria-label', (g.mode === 'frame-set'
26796
- ? 'Accept ordered frame set from frame ' + (i + 1)
26797
- : 'Choose candidate ' + (i + 1) + ' of ' + g.frameUrls.length) +
26798
- (g.recommendedIndex != null && i === recommended ? ' (this asset\u2019s declared slot)' : ''));
26833
+ return entry;
26834
+ }
26799
26835
 
26800
- const preview = document.createElement('img');
26801
- preview.className = 'preview';
26802
- preview.src = url;
26803
- preview.width = displayWidth;
26804
- preview.height = displayHeight;
26805
- preview.loading = 'lazy';
26806
- const index = document.createElement('span');
26807
- index.className = 'idx';
26808
- // A frame's own size, not the manifest's: a 96px loop of a 64px
26809
- // character is 96\xD796. Known up front for a cached file, else once loaded.
26810
- const label = (w, h) => {
26811
- index.textContent = (g.frameLabels?.[i] || String(i + 1)) + ' \xB7 ' + w + '\xD7' + h + ' \xB7 ' + scaleLabel;
26812
- };
26813
- const known = g.frameSizes?.[i];
26814
- label(known ? known.width : g.width, known ? known.height : g.height);
26815
- if (!known) {
26816
- preview.addEventListener('load', () => {
26817
- if (preview.naturalWidth && preview.naturalHeight) label(preview.naturalWidth, preview.naturalHeight);
26818
- }, { once: true });
26819
- }
26820
- c.append(preview, index);
26821
- if (g.recommendedIndex != null && i === recommended) {
26822
- const badge = document.createElement('span');
26823
- badge.className = 'badge';
26824
- badge.textContent = 'declared';
26825
- c.append(badge);
26826
- }
26827
- if (displayScale > 1 && largestSide <= 96) {
26828
- const actual = document.createElement('img');
26829
- actual.className = 'actual';
26830
- actual.src = url;
26831
- actual.width = g.width;
26832
- actual.height = g.height;
26833
- actual.loading = 'lazy';
26834
- actual.setAttribute('aria-label', 'Actual size');
26835
- c.append(actual);
26836
+ // ---- state -----------------------------------------------------------------
26837
+ const blank = () => ({ chosen: null, flagged: [], later: false });
26838
+ const group = (key) => GROUPS.find((g) => g.key === key);
26839
+ const st = (key) => state[key] || (state[key] = blank());
26840
+ function statusOf(g) {
26841
+ if (rerolls[g.key] && rerolls[g.key].state === 'running') return 'rerolling';
26842
+ const s = st(g.key);
26843
+ if (s.chosen !== null) return 'accepted';
26844
+ if (s.flagged.length) return 'flagged';
26845
+ if (s.later) return 'later';
26846
+ return 'undecided';
26847
+ }
26848
+ function inFilter(g) {
26849
+ const s = statusOf(g);
26850
+ return filter === 'all' || s === filter || (filter === 'undecided' && s === 'rerolling');
26851
+ }
26852
+ const visible = () => GROUPS.filter(inFilter);
26853
+ const isSet = (g) => g.mode === 'frame-set';
26854
+ const startIndex = (g) => (g.recommendedIndex != null && g.recommendedIndex < g.frameUrls.length ? g.recommendedIndex : 0);
26855
+ const cur = (g) => (cursor[g.key] != null ? cursor[g.key] : (cursor[g.key] = startIndex(g)));
26856
+
26857
+ function localKey(g) { return STORE + g.reviewObjectId + ':' + g.key; }
26858
+ function remember(g) {
26859
+ try { localStorage.setItem(localKey(g), JSON.stringify(st(g.key))); } catch (e) { /* private mode */ }
26860
+ }
26861
+ function recall(g) {
26862
+ try {
26863
+ const raw = localStorage.getItem(localKey(g));
26864
+ if (raw) state[g.key] = Object.assign(blank(), JSON.parse(raw));
26865
+ } catch (e) { /* ignore */ }
26866
+ }
26867
+
26868
+ const pending = new Map();
26869
+ function save(g) {
26870
+ remember(g);
26871
+ if (!CONFIG.stateUrl) return;
26872
+ clearTimeout(pending.get(g.key));
26873
+ pending.set(g.key, setTimeout(async () => {
26874
+ pending.delete(g.key);
26875
+ try {
26876
+ const res = await fetch(CONFIG.stateUrl, {
26877
+ method: 'POST',
26878
+ headers: Object.assign({ 'Content-Type': 'application/json' }, CONFIG.headers),
26879
+ body: JSON.stringify(Object.assign({ key: g.key }, st(g.key))),
26880
+ });
26881
+ if (!res.ok) throw new Error(await res.text());
26882
+ } catch (err) {
26883
+ say('Could not save ' + g.assetId + ': ' + err.message + '. It is kept in this browser.', true);
26836
26884
  }
26885
+ }, 200));
26886
+ }
26837
26887
 
26838
- c.onclick = () => {
26839
- activate(i, frames);
26840
- choose(gi, i, c, frames, el);
26841
- // Keep the row as the keyboard target. Otherwise a clicked <button>
26842
- // receives focus and Enter would invoke both its native click and the
26843
- // row shortcut, toggling the same choice twice.
26844
- el.focus();
26845
- };
26846
- c.onmouseenter = () => activate(i, frames);
26847
- frames.appendChild(c);
26848
- });
26849
- frames.dataset.active = '0';
26850
- frames.querySelector('.cand')?.classList.add('active');
26851
- if (recommended > 0) activate(recommended, frames);
26852
- root.appendChild(el);
26853
- });
26888
+ // ---- rendering: list -------------------------------------------------------
26889
+ const list = $('list');
26890
+ const rows = new Map();
26891
+ const thumbsOnScreen = new Set();
26892
+ const io = 'IntersectionObserver' in window ? new IntersectionObserver((entries) => {
26893
+ for (const e of entries) (e.isIntersecting ? thumbsOnScreen.add(e.target.dataset.key) : thumbsOnScreen.delete(e.target.dataset.key));
26894
+ dirty = true;
26895
+ }, { root: list }) : null;
26854
26896
 
26855
- function activate(i, frames) {
26856
- const candidates = [...frames.querySelectorAll('.cand')];
26857
- if (!candidates.length) return null;
26858
- const next = ((i % candidates.length) + candidates.length) % candidates.length;
26859
- candidates.forEach(n => n.classList.remove('active'));
26860
- candidates[next].classList.add('active');
26861
- frames.dataset.active = String(next);
26862
- candidates[next].scrollIntoView({ block: 'nearest', inline: 'nearest' });
26863
- return candidates[next];
26897
+ function stateLabel(g) {
26898
+ const s = statusOf(g);
26899
+ const st0 = st(g.key);
26900
+ if (s === 'accepted') return isSet(g) ? 'Accepted' : 'Accepted ' + (st0.chosen + 1);
26901
+ if (s === 'flagged') return st0.flagged.length + ' flagged';
26902
+ if (s === 'later') return 'Later';
26903
+ if (s === 'rerolling') return 'Rerolling';
26904
+ if (rerolls[g.key] && rerolls[g.key].state === 'failed') return 'Reroll failed';
26905
+ return '';
26864
26906
  }
26865
26907
 
26866
- function choose(gi, i, node, frames, groupEl) {
26867
- if (GROUPS[gi].mode === 'frame-set') {
26868
- const selected = picks.has(gi);
26869
- frames.querySelectorAll('.cand').forEach(n => n.classList.toggle('sel', !selected));
26870
- if (selected) { picks.delete(gi); groupEl.classList.remove('done'); }
26871
- else { picks.set(gi, 0); groupEl.classList.add('done'); }
26872
- refresh();
26908
+ function buildList() {
26909
+ list.textContent = '';
26910
+ rows.clear();
26911
+ if (io) io.disconnect();
26912
+ thumbsOnScreen.clear();
26913
+ const shown = visible();
26914
+ if (!shown.length) {
26915
+ const p = document.createElement('p');
26916
+ p.className = 'empty';
26917
+ p.textContent = filter === 'all' ? 'Nothing is waiting for review.' : 'No assets are ' + filter + '. Press 1 to show all.';
26918
+ list.append(p);
26873
26919
  return;
26874
26920
  }
26875
- const current = picks.get(gi);
26876
- frames.querySelectorAll('.cand').forEach(n => n.classList.remove('sel'));
26877
- if (current === i) { picks.delete(gi); groupEl.classList.remove('done'); }
26878
- else { picks.set(gi, i); node.classList.add('sel'); groupEl.classList.add('done'); }
26879
- refresh();
26921
+ for (const g of shown) {
26922
+ const row = document.createElement('button');
26923
+ row.type = 'button';
26924
+ row.className = 'row';
26925
+ row.id = 'row-' + GROUPS.indexOf(g);
26926
+ row.setAttribute('role', 'option');
26927
+ row.tabIndex = -1;
26928
+ row.dataset.key = g.key;
26929
+ const thumb = document.createElement('span');
26930
+ thumb.className = 'thumb';
26931
+ const c = document.createElement('canvas');
26932
+ c.width = c.height = 0;
26933
+ thumb.append(c);
26934
+ const text = document.createElement('span');
26935
+ text.style.minWidth = '0';
26936
+ const name = document.createElement('span');
26937
+ name.className = 'name';
26938
+ name.textContent = decode(g.assetId);
26939
+ const meta = document.createElement('span');
26940
+ meta.className = 'meta num';
26941
+ meta.textContent = decode(g.styleId) + ', ' + g.frameUrls.length + (isSet(g) ? ' frames' : g.frameUrls.length === 1 ? ' candidate' : ' candidates');
26942
+ text.append(name, meta);
26943
+ const label = document.createElement('span');
26944
+ label.className = 'state';
26945
+ row.append(thumb, text, label);
26946
+ row.addEventListener('click', () => { select(g.key); row.blur(); list.focus({ preventScroll: true }); });
26947
+ list.append(row);
26948
+ rows.set(g.key, { row, canvas: c, label, drawn: -1 });
26949
+ if (io) io.observe(row); else thumbsOnScreen.add(g.key);
26950
+ }
26951
+ refreshRows();
26952
+ }
26953
+ function refreshRows() {
26954
+ for (const [key, r] of rows) {
26955
+ const g = group(key);
26956
+ if (!g) continue;
26957
+ r.label.textContent = stateLabel(g);
26958
+ r.label.className = 'state ' + statusOf(g);
26959
+ r.row.setAttribute('aria-selected', String(key === currentKey));
26960
+ r.row.setAttribute('aria-label', decode(g.assetId) + ' in ' + decode(g.styleId) + (stateLabel(g) ? ', ' + stateLabel(g) : ', undecided'));
26961
+ }
26962
+ const active = rows.get(currentKey);
26963
+ if (active) list.setAttribute('aria-activedescendant', active.row.id);
26880
26964
  }
26881
- function refresh() {
26882
- document.getElementById('picked').textContent = picks.size;
26883
- document.getElementById('submit').disabled = picks.size === 0;
26965
+
26966
+ // Prompts arrive HTML-escaped; textContent wants them plain.
26967
+ const decoder = document.createElement('textarea');
26968
+ function decode(s) { decoder.innerHTML = s; return decoder.value; }
26969
+
26970
+ // ---- rendering: header -----------------------------------------------------
26971
+ function buildFilters() {
26972
+ const nav = $('filters');
26973
+ nav.textContent = '';
26974
+ FILTERS.forEach(([id, label], i) => {
26975
+ const b = document.createElement('button');
26976
+ b.type = 'button';
26977
+ b.dataset.filter = id;
26978
+ b.title = label + ' (' + (i + 1) + ')';
26979
+ b.addEventListener('click', () => { setFilter(id); b.blur(); });
26980
+ nav.append(b);
26981
+ });
26982
+ }
26983
+ function refreshHeader() {
26984
+ const counts = { all: GROUPS.length, undecided: 0, accepted: 0, flagged: 0, later: 0 };
26985
+ for (const g of GROUPS) {
26986
+ const s = statusOf(g);
26987
+ counts[s === 'rerolling' ? 'undecided' : s]++;
26988
+ }
26989
+ $('counter').innerHTML = '<b>' + counts.accepted + '</b> of ' + GROUPS.length + ' accepted' +
26990
+ (counts.flagged ? ', ' + counts.flagged + ' flagged' : '');
26991
+ for (const b of $('filters').children) {
26992
+ const id = b.dataset.filter;
26993
+ b.setAttribute('aria-pressed', String(id === filter));
26994
+ b.innerHTML = '';
26995
+ b.append(FILTERS.find((f) => f[0] === id)[1]);
26996
+ const n = document.createElement('span');
26997
+ n.className = 'n num';
26998
+ n.textContent = counts[id];
26999
+ b.append(n);
27000
+ }
27001
+ const running = Object.values(rerolls).some((r) => r.state === 'running');
27002
+ const apply = $('apply');
27003
+ apply.disabled = applying || counts.accepted === 0 || running;
27004
+ apply.textContent = counts.accepted ? 'Apply ' + counts.accepted : 'Apply';
27005
+ apply.title = running ? 'Wait for the reroll to finish' : 'Commit the accepted assets (Ctrl or Cmd+Enter)';
26884
27006
  }
26885
- document.addEventListener('keydown', e => {
26886
- const g = document.activeElement?.closest?.('.group');
26887
- if (!g) return;
26888
- const gi = Number(g.dataset.gi);
26889
- const frames = g.querySelector('.frames');
26890
- const candidates = [...frames.querySelectorAll('.cand')];
26891
- const active = Number(frames.dataset.active || 0);
26892
- let advance = false;
26893
27007
 
26894
- if (e.key === 'ArrowLeft') activate(active - 1, frames);
26895
- else if (e.key === 'ArrowRight') activate(active + 1, frames);
26896
- else if (e.key === 'Home') activate(0, frames);
26897
- else if (e.key === 'End') activate(candidates.length - 1, frames);
26898
- else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
26899
- const sibling = e.key === 'ArrowUp' ? g.previousElementSibling : g.nextElementSibling;
26900
- if (sibling) { sibling.focus(); sibling.scrollIntoView({ block: 'center', behavior: 'smooth' }); }
26901
- } else if (e.key === 'Enter' || e.key === ' ') {
26902
- const node = candidates[active];
26903
- if (!node) return;
26904
- choose(gi, active, node, frames, g);
26905
- advance = true;
26906
- } else if (e.key === '0') {
26907
- picks.delete(gi); g.classList.remove('done');
26908
- frames.querySelectorAll('.cand').forEach(n => n.classList.remove('sel'));
26909
- refresh();
26910
- advance = true;
26911
- } else if (/^[1-9]$/.test(e.key)) {
26912
- const i = Number(e.key) - 1;
26913
- const node = candidates[i];
26914
- if (!node) return;
26915
- activate(i, frames);
26916
- choose(gi, i, node, frames, g);
26917
- advance = true;
27008
+ // ---- rendering: stage ------------------------------------------------------
27009
+ const canvas = $('s-canvas');
27010
+ const ctx = canvas.getContext('2d');
27011
+ let dirty = true;
27012
+
27013
+ function views(g) {
27014
+ const out = [{ label: isSet(g) ? 'Candidate' : 'Candidate', kind: 'candidate' }];
27015
+ if (g.current) out.push({ label: 'Current art', kind: 'current', url: g.current.url });
27016
+ if (g.revision) out.push({ label: 'Revision source', kind: 'source', url: g.revision.sourceUrl });
27017
+ return out;
27018
+ }
27019
+ function frameSize(g, i) {
27020
+ const known = g.frameSizes && g.frameSizes[i];
27021
+ if (known) return known;
27022
+ const e = image(g.frameUrls[i]);
27023
+ if (e.ready) return { width: e.img.naturalWidth, height: e.img.naturalHeight };
27024
+ return { width: g.width, height: g.height };
27025
+ }
27026
+ // The largest whole-number zoom that fits; below 1x the frame is fitted and
27027
+ // labelled so, never stretched.
27028
+ function fitScale(w, h, boxW, boxH) {
27029
+ const s = Math.min(boxW / w, boxH / h);
27030
+ return s >= 1 ? Math.min(32, Math.floor(s)) : s;
27031
+ }
27032
+
27033
+ let clock = 0, lastTick = 0;
27034
+ function playIndex(g) {
27035
+ const n = g.frameUrls.length;
27036
+ if (n < 2) return 0;
27037
+ const step = Math.floor(clock * (g.fps || 12) / 1000);
27038
+ if (!pingpong) return step % n;
27039
+ const period = 2 * n - 2;
27040
+ const k = step % period;
27041
+ return k < n ? k : period - k;
27042
+ }
27043
+ // What the stage shows right now: frame sets play, candidates hold the cursor.
27044
+ function stageIndex(g) {
27045
+ return isSet(g) && playing ? playIndex(g) : cur(g);
27046
+ }
27047
+
27048
+ function drawStage() {
27049
+ const g = group(currentKey);
27050
+ const view = $('view');
27051
+ if (!g) { canvas.width = canvas.height = 0; return; }
27052
+ const vs = views(g);
27053
+ const mode = vs[flipped % vs.length];
27054
+ view.classList.toggle('flipped', mode.kind !== 'candidate');
27055
+ const box = view.getBoundingClientRect();
27056
+ const i = stageIndex(g);
27057
+ const size = frameSize(g, i);
27058
+ const scale = fitScale(size.width, size.height, Math.max(1, box.width - 48), Math.max(1, box.height - 72));
27059
+ const w = Math.max(1, Math.round(size.width * scale)), h = Math.max(1, Math.round(size.height * scale));
27060
+ if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
27061
+ ctx.imageSmoothingEnabled = scale < 1;
27062
+ ctx.clearRect(0, 0, w, h);
27063
+ const draw = (url, alpha) => {
27064
+ const e = image(url);
27065
+ if (!e.ready) return false;
27066
+ ctx.globalAlpha = alpha;
27067
+ // Same scale as the candidate, so a comparison is pixel for pixel.
27068
+ ctx.drawImage(e.img, 0, 0, e.img.naturalWidth * scale, e.img.naturalHeight * scale);
27069
+ ctx.globalAlpha = 1;
27070
+ return true;
27071
+ };
27072
+ let notice = '';
27073
+ if (mode.kind === 'candidate') {
27074
+ if (onion && g.frameUrls.length > 1) {
27075
+ const prev = (i - 1 + g.frameUrls.length) % g.frameUrls.length;
27076
+ draw(g.frameUrls[prev], 0.3);
27077
+ }
27078
+ const e = image(g.frameUrls[i]);
27079
+ if (e.failed) notice = 'This frame did not load. Reroll the asset or check the run log.';
27080
+ else if (!draw(g.frameUrls[i], 1)) notice = 'Loading…';
27081
+ } else {
27082
+ const e = image(mode.url);
27083
+ if (e.failed) notice = 'The ' + mode.label.toLowerCase() + ' did not load.';
27084
+ else draw(mode.url, 1);
27085
+ }
27086
+ const n = g.frameUrls.length;
27087
+ const s = st(g.key);
27088
+ let tag = '<b>' + mode.label + '</b>';
27089
+ if (mode.kind === 'candidate') {
27090
+ tag += isSet(g)
27091
+ ? ', frame ' + (i + 1) + ' of ' + n + ', ' + (g.fps || 12) + ' fps'
27092
+ : ', ' + (i + 1) + ' of ' + n + (g.recommendedIndex === i ? ' (declared slot)' : '');
27093
+ if (s.flagged.includes(i)) tag += ', flagged';
27094
+ if (!isSet(g) && s.chosen === i) tag += ', accepted';
26918
27095
  } else {
27096
+ tag += ' at the candidate’s scale';
27097
+ }
27098
+ $('s-tag').innerHTML = tag;
27099
+ $('s-scale').textContent = size.width + '×' + size.height + ', ' + (scale >= 1 ? scale + '×' : 'fitted');
27100
+ $('s-notice').textContent = notice;
27101
+ }
27102
+
27103
+ function buildStage() {
27104
+ const g = group(currentKey);
27105
+ const has = Boolean(g);
27106
+ for (const id of ['a-accept', 'a-flag', 'a-later', 'a-reroll', 't-play', 't-flip', 't-strip', 't-onion', 't-pong']) $(id).disabled = !has;
27107
+ if (!g) {
27108
+ $('s-name').textContent = 'Nothing selected';
27109
+ $('s-key').textContent = '';
27110
+ $('s-pos').textContent = '';
27111
+ $('s-prompt').textContent = visible().length ? '' : 'Change the filter to see more assets.';
27112
+ $('strip').hidden = true;
27113
+ dirty = true;
26919
27114
  return;
26920
27115
  }
26921
- if (advance) {
26922
- const next = g.nextElementSibling;
26923
- if (next) { next.focus(); next.scrollIntoView({ block: 'center', behavior: 'smooth' }); }
27116
+ const shown = visible();
27117
+ $('s-name').textContent = decode(g.assetId);
27118
+ $('s-key').textContent = decode(g.styleId) + '/' + decode(g.assetId);
27119
+ const pos = shown.indexOf(g);
27120
+ $('s-pos').textContent = (pos >= 0 ? pos + 1 : '–') + ' of ' + shown.length;
27121
+ $('s-prompt').textContent = decode(g.prompt);
27122
+ // Warm this asset's frames and the next one's: still one request each.
27123
+ g.frameUrls.forEach(image);
27124
+ const after = shown[pos + 1];
27125
+ if (after) after.frameUrls.forEach(image);
27126
+ const vs = views(g);
27127
+ $('t-flip').disabled = vs.length < 2;
27128
+ const next = vs[(flipped + 1) % vs.length];
27129
+ $('t-flip').firstChild.textContent = vs.length < 2 ? 'No current art' : flipped % vs.length ? 'Show candidate' : 'Show ' + next.label.toLowerCase();
27130
+ $('t-flip').setAttribute('aria-pressed', String(flipped % vs.length !== 0));
27131
+ $('t-play').firstChild.textContent = playing ? 'Pause' : 'Play';
27132
+ $('t-play').setAttribute('aria-pressed', String(!playing));
27133
+ $('t-strip').setAttribute('aria-pressed', String(showStrip));
27134
+ $('t-onion').setAttribute('aria-pressed', String(onion));
27135
+ $('t-pong').setAttribute('aria-pressed', String(pingpong));
27136
+ $('t-onion').disabled = $('t-pong').disabled = g.frameUrls.length < 2;
27137
+ if (!isSet(g)) $('t-pong').disabled = true;
27138
+
27139
+ const s = st(g.key);
27140
+ const status = statusOf(g);
27141
+ const accept = $('a-accept');
27142
+ accept.className = 'act' + (s.chosen !== null ? ' on' : '');
27143
+ accept.firstChild.textContent = s.chosen !== null ? 'Accepted' : isSet(g) ? 'Accept set' : 'Accept ' + (cur(g) + 1);
27144
+ accept.setAttribute('aria-label', s.chosen !== null ? 'Accepted; press to undo' : isSet(g) ? 'Accept ordered frame set' : 'Choose candidate ' + (cur(g) + 1) + ' of ' + g.frameUrls.length);
27145
+ accept.disabled = status === 'rerolling';
27146
+ const flag = $('a-flag');
27147
+ const flaggedHere = s.flagged.includes(cur(g));
27148
+ flag.className = 'act' + (flaggedHere ? ' warn' : '');
27149
+ flag.firstChild.textContent = flaggedHere && !(isSet(g) && playing) ? 'Unflag ' + (cur(g) + 1) : isSet(g) ? (playing ? 'Flag this frame' : 'Flag frame ' + (cur(g) + 1)) : 'Flag ' + (cur(g) + 1);
27150
+ $('a-later').className = 'act' + (s.later ? ' on' : '');
27151
+ const reroll = $('a-reroll');
27152
+ reroll.hidden = !canReroll;
27153
+ const r = rerolls[g.key];
27154
+ reroll.disabled = status === 'rerolling';
27155
+ reroll.className = 'act' + (armedReroll === g.key ? ' warn' : '');
27156
+ reroll.firstChild.textContent = status === 'rerolling' ? 'Rerolling…' : armedReroll === g.key ? 'Press R again to spend' : 'Reroll';
27157
+ if (r && r.state === 'failed') say('Reroll of ' + g.assetId + ' failed: ' + r.error, true);
27158
+ buildStrip(g);
27159
+ dirty = true;
27160
+ }
27161
+
27162
+ function buildStrip(g) {
27163
+ const strip = $('strip');
27164
+ strip.hidden = !showStrip;
27165
+ if (!showStrip) return;
27166
+ strip.textContent = '';
27167
+ const s = st(g.key);
27168
+ g.frameUrls.forEach((url, i) => {
27169
+ const cell = document.createElement('button');
27170
+ cell.type = 'button';
27171
+ cell.className = 'cell' + (s.flagged.includes(i) ? ' flag' : '') +
27172
+ ((isSet(g) ? s.chosen !== null : s.chosen === i) ? ' chosen' : '');
27173
+ cell.setAttribute('role', 'option');
27174
+ cell.setAttribute('aria-current', String(i === cur(g)));
27175
+ cell.setAttribute('aria-label', (isSet(g) ? 'Frame ' : 'Candidate ') + (i + 1) + (s.flagged.includes(i) ? ', flagged' : ''));
27176
+ cell.tabIndex = -1;
27177
+ const pic = document.createElement('span');
27178
+ pic.className = 'pic';
27179
+ const c = document.createElement('canvas');
27180
+ c.width = c.height = 0;
27181
+ pic.append(c);
27182
+ const lab = document.createElement('span');
27183
+ lab.className = 'lab num';
27184
+ lab.textContent = String(i + 1) + (s.flagged.includes(i) ? ' flagged' : '');
27185
+ cell.append(pic, lab);
27186
+ cell.addEventListener('click', () => { setCursor(g, i); cell.blur(); });
27187
+ strip.append(cell);
27188
+ const paint = () => {
27189
+ const e = image(url);
27190
+ if (!e.ready) return;
27191
+ const w = e.img.naturalWidth, h = e.img.naturalHeight;
27192
+ const k = fitScale(w, h, 96, 72);
27193
+ c.width = Math.max(1, Math.round(w * k)); c.height = Math.max(1, Math.round(h * k));
27194
+ const x = c.getContext('2d');
27195
+ x.imageSmoothingEnabled = k < 1;
27196
+ x.drawImage(e.img, 0, 0, c.width, c.height);
27197
+ };
27198
+ const e = image(url);
27199
+ if (e.ready) paint(); else e.img.addEventListener('load', paint, { once: true });
27200
+ });
27201
+ const active = strip.children[cur(g)];
27202
+ if (active) active.scrollIntoView({ block: 'nearest', inline: 'nearest' });
27203
+ }
27204
+
27205
+ function drawThumbs() {
27206
+ for (const key of thumbsOnScreen) {
27207
+ const r = rows.get(key);
27208
+ const g = group(key);
27209
+ if (!r || !g) continue;
27210
+ const s = st(key);
27211
+ const i = isSet(g) ? (playing ? playIndex(g) : 0) : (s.chosen !== null ? s.chosen : cur(g));
27212
+ const e = image(g.frameUrls[i]);
27213
+ if (!e.ready) continue;
27214
+ if (r.drawn === i && r.canvas.width) continue;
27215
+ const w = e.img.naturalWidth, h = e.img.naturalHeight;
27216
+ const k = fitScale(w, h, 40, 40);
27217
+ const cw = Math.max(1, Math.round(w * k)), ch = Math.max(1, Math.round(h * k));
27218
+ if (r.canvas.width !== cw || r.canvas.height !== ch) { r.canvas.width = cw; r.canvas.height = ch; }
27219
+ const x = r.canvas.getContext('2d');
27220
+ x.imageSmoothingEnabled = k < 1;
27221
+ x.clearRect(0, 0, cw, ch);
27222
+ x.drawImage(e.img, 0, 0, cw, ch);
27223
+ r.drawn = i;
26924
27224
  }
26925
- e.preventDefault();
26926
- });
27225
+ }
26927
27226
 
26928
- document.getElementById('submit').onclick = async () => {
26929
- const btn = document.getElementById('submit');
26930
- btn.disabled = true;
26931
- const status = document.getElementById('status');
26932
- status.textContent = 'applying\u2026';
26933
- const selections = [...picks.entries()].map(([gi, index]) => ({ key: GROUPS[gi].key, index }));
27227
+ // One clock for the page: thumbnails and stage advance together, and stop
27228
+ // when the tab is hidden.
27229
+ function tick(t) {
27230
+ if (playing && lastTick) clock += t - lastTick;
27231
+ lastTick = t;
27232
+ const g = group(currentKey);
27233
+ const before = tick.last;
27234
+ const now = g ? stageIndex(g) + ':' + flipped + ':' + onion : '';
27235
+ if (dirty || now !== before) { drawStage(); tick.last = now; dirty = false; }
27236
+ drawThumbs();
27237
+ requestAnimationFrame(tick);
27238
+ }
27239
+
27240
+ // ---- actions ---------------------------------------------------------------
27241
+ function say(text, error) {
27242
+ const s = $('status');
27243
+ s.textContent = text;
27244
+ s.title = text;
27245
+ s.className = error ? 'error' : '';
27246
+ }
27247
+ function refresh() { refreshRows(); refreshHeader(); buildStage(); }
27248
+
27249
+ function select(key, scroll) {
27250
+ currentKey = key;
27251
+ flipped = 0;
27252
+ if (armedReroll && armedReroll !== key) armedReroll = null;
27253
+ refresh();
27254
+ const r = rows.get(key);
27255
+ if (r && scroll !== false) r.row.scrollIntoView({ block: 'nearest' });
27256
+ }
27257
+ function move(delta) {
27258
+ const shown = visible();
27259
+ if (!shown.length) return;
27260
+ const at = shown.findIndex((g) => g.key === currentKey);
27261
+ const next = at < 0 ? 0 : Math.max(0, Math.min(shown.length - 1, at + delta));
27262
+ select(shown[next].key);
27263
+ }
27264
+ function advance() {
27265
+ // After a decision, go to the next asset still waiting in this view.
27266
+ const shown = visible();
27267
+ const at = GROUPS.findIndex((g) => g.key === currentKey);
27268
+ const after = GROUPS.slice(at + 1).concat(GROUPS.slice(0, at + 1));
27269
+ const next = after.find((g) => inFilter(g) && statusOf(g) === 'undecided');
27270
+ if (filter !== 'all' && !inFilter(group(currentKey))) { buildList(); }
27271
+ if (next) select(next.key); else if (shown.length) refresh(); else { buildList(); select(visible()[0] ? visible()[0].key : null); }
27272
+ }
27273
+ // Pausing holds the frame on screen, so the arrows step from there.
27274
+ function togglePlay() {
27275
+ const g = group(currentKey);
27276
+ if (playing && g && isSet(g)) cursor[g.key] = playIndex(g);
27277
+ playing = !playing;
27278
+ buildStage();
27279
+ }
27280
+ function setCursor(g, i) {
27281
+ const n = g.frameUrls.length;
27282
+ cursor[g.key] = ((i % n) + n) % n;
27283
+ if (isSet(g)) playing = false;
27284
+ if (!isSet(g) && rows.get(g.key)) rows.get(g.key).drawn = -1;
27285
+ buildStage();
27286
+ refreshHeader();
27287
+ }
27288
+ function changed(g) { save(g); if (!inFilter(g)) buildList(); refresh(); }
27289
+
27290
+ function accept() {
27291
+ const g = group(currentKey);
27292
+ if (!g || statusOf(g) === 'rerolling') return;
27293
+ const s = st(g.key);
27294
+ const index = isSet(g) ? 0 : cur(g);
27295
+ if (s.chosen === index) { s.chosen = null; changed(g); return; }
27296
+ s.chosen = index;
27297
+ s.later = false;
27298
+ save(g);
27299
+ if (rows.get(g.key)) rows.get(g.key).drawn = -1;
27300
+ advance();
27301
+ }
27302
+ function flag() {
27303
+ const g = group(currentKey);
27304
+ if (!g) return;
27305
+ // A playing set flags the frame on screen, and holds it there.
27306
+ if (isSet(g) && playing) { cursor[g.key] = playIndex(g); playing = false; }
27307
+ const s = st(g.key);
27308
+ const i = cur(g);
27309
+ s.flagged =s.flagged.includes(i) ? s.flagged.filter((n) => n !== i) : s.flagged.concat(i).sort((a, b) => a - b);
27310
+ // A set with a bad frame is not accepted; a flagged candidate cannot be the choice.
27311
+ if (s.flagged.length && (isSet(g) || s.chosen === i)) s.chosen = null;
27312
+ changed(g);
27313
+ }
27314
+ function later() {
27315
+ const g = group(currentKey);
27316
+ if (!g) return;
27317
+ const s = st(g.key);
27318
+ s.later = !s.later;
27319
+ if (s.later) { s.chosen = null; save(g); advance(); } else changed(g);
27320
+ }
27321
+ async function reroll() {
27322
+ const g = group(currentKey);
27323
+ if (!g || !canReroll || statusOf(g) === 'rerolling') return;
27324
+ if (armedReroll !== g.key) {
27325
+ armedReroll = g.key;
27326
+ clearTimeout(armedTimer);
27327
+ armedTimer = setTimeout(() => { armedReroll = null; buildStage(); }, 4000);
27328
+ say('Rerolling spends credits. Press R again to regenerate ' + decode(g.assetId) + '.');
27329
+ buildStage();
27330
+ return;
27331
+ }
27332
+ armedReroll = null;
27333
+ clearTimeout(armedTimer);
27334
+ try {
27335
+ const res = await fetch(CONFIG.rerollUrl, {
27336
+ method: 'POST',
27337
+ headers: Object.assign({ 'Content-Type': 'application/json' }, CONFIG.headers),
27338
+ body: JSON.stringify({ key: g.key }),
27339
+ });
27340
+ if (!res.ok) throw new Error(await res.text());
27341
+ rerolls[g.key] = { state: 'running' };
27342
+ say('Rerolling ' + decode(g.assetId) + '. Keep reviewing; it comes back here when ready.');
27343
+ refresh();
27344
+ watch();
27345
+ } catch (err) {
27346
+ say('Reroll failed: ' + err.message, true);
27347
+ }
27348
+ }
27349
+ function batch(kind) {
27350
+ const shown = kind === 'select' ? visible() : GROUPS;
27351
+ let n = 0;
27352
+ for (const g of shown) {
27353
+ if (statusOf(g) === 'rerolling') continue;
27354
+ const s = st(g.key);
27355
+ if (kind === 'deselect') { if (s.chosen !== null) { s.chosen = null; save(g); n++; } continue; }
27356
+ if (s.chosen !== null) continue;
27357
+ if (kind === 'unflagged' && (s.flagged.length || s.later)) continue;
27358
+ if (isSet(g) && s.flagged.length) continue;
27359
+ const index = isSet(g) ? 0 : (s.flagged.includes(cur(g)) ? -1 : cur(g));
27360
+ if (index < 0) continue;
27361
+ s.chosen = index; s.later = false; save(g); n++;
27362
+ }
27363
+ say(kind === 'deselect' ? 'Cleared ' + n + ' acceptance' + (n === 1 ? '' : 's') : 'Accepted ' + n + ' asset' + (n === 1 ? '' : 's'));
27364
+ for (const r of rows.values()) r.drawn = -1;
27365
+ buildList();
27366
+ refresh();
27367
+ }
27368
+ function setFilter(id) {
27369
+ filter = id;
27370
+ buildList();
27371
+ const shown = visible();
27372
+ if (!shown.some((g) => g.key === currentKey)) currentKey = shown[0] ? shown[0].key : null;
27373
+ select(currentKey);
27374
+ }
27375
+
27376
+ async function apply() {
27377
+ if ($('apply').disabled) return;
27378
+ applying = true;
27379
+ refreshHeader();
27380
+ say('Applying…');
27381
+ const selections = GROUPS.filter((g) => st(g.key).chosen !== null).map((g) => ({ key: g.key, index: st(g.key).chosen }));
26934
27382
  try {
26935
- const res = await fetch(APPLY.url, {
26936
- method: 'POST', headers: { 'Content-Type': 'application/json', ...APPLY.headers },
27383
+ const res = await fetch(CONFIG.applyUrl, {
27384
+ method: 'POST',
27385
+ headers: Object.assign({ 'Content-Type': 'application/json' }, CONFIG.headers),
26937
27386
  body: JSON.stringify({ selections }),
26938
27387
  });
26939
27388
  if (!res.ok) throw new Error(await res.text());
26940
27389
  const result = await res.json();
26941
- status.textContent = APPLY.embedded ? 'applied' : 'done, you can close this tab';
26942
- document.body.style.opacity = '.6';
26943
- if (APPLY.embedded && window.parent !== window) {
27390
+ for (const g of GROUPS) { try { localStorage.removeItem(localKey(g)); } catch (e) { /* ignore */ } }
27391
+ say(CONFIG.embedded ? 'Applied ' + result.selected : 'Applied ' + result.selected + '. You can close this tab.');
27392
+ document.body.classList.add('done');
27393
+ if (CONFIG.embedded && window.parent !== window) {
26944
27394
  window.parent.postMessage({ type: 'pixelkiln:review-applied', result }, location.origin);
26945
27395
  }
26946
27396
  } catch (err) {
26947
- status.textContent = 'failed: ' + err.message;
26948
- btn.disabled = false;
27397
+ applying = false;
27398
+ say('Apply failed: ' + err.message, true);
27399
+ refreshHeader();
26949
27400
  }
26950
- };
26951
- </script>
26952
- </body>
26953
- </html>`;
26954
27401
  }
26955
27402
 
27403
+ // ---- server session --------------------------------------------------------
27404
+ let watching = null;
27405
+ async function sync() {
27406
+ if (!CONFIG.sessionUrl) return;
27407
+ const res = await fetch(CONFIG.sessionUrl, { headers: CONFIG.headers });
27408
+ if (!res.ok) throw new Error(await res.text());
27409
+ const data = await res.json();
27410
+ const before = new Map(GROUPS.map((g) => [g.key, g.reviewObjectId]));
27411
+ GROUPS = data.groups;
27412
+ canReroll = Boolean(data.canReroll && CONFIG.rerollUrl);
27413
+ rerolls = data.rerolls || {};
27414
+ for (const g of GROUPS) {
27415
+ const fresh = before.get(g.key) !== g.reviewObjectId;
27416
+ if (fresh) { delete cursor[g.key]; if (before.has(g.key)) say(decode(g.assetId) + ' is back with a new take.'); }
27417
+ state[g.key] = Object.assign(blank(), data.state[g.key] || {});
27418
+ }
27419
+ buildList();
27420
+ refresh();
27421
+ }
27422
+ function watch() {
27423
+ if (watching || !CONFIG.sessionUrl) return;
27424
+ watching = setInterval(async () => {
27425
+ try { await sync(); } catch (e) { /* the run may have ended */ }
27426
+ if (!Object.values(rerolls).some((r) => r.state === 'running')) { clearInterval(watching); watching = null; }
27427
+ }, 2000);
27428
+ }
27429
+
27430
+ // ---- keyboard --------------------------------------------------------------
27431
+ document.addEventListener('keydown', (e) => {
27432
+ if (document.body.classList.contains('done')) return;
27433
+ const onButton = e.target instanceof HTMLButtonElement && !e.target.closest('#list');
27434
+ if (onButton && (e.key === 'Enter' || e.key === ' ')) return;
27435
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { apply(); e.preventDefault(); return; }
27436
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
27437
+ const g = group(currentKey);
27438
+ const k = e.key;
27439
+ if (k === 'ArrowDown' || k === 'j') move(1);
27440
+ else if (k === 'ArrowUp' || k === 'k') move(-1);
27441
+ else if (k === 'Home') { const v = visible(); if (v[0]) select(v[0].key); }
27442
+ else if (k === 'End') { const v = visible(); if (v.length) select(v[v.length - 1].key); }
27443
+ else if ((k === 'ArrowRight' || k === 'ArrowLeft') && g) setCursor(g, cur(g) + (k === 'ArrowRight' ? 1 : -1));
27444
+ else if (k === ' ') togglePlay();
27445
+ else if (k === 'A' && e.shiftKey) batch('unflagged');
27446
+ else if (k === 'S' && e.shiftKey) batch('select');
27447
+ else if (k === 'D' && e.shiftKey) batch('deselect');
27448
+ else if (k === 'a' || k === 'Enter') accept();
27449
+ else if (k === 'f') flag();
27450
+ else if (k === 'l') later();
27451
+ else if (k === 'r') reroll();
27452
+ else if (k === 'x') { showStrip = !showStrip; buildStage(); }
27453
+ else if (k === 'c' && g) { flipped = (flipped + 1) % views(g).length; buildStage(); }
27454
+ else if (k === 'o') { onion = !onion; buildStage(); }
27455
+ else if (k === 'p') { pingpong = !pingpong; buildStage(); }
27456
+ else if (/^[1-5]$/.test(k)) setFilter(FILTERS[Number(k) - 1][0]);
27457
+ else if (k === 'Escape' && armedReroll) { armedReroll = null; say(''); buildStage(); }
27458
+ else return;
27459
+ e.preventDefault();
27460
+ });
27461
+
27462
+ const press = (id, fn) => $(id).addEventListener('click', (e) => { fn(); e.currentTarget.blur(); });
27463
+ press('a-accept', accept);
27464
+ press('a-flag', flag);
27465
+ press('a-later', later);
27466
+ press('a-reroll', reroll);
27467
+ press('t-play', togglePlay);
27468
+ press('t-flip', () => { const g = group(currentKey); if (g) { flipped = (flipped + 1) % views(g).length; buildStage(); } });
27469
+ press('t-strip', () => { showStrip = !showStrip; buildStage(); });
27470
+ press('t-onion', () => { onion = !onion; buildStage(); });
27471
+ press('t-pong', () => { pingpong = !pingpong; buildStage(); });
27472
+ press('select-all', () => batch('select'));
27473
+ press('deselect-all', () => batch('deselect'));
27474
+ press('accept-unflagged', () => batch('unflagged'));
27475
+ press('apply', apply);
27476
+ window.addEventListener('resize', () => { dirty = true; });
27477
+ document.addEventListener('visibilitychange', () => { lastTick = 0; });
27478
+
27479
+ // ---- boot ------------------------------------------------------------------
27480
+ for (const g of GROUPS) recall(g);
27481
+ buildFilters();
27482
+ buildList();
27483
+ refresh();
27484
+ list.focus({ preventScroll: true });
27485
+ requestAnimationFrame(tick);
27486
+ if (CONFIG.sessionUrl) {
27487
+ sync().then(() => { if (Object.values(rerolls).some((r) => r.state === 'running')) watch(); })
27488
+ .catch((err) => say('Could not load saved selections: ' + err.message, true));
27489
+ }
27490
+ `;
27491
+
26956
27492
  // src/pick/server.ts
26957
27493
  async function currentArt(entry, spec) {
26958
27494
  if (!spec || !entry.supersededOutputs?.length) return null;
@@ -27036,11 +27572,11 @@ async function prepareReview(provider, lock, opts = {}) {
27036
27572
  continue;
27037
27573
  }
27038
27574
  frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile33(cached2.path).catch(() => Buffer.alloc(0))) : null);
27039
- const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
27575
+ const route = `${prefix}/review-frame/${encodeURIComponent(String((opts.routeBase ?? 0) + groups.length))}/${index}`;
27040
27576
  frameAssets.push([route, cached2]);
27041
27577
  frameUrls.push(route);
27042
27578
  }
27043
- const sourceRoute = spec?.revision ? `${prefix}/revision-source/${encodeURIComponent(String(groups.length))}` : null;
27579
+ const sourceRoute = spec?.revision ? `${prefix}/revision-source/${encodeURIComponent(String((opts.routeBase ?? 0) + groups.length))}` : null;
27044
27580
  if (sourceRoute && spec?.revision) {
27045
27581
  reviewAssets.set(sourceRoute, {
27046
27582
  path: spec.revision.sourceFile,
@@ -27048,7 +27584,7 @@ async function prepareReview(provider, lock, opts = {}) {
27048
27584
  });
27049
27585
  }
27050
27586
  const current = await currentArt(entry, spec);
27051
- const currentRoute = current ? `${prefix}/current-art/${encodeURIComponent(String(groups.length))}` : null;
27587
+ const currentRoute = current ? `${prefix}/current-art/${encodeURIComponent(String((opts.routeBase ?? 0) + groups.length))}` : null;
27052
27588
  if (current && currentRoute) {
27053
27589
  reviewAssets.set(currentRoute, { path: current.path, contentType: current.contentType });
27054
27590
  }
@@ -27199,6 +27735,130 @@ async function prepareReview(provider, lock, opts = {}) {
27199
27735
  }
27200
27736
  };
27201
27737
  }
27738
+ function createReviewHost(provider, lock, lockPath, first, opts = {}) {
27739
+ const log2 = opts.onProgress ?? (() => {
27740
+ });
27741
+ const statePath = reviewStatePathFor(lockPath);
27742
+ let groups = [...first.groups];
27743
+ const owner = new Map(groups.map((g) => [g.key, first]));
27744
+ const assets = new Map(first.assets);
27745
+ const memory = /* @__PURE__ */ new Map();
27746
+ const rerolls = /* @__PURE__ */ new Map();
27747
+ const running = /* @__PURE__ */ new Set();
27748
+ let nextRoute = groups.length;
27749
+ const readState = async () => {
27750
+ const saved = (await loadReviewState(statePath)).assets;
27751
+ const out = {};
27752
+ for (const g of groups) {
27753
+ const record = saved[g.key];
27754
+ out[g.key] = record && record.jobId === g.reviewObjectId && record.status === "pending" ? { chosen: record.chosen, flagged: record.flagged ?? [], later: record.later ?? false } : memory.get(g.key) ?? { chosen: null, flagged: [], later: false };
27755
+ }
27756
+ return out;
27757
+ };
27758
+ const writeState = async (body) => {
27759
+ const { key: key3, chosen, flagged, later } = body ?? {};
27760
+ const group = groups.find((g) => g.key === key3);
27761
+ if (!group) throw new Error(`${String(key3)} is not on this review page`);
27762
+ const count = group.frameUrls.length;
27763
+ const index = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0 && n < count;
27764
+ if (chosen !== null && chosen !== void 0 && !index(chosen)) throw new Error(`chosen must be a candidate index below ${count}`);
27765
+ if (flagged !== void 0 && (!Array.isArray(flagged) || !flagged.every(index))) throw new Error("flagged must list frame indexes");
27766
+ const next = {
27767
+ chosen: chosen ?? null,
27768
+ flagged: [...new Set(flagged ?? [])].sort((a, b) => a - b),
27769
+ later: later === true
27770
+ };
27771
+ const saved = await updateReviewAsset(
27772
+ statePath,
27773
+ group.key,
27774
+ (asset) => asset.jobId !== group.reviewObjectId ? asset : {
27775
+ ...asset,
27776
+ chosen: next.chosen,
27777
+ ...next.flagged.length ? { flagged: next.flagged } : { flagged: void 0 },
27778
+ ...next.later ? { later: true } : { later: void 0 }
27779
+ }
27780
+ );
27781
+ if (!saved || saved.jobId !== group.reviewObjectId) memory.set(group.key, next);
27782
+ return next;
27783
+ };
27784
+ const startReroll = (key3) => {
27785
+ if (!opts.reroll) throw new Error("this review page cannot reroll; run gen --force for the asset");
27786
+ if (!groups.some((g) => g.key === key3)) throw new Error(`${key3} is not on this review page`);
27787
+ if (rerolls.get(key3)?.state === "running") return;
27788
+ rerolls.set(key3, { state: "running" });
27789
+ log2(` rerolling ${key3} (--force)\u2026`);
27790
+ const job = (async () => {
27791
+ await opts.reroll(key3);
27792
+ const session = await prepareReview(provider, lock, {
27793
+ keys: [key3],
27794
+ specs: opts.specs,
27795
+ onProgress: log2,
27796
+ lockPath,
27797
+ routeBase: nextRoute
27798
+ });
27799
+ const fresh = session?.groups.find((g) => g.key === key3);
27800
+ if (!session || !fresh) throw new Error(`${key3} did not come back into review`);
27801
+ nextRoute += session.groups.length;
27802
+ for (const [route, asset] of session.assets) assets.set(route, asset);
27803
+ groups = groups.map((g) => g.key === key3 ? fresh : g);
27804
+ owner.set(key3, session);
27805
+ memory.delete(key3);
27806
+ rerolls.delete(key3);
27807
+ log2(` ${key3}: new candidate ready on the review page`);
27808
+ })().catch((err) => {
27809
+ const message6 = err instanceof Error ? err.message : String(err);
27810
+ rerolls.set(key3, { state: "failed", error: message6 });
27811
+ log2(` reroll ${key3} failed: ${message6}`);
27812
+ });
27813
+ running.add(job);
27814
+ void job.finally(() => running.delete(job));
27815
+ };
27816
+ return {
27817
+ groups: () => groups,
27818
+ assets,
27819
+ html: () => renderSheet(groups, { sessionUrl: "/session", stateUrl: "/state", rerollUrl: opts.reroll ? "/reroll" : void 0 }),
27820
+ async apply(body) {
27821
+ if ([...rerolls.values()].some((r) => r.state === "running")) {
27822
+ throw new Error("a reroll is still running; apply once it is back");
27823
+ }
27824
+ const { selections } = body ?? {};
27825
+ if (!Array.isArray(selections)) throw new Error("selections must be a list");
27826
+ const bySession = /* @__PURE__ */ new Map();
27827
+ for (const selection of selections) {
27828
+ const session = owner.get(selection?.key);
27829
+ if (!session) continue;
27830
+ bySession.set(session, [...bySession.get(session) ?? [], selection]);
27831
+ }
27832
+ let selected = 0;
27833
+ for (const [session, picks] of bySession) selected += (await session.apply({ selections: picks }, lockPath)).selected;
27834
+ return { selected, skipped: groups.length - selected };
27835
+ },
27836
+ async handleRequest(method, url, body) {
27837
+ if (method === "GET" && url === "/session") {
27838
+ return {
27839
+ status: 200,
27840
+ body: {
27841
+ groups: renderableGroups(groups),
27842
+ state: await readState(),
27843
+ rerolls: Object.fromEntries(rerolls),
27844
+ canReroll: Boolean(opts.reroll)
27845
+ }
27846
+ };
27847
+ }
27848
+ if (method === "POST" && url === "/state") return { status: 200, body: await writeState(body) };
27849
+ if (method === "POST" && url === "/reroll") {
27850
+ const key3 = body?.key;
27851
+ if (typeof key3 !== "string") throw new Error("key is required");
27852
+ startReroll(key3);
27853
+ return { status: 202, body: { key: key3, ...rerolls.get(key3) } };
27854
+ }
27855
+ return void 0;
27856
+ },
27857
+ async idle() {
27858
+ while (running.size) await Promise.all([...running]);
27859
+ }
27860
+ };
27861
+ }
27202
27862
  async function runPicker(provider, lock, lockPath, opts = {}) {
27203
27863
  const log2 = opts.onProgress ?? (() => {
27204
27864
  });
@@ -27217,30 +27877,34 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
27217
27877
  autoSelected = res.selected;
27218
27878
  log2(` --yes: accepted ${res.selected} single-candidate asset(s)`);
27219
27879
  const rest = session.groups.filter((g) => !singles.includes(g)).map((g) => g.key);
27220
- session = rest.length ? await prepareReview(provider, lock, { onProgress: log2, keys: rest, specs: opts.specs }) : null;
27880
+ session = rest.length ? await prepareReview(provider, lock, { onProgress: log2, keys: rest, specs: opts.specs, lockPath }) : null;
27221
27881
  if (!session) return { selected: autoSelected, skipped: 0 };
27222
27882
  }
27223
27883
  }
27224
- const live = session;
27225
- const groups = live.groups;
27884
+ const host = createReviewHost(provider, lock, lockPath, session, {
27885
+ specs: opts.specs,
27886
+ onProgress: log2,
27887
+ reroll: opts.reroll
27888
+ });
27226
27889
  const served = await serveReviewPage({
27227
- html: live.html(),
27890
+ html: host.html,
27228
27891
  port: opts.port,
27229
27892
  open: opts.open,
27230
27893
  onProgress: log2,
27231
- assets: live.assets,
27894
+ assets: host.assets,
27895
+ handleRequest: host.handleRequest,
27232
27896
  onReady: (url) => {
27233
- const info = { url, keys: groups.map((group) => group.key) };
27897
+ const info = { url, keys: host.groups().map((group) => group.key) };
27234
27898
  if (opts.onReady) {
27235
27899
  opts.onReady(info);
27236
27900
  } else {
27237
27901
  log2(`
27238
- ${groups.length} asset(s) awaiting selection: ${url}`);
27902
+ ${info.keys.length} asset(s) awaiting selection: ${url}`);
27239
27903
  log2(` (leave this running; it exits once you apply)
27240
27904
  `);
27241
27905
  }
27242
27906
  },
27243
- handleApply: (body) => live.apply(body, lockPath)
27907
+ handleApply: host.apply
27244
27908
  });
27245
27909
  return { selected: served.selected + autoSelected, skipped: served.skipped };
27246
27910
  }
@@ -28231,6 +28895,30 @@ async function runLifecycle(args, wave, spent) {
28231
28895
  onProgress: log,
28232
28896
  onReady: announceReviewReady,
28233
28897
  autoAcceptSingle: args.yes,
28898
+ // A reroll from the page is `gen --force` for that one asset, inside
28899
+ // this run: same plan, same budget ceiling, same submit and poll.
28900
+ reroll: args.command === "gen" ? async (key3) => {
28901
+ const spec = providerSpecsForRun.find((s) => lockKey(s.styleId, s.assetId) === key3);
28902
+ if (!spec) throw new Error(`${key3} is not part of this run`);
28903
+ const plan2 = await buildPlan([spec], lock, { force: true });
28904
+ if (!plan2.actionable.length) throw new Error(`${key3} cannot be regenerated: ${plan2.items[0]?.reason ?? "not actionable"}`);
28905
+ const budgets = budgetsForPlan(plan2, remainingBudgets(args, spent));
28906
+ for (const group of plan2.groups) {
28907
+ const ceiling = budgets.get(group.provider);
28908
+ if (ceiling !== void 0 && group.cost > ceiling) {
28909
+ throw new BudgetError(`${key3} would spend ${formatCost(group.costUnit, group.cost)} but only ${formatCost(group.costUnit, ceiling)} of the budget is left`);
28910
+ }
28911
+ const res2 = await submit(providerFor(group.provider), loaded, group.actionable, lock, args.lock, {
28912
+ budget: ceiling,
28913
+ onProgress: log
28914
+ });
28915
+ spent.set(group.provider, (spent.get(group.provider) ?? 0) + res2.spent);
28916
+ if (res2.failed) throw new Error(`${key3}: the provider refused the resubmission`);
28917
+ }
28918
+ await poll(providerFor(providerId), lock, args.lock, { onProgress: log, specs: [spec] });
28919
+ const status = lock.entries[key3]?.status;
28920
+ if (status !== "review") throw new Error(`${key3} finished as ${status ?? "missing"}, not in review`);
28921
+ } : void 0,
28234
28922
  keys: providerSpecsForRun.map((spec) => lockKey(spec.styleId, spec.assetId)),
28235
28923
  specs: providerSpecsForRun
28236
28924
  });
@@ -33645,17 +34333,17 @@ async function runPlan2(args) {
33645
34333
  }
33646
34334
  loadKeys5(args);
33647
34335
  const plan = await planLipSync(clientFromEnv(), text, { ...source, mood, visemeCount: count }, { frameMs: args.frameMs, holdMs: args.holdMs });
33648
- const json = `${JSON.stringify(plan, null, 2)}
34336
+ const json2 = `${JSON.stringify(plan, null, 2)}
33649
34337
  `;
33650
34338
  if (!args.out) {
33651
- log(json.trimEnd());
34339
+ log(json2.trimEnd());
33652
34340
  return;
33653
34341
  }
33654
34342
  const out = path66.extname(args.out) ? path66.resolve(args.out) : path66.resolve(`${args.out}.json`);
33655
34343
  if (existsSync53(out) && !args.force) throw new Error(`${out} already exists; pass --force to replace it`);
33656
34344
  await mkdir25(path66.dirname(out), { recursive: true });
33657
- await writeFile30(out, json);
33658
- if (args.json) log(json.trimEnd());
34345
+ await writeFile30(out, json2);
34346
+ if (args.json) log(json2.trimEnd());
33659
34347
  else log(` wrote ${out} (${plan.frames.length} frames, ${(plan.totalMs / 1e3).toFixed(2)} s, free)`);
33660
34348
  }
33661
34349
  async function runTalk(args) {
@@ -35143,13 +35831,13 @@ async function runEstimateSkeleton(args) {
35143
35831
  image: { base64: bytes.toString("base64"), format: metadata.format }
35144
35832
  });
35145
35833
  const frames = args.frames ?? DEFAULT_SCAFFOLD_FRAMES;
35146
- const json = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames), null, 2);
35834
+ const json2 = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames), null, 2);
35147
35835
  if (args.out) {
35148
- await writeFile32(path75.resolve(args.out), json + "\n");
35836
+ await writeFile32(path75.resolve(args.out), json2 + "\n");
35149
35837
  log(` wrote ${args.out}: the estimated pose and ${frames} frames to edit`);
35150
35838
  log(` preview it with: pixelkiln skeleton-preview ${args.out} --from ${image}`);
35151
35839
  } else {
35152
- log(json);
35840
+ log(json2);
35153
35841
  }
35154
35842
  }
35155
35843
  var VIEWS = ["side", "low top-down", "high top-down"];
@@ -35177,15 +35865,15 @@ async function estimateCustom(args, image, bytes, metadata) {
35177
35865
  ...args.action ? { action: args.action } : {}
35178
35866
  });
35179
35867
  const frames = args.frames ?? DEFAULT_SCAFFOLD_FRAMES;
35180
- const json = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames, { rig: res.rig, kind: res.kind }), null, 2);
35868
+ const json2 = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames, { rig: res.rig, kind: res.kind }), null, 2);
35181
35869
  const extra = res.rig.filter((joint) => !joint.estimate).map((joint) => joint.name);
35182
35870
  if (args.out) {
35183
- await writeFile32(path75.resolve(args.out), json + "\n");
35871
+ await writeFile32(path75.resolve(args.out), json2 + "\n");
35184
35872
  log(` wrote ${args.out}: a ${res.kind ?? "custom"} rig of ${res.rig.length} joints and ${frames} frames to edit`);
35185
35873
  if (extra.length) log(` joints beyond the 18: ${extra.slice(0, 12).join(", ")}${extra.length > 12 ? ", \u2026" : ""}`);
35186
35874
  log(` preview it with: pixelkiln skeleton-preview ${args.out} --from ${image}`);
35187
35875
  } else {
35188
- log(json);
35876
+ log(json2);
35189
35877
  }
35190
35878
  }
35191
35879
  async function runSkeletonPreview(args) {
@@ -35211,13 +35899,13 @@ async function runSkeletonPreview(args) {
35211
35899
  label = `${spec.styleId}/${spec.assetId}`;
35212
35900
  }
35213
35901
  if (!existsSync57(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
35214
- let json;
35902
+ let json2;
35215
35903
  try {
35216
- json = JSON.parse(await readFile51(keypointsFile, "utf8"));
35904
+ json2 = JSON.parse(await readFile51(keypointsFile, "utf8"));
35217
35905
  } catch (error) {
35218
35906
  throw new UsageError(`${keypointsFile} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
35219
35907
  }
35220
- const set = parseSkeletonSet(json, keypointsFile);
35908
+ const set = parseSkeletonSet(json2, keypointsFile);
35221
35909
  let source;
35222
35910
  if (sourceFile) {
35223
35911
  if (!existsSync57(sourceFile)) {