pixelkiln 0.148.1 → 0.149.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
@@ -929,6 +929,13 @@ var CharacterLayerSchema = import_zod.z.object({
929
929
  skin: import_zod.z.array(HexColorSchema).min(1).max(64).optional(),
930
930
  /** The stand-in colour skin is painted before the provider sees it. Default cyan. */
931
931
  key: HexColorSchema.optional(),
932
+ /**
933
+ * Key every opaque pixel inside the mask, whatever its colour, not only
934
+ * skin. For a base that wears underwear (or anything else it cannot be
935
+ * drawn without): what it wears is body to dress over, so the outfit
936
+ * covers it instead of being drawn around it. Default false.
937
+ */
938
+ cover: import_zod.z.boolean().optional(),
932
939
  /**
933
940
  * Remove animation ghosts from the loops before dressing them, judged
934
941
  * against the stills among `of` (bases and states). Default true; it has
@@ -969,7 +976,7 @@ var CharacterLayerSchema = import_zod.z.object({
969
976
  attach: CharacterAttachSchema.optional()
970
977
  }).strict().superRefine((layer, context) => {
971
978
  if (!layer.attach) return;
972
- for (const field of ["mask", "keyed", "skin", "key", "clean", "region"]) {
979
+ for (const field of ["mask", "keyed", "skin", "key", "cover", "clean", "region"]) {
973
980
  if (layer[field] !== void 0) {
974
981
  context.addIssue({
975
982
  code: import_zod.z.ZodIssueCode.custom,
@@ -1973,7 +1980,7 @@ var AssetDeriveSchema = import_zod.z.object({
1973
1980
  /** key-skin: how far a pixel may sit from a `skin` colour. despeckle: how near a reference colour must be to vouch for a pixel. */
1974
1981
  tolerance: import_zod.z.number().min(0).max(442).optional()
1975
1982
  }).strict().superRefine((derive, context) => {
1976
- const issue = (message6, path54) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path54] });
1983
+ const issue = (message6, path55) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path55] });
1977
1984
  if (Boolean(derive.from) === Boolean(derive.file)) {
1978
1985
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1979
1986
  }
