pixelkiln 0.113.0 → 0.115.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/index.cjs CHANGED
@@ -11,9 +11,9 @@ var __export = (target, all) => {
11
11
  };
12
12
  var __copyProps = (to, from, except, desc) => {
13
13
  if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key2 of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key2) && key2 !== except)
16
- __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
14
+ for (let key3 of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key3) && key3 !== except)
16
+ __defProp(to, key3, { get: () => from[key3], enumerable: !(desc = __getOwnPropDesc(from, key3)) || desc.enumerable });
17
17
  }
18
18
  return to;
19
19
  };
@@ -239,6 +239,7 @@ __export(index_exports, {
239
239
  expandObject: () => expandObject,
240
240
  expectedOutputPath: () => expectedOutputPath,
241
241
  exportAssetFile: () => exportAssetFile,
242
+ exportMergedTilesets: () => exportMergedTilesets,
242
243
  exportOutPath: () => exportOutPath,
243
244
  exportTileset: () => exportTileset,
244
245
  fallbackOutputRole: () => fallbackOutputRole,
@@ -448,9 +449,11 @@ __export(index_exports, {
448
449
  summarize: () => summarize,
449
450
  tagAdopted: () => tagAdopted,
450
451
  targetPaletteBody: () => targetPaletteBody,
452
+ terrainColor: () => terrainColor,
451
453
  terrainCost: () => terrainCost,
452
454
  terrainSettings: () => terrainSettings,
453
455
  terrainTileCount: () => terrainTileCount,
456
+ tileCorners: () => tileCorners,
454
457
  tileFeatureOutputCount: () => tileFeatureOutputCount,
455
458
  tileVariationCount: () => tileVariationCount,
456
459
  tilesCost: () => tilesCost,
@@ -776,24 +779,24 @@ var AssetVfxSchema = import_zod.z.object({
776
779
  spriteFrames: import_zod.z.number().int().min(1).max(32).optional(),
777
780
  spriteFps: import_zod.z.number().int().min(1).max(60).optional()
778
781
  }).strict().superRefine((vfx, context) => {
779
- for (const key2 of ["spriteFrames", "spriteFps"]) {
780
- if (vfx[key2] === void 0) continue;
782
+ for (const key3 of ["spriteFrames", "spriteFps"]) {
783
+ if (vfx[key3] === void 0) continue;
781
784
  if (vfx.description === void 0) {
782
- context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key2} describes the sprite sent to PixelLab's VFX artist; add a description`, path: [key2] });
785
+ context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key3} describes the sprite sent to PixelLab's VFX artist; add a description`, path: [key3] });
783
786
  } else if (!vfx.sprite) {
784
- context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key2} describes a sprite strip; add a sprite`, path: [key2] });
787
+ context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key3} describes a sprite strip; add a sprite`, path: [key3] });
785
788
  }
786
789
  }
787
790
  if (vfx.spriteFps !== void 0 && vfx.sprite && vfx.description !== void 0 && (vfx.spriteFrames ?? 1) < 2) {
788
791
  context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: "spriteFps is the speed of a sprite strip; set spriteFrames to 2 or more", path: ["spriteFps"] });
789
792
  }
790
793
  if (vfx.description !== void 0) {
791
- for (const key2 of ["preset", "recipe", "parts", "fps"]) {
792
- if (vfx[key2] !== void 0) {
794
+ for (const key3 of ["preset", "recipe", "parts", "fps"]) {
795
+ if (vfx[key3] !== void 0) {
793
796
  context.addIssue({
794
797
  code: import_zod.z.ZodIssueCode.custom,
795
- message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key2}; use a description or the workbench's preset/recipe/parts/fps, not both`,
796
- path: [key2]
798
+ message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key3}; use a description or the workbench's preset/recipe/parts/fps, not both`,
799
+ path: [key3]
797
800
  });
798
801
  }
799
802
  }
@@ -1041,18 +1044,18 @@ var CharacterAnimationSchema = import_zod.z.object({
1041
1044
  context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: "a skeleton-v3 loop from a sentence takes 3 to 15 frames", path: ["frames"] });
1042
1045
  }
1043
1046
  const mode2 = animation.mode ?? (animation.template ? "template" : "v3");
1044
- for (const key2 of ["startFrame", "endFrame", "enhancePrompt"]) {
1045
- if (animation[key2] !== void 0 && mode2 !== "v3") {
1047
+ for (const key3 of ["startFrame", "endFrame", "enhancePrompt"]) {
1048
+ if (animation[key3] !== void 0 && mode2 !== "v3") {
1046
1049
  context.addIssue({
1047
1050
  code: import_zod.z.ZodIssueCode.custom,
1048
- message: `${key2} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
1049
- path: [key2]
1051
+ message: `${key3} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
1052
+ path: [key3]
1050
1053
  });
1051
1054
  }
1052
1055
  }
1053
- for (const key2 of ["outline", "shading", "detail"]) {
1054
- if (animation[key2] !== void 0 && mode2 !== "template") {
1055
- context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key2} overrides apply to template loops only`, path: [key2] });
1056
+ for (const key3 of ["outline", "shading", "detail"]) {
1057
+ if (animation[key3] !== void 0 && mode2 !== "template") {
1058
+ context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key3} overrides apply to template loops only`, path: [key3] });
1056
1059
  }
1057
1060
  }
1058
1061
  if (animation.template && animation.mode && animation.mode !== "template" && animation.mode !== "skeleton-v3") {
@@ -4914,13 +4917,13 @@ var PixelLabClient = class {
4914
4917
  }
4915
4918
  };
4916
4919
  function clientFromEnv() {
4917
- const key2 = process.env.PIXELLAB_API_KEY;
4918
- if (!key2) {
4920
+ const key3 = process.env.PIXELLAB_API_KEY;
4921
+ if (!key3) {
4919
4922
  throw new Error(
4920
4923
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
4921
4924
  );
4922
4925
  }
4923
- return new PixelLabClient(key2);
4926
+ return new PixelLabClient(key3);
4924
4927
  }
4925
4928
 
4926
4929
  // src/open.ts
@@ -5260,14 +5263,14 @@ function extractPalette(png, topN = 8, alphaThreshold = 128) {
5260
5263
  const alpha = png.pixels[i + 3];
5261
5264
  if (alpha < alphaThreshold) continue;
5262
5265
  opaque2++;
5263
- const key2 = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
5264
- counts.set(key2, (counts.get(key2) ?? 0) + 1);
5266
+ const key3 = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
5267
+ counts.set(key3, (counts.get(key3) ?? 0) + 1);
5265
5268
  }
5266
5269
  if (opaque2 === 0) return [];
5267
- return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key2, n]) => ({
5268
- r: key2 >> 16 & 255,
5269
- g: key2 >> 8 & 255,
5270
- b: key2 & 255,
5270
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key3, n]) => ({
5271
+ r: key3 >> 16 & 255,
5272
+ g: key3 >> 8 & 255,
5273
+ b: key3 & 255,
5271
5274
  weight: n / opaque2
5272
5275
  }));
5273
5276
  }
@@ -5896,13 +5899,13 @@ var PixelLabMcpClient = class {
5896
5899
  }
5897
5900
  };