@@ -3552,9 +3559,9 @@ var PixelLabClient = class {
3552
3559
  apiKey;
3553
3560
  http;
3554
3561
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
3555
- async request(path54, init) {
3562
+ async request(path55, init) {
3556
3563
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
3557
- const res = await this.http(`${BASE}${path54}`, {
3564
+ const res = await this.http(`${BASE}${path55}`, {
3558
3565
  ...init,
3559
3566
  headers: {
3560
3567
  Authorization: auth,
@@ -3565,13 +3572,13 @@ var PixelLabClient = class {
3565
3572
  const text = await res.text();
3566
3573
  if (!res.ok) {
3567
3574
  const hint = res.status === 500 && text.includes("Failed to start any animation jobs") ? '; a skeleton-v3 loop needs a character with a stored 3D skeleton (a v3 base), use mode: "template" on a standard one' : "";
3568
- throw new PixelLabError(`${init?.method ?? "GET"} ${path54} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3575
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path55} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3569
3576
  }
3570
3577
  if (!text) return {};
3571
3578
  try {
3572
3579
  return JSON.parse(text);
3573
3580
  } catch {
3574
- throw new Error(`${init?.method ?? "GET"} ${path54} returned invalid JSON`);
3581
+ throw new Error(`${init?.method ?? "GET"} ${path55} returned invalid JSON`);
3575
3582
  }
3576
3583
  }
3577
3584
  async balance() {
@@ -4123,10 +4130,10 @@ var PixelLabClient = class {
4123
4130
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
4124
4131
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
4125
4132
  const south = args.reference?.south;
4126
- let path54;
4133
+ let path55;
4127
4134
  let body;
4128
4135
  if (args.mode === "v3") {
4129
- path54 = "/create-character-v3";
4136
+ path55 = "/create-character-v3";
4130
4137
  body = {
4131
4138
  description: args.description,
4132
4139
  image_size: imageSize,
@@ -4140,7 +4147,7 @@ var PixelLabClient = class {
4140
4147
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
4141
4148
  };
4142
4149
  } else if (args.mode === "pro-flash") {
4143
- path54 = "/create-character-pro-flash";
4150
+ path55 = "/create-character-pro-flash";
4144
4151
  const traits = args.styleTraits;
4145
4152
  body = {
4146
4153
  description: args.description,
@@ -4164,7 +4171,7 @@ var PixelLabClient = class {
4164
4171
  } : {}
4165
4172
  };
4166
4173
  } else if (args.mode === "pro") {
4167
- path54 = "/create-character-pro";
4174
+ path55 = "/create-character-pro";
4168
4175
  body = {
4169
4176
  description: args.description,
4170
4177
  image_size: imageSize,
@@ -4178,7 +4185,7 @@ var PixelLabClient = class {
4178
4185
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
4179
4186
  };
4180
4187
  } else {
4181
- path54 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
4188
+ path55 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
4182
4189
  body = {
4183
4190
  description: args.description,
4184
4191
  image_size: imageSize,
@@ -4196,8 +4203,8 @@ var PixelLabClient = class {
4196
4203
  };
4197
4204
  }
4198
4205
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
4199
- const raw = await this.request(path54, { method: "POST", body: JSON.stringify(body) });
4200
- return validateResponse(CharacterSubmitSchema, raw, path54.slice(1));
4206
+ const raw = await this.request(path55, { method: "POST", body: JSON.stringify(body) });
4207
+ return validateResponse(CharacterSubmitSchema, raw, path55.slice(1));
4201
4208
  }
4202
4209
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
4203
4210
  async createCharacterState(args) {
@@ -5251,8 +5258,8 @@ var PixelLabClient = class {
5251
5258
  }
5252
5259
  /** Irreversible: the character, its states are separate records, and its animations. Checks `success` like `deleteObject`. */
5253
5260
  async deleteCharacter(characterId) {
5254
- const path54 = `/characters/${encodeURIComponent(characterId)}`;
5255
- return deleteSucceeded(await this.request(path54, { method: "DELETE" }), `DELETE ${path54}`);
5261
+ const path55 = `/characters/${encodeURIComponent(characterId)}`;
5262
+ return deleteSucceeded(await this.request(path55, { method: "DELETE" }), `DELETE ${path55}`);
5256
5263
  }
5257
5264
  setCharacterTags(characterId, tags) {
5258
5265
  return this.request(`/characters/${encodeURIComponent(characterId)}/tags`, {
@@ -5888,10 +5895,10 @@ function normalizeHex(value) {
5888
5895
  function sha256(data) {
5889
5896
  return (0, import_node_crypto.createHash)("sha256").update(data).digest("hex");
5890
5897
  }
5891
- async function sha256File(path54) {
5898
+ async function sha256File(path55) {
5892
5899
  return new Promise((resolve, reject) => {
5893
5900
  const hash = (0, import_node_crypto.createHash)("sha256");
5894
- const stream = (0, import_node_fs.createReadStream)(path54);
5901
+ const stream = (0, import_node_fs.createReadStream)(path55);
5895
5902
  stream.on("data", (chunk2) => hash.update(chunk2));
5896
5903
  stream.on("error", reject);
5897
5904
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -6034,6 +6041,8 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
6034
6041
  keyed: spec.character.layer.keyed?.sha256,
6035
6042
  skin: spec.character.layer.skin?.map(normalizeHex),
6036
6043
  key: spec.character.layer.key ? normalizeHex(spec.character.layer.key) : void 0,
6044
+ // Omitted unless set so a layer made before it existed keeps its identity.
6045
+ cover: spec.character.layer.cover,
6037
6046
  clean: spec.character.layer.clean,
6038
6047
  columns: spec.character.layer.columns,
6039
6048
  // Omitted at their defaults so a layer made before these existed keeps its identity.
@@ -7261,6 +7270,7 @@ function hsv(r, g, b) {
7261
7270
  }
7262
7271
  var DEFAULT_KEY = "#00ffff";
7263
7272
  var KEY_SATURATION = 0.85;
7273
+ var COVER_FLOOR = 96;
7264
7274
  function keySkin(png, options = {}) {
7265
7275
  const image = decodePng(png);
7266
7276
  const key3 = parseHex(options.key ?? DEFAULT_KEY);
@@ -7313,23 +7323,103 @@ function neckRow(image, cell = whole(image)) {
7313
7323
  }
7314
7324
  return best === null ? null : cell.y + best;
7315
7325
  }
7316
- function bodyMask(sheet, cells, region = "body") {
7326
+ function longestRun(image, cell, y) {
7327
+ let best = null;
7328
+ let start = -1;
7329
+ for (let x = 0; x <= cell.width; x++) {
7330
+ const on = x < cell.width && opaque(image, cell.x + x, cell.y + y);
7331
+ if (on && start < 0) start = x;
7332
+ if (!on && start >= 0) {
7333
+ if (!best || x - 1 - start > best[1] - best[0]) best = [start, x - 1];
7334
+ start = -1;
7335
+ }
7336
+ }
7337
+ return best;
7338
+ }
7339
+ var median = (values) => {
7340
+ const sorted = [...values].sort((a, b) => a - b);
7341
+ return sorted[Math.floor((sorted.length - 1) / 2)];
7342
+ };
7343
+ function layerMask(sheet, cells, region = "body") {
7317
7344
  const image = decodePng(sheet);
7318
7345
  const out = Buffer.alloc(image.width * image.height * 4);
7319
7346
  for (let i = 3; i < out.length; i += 4) out[i] = 255;
7320
- for (const cell of cells ?? [whole(image)]) {
7347
+ const all = cells ?? [whole(image)];
7348
+ const first = all.map((cell) => {
7349
+ let top = -1;
7350
+ let bottom = -1;
7351
+ for (let y = 0; y < cell.height && top < 0; y++) if (longestRun(image, cell, y)) top = y;
7352
+ for (let y = cell.height - 1; y >= 0 && bottom < 0; y--) if (longestRun(image, cell, y)) bottom = y;
7353
+ if (top < 0) return null;
7321
7354
  const neck = neckRow(image, cell);
7322
- if (neck === null) continue;
7323
- const from = region === "head" ? cell.y : neck + 1;
7324
- const to = region === "head" ? neck + 1 : cell.y + cell.height;
7355
+ return { top, bottom, detected: neck === null ? null : neck - cell.y };
7356
+ });
7357
+ const seen = first.filter((frame) => frame !== null);
7358
+ const offsets = seen.filter((frame) => frame.detected !== null).map((frame) => frame.detected - frame.top);
7359
+ if (!offsets.length) return { png: encodeRgbaPng(image.width, image.height, out), necks: all.map(() => null) };
7360
+ const drop = median(offsets);
7361
+ const heads = seen.map((frame) => {
7362
+ const cell = all[first.indexOf(frame)];
7363
+ const run = longestRun(image, cell, Math.min(frame.bottom, frame.top + Math.floor(drop / 2)));
7364
+ return run ? run[1] - run[0] + 1 : 1;
7365
+ });
7366
+ const wide = Math.max(1, Math.ceil(median(heads) / 2));
7367
+ const necks = all.map((cell, index) => {
7368
+ const frame = first[index];
7369
+ if (!frame) return null;
7370
+ let head = frame.top;
7371
+ for (let y = frame.top; y <= frame.bottom; y++) {
7372
+ const run = longestRun(image, cell, y);
7373
+ if (run && run[1] - run[0] + 1 >= wide) {
7374
+ head = y;
7375
+ break;
7376
+ }
7377
+ }
7378
+ const row = Math.min(head + drop, frame.bottom);
7379
+ const slack = Math.max(2, Math.round((frame.bottom - frame.top + 1) * 0.06));
7380
+ const corrected = frame.detected === null || Math.abs(frame.detected - row) > slack;
7381
+ const from = region === "head" ? 0 : row + 1;
7382
+ const to = region === "head" ? row + 1 : cell.height;
7325
7383
  for (let y = from; y < to; y++) {
7326
- for (let x = cell.x; x < cell.x + cell.width; x++) {
7327
- if (region === "body" && !opaque(image, x, y)) continue;
7328
- out.fill(255, at(image, x, y), at(image, x, y) + 3);
7384
+ for (let x = 0; x < cell.width; x++) {
7385
+ if (region === "body" && !opaque(image, cell.x + x, cell.y + y)) continue;
7386
+ out.fill(255, at(image, cell.x + x, cell.y + y), at(image, cell.x + x, cell.y + y) + 3);
7387
+ }
7388
+ }
7389
+ if (region === "body") {
7390
+ const seed = longestRun(image, cell, head);
7391
+ const inHead = new Uint8Array(cell.width * (row + 1));
7392
+ const queue = [];
7393
+ for (let x = seed[0]; x <= seed[1]; x++) {
7394
+ inHead[head * cell.width + x] = 1;
7395
+ queue.push([x, head]);
7396
+ }
7397
+ let left = seed[0];
7398
+ let right = seed[1];
7399
+ while (queue.length) {
7400
+ const [x, y] = queue.pop();
7401
+ left = Math.min(left, x);
7402
+ right = Math.max(right, x);
7403
+ for (const [dx, dy] of STEPS) {
7404
+ const nx = x + dx;
7405
+ const ny = y + dy;
7406
+ if (nx < 0 || nx >= cell.width || ny < 0 || ny > row) continue;
7407
+ if (inHead[ny * cell.width + nx] || !opaque(image, cell.x + nx, cell.y + ny)) continue;
7408
+ inHead[ny * cell.width + nx] = 1;
7409
+ queue.push([nx, ny]);
7410
+ }
7411
+ }
7412
+ for (let y = 0; y <= row; y++) {
7413
+ for (let x = 0; x < cell.width; x++) {
7414
+ if (x >= left - 1 && x <= right + 1) continue;
7415
+ if (!opaque(image, cell.x + x, cell.y + y)) continue;
7416
+ out.fill(255, at(image, cell.x + x, cell.y + y), at(image, cell.x + x, cell.y + y) + 3);
7417
+ }
7329
7418
  }
7330
7419
  }
7331
- }
7332
- return encodeRgbaPng(image.width, image.height, out);
7420
+ return { row, head, detected: frame.detected, corrected };
7421
+ });
7422
+ return { png: encodeRgbaPng(image.width, image.height, out), necks };
7333
7423
  }
7334
7424
  function extractLayer(result, keyed, mask, options = {}) {
7335
7425
  const out = decodePng(result);
@@ -7624,23 +7714,55 @@ function buildLayerSheet(sources, options) {
7624
7714
  }
7625
7715
  return png;
7626
7716
  };
7627
- const mask = options.mask ? sized("mask", options.mask) : bodyMask(sheetPng, frames.map((frame) => frame.cell), options.region);
7717
+ const computed = options.mask ? void 0 : layerMask(sheetPng, frames.map((frame) => frame.cell), options.region);
7718
+ const mask = options.mask ? sized("mask", options.mask) : computed.png;
7719
+ const keyed = options.keyed ? void 0 : keyInsideMask(sheetPng, mask, { key: options.key, skin: options.skin, cover: options.cover });
7628
7720
  return {
7629
7721
  sheet: sheetPng,
7630
- keyed: options.keyed ? sized("keyed sheet", options.keyed) : keyInsideMask(sheetPng, mask, { key: options.key, skin: options.skin }),
7722
+ keyed: options.keyed ? sized("keyed sheet", options.keyed) : keyed.png,
7631
7723
  mask,
7632
7724
  frames,
7633
- cleaned
7725
+ cleaned,
7726
+ ...computed ? { necks: computed.necks } : {},
7727
+ ...keyed ? { closed: keyed.closed } : {}
7634
7728
  };
7635
7729
  }
7636
7730
  function keyInsideMask(sheet, mask, options) {
7637
7731
  const original = decodePng(sheet);
7638
- const keyed = decodePng(keySkin(sheet, options));
7639
7732
  const allowed = decodePng(mask);
7733
+ const key3 = parseHex(options.key ?? DEFAULT_KEY);
7734
+ const keyed = options.cover ? { ...original, pixels: Buffer.from(original.pixels) } : decodePng(keySkin(sheet, options));
7735
+ const paint = (i, lift) => {
7736
+ const brightest = Math.max(original.pixels[i], original.pixels[i + 1], original.pixels[i + 2]);
7737
+ const value = lift ? COVER_FLOOR + Math.floor(brightest * (255 - COVER_FLOOR) / 255) : brightest;
7738
+ const tint = (channel) => Math.floor(value * (1 - KEY_SATURATION + KEY_SATURATION * channel / 255));
7739
+ keyed.pixels[i] = tint(key3.r);
7740
+ keyed.pixels[i + 1] = tint(key3.g);
7741
+ keyed.pixels[i + 2] = tint(key3.b);
7742
+ };
7640
7743
  for (let i = 0; i < keyed.pixels.length; i += 4) {
7641
7744
  if (allowed.pixels[i] !== 255) original.pixels.copy(keyed.pixels, i, i, i + 4);
7745
+ else if (options.cover && original.pixels[i + 3]) paint(i, true);
7746
+ }
7747
+ let closed = 0;
7748
+ if (!options.cover && !options.skin) {
7749
+ const changed = (i) => original.pixels[i + 3] > 0 && original.pixels.compare(keyed.pixels, i, i + 3, i, i + 3) !== 0;
7750
+ const holes = [];
7751
+ for (let y = 0; y < keyed.height; y++) {
7752
+ for (let x = 0; x < keyed.width; x++) {
7753
+ const i = (y * keyed.width + x) * 4;
7754
+ if (allowed.pixels[i] !== 255 || !original.pixels[i + 3] || changed(i)) continue;
7755
+ const near = (dir) => [1, 2, 3].some((k) => {
7756
+ const nx = x + dir * k;
7757
+ return nx >= 0 && nx < keyed.width && allowed.pixels[i + dir * k * 4] === 255 && changed(i + dir * k * 4);
7758
+ });
7759
+ if (near(-1) && near(1)) holes.push(i);
7760
+ }
7761
+ }
7762
+ for (const i of holes) paint(i, false);
7763
+ closed = holes.length;
7642
7764
  }
7643
- return encodeRgbaPng(keyed.width, keyed.height, keyed.pixels);
7765
+ return { png: encodeRgbaPng(keyed.width, keyed.height, keyed.pixels), closed };
7644
7766
  }
7645
7767
  var SPECK = 8;
7646
7768
  var BLEED = 20;
@@ -8765,6 +8887,37 @@ var GRASP_PROMPT = "Every cyan mannequin on this spritesheet carries the same it
8765
8887
  function layerWorkDir(spec) {
8766
8888
  return import_node_path7.default.join(spec.root, ".pixelkiln", "layers", spec.styleId, spec.assetId);
8767
8889
  }
8890
+ function layerSheetFor(spec, outputs) {
8891
+ const character = spec.character;
8892
+ const layer = character.layer;
8893
+ const label = `${spec.styleId}/${spec.assetId}`;
8894
+ if (!outputs.length) throw new Error(`${label}: its layer sources have no downloaded frames`);
8895
+ const sources = outputs.map((output) => ({
8896
+ assetId: output.assetId ?? character.parentAssetId,
8897
+ ...output.role ? { role: output.role } : {},
8898
+ png: (0, import_node_fs7.readFileSync)(output.path),
8899
+ still: output.still === true
8900
+ }));
8901
+ const supplied = (name, file) => {
8902
+ if (!file) return void 0;
8903
+ const bytes = (0, import_node_fs7.readFileSync)(file.path);
8904
+ if (sha256(bytes) !== file.sha256) throw new Error(`${label}: layer ${name} changed after the manifest was resolved: ${file.path}`);
8905
+ return bytes;
8906
+ };
8907
+ return buildLayerSheet(sources, {
8908
+ minSide: 32,
8909
+ maxSide: LAYER_SHEET_MAX_SIDE,
8910
+ columns: layer.columns,
8911
+ region: layer.region,
8912
+ padding: layer.padding,
8913
+ key: layer.key,
8914
+ skin: layer.skin,
8915
+ cover: layer.cover,
8916
+ reference: layer.clean ? sources.filter((source) => source.still).map((source) => source.png) : [],
8917
+ mask: supplied("mask", layer.mask),
8918
+ keyed: supplied("keyed sheet", layer.keyed)
8919
+ });
8920
+ }
8768
8921
  var PixelLabProvider = class _PixelLabProvider {
8769
8922
  /**
8770
8923
  * `mcp` reaches the tools PixelLab offers only over MCP (the VFX
@@ -9656,31 +9809,7 @@ var PixelLabProvider = class _PixelLabProvider {
9656
9809
  const layer = character.layer;
9657
9810
  const label = `${spec.styleId}/${spec.assetId}`;
9658
9811
  const outputs = context?.parentOutputs ?? [];
9659
- if (!outputs.length) throw new Error(`${label}: its layer sources have no downloaded frames`);
9660
- const sources = outputs.map((output) => ({
9661
- assetId: output.assetId ?? character.parentAssetId,
9662
- ...output.role ? { role: output.role } : {},
9663
- png: (0, import_node_fs7.readFileSync)(output.path),
9664
- still: output.still === true
9665
- }));
9666
- const supplied = (name2, file) => {
9667
- if (!file) return void 0;
9668
- const bytes = (0, import_node_fs7.readFileSync)(file.path);
9669
- if (sha256(bytes) !== file.sha256) throw new Error(`${label}: layer ${name2} changed after the manifest was resolved: ${file.path}`);
9670
- return bytes;
9671
- };
9672
- const built = buildLayerSheet(sources, {
9673
- minSide: 32,
9674
- maxSide: LAYER_SHEET_MAX_SIDE,
9675
- columns: layer.columns,
9676
- region: layer.region,
9677
- padding: layer.padding,
9678
- key: layer.key,
9679
- skin: layer.skin,
9680
- reference: layer.clean ? sources.filter((source) => source.still).map((source) => source.png) : [],
9681
- mask: supplied("mask", layer.mask),
9682
- keyed: supplied("keyed sheet", layer.keyed)
9683
- });
9812
+ const built = layerSheetFor(spec, outputs);
9684
9813
  const dir = layerWorkDir(spec);
9685
9814
  (0, import_node_fs7.mkdirSync)(dir, { recursive: true });
9686
9815
  let prepared = built;
@@ -9735,7 +9864,15 @@ var PixelLabProvider = class _PixelLabProvider {
9735
9864
  character: {
9736
9865
  kind: "layer",
9737
9866
  backgroundJobId: res2.background_job_id,
9738
- sheet: { width, height, frames: prepared.frames.length, cleanedPixels: prepared.cleaned }
9867
+ sheet: {
9868
+ width,
9869
+ height,
9870
+ frames: prepared.frames.length,
9871
+ cleanedPixels: prepared.cleaned,
9872
+ // Each frame's neck row in its cell, and the frames whose own narrowest row was overruled; submit prints both.
9873
+ ...prepared.necks ? { necks: prepared.necks.map((neck) => neck?.row ?? null) } : {},
9874
+ ...prepared.necks?.some((neck) => neck?.corrected) ? { neckCorrected: prepared.necks.flatMap((neck, index) => neck?.corrected ? [index] : []) } : {}
9875
+ }
9739
9876
  }
9740
9877
  }
9741
9878
  };
@@ -11798,9 +11935,9 @@ var RetroDiffusionClient = class {
11798
11935
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
11799
11936
  return Buffer.from(await response.arrayBuffer());
11800
11937
  }
11801
- async call(path54, init = {}) {
11938
+ async call(path55, init = {}) {
11802
11939
  if (!this.token) throw new Error("RD_API_KEY is not set");
11803
- const response = await this.request(`${this.baseUrl}${path54}`, {
11940
+ const response = await this.request(`${this.baseUrl}${path55}`, {
11804
11941
  ...init,
11805
11942
  headers: {
11806
11943
  "Content-Type": "application/json",
@@ -15306,6 +15443,7 @@ async function resolveSpecs(loaded, filter) {
15306
15443
  ...keyed ? { keyed } : {},
15307
15444
  ...asset.layer.skin ? { skin: asset.layer.skin } : {},
15308
15445
  ...asset.layer.key ? { key: asset.layer.key } : {},
15446
+ ...asset.layer.cover ? { cover: true } : {},
15309
15447
  clean: asset.layer.clean ?? true,
15310
15448
  ...asset.layer.columns ? { columns: asset.layer.columns } : {},
15311
15449
  region: asset.layer.region ?? "body",
@@ -20167,10 +20305,10 @@ function isSha256Hash(value) {
20167
20305
  function parseCache(value) {
20168
20306
  return HashCacheSchema.parse(value);
20169
20307
  }
20170
- async function loadCache(path54) {
20171
- if (!(0, import_node_fs26.existsSync)(path54)) return { version: 1, hashes: {} };
20308
+ async function loadCache(path55) {
20309
+ if (!(0, import_node_fs26.existsSync)(path55)) return { version: 1, hashes: {} };
20172
20310
  try {
20173
- const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises20.readFile)(path54, "utf8")));
20311
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises20.readFile)(path55, "utf8")));
20174
20312
  if (!parsed.success) return { version: 1, hashes: {} };
20175
20313
  return {
20176
20314
  version: 1,
@@ -20182,18 +20320,18 @@ async function loadCache(path54) {
20182
20320
  return { version: 1, hashes: {} };
20183
20321
  }
20184
20322
  }
20185
- async function saveCache(path54, cache) {
20323
+ async function saveCache(path55, cache) {
20186
20324
  const sorted = {};
20187
20325
  for (const key3 of Object.keys(cache.hashes).sort()) {
20188
20326
  const hash = cache.hashes[key3];
20189
20327
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
20190
20328
  sorted[key3] = hash;
20191
20329
  }
20192
- await (0, import_promises20.mkdir)(import_node_path29.default.dirname(import_node_path29.default.resolve(path54)), { recursive: true });
20193
- const tmp = `${path54}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
20330
+ await (0, import_promises20.mkdir)(import_node_path29.default.dirname(import_node_path29.default.resolve(path55)), { recursive: true });
20331
+ const tmp = `${path55}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
20194
20332
  try {
20195
20333
  await (0, import_promises20.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
20196
- await (0, import_promises20.rename)(tmp, path54);
20334
+ await (0, import_promises20.rename)(tmp, path55);
20197
20335
  } finally {
20198
20336
  await (0, import_promises20.rm)(tmp, { force: true });
20199
20337
  }
@@ -22361,6 +22499,21 @@ function renderSheetDocument(format, atlas, opts) {
22361
22499
  return { extension: ".json", document: JSON.stringify(atlas, null, 2) + "\n" };
22362
22500
  }
22363
22501
 
22502
+ // src/pipeline/layer-preview.ts
22503
+ var import_promises23 = require("fs/promises");
22504
+ var import_node_path34 = __toESM(require("path"), 1);
22505
+ function layerSourceOutputs(spec, lock) {
22506
+ return spec.character.layer.sources.flatMap((source) => {
22507
+ const sourceEntry = lock.entries[lockKey(source.spec.styleId, source.spec.assetId)];
22508
+ return sourceEntry.outputs.map((output, index) => ({
22509
+ path: currentEntryOutputPath(sourceEntry, source.spec, index),
22510
+ role: output.role,
22511
+ assetId: source.assetId,
22512
+ still: source.spec.character?.kind !== "animation"
22513
+ }));
22514
+ });
22515
+ }
22516
+
22364
22517
  // src/pipeline/submit.ts
22365
22518
  var IN_FLIGHT_POLL_MS = 5e3;
22366
22519
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -22643,15 +22796,7 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
22643
22796
  const parentOutputs = spec.character?.kind === "outfit" && parentEntry ? parentEntry.outputs.map((output, index) => ({
22644
22797
  path: currentEntryOutputPath(parentEntry, spec.character.parentSpec, index),
22645
22798
  role: output.role
22646
- })) : spec.character?.kind === "layer" ? spec.character.layer.sources.flatMap((source) => {
22647
- const sourceEntry = lock.entries[lockKey(source.spec.styleId, source.spec.assetId)];
22648
- return sourceEntry.outputs.map((output, index) => ({
22649
- path: currentEntryOutputPath(sourceEntry, source.spec, index),
22650
- role: output.role,
22651
- assetId: source.assetId,
22652
- still: source.spec.character?.kind !== "animation"
22653
- }));
22654
- }) : void 0;
22799
+ })) : spec.character?.kind === "layer" ? layerSourceOutputs(spec, lock) : void 0;
22655
22800
  const referenceSourceImageId = ownedReferenceImageId(spec, lock, provider.id);
22656
22801
  const { jobId, metadata } = await provider.submit(spec, refs, {
22657
22802
  ...previousJobId ? { previousJobId } : {},
@@ -22700,6 +22845,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
22700
22845
  log(
22701
22846
  ` ${key3} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
22702
22847
  );
22848
+ const sheet = metadata?.character?.sheet;
22849
+ if (sheet?.necks) {
22850
+ log(` neck rows by frame: ${sheet.necks.map((row) => row ?? "-").join(" ")}`);
22851
+ if (sheet.neckCorrected?.length) {
22852
+ log(` frame${sheet.neckCorrected.length === 1 ? "" : "s"} ${sheet.neckCorrected.join(", ")}: own narrowest row disagreed; neck taken from the head and the other frames`);
22853
+ }
22854
+ }
22703
22855
  } catch (err) {
22704
22856
  const message6 = err instanceof Error ? err.message : String(err);
22705
22857
  const entry = lock.entries[key3];
@@ -22739,8 +22891,8 @@ function ownedReferenceImageId(spec, lock, providerId) {
22739
22891
 
22740
22892
  // src/pick/candidates.ts
22741
22893
  var import_node_fs31 = require("fs");
22742
- var import_promises23 = require("fs/promises");
22743
- var import_node_path34 = __toESM(require("path"), 1);
22894
+ var import_promises24 = require("fs/promises");
22895
+ var import_node_path35 = __toESM(require("path"), 1);
22744
22896
  var import_zod8 = require("zod");
22745
22897
  var REVIEW_STATE_VERSION = 1;
22746
22898
  var CandidateSchema = import_zod8.z.object({
@@ -22784,30 +22936,30 @@ var ReviewStateSchema = import_zod8.z.object({
22784
22936
  assets: import_zod8.z.record(ReviewAssetSchema)
22785
22937
  });
22786
22938
  function candidateCacheDirFor(lockPath) {
22787
- return import_node_path34.default.resolve(import_node_path34.default.dirname(lockPath), ".pixelkiln", "cache");
22939
+ return import_node_path35.default.resolve(import_node_path35.default.dirname(lockPath), ".pixelkiln", "cache");
22788
22940
  }
22789
22941
  function reviewStatePathFor(lockPath) {
22790
- const base = import_node_path34.default.basename(lockPath);
22942
+ const base = import_node_path35.default.basename(lockPath);
22791
22943
  const name = base === "pixelkiln.lock.json" ? "review-state.json" : `${base.replace(/\.json$/, "")}.review-state.json`;
22792
- return import_node_path34.default.resolve(import_node_path34.default.dirname(lockPath), ".pixelkiln", name);
22944
+ return import_node_path35.default.resolve(import_node_path35.default.dirname(lockPath), ".pixelkiln", name);
22793
22945
  }
22794
22946
  async function loadReviewState(file) {
22795
22947
  if (!(0, import_node_fs31.existsSync)(file)) return { version: REVIEW_STATE_VERSION, assets: {} };
22796
22948
  try {
22797
- const parsed = ReviewStateSchema.safeParse(JSON.parse(await (0, import_promises23.readFile)(file, "utf8")));
22949
+ const parsed = ReviewStateSchema.safeParse(JSON.parse(await (0, import_promises24.readFile)(file, "utf8")));
22798
22950
  if (parsed.success) return parsed.data;
22799
22951
  } catch {
22800
22952
  }
22801
22953
  return { version: REVIEW_STATE_VERSION, assets: {} };
22802
22954
  }
22803
22955
  async function saveReviewState(file, state) {
22804
- await (0, import_promises23.mkdir)(import_node_path34.default.dirname(file), { recursive: true });
22956
+ await (0, import_promises24.mkdir)(import_node_path35.default.dirname(file), { recursive: true });
22805
22957
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
22806
22958
  try {
22807
- await (0, import_promises23.writeFile)(tmp, JSON.stringify(state, null, 2) + "\n");
22808
- await (0, import_promises23.rename)(tmp, file);
22959
+ await (0, import_promises24.writeFile)(tmp, JSON.stringify(state, null, 2) + "\n");
22960
+ await (0, import_promises24.rename)(tmp, file);
22809
22961
  } finally {
22810
- await (0, import_promises23.rm)(tmp, { force: true });
22962
+ await (0, import_promises24.rm)(tmp, { force: true });
22811
22963
  }
22812
22964
  }
22813
22965
  async function updateReviewAsset(file, key3, change) {
@@ -22821,7 +22973,7 @@ async function updateReviewAsset(file, key3, change) {
22821
22973
  }
22822
22974
  function cachedCandidatePath(cacheDir, candidate) {
22823
22975
  if (!candidate.sha256 || !candidate.mediaType) return null;
22824
- const file = import_node_path34.default.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
22976
+ const file = import_node_path35.default.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
22825
22977
  return (0, import_node_fs31.existsSync)(file) ? file : null;
22826
22978
  }
22827
22979
  function fullyCached(cacheDir, asset) {
@@ -23029,12 +23181,12 @@ async function poll(provider, lock, lockPath, opts = {}) {
23029
23181
 
23030
23182
  // src/pipeline/doctor.ts
23031
23183
  var import_node_fs33 = require("fs");
23032
- var import_promises24 = require("fs/promises");
23033
- var import_node_path36 = __toESM(require("path"), 1);
23184
+ var import_promises25 = require("fs/promises");
23185
+ var import_node_path37 = __toESM(require("path"), 1);
23034
23186
 
23035
23187
  // src/pipeline/install-check.ts
23036
23188
  var import_node_fs32 = require("fs");
23037
- var import_node_path35 = __toESM(require("path"), 1);
23189
+ var import_node_path36 = __toESM(require("path"), 1);
23038
23190
  function readJson(file) {
23039
23191
  try {
23040
23192
  return JSON.parse((0, import_node_fs32.readFileSync)(file, "utf8"));
@@ -23043,18 +23195,18 @@ function readJson(file) {
23043
23195
  }
23044
23196
  }
23045
23197
  function readInstallFacts(manifestDir, running) {
23046
- let dir = import_node_path35.default.resolve(manifestDir);
23198
+ let dir = import_node_path36.default.resolve(manifestDir);
23047
23199
  for (let depth = 0; depth < 4; depth++) {
23048
- const pkg = readJson(import_node_path35.default.join(dir, "package.json"));
23200
+ const pkg = readJson(import_node_path36.default.join(dir, "package.json"));
23049
23201
  if (pkg) {
23050
23202
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
23051
23203
  if (pinned) {
23052
- const installedPkg = readJson(import_node_path35.default.join(dir, "node_modules", "pixelkiln", "package.json"));
23204
+ const installedPkg = readJson(import_node_path36.default.join(dir, "node_modules", "pixelkiln", "package.json"));
23053
23205
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
23054
23206
  return { pinned, installed, running };
23055
23207
  }
23056
23208
  }
23057
- const parent = import_node_path35.default.dirname(dir);
23209
+ const parent = import_node_path36.default.dirname(dir);
23058
23210
  if (parent === dir || !(0, import_node_fs32.existsSync)(parent)) break;
23059
23211
  dir = parent;
23060
23212
  }
@@ -23118,18 +23270,18 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
23118
23270
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
23119
23271
  );
23120
23272
  }
23121
- const facts = readInstallFacts(import_node_path36.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
23273
+ const facts = readInstallFacts(import_node_path37.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
23122
23274
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
23123
23275
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
23124
23276
  const dirs = [...new Set(specs.flatMap((spec) => [
23125
- import_node_path36.default.dirname(spec.outFile),
23126
- ...spec.quality ? [import_node_path36.default.dirname(spec.quality.outFile)] : []
23277
+ import_node_path37.default.dirname(spec.outFile),
23278
+ ...spec.quality ? [import_node_path37.default.dirname(spec.quality.outFile)] : []
23127
23279
  ]))];
23128
23280
  const unwritable = [];
23129
23281
  for (const dir of dirs) {
23130
23282
  const ancestor = await nearestExistingDirectory(dir);
23131
23283
  try {
23132
- await (0, import_promises24.access)(ancestor, import_node_fs33.constants.W_OK);
23284
+ await (0, import_promises25.access)(ancestor, import_node_fs33.constants.W_OK);
23133
23285
  } catch {
23134
23286
  unwritable.push(dir);
23135
23287
  }
@@ -23146,7 +23298,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
23146
23298
  for (let index = 0; index < entry.outputs.length; index++) {
23147
23299
  const output = entry.outputs[index];
23148
23300
  const spec = specByKey.get(key3);
23149
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path36.default.dirname(lockPath));
23301
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path37.default.dirname(lockPath));
23150
23302
  const owner = outputOwners.get(absolute);
23151
23303
  if (owner && owner !== key3) duplicateOutputs.push(`${output.path} (${owner}, ${key3})`);
23152
23304
  outputOwners.set(absolute, key3);
@@ -23161,7 +23313,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
23161
23313
  } else {
23162
23314
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
23163
23315
  }
23164
- const cacheDir = import_node_path36.default.join(import_node_path36.default.dirname(lockPath), ".pixelkiln", "cache");
23316
+ const cacheDir = import_node_path37.default.join(import_node_path37.default.dirname(lockPath), ".pixelkiln", "cache");
23165
23317
  const stranded = [];
23166
23318
  const invalidState = [];
23167
23319
  const staleMapUrls = [];
@@ -23177,7 +23329,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
23177
23329
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
23178
23330
  let hasCache = false;
23179
23331
  for (const output of entry.outputs) {
23180
- const cached2 = import_node_path36.default.join(
23332
+ const cached2 = import_node_path37.default.join(
23181
23333
  cacheDir,
23182
23334
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
23183
23335
  );
@@ -23274,10 +23426,10 @@ async function nearestExistingDirectory(start) {
23274
23426
  let current = start;
23275
23427
  for (; ; ) {
23276
23428
  try {
23277
- if ((await (0, import_promises24.stat)(current)).isDirectory()) return current;
23429
+ if ((await (0, import_promises25.stat)(current)).isDirectory()) return current;
23278
23430
  } catch {
23279
23431
  }
23280
- const parent = import_node_path36.default.dirname(current);
23432
+ const parent = import_node_path37.default.dirname(current);
23281
23433
  if (parent === current) return current;
23282
23434
  current = parent;
23283
23435
  }
@@ -23285,8 +23437,8 @@ async function nearestExistingDirectory(start) {
23285
23437
 
23286
23438
  // src/pipeline/adopt.ts
23287
23439
  var import_node_fs34 = require("fs");
23288
- var import_promises25 = require("fs/promises");
23289
- var import_node_path37 = __toESM(require("path"), 1);
23440
+ var import_promises26 = require("fs/promises");
23441
+ var import_node_path38 = __toESM(require("path"), 1);
23290
23442
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
23291
23443
  const log = opts.onProgress ?? (() => {
23292
23444
  });
@@ -23301,7 +23453,7 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
23301
23453
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
23302
23454
  continue;
23303
23455
  }
23304
- const bytes = await (0, import_promises25.readFile)(spec.outFile);
23456
+ const bytes = await (0, import_promises26.readFile)(spec.outFile);
23305
23457
  try {
23306
23458
  decodePng(bytes);
23307
23459
  } catch (err) {
@@ -23420,8 +23572,8 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
23420
23572
 
23421
23573
  // src/pipeline/import.ts
23422
23574
  var import_node_fs35 = require("fs");
23423
- var import_promises26 = require("fs/promises");
23424
- var import_node_path38 = __toESM(require("path"), 1);
23575
+ var import_promises27 = require("fs/promises");
23576
+ var import_node_path39 = __toESM(require("path"), 1);
23425
23577
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date(), frames) {
23426
23578
  const png = decodePng(bytes);
23427
23579
  for (const frame of frames ?? []) decodePng(frame.bytes);
@@ -23474,10 +23626,10 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
23474
23626
  var frameRole2 = (index) => `frame-${String(index).padStart(2, "0")}`;
23475
23627
  async function findFrames(spec) {
23476
23628
  const at2 = (index) => memberPath(spec.outFile, frameRole2(index), 0, 2, MediaType.PNG);
23477
- const base = import_node_path38.default.basename(at2(0)).replace(/00\.png$/, "");
23629
+ const base = import_node_path39.default.basename(at2(0)).replace(/00\.png$/, "");
23478
23630
  let names = [];
23479
23631
  try {
23480
- names = await (0, import_promises26.readdir)(import_node_path38.default.dirname(spec.outFile));
23632
+ names = await (0, import_promises27.readdir)(import_node_path39.default.dirname(spec.outFile));
23481
23633
  } catch {
23482
23634
  names = [];
23483
23635
  }
@@ -23507,13 +23659,13 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
23507
23659
  if (opts.objectId && specs.length !== 1) {
23508
23660
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
23509
23661
  }
23510
- const cacheDir = opts.cacheDir === false ? null : import_node_path38.default.resolve(opts.cacheDir ?? import_node_path38.default.join(import_node_path38.default.dirname(lockPath), ".pixelkiln", "cache"));
23662
+ const cacheDir = opts.cacheDir === false ? null : import_node_path39.default.resolve(opts.cacheDir ?? import_node_path39.default.join(import_node_path39.default.dirname(lockPath), ".pixelkiln", "cache"));
23511
23663
  let rawSha256;
23512
23664
  let rawBytes;
23513
23665
  if (opts.raw) {
23514
23666
  if (specs.length !== 1) throw new Error(`--raw names one original; ${specs.length} assets are selected. Narrow with --only and --style.`);
23515
23667
  try {
23516
- rawBytes = await (0, import_promises26.readFile)(opts.raw);
23668
+ rawBytes = await (0, import_promises27.readFile)(opts.raw);
23517
23669
  decodePng(rawBytes);
23518
23670
  } catch (error) {
23519
23671
  throw new Error(`--raw ${opts.raw} is not a readable PNG: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
@@ -23537,7 +23689,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
23537
23689
  continue;
23538
23690
  }
23539
23691
  if ("missing" in frames2) {
23540
- skipped.push({ key: key3, reason: `frame set is missing ${frames2.missing.map((file) => import_node_path38.default.basename(file)).join(", ")} (in ${import_node_path38.default.dirname(spec.outFile)})` });
23692
+ skipped.push({ key: key3, reason: `frame set is missing ${frames2.missing.map((file) => import_node_path39.default.basename(file)).join(", ")} (in ${import_node_path39.default.dirname(spec.outFile)})` });
23541
23693
  continue;
23542
23694
  }
23543
23695
  frameFiles = frames2.files;
@@ -23550,8 +23702,8 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
23550
23702
  let bytes;
23551
23703
  let frames;
23552
23704
  try {
23553
- frames = frameFiles ? await Promise.all(frameFiles.map(async (frame) => ({ ...frame, bytes: await (0, import_promises26.readFile)(frame.file) }))) : void 0;
23554
- bytes = frames ? frames[0].bytes : await (0, import_promises26.readFile)(spec.outFile);
23705
+ frames = frameFiles ? await Promise.all(frameFiles.map(async (frame) => ({ ...frame, bytes: await (0, import_promises27.readFile)(frame.file) }))) : void 0;
23706
+ bytes = frames ? frames[0].bytes : await (0, import_promises27.readFile)(spec.outFile);
23555
23707
  patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date(), frames);
23556
23708
  } catch (error) {
23557
23709
  skipped.push({ key: key3, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
@@ -23584,7 +23736,7 @@ async function reportSpecHashes(specs, lock) {
23584
23736
  for (const spec of specs) {
23585
23737
  const key3 = lockKey(spec.styleId, spec.assetId);
23586
23738
  let bytes = null;
23587
- if ((0, import_node_fs35.existsSync)(spec.outFile)) bytes = await (0, import_promises26.readFile)(spec.outFile);
23739
+ if ((0, import_node_fs35.existsSync)(spec.outFile)) bytes = await (0, import_promises27.readFile)(spec.outFile);
23588
23740
  let wouldImport = null;
23589
23741
  if (bytes && !unimportable(spec)) {
23590
23742
  try {
@@ -23614,12 +23766,12 @@ async function reportSpecHashes(specs, lock) {
23614
23766
 
23615
23767
  // src/pick/server.ts
23616
23768
  var import_node_fs37 = require("fs");
23617
- var import_promises29 = require("fs/promises");
23769
+ var import_promises30 = require("fs/promises");
23618
23770
 
23619
23771
  // src/pipeline/init.ts
23620
- var import_promises27 = require("fs/promises");
23772
+ var import_promises28 = require("fs/promises");
23621
23773
  var import_node_fs36 = require("fs");
23622
- var import_node_path39 = __toESM(require("path"), 1);
23774
+ var import_node_path40 = __toESM(require("path"), 1);
23623
23775
  function pngSize(buf) {
23624
23776
  if (buf.length < 24) return null;
23625
23777
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -23632,8 +23784,8 @@ function slugify(value) {
23632
23784
  }
23633
23785
  async function walk(dir, exclude) {
23634
23786
  const out = [];
23635
- for (const entry of await (0, import_promises27.readdir)(dir, { withFileTypes: true })) {
23636
- const full = import_node_path39.default.join(dir, entry.name);
23787
+ for (const entry of await (0, import_promises28.readdir)(dir, { withFileTypes: true })) {
23788
+ const full = import_node_path40.default.join(dir, entry.name);
23637
23789
  if (exclude.some((x) => full.includes(x))) continue;
23638
23790
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
23639
23791
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -23647,14 +23799,14 @@ async function scanAssets(root, opts = {}) {
23647
23799
  const skipped = [];
23648
23800
  const seen = /* @__PURE__ */ new Map();
23649
23801
  for (const file of files.sort()) {
23650
- const size = pngSize(await (0, import_promises27.readFile)(file));
23802
+ const size = pngSize(await (0, import_promises28.readFile)(file));
23651
23803
  if (!size) {
23652
23804
  skipped.push(`${file} (not a readable PNG)`);
23653
23805
  continue;
23654
23806
  }
23655
- const rel = import_node_path39.default.relative(root, file);
23656
- const category = import_node_path39.default.dirname(rel) === "." ? "" : import_node_path39.default.dirname(rel);
23657
- let id = slugify(import_node_path39.default.basename(rel));
23807
+ const rel = import_node_path40.default.relative(root, file);
23808
+ const category = import_node_path40.default.dirname(rel) === "." ? "" : import_node_path40.default.dirname(rel);
23809
+ let id = slugify(import_node_path40.default.basename(rel));
23658
23810
  if (seen.has(id)) {
23659
23811
  const n = seen.get(id) + 1;
23660
23812
  seen.set(id, n);
@@ -24631,7 +24783,7 @@ if (CONFIG.sessionUrl) {
24631
24783
 
24632
24784
  // src/pick/review-server.ts
24633
24785
  var import_node_http = require("http");
24634
- var import_promises28 = require("fs/promises");
24786
+ var import_promises29 = require("fs/promises");
24635
24787
  async function readJsonBody(req, res) {
24636
24788
  const expectedOrigin = req.headers.host ? `http://${req.headers.host}` : null;
24637
24789
  if (req.headers.origin && req.headers.origin !== expectedOrigin) {
@@ -24666,7 +24818,7 @@ function serveReviewPage(opts) {
24666
24818
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
24667
24819
  try {
24668
24820
  const asset = opts.assets.get(req.url);
24669
- const bytes = await (0, import_promises28.readFile)(asset.path);
24821
+ const bytes = await (0, import_promises29.readFile)(asset.path);
24670
24822
  res.writeHead(200, {
24671
24823
  "Content-Type": asset.contentType,
24672
24824
  // A frame route names one cached candidate for the life of this
@@ -24749,7 +24901,7 @@ async function currentArt(entry, spec) {
24749
24901
  let width = entry.width;
24750
24902
  let height = entry.height;
24751
24903
  if (contentType === "image/png") {
24752
- const size = pngSize(await (0, import_promises29.readFile)(file));
24904
+ const size = pngSize(await (0, import_promises30.readFile)(file));
24753
24905
  if (size) ({ width, height } = size);
24754
24906
  }
24755
24907
  return { path: file, contentType, width, height };
@@ -24757,7 +24909,7 @@ async function currentArt(entry, spec) {
24757
24909
  async function cachedFrame(url) {
24758
24910
  if (!url.startsWith("file://")) return null;
24759
24911
  const file = url.slice("file://".length);
24760
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises29.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
24912
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises30.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
24761
24913
  return { path: file, contentType };
24762
24914
  }
24763
24915
  async function prepareReview(provider, lock, opts = {}) {
@@ -24819,7 +24971,7 @@ async function prepareReview(provider, lock, opts = {}) {
24819
24971
  frameSizes.push(null);
24820
24972
  continue;
24821
24973
  }
24822
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises29.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
24974
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises30.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
24823
24975
  const route = `${prefix}/review-frame/${encodeURIComponent(String((opts.routeBase ?? 0) + groups.length))}/${index}`;
24824
24976
  frameAssets.push([route, cached2]);
24825
24977
  frameUrls.push(route);
@@ -25160,13 +25312,13 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
25160
25312
  // src/gallery/snapshot.ts
25161
25313
  var import_node_crypto10 = require("crypto");
25162
25314
  var import_node_fs46 = require("fs");
25163
- var import_promises40 = require("fs/promises");
25164
- var import_node_path50 = __toESM(require("path"), 1);
25315
+ var import_promises41 = require("fs/promises");
25316
+ var import_node_path51 = __toESM(require("path"), 1);
25165
25317
 
25166
25318
  // src/gallery/models.ts
25167
25319
  var import_node_fs41 = require("fs");
25168
- var import_promises34 = require("fs/promises");
25169
- var import_node_path44 = __toESM(require("path"), 1);
25320
+ var import_promises35 = require("fs/promises");
25321
+ var import_node_path45 = __toESM(require("path"), 1);
25170
25322
  var import_zod12 = require("zod");
25171
25323
 
25172
25324
  // src/glb.ts
@@ -25499,11 +25651,11 @@ function modelItems(json2) {
25499
25651
  }
25500
25652
 
25501
25653
  // src/manifest-edit.ts
25502
- var import_promises30 = require("fs/promises");
25503
- var import_node_path40 = __toESM(require("path"), 1);
25654
+ var import_promises31 = require("fs/promises");
25655
+ var import_node_path41 = __toESM(require("path"), 1);
25504
25656
  var import_zod9 = require("zod");
25505
25657
  var HexSha = import_zod9.z.string().regex(/^[0-9a-f]{64}$/);
25506
- var ProjectFileSchema = import_zod9.z.string().min(1).refine((file) => !import_node_path40.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
25658
+ var ProjectFileSchema = import_zod9.z.string().min(1).refine((file) => !import_node_path41.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
25507
25659
  var AssetPatchSchema = import_zod9.z.object({
25508
25660
  prompt: import_zod9.z.string().optional(),
25509
25661
  /** Per-style override for the style being viewed; null removes it. */
@@ -25924,8 +26076,8 @@ function applyEdit(raw, edit) {
25924
26076
  }
25925
26077
  }
25926
26078
  async function withCandidate(manifestPath, edit, use, unchanged) {
25927
- const absolute = import_node_path40.default.resolve(manifestPath);
25928
- const original = await (0, import_promises30.readFile)(absolute, "utf8");
26079
+ const absolute = import_node_path41.default.resolve(manifestPath);
26080
+ const original = await (0, import_promises31.readFile)(absolute, "utf8");
25929
26081
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
25930
26082
  let raw;
25931
26083
  try {
@@ -25938,12 +26090,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
25938
26090
  applyEdit(raw, edit);
25939
26091
  const next = serializeLike(original, raw);
25940
26092
  if (next === original) return unchanged(absolute, original);
25941
- const tmp = import_node_path40.default.join(
25942
- import_node_path40.default.dirname(absolute),
25943
- `.${import_node_path40.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
26093
+ const tmp = import_node_path41.default.join(
26094
+ import_node_path41.default.dirname(absolute),
26095
+ `.${import_node_path41.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
25944
26096
  );
25945
26097
  try {
25946
- await (0, import_promises30.writeFile)(tmp, next);
26098
+ await (0, import_promises31.writeFile)(tmp, next);
25947
26099
  let specs;
25948
26100
  try {
25949
26101
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -25953,7 +26105,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
25953
26105
  }
25954
26106
  return await use({ absolute, original, next, tmp, specs });
25955
26107
  } finally {
25956
- await (0, import_promises30.rm)(tmp, { force: true });
26108
+ await (0, import_promises31.rm)(tmp, { force: true });
25957
26109
  }
25958
26110
  }
25959
26111
  async function applyManifestEdit(manifestPath, edit) {
@@ -25961,7 +26113,7 @@ async function applyManifestEdit(manifestPath, edit) {
25961
26113
  manifestPath,
25962
26114
  edit,
25963
26115
  async ({ absolute, next, tmp }) => {
25964
- await (0, import_promises30.rename)(tmp, absolute);
26116
+ await (0, import_promises31.rename)(tmp, absolute);
25965
26117
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
25966
26118
  },
25967
26119
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -25970,17 +26122,17 @@ async function applyManifestEdit(manifestPath, edit) {
25970
26122
 
25971
26123
  // src/pipeline/hand-edit.ts
25972
26124
  var import_node_fs38 = require("fs");
25973
- var import_promises31 = require("fs/promises");
25974
- var import_node_path41 = __toESM(require("path"), 1);
26125
+ var import_promises32 = require("fs/promises");
26126
+ var import_node_path42 = __toESM(require("path"), 1);
25975
26127
  var import_zod10 = require("zod");
25976
26128
  var HAND_EDIT_DIR = "edits";
25977
26129
  function handEditPath(loaded, spec) {
25978
26130
  const style = loaded.manifest.styles[spec.styleId];
25979
- const outDir = import_node_path41.default.resolve(loaded.root, style?.outDir ?? ".");
25980
- const relative = import_node_path41.default.relative(outDir, spec.outFile);
25981
- const inside2 = relative && !relative.startsWith("..") && !import_node_path41.default.isAbsolute(relative);
25982
- const file = inside2 ? relative : import_node_path41.default.basename(spec.outFile);
25983
- return import_node_path41.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
26131
+ const outDir = import_node_path42.default.resolve(loaded.root, style?.outDir ?? ".");
26132
+ const relative = import_node_path42.default.relative(outDir, spec.outFile);
26133
+ const inside2 = relative && !relative.startsWith("..") && !import_node_path42.default.isAbsolute(relative);
26134
+ const file = inside2 ? relative : import_node_path42.default.basename(spec.outFile);
26135
+ return import_node_path42.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
25984
26136
  }
25985
26137
  function handEditBases(spec, lock) {
25986
26138
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -26046,7 +26198,7 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
26046
26198
  `${spec.styleId}/${spec.assetId} declares ${spec.source}, one committed file placed for the whole set; clear that source (pixelkiln edit detach) to hand-edit the members one by one`
26047
26199
  );
26048
26200
  }
26049
- const existing = spec.source ? import_node_path41.default.resolve(loaded.root, spec.source) : null;
26201
+ const existing = spec.source ? import_node_path42.default.resolve(loaded.root, spec.source) : null;
26050
26202
  const editPath = existing ?? handEditPath(loaded, spec);
26051
26203
  const members = handEditMembers(loaded, spec, lock, editPath);
26052
26204
  let created = false;
@@ -26057,8 +26209,8 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
26057
26209
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
26058
26210
  );
26059
26211
  }
26060
- await (0, import_promises31.mkdir)(import_node_path41.default.dirname(member.path), { recursive: true });
26061
- await (0, import_promises31.copyFile)(member.base, member.path);
26212
+ await (0, import_promises32.mkdir)(import_node_path42.default.dirname(member.path), { recursive: true });
26213
+ await (0, import_promises32.copyFile)(member.base, member.path);
26062
26214
  created = true;
26063
26215
  }
26064
26216
  const source = portableOutputPath(editPath, loaded.root);
@@ -26136,7 +26288,7 @@ function handEditProjectPath(editPath) {
26136
26288
  async function readHandEditCompanion(editPath) {
26137
26289
  let text;
26138
26290
  try {
26139
- text = await (0, import_promises31.readFile)(handEditCompanionPath(editPath), "utf8");
26291
+ text = await (0, import_promises32.readFile)(handEditCompanionPath(editPath), "utf8");
26140
26292
  } catch {
26141
26293
  return null;
26142
26294
  }
@@ -26180,7 +26332,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
26180
26332
  }
26181
26333
  });
26182
26334
  const bases = handEditBases(spec, lock);
26183
- const expectedSize = bases?.[0] ? decodePng(await (0, import_promises31.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
26335
+ const expectedSize = bases?.[0] ? decodePng(await (0, import_promises32.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
26184
26336
  for (const [index, image] of decoded.entries()) {
26185
26337
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
26186
26338
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -26196,7 +26348,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
26196
26348
  editor: input.editor,
26197
26349
  protocol: input.protocol,
26198
26350
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
26199
- project: projectPath ? import_node_path41.default.basename(projectPath) : null,
26351
+ project: projectPath ? import_node_path42.default.basename(projectPath) : null,
26200
26352
  outputs: incoming.map((frame, index) => ({
26201
26353
  role: frame.role,
26202
26354
  basedOn: basedOnHash(entry, index),
@@ -26226,10 +26378,10 @@ function basedOnHash(entry, index) {
26226
26378
  async function replaceFile(file, bytes) {
26227
26379
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
26228
26380
  try {
26229
- await (0, import_promises31.writeFile)(tmp, bytes);
26230
- await (0, import_promises31.rename)(tmp, file);
26381
+ await (0, import_promises32.writeFile)(tmp, bytes);
26382
+ await (0, import_promises32.rename)(tmp, file);
26231
26383
  } finally {
26232
- await (0, import_promises31.rm)(tmp, { force: true });
26384
+ await (0, import_promises32.rm)(tmp, { force: true });
26233
26385
  }
26234
26386
  }
26235
26387
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -26240,8 +26392,8 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
26240
26392
  // src/pipeline/model-edit.ts
26241
26393
  var import_node_child_process3 = require("child_process");
26242
26394
  var import_node_fs39 = require("fs");
26243
- var import_promises32 = require("fs/promises");
26244
- var import_node_path42 = __toESM(require("path"), 1);
26395
+ var import_promises33 = require("fs/promises");
26396
+ var import_node_path43 = __toESM(require("path"), 1);
26245
26397
  var import_zod11 = require("zod");
26246
26398
 
26247
26399
  // src/jpeg.ts
@@ -26623,27 +26775,27 @@ var MAX_MODELS = 200;
26623
26775
  var MAX_DEPTH = 8;
26624
26776
  var SKIPPED_DIRS = /* @__PURE__ */ new Set([HAND_EDIT_DIR, "node_modules"]);
26625
26777
  async function discoverModels(loaded, opts = {}) {
26626
- const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: import_node_path42.default.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
26778
+ const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: import_node_path43.default.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
26627
26779
  const seen = /* @__PURE__ */ new Set();
26628
26780
  const models = [];
26629
26781
  const walk2 = async (styleId, outDir, dir, depth) => {
26630
26782
  if (depth > MAX_DEPTH || models.length >= MAX_MODELS) return;
26631
26783
  let entries;
26632
26784
  try {
26633
- entries = await (0, import_promises32.readdir)(dir, { withFileTypes: true });
26785
+ entries = await (0, import_promises33.readdir)(dir, { withFileTypes: true });
26634
26786
  } catch {
26635
26787
  return;
26636
26788
  }
26637
26789
  entries.sort((a, b) => a.name.localeCompare(b.name));
26638
26790
  for (const entry of entries) {
26639
26791
  if (models.length >= MAX_MODELS) return;
26640
- const full = import_node_path42.default.join(dir, entry.name);
26792
+ const full = import_node_path43.default.join(dir, entry.name);
26641
26793
  if (entry.isDirectory()) {
26642
26794
  if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
26643
26795
  await walk2(styleId, outDir, full, depth + 1);
26644
26796
  } else if (entry.isFile() && entry.name.toLowerCase().endsWith(MODEL_EXTENSION) && !seen.has(full)) {
26645
26797
  seen.add(full);
26646
- models.push({ styleId, file: full, editFile: import_node_path42.default.join(outDir, HAND_EDIT_DIR, import_node_path42.default.relative(outDir, full)) });
26798
+ models.push({ styleId, file: full, editFile: import_node_path43.default.join(outDir, HAND_EDIT_DIR, import_node_path43.default.relative(outDir, full)) });
26647
26799
  }
26648
26800
  }
26649
26801
  };
@@ -26651,12 +26803,12 @@ async function discoverModels(loaded, opts = {}) {
26651
26803
  return models.sort((a, b) => a.styleId.localeCompare(b.styleId) || a.file.localeCompare(b.file));
26652
26804
  }
26653
26805
  async function findModel(loaded, portablePath) {
26654
- const wanted = import_node_path42.default.resolve(loaded.root, portablePath);
26806
+ const wanted = import_node_path43.default.resolve(loaded.root, portablePath);
26655
26807
  const model = (await discoverModels(loaded)).find((candidate) => candidate.file === wanted);
26656
26808
  if (!model) throw new ManifestEditError(`"${portablePath}" is not a model under one of this project's output folders`);
26657
26809
  return model;
26658
26810
  }
26659
- var stem = (editFile) => editFile.slice(0, -import_node_path42.default.extname(editFile).length);
26811
+ var stem = (editFile) => editFile.slice(0, -import_node_path43.default.extname(editFile).length);
26660
26812
  function modelCompanionPath(editFile) {
26661
26813
  return stem(editFile) + ".edit.json";
26662
26814
  }
@@ -26695,7 +26847,7 @@ var ModelEditCompanionSchema = import_zod11.z.object({
26695
26847
  }).strict();
26696
26848
  async function readModelCompanion(editFile) {
26697
26849
  try {
26698
- return ModelEditCompanionSchema.parse(JSON.parse(await (0, import_promises32.readFile)(modelCompanionPath(editFile), "utf8")));
26850
+ return ModelEditCompanionSchema.parse(JSON.parse(await (0, import_promises33.readFile)(modelCompanionPath(editFile), "utf8")));
26699
26851
  } catch {
26700
26852
  return null;
26701
26853
  }
@@ -26705,19 +26857,19 @@ function modelEditStatus(companion, builtSha256) {
26705
26857
  return companion.outputs[0].basedOn === builtSha256 ? "edited" : "rebuilt-since";
26706
26858
  }
26707
26859
  async function replaceFile2(file, bytes) {
26708
- await (0, import_promises32.mkdir)(import_node_path42.default.dirname(file), { recursive: true });
26860
+ await (0, import_promises33.mkdir)(import_node_path43.default.dirname(file), { recursive: true });
26709
26861
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
26710
26862
  try {
26711
- await (0, import_promises32.writeFile)(tmp, bytes);
26712
- await (0, import_promises32.rename)(tmp, file);
26863
+ await (0, import_promises33.writeFile)(tmp, bytes);
26864
+ await (0, import_promises33.rename)(tmp, file);
26713
26865
  } finally {
26714
- await (0, import_promises32.rm)(tmp, { force: true });
26866
+ await (0, import_promises33.rm)(tmp, { force: true });
26715
26867
  }
26716
26868
  }
26717
26869
  async function readModel(file, what) {
26718
26870
  let bytes;
26719
26871
  try {
26720
- bytes = await (0, import_promises32.readFile)(file);
26872
+ bytes = await (0, import_promises33.readFile)(file);
26721
26873
  } catch {
26722
26874
  throw new ManifestEditError(`${what} is not on disk at ${file}`);
26723
26875
  }
@@ -26766,7 +26918,7 @@ async function saveModelTexture(model, input) {
26766
26918
  sha256: sha256(input.png),
26767
26919
  editor: input.editor,
26768
26920
  savedAt,
26769
- project: projectPath ? import_node_path42.default.basename(projectPath) : null
26921
+ project: projectPath ? import_node_path43.default.basename(projectPath) : null
26770
26922
  };
26771
26923
  const companion = {
26772
26924
  version: 2,
@@ -26870,16 +27022,16 @@ function blenderCommand(env = process.env, platform = process.platform, exists =
26870
27022
  const candidates = [];
26871
27023
  if (platform === "darwin") {
26872
27024
  candidates.push("/Applications/Blender.app/Contents/MacOS/Blender");
26873
- if (env.HOME) candidates.push(import_node_path42.default.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
27025
+ if (env.HOME) candidates.push(import_node_path43.default.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
26874
27026
  } else if (platform === "win32") {
26875
27027
  for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((value) => Boolean(value))) {
26876
- const foundation = import_node_path42.default.win32.join(root, "Blender Foundation");
27028
+ const foundation = import_node_path43.default.win32.join(root, "Blender Foundation");
26877
27029
  const versions = list(foundation).filter((name) => /^Blender/i.test(name)).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
26878
- for (const version of versions) candidates.push(import_node_path42.default.win32.join(foundation, version, "blender.exe"));
27030
+ for (const version of versions) candidates.push(import_node_path43.default.win32.join(foundation, version, "blender.exe"));
26879
27031
  }
26880
27032
  } else {
26881
27033
  candidates.push("/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender", "/var/lib/flatpak/exports/bin/org.blender.Blender");
26882
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(import_node_path42.default.join(dir, "blender"));
27034
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(import_node_path43.default.join(dir, "blender"));
26883
27035
  }
26884
27036
  const found = candidates.find((candidate) => exists(candidate));
26885
27037
  return found ? [found] : null;
@@ -26922,14 +27074,14 @@ function openInBlender(model, opts = {}) {
26922
27074
  child.unref();
26923
27075
  });
26924
27076
  launch(program, args);
26925
- return `${command.join(" ")} (${import_node_path42.default.basename(file)})`;
27077
+ return `${command.join(" ")} (${import_node_path43.default.basename(file)})`;
26926
27078
  }
26927
27079
 
26928
27080
  // src/pipeline/model-normals.ts
26929
27081
  var import_node_crypto9 = require("crypto");
26930
27082
  var import_node_fs40 = require("fs");
26931
- var import_promises33 = require("fs/promises");
26932
- var import_node_path43 = __toESM(require("path"), 1);
27083
+ var import_promises34 = require("fs/promises");
27084
+ var import_node_path44 = __toESM(require("path"), 1);
26933
27085
  var MODEL_NORMAL_SOURCES = ["texture", "views", "sprites"];
26934
27086
  var TILE_MAX = 512;
26935
27087
  function decodeImage(bytes) {
@@ -27021,13 +27173,13 @@ function poseNodes(document2, pose) {
27021
27173
  const posed = /* @__PURE__ */ new Map();
27022
27174
  for (const channel of animation.channels) {
27023
27175
  const node = channel.target.node;
27024
- const path54 = channel.target.path;
27025
- if (node === void 0 || !["translation", "rotation", "scale"].includes(path54)) continue;
27176
+ const path55 = channel.target.path;
27177
+ if (node === void 0 || !["translation", "rotation", "scale"].includes(path55)) continue;
27026
27178
  const sampler = animation.samplers[channel.sampler];
27027
27179
  if (!sampler) continue;
27028
27180
  const times = readAccessor(document2, sampler.input).data;
27029
27181
  const values = readAccessor(document2, sampler.output);
27030
- const width = path54 === "rotation" ? 4 : 3;
27182
+ const width = path55 === "rotation" ? 4 : 3;
27031
27183
  const cubic = sampler.interpolation === "CUBICSPLINE";
27032
27184
  const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
27033
27185
  const last = times.length - 1;
@@ -27039,16 +27191,16 @@ function poseNodes(document2, pose) {
27039
27191
  const span = times[key3 + 1] - times[key3];
27040
27192
  const f = span > 0 ? (time - times[key3]) / span : 0;
27041
27193
  const next = valueAt(key3 + 1);
27042
- const sign = path54 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
27194
+ const sign = path55 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
27043
27195
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
27044
27196
  }
27045
- if (path54 === "rotation") {
27197
+ if (path55 === "rotation") {
27046
27198
  const length = Math.hypot(...value) || 1;
27047
27199
  value = value.map((v) => v / length);
27048
27200
  }
27049
27201
  const base = posed.get(node) ?? { ...document2.json.nodes?.[node] ?? {} };
27050
27202
  if (base.matrix) delete base.matrix;
27051
- base[path54] = value;
27203
+ base[path55] = value;
27052
27204
  posed.set(node, base);
27053
27205
  }
27054
27206
  return posed;
@@ -27658,9 +27810,9 @@ function modelSpritesDir(modelFile) {
27658
27810
  return modelFile.replace(/\.glb$/i, "") + ".sprites";
27659
27811
  }
27660
27812
  async function readSpriteFolder(dir) {
27661
- const folder = (0, import_node_fs40.existsSync)(import_node_path43.default.join(dir, "rotations")) ? import_node_path43.default.join(dir, "rotations") : dir;
27662
- const names = (await (0, import_promises33.readdir)(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
27663
- return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await (0, import_promises33.readFile)(import_node_path43.default.join(folder, name)), file: import_node_path43.default.join(folder, name) })));
27813
+ const folder = (0, import_node_fs40.existsSync)(import_node_path44.default.join(dir, "rotations")) ? import_node_path44.default.join(dir, "rotations") : dir;
27814
+ const names = (await (0, import_promises34.readdir)(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
27815
+ return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await (0, import_promises34.readFile)(import_node_path44.default.join(folder, name)), file: import_node_path44.default.join(folder, name) })));
27664
27816
  }
27665
27817
  function modelNormalDir(editFile) {
27666
27818
  return editFile.replace(/\.glb$/i, "") + ".normal-map";
@@ -27671,7 +27823,7 @@ function requestKey(png, options) {
27671
27823
  }
27672
27824
  async function prepare(model, opts) {
27673
27825
  const fromEdit = (0, import_node_fs40.existsSync)(model.editFile);
27674
- const document2 = parseGlb(await (0, import_promises33.readFile)(fromEdit ? model.editFile : model.file));
27826
+ const document2 = parseGlb(await (0, import_promises34.readFile)(fromEdit ? model.editFile : model.file));
27675
27827
  const summary = describeGlb(document2);
27676
27828
  const normalImages = summary.images.filter((image) => image.roles.includes("normal"));
27677
27829
  if (!normalImages.length) throw new Error("the model has no normal maps; this adds detail to one it has, it does not add a new one");
@@ -27680,13 +27832,13 @@ async function prepare(model, opts) {
27680
27832
  if (!normalImages.some((image) => image.index === index)) throw new Error(`image ${index} is not one of the model's normal maps`);
27681
27833
  }
27682
27834
  const primitives = restPrimitives(document2, opts.pose);
27683
- const dir = import_node_path43.default.join(modelNormalDir(model.editFile), opts.source);
27835
+ const dir = import_node_path44.default.join(modelNormalDir(model.editFile), opts.source);
27684
27836
  const surfaces = /* @__PURE__ */ new Map();
27685
27837
  const tiles = /* @__PURE__ */ new Map();
27686
27838
  const calls = [];
27687
27839
  const images = [];
27688
27840
  const call = (label, png) => {
27689
- const cache = import_node_path43.default.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
27841
+ const cache = import_node_path44.default.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
27690
27842
  calls.push({ label, png, cache, cached: (0, import_node_fs40.existsSync)(cache) });
27691
27843
  };
27692
27844
  for (const index of wanted) {
@@ -27755,15 +27907,15 @@ async function prepare(model, opts) {
27755
27907
  }
27756
27908
  async function planModelNormals(model, opts) {
27757
27909
  const { plan } = await prepare(model, opts);
27758
- await (0, import_promises33.mkdir)(plan.dir, { recursive: true });
27759
- for (const entry of plan.calls) await (0, import_promises33.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27760
- for (const fit of plan.fits ?? []) await (0, import_promises33.writeFile)(import_node_path43.default.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
27910
+ await (0, import_promises34.mkdir)(plan.dir, { recursive: true });
27911
+ for (const entry of plan.calls) await (0, import_promises34.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27912
+ for (const fit of plan.fits ?? []) await (0, import_promises34.writeFile)(import_node_path44.default.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
27761
27913
  return plan;
27762
27914
  }
27763
27915
  async function generateModelNormals(model, opts, mapper, hooks = {}) {
27764
27916
  const prepared = await prepare(model, opts);
27765
27917
  const { plan, document: document2 } = prepared;
27766
- await (0, import_promises33.mkdir)(plan.dir, { recursive: true });
27918
+ await (0, import_promises34.mkdir)(plan.dir, { recursive: true });
27767
27919
  const request = {
27768
27920
  ...opts.mode ? { mode: opts.mode } : {},
27769
27921
  ...opts.kind ? { kind: opts.kind } : {},
@@ -27775,14 +27927,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
27775
27927
  let sent = 0;
27776
27928
  for (const entry of plan.calls) {
27777
27929
  hooks.onCall?.(entry.label, entry.cached);
27778
- await (0, import_promises33.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27930
+ await (0, import_promises34.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27779
27931
  if (entry.cached) {
27780
- answers.push(await (0, import_promises33.readFile)(entry.cache));
27932
+ answers.push(await (0, import_promises34.readFile)(entry.cache));
27781
27933
  continue;
27782
27934
  }
27783
27935
  const answer = await mapper(entry.png, request);
27784
27936
  sent++;
27785
- await (0, import_promises33.writeFile)(entry.cache, answer);
27937
+ await (0, import_promises34.writeFile)(entry.cache, answer);
27786
27938
  answers.push(answer);
27787
27939
  }
27788
27940
  let result = null;
@@ -27800,14 +27952,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
27800
27952
  field = detailFromViews(surface, prepared.views, answers);
27801
27953
  }
27802
27954
  bleed(field);
27803
- const detail = import_node_path43.default.join(plan.dir, `image-${image}.detail.png`);
27804
- await (0, import_promises33.writeFile)(detail, encodeImage(fieldImage(field)));
27955
+ const detail = import_node_path44.default.join(plan.dir, `image-${image}.detail.png`);
27956
+ await (0, import_promises34.writeFile)(detail, encodeImage(fieldImage(field)));
27805
27957
  details.push(detail);
27806
- const basePath = import_node_path43.default.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
27958
+ const basePath = import_node_path44.default.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
27807
27959
  const record = companion?.textures.find((entry) => entry.image === image);
27808
27960
  const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && (0, import_node_fs40.existsSync)(basePath);
27809
- const existing = ours ? decodeImage(await (0, import_promises33.readFile)(basePath)) : decodeImage(glbImageBytes(document2, image).bytes);
27810
- if (!ours) await (0, import_promises33.writeFile)(basePath, encodeImage(existing));
27961
+ const existing = ours ? decodeImage(await (0, import_promises34.readFile)(basePath)) : decodeImage(glbImageBytes(document2, image).bytes);
27962
+ if (!ours) await (0, import_promises34.writeFile)(basePath, encodeImage(existing));
27811
27963
  const png = encodeImage(applyDetail(existing, field, opts));
27812
27964
  result = await saveModelTexture(model, {
27813
27965
  image,
@@ -27836,7 +27988,7 @@ function modelNormalMapper(client2) {
27836
27988
  // src/gallery/models.ts
27837
27989
  var MODEL_FILE_TYPE = "model/gltf-binary";
27838
27990
  async function describeFile(media, mediaId, root, file, bytes) {
27839
- const info = await (0, import_promises34.stat)(file);
27991
+ const info = await (0, import_promises35.stat)(file);
27840
27992
  const id = mediaId(file);
27841
27993
  const hash = sha256(bytes);
27842
27994
  media.set(id, { path: file, contentType: MODEL_FILE_TYPE });
@@ -27855,11 +28007,11 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27855
28007
  for (const model of await discoverModels(loaded, opts)) {
27856
28008
  let bytes;
27857
28009
  try {
27858
- bytes = await (0, import_promises34.readFile)(model.file);
28010
+ bytes = await (0, import_promises35.readFile)(model.file);
27859
28011
  } catch {
27860
28012
  continue;
27861
28013
  }
27862
- const outDir = import_node_path44.default.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
28014
+ const outDir = import_node_path45.default.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
27863
28015
  let summary = null;
27864
28016
  let error = null;
27865
28017
  if (bytes.length > MAX_MODEL_BYTES) error = `the file is ${bytes.length} bytes; models over ${MAX_MODEL_BYTES} are listed but not opened`;
@@ -27875,7 +28027,7 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27875
28027
  let adoptedExport = null;
27876
28028
  if ((0, import_node_fs41.existsSync)(model.editFile)) {
27877
28029
  try {
27878
- const editBytes = await (0, import_promises34.readFile)(model.editFile);
28030
+ const editBytes = await (0, import_promises35.readFile)(model.editFile);
27879
28031
  const described = await describeFile(media, mediaId, root, model.editFile, editBytes);
27880
28032
  const companion = await readModelCompanion(model.editFile);
27881
28033
  adoptedExport = companion?.adoptedExport ?? null;
@@ -27911,8 +28063,8 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27911
28063
  const exportFile = modelExportPath(model.editFile);
27912
28064
  let exportWaiting = null;
27913
28065
  try {
27914
- const info = await (0, import_promises34.stat)(exportFile);
27915
- if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await (0, import_promises34.readFile)(exportFile)) !== adoptedExport) {
28066
+ const info = await (0, import_promises35.stat)(exportFile);
28067
+ if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await (0, import_promises35.readFile)(exportFile)) !== adoptedExport) {
27916
28068
  exportWaiting = { bytes: info.size, modifiedAt: info.mtime.toISOString() };
27917
28069
  }
27918
28070
  } catch {
@@ -27925,12 +28077,12 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27925
28077
  } catch {
27926
28078
  }
27927
28079
  }
27928
- const relative = import_node_path44.default.relative(outDir, model.file).split(import_node_path44.default.sep).join("/");
28080
+ const relative = import_node_path45.default.relative(outDir, model.file).split(import_node_path45.default.sep).join("/");
27929
28081
  models.push({
27930
28082
  id: `model:${model.styleId}/${relative}`,
27931
28083
  project: null,
27932
28084
  styleId: model.styleId,
27933
- name: import_node_path44.default.basename(model.file, import_node_path44.default.extname(model.file)),
28085
+ name: import_node_path45.default.basename(model.file, import_node_path45.default.extname(model.file)),
27934
28086
  file,
27935
28087
  summary,
27936
28088
  error,
@@ -28025,9 +28177,9 @@ function blenderAvailable() {
28025
28177
  }
28026
28178
 
28027
28179
  // src/workspace.ts
28028
- var import_promises35 = require("fs/promises");
28180
+ var import_promises36 = require("fs/promises");
28029
28181
  var import_node_fs42 = require("fs");
28030
- var import_node_path45 = __toESM(require("path"), 1);
28182
+ var import_node_path46 = __toESM(require("path"), 1);
28031
28183
  var import_zod13 = require("zod");
28032
28184
  var WorkspaceProjectSchema = import_zod13.z.object({
28033
28185
  id: import_zod13.z.string().min(1),
@@ -28055,7 +28207,7 @@ async function loadWorkspace(workspacePath) {
28055
28207
  if (!(0, import_node_fs42.existsSync)(workspacePath)) return { version: 1, projects: [] };
28056
28208
  let raw;
28057
28209
  try {
28058
- raw = JSON.parse(await (0, import_promises35.readFile)(workspacePath, "utf8"));
28210
+ raw = JSON.parse(await (0, import_promises36.readFile)(workspacePath, "utf8"));
28059
28211
  } catch (err) {
28060
28212
  throw new ProjectError(
28061
28213
  `Workspace catalog at ${workspacePath} is malformed:
@@ -28069,22 +28221,22 @@ async function saveWorkspace(workspacePath, ws) {
28069
28221
  version: 1,
28070
28222
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
28071
28223
  };
28072
- await (0, import_promises35.mkdir)(import_node_path45.default.dirname(import_node_path45.default.resolve(workspacePath)), { recursive: true });
28224
+ await (0, import_promises36.mkdir)(import_node_path46.default.dirname(import_node_path46.default.resolve(workspacePath)), { recursive: true });
28073
28225
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
28074
28226
  try {
28075
- await (0, import_promises35.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
28076
- await (0, import_promises35.rename)(tmp, workspacePath);
28227
+ await (0, import_promises36.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
28228
+ await (0, import_promises36.rename)(tmp, workspacePath);
28077
28229
  } finally {
28078
- await (0, import_promises35.rm)(tmp, { force: true });
28230
+ await (0, import_promises36.rm)(tmp, { force: true });
28079
28231
  }
28080
28232
  }
28081
28233
  function toPortablePath(dir, absolute) {
28082
- return import_node_path45.default.relative(dir, absolute).split(import_node_path45.default.sep).join("/");
28234
+ return import_node_path46.default.relative(dir, absolute).split(import_node_path46.default.sep).join("/");
28083
28235
  }
28084
28236
  function resolveProject(dir, project2) {
28085
28237
  return {
28086
- manifestPath: import_node_path45.default.resolve(dir, project2.manifest.split("/").join(import_node_path45.default.sep)),
28087
- lockPath: import_node_path45.default.resolve(dir, project2.lock.split("/").join(import_node_path45.default.sep))
28238
+ manifestPath: import_node_path46.default.resolve(dir, project2.manifest.split("/").join(import_node_path46.default.sep)),
28239
+ lockPath: import_node_path46.default.resolve(dir, project2.lock.split("/").join(import_node_path46.default.sep))
28088
28240
  };
28089
28241
  }
28090
28242
  function validateWorkspace(ws, dir) {
@@ -28097,7 +28249,7 @@ function validateWorkspace(ws, dir) {
28097
28249
  const { manifestPath, lockPath } = resolveProject(dir, project2);
28098
28250
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project2.id]);
28099
28251
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project2.id]);
28100
- if (import_node_path45.default.isAbsolute(project2.manifest) || import_node_path45.default.isAbsolute(project2.lock)) {
28252
+ if (import_node_path46.default.isAbsolute(project2.manifest) || import_node_path46.default.isAbsolute(project2.lock)) {
28101
28253
  diagnostics.push({
28102
28254
  id: "absolute-path",
28103
28255
  level: "warning",
@@ -28158,14 +28310,14 @@ function validateWorkspace(ws, dir) {
28158
28310
  }
28159
28311
 
28160
28312
  // src/gallery/edit.ts
28161
- var import_promises39 = require("fs/promises");
28162
- var import_node_path49 = __toESM(require("path"), 1);
28313
+ var import_promises40 = require("fs/promises");
28314
+ var import_node_path50 = __toESM(require("path"), 1);
28163
28315
  var import_zod17 = require("zod");
28164
28316
 
28165
28317
  // src/gallery/upload.ts
28166
28318
  var import_node_fs43 = require("fs");
28167
- var import_promises36 = require("fs/promises");
28168
- var import_node_path46 = __toESM(require("path"), 1);
28319
+ var import_promises37 = require("fs/promises");
28320
+ var import_node_path47 = __toESM(require("path"), 1);
28169
28321
  var import_zod14 = require("zod");
28170
28322
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
28171
28323
  var UploadImageSchema = import_zod14.z.object({
@@ -28178,12 +28330,12 @@ var UploadImageSchema = import_zod14.z.object({
28178
28330
  overwrite: import_zod14.z.boolean().optional()
28179
28331
  }).strict();
28180
28332
  async function saveProjectImage(root, request) {
28181
- const file = import_node_path46.default.resolve(root, request.path);
28182
- const relative = import_node_path46.default.relative(root, file);
28183
- if (relative.startsWith("..") || import_node_path46.default.isAbsolute(relative)) {
28333
+ const file = import_node_path47.default.resolve(root, request.path);
28334
+ const relative = import_node_path47.default.relative(root, file);
28335
+ if (relative.startsWith("..") || import_node_path47.default.isAbsolute(relative)) {
28184
28336
  throw new ManifestEditError("an upload must stay inside the project");
28185
28337
  }
28186
- const extension = import_node_path46.default.extname(file).toLowerCase();
28338
+ const extension = import_node_path47.default.extname(file).toLowerCase();
28187
28339
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
28188
28340
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
28189
28341
  const bytes = Buffer.from(request.base64, "base64");
@@ -28196,17 +28348,17 @@ async function saveProjectImage(root, request) {
28196
28348
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
28197
28349
  }
28198
28350
  if ((0, import_node_fs43.existsSync)(file) && !request.overwrite) {
28199
- throw new ManifestEditError(`${relative.split(import_node_path46.default.sep).join("/")} already exists; choose another name, or replace it`);
28351
+ throw new ManifestEditError(`${relative.split(import_node_path47.default.sep).join("/")} already exists; choose another name, or replace it`);
28200
28352
  }
28201
- await (0, import_promises36.mkdir)(import_node_path46.default.dirname(file), { recursive: true });
28202
- await (0, import_promises36.writeFile)(file, bytes);
28203
- return relative.split(import_node_path46.default.sep).join("/");
28353
+ await (0, import_promises37.mkdir)(import_node_path47.default.dirname(file), { recursive: true });
28354
+ await (0, import_promises37.writeFile)(file, bytes);
28355
+ return relative.split(import_node_path47.default.sep).join("/");
28204
28356
  }
28205
28357
 
28206
28358
  // src/gallery/image-revision.ts
28207
28359
  var import_node_fs44 = require("fs");
28208
- var import_promises37 = require("fs/promises");
28209
- var import_node_path47 = __toESM(require("path"), 1);
28360
+ var import_promises38 = require("fs/promises");
28361
+ var import_node_path48 = __toESM(require("path"), 1);
28210
28362
  var import_zod15 = require("zod");
28211
28363
  var InpaintRevisionRequestSchema = import_zod15.z.object({
28212
28364
  action: import_zod15.z.literal("create-inpaint-revision"),
@@ -28225,15 +28377,15 @@ var InpaintRevisionRequestSchema = import_zod15.z.object({
28225
28377
  overwrite: import_zod15.z.boolean().optional()
28226
28378
  }).strict();
28227
28379
  async function createInpaintRevision(manifestPath, request) {
28228
- const root = import_node_path47.default.dirname(import_node_path47.default.resolve(manifestPath));
28229
- if (import_node_path47.default.extname(request.maskPath).toLowerCase() !== ".png") {
28380
+ const root = import_node_path48.default.dirname(import_node_path48.default.resolve(manifestPath));
28381
+ if (import_node_path48.default.extname(request.maskPath).toLowerCase() !== ".png") {
28230
28382
  throw new ManifestEditError("the mask must be a .png path inside the project");
28231
28383
  }
28232
28384
  const bytes = Buffer.from(request.maskBase64, "base64");
28233
28385
  const metadata = imageMetadata(bytes);
28234
28386
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
28235
- const file = import_node_path47.default.resolve(root, request.maskPath);
28236
- const previous = (0, import_node_fs44.existsSync)(file) ? await (0, import_promises37.readFile)(file) : null;
28387
+ const file = import_node_path48.default.resolve(root, request.maskPath);
28388
+ const previous = (0, import_node_fs44.existsSync)(file) ? await (0, import_promises38.readFile)(file) : null;
28237
28389
  const mask = await saveProjectImage(root, {
28238
28390
  action: "upload-image",
28239
28391
  path: request.maskPath,
@@ -28252,8 +28404,8 @@ async function createInpaintRevision(manifestPath, request) {
28252
28404
  }
28253
28405
  });
28254
28406
  } catch (error) {
28255
- if (previous) await (0, import_promises37.writeFile)(file, previous);
28256
- else await (0, import_promises37.rm)(file, { force: true });
28407
+ if (previous) await (0, import_promises38.writeFile)(file, previous);
28408
+ else await (0, import_promises38.rm)(file, { force: true });
28257
28409
  throw error;
28258
28410
  }
28259
28411
  return mask;
@@ -28261,8 +28413,8 @@ async function createInpaintRevision(manifestPath, request) {
28261
28413
 
28262
28414
  // src/gallery/skeleton.ts
28263
28415
  var import_node_fs45 = require("fs");
28264
- var import_promises38 = require("fs/promises");
28265
- var import_node_path48 = __toESM(require("path"), 1);
28416
+ var import_promises39 = require("fs/promises");
28417
+ var import_node_path49 = __toESM(require("path"), 1);
28266
28418
  var import_zod16 = require("zod");
28267
28419
  var SkeletonEstimateRequestSchema = import_zod16.z.object({
28268
28420
  project: import_zod16.z.string().min(1).optional(),
@@ -28301,10 +28453,10 @@ var SkeletonKeypointsUpdateSchema = import_zod16.z.object({
28301
28453
  set: SkeletonSetSchema
28302
28454
  }).strict();
28303
28455
  async function createSkeletonAnimation(manifestPath, request) {
28304
- const root = import_node_path48.default.dirname(import_node_path48.default.resolve(manifestPath));
28305
- const file = import_node_path48.default.resolve(root, request.keypointsFile);
28306
- const relative = import_node_path48.default.relative(root, file);
28307
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path48.default.isAbsolute(relative)) {
28456
+ const root = import_node_path49.default.dirname(import_node_path49.default.resolve(manifestPath));
28457
+ const file = import_node_path49.default.resolve(root, request.keypointsFile);
28458
+ const relative = import_node_path49.default.relative(root, file);
28459
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path49.default.isAbsolute(relative)) {
28308
28460
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
28309
28461
  }
28310
28462
  const existed = (0, import_node_fs45.existsSync)(file);
@@ -28313,9 +28465,9 @@ async function createSkeletonAnimation(manifestPath, request) {
28313
28465
  if (existed && !request.overwrite) {
28314
28466
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
28315
28467
  }
28316
- if (existed) previous = await (0, import_promises38.readFile)(file);
28317
- await (0, import_promises38.mkdir)(import_node_path48.default.dirname(file), { recursive: true });
28318
- await (0, import_promises38.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
28468
+ if (existed) previous = await (0, import_promises39.readFile)(file);
28469
+ await (0, import_promises39.mkdir)(import_node_path49.default.dirname(file), { recursive: true });
28470
+ await (0, import_promises39.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
28319
28471
  } else if (!existed) {
28320
28472
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
28321
28473
  }
@@ -28330,7 +28482,7 @@ async function createSkeletonAnimation(manifestPath, request) {
28330
28482
  revision: {
28331
28483
  mode: "animate-skeleton",
28332
28484
  from: request.from,
28333
- keypointsFile: relative.split(import_node_path48.default.sep).join("/"),
28485
+ keypointsFile: relative.split(import_node_path49.default.sep).join("/"),
28334
28486
  direction: request.direction,
28335
28487
  description: request.description,
28336
28488
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -28339,8 +28491,8 @@ async function createSkeletonAnimation(manifestPath, request) {
28339
28491
  });
28340
28492
  } catch (error) {
28341
28493
  if (request.set) {
28342
- if (previous) await (0, import_promises38.writeFile)(file, previous);
28343
- else await (0, import_promises38.rm)(file, { force: true });
28494
+ if (previous) await (0, import_promises39.writeFile)(file, previous);
28495
+ else await (0, import_promises39.rm)(file, { force: true });
28344
28496
  }
28345
28497
  throw error;
28346
28498
  }
@@ -28351,19 +28503,19 @@ async function updateSkeletonKeypoints(ctx, request) {
28351
28503
  if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
28352
28504
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
28353
28505
  if (!file) throw new ManifestEditError(`${key3} is not an animate-skeleton revision`);
28354
- const relative = import_node_path48.default.relative(ctx.loaded.root, file);
28355
- if (relative.startsWith("..") || import_node_path48.default.isAbsolute(relative)) {
28506
+ const relative = import_node_path49.default.relative(ctx.loaded.root, file);
28507
+ if (relative.startsWith("..") || import_node_path49.default.isAbsolute(relative)) {
28356
28508
  throw new ManifestEditError(`${key3}'s keypoints file is outside the project; edit it by hand`);
28357
28509
  }
28358
- const current = (0, import_node_fs45.existsSync)(file) ? sha256(await (0, import_promises38.readFile)(file)) : null;
28510
+ const current = (0, import_node_fs45.existsSync)(file) ? sha256(await (0, import_promises39.readFile)(file)) : null;
28359
28511
  if (current !== request.expectedSha256) {
28360
28512
  throw Object.assign(
28361
- new Error(`${relative.split(import_node_path48.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
28513
+ new Error(`${relative.split(import_node_path49.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
28362
28514
  { status: 409 }
28363
28515
  );
28364
28516
  }
28365
- await (0, import_promises38.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
28366
- return relative.split(import_node_path48.default.sep).join("/");
28517
+ await (0, import_promises39.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
28518
+ return relative.split(import_node_path49.default.sep).join("/");
28367
28519
  }
28368
28520
 
28369
28521
  // src/gallery/edit.ts
@@ -28417,7 +28569,7 @@ function createGalleryEditHandler(opts) {
28417
28569
  const history = /* @__PURE__ */ new Map();
28418
28570
  const manifestOf = async (project2) => {
28419
28571
  try {
28420
- return import_node_path49.default.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
28572
+ return import_node_path50.default.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
28421
28573
  } catch {
28422
28574
  return null;
28423
28575
  }
@@ -28427,7 +28579,7 @@ function createGalleryEditHandler(opts) {
28427
28579
  if (undo.success) {
28428
28580
  const manifestPath2 = await manifestOf(undo.data.project);
28429
28581
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
28430
- const current = await (0, import_promises39.readFile)(manifestPath2, "utf8");
28582
+ const current = await (0, import_promises40.readFile)(manifestPath2, "utf8");
28431
28583
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
28432
28584
  const stack = history.get(manifestPath2) ?? [];
28433
28585
  const last = stack[stack.length - 1];
@@ -28437,17 +28589,17 @@ function createGalleryEditHandler(opts) {
28437
28589
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
28438
28590
  }
28439
28591
  const tmp = manifestPath2 + ".pixelkiln-undo";
28440
- await (0, import_promises39.writeFile)(tmp, last.before);
28441
- await (0, import_promises39.rename)(tmp, manifestPath2);
28592
+ await (0, import_promises40.writeFile)(tmp, last.before);
28593
+ await (0, import_promises40.rename)(tmp, manifestPath2);
28442
28594
  stack.pop();
28443
- log(` manifest edit undone in ${import_node_path49.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
28595
+ log(` manifest edit undone in ${import_node_path50.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
28444
28596
  return opts.reload();
28445
28597
  }
28446
28598
  const manifestPath = await manifestOf(body?.project);
28447
- const before = manifestPath ? await (0, import_promises39.readFile)(manifestPath, "utf8").catch(() => null) : null;
28599
+ const before = manifestPath ? await (0, import_promises40.readFile)(manifestPath, "utf8").catch(() => null) : null;
28448
28600
  const build = await apply(body);
28449
28601
  if (manifestPath && before !== null) {
28450
- const after = await (0, import_promises39.readFile)(manifestPath, "utf8").catch(() => null);
28602
+ const after = await (0, import_promises40.readFile)(manifestPath, "utf8").catch(() => null);
28451
28603
  if (after !== null && after !== before) {
28452
28604
  const stack = history.get(manifestPath) ?? [];
28453
28605
  stack.push({ before, afterSha: sha256(after) });
@@ -28526,7 +28678,7 @@ function createEditApplier(opts, log) {
28526
28678
  } catch (error) {
28527
28679
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
28528
28680
  }
28529
- const written = await saveProjectImage(import_node_path49.default.dirname(import_node_path49.default.resolve(manifestPath2)), upload.data);
28681
+ const written = await saveProjectImage(import_node_path50.default.dirname(import_node_path50.default.resolve(manifestPath2)), upload.data);
28530
28682
  log(` image added: ${written}`);
28531
28683
  return opts.reload();
28532
28684
  }
@@ -28593,7 +28745,7 @@ function createEditApplier(opts, log) {
28593
28745
  }
28594
28746
  const result = await applyManifestEdit(manifestPath, parsed.data);
28595
28747
  if (result.changed) {
28596
- const relative = import_node_path49.default.relative(process.cwd(), result.manifestPath);
28748
+ const relative = import_node_path50.default.relative(process.cwd(), result.manifestPath);
28597
28749
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
28598
28750
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
28599
28751
  }
@@ -28621,7 +28773,7 @@ function describeEdit(edit) {
28621
28773
  // src/gallery/snapshot.ts
28622
28774
  var PROJECT_FILE_TYPE = "application/octet-stream";
28623
28775
  function galleryMediaId(absolutePath) {
28624
- return (0, import_node_crypto10.createHash)("sha256").update(import_node_path50.default.resolve(absolutePath)).digest("hex").slice(0, 24);
28776
+ return (0, import_node_crypto10.createHash)("sha256").update(import_node_path51.default.resolve(absolutePath)).digest("hex").slice(0, 24);
28625
28777
  }
28626
28778
  function galleryMediaRoute(id) {
28627
28779
  return `/media/${id}`;
@@ -28645,7 +28797,7 @@ function describeHistory(media, entry, cacheDir) {
28645
28797
  return (entry.history ?? []).map((generation, i) => {
28646
28798
  const outputs = generation.outputs.map((output) => {
28647
28799
  const mediaType = output.mediaType ?? MediaType.PNG;
28648
- const file = import_node_path50.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
28800
+ const file = import_node_path51.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
28649
28801
  let url = null;
28650
28802
  if ((0, import_node_fs46.existsSync)(file)) {
28651
28803
  const id = galleryMediaId(file);
@@ -28679,7 +28831,7 @@ function describeHistory(media, entry, cacheDir) {
28679
28831
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
28680
28832
  async function samePixels(a, b) {
28681
28833
  try {
28682
- const [left, right] = await Promise.all([(0, import_promises40.readFile)(a), (0, import_promises40.readFile)(b)]);
28834
+ const [left, right] = await Promise.all([(0, import_promises41.readFile)(a), (0, import_promises41.readFile)(b)]);
28683
28835
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
28684
28836
  const x = decodePng(left);
28685
28837
  const y = decodePng(right);
@@ -28745,7 +28897,7 @@ function describeCharacter(spec, entry) {
28745
28897
  }
28746
28898
  async function fileInfo(absolutePath) {
28747
28899
  try {
28748
- const info = await (0, import_promises40.stat)(absolutePath);
28900
+ const info = await (0, import_promises41.stat)(absolutePath);
28749
28901
  return info.isFile() ? { bytes: info.size, modifiedAt: info.mtime.toISOString() } : null;
28750
28902
  } catch {
28751
28903
  return null;
@@ -28777,9 +28929,9 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
28777
28929
  async function describeQuality(media, root, inspection) {
28778
28930
  const outputPaths = inspection.outputs ?? [inspection.output];
28779
28931
  const outputs = await Promise.all(
28780
- outputPaths.map((file) => describeOutput(media, root, import_node_path50.default.resolve(root, file)))
28932
+ outputPaths.map((file) => describeOutput(media, root, import_node_path51.default.resolve(root, file)))
28781
28933
  );
28782
- const recordPath = import_node_path50.default.resolve(root, inspection.record);
28934
+ const recordPath = import_node_path51.default.resolve(root, inspection.record);
28783
28935
  const recordExists = (0, import_node_fs46.existsSync)(recordPath);
28784
28936
  let options = null;
28785
28937
  let check = null;
@@ -28799,7 +28951,7 @@ async function describeQuality(media, root, inspection) {
28799
28951
  return {
28800
28952
  state: inspection.state,
28801
28953
  reason: inspection.reason,
28802
- output: portableOutputPath(import_node_path50.default.resolve(root, inspection.output), root),
28954
+ output: portableOutputPath(import_node_path51.default.resolve(root, inspection.output), root),
28803
28955
  record: portableOutputPath(recordPath, root),
28804
28956
  recordExists,
28805
28957
  outputs,
@@ -28837,9 +28989,9 @@ async function buildGallerySnapshot(opts) {
28837
28989
  const media = /* @__PURE__ */ new Map();
28838
28990
  const plan = await buildPlan(specs, lock);
28839
28991
  const items = [];
28840
- const manifestText = await (0, import_promises40.readFile)(loaded.path, "utf8");
28992
+ const manifestText = await (0, import_promises41.readFile)(loaded.path, "utf8");
28841
28993
  const manifestSha256 = sha256(manifestText);
28842
- const cacheDir = import_node_path50.default.resolve(import_node_path50.default.dirname(opts.lockPath), ".pixelkiln", "cache");
28994
+ const cacheDir = import_node_path51.default.resolve(import_node_path51.default.dirname(opts.lockPath), ".pixelkiln", "cache");
28843
28995
  let rawStyles = {};
28844
28996
  try {
28845
28997
  const raw = JSON.parse(manifestText);
@@ -28863,7 +29015,7 @@ async function buildGallerySnapshot(opts) {
28863
29015
  )
28864
29016
  );
28865
29017
  if (spec.source) {
28866
- const editPath = import_node_path50.default.resolve(root, spec.source);
29018
+ const editPath = import_node_path51.default.resolve(root, spec.source);
28867
29019
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
28868
29020
  const editShas = await Promise.all(
28869
29021
  Array.from({ length: memberCount }, async (_, index) => {
@@ -28912,7 +29064,7 @@ async function buildGallerySnapshot(opts) {
28912
29064
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
28913
29065
  }
28914
29066
  } else if (spec.source) {
28915
- outputs = [await describeOutput(media, root, import_node_path50.default.resolve(root, spec.source))];
29067
+ outputs = [await describeOutput(media, root, import_node_path51.default.resolve(root, spec.source))];
28916
29068
  } else if (!entry && (0, import_node_fs46.existsSync)(spec.outFile)) {
28917
29069
  outputs = [await describeOutput(media, root, spec.outFile)];
28918
29070
  } else {
@@ -29117,7 +29269,7 @@ async function buildGallerySnapshot(opts) {
29117
29269
  id: loaded.manifest.name,
29118
29270
  name: loaded.manifest.name,
29119
29271
  manifest: loaded.path,
29120
- lock: import_node_path50.default.resolve(opts.lockPath),
29272
+ lock: import_node_path51.default.resolve(opts.lockPath),
29121
29273
  root,
29122
29274
  provider: loaded.manifest.provider,
29123
29275
  account: null,
@@ -29146,7 +29298,7 @@ async function buildGallerySnapshot(opts) {
29146
29298
  return { snapshot, media };
29147
29299
  }
29148
29300
  async function buildWorkspaceGallerySnapshot(opts) {
29149
- const dir = import_node_path50.default.dirname(import_node_path50.default.resolve(opts.workspacePath));
29301
+ const dir = import_node_path51.default.dirname(import_node_path51.default.resolve(opts.workspacePath));
29150
29302
  const media = /* @__PURE__ */ new Map();
29151
29303
  const projects = [];
29152
29304
  const items = [];
@@ -29191,11 +29343,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
29191
29343
  id: project2.id,
29192
29344
  name: loaded.manifest.name,
29193
29345
  manifest: manifestPath,
29194
- lock: import_node_path50.default.resolve(lockPath),
29346
+ lock: import_node_path51.default.resolve(lockPath),
29195
29347
  root: loaded.root,
29196
29348
  provider: loaded.manifest.provider,
29197
29349
  account: project2.account ?? null,
29198
- manifestSha256: manifestSha256 ?? sha256(await (0, import_promises40.readFile)(manifestPath, "utf8")),
29350
+ manifestSha256: manifestSha256 ?? sha256(await (0, import_promises41.readFile)(manifestPath, "utf8")),
29199
29351
  historyLimit: historyLimit(loaded.manifest),
29200
29352
  entries: Object.keys(lock.entries).length,
29201
29353
  items: projectItems.length,
@@ -29207,8 +29359,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
29207
29359
  id: project2.id,
29208
29360
  name: project2.id,
29209
29361
  manifest: manifestPath,
29210
- lock: import_node_path50.default.resolve(lockPath),
29211
- root: import_node_path50.default.dirname(manifestPath),
29362
+ lock: import_node_path51.default.resolve(lockPath),
29363
+ root: import_node_path51.default.dirname(manifestPath),
29212
29364
  provider: project2.provider,
29213
29365
  account: project2.account ?? null,
29214
29366
  manifestSha256: null,
@@ -29235,7 +29387,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
29235
29387
  version: 1,
29236
29388
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
29237
29389
  project: null,
29238
- workspace: { path: import_node_path50.default.resolve(opts.workspacePath), dir, projects },
29390
+ workspace: { path: import_node_path51.default.resolve(opts.workspacePath), dir, projects },
29239
29391
  filter,
29240
29392
  totals: {
29241
29393
  entries: projects.reduce((sum, project2) => sum + project2.entries, 0),
@@ -29439,9 +29591,9 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
29439
29591
  // src/editor/install.ts
29440
29592
  var import_node_crypto11 = require("crypto");
29441
29593
  var import_node_fs48 = require("fs");
29442
- var import_promises41 = require("fs/promises");
29594
+ var import_promises42 = require("fs/promises");
29443
29595
  var import_node_os4 = __toESM(require("os"), 1);
29444
- var import_node_path51 = __toESM(require("path"), 1);
29596
+ var import_node_path52 = __toESM(require("path"), 1);
29445
29597
  var EditorInstallError = class extends Error {
29446
29598
  constructor(message6, file) {
29447
29599
  super(message6);
@@ -29452,15 +29604,15 @@ var EditorInstallError = class extends Error {
29452
29604
  };
29453
29605
  function editorToolsRoot() {
29454
29606
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
29455
- if (override) return import_node_path51.default.resolve(override);
29456
- if (process.platform === "darwin") return import_node_path51.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
29607
+ if (override) return import_node_path52.default.resolve(override);
29608
+ if (process.platform === "darwin") return import_node_path52.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
29457
29609
  if (process.platform === "win32") {
29458
- return import_node_path51.default.join(process.env.LOCALAPPDATA ?? import_node_path51.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
29610
+ return import_node_path52.default.join(process.env.LOCALAPPDATA ?? import_node_path52.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
29459
29611
  }
29460
- return import_node_path51.default.join(process.env.XDG_CACHE_HOME ?? import_node_path51.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
29612
+ return import_node_path52.default.join(process.env.XDG_CACHE_HOME ?? import_node_path52.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
29461
29613
  }
29462
29614
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
29463
- return import_node_path51.default.join(root, "pixelorama", pin.release ?? "unpublished");
29615
+ return import_node_path52.default.join(root, "pixelorama", pin.release ?? "unpublished");
29464
29616
  }
29465
29617
  function editorBaseUrl(pin = EDITOR_PIN) {
29466
29618
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -29470,7 +29622,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
29470
29622
  }
29471
29623
  async function sha256Of(file) {
29472
29624
  try {
29473
- return (0, import_node_crypto11.createHash)("sha256").update(await (0, import_promises41.readFile)(file)).digest("hex");
29625
+ return (0, import_node_crypto11.createHash)("sha256").update(await (0, import_promises42.readFile)(file)).digest("hex");
29474
29626
  } catch {
29475
29627
  return null;
29476
29628
  }
@@ -29483,8 +29635,8 @@ async function editorStatus(opts = {}) {
29483
29635
  let totalBytes = 0;
29484
29636
  for (const [name, expected] of Object.entries(pin.files)) {
29485
29637
  totalBytes += expected.bytes;
29486
- const file = import_node_path51.default.join(dir, name);
29487
- const info = (0, import_node_fs48.existsSync)(file) ? await (0, import_promises41.stat)(file).catch(() => null) : null;
29638
+ const file = import_node_path52.default.join(dir, name);
29639
+ const info = (0, import_node_fs48.existsSync)(file) ? await (0, import_promises42.stat)(file).catch(() => null) : null;
29488
29640
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
29489
29641
  installedBytes += expected.bytes;
29490
29642
  } else {
@@ -29513,7 +29665,7 @@ async function installEditor(opts = {}) {
29513
29665
  );
29514
29666
  }
29515
29667
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
29516
- await (0, import_promises41.mkdir)(dir, { recursive: true });
29668
+ await (0, import_promises42.mkdir)(dir, { recursive: true });
29517
29669
  const downloaded = [];
29518
29670
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
29519
29671
  let fetchedBytes = before.installedBytes;
@@ -29541,13 +29693,13 @@ async function installEditor(opts = {}) {
29541
29693
  if (digest2 !== expected.sha256) {
29542
29694
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
29543
29695
  }
29544
- const final = import_node_path51.default.join(dir, name);
29696
+ const final = import_node_path52.default.join(dir, name);
29545
29697
  const tmp = `${final}.${process.pid}.part`;
29546
29698
  try {
29547
- await (0, import_promises41.writeFile)(tmp, bytes);
29548
- await (0, import_promises41.rename)(tmp, final);
29699
+ await (0, import_promises42.writeFile)(tmp, bytes);
29700
+ await (0, import_promises42.rename)(tmp, final);
29549
29701
  } finally {
29550
- await (0, import_promises41.rm)(tmp, { force: true });
29702
+ await (0, import_promises42.rm)(tmp, { force: true });
29551
29703
  }
29552
29704
  fetchedBytes += bytes.length;
29553
29705
  downloaded.push(name);
@@ -29587,12 +29739,12 @@ var EDITOR_CONTENT_TYPES = {
29587
29739
  ".json": "application/json; charset=utf-8"
29588
29740
  };
29589
29741
  function editorContentType(name) {
29590
- return EDITOR_CONTENT_TYPES[import_node_path51.default.extname(name).toLowerCase()] ?? null;
29742
+ return EDITOR_CONTENT_TYPES[import_node_path52.default.extname(name).toLowerCase()] ?? null;
29591
29743
  }
29592
29744
 
29593
29745
  // src/gallery/editor.ts
29594
- var import_promises42 = require("fs/promises");
29595
- var import_node_path52 = __toESM(require("path"), 1);
29746
+ var import_promises43 = require("fs/promises");
29747
+ var import_node_path53 = __toESM(require("path"), 1);
29596
29748
  function editorRoute(release, name = "index.html") {
29597
29749
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
29598
29750
  }
@@ -29665,7 +29817,7 @@ function createGalleryEditorHandlers(opts = {}) {
29665
29817
  if (!status.installed) return null;
29666
29818
  let bytes;
29667
29819
  try {
29668
- bytes = await (0, import_promises42.readFile)(import_node_path52.default.join(dir, name));
29820
+ bytes = await (0, import_promises43.readFile)(import_node_path53.default.join(dir, name));
29669
29821
  } catch {
29670
29822
  verified = null;
29671
29823
  return null;
@@ -29682,7 +29834,7 @@ function createGalleryEditorHandlers(opts = {}) {
29682
29834
  // src/gallery/server.ts
29683
29835
  var import_node_crypto12 = require("crypto");
29684
29836
  var import_node_http2 = require("http");
29685
- var import_promises43 = require("fs/promises");
29837
+ var import_promises44 = require("fs/promises");
29686
29838
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
29687
29839
  var EDITOR_CSP = [
29688
29840
  "default-src 'self'",
@@ -29863,7 +30015,7 @@ async function serveGallery(opts) {
29863
30015
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
29864
30016
  if (!asset) return fail(404, "no such review asset");
29865
30017
  try {
29866
- const bytes = await (0, import_promises43.readFile)(asset.path);
30018
+ const bytes = await (0, import_promises44.readFile)(asset.path);
29867
30019
  res.writeHead(200, {
29868
30020
  "Content-Type": asset.contentType,
29869
30021
  "Cache-Control": "no-store",
@@ -29946,7 +30098,7 @@ async function serveGallery(opts) {
29946
30098
  if (!asset) return fail(404, "no such gallery media");
29947
30099
  let bytes;
29948
30100
  try {
29949
- bytes = await (0, import_promises43.readFile)(asset.path);
30101
+ bytes = await (0, import_promises44.readFile)(asset.path);
29950
30102
  } catch {
29951
30103
  return fail(404, "gallery media is no longer on disk; refresh the page");
29952
30104
  }
@@ -30357,9 +30509,9 @@ function createGenerateHandlers(opts) {
30357
30509
  }
30358
30510
 
30359
30511
  // src/pipeline/salvage.ts
30360
- var import_promises44 = require("fs/promises");
30512
+ var import_promises45 = require("fs/promises");
30361
30513
  var import_node_fs49 = require("fs");
30362
- var import_node_path53 = __toESM(require("path"), 1);
30514
+ var import_node_path54 = __toESM(require("path"), 1);
30363
30515
  function providerClaimId(provider, objectId) {
30364
30516
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
30365
30517
  }
@@ -30369,7 +30521,7 @@ async function loadClaims(lockPaths, opts = {}) {
30369
30521
  if (!(0, import_node_fs49.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
30370
30522
  let parsed;
30371
30523
  try {
30372
- parsed = parseLock(JSON.parse(await (0, import_promises44.readFile)(p, "utf8")));
30524
+ parsed = parseLock(JSON.parse(await (0, import_promises45.readFile)(p, "utf8")));
30373
30525
  } catch {
30374
30526
  throw new Error(`Claim lockfile is malformed: ${p}`);
30375
30527
  }
@@ -30473,20 +30625,20 @@ function matchOrphanStyle(prompt, manifest) {
30473
30625
  return matchStyleByPattern(prompt, manifest);
30474
30626
  }
30475
30627
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
30476
- const own = import_node_path53.default.resolve(ownManifestPath);
30628
+ const own = import_node_path54.default.resolve(ownManifestPath);
30477
30629
  const siblingManifestPaths = [
30478
30630
  .../* @__PURE__ */ new Set([
30479
30631
  ...workspaceManifestPaths,
30480
- ...claimPaths.map((c) => import_node_path53.default.join(import_node_path53.default.dirname(import_node_path53.default.resolve(c)), "pixelkiln.manifest.json"))
30632
+ ...claimPaths.map((c) => import_node_path54.default.join(import_node_path54.default.dirname(import_node_path54.default.resolve(c)), "pixelkiln.manifest.json"))
30481
30633
  ])
30482
30634
  ];
30483
30635
  const siblings = [];
30484
30636
  for (const siblingManifestPath of siblingManifestPaths) {
30485
- if (import_node_path53.default.resolve(siblingManifestPath) === own) continue;
30637
+ if (import_node_path54.default.resolve(siblingManifestPath) === own) continue;
30486
30638
  if (!(0, import_node_fs49.existsSync)(siblingManifestPath)) continue;
30487
30639
  try {
30488
30640
  const { manifest } = await loadManifest(siblingManifestPath);
30489
- siblings.push({ label: import_node_path53.default.basename(import_node_path53.default.dirname(siblingManifestPath)), manifest });
30641
+ siblings.push({ label: import_node_path54.default.basename(import_node_path54.default.dirname(siblingManifestPath)), manifest });
30490
30642
  } catch {
30491
30643
  }
30492
30644
  }
@@ -30606,8 +30758,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
30606
30758
  }
30607
30759
 
30608
30760
  // src/pick/salvage-server.ts
30609
- var import_promises45 = require("fs/promises");
30610
- var import_node_path54 = __toESM(require("path"), 1);
30761
+ var import_promises46 = require("fs/promises");
30762
+ var import_node_path55 = __toESM(require("path"), 1);
30611
30763
 
30612
30764
  // src/pick/salvage-sheet.ts
30613
30765
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -30773,7 +30925,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30773
30925
  });
30774
30926
  const html = renderSalvageSheet(orphans, {
30775
30927
  styleId: ctx.styleId,
30776
- importDir: import_node_path54.default.relative(process.cwd(), ctx.importDir) || "."
30928
+ importDir: import_node_path55.default.relative(process.cwd(), ctx.importDir) || "."
30777
30929
  });
30778
30930
  const byId = new Map(orphans.map((o) => [o.id, o]));
30779
30931
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -30829,10 +30981,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30829
30981
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
30830
30982
  decodePng(buf);
30831
30983
  const assetId = idFromPrompt(orphan.prompt, taken);
30832
- const rel = import_node_path54.default.join("_salvaged", `${assetId}.png`);
30833
- const outFile = import_node_path54.default.resolve(ctx.importDir, rel);
30834
- await (0, import_promises45.mkdir)(import_node_path54.default.dirname(outFile), { recursive: true });
30835
- await (0, import_promises45.writeFile)(outFile, buf);
30984
+ const rel = import_node_path55.default.join("_salvaged", `${assetId}.png`);
30985
+ const outFile = import_node_path55.default.resolve(ctx.importDir, rel);
30986
+ await (0, import_promises46.mkdir)(import_node_path55.default.dirname(outFile), { recursive: true });
30987
+ await (0, import_promises46.writeFile)(outFile, buf);
30836
30988
  ctx.manifest.assets[assetId] = {
30837
30989
  prompt: orphan.prompt,
30838
30990
  promptByStyle: {},
@@ -30864,7 +31016,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30864
31016
  sourceUrl: durableSource,
30865
31017
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
30866
31018
  outputs: [{
30867
- path: portableOutputPath(outFile, import_node_path54.default.dirname(ctx.manifestPath)),
31019
+ path: portableOutputPath(outFile, import_node_path55.default.dirname(ctx.manifestPath)),
30868
31020
  sha256: sha256(buf)
30869
31021
  }],
30870
31022
  submittedAt: orphan.createdAt,
@@ -30888,9 +31040,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30888
31040
  }
30889
31041
  }
30890
31042
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
30891
- const raw = JSON.parse(await (0, import_promises45.readFile)(ctx.manifestPath, "utf8"));
31043
+ const raw = JSON.parse(await (0, import_promises46.readFile)(ctx.manifestPath, "utf8"));
30892
31044
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
30893
- await (0, import_promises45.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
31045
+ await (0, import_promises46.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
30894
31046
  await saveLock(ctx.lockPath, ctx.lock);
30895
31047
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
30896
31048
  return result;