5898
5901
  function mcpClientFromEnv() {
5899
- const key2 = process.env.PIXELLAB_API_KEY;
5900
- if (!key2) {
5902
+ const key3 = process.env.PIXELLAB_API_KEY;
5903
+ if (!key3) {
5901
5904
  throw new Error(
5902
5905
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
5903
5906
  );
5904
5907
  }
5905
- return new PixelLabMcpClient(key2);
5908
+ return new PixelLabMcpClient(key3);
5906
5909
  }
5907
5910
 
5908
5911
  // src/pixellab-vfx.ts
@@ -6223,27 +6226,27 @@ function vfxArtistFiles(raw) {
6223
6226
  const urlOf = (value) => {
6224
6227
  if (typeof value === "string") return /^https?:\/\//i.test(value) ? value : null;
6225
6228
  if (!value || typeof value !== "object") return null;
6226
- for (const key2 of ["url", "download_url", "href"]) {
6227
- const url = value[key2];
6229
+ for (const key3 of ["url", "download_url", "href"]) {
6230
+ const url = value[key3];
6228
6231
  if (typeof url === "string" && /^https?:\/\//i.test(url)) return url;
6229
6232
  }
6230
6233
  return null;
6231
6234
  };
6232
- const nameOf = (value, url, key2) => {
6235
+ const nameOf = (value, url, key3) => {
6233
6236
  if (value && typeof value === "object") {
6234
6237
  for (const field of ["name", "filename", "file"]) {
6235
6238
  const name = value[field];
6236
6239
  if (typeof name === "string" && name) return name;
6237
6240
  }
6238
6241
  }
6239
- if (key2 && /\.[a-z0-9]+$/i.test(key2)) return key2;
6242
+ if (key3 && /\.[a-z0-9]+$/i.test(key3)) return key3;
6240
6243
  return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
6241
6244
  };
6242
6245
  const entries = Array.isArray(raw) ? raw.map((value) => [void 0, value]) : raw && typeof raw === "object" ? Object.entries(raw) : [];
6243
6246
  const files = [];
6244
- for (const [key2, value] of entries) {
6247
+ for (const [key3, value] of entries) {
6245
6248
  const url = urlOf(value);
6246
- if (url) files.push({ name: nameOf(value, url, key2), url });
6249
+ if (url) files.push({ name: nameOf(value, url, key3), url });
6247
6250
  }
6248
6251
  return files;
6249
6252
  }
@@ -6346,14 +6349,14 @@ async function makeVfxWithArtist(client2, opts) {
6346
6349
  `);
6347
6350
  written.atlas = paths.atlas;
6348
6351
  }
6349
- for (const [file, target, key2] of [
6352
+ for (const [file, target, key3] of [
6350
6353
  [result.gif, paths.gif, "gif"],
6351
6354
  [result.gamePack, paths.gamePack, "gamePack"],
6352
6355
  [result.normals, paths.normals, "normals"]
6353
6356
  ]) {
6354
6357
  if (!file) continue;
6355
6358
  await (0, import_promises.writeFile)(target, await client2.download(file.url));
6356
- written[key2] = target;
6359
+ written[key3] = target;
6357
6360
  }
6358
6361
  const facts = vfxArtistFrameFacts(result, atlas);
6359
6362
  const usage = job.usage ?? null;
@@ -6379,7 +6382,7 @@ async function makeVfxWithArtist(client2, opts) {
6379
6382
  anchor: result.anchor,
6380
6383
  parts: result.parts,
6381
6384
  files: Object.fromEntries(
6382
- ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key2) => written[key2]).map((key2) => [key2, import_node_path.default.basename(written[key2])])
6385
+ ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key3) => written[key3]).map((key3) => [key3, import_node_path.default.basename(written[key3])])
6383
6386
  ),
6384
6387
  quotedGenerations: submitted.quoted_generations ?? null,
6385
6388
  usage,
@@ -6404,8 +6407,8 @@ async function makeVfxWithArtist(client2, opts) {
6404
6407
  };
6405
6408
  }
6406
6409
  function vfxJobFailure(done) {
6407
- for (const key2 of ["error", "detail", "message"]) {
6408
- const value = done?.[key2];
6410
+ for (const key3 of ["error", "detail", "message"]) {
6411
+ const value = done?.[key3];
6409
6412
  if (typeof value === "string" && value) return `: ${value}`;
6410
6413
  }
6411
6414
  return "";
@@ -6440,8 +6443,8 @@ function isSensitiveSourceUrl(value) {
6440
6443
  return false;
6441
6444
  }
6442
6445
  if (parsed.username || parsed.password) return true;
6443
- for (const key2 of parsed.searchParams.keys()) {
6444
- const normalized = key2.toLowerCase();
6446
+ for (const key3 of parsed.searchParams.keys()) {
6447
+ const normalized = key3.toLowerCase();
6445
6448
  if (SENSITIVE_QUERY_KEYS.has(normalized) || normalized.includes("credential") || normalized.includes("signature") || normalized.includes("security-token") || normalized.includes("token")) return true;
6446
6449
  }
6447
6450
  return false;
@@ -6899,7 +6902,7 @@ var DEFAULT_KEY = "#00ffff";
6899
6902
  var KEY_SATURATION = 0.85;
6900
6903
  function keySkin(png, options = {}) {
6901
6904
  const image = decodePng(png);
6902
- const key2 = parseHex(options.key ?? DEFAULT_KEY);
6905
+ const key3 = parseHex(options.key ?? DEFAULT_KEY);
6903
6906
  const skin = options.skin?.map((hex2) => parseHex(hex2));
6904
6907
  const reach = (options.tolerance ?? 0) ** 2;
6905
6908
  const outlineBelow = options.outlineBelow ?? 46;
@@ -6914,14 +6917,14 @@ function keySkin(png, options = {}) {
6914
6917
  if (!skin.some((c) => (c.r - r) ** 2 + (c.g - g) ** 2 + (c.b - b) ** 2 <= reach)) continue;
6915
6918
  } else if (brightest < outlineBelow) continue;
6916
6919
  const tint = (channel) => Math.floor(brightest * (1 - KEY_SATURATION + KEY_SATURATION * channel / 255));
6917
- out[i] = tint(key2.r);
6918
- out[i + 1] = tint(key2.g);
6919
- out[i + 2] = tint(key2.b);
6920
+ out[i] = tint(key3.r);
6921
+ out[i + 1] = tint(key3.g);
6922
+ out[i + 2] = tint(key3.b);
6920
6923
  }
6921
6924
  return encodeRgbaPng(image.width, image.height, out);
6922
6925
  }
6923
- function isKeyColor(r, g, b, key2 = DEFAULT_KEY) {
6924
- const target = parseHex(key2);
6926
+ function isKeyColor(r, g, b, key3 = DEFAULT_KEY) {
6927
+ const target = parseHex(key3);
6925
6928
  const want = hsv(target.r, target.g, target.b).h;
6926
6929
  const { h, s, v } = hsv(r, g, b);
6927
6930
  const apart = Math.abs(h - want);
@@ -7524,22 +7527,22 @@ async function writeLockWhileHeld(file, lock) {
7524
7527
  }
7525
7528
  const dirty = dirtyPatches.get(lock) ?? /* @__PURE__ */ new Map();
7526
7529
  const snapshot = /* @__PURE__ */ new Map();
7527
- for (const [key2, patch] of dirty) snapshot.set(key2, { ...patch });
7530
+ for (const [key3, patch] of dirty) snapshot.set(key3, { ...patch });
7528
7531
  const merged = { ...disk.entries };
7529
- for (const [key2, patch] of snapshot) {
7530
- const local = lock.entries[key2];
7532
+ for (const [key3, patch] of snapshot) {
7533
+ const local = lock.entries[key3];
7531
7534
  if (!local) continue;
7532
- merged[key2] = merged[key2] ? { ...merged[key2], ...patch } : local;
7535
+ merged[key3] = merged[key3] ? { ...merged[key3], ...patch } : local;
7533
7536
  }
7534
- for (const [key2, entry] of Object.entries(lock.entries)) {
7535
- if (!merged[key2]) merged[key2] = entry;
7537
+ for (const [key3, entry] of Object.entries(lock.entries)) {
7538
+ if (!merged[key3]) merged[key3] = entry;
7536
7539
  }
7537
7540
  const deletes = dirtyDeletes.get(lock);
7538
7541
  const deleteSnapshot = deletes ? new Set(deletes) : /* @__PURE__ */ new Set();
7539
- for (const key2 of deleteSnapshot) delete merged[key2];
7542
+ for (const key3 of deleteSnapshot) delete merged[key3];
7540
7543
  const sorted = {};
7541
- for (const key2 of Object.keys(merged).sort()) {
7542
- sorted[key2] = merged[key2];
7544
+ for (const key3 of Object.keys(merged).sort()) {
7545
+ sorted[key3] = merged[key3];
7543
7546
  }
7544
7547
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
7545
7548
  try {
@@ -7550,48 +7553,48 @@ async function writeLockWhileHeld(file, lock) {
7550
7553
  }
7551
7554
  const currentDirty = dirtyPatches.get(lock);
7552
7555
  if (currentDirty) {
7553
- for (const [key2, patch] of snapshot) {
7554
- const current = currentDirty.get(key2);
7556
+ for (const [key3, patch] of snapshot) {
7557
+ const current = currentDirty.get(key3);
7555
7558
  if (!current) continue;
7556
7559
  for (const [field, value] of Object.entries(patch)) {
7557
7560
  if (Object.is(current[field], value)) {
7558
7561
  delete current[field];
7559
7562
  }
7560
7563
  }
7561
- if (Object.keys(current).length === 0) currentDirty.delete(key2);
7564
+ if (Object.keys(current).length === 0) currentDirty.delete(key3);
7562
7565
  }
7563
7566
  }
7564
7567
  const stillDirty = dirtyDeletes.get(lock);
7565
7568
  if (stillDirty) {
7566
- for (const key2 of deleteSnapshot) stillDirty.delete(key2);
7569
+ for (const key3 of deleteSnapshot) stillDirty.delete(key3);
7567
7570
  if (stillDirty.size === 0) dirtyDeletes.delete(lock);
7568
7571
  }
7569
7572
  const localAfterWrite = lock.entries;
7570
7573
  lock.entries = { ...merged };
7571
- for (const [key2, patch] of currentDirty ?? []) {
7572
- const base = lock.entries[key2] ?? localAfterWrite[key2];
7573
- if (base) lock.entries[key2] = { ...base, ...patch };
7574
+ for (const [key3, patch] of currentDirty ?? []) {
7575
+ const base = lock.entries[key3] ?? localAfterWrite[key3];
7576
+ if (base) lock.entries[key3] = { ...base, ...patch };
7574
7577
  }
7575
7578
  }
7576
- function upsert(lock, key2, patch) {
7577
- dirtyDeletes.get(lock)?.delete(key2);
7578
- const existing = lock.entries[key2];
7579
+ function upsert(lock, key3, patch) {
7580
+ dirtyDeletes.get(lock)?.delete(key3);
7581
+ const existing = lock.entries[key3];
7579
7582
  const next = { ...existing, ...patch };
7580
- lock.entries[key2] = next;
7583
+ lock.entries[key3] = next;
7581
7584
  let dirty = dirtyPatches.get(lock);
7582
7585
  if (!dirty) {
7583
7586
  dirty = /* @__PURE__ */ new Map();
7584
7587
  dirtyPatches.set(lock, dirty);
7585
7588
  }
7586
- dirty.set(key2, { ...dirty.get(key2) ?? {}, ...patch });
7589
+ dirty.set(key3, { ...dirty.get(key3) ?? {}, ...patch });
7587
7590
  return next;
7588
7591
  }
7589
- function remove(lock, key2) {
7590
- if (!lock.entries[key2]) return false;
7591
- delete lock.entries[key2];
7592
+ function remove(lock, key3) {
7593
+ if (!lock.entries[key3]) return false;
7594
+ delete lock.entries[key3];
7592
7595
  const patches = dirtyPatches.get(lock);
7593
7596
  if (patches) {
7594
- patches.delete(key2);
7597
+ patches.delete(key3);
7595
7598
  if (patches.size === 0) dirtyPatches.delete(lock);
7596
7599
  }
7597
7600
  let deletes = dirtyDeletes.get(lock);
@@ -7599,7 +7602,7 @@ function remove(lock, key2) {
7599
7602
  deletes = /* @__PURE__ */ new Set();
7600
7603
  dirtyDeletes.set(lock, deletes);
7601
7604
  }
7602
- deletes.add(key2);
7605
+ deletes.add(key3);
7603
7606
  return true;
7604
7607
  }
7605
7608
  var FILE_LOCK_TIMEOUT_MS = 1e4;
@@ -7699,8 +7702,8 @@ function currentEntryOutputPath(entry, spec, index) {
7699
7702
  function normalizeLockOutputPaths(lock, specs) {
7700
7703
  const byKey = new Map(specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
7701
7704
  let changed = 0;
7702
- for (const [key2, entry] of Object.entries(lock.entries)) {
7703
- const spec = byKey.get(key2);
7705
+ for (const [key3, entry] of Object.entries(lock.entries)) {
7706
+ const spec = byKey.get(key3);
7704
7707
  if (!spec) continue;
7705
7708
  let entryChanged = false;
7706
7709
  const outputs = entry.outputs.map((output, index) => {
@@ -7711,7 +7714,7 @@ function normalizeLockOutputPaths(lock, specs) {
7711
7714
  entryChanged = true;
7712
7715
  return { ...output, path: portable };
7713
7716
  });
7714
- if (entryChanged) upsert(lock, key2, { outputs });
7717
+ if (entryChanged) upsert(lock, key3, { outputs });
7715
7718
  }
7716
7719
  return changed;
7717
7720
  }
@@ -7742,8 +7745,8 @@ function resolveSpecEntryOutputs(entry, spec) {
7742
7745
  }
7743
7746
  function resolveStyleOutputs(lock, styleId, manifestDir) {
7744
7747
  const prefix = `${styleId}/`;
7745
- return Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
7746
- ([key2, entry]) => resolveEntryOutputs(entry, key2.slice(prefix.length), manifestDir)
7748
+ return Object.entries(lock.entries).filter(([key3]) => key3.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
7749
+ ([key3, entry]) => resolveEntryOutputs(entry, key3.slice(prefix.length), manifestDir)
7747
7750
  );
7748
7751
  }
7749
7752
  function selectEntryOutput(entry, role) {
@@ -7827,8 +7830,8 @@ function quantize(png, palette) {
7827
7830
  pixels[i + 2] = 0;
7828
7831
  continue;
7829
7832
  }
7830
- const key2 = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
7831
- let nearest = nearestOf.get(key2);
7833
+ const key3 = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
7834
+ let nearest = nearestOf.get(key3);
7832
7835
  if (!nearest) {
7833
7836
  const pixel = { r: pixels[i], g: pixels[i + 1], b: pixels[i + 2] };
7834
7837
  nearest = colors[0];
@@ -7841,7 +7844,7 @@ function quantize(png, palette) {
7841
7844
  distance = candidateDistance;
7842
7845
  }
7843
7846
  }
7844
- nearestOf.set(key2, nearest);
7847
+ nearestOf.set(key3, nearest);
7845
7848
  }
7846
7849
  if (pixels[i] !== nearest.r || pixels[i + 1] !== nearest.g || pixels[i + 2] !== nearest.b) changed++;
7847
7850
  pixels[i] = nearest.r;
@@ -7947,7 +7950,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
7947
7950
  const log = opts.onProgress ?? (() => {
7948
7951
  });
7949
7952
  const mirror = spec.mirror;
7950
- const key2 = lockKey(spec.styleId, spec.assetId);
7953
+ const key3 = lockKey(spec.styleId, spec.assetId);
7951
7954
  const sourceKey = lockKey(spec.styleId, mirror.sourceAssetId);
7952
7955
  const source = lock.entries[sourceKey];
7953
7956
  if (!source || source.status !== "downloaded" || !source.outputs.length) {
@@ -7979,7 +7982,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
7979
7982
  }
7980
7983
  const sourceMetadata = source.providerMetadata?.[source.provider] ?? {};
7981
7984
  const character = spec.character;
7982
- const entry = upsert(lock, key2, {
7985
+ const entry = upsert(lock, key3, {
7983
7986
  styleId: spec.styleId,
7984
7987
  assetId: spec.assetId,
7985
7988
  specHash: spec.specHash,
@@ -8022,7 +8025,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
8022
8025
  postprocess: postprocessFor(spec)
8023
8026
  });
8024
8027
  await saveLock(lockPath, lock);
8025
- log(` mirror ${key2} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
8028
+ log(` mirror ${key3} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
8026
8029
  return entry;
8027
8030
  }
8028
8031
 
@@ -8030,14 +8033,14 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
8030
8033
  function heldFrames(spec, lock) {
8031
8034
  const frames = [];
8032
8035
  for (const source of spec.character.layer.sources) {
8033
- const key2 = lockKey(source.spec.styleId, source.spec.assetId);
8034
- const entry = lock.entries[key2];
8036
+ const key3 = lockKey(source.spec.styleId, source.spec.assetId);
8037
+ const entry = lock.entries[key3];
8035
8038
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
8036
- throw new Error(`held item source ${key2} has no downloaded frames`);
8039
+ throw new Error(`held item source ${key3} has no downloaded frames`);
8037
8040
  }
8038
8041
  for (const [index, output] of entry.outputs.entries()) {
8039
8042
  const direction = isDirection(output.role) ? output.role : source.spec.character?.animation?.direction;
8040
- if (!direction) throw new Error(`cannot tell which way ${key2} frame ${output.role ?? index} faces`);
8043
+ if (!direction) throw new Error(`cannot tell which way ${key3} frame ${output.role ?? index} faces`);
8041
8044
  frames.push({
8042
8045
  assetId: source.assetId,
8043
8046
  role: output.role ?? String(index).padStart(2, "0"),
@@ -8106,7 +8109,7 @@ async function heldItemAsset(spec, lock, lockPath, opts = {}) {
8106
8109
  });
8107
8110
  const layer = spec.character.layer;
8108
8111
  const attach = layer.attach;
8109
- const key2 = lockKey(spec.styleId, spec.assetId);
8112
+ const key3 = lockKey(spec.styleId, spec.assetId);
8110
8113
  const frames = heldFrames(spec, lock);
8111
8114
  const placed = await placeHeldFrames(spec, frames);
8112
8115
  const outputs = [];
@@ -8123,7 +8126,7 @@ async function heldItemAsset(spec, lock, lockPath, opts = {}) {
8123
8126
  outputs.push({ path: portableOutputPath(target, spec.root), sha256: sha256(bytes), role, mediaType: MediaType.PNG });
8124
8127
  }
8125
8128
  const now = (/* @__PURE__ */ new Date()).toISOString();
8126
- const entry = upsert(lock, key2, {
8129
+ const entry = upsert(lock, key3, {
8127
8130
  styleId: spec.styleId,
8128
8131
  assetId: spec.assetId,
8129
8132
  specHash: spec.specHash,
@@ -8162,7 +8165,7 @@ async function heldItemAsset(spec, lock, lockPath, opts = {}) {
8162
8165
  postprocess: void 0
8163
8166
  });
8164
8167
  await saveLock(lockPath, lock);
8165
- log(` attach ${key2} (${frames.length} frame${frames.length === 1 ? "" : "s"}, ${attach.joint}, no generation cost)`);
8168
+ log(` attach ${key3} (${frames.length} frame${frames.length === 1 ? "" : "s"}, ${attach.joint}, no generation cost)`);
8166
8169
  if (clipped) log(` ${clipped} item pixel${clipped === 1 ? "" : "s"} fell outside the canvas; raise layer.padding above ${layer.padding} to keep them`);
8167
8170
  return entry;
8168
8171
  }
@@ -10633,8 +10636,8 @@ var PixelLabProvider = class _PixelLabProvider {
10633
10636
  billed
10634
10637
  };
10635
10638
  };
10636
- for (const key2 of ["frame_urls", "frames", "images"]) {
10637
- const list = done[key2];
10639
+ for (const key3 of ["frame_urls", "frames", "images"]) {
10640
+ const list = done[key3];
10638
10641
  if (!Array.isArray(list) || !list.length) continue;
10639
10642
  const urls = [];
10640
10643
  for (const [index, item] of list.entries()) {
@@ -10689,15 +10692,15 @@ var PixelLabProvider = class _PixelLabProvider {
10689
10692
  const billed = billedFromUsage(job.usage);
10690
10693
  const done = job.last_response ?? {};
10691
10694
  const urlKeys = ["image_url", "download_url", "url", "output_url"];
10692
- for (const key2 of urlKeys) {
10693
- const url = done[key2];
10695
+ for (const key3 of urlKeys) {
10696
+ const url = done[key3];
10694
10697
  if (typeof url === "string" && url) {
10695
10698
  return { status: "ready", objectId: jobId, sourceUrl: url, sources: [{ url }], billed };
10696
10699
  }
10697
10700
  }
10698
10701
  const imageKeys = ["image", "output_image", "result_image", "edited_image"];
10699
- for (const key2 of imageKeys) {
10700
- const candidate = done[key2];
10702
+ for (const key3 of imageKeys) {
10703
+ const candidate = done[key3];
10701
10704
  const base64 = extractBase64(candidate);
10702
10705
  if (base64) {
10703
10706
  const file = import_node_path7.default.join(_PixelLabProvider.cacheDir(), `${jobId}.png`);
@@ -11166,7 +11169,7 @@ function requirePixelLabOption(generator, name, value, allowed) {
11166
11169
  }
11167
11170
  }
11168
11171
  function tilesInIndexOrder(urls) {
11169
- return Object.entries(urls).map(([key2, url]) => ({ index: Number(key2.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
11172
+ return Object.entries(urls).map(([key3, url]) => ({ index: Number(key3.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
11170
11173
  }
11171
11174
  function firstUrl(urls) {
11172
11175
  if (!urls) return null;
@@ -11799,8 +11802,8 @@ var ScenarioClient = class {
11799
11802
  throw new Error(`${missing.join(" and ")} ${missing.length > 1 ? "are" : "is"} not set`);
11800
11803
  }
11801
11804
  const url = new URL(`${this.baseUrl.replace(/\/$/, "")}${pathname}`);
11802
- for (const [key2, value2] of Object.entries(query)) {
11803
- if (value2 != null) url.searchParams.set(key2, value2);
11805
+ for (const [key3, value2] of Object.entries(query)) {
11806
+ if (value2 != null) url.searchParams.set(key3, value2);
11804
11807
  }
11805
11808
  const auth = Buffer.from(`${this.apiKey}:${this.apiSecret}`).toString("base64");
11806
11809
  const response = await this.request(url, {
@@ -12040,12 +12043,12 @@ function readUploadCache() {
12040
12043
  return {};
12041
12044
  }
12042
12045
  }
12043
- function writeUploadCache(key2, assetId) {
12046
+ function writeUploadCache(key3, assetId) {
12044
12047
  try {
12045
12048
  const file = uploadCachePath();
12046
12049
  (0, import_node_fs8.mkdirSync)(import_node_path8.default.dirname(file), { recursive: true });
12047
12050
  const tmp = `${file}.${process.pid}.tmp`;
12048
- (0, import_node_fs8.writeFileSync)(tmp, JSON.stringify({ ...readUploadCache(), [key2]: assetId }));
12051
+ (0, import_node_fs8.writeFileSync)(tmp, JSON.stringify({ ...readUploadCache(), [key3]: assetId }));
12049
12052
  (0, import_node_fs8.renameSync)(tmp, file);
12050
12053
  } catch {
12051
12054
  }
@@ -12095,9 +12098,9 @@ function validateParameters(parameters) {
12095
12098
  if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
12096
12099
  throw new Error("Scenario parameters must be a JSON object");
12097
12100
  }
12098
- for (const key2 of Object.keys(parameters)) {
12099
- if (PROTECTED_PARAMETERS.has(key2)) {
12100
- throw new Error(`Scenario parameters.${key2} is managed by PixelKiln and cannot be overridden`);
12101
+ for (const key3 of Object.keys(parameters)) {
12102
+ if (PROTECTED_PARAMETERS.has(key3)) {
12103
+ throw new Error(`Scenario parameters.${key3} is managed by PixelKiln and cannot be overridden`);
12101
12104
  }
12102
12105
  }
12103
12106
  assertJsonValue(parameters, "Scenario parameters");
@@ -12120,8 +12123,8 @@ function assertJsonValue(value, label, seen = /* @__PURE__ */ new Set()) {
12120
12123
  if (Array.isArray(value)) {
12121
12124
  value.forEach((item, index) => assertJsonValue(item, `${label}[${index}]`, seen));
12122
12125
  } else {
12123
- for (const [key2, item] of Object.entries(value)) {
12124
- assertJsonValue(item, `${label}.${key2}`, seen);
12126
+ for (const [key3, item] of Object.entries(value)) {
12127
+ assertJsonValue(item, `${label}.${key3}`, seen);
12125
12128
  }
12126
12129
  }
12127
12130
  seen.delete(value);
@@ -12222,8 +12225,8 @@ function numericRecord(value) {
12222
12225
  throw new Error("Scenario returned invalid cost details");
12223
12226
  }
12224
12227
  const out = {};
12225
- for (const [key2, amount] of Object.entries(value)) {
12226
- out[key2] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key2}"`);
12228
+ for (const [key3, amount] of Object.entries(value)) {
12229
+ out[key3] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key3}"`);
12227
12230
  }
12228
12231
  return out;
12229
12232
  }
@@ -12829,7 +12832,7 @@ function parseOptions(value) {
12829
12832
  "workflow",
12830
12833
  "workflowSha256"
12831
12834
  ]);
12832
- const extra = Object.keys(value).filter((key2) => !allowed.has(key2));
12835
+ const extra = Object.keys(value).filter((key3) => !allowed.has(key3));
12833
12836
  if (extra.length) throw new Error(`Unknown ComfyUI option(s): ${extra.join(", ")}`);
12834
12837
  const workflowFile = requiredString(value.workflowFile, "workflowFile");
12835
12838
  const outputNodeId = requiredString(value.outputNodeId, "outputNodeId");
@@ -12865,7 +12868,7 @@ function parseOptions(value) {
12865
12868
  }
12866
12869
  function parseFrames(value) {
12867
12870
  if (!isObject(value)) throw new Error("ComfyUI frames must be an object");
12868
- const extra = Object.keys(value).filter((key2) => key2 !== "vary" && key2 !== "seedStep");
12871
+ const extra = Object.keys(value).filter((key3) => key3 !== "vary" && key3 !== "seedStep");
12869
12872
  if (extra.length) throw new Error(`Unknown ComfyUI frames field(s): ${extra.join(", ")}`);
12870
12873
  const vary = requiredString(value.vary, "frames.vary");
12871
12874
  const seedStep = value.seedStep ?? 0;
@@ -12883,7 +12886,7 @@ function resolvedOptions(spec) {
12883
12886
  }
12884
12887
  function parseBinding(value, name) {
12885
12888
  if (!isObject(value)) throw new Error(`ComfyUI bindings.${name} must be an object`);
12886
- const extra = Object.keys(value).filter((key2) => key2 !== "nodeId" && key2 !== "input");
12889
+ const extra = Object.keys(value).filter((key3) => key3 !== "nodeId" && key3 !== "input");
12887
12890
  if (extra.length) throw new Error(`Unknown ComfyUI bindings.${name} field(s): ${extra.join(", ")}`);
12888
12891
  return {
12889
12892
  nodeId: requiredString(value.nodeId, `bindings.${name}.nodeId`),
@@ -13148,7 +13151,7 @@ function canonical(value) {
13148
13151
  if (Array.isArray(value)) return value.map(canonical);
13149
13152
  if (!isObject(value)) return value;
13150
13153
  return Object.fromEntries(
13151
- Object.keys(value).sort().map((key2) => [key2, canonical(value[key2])])
13154
+ Object.keys(value).sort().map((key3) => [key3, canonical(value[key3])])
13152
13155
  );
13153
13156
  }
13154
13157
 
@@ -13808,10 +13811,10 @@ function culpritEntries(message6) {
13808
13811
  const match = /^ {2}(assets|styles)\.([^.:\s]+)[.:]/.exec(line);
13809
13812
  if (!match) continue;
13810
13813
  const kind = match[1] === "styles" ? "style" : "asset";
13811
- const key2 = `${kind}:${match[2]}`;
13812
- const entry = found.get(key2) ?? { kind, id: match[2], issues: [] };
13814
+ const key3 = `${kind}:${match[2]}`;
13815
+ const entry = found.get(key3) ?? { kind, id: match[2], issues: [] };
13813
13816
  entry.issues.push(line.trim());
13814
- found.set(key2, entry);
13817
+ found.set(key3, entry);
13815
13818
  }
13816
13819
  return [...found.values()];
13817
13820
  }
@@ -15001,8 +15004,8 @@ async function resolveSpecs(loaded, filter) {
15001
15004
  byOutput.set(file, owner);
15002
15005
  };
15003
15006
  for (const spec of specs) {
15004
- const key2 = `${spec.styleId}/${spec.assetId}`;
15005
- claimOutput(spec.outFile, key2);
15007
+ const key3 = `${spec.styleId}/${spec.assetId}`;
15008
+ claimOutput(spec.outFile, key3);
15006
15009
  if (spec.quality) {
15007
15010
  if (spec.generator === "frames") {
15008
15011
  const frameInputs = Object.values(spec.providerInputs ?? {}).find(Array.isArray);
@@ -15017,11 +15020,11 @@ async function resolveSpecs(loaded, filter) {
15017
15020
  count,
15018
15021
  MediaType.PNG
15019
15022
  ),
15020
- `${key2} quality ${role}`
15023
+ `${key3} quality ${role}`
15021
15024
  );
15022
15025
  }
15023
15026
  } else {
15024
- claimOutput(spec.quality.outFile, `${key2} quality output`);
15027
+ claimOutput(spec.quality.outFile, `${key3} quality output`);
15025
15028
  }
15026
15029
  }
15027
15030
  }
@@ -15303,8 +15306,8 @@ var import_node_path12 = __toESM(require("path"), 1);
15303
15306
  function loadEnvFiles(dir) {
15304
15307
  const loaded = [];
15305
15308
  for (const [file, vars] of envFiles(dir)) {
15306
- for (const [key2, value] of Object.entries(vars)) {
15307
- if (!(key2 in process.env)) process.env[key2] = value;
15309
+ for (const [key3, value] of Object.entries(vars)) {
15310
+ if (!(key3 in process.env)) process.env[key3] = value;
15308
15311
  }
15309
15312
  loaded.push(file);
15310
15313
  }
@@ -15329,14 +15332,14 @@ function parseEnv(contents) {
15329
15332
  if (!line || line.startsWith("#")) continue;
15330
15333
  const eq = line.indexOf("=");
15331
15334
  if (eq <= 0) continue;
15332
- const key2 = line.slice(0, eq).replace(/^export\s+/, "").trim();
15333
- if (!key2 || key2 in vars) continue;
15335
+ const key3 = line.slice(0, eq).replace(/^export\s+/, "").trim();
15336
+ if (!key3 || key3 in vars) continue;
15334
15337
  let value = line.slice(eq + 1).trim();
15335
15338
  const quote = value[0];
15336
15339
  if ((quote === '"' || quote === "'") && value.endsWith(quote) && value.length >= 2) {
15337
15340
  value = value.slice(1, -1);
15338
15341
  }
15339
- vars[key2] = value;
15342
+ vars[key3] = value;
15340
15343
  }
15341
15344
  return vars;
15342
15345
  }
@@ -15402,9 +15405,9 @@ function canonical2(value) {
15402
15405
  if (Array.isArray(value)) return value.map(canonical2);
15403
15406
  if (typeof value === "object") {
15404
15407
  const sorted = {};
15405
- for (const key2 of Object.keys(value).sort()) {
15406
- const item = value[key2];
15407
- if (item !== void 0) sorted[key2] = canonical2(item);
15408
+ for (const key3 of Object.keys(value).sort()) {
15409
+ const item = value[key3];
15410
+ if (item !== void 0) sorted[key3] = canonical2(item);
15408
15411
  }
15409
15412
  return sorted;
15410
15413
  }
@@ -16391,18 +16394,18 @@ async function qualitySource(spec, lock) {
16391
16394
  }
16392
16395
  async function inspectQualityProfile(spec, lock) {
16393
16396
  if (!spec.quality) return null;
16394
- const key2 = lockKey(spec.styleId, spec.assetId);
16397
+ const key3 = lockKey(spec.styleId, spec.assetId);
16395
16398
  const output = spec.quality.outFile;
16396
16399
  const record = qualityRecordPath(output);
16397
16400
  const source = await qualitySource(spec, lock);
16398
16401
  if (!source.items) {
16399
- return { key: key2, state: "blocked", reason: source.reason, source: null, output, record };
16402
+ return { key: key3, state: "blocked", reason: source.reason, source: null, output, record };
16400
16403
  }
16401
16404
  const sourcePaths = source.items.map((item) => item.path);
16402
16405
  const expectedOutputs = spec.generator === "frames" ? source.items.map((item, index) => qualityFrameOutputPath(output, item.role, index)) : [output];
16403
16406
  if (!(0, import_node_fs14.existsSync)(record)) {
16404
16407
  return {
16405
- key: key2,
16408
+ key: key3,
16406
16409
  state: "needs-refinement",
16407
16410
  reason: "no refinement record",
16408
16411
  source: sourcePaths[0],
@@ -16421,7 +16424,7 @@ async function inspectQualityProfile(spec, lock) {
16421
16424
  const contractChanged = JSON.stringify(check.sources.map((item) => import_node_path16.default.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => import_node_path16.default.resolve(item))) || JSON.stringify(check.outputs.map((item) => import_node_path16.default.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => import_node_path16.default.resolve(item))) || JSON.stringify(check.options.palette.colors) !== JSON.stringify(expectedPalette) || check.options.nativeGrid.revision !== expectedRevision || check.options.audit.thresholds.minGridConfidence !== spec.quality.minGridConfidence || check.options.audit.thresholds.minTransparency !== expectedTransparency || (expectedFrameSet ? !check.options.frameSet || check.options.frameSet.fps !== expectedFrameSet.fps || check.options.frameSet.count !== expectedFrameSet.count || JSON.stringify(check.options.frameSet.roles) !== JSON.stringify(expectedFrameSet.roles) : check.options.frameSet !== void 0);
16422
16425
  if (contractChanged) {
16423
16426
  return {
16424
- key: key2,
16427
+ key: key3,
16425
16428
  state: "needs-refinement",
16426
16429
  reason: "quality profile changed",
16427
16430
  source: sourcePaths[0],
@@ -16433,7 +16436,7 @@ async function inspectQualityProfile(spec, lock) {
16433
16436
  }
16434
16437
  if (!check.current || !check.auditSafe) {
16435
16438
  return {
16436
- key: key2,
16439
+ key: key3,
16437
16440
  state: "needs-refinement",
16438
16441
  reason: check.reasons.filter((reason) => reason !== "human 1\xD7 review is pending").join("; ") || "refinement record is stale",
16439
16442
  source: sourcePaths[0],
@@ -16445,7 +16448,7 @@ async function inspectQualityProfile(spec, lock) {
16445
16448
  }
16446
16449
  if (!check.approved) {
16447
16450
  return {
16448
- key: key2,
16451
+ key: key3,
16449
16452
  state: "needs-approval",
16450
16453
  reason: "automated checks passed; human 1\xD7 review is pending",
16451
16454
  source: sourcePaths[0],
@@ -16456,7 +16459,7 @@ async function inspectQualityProfile(spec, lock) {
16456
16459
  };
16457
16460
  }
16458
16461
  return {
16459
- key: key2,
16462
+ key: key3,
16460
16463
  state: "approved",
16461
16464
  reason: "refined output and human approval are current",
16462
16465
  source: sourcePaths[0],
@@ -16467,7 +16470,7 @@ async function inspectQualityProfile(spec, lock) {
16467
16470
  };
16468
16471
  } catch (error) {
16469
16472
  return {
16470
- key: key2,
16473
+ key: key3,
16471
16474
  state: "needs-refinement",
16472
16475
  reason: `invalid refinement record: ${error instanceof Error ? error.message : String(error)}`,
16473
16476
  source: sourcePaths[0],
@@ -16819,10 +16822,10 @@ async function requireRevisionReady(spec, lock) {
16819
16822
  if (inspection && !inspection.ready) throw new Error(inspection.reason);
16820
16823
  }
16821
16824
  async function inspectParent(spec, lock, seen) {
16822
- const key2 = lockKey(spec.styleId, spec.assetId);
16823
- if (seen.has(key2)) return { ready: false, reason: `revision dependency cycle at ${key2}` };
16825
+ const key3 = lockKey(spec.styleId, spec.assetId);
16826
+ if (seen.has(key3)) return { ready: false, reason: `revision dependency cycle at ${key3}` };
16824
16827
  const nextSeen = new Set(seen);
16825
- nextSeen.add(key2);
16828
+ nextSeen.add(key3);
16826
16829
  if (spec.mirror) {
16827
16830
  const inputs = await inspectMirror(spec, lock, nextSeen);
16828
16831
  if (!inputs.ready) return inputs;
@@ -16868,7 +16871,7 @@ async function inspectParent(spec, lock, seen) {
16868
16871
  const source = import_node_path17.default.resolve(spec.root, spec.source);
16869
16872
  return (0, import_node_fs15.existsSync)(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
16870
16873
  }
16871
- const entry = lock.entries[key2];
16874
+ const entry = lock.entries[key3];
16872
16875
  if (!entry) return { ready: false, reason: "parent is not in the lockfile" };
16873
16876
  if (entry.specHash !== spec.specHash) {
16874
16877
  return { ready: false, reason: "parent generation spec is stale" };
@@ -16952,15 +16955,15 @@ function resumeCommandForStatus(status) {
16952
16955
  function resumeActions(specs, lock) {
16953
16956
  const grouped = /* @__PURE__ */ new Map();
16954
16957
  for (const spec of specs) {
16955
- const key2 = lockKey(spec.styleId, spec.assetId);
16956
- const entry = lock.entries[key2];
16958
+ const key3 = lockKey(spec.styleId, spec.assetId);
16959
+ const entry = lock.entries[key3];
16957
16960
  if (!entry || entry.specHash !== spec.specHash) continue;
16958
16961
  if (entry.submissionComplete === false) continue;
16959
16962
  const command = resumeCommandForStatus(entry.status) ?? (entry.status === "downloaded" && entry.outputs.length && !postprocessCurrent(entry, spec) ? "fetch" : null);
16960
16963
  if (!command) continue;
16961
16964
  if (command === "poll" && !entry.jobId) continue;
16962
16965
  if (command === "pick" && !entry.reviewObjectId) continue;
16963
- grouped.set(command, [...grouped.get(command) ?? [], key2]);
16966
+ grouped.set(command, [...grouped.get(command) ?? [], key3]);
16964
16967
  }
16965
16968
  return ["poll", "pick", "fetch"].flatMap((command) => {
16966
16969
  const keys = grouped.get(command);
@@ -16970,8 +16973,8 @@ function resumeActions(specs, lock) {
16970
16973
  async function buildPlan(specs, lock, opts = {}) {
16971
16974
  const items = [];
16972
16975
  for (const spec of specs) {
16973
- const key2 = lockKey(spec.styleId, spec.assetId);
16974
- const entry = lock.entries[key2];
16976
+ const key3 = lockKey(spec.styleId, spec.assetId);
16977
+ const entry = lock.entries[key3];
16975
16978
  let state;
16976
16979
  let reason;
16977
16980
  const changedConnection = entry ? changedTerrainConnection(spec, entry, lock) : null;
@@ -17086,7 +17089,7 @@ async function buildPlan(specs, lock, opts = {}) {
17086
17089
  reason = "up to date";
17087
17090
  }
17088
17091
  const quality = await inspectQualityProfile(spec, lock);
17089
- items.push({ spec, key: key2, state, reason, ...quality ? { quality } : {} });
17092
+ items.push({ spec, key: key3, state, reason, ...quality ? { quality } : {} });
17090
17093
  }
17091
17094
  const isActionable = (i) => i.state === "missing" || i.state === "stale" || i.state === "failed";
17092
17095
  const stateOf = new Map(items.map((i) => [i.key, i.state]));
@@ -17210,11 +17213,11 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
17210
17213
  reload: () => openProject(absolute, { ...opts, env: false }),
17211
17214
  providers: () => [...new Set(specs.map((spec) => spec.provider))].sort(),
17212
17215
  provider: (id, mode2 = "online") => {
17213
- const key2 = `${mode2}:${id}`;
17214
- let adapter = adapters.get(key2);
17216
+ const key3 = `${mode2}:${id}`;
17217
+ let adapter = adapters.get(key3);
17215
17218
  if (!adapter) {
17216
17219
  adapter = createProvider(id, mode2);
17217
- adapters.set(key2, adapter);
17220
+ adapters.set(key3, adapter);
17218
17221
  }
17219
17222
  return adapter;
17220
17223
  }
@@ -17393,9 +17396,9 @@ function canonical3(value) {
17393
17396
  if (Array.isArray(value)) return value.map(canonical3);
17394
17397
  if (typeof value === "object") {
17395
17398
  const sorted = {};
17396
- for (const key2 of Object.keys(value).sort()) {
17397
- const item = value[key2];
17398
- if (item !== void 0) sorted[key2] = canonical3(item);
17399
+ for (const key3 of Object.keys(value).sort()) {
17400
+ const item = value[key3];
17401
+ if (item !== void 0) sorted[key3] = canonical3(item);
17399
17402
  }
17400
17403
  return sorted;
17401
17404
  }
@@ -17534,7 +17537,7 @@ function renderStyle(style, destination, cwd) {
17534
17537
  if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
17535
17538
  if (Array.isArray(value)) return value.map(replace);
17536
17539
  if (value && typeof value === "object") {
17537
- return Object.fromEntries(Object.entries(value).map(([key2, item]) => [key2, replace(item)]));
17540
+ return Object.fromEntries(Object.entries(value).map(([key3, item]) => [key3, replace(item)]));
17538
17541
  }
17539
17542
  return value;
17540
17543
  };
@@ -17602,10 +17605,10 @@ function mergePalettes(palettes, topN = 24) {
17602
17605
  const totals = /* @__PURE__ */ new Map();
17603
17606
  for (const palette of palettes) {
17604
17607
  for (const color of palette) {
17605
- const key2 = `${color.r},${color.g},${color.b}`;
17606
- const existing = totals.get(key2);
17608
+ const key3 = `${color.r},${color.g},${color.b}`;
17609
+ const existing = totals.get(key3);
17607
17610
  if (existing) existing.weight += color.weight;
17608
- else totals.set(key2, { ...color });
17611
+ else totals.set(key3, { ...color });
17609
17612
  }
17610
17613
  }
17611
17614
  const merged = [...totals.values()].sort((a, b) => b.weight - a.weight).slice(0, topN);
@@ -18277,7 +18280,7 @@ function tilesetSheetReadings(width, height) {
18277
18280
  }
18278
18281
  function chooseTilesetSheetReading(file, width, height, tileSize) {
18279
18282
  const readings = tilesetSheetReadings(width, height);
18280
- const describe = (reading) => `${reading.tileSize}px tiles (${reading.layout === "compact" ? "4 wide" : "8 wide"})`;
18283
+ const describe2 = (reading) => `${reading.tileSize}px tiles (${reading.layout === "compact" ? "4 wide" : "8 wide"})`;
18281
18284
  if (readings.length === 0) {
18282
18285
  throw new Error(
18283
18286
  `${file} is ${width}x${height}, not a PixelLab tileset sheet: it takes a square sheet 4 or 8 tiles wide (or twice as tall, for a set with transitions) of 16, 24, 32, 48 or 64px tiles`
@@ -18286,13 +18289,13 @@ function chooseTilesetSheetReading(file, width, height, tileSize) {
18286
18289
  if (tileSize === void 0) {
18287
18290
  if (readings.length > 1) {
18288
18291
  throw new Error(
18289
- `${file} is ${width}x${height}, which reads as ${readings.map(describe).join(" or ")}; say which with --size ${readings.map((reading) => reading.tileSize).join(" or --size ")}`
18292
+ `${file} is ${width}x${height}, which reads as ${readings.map(describe2).join(" or ")}; say which with --size ${readings.map((reading) => reading.tileSize).join(" or --size ")}`
18290
18293
  );
18291
18294
  }
18292
18295
  return readings[0];
18293
18296
  }
18294
18297
  const chosen = readings.find((reading) => reading.tileSize === tileSize);
18295
- if (!chosen) throw new Error(`${file} is ${width}x${height}, which holds ${readings.map(describe).join(" or ")}, not ${tileSize}px tiles`);
18298
+ if (!chosen) throw new Error(`${file} is ${width}x${height}, which holds ${readings.map(describe2).join(" or ")}, not ${tileSize}px tiles`);
18296
18299
  return chosen;
18297
18300
  }
18298
18301
  function readPng(bytes, file) {
@@ -18861,7 +18864,7 @@ function listCodexEffects(lib) {
18861
18864
  ...entry,
18862
18865
  loopSeconds: def.loop,
18863
18866
  params: Object.fromEntries(
18864
- Object.entries(def.params ?? {}).map(([key2, param]) => [key2, { label: param.en ?? key2, min: param.min, max: param.max, value: param.value }])
18867
+ Object.entries(def.params ?? {}).map(([key3, param]) => [key3, { label: param.en ?? key3, min: param.min, max: param.max, value: param.value }])
18865
18868
  )
18866
18869
  };
18867
18870
  });
@@ -18902,19 +18905,19 @@ function checkCodexRecipe(lib, recipe) {
18902
18905
  if (hue !== void 0 && (typeof hue !== "number" || !Number.isFinite(hue) || hue < -360 || hue > 360)) {
18903
18906
  throw new UsageError(`codex hue is degrees from -360 to 360, got ${JSON.stringify(hue)}`);
18904
18907
  }
18905
- for (const [key2, value] of Object.entries(params)) {
18906
- const param = info.params[key2];
18908
+ for (const [key3, value] of Object.entries(params)) {
18909
+ const param = info.params[key3];
18907
18910
  if (!param) {
18908
18911
  const known = Object.keys(info.params);
18909
- throw new UsageError(`${recipe.effect} has no parameter "${key2}"${known.length ? `; it has ${known.join(", ")}` : " (it takes none)"}`);
18912
+ throw new UsageError(`${recipe.effect} has no parameter "${key3}"${known.length ? `; it has ${known.join(", ")}` : " (it takes none)"}`);
18910
18913
  }
18911
18914
  if (typeof value !== "number" || !Number.isFinite(value) || value < param.min || value > param.max) {
18912
- throw new UsageError(`${recipe.effect} ${key2} is a number from ${param.min} to ${param.max}, got ${JSON.stringify(value)}`);
18915
+ throw new UsageError(`${recipe.effect} ${key3} is a number from ${param.min} to ${param.max}, got ${JSON.stringify(value)}`);
18913
18916
  }
18914
18917
  }
18915
- for (const [key2, value] of Object.entries(tune)) {
18916
- if (!CODEX_TUNE_KEYS.includes(key2)) throw new UsageError(`unknown tune knob "${key2}"; they are ${CODEX_TUNE_KEYS.join(", ")}`);
18917
- if (typeof value !== "number" || !Number.isFinite(value)) throw new UsageError(`tune ${key2} is a number, got ${JSON.stringify(value)}`);
18918
+ for (const [key3, value] of Object.entries(tune)) {
18919
+ if (!CODEX_TUNE_KEYS.includes(key3)) throw new UsageError(`unknown tune knob "${key3}"; they are ${CODEX_TUNE_KEYS.join(", ")}`);
18920
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new UsageError(`tune ${key3} is a number, got ${JSON.stringify(value)}`);
18918
18921
  }
18919
18922
  return info;
18920
18923
  }
@@ -19000,12 +19003,12 @@ async function readCodexRecipe(file, opts = {}) {
19000
19003
  }
19001
19004
  const recipe = { effect: raw.effect };
19002
19005
  if (raw.camera !== void 0) recipe.camera = raw.camera;
19003
- for (const key2 of ["fps", "margin", "hue"]) if (raw[key2] !== void 0) recipe[key2] = raw[key2];
19004
- for (const key2 of ["params", "tune"]) {
19005
- const value = raw[key2];
19006
+ for (const key3 of ["fps", "margin", "hue"]) if (raw[key3] !== void 0) recipe[key3] = raw[key3];
19007
+ for (const key3 of ["params", "tune"]) {
19008
+ const value = raw[key3];
19006
19009
  if (value === void 0) continue;
19007
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${file}: a codex recipe's ${key2} is an object`);
19008
- recipe[key2] = value;
19010
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${file}: a codex recipe's ${key3} is an object`);
19011
+ recipe[key3] = value;
19009
19012
  }
19010
19013
  const library = record ? parsed.library : void 0;
19011
19014
  return {
@@ -19160,8 +19163,8 @@ function measureDecodedImageQuality(png, digest2) {
19160
19163
  const index = offset / 4;
19161
19164
  const x = index % png.width;
19162
19165
  const y = Math.floor(index / png.width);
19163
- const key2 = pixelKey(png.pixels, offset);
19164
- const hasSameNeighbor = x > 0 && pixelKey(png.pixels, offset - 4) === key2 || x + 1 < png.width && pixelKey(png.pixels, offset + 4) === key2 || y > 0 && pixelKey(png.pixels, offset - png.width * 4) === key2 || y + 1 < png.height && pixelKey(png.pixels, offset + png.width * 4) === key2;
19166
+ const key3 = pixelKey(png.pixels, offset);
19167
+ const hasSameNeighbor = x > 0 && pixelKey(png.pixels, offset - 4) === key3 || x + 1 < png.width && pixelKey(png.pixels, offset + 4) === key3 || y > 0 && pixelKey(png.pixels, offset - png.width * 4) === key3 || y + 1 < png.height && pixelKey(png.pixels, offset + png.width * 4) === key3;
19165
19168
  if (!hasSameNeighbor) {
19166
19169
  isolated++;
19167
19170
  }
@@ -19543,10 +19546,10 @@ async function loadCache(path53) {
19543
19546
  }
19544
19547
  async function saveCache(path53, cache) {
19545
19548
  const sorted = {};
19546
- for (const key2 of Object.keys(cache.hashes).sort()) {
19547
- const hash = cache.hashes[key2];
19548
- if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
19549
- sorted[key2] = hash;
19549
+ for (const key3 of Object.keys(cache.hashes).sort()) {
19550
+ const hash = cache.hashes[key3];
19551
+ if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
19552
+ sorted[key3] = hash;
19550
19553
  }
19551
19554
  await (0, import_promises20.mkdir)(import_node_path29.default.dirname(import_node_path29.default.resolve(path53)), { recursive: true });
19552
19555
  const tmp = `${path53}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
@@ -19559,12 +19562,12 @@ async function saveCache(path53, cache) {
19559
19562
  }
19560
19563
  function pruneCache(cache, liveIds, namespace = "") {
19561
19564
  let removed = 0;
19562
- for (const key2 of Object.keys(cache.hashes)) {
19563
- const owned = namespace ? key2.startsWith(namespace) : !key2.includes(":");
19565
+ for (const key3 of Object.keys(cache.hashes)) {
19566
+ const owned = namespace ? key3.startsWith(namespace) : !key3.includes(":");
19564
19567
  if (!owned) continue;
19565
- const id = namespace ? key2.slice(namespace.length) : key2;
19568
+ const id = namespace ? key3.slice(namespace.length) : key3;
19566
19569
  if (!liveIds.has(id)) {
19567
- delete cache.hashes[key2];
19570
+ delete cache.hashes[key3];
19568
19571
  removed++;
19569
19572
  }
19570
19573
  }
@@ -19590,15 +19593,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19590
19593
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
19591
19594
  normalizeLockOutputPaths(lock, specs);
19592
19595
  const cacheDir = opts.cacheDir === false ? null : import_node_path30.default.resolve(opts.cacheDir ?? import_node_path30.default.join(import_node_path30.default.dirname(lockPath), ".pixelkiln", "cache"));
19593
- const pending = Object.entries(lock.entries).filter(([key2, e]) => {
19594
- if (e.provider !== provider.id || !specByKey.has(key2)) return false;
19595
- if (specByKey.get(key2)?.mirror) return false;
19596
- if (specByKey.get(key2)?.derive || specByKey.get(key2)?.external) return false;
19597
- if (specByKey.get(key2) && isHeldItem(specByKey.get(key2))) return false;
19596
+ const pending = Object.entries(lock.entries).filter(([key3, e]) => {
19597
+ if (e.provider !== provider.id || !specByKey.has(key3)) return false;
19598
+ if (specByKey.get(key3)?.mirror) return false;
19599
+ if (specByKey.get(key3)?.derive || specByKey.get(key3)?.external) return false;
19600
+ if (specByKey.get(key3) && isHeldItem(specByKey.get(key3))) return false;
19598
19601
  if (e.status === "selected" || e.status === "download-failed") return true;
19599
19602
  if (e.status !== "downloaded") return false;
19600
19603
  if (opts.refresh) return e.outputs.length > 0 && Boolean(e.sourceUrls?.length || e.sourceUrl);
19601
- const spec = specByKey.get(key2);
19604
+ const spec = specByKey.get(key3);
19602
19605
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
19603
19606
  return Boolean(opts.force) || e.outputs.every((output) => {
19604
19607
  const file = resolveOutputPath(output.path, spec.root);
@@ -19621,15 +19624,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19621
19624
  for (; ; ) {
19622
19625
  const next = pending[cursor++];
19623
19626
  if (!next) return;
19624
- const [key2, entry] = next;
19625
- const spec = specByKey.get(key2);
19627
+ const [key3, entry] = next;
19628
+ const spec = specByKey.get(key3);
19626
19629
  if (!spec) {
19627
- log(` skip ${key2} (not in current manifest)`);
19630
+ log(` skip ${key3} (not in current manifest)`);
19628
19631
  result.skipped++;
19629
19632
  continue;
19630
19633
  }
19631
19634
  if (entry.specHash !== spec.specHash) {
19632
- log(` skip ${key2} (source belongs to a stale spec)`);
19635
+ log(` skip ${key3} (source belongs to a stale spec)`);
19633
19636
  result.skipped++;
19634
19637
  continue;
19635
19638
  }
@@ -19646,16 +19649,16 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19646
19649
  });
19647
19650
  } catch (err) {
19648
19651
  const message6 = err instanceof Error ? err.message : String(err);
19649
- upsert(lock, key2, { status: "download-failed", error: `download failed: ${message6}` });
19652
+ upsert(lock, key3, { status: "download-failed", error: `download failed: ${message6}` });
19650
19653
  result.failed++;
19651
- log(` FAILED ${key2}: ${message6}`);
19654
+ log(` FAILED ${key3}: ${message6}`);
19652
19655
  await saveLock(lockPath, lock);
19653
19656
  continue;
19654
19657
  }
19655
19658
  if (current === null) {
19656
- upsert(lock, key2, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
19659
+ upsert(lock, key3, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
19657
19660
  result.failed++;
19658
- log(` FAILED ${key2}: ${entry.objectId} no longer exists upstream`);
19661
+ log(` FAILED ${key3}: ${entry.objectId} no longer exists upstream`);
19659
19662
  await saveLock(lockPath, lock);
19660
19663
  continue;
19661
19664
  }
@@ -19668,7 +19671,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19668
19671
  }
19669
19672
  }
19670
19673
  if (!sources.length) {
19671
- upsert(lock, key2, {
19674
+ upsert(lock, key3, {
19672
19675
  status: "download-failed",
19673
19676
  error: "no persisted source URL to download; poll the job again if it still exists upstream"
19674
19677
  });
@@ -19685,11 +19688,11 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19685
19688
  const parentSpec = spec.character?.parentSpec;
19686
19689
  const parentEntry = parentSpec ? lock.entries[lockKey(parentSpec.styleId, parentSpec.assetId)] : void 0;
19687
19690
  if (!parentSpec || !parentEntry?.outputs.length) {
19688
- throw new Error(`cannot clean ${key2}: ${wanted.despeckle.of} has no downloaded rotations to judge against`);
19691
+ throw new Error(`cannot clean ${key3}: ${wanted.despeckle.of} has no downloaded rotations to judge against`);
19689
19692
  }
19690
19693
  for (let index = 0; index < parentEntry.outputs.length; index++) {
19691
19694
  const file = currentEntryOutputPath(parentEntry, parentSpec, index);
19692
- if (!(0, import_node_fs27.existsSync)(file)) throw new Error(`cannot clean ${key2}: ${wanted.despeckle.of}'s rotation is missing on disk: ${file}`);
19695
+ if (!(0, import_node_fs27.existsSync)(file)) throw new Error(`cannot clean ${key3}: ${wanted.despeckle.of}'s rotation is missing on disk: ${file}`);
19693
19696
  reference.push(await (0, import_promises21.readFile)(file));
19694
19697
  }
19695
19698
  }
@@ -19810,7 +19813,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19810
19813
  mediaType,
19811
19814
  ...rawHash ? { raw: rawHash } : {}
19812
19815
  });
19813
- upsert(lock, key2, { outputs: mergeOutputs(entry.outputs, outputs) });
19816
+ upsert(lock, key3, { outputs: mergeOutputs(entry.outputs, outputs) });
19814
19817
  await saveLock(lockPath, lock);
19815
19818
  await (0, import_promises21.rename)(tmp, target);
19816
19819
  wrote = true;
@@ -19819,13 +19822,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19819
19822
  if (opts.refresh && !wrote) {
19820
19823
  if (rotated) {
19821
19824
  const persistent = sources.filter((source) => shouldPersistSourceUrl(source.url));
19822
- upsert(lock, key2, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
19825
+ upsert(lock, key3, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
19823
19826
  }
19824
19827
  result.unchanged = (result.unchanged ?? 0) + 1;
19825
19828
  continue;
19826
19829
  }
19827
19830
  const persistentSources = sources.filter((source) => shouldPersistSourceUrl(source.url));
19828
- upsert(lock, key2, {
19831
+ upsert(lock, key3, {
19829
19832
  status: "downloaded",
19830
19833
  provider: provider.id,
19831
19834
  outputs,
@@ -19842,13 +19845,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19842
19845
  result.downloaded++;
19843
19846
  } catch (err) {
19844
19847
  const message6 = err instanceof Error ? err.message : String(err);
19845
- upsert(lock, key2, {
19848
+ upsert(lock, key3, {
19846
19849
  status: "download-failed",
19847
19850
  outputs: mergeOutputs(entry.outputs, outputs),
19848
19851
  error: `download failed: ${message6}`
19849
19852
  });
19850
19853
  result.failed++;
19851
- log(` FAILED ${key2}: ${message6}`);
19854
+ log(` FAILED ${key3}: ${message6}`);
19852
19855
  }
19853
19856
  await saveLock(lockPath, lock);
19854
19857
  }
@@ -19897,8 +19900,8 @@ async function pushTags(provider, specs, lock, opts = {}) {
19897
19900
  });
19898
19901
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
19899
19902
  let tagged = 0;
19900
- for (const [key2, entry] of Object.entries(lock.entries)) {
19901
- const spec = specByKey.get(key2);
19903
+ for (const [key3, entry] of Object.entries(lock.entries)) {
19904
+ const spec = specByKey.get(key3);
19902
19905
  if (!spec || entry.provider !== provider.id || !entry.objectId) continue;
19903
19906
  if (entry.generator === "pixflux" || entry.generator === "vfx") continue;
19904
19907
  if (!provider.setTags) return tagged;
@@ -19906,7 +19909,7 @@ async function pushTags(provider, specs, lock, opts = {}) {
19906
19909
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
19907
19910
  tagged++;
19908
19911
  } catch (err) {
19909
- log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
19912
+ log(` tag failed ${key3}: ${err instanceof Error ? err.message : String(err)}`);
19910
19913
  }
19911
19914
  }
19912
19915
  return tagged;
@@ -19992,15 +19995,15 @@ function pickHistory(entry, selector) {
19992
19995
  return matches[0];
19993
19996
  }
19994
19997
  async function revertGeneration(provider, spec, lock, lockPath, opts) {
19995
- const key2 = lockKey(spec.styleId, spec.assetId);
19996
- const entry = lock.entries[key2];
19997
- if (!entry) throw new Error(`${key2} is not in the lockfile`);
19998
+ const key3 = lockKey(spec.styleId, spec.assetId);
19999
+ const entry = lock.entries[key3];
20000
+ if (!entry) throw new Error(`${key3} is not in the lockfile`);
19998
20001
  if (entry.status !== "downloaded") {
19999
- throw new Error(`${key2} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
20002
+ throw new Error(`${key3} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
20000
20003
  }
20001
20004
  const { index, generation } = pickHistory(entry, opts.generation);
20002
20005
  if (generation.provider !== provider.id) {
20003
- throw new Error(`${key2}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
20006
+ throw new Error(`${key3}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
20004
20007
  }
20005
20008
  for (let i = 0; i < entry.outputs.length; i++) {
20006
20009
  const file = currentEntryOutputPath(entry, spec, i);
@@ -20015,7 +20018,7 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
20015
20018
  const now = (/* @__PURE__ */ new Date()).toISOString();
20016
20019
  const remaining = (entry.history ?? []).filter((_, i) => i !== index - 1);
20017
20020
  const history = [retireGeneration(entry, now), ...remaining];
20018
- upsert(lock, key2, {
20021
+ upsert(lock, key3, {
20019
20022
  specHash: generation.specHash,
20020
20023
  generator: generation.generator,
20021
20024
  tileFeature: generation.tileFeature,
@@ -20306,7 +20309,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
20306
20309
  return { ...packed2, atlas: { ...packed2.atlas, style: styleId } };
20307
20310
  }
20308
20311
  const prefix = `${styleId}/`;
20309
- const entries = Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix));
20312
+ const entries = Object.entries(lock.entries).filter(([key3]) => key3.startsWith(prefix));
20310
20313
  const sources = options.sources ?? {};
20311
20314
  if (!entries.length && !Object.keys(sources).length) {
20312
20315
  throw new Error(
@@ -20325,8 +20328,8 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
20325
20328
  return parent ? layerSources(parent, seen.add(id)) : void 0;
20326
20329
  };
20327
20330
  const layered = [];
20328
- for (const [key2, entry] of entries) {
20329
- const id = key2.slice(prefix.length);
20331
+ for (const [key3, entry] of entries) {
20332
+ const id = key3.slice(prefix.length);
20330
20333
  locked.add(id);
20331
20334
  let outputs = resolveEntryOutputs(entry, id, manifestDir);
20332
20335
  const source = sources[id];
@@ -20417,14 +20420,14 @@ function mountSprites(placements, options) {
20417
20420
  }
20418
20421
  const byCell = /* @__PURE__ */ new Map();
20419
20422
  for (const p of placements) {
20420
- const key2 = `${p.cell[0]},${p.cell[1]}`;
20421
- const owner = byCell.get(key2);
20423
+ const key3 = `${p.cell[0]},${p.cell[1]}`;
20424
+ const owner = byCell.get(key3);
20422
20425
  if (owner) {
20423
20426
  throw new Error(
20424
- `mountSprites: "${p.id}" and "${owner}" both claim cell ${key2}; a cell has exactly one owner`
20427
+ `mountSprites: "${p.id}" and "${owner}" both claim cell ${key3}; a cell has exactly one owner`
20425
20428
  );
20426
20429
  }
20427
- byCell.set(key2, p.id);
20430
+ byCell.set(key3, p.id);
20428
20431
  }
20429
20432
  const loaded = [];
20430
20433
  const skipped = [];
@@ -20555,13 +20558,130 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
20555
20558
  };
20556
20559
  }
20557
20560
 
20561
+ // src/pipeline/connected-sets.ts
20562
+ var key2 = (spec) => `${spec.styleId}/${spec.assetId}`;
20563
+ var SIDES = ["lower", "upper"];
20564
+ function describe(prompt, side) {
20565
+ const parsed = prompt ? parseTerrainDescriptions(prompt) : null;
20566
+ const text = parsed?.[side];
20567
+ if (!text) return void 0;
20568
+ const clause = text.split(/[,;.]/)[0].replace(/\s+/g, " ").trim().toLowerCase();
20569
+ return clause ? clause.slice(0, 32).trim() : void 0;
20570
+ }
20571
+ function sideOf(name, terrainTypes) {
20572
+ const index = terrainTypes.indexOf(name);
20573
+ if (index === 0) return "lower";
20574
+ if (index === 1) return "upper";
20575
+ if (name === "transition") return "upper";
20576
+ throw new Error(`a tile corner is "${name}", which is not one of the set's terrains (${terrainTypes.join(", ")})`);
20577
+ }
20578
+ function mergeConnectedTerrain(members, manifestDir) {
20579
+ const ids = members.map((member) => member.spec.assetId);
20580
+ if (members.length < 2) throw new Error("a connected tileset needs at least two sets");
20581
+ for (const { spec } of members) {
20582
+ if (spec.terrainOrientation === "sidescroller") {
20583
+ throw new Error(
20584
+ `${key2(spec)} is a sidescroller set, which connects only its platform; export it on its own, without --merge-connected`
20585
+ );
20586
+ }
20587
+ }
20588
+ const tileTypes = new Set(members.map((member) => member.spec.tileType ?? ""));
20589
+ if (tileTypes.size > 1) {
20590
+ throw new Error(`connected sets ${ids.join(", ")} use different tile shapes; export them one at a time`);
20591
+ }
20592
+ const parent = /* @__PURE__ */ new Map();
20593
+ const find = (node) => {
20594
+ if (!parent.has(node)) parent.set(node, node);
20595
+ const above = parent.get(node);
20596
+ if (above === node) return node;
20597
+ const root = find(above);
20598
+ parent.set(node, root);
20599
+ return root;
20600
+ };
20601
+ const nodeOf = (assetId, side) => `${assetId}:${side}`;
20602
+ for (const { spec } of members) {
20603
+ for (const side of SIDES) {
20604
+ const other = spec.terrainConnect?.[side];
20605
+ if (other) parent.set(find(nodeOf(spec.assetId, side)), find(nodeOf(other.assetId, other.terrain)));
20606
+ }
20607
+ }
20608
+ const indexOfClass = /* @__PURE__ */ new Map();
20609
+ const names = [];
20610
+ const taken = /* @__PURE__ */ new Set();
20611
+ const defining = /* @__PURE__ */ new Map();
20612
+ for (const { spec } of members) {
20613
+ for (const side of SIDES) {
20614
+ const root = find(nodeOf(spec.assetId, side));
20615
+ if (!indexOfClass.has(root)) {
20616
+ indexOfClass.set(root, names.length);
20617
+ names.push("");
20618
+ }
20619
+ if (!spec.terrainConnect?.[side] && !defining.has(root)) defining.set(root, nodeOf(spec.assetId, side));
20620
+ }
20621
+ }
20622
+ for (const [root, index] of indexOfClass) {
20623
+ const node = defining.get(root) ?? root;
20624
+ const [assetId, side] = node.split(":");
20625
+ const member = members.find((candidate) => candidate.spec.assetId === assetId);
20626
+ const base = describe(member.spec.prompt, side) ?? `${assetId}_${side}`;
20627
+ let name = base;
20628
+ for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
20629
+ taken.add(name);
20630
+ names[index] = name;
20631
+ }
20632
+ const tiles = [];
20633
+ const providerRules = {};
20634
+ for (const { spec, entry } of members) {
20635
+ const metadata = entry.providerMetadata?.[entry.provider];
20636
+ const terrainTypes = Array.isArray(metadata?.terrainTypes) ? metadata.terrainTypes.filter((item) => typeof item === "string") : [];
20637
+ const terrainTiles = Array.isArray(metadata?.terrainTiles) ? metadata.terrainTiles : [];
20638
+ if (terrainTypes.length < 2 || !terrainTiles.length) {
20639
+ throw new Error(`${key2(spec)} has no terrain tile data; regenerate it before merging`);
20640
+ }
20641
+ providerRules[spec.assetId] = metadata;
20642
+ let outputs = resolveSpecEntryOutputs(entry, spec);
20643
+ if (!outputs.length) throw new Error(`${key2(spec)} has no downloaded outputs`);
20644
+ if (spec.source && sourceIsStem(spec.source, entry, manifestDir)) {
20645
+ outputs = outputs.map((output) => ({ ...output, absolutePath: sourceOutputPath(spec.source, entry, output.index, manifestDir) }));
20646
+ }
20647
+ for (const output of outputs) {
20648
+ const tile = (output.role ? terrainTiles.find((item) => isRecord2(item) && item.role === output.role) : void 0) ?? terrainTiles[output.index];
20649
+ if (!isRecord2(tile) || !isRecord2(tile.corners)) continue;
20650
+ const corner = (position) => {
20651
+ const name = tile.corners && tile.corners[position];
20652
+ if (typeof name !== "string") throw new Error(`${key2(spec)}: ${output.role ?? output.index} has no ${position} corner`);
20653
+ return indexOfClass.get(find(nodeOf(spec.assetId, sideOf(name, terrainTypes))));
20654
+ };
20655
+ tiles.push({
20656
+ id: `${spec.assetId}/${output.role ?? `tile-${String(output.index).padStart(2, "0")}`}`,
20657
+ assetId: spec.assetId,
20658
+ path: output.absolutePath,
20659
+ corners: [corner("NW"), corner("NE"), corner("SW"), corner("SE")]
20660
+ });
20661
+ }
20662
+ }
20663
+ if (!tiles.length) throw new Error(`connected sets ${ids.join(", ")} have no tiles with corner data`);
20664
+ return { assets: ids, terrains: names, tiles, tileType: members[0].spec.tileType, providerRules };
20665
+ }
20666
+ function tileCorners(rules, tile) {
20667
+ if (tile.corners) return tile.corners;
20668
+ if (rules.ruleType !== "corner" || tile.bitmask === void 0) return null;
20669
+ const mask = tile.bitmask;
20670
+ const corner = (bit) => (mask & 1 << bit) !== 0 ? 0 : 1;
20671
+ return [corner(3), corner(2), corner(1), corner(0)];
20672
+ }
20673
+ var TERRAIN_PALETTE = ["#5ab552", "#4c78a8", "#e0a458", "#a0522d", "#9b6bd1", "#d9534f", "#4fb8b8", "#8c8c8c"];
20674
+ var terrainColor = (index) => TERRAIN_PALETTE[index % TERRAIN_PALETTE.length];
20675
+ function isRecord2(value) {
20676
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20677
+ }
20678
+
20558
20679
  // src/pipeline/ldtk-export.ts
20559
20680
  var import_node_crypto8 = require("crypto");
20560
20681
  var LDTK_JSON_VERSION = "1.5.3";
20561
20682
  var FIRST = 1;
20562
20683
  var SECOND = 2;
20563
- var DEMO_WIDTH = 12;
20564
- var DEMO_HEIGHT = 9;
20684
+ var DEMO_SIZE = { small: [12, 9], large: [16, 12] };
20565
20685
  function ldtkRuleMatches(rule, grid, cx, cy) {
20566
20686
  const radius = Math.floor(rule.size / 2);
20567
20687
  for (let py = 0; py < rule.size; py++) {
@@ -20607,6 +20727,14 @@ function ldtkPattern(rules, mask) {
20607
20727
  pattern[3] = value(3);
20608
20728
  return pattern;
20609
20729
  }
20730
+ function ldtkCornerPattern(corners) {
20731
+ const pattern = new Array(9).fill(0);
20732
+ pattern[4] = corners[0] + 1;
20733
+ pattern[5] = corners[1] + 1;
20734
+ pattern[7] = corners[2] + 1;
20735
+ pattern[8] = corners[3] + 1;
20736
+ return pattern;
20737
+ }
20610
20738
  function resolveLdtkTiles(rules, grid) {
20611
20739
  const out = [];
20612
20740
  for (let cy = 0; cy < grid.height; cy++) {
@@ -20617,16 +20745,16 @@ function resolveLdtkTiles(rules, grid) {
20617
20745
  }
20618
20746
  return out;
20619
20747
  }
20620
- function demoGrid(rules, wanted) {
20748
+ function demoGrid(rules, wanted, width, height) {
20621
20749
  let best = null;
20622
20750
  let bestCovered = -1;
20623
20751
  for (let seed = 1; seed <= 400; seed++) {
20624
20752
  let state = seed * 2654435761 >>> 0;
20625
- const cells = Array.from({ length: DEMO_WIDTH * DEMO_HEIGHT }, () => {
20753
+ const cells = Array.from({ length: width * height }, () => {
20626
20754
  state = Math.imul(state, 1664525) + 1013904223 >>> 0;
20627
20755
  return (state >>> 16) % 100 < 52 ? FIRST : SECOND;
20628
20756
  });
20629
- const grid = { width: DEMO_WIDTH, height: DEMO_HEIGHT, cells };
20757
+ const grid = { width, height, cells };
20630
20758
  const covered = new Set(resolveLdtkTiles(rules, grid).map((hit) => hit.rule.uid)).size;
20631
20759
  if (covered > bestCovered) {
20632
20760
  best = grid;
@@ -20636,7 +20764,63 @@ function demoGrid(rules, wanted) {
20636
20764
  }
20637
20765
  return best;
20638
20766
  }
20639
- var TERRAIN_COLORS = ["#5AB552", "#4C78A8"];
20767
+ function constrainedDemoGrid(rules, combos, count, outside, width, height) {
20768
+ const stride = width + 1;
20769
+ const comboList = [...combos].map((combo) => combo.split(",").map(Number));
20770
+ let best = null;
20771
+ let bestCovered = -1;
20772
+ for (let seed = 1; seed <= 600; seed++) {
20773
+ let state = seed * 2654435761 >>> 0;
20774
+ const random = () => {
20775
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
20776
+ return (state >>> 8) / 16777216;
20777
+ };
20778
+ const vertices = new Array(stride * (height + 1)).fill(0);
20779
+ for (let x = 0; x <= width; x++) vertices[height * stride + x] = outside;
20780
+ for (let y = 0; y <= height; y++) vertices[y * stride + width] = outside;
20781
+ const at2 = (x, y) => vertices[y * stride + x];
20782
+ const comboAt = (x, y) => {
20783
+ if (x < 0 || y < 0 || x >= width || y >= height) return void 0;
20784
+ const painted = [at2(x, y), at2(x + 1, y), at2(x, y + 1), at2(x + 1, y + 1)];
20785
+ if (!comboList.some((combo) => combo.every((terrain, corner) => !painted[corner] || painted[corner] === terrain + 1))) return null;
20786
+ return painted.every(Boolean) ? painted.map((value) => value - 1).join(",") : void 0;
20787
+ };
20788
+ const around = (x, y) => [comboAt(x - 1, y - 1), comboAt(x, y - 1), comboAt(x - 1, y), comboAt(x, y)];
20789
+ const seen = /* @__PURE__ */ new Set();
20790
+ let ok = true;
20791
+ for (let y = 0; y < height && ok; y++) {
20792
+ for (let x = 0; x < width && ok; x++) {
20793
+ const options = [];
20794
+ for (let value = 1; value <= count; value++) {
20795
+ vertices[y * stride + x] = value;
20796
+ const made = around(x, y);
20797
+ if (made.includes(null)) continue;
20798
+ options.push({ value, fresh: made.filter((combo) => combo !== void 0 && !seen.has(combo)).length });
20799
+ }
20800
+ if (!options.length) {
20801
+ ok = false;
20802
+ break;
20803
+ }
20804
+ const best2 = Math.max(...options.map((option) => option.fresh));
20805
+ const pool = best2 > 0 && random() < 0.85 ? options.filter((option) => option.fresh === best2) : options;
20806
+ vertices[y * stride + x] = pool[Math.floor(random() * pool.length)].value;
20807
+ for (const combo of around(x, y)) if (combo) seen.add(combo);
20808
+ }
20809
+ }
20810
+ if (!ok) continue;
20811
+ const cells = [];
20812
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) cells.push(at2(x, y));
20813
+ const grid = { width, height, cells };
20814
+ const covered = new Set(resolveLdtkTiles(rules, grid).map((hit) => hit.rule.uid)).size;
20815
+ if (covered > bestCovered) {
20816
+ best = grid;
20817
+ bestCovered = covered;
20818
+ }
20819
+ if (covered >= rules.length) break;
20820
+ }
20821
+ if (!best) throw new Error("ldtk export could not paint a preview level for these connected sets");
20822
+ return best;
20823
+ }
20640
20824
  function buildLdtk(generic, tileType) {
20641
20825
  const rules = generic.rules;
20642
20826
  if (!rules || rules.ruleType === "outline") {
@@ -20654,20 +20838,27 @@ function buildLdtk(generic, tileType) {
20654
20838
  const corner = rules.ruleType === "corner";
20655
20839
  const base = identifier(generic.name.replace("/", "_"), "Tileset");
20656
20840
  const name = base.charAt(0).toUpperCase() + base.slice(1);
20657
- const terrainNames = [rules.terrains[0] ?? "feature", rules.terrains[1] ?? "background"];
20841
+ const merged = rules.terrains.length > 2;
20842
+ const terrainNames = merged ? rules.terrains : [rules.terrains[0] ?? "feature", rules.terrains[1] ?? "background"];
20843
+ const [demoWidth, demoHeight] = merged ? DEMO_SIZE.large : DEMO_SIZE.small;
20658
20844
  const columns = generic.sheet.columns;
20659
20845
  const rows = Math.ceil(generic.tiles.length / columns);
20660
- const byMask = /* @__PURE__ */ new Map();
20846
+ const byAdjacency = /* @__PURE__ */ new Map();
20661
20847
  for (const tile of generic.tiles) {
20662
- if (tile.bitmask === void 0) continue;
20663
- byMask.set(tile.bitmask, [...byMask.get(tile.bitmask) ?? [], tile.id]);
20664
- }
20665
- if (!byMask.size) throw new Error("ldtk export found no tiles with adjacency masks; use --format generic");
20848
+ const corners = corner ? tileCorners(rules, tile) : null;
20849
+ if (corner ? !corners : tile.bitmask === void 0) continue;
20850
+ const adjacency = corners ? corners.join(",") : String(tile.bitmask);
20851
+ const known = byAdjacency.get(adjacency);
20852
+ if (known) known.ids.push(tile.id);
20853
+ else byAdjacency.set(adjacency, { pattern: corners ? ldtkCornerPattern(corners) : ldtkPattern(rules, tile.bitmask), ids: [tile.id] });
20854
+ }
20855
+ if (!byAdjacency.size) throw new Error("ldtk export found no tiles with adjacency rules; use --format generic");
20856
+ const outside = merged ? FIRST : SECOND;
20666
20857
  const tilesetUid = 1;
20667
20858
  const sourceUid = 2;
20668
20859
  const autoUid = 3;
20669
20860
  const groupUid = 4;
20670
- const ruleList = [...byMask.entries()].map(([mask, ids], index) => ({
20861
+ const ruleList = [...byAdjacency.values()].map(({ pattern, ids }, index) => ({
20671
20862
  uid: 5 + index,
20672
20863
  active: true,
20673
20864
  size: 3,
@@ -20675,7 +20866,7 @@ function buildLdtk(generic, tileType) {
20675
20866
  alpha: 1,
20676
20867
  chance: 1,
20677
20868
  breakOnMatch: true,
20678
- pattern: ldtkPattern(rules, mask),
20869
+ pattern,
20679
20870
  flipX: false,
20680
20871
  flipY: false,
20681
20872
  xModulo: 1,
@@ -20692,7 +20883,7 @@ function buildLdtk(generic, tileType) {
20692
20883
  tileMode: "Single",
20693
20884
  pivotX: 0,
20694
20885
  pivotY: 0,
20695
- outOfBoundsValue: SECOND,
20886
+ outOfBoundsValue: outside,
20696
20887
  invalidated: false,
20697
20888
  perlinActive: false,
20698
20889
  perlinSeed: 1,
@@ -20706,9 +20897,10 @@ function buildLdtk(generic, tileType) {
20706
20897
  return tile ? { tilesetUid, x: tile.x, y: tile.y, w: tile.width, h: tile.height } : null;
20707
20898
  };
20708
20899
  const full = (1 << rules.arity) - 1;
20709
- const representative = (terrain) => generic.tiles.find((tile) => tile.bitmask === (terrain === 0 ? full : 0))?.id;
20900
+ const representative = (terrain) => corner ? generic.tiles.find((tile) => tileCorners(rules, tile)?.every((value) => value === terrain))?.id : generic.tiles.find((tile) => tile.bitmask === (terrain === 0 ? full : 0))?.id;
20710
20901
  const shift = corner ? -Math.floor(grid / 2) : 0;
20711
20902
  const sourceName = `${name}_${corner ? "corners" : "cells"}`;
20903
+ const paintList = terrainNames.map((terrainName, index) => `${terrainName} (${index + 1})`).join(", ");
20712
20904
  const autoName = name;
20713
20905
  const layerBase = {
20714
20906
  guideGridWid: 0,
@@ -20737,16 +20929,16 @@ function buildLdtk(generic, tileType) {
20737
20929
  identifier: sourceName,
20738
20930
  type: "IntGrid",
20739
20931
  uid: sourceUid,
20740
- doc: corner ? `Paint ${terrainNames[0]} (1) and ${terrainNames[1]} (2). Each cell is a corner where four tiles meet, so it is drawn half a tile up and left of the tiles it controls.` : `Paint ${terrainNames[0]} (1) and ${terrainNames[1]} (2). Each tile looks at its own cell and the four around it.`,
20741
- uiColor: TERRAIN_COLORS[0],
20932
+ doc: `Paint ${paintList}. ` + (corner ? "Each cell is a corner where four tiles meet, so it is drawn half a tile up and left of the tiles it controls." : "Each tile looks at its own cell and the four around it."),
20933
+ uiColor: terrainColor(0).toUpperCase(),
20742
20934
  ...layerBase,
20743
20935
  renderInWorldView: true,
20744
20936
  pxOffsetX: shift,
20745
20937
  pxOffsetY: shift,
20746
- intGridValues: [FIRST, SECOND].map((value, index) => ({
20747
- value,
20748
- identifier: identifier(terrainNames[index], `terrain${value}`),
20749
- color: TERRAIN_COLORS[index],
20938
+ intGridValues: terrainNames.map((terrainName, index) => ({
20939
+ value: index + 1,
20940
+ identifier: identifier(terrainName, `terrain${index + 1}`),
20941
+ color: terrainColor(index).toUpperCase(),
20750
20942
  tile: tileRect(representative(index)),
20751
20943
  groupUid: 0
20752
20944
  })),
@@ -20759,8 +20951,8 @@ function buildLdtk(generic, tileType) {
20759
20951
  identifier: autoName,
20760
20952
  type: "AutoLayer",
20761
20953
  uid: autoUid,
20762
- doc: `Drawn by rules from ${sourceName}: one rule for each way the two terrains can meet.`,
20763
- uiColor: TERRAIN_COLORS[1],
20954
+ doc: `Drawn by rules from ${sourceName}: one rule for each way the ${merged ? "terrains" : "two terrains"} can meet.`,
20955
+ uiColor: terrainColor(1).toUpperCase(),
20764
20956
  ...layerBase,
20765
20957
  renderInWorldView: true,
20766
20958
  pxOffsetX: 0,
@@ -20781,14 +20973,21 @@ function buildLdtk(generic, tileType) {
20781
20973
  }],
20782
20974
  autoSourceLayerDefUid: sourceUid
20783
20975
  };
20784
- const level = demoGrid(ruleList, ruleList.length);
20976
+ const level = merged ? constrainedDemoGrid(
20977
+ ruleList,
20978
+ new Set(generic.tiles.flatMap((tile) => tile.corners ? [tile.corners.join(",")] : [])),
20979
+ terrainNames.length,
20980
+ outside,
20981
+ demoWidth,
20982
+ demoHeight
20983
+ ) : demoGrid(ruleList, ruleList.length, demoWidth, demoHeight);
20785
20984
  const hits = resolveLdtkTiles(ruleList, level);
20786
20985
  const tileAt = (id) => ({ x: id % columns * grid, y: Math.floor(id / columns) * grid });
20787
20986
  const instanceBase = (layerDef, offset) => ({
20788
20987
  __identifier: layerDef.identifier,
20789
20988
  __type: layerDef.__type,
20790
- __cWid: DEMO_WIDTH,
20791
- __cHei: DEMO_HEIGHT,
20989
+ __cWid: demoWidth,
20990
+ __cHei: demoHeight,
20792
20991
  __gridSize: grid,
20793
20992
  __opacity: 1,
20794
20993
  __pxTotalOffsetX: offset,
@@ -20826,8 +21025,8 @@ function buildLdtk(generic, tileType) {
20826
21025
  worldLayout: "LinearHorizontal",
20827
21026
  worldGridWidth: 256,
20828
21027
  worldGridHeight: 256,
20829
- defaultLevelWidth: DEMO_WIDTH * grid,
20830
- defaultLevelHeight: DEMO_HEIGHT * grid,
21028
+ defaultLevelWidth: demoWidth * grid,
21029
+ defaultLevelHeight: demoHeight * grid,
20831
21030
  defaultPivotX: 0,
20832
21031
  defaultPivotY: 0,
20833
21032
  defaultGridSize: grid,
@@ -20867,7 +21066,7 @@ function buildLdtk(generic, tileType) {
20867
21066
  tags: [],
20868
21067
  tagsSourceEnumUid: null,
20869
21068
  enumTags: [],
20870
- customData: generic.tiles.filter((tile) => tile.bitmask !== void 0).map((tile) => ({ tileId: tile.id, data: `mask=${tile.bitmask}` })),
21069
+ customData: generic.tiles.filter((tile) => tile.bitmask !== void 0 || tile.corners !== void 0).map((tile) => ({ tileId: tile.id, data: tile.corners ? `corners=${tile.corners.join(",")}` : `mask=${tile.bitmask}` })),
20871
21070
  savedSelections: [],
20872
21071
  cachedPixelData: null
20873
21072
  }],
@@ -20883,8 +21082,8 @@ function buildLdtk(generic, tileType) {
20883
21082
  worldX: -1,
20884
21083
  worldY: -1,
20885
21084
  worldDepth: 0,
20886
- pxWid: DEMO_WIDTH * grid,
20887
- pxHei: DEMO_HEIGHT * grid,
21085
+ pxWid: demoWidth * grid,
21086
+ pxHei: demoHeight * grid,
20888
21087
  __bgColor: "#474B67",
20889
21088
  bgColor: null,
20890
21089
  useAutoIdentifier: false,
@@ -20905,7 +21104,7 @@ function buildLdtk(generic, tileType) {
20905
21104
  src: [tileAt(hit.tile).x, tileAt(hit.tile).y],
20906
21105
  f: 0,
20907
21106
  t: hit.tile,
20908
- d: [hit.rule.uid, hit.cy * DEMO_WIDTH + hit.cx],
21107
+ d: [hit.rule.uid, hit.cy * demoWidth + hit.cx],
20909
21108
  a: 1
20910
21109
  }))
20911
21110
  },
@@ -20925,16 +21124,16 @@ function buildLdtk(generic, tileType) {
20925
21124
 
20926
21125
  // src/pipeline/tileset-export.ts
20927
21126
  function normalizeTileRules(raw) {
20928
- if (!isRecord2(raw)) return null;
21127
+ if (!isRecord3(raw)) return null;
20929
21128
  const ruleType = raw.rule_type;
20930
21129
  const arity = raw.arity;
20931
21130
  if (ruleType !== "edge" && ruleType !== "corner" && ruleType !== "outline") return null;
20932
21131
  if (arity !== 4 && arity !== 6) return null;
20933
21132
  const masks = {};
20934
- if (isRecord2(raw.tiles)) {
20935
- for (const [key2, value] of Object.entries(raw.tiles)) {
20936
- const index = tileIndex(key2);
20937
- const mask = typeof value === "number" ? value : isRecord2(value) && typeof value.bitmask === "number" ? value.bitmask : isRecord2(value) && typeof value.mask === "number" ? value.mask : null;
21133
+ if (isRecord3(raw.tiles)) {
21134
+ for (const [key3, value] of Object.entries(raw.tiles)) {
21135
+ const index = tileIndex(key3);
21136
+ const mask = typeof value === "number" ? value : isRecord3(value) && typeof value.bitmask === "number" ? value.bitmask : isRecord3(value) && typeof value.mask === "number" ? value.mask : null;
20938
21137
  if (index !== null && mask !== null && Number.isInteger(mask) && mask >= 0) masks[index] = mask;
20939
21138
  }
20940
21139
  }
@@ -20950,12 +21149,12 @@ function normalizeTileRules(raw) {
20950
21149
  };
20951
21150
  }
20952
21151
  function normalizeTerrainTiles(metadata) {
20953
- if (!isRecord2(metadata) || !Array.isArray(metadata.terrainTiles)) return null;
21152
+ if (!isRecord3(metadata) || !Array.isArray(metadata.terrainTiles)) return null;
20954
21153
  const terrains = Array.isArray(metadata.terrainTypes) ? metadata.terrainTypes.filter((item) => typeof item === "string") : [];
20955
21154
  if (terrains.length < 2) return null;
20956
21155
  const masks = {};
20957
21156
  metadata.terrainTiles.forEach((tile, index) => {
20958
- if (!isRecord2(tile) || !isRecord2(tile.corners)) return;
21157
+ if (!isRecord3(tile) || !isRecord3(tile.corners)) return;
20959
21158
  const corners = tile.corners;
20960
21159
  const bit = (corner) => corners[corner] === terrains[0] ? 1 : 0;
20961
21160
  masks[index] = bit("NW") << 3 | bit("NE") << 2 | bit("SW") << 1 | bit("SE");
@@ -20987,13 +21186,13 @@ function exportTileset(entry, spec, options) {
20987
21186
  );
20988
21187
  }
20989
21188
  const metadata = entry.providerMetadata?.[entry.provider];
20990
- const rawRules = isRecord2(metadata) ? metadata.tileRules : void 0;
21189
+ const rawRules = isRecord3(metadata) ? metadata.tileRules : void 0;
20991
21190
  const terrainRules = normalizeTerrainTiles(metadata);
20992
21191
  const rules = normalizeTileRules(rawRules) ?? terrainRules;
20993
- const providerRules = isRecord2(rawRules) ? rawRules : terrainRules ? metadata : null;
21192
+ const providerRules = isRecord3(rawRules) ? rawRules : terrainRules ? metadata : null;
20994
21193
  const frames = packed.atlas.frames;
20995
21194
  const generic = buildGeneric(
20996
- spec,
21195
+ { name: `${spec.styleId}/${spec.assetId}`, style: spec.styleId, asset: spec.assetId },
20997
21196
  options.imageName,
20998
21197
  packed.atlas,
20999
21198
  frames,
@@ -21030,6 +21229,9 @@ function exportTileset(entry, spec, options) {
21030
21229
  "godot export does not yet map edge/side adjacency onto an isometric or oblique tile's diagonal peering bits safely; use --format generic or --format tiled"
21031
21230
  );
21032
21231
  }
21232
+ return renderTileset(generic, packed, spec.tileType, options);
21233
+ }
21234
+ function renderTileset(generic, packed, tileType, options) {
21033
21235
  if (options.format === "tiled") {
21034
21236
  return {
21035
21237
  png: packed.png,
@@ -21043,7 +21245,7 @@ function exportTileset(entry, spec, options) {
21043
21245
  return {
21044
21246
  png: packed.png,
21045
21247
  extension: ".ldtk",
21046
- document: buildLdtk(generic, spec.tileType),
21248
+ document: buildLdtk(generic, tileType),
21047
21249
  generic,
21048
21250
  sources: packed.sources
21049
21251
  };
@@ -21051,23 +21253,67 @@ function exportTileset(entry, spec, options) {
21051
21253
  return {
21052
21254
  png: packed.png,
21053
21255
  extension: ".tres",
21054
- document: buildGodot(generic, spec),
21256
+ document: buildGodot(generic, tileType),
21055
21257
  generic,
21056
21258
  sources: packed.sources
21057
21259
  };
21058
21260
  }
21059
- function buildGeneric(spec, imageName, atlas, frames, providerRules, rules) {
21261
+ function exportMergedTilesets(members, options) {
21262
+ const merged = mergeConnectedTerrain(members, options.manifestDir);
21263
+ const packed = packSprites(
21264
+ merged.tiles.map((tile) => ({ id: tile.id, path: tile.path })),
21265
+ { columns: options.columns, order: "input" }
21266
+ );
21267
+ if (packed.skipped.length) {
21268
+ throw new Error(
21269
+ `Cannot export ${merged.assets.join(" + ")}: ` + packed.skipped.map((item) => `${item.id}: ${item.reason}`).join("; ")
21270
+ );
21271
+ }
21272
+ const rules = {
21273
+ ruleType: "corner",
21274
+ arity: 4,
21275
+ terrains: merged.terrains,
21276
+ masks: {},
21277
+ corners: Object.fromEntries(merged.tiles.map((tile, index) => [index, tile.corners])),
21278
+ raw: merged.providerRules
21279
+ };
21280
+ const styleId = members[0].spec.styleId;
21281
+ const asset = merged.assets.join("+");
21282
+ const generic = buildGeneric(
21283
+ { name: `${styleId}/${asset}`, style: styleId, asset, sets: merged.assets },
21284
+ options.imageName,
21285
+ packed.atlas,
21286
+ packed.atlas.frames,
21287
+ merged.providerRules,
21288
+ rules,
21289
+ new Map(merged.tiles.map((tile, index) => [tile.id, index]))
21290
+ );
21291
+ if (options.format === "generic") {
21292
+ return {
21293
+ png: packed.png,
21294
+ extension: ".json",
21295
+ document: JSON.stringify(generic, null, 2) + "\n",
21296
+ generic,
21297
+ sources: packed.sources
21298
+ };
21299
+ }
21300
+ assertUniformTiles(generic);
21301
+ return renderTileset(generic, packed, merged.tileType, options);
21302
+ }
21303
+ function buildGeneric(identity2, imageName, atlas, frames, providerRules, rules, indexOf) {
21060
21304
  return {
21061
21305
  format: "pixelkiln-tileset",
21062
21306
  version: 1,
21063
- name: `${spec.styleId}/${spec.assetId}`,
21064
- style: spec.styleId,
21065
- asset: spec.assetId,
21307
+ name: identity2.name,
21308
+ style: identity2.style,
21309
+ asset: identity2.asset,
21310
+ ...identity2.sets ? { sets: identity2.sets } : {},
21066
21311
  image: imageName,
21067
21312
  tile: { ...atlas.cell },
21068
21313
  sheet: { ...atlas.sheet, columns: atlas.columns },
21069
21314
  tiles: frames.map((frame, index) => {
21070
- const sourceIndex = tileIndex(frame.id) ?? index;
21315
+ const sourceIndex = indexOf?.get(frame.id) ?? tileIndex(frame.id) ?? index;
21316
+ const corners = rules?.corners?.[sourceIndex];
21071
21317
  return {
21072
21318
  id: index,
21073
21319
  sourceIndex,
@@ -21077,7 +21323,8 @@ function buildGeneric(spec, imageName, atlas, frames, providerRules, rules) {
21077
21323
  width: frame.width,
21078
21324
  height: frame.height,
21079
21325
  ...rules?.masks[sourceIndex] !== void 0 ? { bitmask: rules.masks[sourceIndex] } : {},
21080
- stampOnly: rules ? rules.masks[sourceIndex] === void 0 : true
21326
+ ...corners ? { corners } : {},
21327
+ stampOnly: rules ? rules.masks[sourceIndex] === void 0 && !corners : true
21081
21328
  };
21082
21329
  }),
21083
21330
  providerRules,
@@ -21109,25 +21356,28 @@ function buildTiled(generic) {
21109
21356
  tile: representativeTile(generic, 0),
21110
21357
  colors: terrainNames.map((name, index) => ({
21111
21358
  name,
21112
- color: index === 0 ? "#5ab552" : "#4c78a8",
21359
+ color: terrainColor(index),
21113
21360
  tile: representativeTile(generic, index),
21114
21361
  probability: 1
21115
21362
  })),
21116
21363
  properties: rules.connectivity ? [{ name: "pixelkiln:connectivity", type: "string", value: rules.connectivity }] : [],
21117
- wangtiles: generic.tiles.filter((tile) => tile.bitmask !== void 0).map((tile) => ({ tileid: tile.id, wangid: tiledWangId(rules, tile.bitmask) }))
21364
+ wangtiles: generic.tiles.filter((tile) => tile.bitmask !== void 0 || tile.corners !== void 0).map((tile) => ({ tileid: tile.id, wangid: tiledWangId(rules, tile) }))
21118
21365
  }];
21119
21366
  return tiled;
21120
21367
  }
21121
- function tiledWangId(rules, mask) {
21122
- const bitColor = (bit) => (mask & 1 << bit) !== 0 ? 1 : 2;
21123
- if (rules.ruleType === "corner") {
21124
- return [0, bitColor(2), 0, bitColor(0), 0, bitColor(1), 0, bitColor(3)];
21368
+ function tiledWangId(rules, tile) {
21369
+ const corners = tileCorners(rules, tile);
21370
+ if (corners) {
21371
+ const [nw, ne, sw, se] = corners;
21372
+ return [0, ne + 1, 0, se + 1, 0, sw + 1, 0, nw + 1];
21125
21373
  }
21374
+ const mask = tile.bitmask;
21375
+ const bitColor = (bit) => (mask & 1 << bit) !== 0 ? 1 : 2;
21126
21376
  return [bitColor(0), 0, bitColor(1), 0, bitColor(2), 0, bitColor(3), 0];
21127
21377
  }
21128
- function buildGodot(generic, spec) {
21378
+ function buildGodot(generic, tileType) {
21129
21379
  const rules = generic.rules;
21130
- const shape = godotTileShape(spec.tileType ?? "isometric");
21380
+ const shape = godotTileShape(tileType ?? "isometric");
21131
21381
  const lines = [
21132
21382
  `[gd_resource type="TileSet" load_steps=3 format=3]`,
21133
21383
  "",
@@ -21141,8 +21391,8 @@ function buildGodot(generic, spec) {
21141
21391
  const x = tile.id % generic.sheet.columns;
21142
21392
  const y = Math.floor(tile.id / generic.sheet.columns);
21143
21393
  lines.push(`${x}:${y}/0 = 0`);
21144
- if (!rules || tile.bitmask === void 0 || rules.ruleType === "outline") continue;
21145
- const values = godotTerrainBits(rules, tile.bitmask, shape);
21394
+ if (!rules || tile.bitmask === void 0 && tile.corners === void 0 || rules.ruleType === "outline") continue;
21395
+ const values = godotTerrainBits(rules, tile, shape);
21146
21396
  lines.push(`${x}:${y}/0/terrain_set = 0`);
21147
21397
  lines.push(`${x}:${y}/0/terrain = ${dominantTerrain(values)}`);
21148
21398
  for (const [side, value] of Object.entries(values)) {
@@ -21156,32 +21406,23 @@ function buildGodot(generic, spec) {
21156
21406
  lines.push(`terrain_set_0/mode = ${rules.ruleType === "corner" ? 1 : 2}`);
21157
21407
  for (const [index, name] of terrainNamesFor(rules).entries()) {
21158
21408
  lines.push(`terrain_set_0/terrain_${index}/name = ${JSON.stringify(name)}`);
21159
- lines.push(
21160
- `terrain_set_0/terrain_${index}/color = ` + (index === 0 ? "Color(0.3529, 0.7098, 0.3216, 1)" : "Color(0.298, 0.4706, 0.6588, 1)")
21161
- );
21409
+ lines.push(`terrain_set_0/terrain_${index}/color = ${godotColor(terrainColor(index))}`);
21162
21410
  }
21163
21411
  }
21164
21412
  lines.push(`sources/0 = SubResource("TileSetAtlasSource_pixelkiln")`, "");
21165
21413
  return lines.join("\n");
21166
21414
  }
21167
- function godotTerrainBits(rules, mask, shape) {
21168
- const terrain = (bit) => (mask & 1 << bit) !== 0 ? 0 : 1;
21169
- if (rules.ruleType === "corner") {
21415
+ function godotTerrainBits(rules, tile, shape) {
21416
+ const corners = tileCorners(rules, tile);
21417
+ if (corners) {
21418
+ const [nw, ne, sw, se] = corners;
21170
21419
  if (shape === 1) {
21171
- return {
21172
- top_corner: terrain(3),
21173
- right_corner: terrain(2),
21174
- left_corner: terrain(1),
21175
- bottom_corner: terrain(0)
21176
- };
21420
+ return { top_corner: nw, right_corner: ne, left_corner: sw, bottom_corner: se };
21177
21421
  }
21178
- return {
21179
- top_left_corner: terrain(3),
21180
- top_right_corner: terrain(2),
21181
- bottom_left_corner: terrain(1),
21182
- bottom_right_corner: terrain(0)
21183
- };
21422
+ return { top_left_corner: nw, top_right_corner: ne, bottom_left_corner: sw, bottom_right_corner: se };
21184
21423
  }
21424
+ const mask = tile.bitmask;
21425
+ const terrain = (bit) => (mask & 1 << bit) !== 0 ? 0 : 1;
21185
21426
  return {
21186
21427
  top_side: terrain(0),
21187
21428
  right_side: terrain(1),
@@ -21190,8 +21431,17 @@ function godotTerrainBits(rules, mask, shape) {
21190
21431
  };
21191
21432
  }
21192
21433
  function dominantTerrain(values) {
21193
- const terrainZero = Object.values(values).filter((value) => value === 0).length;
21194
- return terrainZero * 2 >= Object.keys(values).length ? 0 : 1;
21434
+ const counts = /* @__PURE__ */ new Map();
21435
+ for (const value of Object.values(values)) counts.set(value, (counts.get(value) ?? 0) + 1);
21436
+ let best = 0;
21437
+ let bestCount = -1;
21438
+ for (const [terrain, count] of [...counts].sort(([a], [b]) => a - b)) {
21439
+ if (count > bestCount) {
21440
+ best = terrain;
21441
+ bestCount = count;
21442
+ }
21443
+ }
21444
+ return best;
21195
21445
  }
21196
21446
  function godotTileShape(tileType) {
21197
21447
  if (tileType === "isometric" || tileType === "oblique") return 1;
@@ -21200,13 +21450,21 @@ function godotTileShape(tileType) {
21200
21450
  }
21201
21451
  function representativeTile(generic, terrainIndex) {
21202
21452
  const rules = generic.rules;
21453
+ if (rules.ruleType === "corner") {
21454
+ return generic.tiles.find((tile) => tileCorners(rules, tile)?.every((corner) => corner === terrainIndex))?.id ?? -1;
21455
+ }
21203
21456
  const full = (1 << rules.arity) - 1;
21204
21457
  const wanted = terrainIndex === 0 ? full : 0;
21205
21458
  return generic.tiles.find((tile) => tile.bitmask === wanted)?.id ?? -1;
21206
21459
  }
21207
21460
  function terrainNamesFor(rules) {
21461
+ if (rules.terrains.length > 2) return rules.terrains;
21208
21462
  return [rules.terrains[0] ?? "feature", rules.terrains[1] ?? "background"];
21209
21463
  }
21464
+ function godotColor(hex2) {
21465
+ const channel = (at2) => Number((parseInt(hex2.slice(at2, at2 + 2), 16) / 255).toFixed(4));
21466
+ return `Color(${channel(1)}, ${channel(3)}, ${channel(5)}, 1)`;
21467
+ }
21210
21468
  function assertUniformTiles(generic) {
21211
21469
  const mismatched = generic.tiles.filter(
21212
21470
  (tile) => tile.width !== generic.tile.width || tile.height !== generic.tile.height
@@ -21217,11 +21475,11 @@ function assertUniformTiles(generic) {
21217
21475
  );
21218
21476
  }
21219
21477
  }
21220
- function tileIndex(key2) {
21221
- const match = key2.match(/(?:^|[_-])(\d+)$/);
21478
+ function tileIndex(key3) {
21479
+ const match = key3.match(/(?:^|[_-])(\d+)$/);
21222
21480
  return match ? Number(match[1]) : null;
21223
21481
  }
21224
- function isRecord2(value) {
21482
+ function isRecord3(value) {
21225
21483
  return typeof value === "object" && value !== null && !Array.isArray(value);
21226
21484
  }
21227
21485
 
@@ -21433,8 +21691,8 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
21433
21691
  }
21434
21692
  }
21435
21693
  }
21436
- for (const { spec, key: key2 } of items) {
21437
- const estimate = estimates.get(key2);
21694
+ for (const { spec, key: key3 } of items) {
21695
+ const estimate = estimates.get(key3);
21438
21696
  if (spec.batch?.role === "member") {
21439
21697
  continue;
21440
21698
  }
@@ -21448,7 +21706,7 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
21448
21706
  } catch (err) {
21449
21707
  const message6 = err instanceof Error ? err.message : String(err);
21450
21708
  failed++;
21451
- upsert(lock, key2, {
21709
+ upsert(lock, key3, {
21452
21710
  styleId: spec.styleId,
21453
21711
  assetId: spec.assetId,
21454
21712
  specHash: spec.specHash,
@@ -21458,13 +21716,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
21458
21716
  height: spec.height,
21459
21717
  status: "failed",
21460
21718
  error: message6,
21461
- outputs: lock.entries[key2]?.outputs ?? [],
21719
+ outputs: lock.entries[key3]?.outputs ?? [],
21462
21720
  cost: 0,
21463
21721
  costUnit: spec.costUnit,
21464
21722
  provider: provider.id
21465
21723
  });
21466
21724
  await saveLock(lockPath, lock);
21467
- log(` FAILED ${key2}: ${message6}`);
21725
+ log(` FAILED ${key3}: ${message6}`);
21468
21726
  }
21469
21727
  continue;
21470
21728
  }
@@ -21476,11 +21734,11 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
21476
21734
  const missing = (spec.batch.memberAssetIds ?? []).filter((id) => !byKey.has(lockKey(spec.styleId, id)));
21477
21735
  if (missing.length) {
21478
21736
  throw new Error(
21479
- `${key2}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
21737
+ `${key3}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
21480
21738
  );
21481
21739
  }
21482
21740
  }
21483
- const previousEntry = lock.entries[key2];
21741
+ const previousEntry = lock.entries[key3];
21484
21742
  const resumesCheckpoint = Boolean(
21485
21743
  previousEntry?.specHash === spec.specHash && previousEntry.provider === provider.id && previousEntry.generator === spec.generator && previousEntry.submissionComplete === false && previousEntry.jobId
21486
21744
  );
@@ -21510,9 +21768,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
21510
21768
  const leaderGroup = motionLeader ? recordedAnimationGroup(lock.entries[lockKey(motionLeader.spec.styleId, motionLeader.spec.assetId)]) : void 0;
21511
21769
  const motionGroup = leaderGroup?.animationGroupId && leaderGroup.animationName ? { animationGroupId: leaderGroup.animationGroupId, animationName: leaderGroup.animationName } : void 0;
21512
21770
  if (motionLeader && !motionGroup) {
21513
- log(` ${key2}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
21771
+ log(` ${key3}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
21514
21772
  }
21515
- upsert(lock, key2, {
21773
+ upsert(lock, key3, {
21516
21774
  styleId: spec.styleId,
21517
21775
  assetId: spec.assetId,
21518
21776
  specHash: spec.specHash,
@@ -21624,8 +21882,8 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
21624
21882
  ...previousMetadata ? { previousMetadata } : {},
21625
21883
  checkpoint: async (checkpoint) => {
21626
21884
  if (!checkpoint.jobId) throw new Error("Provider checkpoint returned an empty job id");
21627
- const entry = lock.entries[key2];
21628
- upsert(lock, key2, {
21885
+ const entry = lock.entries[key3];
21886
+ upsert(lock, key3, {
21629
21887
  jobId: checkpoint.jobId,
21630
21888
  submissionComplete: checkpoint.complete,
21631
21889
  reviewObjectId: checkpoint.complete && (spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature) ? checkpoint.jobId : null,
@@ -21642,41 +21900,41 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
21642
21900
  await saveLock(lockPath, lock);
21643
21901
  }
21644
21902
  });
21645
- upsert(lock, key2, {
21903
+ upsert(lock, key3, {
21646
21904
  jobId,
21647
21905
  submissionComplete: true,
21648
21906
  // A multi-candidate generator routes through review; record the parent
21649
21907
  // so `pick` knows where to look.
21650
21908
  reviewObjectId: spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature ? jobId : null,
21651
21909
  status: "processing",
21652
- providerMetadata: metadata ? { ...lock.entries[key2].providerMetadata, [provider.id]: metadata } : lock.entries[key2].providerMetadata
21910
+ providerMetadata: metadata ? { ...lock.entries[key3].providerMetadata, [provider.id]: metadata } : lock.entries[key3].providerMetadata
21653
21911
  });
21654
21912
  inFlight.set(jobId, spec);
21655
21913
  submitted++;
21656
21914
  spent += estimate.amount;
21657
- writeBatchMembers(spec, key2, null);
21915
+ writeBatchMembers(spec, key3, null);
21658
21916
  log(
21659
- ` ${key2} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
21917
+ ` ${key3} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
21660
21918
  );
21661
21919
  } catch (err) {
21662
21920
  const message6 = err instanceof Error ? err.message : String(err);
21663
- const entry = lock.entries[key2];
21921
+ const entry = lock.entries[key3];
21664
21922
  if (entry.jobId && entry.submissionComplete === true) {
21665
- upsert(lock, key2, { status: "processing", error: null });
21923
+ upsert(lock, key3, { status: "processing", error: null });
21666
21924
  inFlight.set(entry.jobId, spec);
21667
21925
  submitted++;
21668
21926
  spent += estimate.amount;
21669
- writeBatchMembers(spec, key2, null);
21670
- log(` ${key2} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
21927
+ writeBatchMembers(spec, key3, null);
21928
+ log(` ${key3} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
21671
21929
  } else {
21672
21930
  failed++;
21673
- upsert(lock, key2, {
21931
+ upsert(lock, key3, {
21674
21932
  status: "failed",
21675
21933
  error: message6,
21676
21934
  cost: entry.jobId ? estimate.amount : 0
21677
21935
  });
21678
- writeBatchMembers(spec, key2, message6);
21679
- log(` FAILED ${key2}: ${message6}`);
21936
+ writeBatchMembers(spec, key3, message6);
21937
+ log(` FAILED ${key3}: ${message6}`);
21680
21938
  }
21681
21939
  }
21682
21940
  await saveLock(lockPath, lock);
@@ -21707,14 +21965,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
21707
21965
  const selectedKeys = opts.specs ? new Set(specByKey.keys()) : null;
21708
21966
  const result = { review: 0, completed: 0, failed: 0, stillRunning: 0 };
21709
21967
  const incompleteSubmissions = Object.entries(lock.entries).filter(
21710
- ([key2, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
21968
+ ([key3, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key3)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
21711
21969
  );
21712
- for (const [key2] of incompleteSubmissions) {
21713
- log(` incomplete submission ${key2}; rerun \`pixelkiln submit\` to resume`);
21970
+ for (const [key3] of incompleteSubmissions) {
21971
+ log(` incomplete submission ${key3}; rerun \`pixelkiln submit\` to resume`);
21714
21972
  }
21715
21973
  result.stillRunning = incompleteSubmissions.length;
21716
21974
  const pending = () => Object.entries(lock.entries).filter(
21717
- ([key2, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
21975
+ ([key3, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key3)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
21718
21976
  );
21719
21977
  while (pending().length > 0) {
21720
21978
  if (Date.now() - started > timeout) {
@@ -21722,16 +21980,16 @@ async function poll(provider, lock, lockPath, opts = {}) {
21722
21980
  log(` timed out with ${result.stillRunning} job(s) still running; re-run \`poll\` to resume`);
21723
21981
  break;
21724
21982
  }
21725
- for (const [key2, entry] of pending()) {
21983
+ for (const [key3, entry] of pending()) {
21726
21984
  try {
21727
- const currentSpec = specByKey.get(key2);
21985
+ const currentSpec = specByKey.get(key3);
21728
21986
  const state = await provider.poll(entry.jobId, entry.generator, {
21729
21987
  tileFeature: entry.tileFeature ?? currentSpec?.tileFeature,
21730
21988
  spec: currentSpec,
21731
21989
  metadata: entry.providerMetadata?.[provider.id]
21732
21990
  });
21733
21991
  if (state.status === "review" || state.status === "review-set") {
21734
- upsert(lock, key2, {
21992
+ upsert(lock, key3, {
21735
21993
  status: "review",
21736
21994
  reviewObjectId: entry.jobId,
21737
21995
  providerMetadata: state.metadata ? {
@@ -21745,11 +22003,11 @@ async function poll(provider, lock, lockPath, opts = {}) {
21745
22003
  });
21746
22004
  result.review++;
21747
22005
  log(
21748
- state.status === "review-set" ? ` review ${key2} (${state.frameUrls.length} ordered frames)` : ` review ${key2} (${state.candidateUrls.length} candidates)`
22006
+ state.status === "review-set" ? ` review ${key3} (${state.frameUrls.length} ordered frames)` : ` review ${key3} (${state.candidateUrls.length} candidates)`
21749
22007
  );
21750
22008
  } else if (state.status === "ready") {
21751
22009
  const sourceUrls = state.sources?.length ? state.sources : state.sourceUrl ? [{ url: state.sourceUrl }] : [];
21752
- upsert(lock, key2, {
22010
+ upsert(lock, key3, {
21753
22011
  status: "selected",
21754
22012
  objectId: state.objectId,
21755
22013
  sourceUrl: sourceUrls[0]?.url ?? null,
@@ -21765,14 +22023,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
21765
22023
  billed: state.billed ?? entry.billed
21766
22024
  });
21767
22025
  result.completed++;
21768
- log(` ready ${key2}`);
22026
+ log(` ready ${key3}`);
21769
22027
  } else if (state.status === "failed") {
21770
- upsert(lock, key2, { status: "failed", error: state.error });
22028
+ upsert(lock, key3, { status: "failed", error: state.error });
21771
22029
  result.failed++;
21772
- log(` FAILED ${key2}: ${state.error}`);
22030
+ log(` FAILED ${key3}: ${state.error}`);
21773
22031
  }
21774
22032
  } catch (err) {
21775
- log(` error polling ${key2}: ${err instanceof Error ? err.message : String(err)}`);
22033
+ log(` error polling ${key3}: ${err instanceof Error ? err.message : String(err)}`);
21776
22034
  }
21777
22035
  }
21778
22036
  await saveLock(lockPath, lock);
@@ -21897,14 +22155,14 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21897
22155
  const outputOwners = /* @__PURE__ */ new Map();
21898
22156
  const duplicateOutputs = [];
21899
22157
  const specByKey = new Map(specs.map((spec) => [`${spec.styleId}/${spec.assetId}`, spec]));
21900
- for (const [key2, entry] of Object.entries(lock.entries)) {
22158
+ for (const [key3, entry] of Object.entries(lock.entries)) {
21901
22159
  for (let index = 0; index < entry.outputs.length; index++) {
21902
22160
  const output = entry.outputs[index];
21903
- const spec = specByKey.get(key2);
22161
+ const spec = specByKey.get(key3);
21904
22162
  const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path35.default.dirname(lockPath));
21905
22163
  const owner = outputOwners.get(absolute);
21906
- if (owner && owner !== key2) duplicateOutputs.push(`${output.path} (${owner}, ${key2})`);
21907
- outputOwners.set(absolute, key2);
22164
+ if (owner && owner !== key3) duplicateOutputs.push(`${output.path} (${owner}, ${key3})`);
22165
+ outputOwners.set(absolute, key3);
21908
22166
  }
21909
22167
  }
21910
22168
  if (duplicateOutputs.length) {
@@ -21921,12 +22179,12 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21921
22179
  const invalidState = [];
21922
22180
  const staleMapUrls = [];
21923
22181
  const now = Date.now();
21924
- for (const [key2, entry] of Object.entries(lock.entries)) {
22182
+ for (const [key3, entry] of Object.entries(lock.entries)) {
21925
22183
  if ((entry.status === "pending" || entry.status === "processing") && !entry.jobId) {
21926
- invalidState.push(`${key2} (${entry.status} without job id)`);
22184
+ invalidState.push(`${key3} (${entry.status} without job id)`);
21927
22185
  }
21928
22186
  if (entry.status === "review" && !entry.reviewObjectId) {
21929
- invalidState.push(`${key2} (review without review object id)`);
22187
+ invalidState.push(`${key3} (review without review object id)`);
21930
22188
  }
21931
22189
  if (entry.status !== "selected" && entry.status !== "download-failed") continue;
21932
22190
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
@@ -21941,9 +22199,9 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21941
22199
  break;
21942
22200
  }
21943
22201
  }
21944
- if (!hasSource && !hasCache) stranded.push(key2);
22202
+ if (!hasSource && !hasCache) stranded.push(key3);
21945
22203
  if (entry.generator === "map" && entry.submittedAt && now - Date.parse(entry.submittedAt) > 8 * 60 * 60 * 1e3) {
21946
- staleMapUrls.push(key2);
22204
+ staleMapUrls.push(key3);
21947
22205
  }
21948
22206
  }
21949
22207
  add(
@@ -22101,14 +22359,14 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
22101
22359
  if (!hits?.length) continue;
22102
22360
  matchedRemote.add(obj.id);
22103
22361
  for (const spec of hits) {
22104
- const key2 = lockKey(spec.styleId, spec.assetId);
22105
- const existing = lock.entries[key2];
22362
+ const key3 = lockKey(spec.styleId, spec.assetId);
22363
+ const existing = lock.entries[key3];
22106
22364
  if (existing?.objectId && existing.objectId !== obj.id) {
22107
- ambiguous.push(`${key2}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
22365
+ ambiguous.push(`${key3}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
22108
22366
  continue;
22109
22367
  }
22110
22368
  const durableSource = shouldPersistSourceUrl(url) ? url : null;
22111
- upsert(lock, key2, {
22369
+ upsert(lock, key3, {
22112
22370
  styleId: spec.styleId,
22113
22371
  assetId: spec.assetId,
22114
22372
  // Deliberately the CURRENT spec hash: adoption declares "the file on
@@ -22135,7 +22393,7 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
22135
22393
  provider: provider.id
22136
22394
  });
22137
22395
  matched++;
22138
- log(` adopted ${key2} \u2190 ${obj.id}`);
22396
+ log(` adopted ${key3} \u2190 ${obj.id}`);
22139
22397
  }
22140
22398
  }
22141
22399
  }
@@ -22159,15 +22417,15 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
22159
22417
  });
22160
22418
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
22161
22419
  let count = 0;
22162
- for (const [key2, entry] of Object.entries(lock.entries)) {
22163
- const spec = specByKey.get(key2);
22420
+ for (const [key3, entry] of Object.entries(lock.entries)) {
22421
+ const spec = specByKey.get(key3);
22164
22422
  if (!spec || !entry.objectId) continue;
22165
22423
  if (!provider.setTags) return count;
22166
22424
  try {
22167
22425
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
22168
22426
  count++;
22169
22427
  } catch (err) {
22170
- log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
22428
+ log(` tag failed ${key3}: ${err instanceof Error ? err.message : String(err)}`);
22171
22429
  }
22172
22430
  }
22173
22431
  return count;
@@ -22244,18 +22502,18 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22244
22502
  const imported = [];
22245
22503
  const skipped = [];
22246
22504
  for (const spec of specs) {
22247
- const key2 = lockKey(spec.styleId, spec.assetId);
22505
+ const key3 = lockKey(spec.styleId, spec.assetId);
22248
22506
  const reason = unimportable(spec);
22249
22507
  if (reason) {
22250
- skipped.push({ key: key2, reason });
22508
+ skipped.push({ key: key3, reason });
22251
22509
  continue;
22252
22510
  }
22253
22511
  if (!(0, import_node_fs34.existsSync)(spec.outFile)) {
22254
- skipped.push({ key: key2, reason: `no file at ${spec.outFile}` });
22512
+ skipped.push({ key: key3, reason: `no file at ${spec.outFile}` });
22255
22513
  continue;
22256
22514
  }
22257
- if (lock.entries[key2] && !opts.force) {
22258
- skipped.push({ key: key2, reason: "already in the lockfile (use --force to replace it)" });
22515
+ if (lock.entries[key3] && !opts.force) {
22516
+ skipped.push({ key: key3, reason: "already in the lockfile (use --force to replace it)" });
22259
22517
  continue;
22260
22518
  }
22261
22519
  let patch;
@@ -22264,20 +22522,20 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22264
22522
  bytes = await (0, import_promises25.readFile)(spec.outFile);
22265
22523
  patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
22266
22524
  } catch (error) {
22267
- skipped.push({ key: key2, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
22525
+ skipped.push({ key: key3, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
22268
22526
  continue;
22269
22527
  }
22270
22528
  if (opts.dryRun) {
22271
- imported.push({ key: key2, entry: patch });
22529
+ imported.push({ key: key3, entry: patch });
22272
22530
  continue;
22273
22531
  }
22274
- const existing = lock.entries[key2];
22532
+ const existing = lock.entries[key3];
22275
22533
  const history = existing?.outputs[0]?.sha256 === sha256(bytes) ? existing.history : historyAfterReplacing(existing, opts.historyLimit ?? DEFAULT_HISTORY_LIMIT, patch.downloadedAt ?? (/* @__PURE__ */ new Date()).toISOString());
22276
22534
  if (cacheDir) {
22277
22535
  await cacheMedia(cacheDir, bytes, MediaType.PNG);
22278
22536
  if (rawBytes) await cacheMedia(cacheDir, rawBytes, MediaType.PNG);
22279
22537
  }
22280
- imported.push({ key: key2, entry: upsert(lock, key2, {
22538
+ imported.push({ key: key3, entry: upsert(lock, key3, {
22281
22539
  ...patch,
22282
22540
  // An import replaces the whole record: clear what the entry held that
22283
22541
  // an import never has, or a regenerated entry would keep stale links.
@@ -22291,7 +22549,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22291
22549
  async function reportSpecHashes(specs, lock) {
22292
22550
  const reports = [];
22293
22551
  for (const spec of specs) {
22294
- const key2 = lockKey(spec.styleId, spec.assetId);
22552
+ const key3 = lockKey(spec.styleId, spec.assetId);
22295
22553
  let bytes = null;
22296
22554
  if ((0, import_node_fs34.existsSync)(spec.outFile)) bytes = await (0, import_promises25.readFile)(spec.outFile);
22297
22555
  let wouldImport = null;
@@ -22302,11 +22560,11 @@ async function reportSpecHashes(specs, lock) {
22302
22560
  wouldImport = null;
22303
22561
  }
22304
22562
  }
22305
- const entry = lock.entries[key2];
22563
+ const entry = lock.entries[key3];
22306
22564
  const fileSha256 = bytes ? sha256(bytes) : null;
22307
22565
  const outputSha256 = entry?.outputs[0]?.sha256 ?? null;
22308
22566
  reports.push({
22309
- key: key2,
22567
+ key: key3,
22310
22568
  specHash: spec.specHash,
22311
22569
  file: spec.outFile,
22312
22570
  fileSha256,
@@ -22950,11 +23208,11 @@ async function prepareReview(provider, lock, opts = {}) {
22950
23208
  const prefix = opts.routePrefix ?? "";
22951
23209
  const providerUrls = /* @__PURE__ */ new Map();
22952
23210
  const groups = [];
22953
- for (const [key2, entry] of Object.entries(lock.entries)) {
22954
- if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key2)) continue;
23211
+ for (const [key3, entry] of Object.entries(lock.entries)) {
23212
+ if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key3)) continue;
22955
23213
  if (entry.status !== "review" || !entry.reviewObjectId) continue;
22956
23214
  try {
22957
- const spec = specByKey.get(key2);
23215
+ const spec = specByKey.get(key3);
22958
23216
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
22959
23217
  if (state.status !== "review" && state.status !== "review-set" || (state.status === "review" ? !state.candidateUrls.length : !state.frameUrls.length)) continue;
22960
23218
  const urls = state.status === "review" ? state.candidateUrls : state.frameUrls;
@@ -22986,9 +23244,9 @@ async function prepareReview(provider, lock, opts = {}) {
22986
23244
  reviewAssets.set(currentRoute, { path: current.path, contentType: current.contentType });
22987
23245
  }
22988
23246
  for (const [route, asset] of frameAssets) reviewAssets.set(route, asset);
22989
- providerUrls.set(key2, urls);
23247
+ providerUrls.set(key3, urls);
22990
23248
  groups.push({
22991
- key: key2,
23249
+ key: key3,
22992
23250
  assetId: entry.assetId,
22993
23251
  styleId: entry.styleId,
22994
23252
  prompt: entry.prompt,
@@ -23018,7 +23276,7 @@ async function prepareReview(provider, lock, opts = {}) {
23018
23276
  ...entry.batch?.index != null ? { recommendedIndex: entry.batch.index } : {}
23019
23277
  });
23020
23278
  } catch (err) {
23021
- log(` could not load candidates for ${key2}: ${err instanceof Error ? err.message : String(err)}`);
23279
+ log(` could not load candidates for ${key3}: ${err instanceof Error ? err.message : String(err)}`);
23022
23280
  }
23023
23281
  }
23024
23282
  if (groups.length === 0) return null;
@@ -23030,18 +23288,18 @@ async function prepareReview(provider, lock, opts = {}) {
23030
23288
  apply: async (body, lockPath) => {
23031
23289
  const { selections } = body;
23032
23290
  let selected = 0;
23033
- for (const { key: key2, index } of selections) {
23034
- const group = byKey.get(key2);
23035
- const entry = lock.entries[key2];
23291
+ for (const { key: key3, index } of selections) {
23292
+ const group = byKey.get(key3);
23293
+ const entry = lock.entries[key3];
23036
23294
  if (!group || !entry?.reviewObjectId) continue;
23037
23295
  if (!Number.isInteger(index) || index < 0 || index >= group.frameUrls.length) continue;
23038
23296
  if (group.mode === "frame-set") {
23039
- const spec = specByKey.get(key2);
23297
+ const spec = specByKey.get(key3);
23040
23298
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
23041
23299
  if (state.status !== "review-set") {
23042
- throw new Error(`Frame set ${key2} is no longer ready for review`);
23300
+ throw new Error(`Frame set ${key3} is no longer ready for review`);
23043
23301
  }
23044
- upsert(lock, key2, {
23302
+ upsert(lock, key3, {
23045
23303
  status: "selected",
23046
23304
  objectId: state.objectId,
23047
23305
  candidateIndex: null,
@@ -23057,7 +23315,7 @@ async function prepareReview(provider, lock, opts = {}) {
23057
23315
  } : entry.providerMetadata
23058
23316
  });
23059
23317
  selected++;
23060
- log(` accepted ${key2} \u2192 ${state.sources.length} ordered frames`);
23318
+ log(` accepted ${key3} \u2192 ${state.sources.length} ordered frames`);
23061
23319
  continue;
23062
23320
  }
23063
23321
  const { objectId, sourceUrl, metadata } = await requireSelectCandidate(provider)(
@@ -23066,11 +23324,11 @@ async function prepareReview(provider, lock, opts = {}) {
23066
23324
  `asset:${entry.assetId}`,
23067
23325
  entry.generator
23068
23326
  );
23069
- upsert(lock, key2, {
23327
+ upsert(lock, key3, {
23070
23328
  status: "selected",
23071
23329
  objectId,
23072
23330
  candidateIndex: index,
23073
- sourceUrl: sourceUrl ?? providerUrls.get(key2)?.[index] ?? null,
23331
+ sourceUrl: sourceUrl ?? providerUrls.get(key3)?.[index] ?? null,
23074
23332
  sourceUrls: [],
23075
23333
  provider: provider.id,
23076
23334
  providerMetadata: metadata ? {
@@ -23082,7 +23340,7 @@ async function prepareReview(provider, lock, opts = {}) {
23082
23340
  } : entry.providerMetadata
23083
23341
  });
23084
23342
  selected++;
23085
- log(` picked ${key2} \u2192 candidate ${index + 1}`);
23343
+ log(` picked ${key3} \u2192 candidate ${index + 1}`);
23086
23344
  }
23087
23345
  await saveLock(lockPath, lock);
23088
23346
  return { selected, skipped: groups.length - selected };
@@ -23733,9 +23991,9 @@ function styleProvider(raw, styleId, seen = /* @__PURE__ */ new Set()) {
23733
23991
  seen.add(styleId);
23734
23992
  return style.extends ? styleProvider(raw, style.extends, seen) : raw.provider ?? "pixellab";
23735
23993
  }
23736
- function setOrDelete(target, key2, value) {
23737
- if (value === null || value === void 0) delete target[key2];
23738
- else target[key2] = value;
23994
+ function setOrDelete(target, key3, value) {
23995
+ if (value === null || value === void 0) delete target[key3];
23996
+ else target[key3] = value;
23739
23997
  }
23740
23998
  function assetStyles(raw, asset) {
23741
23999
  const own = Array.isArray(asset.styles) ? asset.styles : [];
@@ -23977,21 +24235,21 @@ function handEditMembers(loaded, spec, lock, editPath) {
23977
24235
  return [{ role: null, path: editPath, base: bases?.[0]?.path ?? null }];
23978
24236
  }
23979
24237
  function refuseUneditable(spec) {
23980
- const key2 = `${spec.styleId}/${spec.assetId}`;
24238
+ const key3 = `${spec.styleId}/${spec.assetId}`;
23981
24239
  if (spec.derive) {
23982
24240
  const from = spec.derive.source.kind === "asset" ? spec.derive.source.assetId : spec.derive.source.file;
23983
24241
  throw new ManifestEditError(
23984
- `${key2} is derived from ${from} (${spec.derive.transform}), so it has no hand edit of its own; edit its source, or change the derive transform in the manifest`
24242
+ `${key3} is derived from ${from} (${spec.derive.transform}), so it has no hand edit of its own; edit its source, or change the derive transform in the manifest`
23985
24243
  );
23986
24244
  }
23987
24245
  if (spec.external) {
23988
24246
  throw new ManifestEditError(
23989
- `${key2} is built outside pixelkiln (${spec.external.builder}); change it there, then run pixelkiln adopt --local --force to record the new file`
24247
+ `${key3} is built outside pixelkiln (${spec.external.builder}); change it there, then run pixelkiln adopt --local --force to record the new file`
23990
24248
  );
23991
24249
  }
23992
24250
  if (spec.mirror) {
23993
24251
  throw new ManifestEditError(
23994
- `${key2} is a flip of ${spec.mirror.sourceAssetId}, so it has no hand edit of its own; edit ${spec.mirror.sourceAssetId} and flip it again`
24252
+ `${key3} is a flip of ${spec.mirror.sourceAssetId}, so it has no hand edit of its own; edit ${spec.mirror.sourceAssetId} and flip it again`
23995
24253
  );
23996
24254
  }
23997
24255
  }
@@ -24771,8 +25029,8 @@ async function adoptModelExport(model, opts = {}) {
24771
25029
  for (const [index, material] of (exported.document.json.materials ?? []).entries()) {
24772
25030
  for (const slot of slots) {
24773
25031
  const image = slotImage(exported.document, index, slot);
24774
- const key2 = `${material.name}\0${slot}`;
24775
- if (material.name && image !== void 0 && !exportedByName.has(key2)) exportedByName.set(key2, image);
25032
+ const key3 = `${material.name}\0${slot}`;
25033
+ if (material.name && image !== void 0 && !exportedByName.has(key3)) exportedByName.set(key3, image);
24776
25034
  }
24777
25035
  }
24778
25036
  let document2 = original.document;
@@ -24991,16 +25249,16 @@ function poseNodes(document2, pose) {
24991
25249
  const values = readAccessor(document2, sampler.output);
24992
25250
  const width = path53 === "rotation" ? 4 : 3;
24993
25251
  const cubic = sampler.interpolation === "CUBICSPLINE";
24994
- const valueAt = (key3) => Array.from(values.data.subarray((cubic ? key3 * 3 + 1 : key3) * width, (cubic ? key3 * 3 + 1 : key3) * width + width));
25252
+ const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
24995
25253
  const last = times.length - 1;
24996
25254
  const time = Math.min(Math.max(pose.time, times[0] ?? 0), times[last] ?? 0);
24997
- let key2 = 0;
24998
- while (key2 < last && times[key2 + 1] <= time) key2++;
24999
- let value = valueAt(key2);
25000
- if (key2 < last && sampler.interpolation !== "STEP" && !cubic) {
25001
- const span = times[key2 + 1] - times[key2];
25002
- const f = span > 0 ? (time - times[key2]) / span : 0;
25003
- const next = valueAt(key2 + 1);
25255
+ let key3 = 0;
25256
+ while (key3 < last && times[key3 + 1] <= time) key3++;
25257
+ let value = valueAt(key3);
25258
+ if (key3 < last && sampler.interpolation !== "STEP" && !cubic) {
25259
+ const span = times[key3 + 1] - times[key3];
25260
+ const f = span > 0 ? (time - times[key3]) / span : 0;
25261
+ const next = valueAt(key3 + 1);
25004
25262
  const sign = path53 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
25005
25263
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
25006
25264
  }
@@ -26308,14 +26566,14 @@ async function createSkeletonAnimation(manifestPath, request) {
26308
26566
  }
26309
26567
  }
26310
26568
  async function updateSkeletonKeypoints(ctx, request) {
26311
- const key2 = lockKey(request.styleId, request.assetId);
26312
- const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key2);
26313
- if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
26569
+ const key3 = lockKey(request.styleId, request.assetId);
26570
+ const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key3);
26571
+ if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
26314
26572
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
26315
- if (!file) throw new ManifestEditError(`${key2} is not an animate-skeleton revision`);
26573
+ if (!file) throw new ManifestEditError(`${key3} is not an animate-skeleton revision`);
26316
26574
  const relative = import_node_path47.default.relative(ctx.loaded.root, file);
26317
26575
  if (relative.startsWith("..") || import_node_path47.default.isAbsolute(relative)) {
26318
- throw new ManifestEditError(`${key2}'s keypoints file is outside the project; edit it by hand`);
26576
+ throw new ManifestEditError(`${key3}'s keypoints file is outside the project; edit it by hand`);
26319
26577
  }
26320
26578
  const current = (0, import_node_fs44.existsSync)(file) ? sha256(await (0, import_promises37.readFile)(file)) : null;
26321
26579
  if (current !== request.expectedSha256) {
@@ -26809,8 +27067,8 @@ async function buildGallerySnapshot(opts) {
26809
27067
  } catch {
26810
27068
  }
26811
27069
  for (const planItem of plan.items) {
26812
- const { spec, key: key2 } = planItem;
26813
- const entry = lock.entries[key2];
27070
+ const { spec, key: key3 } = planItem;
27071
+ const entry = lock.entries[key3];
26814
27072
  const asset = loaded.manifest.assets[spec.assetId] ?? null;
26815
27073
  let outputs;
26816
27074
  let edit = null;
@@ -26882,9 +27140,9 @@ async function buildGallerySnapshot(opts) {
26882
27140
  }
26883
27141
  const quality = planItem.quality ? await describeQuality(media, root, planItem.quality) : null;
26884
27142
  items.push({
26885
- id: key2,
27143
+ id: key3,
26886
27144
  project: null,
26887
- key: key2,
27145
+ key: key3,
26888
27146
  styleId: spec.styleId,
26889
27147
  assetId: spec.assetId,
26890
27148
  declared: true,
@@ -26942,8 +27200,8 @@ async function buildGallerySnapshot(opts) {
26942
27200
  });
26943
27201
  }
26944
27202
  const shown = new Set(items.map((item) => item.key));
26945
- for (const [key2, entry] of Object.entries(lock.entries)) {
26946
- if (shown.has(key2)) continue;
27203
+ for (const [key3, entry] of Object.entries(lock.entries)) {
27204
+ if (shown.has(key3)) continue;
26947
27205
  if (isDeclared(loaded, entry.styleId, entry.assetId)) continue;
26948
27206
  if (!matchesFilter(filter, entry.styleId, entry.assetId)) continue;
26949
27207
  const outputs = await Promise.all(
@@ -26952,9 +27210,9 @@ async function buildGallerySnapshot(opts) {
26952
27210
  )
26953
27211
  );
26954
27212
  items.push({
26955
- id: key2,
27213
+ id: key3,
26956
27214
  project: null,
26957
- key: key2,
27215
+ key: key3,
26958
27216
  styleId: entry.styleId,
26959
27217
  assetId: entry.assetId,
26960
27218
  declared: false,
@@ -27055,7 +27313,7 @@ async function buildGallerySnapshot(opts) {
27055
27313
  } : null,
27056
27314
  tags: style?.tags ?? [],
27057
27315
  extends: typeof rawStyle?.extends === "string" ? rawStyle.extends : null,
27058
- ownFields: rawStyle ? Object.keys(rawStyle).filter((key2) => key2 !== "extends") : [],
27316
+ ownFields: rawStyle ? Object.keys(rawStyle).filter((key3) => key3 !== "extends") : [],
27059
27317
  items: styleItems.length,
27060
27318
  spendByUnit: spend,
27061
27319
  regenerate: {
@@ -27579,7 +27837,7 @@ function createGalleryEditorHandlers(opts = {}) {
27579
27837
  }
27580
27838
  return checking;
27581
27839
  };
27582
- const describe = (status) => ({
27840
+ const describe2 = (status) => ({
27583
27841
  ...status,
27584
27842
  pixelorama: pin.pixelorama,
27585
27843
  protocol: pin.protocol,
@@ -27589,7 +27847,7 @@ function createGalleryEditorHandlers(opts = {}) {
27589
27847
  });
27590
27848
  return {
27591
27849
  release: pin.release,
27592
- status: async () => describe(verified ?? await check()),
27850
+ status: async () => describe2(verified ?? await check()),
27593
27851
  install: async () => {
27594
27852
  if (!running) {
27595
27853
  error = null;
@@ -27616,7 +27874,7 @@ function createGalleryEditorHandlers(opts = {}) {
27616
27874
  running = null;
27617
27875
  });
27618
27876
  }
27619
- return describe(verified ?? await check());
27877
+ return describe2(verified ?? await check());
27620
27878
  },
27621
27879
  file: async (release, name) => {
27622
27880
  if (!pin.release || release !== pin.release) return null;
@@ -28015,7 +28273,7 @@ function createGenerateHandlers(opts) {
28015
28273
  const busy = /* @__PURE__ */ new Map();
28016
28274
  for (const job of jobs.values()) {
28017
28275
  if (job.phase === "done" || job.phase === "failed") continue;
28018
- for (const key2 of job.keys) busy.set(`${job.project ?? ""}:${key2}`, job.id);
28276
+ for (const key3 of job.keys) busy.set(`${job.project ?? ""}:${key3}`, job.id);
28019
28277
  }
28020
28278
  return busy;
28021
28279
  };
@@ -28058,7 +28316,7 @@ function createGenerateHandlers(opts) {
28058
28316
  });
28059
28317
  say(job, `${providerId}: ${res.completed} completed, ${res.review} awaiting review, ${res.failed} failed, ${res.stillRunning} still running`);
28060
28318
  }
28061
- job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key2) => ctx.lock.entries[key2]?.status === "review");
28319
+ job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key3) => ctx.lock.entries[key3]?.status === "review");
28062
28320
  job.phase = "fetching";
28063
28321
  for (const [providerId, providerSpecs] of groupByRecordedProvider(specs, ctx.lock)) {
28064
28322
  const provider = opts.providerFor(job.project ?? void 0, providerId);
@@ -28143,7 +28401,7 @@ function createGenerateHandlers(opts) {
28143
28401
  job.finishedAt = null;
28144
28402
  const next = await opts.loadProject(job.project ?? void 0);
28145
28403
  const byKey = new Map(next.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
28146
- const nextSpecs = job.keys.map((key2) => byKey.get(key2)).filter((spec) => Boolean(spec));
28404
+ const nextSpecs = job.keys.map((key3) => byKey.get(key3)).filter((spec) => Boolean(spec));
28147
28405
  const plan = await buildPlan(nextSpecs, next.lock);
28148
28406
  if (!plan.actionable.length) return finish();
28149
28407
  for (const group of plan.groups) {
@@ -28210,21 +28468,21 @@ function createGenerateHandlers(opts) {
28210
28468
  const ctx = await opts.loadProject(request.project);
28211
28469
  const byKey = new Map(ctx.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
28212
28470
  const specs = [];
28213
- for (const key2 of request.keys) {
28214
- const spec = byKey.get(key2);
28215
- if (!spec) throw new GenerateRequestError(`"${key2}" is not declared by the manifest`);
28471
+ for (const key3 of request.keys) {
28472
+ const spec = byKey.get(key3);
28473
+ if (!spec) throw new GenerateRequestError(`"${key3}" is not declared by the manifest`);
28216
28474
  specs.push(spec);
28217
28475
  }
28218
28476
  const busy = busyKeys();
28219
- for (const key2 of request.keys) {
28220
- const holder = busy.get(`${request.project ?? ""}:${key2}`);
28221
- if (holder) throw new GenerateRequestError(`"${key2}" is already being worked on by job ${holder}`, 409);
28477
+ for (const key3 of request.keys) {
28478
+ const holder = busy.get(`${request.project ?? ""}:${key3}`);
28479
+ if (holder) throw new GenerateRequestError(`"${key3}" is already being worked on by job ${holder}`, 409);
28222
28480
  }
28223
28481
  if (request.restore) {
28224
- for (const key2 of request.keys) {
28225
- const entry = ctx.lock.entries[key2];
28482
+ for (const key3 of request.keys) {
28483
+ const entry = ctx.lock.entries[key3];
28226
28484
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
28227
- throw new GenerateRequestError(`"${key2}" has no downloaded output recorded to restore`);
28485
+ throw new GenerateRequestError(`"${key3}" has no downloaded output recorded to restore`);
28228
28486
  }
28229
28487
  }
28230
28488
  }
@@ -28467,10 +28725,10 @@ function groupOrphansByStyle(orphans, manifest, siblings = []) {
28467
28725
  }
28468
28726
  const sibling = siblings.find((s) => matchStyleByPattern(o.prompt, s.manifest));
28469
28727
  if (sibling) {
28470
- const key2 = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
28471
- const list = elsewhere.get(key2) ?? [];
28728
+ const key3 = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
28729
+ const list = elsewhere.get(key3) ?? [];
28472
28730
  list.push(o);
28473
- elsewhere.set(key2, list);
28731
+ elsewhere.set(key3, list);
28474
28732
  continue;
28475
28733
  }
28476
28734
  if (ownStyleIds.length <= 1 && ownStyleIds[0]) matched.get(ownStyleIds[0]).push(o);
@@ -29169,6 +29427,7 @@ async function workspaceStatus(ws, dir) {
29169
29427
  expandObject,
29170
29428
  expectedOutputPath,
29171
29429
  exportAssetFile,
29430
+ exportMergedTilesets,
29172
29431
  exportOutPath,
29173
29432
  exportTileset,
29174
29433
  fallbackOutputRole,
@@ -29378,9 +29637,11 @@ async function workspaceStatus(ws, dir) {
29378
29637
  summarize,
29379
29638
  tagAdopted,
29380
29639
  targetPaletteBody,
29640
+ terrainColor,
29381
29641
  terrainCost,
29382
29642
  terrainSettings,
29383
29643
  terrainTileCount,
29644
+ tileCorners,
29384
29645
  tileFeatureOutputCount,
29385
29646
  tileVariationCount,
29386
29647
  tilesCost,