pixelkiln 0.129.0 → 0.131.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
@@ -1928,7 +1928,7 @@ var AssetDeriveSchema = import_zod.z.object({
1928
1928
  /** 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. */
1929
1929
  tolerance: import_zod.z.number().min(0).max(442).optional()
1930
1930
  }).strict().superRefine((derive, context) => {
1931
- const issue = (message6, path53) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path53] });
1931
+ const issue = (message6, path54) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path54] });
1932
1932
  if (Boolean(derive.from) === Boolean(derive.file)) {
1933
1933
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1934
1934
  }
@@ -3355,9 +3355,9 @@ var PixelLabClient = class {
3355
3355
  apiKey;
3356
3356
  http;
3357
3357
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
3358
- async request(path53, init) {
3358
+ async request(path54, init) {
3359
3359
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
3360
- const res = await this.http(`${BASE}${path53}`, {
3360
+ const res = await this.http(`${BASE}${path54}`, {
3361
3361
  ...init,
3362
3362
  headers: {
3363
3363
  Authorization: auth,
@@ -3368,13 +3368,13 @@ var PixelLabClient = class {
3368
3368
  const text = await res.text();
3369
3369
  if (!res.ok) {
3370
3370
  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' : "";
3371
- throw new PixelLabError(`${init?.method ?? "GET"} ${path53} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3371
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path54} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3372
3372
  }
3373
3373
  if (!text) return {};
3374
3374
  try {
3375
3375
  return JSON.parse(text);
3376
3376
  } catch {
3377
- throw new Error(`${init?.method ?? "GET"} ${path53} returned invalid JSON`);
3377
+ throw new Error(`${init?.method ?? "GET"} ${path54} returned invalid JSON`);
3378
3378
  }
3379
3379
  }
3380
3380
  async balance() {
@@ -3921,10 +3921,10 @@ var PixelLabClient = class {
3921
3921
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
3922
3922
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
3923
3923
  const south = args.reference?.south;
3924
- let path53;
3924
+ let path54;
3925
3925
  let body;
3926
3926
  if (args.mode === "v3") {
3927
- path53 = "/create-character-v3";
3927
+ path54 = "/create-character-v3";
3928
3928
  body = {
3929
3929
  description: args.description,
3930
3930
  image_size: imageSize,
@@ -3938,7 +3938,7 @@ var PixelLabClient = class {
3938
3938
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
3939
3939
  };
3940
3940
  } else if (args.mode === "pro-flash") {
3941
- path53 = "/create-character-pro-flash";
3941
+ path54 = "/create-character-pro-flash";
3942
3942
  const traits = args.styleTraits;
3943
3943
  body = {
3944
3944
  description: args.description,
@@ -3962,7 +3962,7 @@ var PixelLabClient = class {
3962
3962
  } : {}
3963
3963
  };
3964
3964
  } else if (args.mode === "pro") {
3965
- path53 = "/create-character-pro";
3965
+ path54 = "/create-character-pro";
3966
3966
  body = {
3967
3967
  description: args.description,
3968
3968
  image_size: imageSize,
@@ -3976,7 +3976,7 @@ var PixelLabClient = class {
3976
3976
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
3977
3977
  };
3978
3978
  } else {
3979
- path53 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3979
+ path54 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3980
3980
  body = {
3981
3981
  description: args.description,
3982
3982
  image_size: imageSize,
@@ -3994,8 +3994,8 @@ var PixelLabClient = class {
3994
3994
  };
3995
3995
  }
3996
3996
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
3997
- const raw = await this.request(path53, { method: "POST", body: JSON.stringify(body) });
3998
- return validateResponse(CharacterSubmitSchema, raw, path53.slice(1));
3997
+ const raw = await this.request(path54, { method: "POST", body: JSON.stringify(body) });
3998
+ return validateResponse(CharacterSubmitSchema, raw, path54.slice(1));
3999
3999
  }
4000
4000
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
4001
4001
  async createCharacterState(args) {
@@ -5669,10 +5669,10 @@ function normalizeHex(value) {
5669
5669
  function sha256(data) {
5670
5670
  return (0, import_node_crypto.createHash)("sha256").update(data).digest("hex");
5671
5671
  }
5672
- async function sha256File(path53) {
5672
+ async function sha256File(path54) {
5673
5673
  return new Promise((resolve, reject) => {
5674
5674
  const hash = (0, import_node_crypto.createHash)("sha256");
5675
- const stream = (0, import_node_fs.createReadStream)(path53);
5675
+ const stream = (0, import_node_fs.createReadStream)(path54);
5676
5676
  stream.on("data", (chunk2) => hash.update(chunk2));
5677
5677
  stream.on("error", reject);
5678
5678
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -11499,9 +11499,9 @@ var RetroDiffusionClient = class {
11499
11499
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
11500
11500
  return Buffer.from(await response.arrayBuffer());
11501
11501
  }
11502
- async call(path53, init = {}) {
11502
+ async call(path54, init = {}) {
11503
11503
  if (!this.token) throw new Error("RD_API_KEY is not set");
11504
- const response = await this.request(`${this.baseUrl}${path53}`, {
11504
+ const response = await this.request(`${this.baseUrl}${path54}`, {
11505
11505
  ...init,
11506
11506
  headers: {
11507
11507
  "Content-Type": "application/json",
@@ -19710,10 +19710,10 @@ function isSha256Hash(value) {
19710
19710
  function parseCache(value) {
19711
19711
  return HashCacheSchema.parse(value);
19712
19712
  }
19713
- async function loadCache(path53) {
19714
- if (!(0, import_node_fs26.existsSync)(path53)) return { version: 1, hashes: {} };
19713
+ async function loadCache(path54) {
19714
+ if (!(0, import_node_fs26.existsSync)(path54)) return { version: 1, hashes: {} };
19715
19715
  try {
19716
- const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises20.readFile)(path53, "utf8")));
19716
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises20.readFile)(path54, "utf8")));
19717
19717
  if (!parsed.success) return { version: 1, hashes: {} };
19718
19718
  return {
19719
19719
  version: 1,
@@ -19725,18 +19725,18 @@ async function loadCache(path53) {
19725
19725
  return { version: 1, hashes: {} };
19726
19726
  }
19727
19727
  }
19728
- async function saveCache(path53, cache) {
19728
+ async function saveCache(path54, cache) {
19729
19729
  const sorted = {};
19730
19730
  for (const key3 of Object.keys(cache.hashes).sort()) {
19731
19731
  const hash = cache.hashes[key3];
19732
19732
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
19733
19733
  sorted[key3] = hash;
19734
19734
  }
19735
- await (0, import_promises20.mkdir)(import_node_path29.default.dirname(import_node_path29.default.resolve(path53)), { recursive: true });
19736
- const tmp = `${path53}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19735
+ await (0, import_promises20.mkdir)(import_node_path29.default.dirname(import_node_path29.default.resolve(path54)), { recursive: true });
19736
+ const tmp = `${path54}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19737
19737
  try {
19738
19738
  await (0, import_promises20.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
19739
- await (0, import_promises20.rename)(tmp, path53);
19739
+ await (0, import_promises20.rename)(tmp, path54);
19740
19740
  } finally {
19741
19741
  await (0, import_promises20.rm)(tmp, { force: true });
19742
19742
  }
@@ -19959,7 +19959,8 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19959
19959
  if (!source.url) {
19960
19960
  throw new Error(`no source URL or cached bytes remain for ${source.role ?? "asset"}`);
19961
19961
  }
19962
- raw = await provider.download(source.url);
19962
+ const localFile = source.url.startsWith("file://") ? source.url.slice("file://".length) : null;
19963
+ raw = localFile && (0, import_node_fs27.existsSync)(localFile) ? await (0, import_promises21.readFile)(localFile) : await provider.download(source.url);
19963
19964
  }
19964
19965
  let mediaType;
19965
19966
  const bytes = final ?? raw;
@@ -22276,6 +22277,193 @@ function ownedReferenceImageId(spec, lock, providerId) {
22276
22277
  return void 0;
22277
22278
  }
22278
22279
 
22280
+ // src/pick/candidates.ts
22281
+ var import_node_fs31 = require("fs");
22282
+ var import_promises23 = require("fs/promises");
22283
+ var import_node_path34 = __toESM(require("path"), 1);
22284
+ var import_zod8 = require("zod");
22285
+ var REVIEW_STATE_VERSION = 1;
22286
+ var CandidateSchema = import_zod8.z.object({
22287
+ index: import_zod8.z.number().int().nonnegative(),
22288
+ /** Frame role for a frame set (`frame-00`, ...); absent for candidates. */
22289
+ role: import_zod8.z.string().optional(),
22290
+ /**
22291
+ * Where the provider served the bytes. Null when the URL carried a
22292
+ * credential or signature, which never settles on disk.
22293
+ */
22294
+ sourceUrl: import_zod8.z.string().nullable(),
22295
+ /** sha256 of the cached bytes; null until the download succeeds. */
22296
+ sha256: import_zod8.z.string().nullable(),
22297
+ mediaType: import_zod8.z.string().nullable(),
22298
+ cachedAt: import_zod8.z.string().nullable()
22299
+ });
22300
+ var ReviewAssetSchema = import_zod8.z.object({
22301
+ provider: import_zod8.z.string(),
22302
+ /** The provider job the candidates came from (the lock's `reviewObjectId`). */
22303
+ jobId: import_zod8.z.string(),
22304
+ generator: import_zod8.z.string().optional(),
22305
+ mode: import_zod8.z.enum(["candidates", "frame-set"]),
22306
+ /** Frame-set playback rate. */
22307
+ fps: import_zod8.z.number().optional(),
22308
+ /** Frame-set object id the provider reported. */
22309
+ objectId: import_zod8.z.string().optional(),
22310
+ candidates: import_zod8.z.array(CandidateSchema),
22311
+ /** "pending" while waiting on a choice, "applied" once one was committed. */
22312
+ status: import_zod8.z.enum(["pending", "applied"]),
22313
+ /** The chosen candidate index, or null while nothing is chosen. */
22314
+ chosen: import_zod8.z.number().int().nonnegative().nullable(),
22315
+ updatedAt: import_zod8.z.string()
22316
+ });
22317
+ var ReviewStateSchema = import_zod8.z.object({
22318
+ version: import_zod8.z.literal(REVIEW_STATE_VERSION),
22319
+ /** Keyed by lock key (`<style>/<asset>`). */
22320
+ assets: import_zod8.z.record(ReviewAssetSchema)
22321
+ });
22322
+ function candidateCacheDirFor(lockPath) {
22323
+ return import_node_path34.default.resolve(import_node_path34.default.dirname(lockPath), ".pixelkiln", "cache");
22324
+ }
22325
+ function reviewStatePathFor(lockPath) {
22326
+ const base = import_node_path34.default.basename(lockPath);
22327
+ const name = base === "pixelkiln.lock.json" ? "review-state.json" : `${base.replace(/\.json$/, "")}.review-state.json`;
22328
+ return import_node_path34.default.resolve(import_node_path34.default.dirname(lockPath), ".pixelkiln", name);
22329
+ }
22330
+ async function loadReviewState(file) {
22331
+ if (!(0, import_node_fs31.existsSync)(file)) return { version: REVIEW_STATE_VERSION, assets: {} };
22332
+ try {
22333
+ const parsed = ReviewStateSchema.safeParse(JSON.parse(await (0, import_promises23.readFile)(file, "utf8")));
22334
+ if (parsed.success) return parsed.data;
22335
+ } catch {
22336
+ }
22337
+ return { version: REVIEW_STATE_VERSION, assets: {} };
22338
+ }
22339
+ async function saveReviewState(file, state) {
22340
+ await (0, import_promises23.mkdir)(import_node_path34.default.dirname(file), { recursive: true });
22341
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
22342
+ try {
22343
+ await (0, import_promises23.writeFile)(tmp, JSON.stringify(state, null, 2) + "\n");
22344
+ await (0, import_promises23.rename)(tmp, file);
22345
+ } finally {
22346
+ await (0, import_promises23.rm)(tmp, { force: true });
22347
+ }
22348
+ }
22349
+ async function updateReviewAsset(file, key3, change) {
22350
+ const state = await loadReviewState(file);
22351
+ const asset = state.assets[key3];
22352
+ if (!asset) return null;
22353
+ const next = { ...change(asset), updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
22354
+ state.assets[key3] = next;
22355
+ await saveReviewState(file, state);
22356
+ return next;
22357
+ }
22358
+ function cachedCandidatePath(cacheDir, candidate) {
22359
+ if (!candidate.sha256 || !candidate.mediaType) return null;
22360
+ const file = import_node_path34.default.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
22361
+ return (0, import_node_fs31.existsSync)(file) ? file : null;
22362
+ }
22363
+ function fullyCached(cacheDir, asset) {
22364
+ return asset.candidates.length > 0 && asset.candidates.every((c) => cachedCandidatePath(cacheDir, c));
22365
+ }
22366
+ function storableUrl(url) {
22367
+ return isSensitiveSourceUrl(url) ? null : url;
22368
+ }
22369
+ async function downloadCandidate(provider, cacheDir, url, label) {
22370
+ let bytes;
22371
+ try {
22372
+ bytes = await provider.download(url);
22373
+ } catch (err) {
22374
+ const message6 = err instanceof Error ? err.message : String(err);
22375
+ throw new Error(`${label} could not be downloaded (${message6}); the provider has likely expired it`);
22376
+ }
22377
+ const mediaType = detectMediaType(bytes) ?? MediaType.PNG;
22378
+ const hash = sha256(bytes);
22379
+ await cacheMedia(cacheDir, bytes, mediaType, hash);
22380
+ return { sha256: hash, mediaType };
22381
+ }
22382
+ async function cacheReviewCandidates(provider, key3, jobId, job, opts) {
22383
+ const state = await loadReviewState(opts.statePath);
22384
+ const previous = state.assets[key3]?.jobId === jobId ? state.assets[key3] : void 0;
22385
+ const sources = job.status === "review" ? job.candidateUrls.map((url) => ({ url, role: void 0 })) : job.sources.map((source) => ({ url: source.url, role: source.role }));
22386
+ const failed = [];
22387
+ const candidates = [];
22388
+ for (const [index, source] of sources.entries()) {
22389
+ const known = [previous, ...Object.values(state.assets).filter((a) => a.jobId === jobId && a.provider === provider.id)].map((asset2) => asset2?.candidates[index]).find((candidate) => candidate && candidate.sourceUrl === storableUrl(source.url) && cachedCandidatePath(opts.cacheDir, candidate));
22390
+ if (known) {
22391
+ candidates.push(known);
22392
+ continue;
22393
+ }
22394
+ try {
22395
+ const cached2 = await downloadCandidate(provider, opts.cacheDir, source.url, `${key3} candidate ${index + 1}`);
22396
+ candidates.push({
22397
+ index,
22398
+ ...source.role ? { role: source.role } : {},
22399
+ sourceUrl: storableUrl(source.url),
22400
+ ...cached2,
22401
+ cachedAt: (/* @__PURE__ */ new Date()).toISOString()
22402
+ });
22403
+ } catch (err) {
22404
+ failed.push(err instanceof Error ? err.message : String(err));
22405
+ candidates.push({
22406
+ index,
22407
+ ...source.role ? { role: source.role } : {},
22408
+ sourceUrl: storableUrl(source.url),
22409
+ sha256: null,
22410
+ mediaType: null,
22411
+ cachedAt: null
22412
+ });
22413
+ }
22414
+ }
22415
+ const asset = {
22416
+ provider: provider.id,
22417
+ jobId,
22418
+ ...opts.generator ? { generator: opts.generator } : {},
22419
+ mode: job.status === "review" ? "candidates" : "frame-set",
22420
+ ...job.status === "review-set" ? { fps: job.fps, objectId: job.objectId } : {},
22421
+ candidates,
22422
+ status: "pending",
22423
+ chosen: previous?.chosen ?? null,
22424
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
22425
+ };
22426
+ const latest = await loadReviewState(opts.statePath);
22427
+ latest.assets[key3] = asset;
22428
+ await saveReviewState(opts.statePath, latest);
22429
+ return { asset, failed };
22430
+ }
22431
+ async function ensureCandidatesCached(provider, key3, opts) {
22432
+ const state = await loadReviewState(opts.statePath);
22433
+ const asset = state.assets[key3];
22434
+ if (!asset) throw new Error(`${key3} has no recorded candidates to recover`);
22435
+ const missing = [];
22436
+ const candidates = [];
22437
+ for (const candidate of asset.candidates) {
22438
+ if (cachedCandidatePath(opts.cacheDir, candidate)) {
22439
+ candidates.push(candidate);
22440
+ continue;
22441
+ }
22442
+ if (!candidate.sourceUrl) {
22443
+ missing.push(`candidate ${candidate.index + 1} has no stored source URL`);
22444
+ candidates.push(candidate);
22445
+ continue;
22446
+ }
22447
+ try {
22448
+ const cached2 = await downloadCandidate(provider, opts.cacheDir, candidate.sourceUrl, `candidate ${candidate.index + 1}`);
22449
+ candidates.push({ ...candidate, ...cached2, cachedAt: (/* @__PURE__ */ new Date()).toISOString() });
22450
+ } catch (err) {
22451
+ missing.push(err instanceof Error ? err.message : String(err));
22452
+ candidates.push(candidate);
22453
+ }
22454
+ }
22455
+ const next = { ...asset, candidates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
22456
+ const latest = await loadReviewState(opts.statePath);
22457
+ latest.assets[key3] = next;
22458
+ await saveReviewState(opts.statePath, latest);
22459
+ if (missing.length) {
22460
+ throw new Error(
22461
+ `${key3}: job ${asset.jobId} expired on the provider before every candidate was cached (${missing.join("; ")}); re-run gen for this asset`
22462
+ );
22463
+ }
22464
+ return next;
22465
+ }
22466
+
22279
22467
  // src/pipeline/poll.ts
22280
22468
  var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
22281
22469
  async function poll(provider, lock, lockPath, opts = {}) {
@@ -22325,6 +22513,16 @@ async function poll(provider, lock, lockPath, opts = {}) {
22325
22513
  billed: state.billed ?? entry.billed
22326
22514
  });
22327
22515
  result.review++;
22516
+ try {
22517
+ const { failed } = await cacheReviewCandidates(provider, key3, entry.jobId, state, {
22518
+ cacheDir: candidateCacheDirFor(lockPath),
22519
+ statePath: reviewStatePathFor(lockPath),
22520
+ generator: entry.generator
22521
+ });
22522
+ for (const message6 of failed) log(` could not cache ${message6}`);
22523
+ } catch (err) {
22524
+ log(` could not cache candidates for ${key3}: ${err instanceof Error ? err.message : String(err)}`);
22525
+ }
22328
22526
  log(
22329
22527
  state.status === "review-set" ? ` review ${key3} (${state.frameUrls.length} ordered frames)` : ` review ${key3} (${state.candidateUrls.length} candidates)`
22330
22528
  );
@@ -22364,34 +22562,34 @@ async function poll(provider, lock, lockPath, opts = {}) {
22364
22562
  }
22365
22563
 
22366
22564
  // src/pipeline/doctor.ts
22367
- var import_node_fs32 = require("fs");
22368
- var import_promises23 = require("fs/promises");
22369
- var import_node_path35 = __toESM(require("path"), 1);
22565
+ var import_node_fs33 = require("fs");
22566
+ var import_promises24 = require("fs/promises");
22567
+ var import_node_path36 = __toESM(require("path"), 1);
22370
22568
 
22371
22569
  // src/pipeline/install-check.ts
22372
- var import_node_fs31 = require("fs");
22373
- var import_node_path34 = __toESM(require("path"), 1);
22570
+ var import_node_fs32 = require("fs");
22571
+ var import_node_path35 = __toESM(require("path"), 1);
22374
22572
  function readJson(file) {
22375
22573
  try {
22376
- return JSON.parse((0, import_node_fs31.readFileSync)(file, "utf8"));
22574
+ return JSON.parse((0, import_node_fs32.readFileSync)(file, "utf8"));
22377
22575
  } catch {
22378
22576
  return null;
22379
22577
  }
22380
22578
  }
22381
22579
  function readInstallFacts(manifestDir, running) {
22382
- let dir = import_node_path34.default.resolve(manifestDir);
22580
+ let dir = import_node_path35.default.resolve(manifestDir);
22383
22581
  for (let depth = 0; depth < 4; depth++) {
22384
- const pkg = readJson(import_node_path34.default.join(dir, "package.json"));
22582
+ const pkg = readJson(import_node_path35.default.join(dir, "package.json"));
22385
22583
  if (pkg) {
22386
22584
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
22387
22585
  if (pinned) {
22388
- const installedPkg = readJson(import_node_path34.default.join(dir, "node_modules", "pixelkiln", "package.json"));
22586
+ const installedPkg = readJson(import_node_path35.default.join(dir, "node_modules", "pixelkiln", "package.json"));
22389
22587
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
22390
22588
  return { pinned, installed, running };
22391
22589
  }
22392
22590
  }
22393
- const parent = import_node_path34.default.dirname(dir);
22394
- if (parent === dir || !(0, import_node_fs31.existsSync)(parent)) break;
22591
+ const parent = import_node_path35.default.dirname(dir);
22592
+ if (parent === dir || !(0, import_node_fs32.existsSync)(parent)) break;
22395
22593
  dir = parent;
22396
22594
  }
22397
22595
  return null;
@@ -22454,18 +22652,18 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22454
22652
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
22455
22653
  );
22456
22654
  }
22457
- const facts = readInstallFacts(import_node_path35.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
22655
+ const facts = readInstallFacts(import_node_path36.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
22458
22656
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
22459
22657
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
22460
22658
  const dirs = [...new Set(specs.flatMap((spec) => [
22461
- import_node_path35.default.dirname(spec.outFile),
22462
- ...spec.quality ? [import_node_path35.default.dirname(spec.quality.outFile)] : []
22659
+ import_node_path36.default.dirname(spec.outFile),
22660
+ ...spec.quality ? [import_node_path36.default.dirname(spec.quality.outFile)] : []
22463
22661
  ]))];
22464
22662
  const unwritable = [];
22465
22663
  for (const dir of dirs) {
22466
22664
  const ancestor = await nearestExistingDirectory(dir);
22467
22665
  try {
22468
- await (0, import_promises23.access)(ancestor, import_node_fs32.constants.W_OK);
22666
+ await (0, import_promises24.access)(ancestor, import_node_fs33.constants.W_OK);
22469
22667
  } catch {
22470
22668
  unwritable.push(dir);
22471
22669
  }
@@ -22482,7 +22680,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22482
22680
  for (let index = 0; index < entry.outputs.length; index++) {
22483
22681
  const output = entry.outputs[index];
22484
22682
  const spec = specByKey.get(key3);
22485
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path35.default.dirname(lockPath));
22683
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path36.default.dirname(lockPath));
22486
22684
  const owner = outputOwners.get(absolute);
22487
22685
  if (owner && owner !== key3) duplicateOutputs.push(`${output.path} (${owner}, ${key3})`);
22488
22686
  outputOwners.set(absolute, key3);
@@ -22497,7 +22695,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22497
22695
  } else {
22498
22696
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
22499
22697
  }
22500
- const cacheDir = import_node_path35.default.join(import_node_path35.default.dirname(lockPath), ".pixelkiln", "cache");
22698
+ const cacheDir = import_node_path36.default.join(import_node_path36.default.dirname(lockPath), ".pixelkiln", "cache");
22501
22699
  const stranded = [];
22502
22700
  const invalidState = [];
22503
22701
  const staleMapUrls = [];
@@ -22513,11 +22711,11 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22513
22711
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
22514
22712
  let hasCache = false;
22515
22713
  for (const output of entry.outputs) {
22516
- const cached2 = import_node_path35.default.join(
22714
+ const cached2 = import_node_path36.default.join(
22517
22715
  cacheDir,
22518
22716
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
22519
22717
  );
22520
- if ((0, import_node_fs32.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
22718
+ if ((0, import_node_fs33.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
22521
22719
  hasCache = true;
22522
22720
  break;
22523
22721
  }
@@ -22610,19 +22808,19 @@ async function nearestExistingDirectory(start) {
22610
22808
  let current = start;
22611
22809
  for (; ; ) {
22612
22810
  try {
22613
- if ((await (0, import_promises23.stat)(current)).isDirectory()) return current;
22811
+ if ((await (0, import_promises24.stat)(current)).isDirectory()) return current;
22614
22812
  } catch {
22615
22813
  }
22616
- const parent = import_node_path35.default.dirname(current);
22814
+ const parent = import_node_path36.default.dirname(current);
22617
22815
  if (parent === current) return current;
22618
22816
  current = parent;
22619
22817
  }
22620
22818
  }
22621
22819
 
22622
22820
  // src/pipeline/adopt.ts
22623
- var import_node_fs33 = require("fs");
22624
- var import_promises24 = require("fs/promises");
22625
- var import_node_path36 = __toESM(require("path"), 1);
22821
+ var import_node_fs34 = require("fs");
22822
+ var import_promises25 = require("fs/promises");
22823
+ var import_node_path37 = __toESM(require("path"), 1);
22626
22824
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
22627
22825
  const log = opts.onProgress ?? (() => {
22628
22826
  });
@@ -22633,11 +22831,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
22633
22831
  const localByHash = /* @__PURE__ */ new Map();
22634
22832
  const unmatchedLocal = [];
22635
22833
  for (const spec of specs) {
22636
- if (!(0, import_node_fs33.existsSync)(spec.outFile)) {
22834
+ if (!(0, import_node_fs34.existsSync)(spec.outFile)) {
22637
22835
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
22638
22836
  continue;
22639
22837
  }
22640
- const bytes = await (0, import_promises24.readFile)(spec.outFile);
22838
+ const bytes = await (0, import_promises25.readFile)(spec.outFile);
22641
22839
  try {
22642
22840
  decodePng(bytes);
22643
22841
  } catch (err) {
@@ -22755,9 +22953,9 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
22755
22953
  }
22756
22954
 
22757
22955
  // src/pipeline/import.ts
22758
- var import_node_fs34 = require("fs");
22759
- var import_promises25 = require("fs/promises");
22760
- var import_node_path37 = __toESM(require("path"), 1);
22956
+ var import_node_fs35 = require("fs");
22957
+ var import_promises26 = require("fs/promises");
22958
+ var import_node_path38 = __toESM(require("path"), 1);
22761
22959
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
22762
22960
  const png = decodePng(bytes);
22763
22961
  const at2 = now.toISOString();
@@ -22809,13 +23007,13 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22809
23007
  if (opts.objectId && specs.length !== 1) {
22810
23008
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
22811
23009
  }
22812
- const cacheDir = opts.cacheDir === false ? null : import_node_path37.default.resolve(opts.cacheDir ?? import_node_path37.default.join(import_node_path37.default.dirname(lockPath), ".pixelkiln", "cache"));
23010
+ 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"));
22813
23011
  let rawSha256;
22814
23012
  let rawBytes;
22815
23013
  if (opts.raw) {
22816
23014
  if (specs.length !== 1) throw new Error(`--raw names one original; ${specs.length} assets are selected. Narrow with --only and --style.`);
22817
23015
  try {
22818
- rawBytes = await (0, import_promises25.readFile)(opts.raw);
23016
+ rawBytes = await (0, import_promises26.readFile)(opts.raw);
22819
23017
  decodePng(rawBytes);
22820
23018
  } catch (error) {
22821
23019
  throw new Error(`--raw ${opts.raw} is not a readable PNG: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
@@ -22831,7 +23029,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22831
23029
  skipped.push({ key: key3, reason });
22832
23030
  continue;
22833
23031
  }
22834
- if (!(0, import_node_fs34.existsSync)(spec.outFile)) {
23032
+ if (!(0, import_node_fs35.existsSync)(spec.outFile)) {
22835
23033
  skipped.push({ key: key3, reason: `no file at ${spec.outFile}` });
22836
23034
  continue;
22837
23035
  }
@@ -22842,7 +23040,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22842
23040
  let patch;
22843
23041
  let bytes;
22844
23042
  try {
22845
- bytes = await (0, import_promises25.readFile)(spec.outFile);
23043
+ bytes = await (0, import_promises26.readFile)(spec.outFile);
22846
23044
  patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
22847
23045
  } catch (error) {
22848
23046
  skipped.push({ key: key3, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
@@ -22874,7 +23072,7 @@ async function reportSpecHashes(specs, lock) {
22874
23072
  for (const spec of specs) {
22875
23073
  const key3 = lockKey(spec.styleId, spec.assetId);
22876
23074
  let bytes = null;
22877
- if ((0, import_node_fs34.existsSync)(spec.outFile)) bytes = await (0, import_promises25.readFile)(spec.outFile);
23075
+ if ((0, import_node_fs35.existsSync)(spec.outFile)) bytes = await (0, import_promises26.readFile)(spec.outFile);
22878
23076
  let wouldImport = null;
22879
23077
  if (bytes && !unimportable(spec)) {
22880
23078
  try {
@@ -22903,13 +23101,13 @@ async function reportSpecHashes(specs, lock) {
22903
23101
  }
22904
23102
 
22905
23103
  // src/pick/server.ts
22906
- var import_node_fs36 = require("fs");
22907
- var import_promises28 = require("fs/promises");
23104
+ var import_node_fs37 = require("fs");
23105
+ var import_promises29 = require("fs/promises");
22908
23106
 
22909
23107
  // src/pipeline/init.ts
22910
- var import_promises26 = require("fs/promises");
22911
- var import_node_fs35 = require("fs");
22912
- var import_node_path38 = __toESM(require("path"), 1);
23108
+ var import_promises27 = require("fs/promises");
23109
+ var import_node_fs36 = require("fs");
23110
+ var import_node_path39 = __toESM(require("path"), 1);
22913
23111
  function pngSize(buf) {
22914
23112
  if (buf.length < 24) return null;
22915
23113
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -22922,8 +23120,8 @@ function slugify(value) {
22922
23120
  }
22923
23121
  async function walk(dir, exclude) {
22924
23122
  const out = [];
22925
- for (const entry of await (0, import_promises26.readdir)(dir, { withFileTypes: true })) {
22926
- const full = import_node_path38.default.join(dir, entry.name);
23123
+ for (const entry of await (0, import_promises27.readdir)(dir, { withFileTypes: true })) {
23124
+ const full = import_node_path39.default.join(dir, entry.name);
22927
23125
  if (exclude.some((x) => full.includes(x))) continue;
22928
23126
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
22929
23127
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -22937,14 +23135,14 @@ async function scanAssets(root, opts = {}) {
22937
23135
  const skipped = [];
22938
23136
  const seen = /* @__PURE__ */ new Map();
22939
23137
  for (const file of files.sort()) {
22940
- const size = pngSize(await (0, import_promises26.readFile)(file));
23138
+ const size = pngSize(await (0, import_promises27.readFile)(file));
22941
23139
  if (!size) {
22942
23140
  skipped.push(`${file} (not a readable PNG)`);
22943
23141
  continue;
22944
23142
  }
22945
- const rel = import_node_path38.default.relative(root, file);
22946
- const category = import_node_path38.default.dirname(rel) === "." ? "" : import_node_path38.default.dirname(rel);
22947
- let id = slugify(import_node_path38.default.basename(rel));
23143
+ const rel = import_node_path39.default.relative(root, file);
23144
+ const category = import_node_path39.default.dirname(rel) === "." ? "" : import_node_path39.default.dirname(rel);
23145
+ let id = slugify(import_node_path39.default.basename(rel));
22948
23146
  if (seen.has(id)) {
22949
23147
  const n = seen.get(id) + 1;
22950
23148
  seen.set(id, n);
@@ -23418,7 +23616,7 @@ document.getElementById('submit').onclick = async () => {
23418
23616
 
23419
23617
  // src/pick/review-server.ts
23420
23618
  var import_node_http = require("http");
23421
- var import_promises27 = require("fs/promises");
23619
+ var import_promises28 = require("fs/promises");
23422
23620
  function serveReviewPage(opts) {
23423
23621
  const log = opts.onProgress ?? (() => {
23424
23622
  });
@@ -23427,7 +23625,7 @@ function serveReviewPage(opts) {
23427
23625
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
23428
23626
  try {
23429
23627
  const asset = opts.assets.get(req.url);
23430
- const bytes = await (0, import_promises27.readFile)(asset.path);
23628
+ const bytes = await (0, import_promises28.readFile)(asset.path);
23431
23629
  res.writeHead(200, {
23432
23630
  "Content-Type": asset.contentType,
23433
23631
  "Cache-Control": "no-store",
@@ -23503,13 +23701,13 @@ async function currentArt(entry, spec) {
23503
23701
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
23504
23702
  if (!previous) return null;
23505
23703
  const file = resolveOutputPath(previous.path, spec.root);
23506
- if (!(0, import_node_fs36.existsSync)(file)) return null;
23704
+ if (!(0, import_node_fs37.existsSync)(file)) return null;
23507
23705
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
23508
23706
  if (!contentType) return null;
23509
23707
  let width = entry.width;
23510
23708
  let height = entry.height;
23511
23709
  if (contentType === "image/png") {
23512
- const size = pngSize(await (0, import_promises28.readFile)(file));
23710
+ const size = pngSize(await (0, import_promises29.readFile)(file));
23513
23711
  if (size) ({ width, height } = size);
23514
23712
  }
23515
23713
  return { path: file, contentType, width, height };
@@ -23517,7 +23715,7 @@ async function currentArt(entry, spec) {
23517
23715
  async function cachedFrame(url) {
23518
23716
  if (!url.startsWith("file://")) return null;
23519
23717
  const file = url.slice("file://".length);
23520
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises28.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
23718
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises29.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
23521
23719
  return { path: file, contentType };
23522
23720
  }
23523
23721
  async function prepareReview(provider, lock, opts = {}) {
@@ -23530,26 +23728,56 @@ async function prepareReview(provider, lock, opts = {}) {
23530
23728
  const reviewAssets = /* @__PURE__ */ new Map();
23531
23729
  const prefix = opts.routePrefix ?? "";
23532
23730
  const providerUrls = /* @__PURE__ */ new Map();
23731
+ const store = opts.lockPath ? { cacheDir: candidateCacheDirFor(opts.lockPath), statePath: reviewStatePathFor(opts.lockPath) } : null;
23732
+ const records = /* @__PURE__ */ new Map();
23533
23733
  const groups = [];
23534
23734
  for (const [key3, entry] of Object.entries(lock.entries)) {
23535
23735
  if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key3)) continue;
23536
23736
  if (entry.status !== "review" || !entry.reviewObjectId) continue;
23537
23737
  try {
23538
23738
  const spec = specByKey.get(key3);
23539
- const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
23540
- if (state.status !== "review" && state.status !== "review-set" || (state.status === "review" ? !state.candidateUrls.length : !state.frameUrls.length)) continue;
23541
- const urls = state.status === "review" ? state.candidateUrls : state.frameUrls;
23739
+ const jobId = entry.reviewObjectId;
23740
+ let polled = null;
23741
+ let pollError = null;
23742
+ try {
23743
+ polled = await provider.poll(jobId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
23744
+ } catch (err) {
23745
+ pollError = err;
23746
+ }
23747
+ const live = polled && (polled.status === "review" && polled.candidateUrls.length || polled.status === "review-set" && polled.frameUrls.length) ? polled : null;
23748
+ let record = null;
23749
+ if (store) {
23750
+ if (live) {
23751
+ const cached2 = await cacheReviewCandidates(provider, key3, jobId, live, { ...store, generator: entry.generator });
23752
+ for (const message6 of cached2.failed) log(` could not cache ${message6}`);
23753
+ record = cached2.asset;
23754
+ } else {
23755
+ const saved = (await loadReviewState(store.statePath)).assets[key3];
23756
+ if (saved && saved.jobId === jobId && saved.provider === provider.id) {
23757
+ record = fullyCached(store.cacheDir, saved) ? saved : await ensureCandidatesCached(provider, key3, store);
23758
+ const why = pollError instanceof Error ? pollError.message : polled ? `job is ${polled.status}` : String(pollError);
23759
+ log(` ${key3}: job no longer available upstream (${why}); using the cached candidates`);
23760
+ }
23761
+ }
23762
+ }
23763
+ if (!live && !record) {
23764
+ if (pollError) throw pollError;
23765
+ continue;
23766
+ }
23767
+ if (record) records.set(key3, record);
23768
+ const urls = live ? live.status === "review" ? live.candidateUrls : live.frameUrls : record.candidates.map((c) => c.sourceUrl ?? `file://${cachedCandidatePath(store.cacheDir, c)}`);
23542
23769
  const frameUrls = [];
23543
23770
  const frameAssets = [];
23544
23771
  const frameSizes = [];
23545
23772
  for (const [index, url] of urls.entries()) {
23546
- const cached2 = await cachedFrame(url);
23773
+ const local = record?.candidates[index] && store ? cachedCandidatePath(store.cacheDir, record.candidates[index]) : null;
23774
+ const cached2 = local ? { path: local, contentType: record.candidates[index].mediaType ?? "application/octet-stream" } : await cachedFrame(url);
23547
23775
  if (!cached2) {
23548
23776
  frameUrls.push(url);
23549
23777
  frameSizes.push(null);
23550
23778
  continue;
23551
23779
  }
23552
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises28.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
23780
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises29.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
23553
23781
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
23554
23782
  frameAssets.push([route, cached2]);
23555
23783
  frameUrls.push(route);
@@ -23578,10 +23806,14 @@ async function prepareReview(provider, lock, opts = {}) {
23578
23806
  ...frameSizes.some(Boolean) ? { frameSizes } : {},
23579
23807
  width: entry.width,
23580
23808
  height: entry.height,
23581
- ...state.status === "review-set" ? {
23809
+ ...live?.status === "review-set" ? {
23582
23810
  mode: "frame-set",
23583
- frameLabels: state.sources.map((source, index) => source.role ?? `frame-${index}`),
23584
- fps: state.fps
23811
+ frameLabels: live.sources.map((source, index) => source.role ?? `frame-${index}`),
23812
+ fps: live.fps
23813
+ } : !live && record?.mode === "frame-set" ? {
23814
+ mode: "frame-set",
23815
+ frameLabels: record.candidates.map((c, index) => c.role ?? `frame-${index}`),
23816
+ fps: record.fps ?? 12
23585
23817
  } : { mode: "candidates" },
23586
23818
  ...sourceRoute && spec?.revision && spec.revision.sourceWidth && spec.revision.sourceHeight ? {
23587
23819
  revision: {
@@ -23604,6 +23836,30 @@ async function prepareReview(provider, lock, opts = {}) {
23604
23836
  }
23605
23837
  if (groups.length === 0) return null;
23606
23838
  const byKey = new Map(groups.map((g) => [g.key, g]));
23839
+ const localCandidate = (key3, jobId, index) => {
23840
+ const record = records.get(key3);
23841
+ const candidate = record?.jobId === jobId ? record.candidates[index] : void 0;
23842
+ const file = store && candidate ? cachedCandidatePath(store.cacheDir, candidate) : null;
23843
+ return file ? `file://${file}` : null;
23844
+ };
23845
+ const localFrameSet = (key3, jobId) => {
23846
+ const record = records.get(key3);
23847
+ if (!record || record.jobId !== jobId || record.mode !== "frame-set" || !store || !fullyCached(store.cacheDir, record)) return null;
23848
+ const sources = record.candidates.map((c) => ({
23849
+ url: `file://${cachedCandidatePath(store.cacheDir, c)}`,
23850
+ ...c.role ? { role: c.role } : {}
23851
+ }));
23852
+ return {
23853
+ status: "review-set",
23854
+ objectId: record.objectId ?? jobId,
23855
+ sources,
23856
+ metadata: void 0
23857
+ };
23858
+ };
23859
+ const markApplied = async (key3, index) => {
23860
+ if (!store || !records.has(key3)) return;
23861
+ await updateReviewAsset(store.statePath, key3, (asset) => ({ ...asset, status: "applied", chosen: index }));
23862
+ };
23607
23863
  return {
23608
23864
  groups,
23609
23865
  assets: reviewAssets,
@@ -23618,9 +23874,10 @@ async function prepareReview(provider, lock, opts = {}) {
23618
23874
  if (!Number.isInteger(index) || index < 0 || index >= group.frameUrls.length) continue;
23619
23875
  if (group.mode === "frame-set") {
23620
23876
  const spec = specByKey.get(key3);
23621
- const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
23622
- if (state.status !== "review-set") {
23623
- throw new Error(`Frame set ${key3} is no longer ready for review`);
23877
+ const live = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] }).catch(() => null);
23878
+ const state = live?.status === "review-set" ? live : localFrameSet(key3, entry.reviewObjectId);
23879
+ if (!state) {
23880
+ throw new Error(`Frame set ${key3} is no longer ready for review and has no cached frames`);
23624
23881
  }
23625
23882
  upsert(lock, key3, {
23626
23883
  status: "selected",
@@ -23638,15 +23895,28 @@ async function prepareReview(provider, lock, opts = {}) {
23638
23895
  } : entry.providerMetadata
23639
23896
  });
23640
23897
  selected++;
23641
- log(` accepted ${key3} \u2192 ${state.sources.length} ordered frames`);
23898
+ await markApplied(key3, index);
23899
+ log(` accepted ${key3} \u2192 ${state.sources.length} ordered frames${live?.status === "review-set" ? "" : " (from the local cache)"}`);
23642
23900
  continue;
23643
23901
  }
23644
- const { objectId, sourceUrl, metadata } = await requireSelectCandidate(provider)(
23645
- entry.reviewObjectId,
23646
- index,
23647
- `asset:${entry.assetId}`,
23648
- entry.generator
23649
- );
23902
+ let selection;
23903
+ let fromCache = false;
23904
+ try {
23905
+ selection = await requireSelectCandidate(provider)(
23906
+ entry.reviewObjectId,
23907
+ index,
23908
+ `asset:${entry.assetId}`,
23909
+ entry.generator
23910
+ );
23911
+ } catch (err) {
23912
+ const local = localCandidate(key3, entry.reviewObjectId, index);
23913
+ if (!local) throw err;
23914
+ log(` ${key3}: promotion failed upstream (${err instanceof Error ? err.message : String(err)}); using the cached candidate`);
23915
+ selection = { objectId: `${entry.reviewObjectId}#${index}`, sourceUrl: local };
23916
+ fromCache = true;
23917
+ }
23918
+ const { objectId, metadata } = selection;
23919
+ const sourceUrl = fromCache ? selection.sourceUrl : selection.sourceUrl ?? localCandidate(key3, entry.reviewObjectId, index);
23650
23920
  upsert(lock, key3, {
23651
23921
  status: "selected",
23652
23922
  objectId,
@@ -23663,7 +23933,8 @@ async function prepareReview(provider, lock, opts = {}) {
23663
23933
  } : entry.providerMetadata
23664
23934
  });
23665
23935
  selected++;
23666
- log(` picked ${key3} \u2192 candidate ${index + 1}`);
23936
+ await markApplied(key3, index);
23937
+ log(` picked ${key3} \u2192 candidate ${index + 1}${fromCache ? " (from the local cache)" : ""}`);
23667
23938
  }
23668
23939
  await saveLock(lockPath, lock);
23669
23940
  return { selected, skipped: groups.length - selected };
@@ -23673,19 +23944,33 @@ async function prepareReview(provider, lock, opts = {}) {
23673
23944
  async function runPicker(provider, lock, lockPath, opts = {}) {
23674
23945
  const log = opts.onProgress ?? (() => {
23675
23946
  });
23676
- const session = await prepareReview(provider, lock, {
23947
+ let session = await prepareReview(provider, lock, {
23677
23948
  onProgress: log,
23678
23949
  keys: opts.keys,
23679
- specs: opts.specs
23950
+ specs: opts.specs,
23951
+ lockPath
23680
23952
  });
23681
23953
  if (!session) return { selected: 0, skipped: 0 };
23682
- const groups = session.groups;
23683
- return serveReviewPage({
23684
- html: session.html(),
23954
+ let autoSelected = 0;
23955
+ if (opts.autoAcceptSingle) {
23956
+ const singles = session.groups.filter((g) => g.mode === "frame-set" || g.frameUrls.length === 1);
23957
+ if (singles.length) {
23958
+ const res = await session.apply({ selections: singles.map((g) => ({ key: g.key, index: 0 })) }, lockPath);
23959
+ autoSelected = res.selected;
23960
+ log(` --yes: accepted ${res.selected} single-candidate asset(s)`);
23961
+ const rest = session.groups.filter((g) => !singles.includes(g)).map((g) => g.key);
23962
+ session = rest.length ? await prepareReview(provider, lock, { onProgress: log, keys: rest, specs: opts.specs }) : null;
23963
+ if (!session) return { selected: autoSelected, skipped: 0 };
23964
+ }
23965
+ }
23966
+ const live = session;
23967
+ const groups = live.groups;
23968
+ const served = await serveReviewPage({
23969
+ html: live.html(),
23685
23970
  port: opts.port,
23686
23971
  open: opts.open,
23687
23972
  onProgress: log,
23688
- assets: session.assets,
23973
+ assets: live.assets,
23689
23974
  onReady: (url) => {
23690
23975
  const info = { url, keys: groups.map((group) => group.key) };
23691
23976
  if (opts.onReady) {
@@ -23697,21 +23982,22 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
23697
23982
  `);
23698
23983
  }
23699
23984
  },
23700
- handleApply: (body) => session.apply(body, lockPath)
23985
+ handleApply: (body) => live.apply(body, lockPath)
23701
23986
  });
23987
+ return { selected: served.selected + autoSelected, skipped: served.skipped };
23702
23988
  }
23703
23989
 
23704
23990
  // src/gallery/snapshot.ts
23705
23991
  var import_node_crypto10 = require("crypto");
23706
- var import_node_fs45 = require("fs");
23707
- var import_promises39 = require("fs/promises");
23708
- var import_node_path49 = __toESM(require("path"), 1);
23992
+ var import_node_fs46 = require("fs");
23993
+ var import_promises40 = require("fs/promises");
23994
+ var import_node_path50 = __toESM(require("path"), 1);
23709
23995
 
23710
23996
  // src/gallery/models.ts
23711
- var import_node_fs40 = require("fs");
23712
- var import_promises33 = require("fs/promises");
23713
- var import_node_path43 = __toESM(require("path"), 1);
23714
- var import_zod11 = require("zod");
23997
+ var import_node_fs41 = require("fs");
23998
+ var import_promises34 = require("fs/promises");
23999
+ var import_node_path44 = __toESM(require("path"), 1);
24000
+ var import_zod12 = require("zod");
23715
24001
 
23716
24002
  // src/glb.ts
23717
24003
  var MAGIC = 1179937895;
@@ -24043,57 +24329,57 @@ function modelItems(json) {
24043
24329
  }
24044
24330
 
24045
24331
  // src/manifest-edit.ts
24046
- var import_promises29 = require("fs/promises");
24047
- var import_node_path39 = __toESM(require("path"), 1);
24048
- var import_zod8 = require("zod");
24049
- var HexSha = import_zod8.z.string().regex(/^[0-9a-f]{64}$/);
24050
- var ProjectFileSchema = import_zod8.z.string().min(1).refine((file) => !import_node_path39.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
24051
- var AssetPatchSchema = import_zod8.z.object({
24052
- prompt: import_zod8.z.string().optional(),
24332
+ var import_promises30 = require("fs/promises");
24333
+ var import_node_path40 = __toESM(require("path"), 1);
24334
+ var import_zod9 = require("zod");
24335
+ var HexSha = import_zod9.z.string().regex(/^[0-9a-f]{64}$/);
24336
+ 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");
24337
+ var AssetPatchSchema = import_zod9.z.object({
24338
+ prompt: import_zod9.z.string().optional(),
24053
24339
  /** Per-style override for the style being viewed; null removes it. */
24054
- promptForStyle: import_zod8.z.object({ styleId: import_zod8.z.string().min(1), prompt: import_zod8.z.string().nullable() }).optional(),
24055
- category: import_zod8.z.string().nullable().optional(),
24056
- width: import_zod8.z.number().int().nullable().optional(),
24057
- height: import_zod8.z.number().int().nullable().optional(),
24058
- size: import_zod8.z.number().int().nullable().optional(),
24059
- tags: import_zod8.z.array(import_zod8.z.string()).optional(),
24340
+ promptForStyle: import_zod9.z.object({ styleId: import_zod9.z.string().min(1), prompt: import_zod9.z.string().nullable() }).optional(),
24341
+ category: import_zod9.z.string().nullable().optional(),
24342
+ width: import_zod9.z.number().int().nullable().optional(),
24343
+ height: import_zod9.z.number().int().nullable().optional(),
24344
+ size: import_zod9.z.number().int().nullable().optional(),
24345
+ tags: import_zod9.z.array(import_zod9.z.string()).optional(),
24060
24346
  /**
24061
24347
  * A loop shorthand's `animation.directions`, replaced whole: each named
24062
24348
  * direction is drawn, and each one's flip comes free as a mirror.
24063
24349
  */
24064
- loopDirections: import_zod8.z.array(CharacterDirectionSchema).min(1).optional()
24350
+ loopDirections: import_zod9.z.array(CharacterDirectionSchema).min(1).optional()
24065
24351
  }).strict();
24066
- var NewStateSchema = import_zod8.z.object({
24352
+ var NewStateSchema = import_zod9.z.object({
24067
24353
  /** Asset id of the parent this states; must already exist. */
24068
- of: import_zod8.z.string().min(1),
24069
- paletteFromReference: import_zod8.z.boolean().optional(),
24070
- canvas: import_zod8.z.object({ width: import_zod8.z.number().int().min(16).max(256), height: import_zod8.z.number().int().min(16).max(256) }).strict().optional()
24354
+ of: import_zod9.z.string().min(1),
24355
+ paletteFromReference: import_zod9.z.boolean().optional(),
24356
+ canvas: import_zod9.z.object({ width: import_zod9.z.number().int().min(16).max(256), height: import_zod9.z.number().int().min(16).max(256) }).strict().optional()
24071
24357
  }).strict();
24072
- var NewAnimationSchema = import_zod8.z.object({
24358
+ var NewAnimationSchema = import_zod9.z.object({
24073
24359
  /** Asset id of the parent this animates; must already exist. */
24074
- of: import_zod8.z.string().min(1),
24360
+ of: import_zod9.z.string().min(1),
24075
24361
  /** A PixelLab template id (`character` only; `objectPro` has no template concept). */
24076
- template: import_zod8.z.string().min(1).optional(),
24362
+ template: import_zod9.z.string().min(1).optional(),
24077
24363
  direction: CharacterDirectionSchema.optional(),
24078
- frames: import_zod8.z.number().int().min(4).max(16).optional(),
24079
- fps: import_zod8.z.number().int().min(1).max(60).optional(),
24364
+ frames: import_zod9.z.number().int().min(4).max(16).optional(),
24365
+ fps: import_zod9.z.number().int().min(1).max(60).optional(),
24080
24366
  /** One loop per named direction, plus free mirrors; expanded when the manifest loads. */
24081
- directions: import_zod8.z.array(CharacterDirectionSchema).min(1).optional(),
24367
+ directions: import_zod9.z.array(CharacterDirectionSchema).min(1).optional(),
24082
24368
  mode: CharacterAnimationModeSchema.optional(),
24083
24369
  /** What is being animated, when the parent's own description would mislead the model (`character` only). */
24084
- subject: import_zod8.z.string().min(1).optional(),
24085
- enhancePrompt: import_zod8.z.boolean().optional()
24370
+ subject: import_zod9.z.string().min(1).optional(),
24371
+ enhancePrompt: import_zod9.z.boolean().optional()
24086
24372
  }).strict();
24087
- var NewAssetSchema = import_zod8.z.object({
24373
+ var NewAssetSchema = import_zod9.z.object({
24088
24374
  /** A portrait, an outfit, or a mirror has none of its own; the loader says where one is needed. */
24089
- prompt: import_zod8.z.string().optional(),
24090
- category: import_zod8.z.string().optional(),
24091
- width: import_zod8.z.number().int().optional(),
24092
- height: import_zod8.z.number().int().optional(),
24093
- size: import_zod8.z.number().int().optional(),
24094
- tags: import_zod8.z.array(import_zod8.z.string()).optional(),
24375
+ prompt: import_zod9.z.string().optional(),
24376
+ category: import_zod9.z.string().optional(),
24377
+ width: import_zod9.z.number().int().optional(),
24378
+ height: import_zod9.z.number().int().optional(),
24379
+ size: import_zod9.z.number().int().optional(),
24380
+ tags: import_zod9.z.array(import_zod9.z.string()).optional(),
24095
24381
  /** Restrict to these styles; empty or omitted means every style. */
24096
- styles: import_zod8.z.array(import_zod8.z.string().min(1)).optional(),
24382
+ styles: import_zod9.z.array(import_zod9.z.string().min(1)).optional(),
24097
24383
  /**
24098
24384
  * A controlled regeneration of another asset in the same manifest,
24099
24385
  * instead of a fresh generation. Every mode but `outpaint` can be
@@ -24102,68 +24388,68 @@ var NewAssetSchema = import_zod8.z.object({
24102
24388
  * keyframe, and `animate-skeleton` names the keypoints file the gallery
24103
24389
  * wrote first.
24104
24390
  */
24105
- revision: import_zod8.z.discriminatedUnion("mode", [
24106
- import_zod8.z.object({
24107
- mode: import_zod8.z.literal("image-to-image"),
24391
+ revision: import_zod9.z.discriminatedUnion("mode", [
24392
+ import_zod9.z.object({
24393
+ mode: import_zod9.z.literal("image-to-image"),
24108
24394
  /** Asset id of the parent this revises; must already exist. */
24109
- from: import_zod8.z.string().min(1),
24110
- strength: import_zod8.z.number().min(0).max(1).optional()
24395
+ from: import_zod9.z.string().min(1),
24396
+ strength: import_zod9.z.number().min(0).max(1).optional()
24111
24397
  }).strict(),
24112
- import_zod8.z.object({
24113
- mode: import_zod8.z.literal("reduce-colors"),
24114
- from: import_zod8.z.string().min(1),
24398
+ import_zod9.z.object({
24399
+ mode: import_zod9.z.literal("reduce-colors"),
24400
+ from: import_zod9.z.string().min(1),
24115
24401
  /** A target colour count; the gallery leaves PixelLab's default when this is omitted. */
24116
- numColors: import_zod8.z.number().int().min(2).max(256).optional(),
24402
+ numColors: import_zod9.z.number().int().min(2).max(256).optional(),
24117
24403
  dithering: RevisionDitheringSchema.optional(),
24118
- ditheringStrength: import_zod8.z.number().min(0).max(10).optional()
24404
+ ditheringStrength: import_zod9.z.number().min(0).max(10).optional()
24119
24405
  }).strict(),
24120
- import_zod8.z.object({
24121
- mode: import_zod8.z.literal("inpaint"),
24122
- from: import_zod8.z.string().min(1),
24406
+ import_zod9.z.object({
24407
+ mode: import_zod9.z.literal("inpaint"),
24408
+ from: import_zod9.z.string().min(1),
24123
24409
  /** Black-and-white PNG the same size as the parent; white is repainted. */
24124
24410
  mask: ProjectFileSchema
24125
24411
  }).strict(),
24126
- import_zod8.z.object({
24127
- mode: import_zod8.z.literal("interpolate"),
24128
- from: import_zod8.z.string().min(1),
24412
+ import_zod9.z.object({
24413
+ mode: import_zod9.z.literal("interpolate"),
24414
+ from: import_zod9.z.string().min(1),
24129
24415
  /** The ending keyframe: an image already in the project, the parent's size. */
24130
24416
  lastFrame: ProjectFileSchema,
24131
- fps: import_zod8.z.number().int().min(1).max(60).optional()
24417
+ fps: import_zod9.z.number().int().min(1).max(60).optional()
24132
24418
  }).strict(),
24133
- import_zod8.z.object({ mode: import_zod8.z.literal("correct-pixelart"), from: import_zod8.z.string().min(1), strength: import_zod8.z.number().min(0).max(1).optional() }).strict(),
24134
- import_zod8.z.object({
24135
- mode: import_zod8.z.literal("remove-background"),
24136
- from: import_zod8.z.string().min(1),
24137
- removalTask: import_zod8.z.enum(["simple", "complex"]).optional(),
24419
+ import_zod9.z.object({ mode: import_zod9.z.literal("correct-pixelart"), from: import_zod9.z.string().min(1), strength: import_zod9.z.number().min(0).max(1).optional() }).strict(),
24420
+ import_zod9.z.object({
24421
+ mode: import_zod9.z.literal("remove-background"),
24422
+ from: import_zod9.z.string().min(1),
24423
+ removalTask: import_zod9.z.enum(["simple", "complex"]).optional(),
24138
24424
  /** A short description of the foreground, sent as PixelLab's text hint. */
24139
- description: import_zod8.z.string().min(1).optional()
24425
+ description: import_zod9.z.string().min(1).optional()
24140
24426
  }).strict(),
24141
- import_zod8.z.object({ mode: import_zod8.z.literal("normal-map"), from: import_zod8.z.string().min(1), convention: NormalMapConventionSchema.optional() }).strict(),
24142
- import_zod8.z.object({
24143
- mode: import_zod8.z.enum(["animate", "animate-pixminimax"]),
24144
- from: import_zod8.z.string().min(1),
24145
- frames: import_zod8.z.number().int().min(4).max(40).refine((n) => n % 2 === 0, "frames must be even").optional(),
24146
- fps: import_zod8.z.number().int().min(1).max(60).optional(),
24147
- enhancePrompt: import_zod8.z.boolean().optional(),
24148
- driftThreshold: import_zod8.z.number().min(0).optional(),
24427
+ import_zod9.z.object({ mode: import_zod9.z.literal("normal-map"), from: import_zod9.z.string().min(1), convention: NormalMapConventionSchema.optional() }).strict(),
24428
+ import_zod9.z.object({
24429
+ mode: import_zod9.z.enum(["animate", "animate-pixminimax"]),
24430
+ from: import_zod9.z.string().min(1),
24431
+ frames: import_zod9.z.number().int().min(4).max(40).refine((n) => n % 2 === 0, "frames must be even").optional(),
24432
+ fps: import_zod9.z.number().int().min(1).max(60).optional(),
24433
+ enhancePrompt: import_zod9.z.boolean().optional(),
24434
+ driftThreshold: import_zod9.z.number().min(0).optional(),
24149
24435
  /** `animate-pixminimax` only; the loader refuses these on `animate`. */
24150
24436
  direction: CharacterDirectionSchema.optional(),
24151
- subjectDescription: import_zod8.z.string().min(1).max(300).optional(),
24152
- initialPose: import_zod8.z.string().min(1).max(300).optional()
24437
+ subjectDescription: import_zod9.z.string().min(1).max(300).optional(),
24438
+ initialPose: import_zod9.z.string().min(1).max(300).optional()
24153
24439
  }).strict(),
24154
- import_zod8.z.object({
24155
- mode: import_zod8.z.literal("edit-animation"),
24156
- from: import_zod8.z.string().min(1),
24157
- fps: import_zod8.z.number().int().min(1).max(60).optional()
24440
+ import_zod9.z.object({
24441
+ mode: import_zod9.z.literal("edit-animation"),
24442
+ from: import_zod9.z.string().min(1),
24443
+ fps: import_zod9.z.number().int().min(1).max(60).optional()
24158
24444
  }).strict(),
24159
- import_zod8.z.object({
24160
- mode: import_zod8.z.literal("animate-skeleton"),
24161
- from: import_zod8.z.string().min(1),
24445
+ import_zod9.z.object({
24446
+ mode: import_zod9.z.literal("animate-skeleton"),
24447
+ from: import_zod9.z.string().min(1),
24162
24448
  /** Manifest-relative; checked when the manifest is loaded, like every revision input. */
24163
- keypointsFile: import_zod8.z.string().min(1),
24449
+ keypointsFile: import_zod9.z.string().min(1),
24164
24450
  direction: CharacterDirectionSchema,
24165
- description: import_zod8.z.string().min(1).optional(),
24166
- skeletonTemplate: import_zod8.z.string().min(1).optional()
24451
+ description: import_zod9.z.string().min(1).optional(),
24452
+ skeletonTemplate: import_zod9.z.string().min(1).optional()
24167
24453
  }).strict()
24168
24454
  ]).optional(),
24169
24455
  /** A pose or outfit of an existing `character`/`objectPro` base or state. */
@@ -24175,16 +24461,16 @@ var NewAssetSchema = import_zod8.z.object({
24175
24461
  /** An existing loop re-clothed from a reference image (uploaded first). */
24176
24462
  outfit: CharacterOutfitSchema.optional(),
24177
24463
  /** Another asset of the same style, flipped; free. */
24178
- mirror: import_zod8.z.string().min(1).optional(),
24464
+ mirror: import_zod9.z.string().min(1).optional(),
24179
24465
  /**
24180
24466
  * `character`/`objectPro` bases: the subject's own sprite (uploaded
24181
24467
  * first), or one per direction, which PixelLab rotates instead of drawing.
24182
24468
  */
24183
- reference: import_zod8.z.union([import_zod8.z.string().min(1), import_zod8.z.record(CharacterDirectionSchema, import_zod8.z.string().min(1))]).optional(),
24469
+ reference: import_zod9.z.union([import_zod9.z.string().min(1), import_zod9.z.record(CharacterDirectionSchema, import_zod9.z.string().min(1))]).optional(),
24184
24470
  /** `character` pro bases: a concept image that seeds the design. */
24185
- concept: import_zod8.z.string().min(1).optional(),
24471
+ concept: import_zod9.z.string().min(1).optional(),
24186
24472
  /** `character` pro bases: another character in the style whose look this one follows. */
24187
- styleCharacter: import_zod8.z.string().min(1).optional(),
24473
+ styleCharacter: import_zod9.z.string().min(1).optional(),
24188
24474
  /** `character` standard humanoid bases: this character's proportions, over the style's. */
24189
24475
  proportions: CharacterProportionsSchema.optional()
24190
24476
  }).strict().refine((asset) => !(asset.revision && (asset.state || asset.animation)), {
@@ -24197,79 +24483,79 @@ var CANDIDATE_OPTION = {
24197
24483
  comfyui: "numImages",
24198
24484
  scenario: "numOutputs"
24199
24485
  };
24200
- var NewStyleSchema = import_zod8.z.object({
24201
- generator: import_zod8.z.enum(["character", "objectPro"]),
24486
+ var NewStyleSchema = import_zod9.z.object({
24487
+ generator: import_zod9.z.enum(["character", "objectPro"]),
24202
24488
  /** Where the style's art is written, inside the project. */
24203
- outDir: import_zod8.z.string().min(1).refine((dir) => !dir.split(/[\\/]/).includes("..") && !/^([a-z]:)?[\\/]/i.test(dir), {
24489
+ outDir: import_zod9.z.string().min(1).refine((dir) => !dir.split(/[\\/]/).includes("..") && !/^([a-z]:)?[\\/]/i.test(dir), {
24204
24490
  message: "outDir must be a path inside the project"
24205
24491
  }),
24206
- size: import_zod8.z.number().int().min(16).max(256).optional(),
24492
+ size: import_zod9.z.number().int().min(16).max(256).optional(),
24207
24493
  mode: CharacterModeSchema.optional(),
24208
- directions: import_zod8.z.union([import_zod8.z.literal(4), import_zod8.z.literal(8)]).optional(),
24209
- template: import_zod8.z.string().min(1).optional(),
24210
- view: import_zod8.z.string().min(1).max(64).optional(),
24494
+ directions: import_zod9.z.union([import_zod9.z.literal(4), import_zod9.z.literal(8)]).optional(),
24495
+ template: import_zod9.z.string().min(1).optional(),
24496
+ view: import_zod9.z.string().min(1).max(64).optional(),
24211
24497
  proportions: CharacterProportionsSchema.optional(),
24212
- isometric: import_zod8.z.boolean().optional(),
24213
- textGuidanceScale: import_zod8.z.number().min(1).max(20).optional(),
24214
- enhancePrompt: import_zod8.z.boolean().optional(),
24215
- promptPrefix: import_zod8.z.string().optional(),
24216
- promptSuffix: import_zod8.z.string().optional(),
24217
- palette: import_zod8.z.array(import_zod8.z.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).optional()
24498
+ isometric: import_zod9.z.boolean().optional(),
24499
+ textGuidanceScale: import_zod9.z.number().min(1).max(20).optional(),
24500
+ enhancePrompt: import_zod9.z.boolean().optional(),
24501
+ promptPrefix: import_zod9.z.string().optional(),
24502
+ promptSuffix: import_zod9.z.string().optional(),
24503
+ palette: import_zod9.z.array(import_zod9.z.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).optional()
24218
24504
  }).strict();
24219
- var PatchAssetEdit = import_zod8.z.object({
24220
- action: import_zod8.z.literal("patch-asset"),
24221
- assetId: import_zod8.z.string().min(1),
24505
+ var PatchAssetEdit = import_zod9.z.object({
24506
+ action: import_zod9.z.literal("patch-asset"),
24507
+ assetId: import_zod9.z.string().min(1),
24222
24508
  patch: AssetPatchSchema
24223
24509
  }).strict();
24224
- var AddAssetEdit = import_zod8.z.object({
24225
- action: import_zod8.z.literal("add-asset"),
24226
- assetId: import_zod8.z.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
24510
+ var AddAssetEdit = import_zod9.z.object({
24511
+ action: import_zod9.z.literal("add-asset"),
24512
+ assetId: import_zod9.z.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
24227
24513
  asset: NewAssetSchema
24228
24514
  }).strict();
24229
- var SetSourceEdit = import_zod8.z.object({
24230
- action: import_zod8.z.literal("set-source"),
24231
- assetId: import_zod8.z.string().min(1),
24232
- styleId: import_zod8.z.string().min(1),
24515
+ var SetSourceEdit = import_zod9.z.object({
24516
+ action: import_zod9.z.literal("set-source"),
24517
+ assetId: import_zod9.z.string().min(1),
24518
+ styleId: import_zod9.z.string().min(1),
24233
24519
  /** Manifest-relative path of the art that stands in for this asset in this style. */
24234
- source: import_zod8.z.string().min(1)
24520
+ source: import_zod9.z.string().min(1)
24235
24521
  }).strict();
24236
- var ClearSourceEdit = import_zod8.z.object({
24237
- action: import_zod8.z.literal("clear-source"),
24238
- assetId: import_zod8.z.string().min(1),
24239
- styleId: import_zod8.z.string().min(1)
24522
+ var ClearSourceEdit = import_zod9.z.object({
24523
+ action: import_zod9.z.literal("clear-source"),
24524
+ assetId: import_zod9.z.string().min(1),
24525
+ styleId: import_zod9.z.string().min(1)
24240
24526
  }).strict();
24241
- var PatchStyleEdit = import_zod8.z.object({
24242
- action: import_zod8.z.literal("patch-style"),
24243
- styleId: import_zod8.z.string().min(1),
24244
- patch: import_zod8.z.object({
24527
+ var PatchStyleEdit = import_zod9.z.object({
24528
+ action: import_zod9.z.literal("patch-style"),
24529
+ styleId: import_zod9.z.string().min(1),
24530
+ patch: import_zod9.z.object({
24245
24531
  /** Candidates per generation, written to the provider's own option. */
24246
- candidates: import_zod8.z.number().int().min(1).max(64).optional(),
24532
+ candidates: import_zod9.z.number().int().min(1).max(64).optional(),
24247
24533
  /** Empty clears the style's own value (inherit, or the default). */
24248
- promptPrefix: import_zod8.z.string().optional(),
24249
- promptSuffix: import_zod8.z.string().optional(),
24534
+ promptPrefix: import_zod9.z.string().optional(),
24535
+ promptSuffix: import_zod9.z.string().optional(),
24250
24536
  /** `#rrggbb` values; null or empty clears the style's own palette. */
24251
- palette: import_zod8.z.array(import_zod8.z.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).nullable().optional(),
24537
+ palette: import_zod9.z.array(import_zod9.z.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).nullable().optional(),
24252
24538
  /** Snap downloaded art to the palette; false clears the style's own value. */
24253
- enforcePalette: import_zod8.z.boolean().optional(),
24539
+ enforcePalette: import_zod9.z.boolean().optional(),
24254
24540
  /** Provider view name (PixelLab: low top-down, high top-down, side); empty clears. */
24255
- view: import_zod8.z.string().max(64).nullable().optional(),
24541
+ view: import_zod9.z.string().max(64).nullable().optional(),
24256
24542
  /** pixflux only; null clears the style's own value. */
24257
- noBackground: import_zod8.z.boolean().nullable().optional()
24543
+ noBackground: import_zod9.z.boolean().nullable().optional()
24258
24544
  }).strict().refine((patch) => Object.keys(patch).length > 0, { message: "nothing to change" })
24259
24545
  }).strict();
24260
- var AddStyleEdit = import_zod8.z.object({
24261
- action: import_zod8.z.literal("add-style"),
24262
- styleId: import_zod8.z.string().min(1).regex(/^[^/\\:]+$/, "style ids cannot contain slashes or colons"),
24546
+ var AddStyleEdit = import_zod9.z.object({
24547
+ action: import_zod9.z.literal("add-style"),
24548
+ styleId: import_zod9.z.string().min(1).regex(/^[^/\\:]+$/, "style ids cannot contain slashes or colons"),
24263
24549
  style: NewStyleSchema
24264
24550
  }).strict();
24265
24551
  var Envelope = {
24266
24552
  /** Workspace project id; omitted for a single-project gallery. */
24267
- project: import_zod8.z.string().min(1).optional(),
24553
+ project: import_zod9.z.string().min(1).optional(),
24268
24554
  /** Manifest bytes the page last saw; a mismatch refuses the write. */
24269
24555
  expectedSha256: HexSha
24270
24556
  };
24271
- var SingleEdit = import_zod8.z.discriminatedUnion("action", [PatchAssetEdit, AddAssetEdit, SetSourceEdit, ClearSourceEdit, PatchStyleEdit, AddStyleEdit]);
24272
- var ManifestEditSchema = import_zod8.z.discriminatedUnion("action", [
24557
+ var SingleEdit = import_zod9.z.discriminatedUnion("action", [PatchAssetEdit, AddAssetEdit, SetSourceEdit, ClearSourceEdit, PatchStyleEdit, AddStyleEdit]);
24558
+ var ManifestEditSchema = import_zod9.z.discriminatedUnion("action", [
24273
24559
  PatchAssetEdit.extend(Envelope),
24274
24560
  AddAssetEdit.extend(Envelope),
24275
24561
  SetSourceEdit.extend(Envelope),
@@ -24282,10 +24568,10 @@ var ManifestEditSchema = import_zod8.z.discriminatedUnion("action", [
24282
24568
  * Each edit sees the ones before it, so a base can name a style the same
24283
24569
  * batch adds.
24284
24570
  */
24285
- import_zod8.z.object({
24286
- action: import_zod8.z.literal("batch"),
24571
+ import_zod9.z.object({
24572
+ action: import_zod9.z.literal("batch"),
24287
24573
  ...Envelope,
24288
- edits: import_zod8.z.array(SingleEdit).min(1).max(64)
24574
+ edits: import_zod9.z.array(SingleEdit).min(1).max(64)
24289
24575
  }).strict()
24290
24576
  ]);
24291
24577
  var ManifestDriftError = class extends Error {
@@ -24467,8 +24753,8 @@ function applyEdit(raw, edit) {
24467
24753
  }
24468
24754
  }
24469
24755
  async function withCandidate(manifestPath, edit, use, unchanged) {
24470
- const absolute = import_node_path39.default.resolve(manifestPath);
24471
- const original = await (0, import_promises29.readFile)(absolute, "utf8");
24756
+ const absolute = import_node_path40.default.resolve(manifestPath);
24757
+ const original = await (0, import_promises30.readFile)(absolute, "utf8");
24472
24758
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
24473
24759
  let raw;
24474
24760
  try {
@@ -24481,12 +24767,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
24481
24767
  applyEdit(raw, edit);
24482
24768
  const next = serializeLike(original, raw);
24483
24769
  if (next === original) return unchanged(absolute, original);
24484
- const tmp = import_node_path39.default.join(
24485
- import_node_path39.default.dirname(absolute),
24486
- `.${import_node_path39.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
24770
+ const tmp = import_node_path40.default.join(
24771
+ import_node_path40.default.dirname(absolute),
24772
+ `.${import_node_path40.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
24487
24773
  );
24488
24774
  try {
24489
- await (0, import_promises29.writeFile)(tmp, next);
24775
+ await (0, import_promises30.writeFile)(tmp, next);
24490
24776
  let specs;
24491
24777
  try {
24492
24778
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -24496,7 +24782,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
24496
24782
  }
24497
24783
  return await use({ absolute, original, next, tmp, specs });
24498
24784
  } finally {
24499
- await (0, import_promises29.rm)(tmp, { force: true });
24785
+ await (0, import_promises30.rm)(tmp, { force: true });
24500
24786
  }
24501
24787
  }
24502
24788
  async function applyManifestEdit(manifestPath, edit) {
@@ -24504,7 +24790,7 @@ async function applyManifestEdit(manifestPath, edit) {
24504
24790
  manifestPath,
24505
24791
  edit,
24506
24792
  async ({ absolute, next, tmp }) => {
24507
- await (0, import_promises29.rename)(tmp, absolute);
24793
+ await (0, import_promises30.rename)(tmp, absolute);
24508
24794
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
24509
24795
  },
24510
24796
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -24512,18 +24798,18 @@ async function applyManifestEdit(manifestPath, edit) {
24512
24798
  }
24513
24799
 
24514
24800
  // src/pipeline/hand-edit.ts
24515
- var import_node_fs37 = require("fs");
24516
- var import_promises30 = require("fs/promises");
24517
- var import_node_path40 = __toESM(require("path"), 1);
24518
- var import_zod9 = require("zod");
24801
+ var import_node_fs38 = require("fs");
24802
+ var import_promises31 = require("fs/promises");
24803
+ var import_node_path41 = __toESM(require("path"), 1);
24804
+ var import_zod10 = require("zod");
24519
24805
  var HAND_EDIT_DIR = "edits";
24520
24806
  function handEditPath(loaded, spec) {
24521
24807
  const style = loaded.manifest.styles[spec.styleId];
24522
- const outDir = import_node_path40.default.resolve(loaded.root, style?.outDir ?? ".");
24523
- const relative = import_node_path40.default.relative(outDir, spec.outFile);
24524
- const inside2 = relative && !relative.startsWith("..") && !import_node_path40.default.isAbsolute(relative);
24525
- const file = inside2 ? relative : import_node_path40.default.basename(spec.outFile);
24526
- return import_node_path40.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
24808
+ const outDir = import_node_path41.default.resolve(loaded.root, style?.outDir ?? ".");
24809
+ const relative = import_node_path41.default.relative(outDir, spec.outFile);
24810
+ const inside2 = relative && !relative.startsWith("..") && !import_node_path41.default.isAbsolute(relative);
24811
+ const file = inside2 ? relative : import_node_path41.default.basename(spec.outFile);
24812
+ return import_node_path41.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
24527
24813
  }
24528
24814
  function handEditBases(spec, lock) {
24529
24815
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -24536,10 +24822,10 @@ function handEditBases(spec, lock) {
24536
24822
  }));
24537
24823
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
24538
24824
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
24539
- if (!members.every((member) => (0, import_node_fs37.existsSync)(member.path))) return null;
24825
+ if (!members.every((member) => (0, import_node_fs38.existsSync)(member.path))) return null;
24540
24826
  return members.map(({ role, path: file }) => ({ role, path: file }));
24541
24827
  }
24542
- return (0, import_node_fs37.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
24828
+ return (0, import_node_fs38.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
24543
24829
  }
24544
24830
  function handEditBase(spec, lock) {
24545
24831
  const bases = handEditBases(spec, lock);
@@ -24589,19 +24875,19 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
24589
24875
  `${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`
24590
24876
  );
24591
24877
  }
24592
- const existing = spec.source ? import_node_path40.default.resolve(loaded.root, spec.source) : null;
24878
+ const existing = spec.source ? import_node_path41.default.resolve(loaded.root, spec.source) : null;
24593
24879
  const editPath = existing ?? handEditPath(loaded, spec);
24594
24880
  const members = handEditMembers(loaded, spec, lock, editPath);
24595
24881
  let created = false;
24596
24882
  for (const member of members) {
24597
- if ((0, import_node_fs37.existsSync)(member.path)) continue;
24883
+ if ((0, import_node_fs38.existsSync)(member.path)) continue;
24598
24884
  if (!member.base) {
24599
24885
  throw new ManifestEditError(
24600
24886
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
24601
24887
  );
24602
24888
  }
24603
- await (0, import_promises30.mkdir)(import_node_path40.default.dirname(member.path), { recursive: true });
24604
- await (0, import_promises30.copyFile)(member.base, member.path);
24889
+ await (0, import_promises31.mkdir)(import_node_path41.default.dirname(member.path), { recursive: true });
24890
+ await (0, import_promises31.copyFile)(member.base, member.path);
24605
24891
  created = true;
24606
24892
  }
24607
24893
  const source = portableOutputPath(editPath, loaded.root);
@@ -24632,35 +24918,35 @@ async function detachHandEdit(loaded, spec, opts = {}) {
24632
24918
  });
24633
24919
  return { manifestSha256: result.sha256, changed: result.changed };
24634
24920
  }
24635
- var CompanionOutputSchema = import_zod9.z.object({
24921
+ var CompanionOutputSchema = import_zod10.z.object({
24636
24922
  /** Output role for a set member; null for a single image. */
24637
- role: import_zod9.z.string().nullable(),
24923
+ role: import_zod10.z.string().nullable(),
24638
24924
  /** sha256 of the generated file this member started from; null when it started from untracked art. */
24639
- basedOn: import_zod9.z.string().regex(/^[0-9a-f]{64}$/).nullable(),
24925
+ basedOn: import_zod10.z.string().regex(/^[0-9a-f]{64}$/).nullable(),
24640
24926
  /** sha256 of the member as saved, so a later change by another tool is visible. */
24641
- sha256: import_zod9.z.string().regex(/^[0-9a-f]{64}$/)
24927
+ sha256: import_zod10.z.string().regex(/^[0-9a-f]{64}$/)
24642
24928
  }).strict();
24643
- var CompanionV2Schema = import_zod9.z.object({
24644
- version: import_zod9.z.literal(2),
24929
+ var CompanionV2Schema = import_zod10.z.object({
24930
+ version: import_zod10.z.literal(2),
24645
24931
  /** Editor identity the bridge reported, e.g. `pixelorama@v1.2.2-stable`. */
24646
- editor: import_zod9.z.string().min(1),
24647
- protocol: import_zod9.z.number().int().positive(),
24648
- savedAt: import_zod9.z.string().datetime(),
24932
+ editor: import_zod10.z.string().min(1),
24933
+ protocol: import_zod10.z.number().int().positive(),
24934
+ savedAt: import_zod10.z.string().datetime(),
24649
24935
  /** Basename of the layered project file beside the edit, when one was kept. */
24650
- project: import_zod9.z.string().min(1).nullable(),
24936
+ project: import_zod10.z.string().min(1).nullable(),
24651
24937
  /** One entry per file, in output order. */
24652
- outputs: import_zod9.z.array(CompanionOutputSchema).min(1)
24938
+ outputs: import_zod10.z.array(CompanionOutputSchema).min(1)
24653
24939
  }).strict();
24654
- var CompanionV1Schema = import_zod9.z.object({
24655
- version: import_zod9.z.literal(1),
24656
- basedOn: import_zod9.z.string().regex(/^[0-9a-f]{64}$/).nullable(),
24657
- sha256: import_zod9.z.string().regex(/^[0-9a-f]{64}$/),
24658
- editor: import_zod9.z.string().min(1),
24659
- protocol: import_zod9.z.number().int().positive(),
24660
- savedAt: import_zod9.z.string().datetime(),
24661
- project: import_zod9.z.string().min(1).nullable()
24940
+ var CompanionV1Schema = import_zod10.z.object({
24941
+ version: import_zod10.z.literal(1),
24942
+ basedOn: import_zod10.z.string().regex(/^[0-9a-f]{64}$/).nullable(),
24943
+ sha256: import_zod10.z.string().regex(/^[0-9a-f]{64}$/),
24944
+ editor: import_zod10.z.string().min(1),
24945
+ protocol: import_zod10.z.number().int().positive(),
24946
+ savedAt: import_zod10.z.string().datetime(),
24947
+ project: import_zod10.z.string().min(1).nullable()
24662
24948
  }).strict();
24663
- var HandEditCompanionSchema = import_zod9.z.union([CompanionV2Schema, CompanionV1Schema]).transform(
24949
+ var HandEditCompanionSchema = import_zod10.z.union([CompanionV2Schema, CompanionV1Schema]).transform(
24664
24950
  (value) => value.version === 2 ? value : {
24665
24951
  version: 2,
24666
24952
  editor: value.editor,
@@ -24679,7 +24965,7 @@ function handEditProjectPath(editPath) {
24679
24965
  async function readHandEditCompanion(editPath) {
24680
24966
  let text;
24681
24967
  try {
24682
- text = await (0, import_promises30.readFile)(handEditCompanionPath(editPath), "utf8");
24968
+ text = await (0, import_promises31.readFile)(handEditCompanionPath(editPath), "utf8");
24683
24969
  } catch {
24684
24970
  return null;
24685
24971
  }
@@ -24723,7 +25009,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
24723
25009
  }
24724
25010
  });
24725
25011
  const bases = handEditBases(spec, lock);
24726
- const expectedSize = bases?.[0] ? decodePng(await (0, import_promises30.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
25012
+ const expectedSize = bases?.[0] ? decodePng(await (0, import_promises31.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
24727
25013
  for (const [index, image] of decoded.entries()) {
24728
25014
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
24729
25015
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -24739,7 +25025,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
24739
25025
  editor: input.editor,
24740
25026
  protocol: input.protocol,
24741
25027
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
24742
- project: projectPath ? import_node_path40.default.basename(projectPath) : null,
25028
+ project: projectPath ? import_node_path41.default.basename(projectPath) : null,
24743
25029
  outputs: incoming.map((frame, index) => ({
24744
25030
  role: frame.role,
24745
25031
  basedOn: basedOnHash(entry, index),
@@ -24769,10 +25055,10 @@ function basedOnHash(entry, index) {
24769
25055
  async function replaceFile(file, bytes) {
24770
25056
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
24771
25057
  try {
24772
- await (0, import_promises30.writeFile)(tmp, bytes);
24773
- await (0, import_promises30.rename)(tmp, file);
25058
+ await (0, import_promises31.writeFile)(tmp, bytes);
25059
+ await (0, import_promises31.rename)(tmp, file);
24774
25060
  } finally {
24775
- await (0, import_promises30.rm)(tmp, { force: true });
25061
+ await (0, import_promises31.rm)(tmp, { force: true });
24776
25062
  }
24777
25063
  }
24778
25064
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -24782,10 +25068,10 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
24782
25068
 
24783
25069
  // src/pipeline/model-edit.ts
24784
25070
  var import_node_child_process3 = require("child_process");
24785
- var import_node_fs38 = require("fs");
24786
- var import_promises31 = require("fs/promises");
24787
- var import_node_path41 = __toESM(require("path"), 1);
24788
- var import_zod10 = require("zod");
25071
+ var import_node_fs39 = require("fs");
25072
+ var import_promises32 = require("fs/promises");
25073
+ var import_node_path42 = __toESM(require("path"), 1);
25074
+ var import_zod11 = require("zod");
24789
25075
 
24790
25076
  // src/jpeg.ts
24791
25077
  var ZIGZAG = [
@@ -25129,8 +25415,8 @@ function decodeScan(bytes, start, scan, frameComponents, hMax, vMax, width, heig
25129
25415
  }
25130
25416
  k += r;
25131
25417
  if (k > 63) break;
25132
- const z18 = ZIGZAG[k];
25133
- coefficients[z18] = extend(receive(s), s) * q[z18];
25418
+ const z19 = ZIGZAG[k];
25419
+ coefficients[z19] = extend(receive(s), s) * q[z19];
25134
25420
  k++;
25135
25421
  }
25136
25422
  if (blockRow >= c.blocksHigh || blockColumn >= c.blocksWide) return;
@@ -25166,27 +25452,27 @@ var MAX_MODELS = 200;
25166
25452
  var MAX_DEPTH = 8;
25167
25453
  var SKIPPED_DIRS = /* @__PURE__ */ new Set([HAND_EDIT_DIR, "node_modules"]);
25168
25454
  async function discoverModels(loaded, opts = {}) {
25169
- const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: import_node_path41.default.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
25455
+ 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));
25170
25456
  const seen = /* @__PURE__ */ new Set();
25171
25457
  const models = [];
25172
25458
  const walk2 = async (styleId, outDir, dir, depth) => {
25173
25459
  if (depth > MAX_DEPTH || models.length >= MAX_MODELS) return;
25174
25460
  let entries;
25175
25461
  try {
25176
- entries = await (0, import_promises31.readdir)(dir, { withFileTypes: true });
25462
+ entries = await (0, import_promises32.readdir)(dir, { withFileTypes: true });
25177
25463
  } catch {
25178
25464
  return;
25179
25465
  }
25180
25466
  entries.sort((a, b) => a.name.localeCompare(b.name));
25181
25467
  for (const entry of entries) {
25182
25468
  if (models.length >= MAX_MODELS) return;
25183
- const full = import_node_path41.default.join(dir, entry.name);
25469
+ const full = import_node_path42.default.join(dir, entry.name);
25184
25470
  if (entry.isDirectory()) {
25185
25471
  if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
25186
25472
  await walk2(styleId, outDir, full, depth + 1);
25187
25473
  } else if (entry.isFile() && entry.name.toLowerCase().endsWith(MODEL_EXTENSION) && !seen.has(full)) {
25188
25474
  seen.add(full);
25189
- models.push({ styleId, file: full, editFile: import_node_path41.default.join(outDir, HAND_EDIT_DIR, import_node_path41.default.relative(outDir, full)) });
25475
+ models.push({ styleId, file: full, editFile: import_node_path42.default.join(outDir, HAND_EDIT_DIR, import_node_path42.default.relative(outDir, full)) });
25190
25476
  }
25191
25477
  }
25192
25478
  };
@@ -25194,12 +25480,12 @@ async function discoverModels(loaded, opts = {}) {
25194
25480
  return models.sort((a, b) => a.styleId.localeCompare(b.styleId) || a.file.localeCompare(b.file));
25195
25481
  }
25196
25482
  async function findModel(loaded, portablePath) {
25197
- const wanted = import_node_path41.default.resolve(loaded.root, portablePath);
25483
+ const wanted = import_node_path42.default.resolve(loaded.root, portablePath);
25198
25484
  const model = (await discoverModels(loaded)).find((candidate) => candidate.file === wanted);
25199
25485
  if (!model) throw new ManifestEditError(`"${portablePath}" is not a model under one of this project's output folders`);
25200
25486
  return model;
25201
25487
  }
25202
- var stem = (editFile) => editFile.slice(0, -import_node_path41.default.extname(editFile).length);
25488
+ var stem = (editFile) => editFile.slice(0, -import_node_path42.default.extname(editFile).length);
25203
25489
  function modelCompanionPath(editFile) {
25204
25490
  return stem(editFile) + ".edit.json";
25205
25491
  }
@@ -25209,28 +25495,28 @@ function modelTextureProjectPath(editFile, image) {
25209
25495
  function modelExportPath(editFile) {
25210
25496
  return stem(editFile) + ".export" + MODEL_EXTENSION;
25211
25497
  }
25212
- var Sha = import_zod10.z.string().regex(/^[0-9a-f]{64}$/);
25213
- var ModelEditCompanionSchema = import_zod10.z.object({
25214
- version: import_zod10.z.literal(2),
25498
+ var Sha = import_zod11.z.string().regex(/^[0-9a-f]{64}$/);
25499
+ var ModelEditCompanionSchema = import_zod11.z.object({
25500
+ version: import_zod11.z.literal(2),
25215
25501
  /** What made the latest change: the bridge's editor identity, or `blender`. */
25216
- editor: import_zod10.z.string().min(1),
25217
- protocol: import_zod10.z.number().int().nonnegative(),
25218
- savedAt: import_zod10.z.string().datetime(),
25502
+ editor: import_zod11.z.string().min(1),
25503
+ protocol: import_zod11.z.number().int().nonnegative(),
25504
+ savedAt: import_zod11.z.string().datetime(),
25219
25505
  /** Basename of the layer file of the texture saved last, when one was kept. */
25220
- project: import_zod10.z.string().min(1).nullable(),
25506
+ project: import_zod11.z.string().min(1).nullable(),
25221
25507
  /** One entry: the model. `basedOn` is the hash of the model as built when the edit was made. */
25222
- outputs: import_zod10.z.array(import_zod10.z.object({ role: import_zod10.z.string().nullable(), basedOn: Sha.nullable(), sha256: Sha }).strict()).length(1),
25508
+ outputs: import_zod11.z.array(import_zod11.z.object({ role: import_zod11.z.string().nullable(), basedOn: Sha.nullable(), sha256: Sha }).strict()).length(1),
25223
25509
  /** Every texture this edit replaced, by image index. */
25224
- textures: import_zod10.z.array(
25225
- import_zod10.z.object({
25226
- image: import_zod10.z.number().int().nonnegative(),
25510
+ textures: import_zod11.z.array(
25511
+ import_zod11.z.object({
25512
+ image: import_zod11.z.number().int().nonnegative(),
25227
25513
  /** The material the texture belongs to, for reading the file without the model. */
25228
- name: import_zod10.z.string(),
25514
+ name: import_zod11.z.string(),
25229
25515
  sha256: Sha,
25230
- editor: import_zod10.z.string().min(1),
25231
- savedAt: import_zod10.z.string().datetime(),
25516
+ editor: import_zod11.z.string().min(1),
25517
+ savedAt: import_zod11.z.string().datetime(),
25232
25518
  /** Basename of its layer file, when one was kept. */
25233
- project: import_zod10.z.string().min(1).nullable()
25519
+ project: import_zod11.z.string().min(1).nullable()
25234
25520
  }).strict()
25235
25521
  ),
25236
25522
  /** Hash of the exported file the edit was last adopted from, so the same export is not offered twice. */
@@ -25238,7 +25524,7 @@ var ModelEditCompanionSchema = import_zod10.z.object({
25238
25524
  }).strict();
25239
25525
  async function readModelCompanion(editFile) {
25240
25526
  try {
25241
- return ModelEditCompanionSchema.parse(JSON.parse(await (0, import_promises31.readFile)(modelCompanionPath(editFile), "utf8")));
25527
+ return ModelEditCompanionSchema.parse(JSON.parse(await (0, import_promises32.readFile)(modelCompanionPath(editFile), "utf8")));
25242
25528
  } catch {
25243
25529
  return null;
25244
25530
  }
@@ -25248,19 +25534,19 @@ function modelEditStatus(companion, builtSha256) {
25248
25534
  return companion.outputs[0].basedOn === builtSha256 ? "edited" : "rebuilt-since";
25249
25535
  }
25250
25536
  async function replaceFile2(file, bytes) {
25251
- await (0, import_promises31.mkdir)(import_node_path41.default.dirname(file), { recursive: true });
25537
+ await (0, import_promises32.mkdir)(import_node_path42.default.dirname(file), { recursive: true });
25252
25538
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
25253
25539
  try {
25254
- await (0, import_promises31.writeFile)(tmp, bytes);
25255
- await (0, import_promises31.rename)(tmp, file);
25540
+ await (0, import_promises32.writeFile)(tmp, bytes);
25541
+ await (0, import_promises32.rename)(tmp, file);
25256
25542
  } finally {
25257
- await (0, import_promises31.rm)(tmp, { force: true });
25543
+ await (0, import_promises32.rm)(tmp, { force: true });
25258
25544
  }
25259
25545
  }
25260
25546
  async function readModel(file, what) {
25261
25547
  let bytes;
25262
25548
  try {
25263
- bytes = await (0, import_promises31.readFile)(file);
25549
+ bytes = await (0, import_promises32.readFile)(file);
25264
25550
  } catch {
25265
25551
  throw new ManifestEditError(`${what} is not on disk at ${file}`);
25266
25552
  }
@@ -25287,7 +25573,7 @@ async function saveModelTexture(model, input) {
25287
25573
  throw new ManifestEditError(`the texture is not a valid PNG: ${error instanceof Error ? error.message : String(error)}`);
25288
25574
  }
25289
25575
  const original = await readModel(model.file, "the model");
25290
- const created = !(0, import_node_fs38.existsSync)(model.editFile);
25576
+ const created = !(0, import_node_fs39.existsSync)(model.editFile);
25291
25577
  const base = created ? original : await readModel(model.editFile, "the model's edit");
25292
25578
  let current;
25293
25579
  try {
@@ -25309,7 +25595,7 @@ async function saveModelTexture(model, input) {
25309
25595
  sha256: sha256(input.png),
25310
25596
  editor: input.editor,
25311
25597
  savedAt,
25312
- project: projectPath ? import_node_path41.default.basename(projectPath) : null
25598
+ project: projectPath ? import_node_path42.default.basename(projectPath) : null
25313
25599
  };
25314
25600
  const companion = {
25315
25601
  version: 2,
@@ -25332,7 +25618,7 @@ async function adoptModelExport(model, opts = {}) {
25332
25618
  const mode2 = opts.mode ?? "textures";
25333
25619
  const exported = await readModel(from, "the exported model");
25334
25620
  const original = await readModel(model.file, "the model");
25335
- const created = !(0, import_node_fs38.existsSync)(model.editFile);
25621
+ const created = !(0, import_node_fs39.existsSync)(model.editFile);
25336
25622
  const savedAt = (opts.now ?? /* @__PURE__ */ new Date()).toISOString();
25337
25623
  const editor = opts.editor ?? "blender";
25338
25624
  const taken = [];
@@ -25401,9 +25687,9 @@ async function adoptModelExport(model, opts = {}) {
25401
25687
  await replaceFile2(companionPath, JSON.stringify(companion, null, 2) + "\n");
25402
25688
  return { editFile: model.editFile, companionPath, companion, created, mode: mode2, taken };
25403
25689
  }
25404
- function blenderCommand(env = process.env, platform = process.platform, exists = import_node_fs38.existsSync, list = (dir) => {
25690
+ function blenderCommand(env = process.env, platform = process.platform, exists = import_node_fs39.existsSync, list = (dir) => {
25405
25691
  try {
25406
- return (0, import_node_fs38.readdirSync)(dir);
25692
+ return (0, import_node_fs39.readdirSync)(dir);
25407
25693
  } catch {
25408
25694
  return [];
25409
25695
  }
@@ -25413,16 +25699,16 @@ function blenderCommand(env = process.env, platform = process.platform, exists =
25413
25699
  const candidates = [];
25414
25700
  if (platform === "darwin") {
25415
25701
  candidates.push("/Applications/Blender.app/Contents/MacOS/Blender");
25416
- if (env.HOME) candidates.push(import_node_path41.default.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
25702
+ if (env.HOME) candidates.push(import_node_path42.default.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
25417
25703
  } else if (platform === "win32") {
25418
25704
  for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((value) => Boolean(value))) {
25419
- const foundation = import_node_path41.default.win32.join(root, "Blender Foundation");
25705
+ const foundation = import_node_path42.default.win32.join(root, "Blender Foundation");
25420
25706
  const versions = list(foundation).filter((name) => /^Blender/i.test(name)).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
25421
- for (const version of versions) candidates.push(import_node_path41.default.win32.join(foundation, version, "blender.exe"));
25707
+ for (const version of versions) candidates.push(import_node_path42.default.win32.join(foundation, version, "blender.exe"));
25422
25708
  }
25423
25709
  } else {
25424
25710
  candidates.push("/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender", "/var/lib/flatpak/exports/bin/org.blender.Blender");
25425
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(import_node_path41.default.join(dir, "blender"));
25711
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(import_node_path42.default.join(dir, "blender"));
25426
25712
  }
25427
25713
  const found = candidates.find((candidate) => exists(candidate));
25428
25714
  return found ? [found] : null;
@@ -25455,7 +25741,7 @@ function openInBlender(model, opts = {}) {
25455
25741
  "Blender was not found in its usual place; set PIXELKILN_BLENDER to the program (for example PIXELKILN_BLENDER=/Applications/Blender.app/Contents/MacOS/Blender) and start the gallery again"
25456
25742
  );
25457
25743
  }
25458
- const file = (0, import_node_fs38.existsSync)(model.editFile) ? model.editFile : model.file;
25744
+ const file = (0, import_node_fs39.existsSync)(model.editFile) ? model.editFile : model.file;
25459
25745
  const [program, ...rest] = command;
25460
25746
  const args = [...rest, ...blenderArguments(file, modelExportPath(model.editFile))];
25461
25747
  const launch = opts.launch ?? ((bin, argv) => {
@@ -25465,14 +25751,14 @@ function openInBlender(model, opts = {}) {
25465
25751
  child.unref();
25466
25752
  });
25467
25753
  launch(program, args);
25468
- return `${command.join(" ")} (${import_node_path41.default.basename(file)})`;
25754
+ return `${command.join(" ")} (${import_node_path42.default.basename(file)})`;
25469
25755
  }
25470
25756
 
25471
25757
  // src/pipeline/model-normals.ts
25472
25758
  var import_node_crypto9 = require("crypto");
25473
- var import_node_fs39 = require("fs");
25474
- var import_promises32 = require("fs/promises");
25475
- var import_node_path42 = __toESM(require("path"), 1);
25759
+ var import_node_fs40 = require("fs");
25760
+ var import_promises33 = require("fs/promises");
25761
+ var import_node_path43 = __toESM(require("path"), 1);
25476
25762
  var MODEL_NORMAL_SOURCES = ["texture", "views", "sprites"];
25477
25763
  var TILE_MAX = 512;
25478
25764
  function decodeImage(bytes) {
@@ -25516,18 +25802,18 @@ function localMatrix(node) {
25516
25802
  const [tx, ty, tz] = node.translation ?? [0, 0, 0];
25517
25803
  const [qx, qy, qz, qw] = node.rotation ?? [0, 0, 0, 1];
25518
25804
  const [sx, sy, sz] = node.scale ?? [1, 1, 1];
25519
- const x = qx, y = qy, z18 = qz, w = qw;
25805
+ const x = qx, y = qy, z19 = qz, w = qw;
25520
25806
  return Float64Array.from([
25521
- (1 - 2 * (y * y + z18 * z18)) * sx,
25522
- 2 * (x * y + z18 * w) * sx,
25523
- 2 * (x * z18 - y * w) * sx,
25807
+ (1 - 2 * (y * y + z19 * z19)) * sx,
25808
+ 2 * (x * y + z19 * w) * sx,
25809
+ 2 * (x * z19 - y * w) * sx,
25524
25810
  0,
25525
- 2 * (x * y - z18 * w) * sy,
25526
- (1 - 2 * (x * x + z18 * z18)) * sy,
25527
- 2 * (y * z18 + x * w) * sy,
25811
+ 2 * (x * y - z19 * w) * sy,
25812
+ (1 - 2 * (x * x + z19 * z19)) * sy,
25813
+ 2 * (y * z19 + x * w) * sy,
25528
25814
  0,
25529
- 2 * (x * z18 + y * w) * sz,
25530
- 2 * (y * z18 - x * w) * sz,
25815
+ 2 * (x * z19 + y * w) * sz,
25816
+ 2 * (y * z19 - x * w) * sz,
25531
25817
  (1 - 2 * (x * x + y * y)) * sz,
25532
25818
  0,
25533
25819
  tx,
@@ -25564,13 +25850,13 @@ function poseNodes(document2, pose) {
25564
25850
  const posed = /* @__PURE__ */ new Map();
25565
25851
  for (const channel of animation.channels) {
25566
25852
  const node = channel.target.node;
25567
- const path53 = channel.target.path;
25568
- if (node === void 0 || !["translation", "rotation", "scale"].includes(path53)) continue;
25853
+ const path54 = channel.target.path;
25854
+ if (node === void 0 || !["translation", "rotation", "scale"].includes(path54)) continue;
25569
25855
  const sampler = animation.samplers[channel.sampler];
25570
25856
  if (!sampler) continue;
25571
25857
  const times = readAccessor(document2, sampler.input).data;
25572
25858
  const values = readAccessor(document2, sampler.output);
25573
- const width = path53 === "rotation" ? 4 : 3;
25859
+ const width = path54 === "rotation" ? 4 : 3;
25574
25860
  const cubic = sampler.interpolation === "CUBICSPLINE";
25575
25861
  const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
25576
25862
  const last = times.length - 1;
@@ -25582,16 +25868,16 @@ function poseNodes(document2, pose) {
25582
25868
  const span = times[key3 + 1] - times[key3];
25583
25869
  const f = span > 0 ? (time - times[key3]) / span : 0;
25584
25870
  const next = valueAt(key3 + 1);
25585
- const sign = path53 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
25871
+ const sign = path54 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
25586
25872
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
25587
25873
  }
25588
- if (path53 === "rotation") {
25874
+ if (path54 === "rotation") {
25589
25875
  const length = Math.hypot(...value) || 1;
25590
25876
  value = value.map((v) => v / length);
25591
25877
  }
25592
25878
  const base = posed.get(node) ?? { ...document2.json.nodes?.[node] ?? {} };
25593
25879
  if (base.matrix) delete base.matrix;
25594
- base[path53] = value;
25880
+ base[path54] = value;
25595
25881
  posed.set(node, base);
25596
25882
  }
25597
25883
  return posed;
@@ -25805,9 +26091,9 @@ function texelSurface(primitives, document2, image, width, height) {
25805
26091
  return surface;
25806
26092
  }
25807
26093
  var decodeNormal = (pixels, at2) => {
25808
- const x = pixels[at2] / 127.5 - 1, y = pixels[at2 + 1] / 127.5 - 1, z18 = pixels[at2 + 2] / 127.5 - 1;
25809
- const length = Math.hypot(x, y, z18) || 1;
25810
- return [x / length, y / length, z18 / length];
26094
+ const x = pixels[at2] / 127.5 - 1, y = pixels[at2 + 1] / 127.5 - 1, z19 = pixels[at2 + 2] / 127.5 - 1;
26095
+ const length = Math.hypot(x, y, z19) || 1;
26096
+ return [x / length, y / length, z19 / length];
25811
26097
  };
25812
26098
  function textureTiles(base, surface) {
25813
26099
  const { width, height } = surface;
@@ -25873,12 +26159,12 @@ function basisOf(turn, tilt) {
25873
26159
  toward: [level[0] * Math.cos(e), Math.sin(e), level[2] * Math.cos(e)]
25874
26160
  };
25875
26161
  }
25876
- var dot = (v, x, y, z18) => v[0] * x + v[1] * y + v[2] * z18;
25877
- function project(camera, basis, x, y, z18) {
26162
+ var dot = (v, x, y, z19) => v[0] * x + v[1] * y + v[2] * z19;
26163
+ function project(camera, basis, x, y, z19) {
25878
26164
  return [
25879
- (dot(basis.right, x, y, z18) - camera.centreX) * camera.scale + camera.offsetX,
25880
- camera.offsetY - (dot(basis.up, x, y, z18) - camera.centreY) * camera.scale,
25881
- dot(basis.toward, x, y, z18)
26165
+ (dot(basis.right, x, y, z19) - camera.centreX) * camera.scale + camera.offsetX,
26166
+ camera.offsetY - (dot(basis.up, x, y, z19) - camera.centreY) * camera.scale,
26167
+ dot(basis.toward, x, y, z19)
25882
26168
  ];
25883
26169
  }
25884
26170
  function extent(primitives, basis) {
@@ -25928,10 +26214,10 @@ function drawView(document2, primitives, camera, textures) {
25928
26214
  const l1 = ((c[1] - a[1]) * (px - c[0]) + (a[0] - c[0]) * (py - c[1])) / den;
25929
26215
  const l2 = 1 - l0 - l1;
25930
26216
  if (l0 < 0 || l1 < 0 || l2 < 0) continue;
25931
- const z18 = l0 * a[2] + l1 * b[2] + l2 * c[2];
26217
+ const z19 = l0 * a[2] + l1 * b[2] + l2 * c[2];
25932
26218
  const at3 = y * width + x;
25933
- if (z18 <= depth[at3]) continue;
25934
- depth[at3] = z18;
26219
+ if (z19 <= depth[at3]) continue;
26220
+ depth[at3] = z19;
25935
26221
  let rgb = flat;
25936
26222
  if (texture && uv) {
25937
26223
  const u = l0 * uv[corners[0] * 2] + l1 * uv[corners[1] * 2] + l2 * uv[corners[2] * 2];
@@ -26061,10 +26347,10 @@ function detailFromViews(surface, views, maps, opts = {}) {
26061
26347
  const basis = bases[index];
26062
26348
  const facing = dot(basis.toward, nx, ny, nz);
26063
26349
  if (facing < 0.15) return;
26064
- const [sx, sy, z19] = project(camera, basis, px, py, pz);
26350
+ const [sx, sy, z20] = project(camera, basis, px, py, pz);
26065
26351
  const ix = Math.floor(sx), iy = Math.floor(sy);
26066
26352
  if (ix < 0 || iy < 0 || ix >= camera.width || iy >= camera.height) return;
26067
- if (view.depth[iy * camera.width + ix] - z19 > 1.5 / camera.scale) return;
26353
+ if (view.depth[iy * camera.width + ix] - z20 > 1.5 / camera.scale) return;
26068
26354
  if (view.use && !view.use[iy * camera.width + ix]) return;
26069
26355
  const map = decoded[index];
26070
26356
  if (map.pixels[(iy * camera.width + ix) * 4 + 3] < 128) return;
@@ -26101,9 +26387,9 @@ function detailFromViews(surface, views, maps, opts = {}) {
26101
26387
  total += weight;
26102
26388
  });
26103
26389
  if (!(total > 0)) continue;
26104
- const x = sum[texel * 3] / total, y = sum[texel * 3 + 1] / total, z18 = Math.max(0.05, sum[texel * 3 + 2] / total);
26105
- const length = Math.hypot(x, y, z18);
26106
- field.normal.set([x / length, y / length, z18 / length], texel * 3);
26390
+ const x = sum[texel * 3] / total, y = sum[texel * 3 + 1] / total, z19 = Math.max(0.05, sum[texel * 3 + 2] / total);
26391
+ const length = Math.hypot(x, y, z19);
26392
+ field.normal.set([x / length, y / length, z19 / length], texel * 3);
26107
26393
  field.weight[texel] = 1;
26108
26394
  }
26109
26395
  return field;
@@ -26156,23 +26442,23 @@ function applyDetail(existing, field, opts = {}) {
26156
26442
  if (!field.weight[texel]) continue;
26157
26443
  let dx = field.normal[texel * 3] * amount, dy = field.normal[texel * 3 + 1] * amount;
26158
26444
  const dz = field.normal[texel * 3 + 2];
26159
- let x, y, z18;
26445
+ let x, y, z19;
26160
26446
  if (opts.replace) {
26161
26447
  x = dx;
26162
26448
  y = dy;
26163
- z18 = dz;
26449
+ z19 = dz;
26164
26450
  } else {
26165
26451
  const [bx, by, bz] = decodeNormal(base.pixels, texel * 4);
26166
26452
  x = bx + dx;
26167
26453
  y = by + dy;
26168
- z18 = bz * dz;
26454
+ z19 = bz * dz;
26169
26455
  }
26170
- const length = Math.hypot(x, y, z18) || 1;
26456
+ const length = Math.hypot(x, y, z19) || 1;
26171
26457
  dx = x / length;
26172
26458
  dy = y / length;
26173
26459
  pixels[texel * 4] = Math.round((dx * 0.5 + 0.5) * 255);
26174
26460
  pixels[texel * 4 + 1] = Math.round((dy * 0.5 + 0.5) * 255);
26175
- pixels[texel * 4 + 2] = Math.round((Math.max(0, z18 / length) * 0.5 + 0.5) * 255);
26461
+ pixels[texel * 4 + 2] = Math.round((Math.max(0, z19 / length) * 0.5 + 0.5) * 255);
26176
26462
  pixels[texel * 4 + 3] = 255;
26177
26463
  }
26178
26464
  return { width, height, pixels };
@@ -26201,9 +26487,9 @@ function modelSpritesDir(modelFile) {
26201
26487
  return modelFile.replace(/\.glb$/i, "") + ".sprites";
26202
26488
  }
26203
26489
  async function readSpriteFolder(dir) {
26204
- const folder = (0, import_node_fs39.existsSync)(import_node_path42.default.join(dir, "rotations")) ? import_node_path42.default.join(dir, "rotations") : dir;
26205
- const names = (await (0, import_promises32.readdir)(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
26206
- return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await (0, import_promises32.readFile)(import_node_path42.default.join(folder, name)), file: import_node_path42.default.join(folder, name) })));
26490
+ const folder = (0, import_node_fs40.existsSync)(import_node_path43.default.join(dir, "rotations")) ? import_node_path43.default.join(dir, "rotations") : dir;
26491
+ const names = (await (0, import_promises33.readdir)(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
26492
+ 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) })));
26207
26493
  }
26208
26494
  function modelNormalDir(editFile) {
26209
26495
  return editFile.replace(/\.glb$/i, "") + ".normal-map";
@@ -26213,8 +26499,8 @@ function requestKey(png, options) {
26213
26499
  return (0, import_node_crypto9.createHash)("sha256").update(png).update(asked).digest("hex").slice(0, 16);
26214
26500
  }
26215
26501
  async function prepare(model, opts) {
26216
- const fromEdit = (0, import_node_fs39.existsSync)(model.editFile);
26217
- const document2 = parseGlb(await (0, import_promises32.readFile)(fromEdit ? model.editFile : model.file));
26502
+ const fromEdit = (0, import_node_fs40.existsSync)(model.editFile);
26503
+ const document2 = parseGlb(await (0, import_promises33.readFile)(fromEdit ? model.editFile : model.file));
26218
26504
  const summary = describeGlb(document2);
26219
26505
  const normalImages = summary.images.filter((image) => image.roles.includes("normal"));
26220
26506
  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");
@@ -26223,14 +26509,14 @@ async function prepare(model, opts) {
26223
26509
  if (!normalImages.some((image) => image.index === index)) throw new Error(`image ${index} is not one of the model's normal maps`);
26224
26510
  }
26225
26511
  const primitives = restPrimitives(document2, opts.pose);
26226
- const dir = import_node_path42.default.join(modelNormalDir(model.editFile), opts.source);
26512
+ const dir = import_node_path43.default.join(modelNormalDir(model.editFile), opts.source);
26227
26513
  const surfaces = /* @__PURE__ */ new Map();
26228
26514
  const tiles = /* @__PURE__ */ new Map();
26229
26515
  const calls = [];
26230
26516
  const images = [];
26231
26517
  const call = (label, png) => {
26232
- const cache = import_node_path42.default.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
26233
- calls.push({ label, png, cache, cached: (0, import_node_fs39.existsSync)(cache) });
26518
+ const cache = import_node_path43.default.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
26519
+ calls.push({ label, png, cache, cached: (0, import_node_fs40.existsSync)(cache) });
26234
26520
  };
26235
26521
  for (const index of wanted) {
26236
26522
  const summaryImage = summary.images[index];
@@ -26298,15 +26584,15 @@ async function prepare(model, opts) {
26298
26584
  }
26299
26585
  async function planModelNormals(model, opts) {
26300
26586
  const { plan } = await prepare(model, opts);
26301
- await (0, import_promises32.mkdir)(plan.dir, { recursive: true });
26302
- for (const entry of plan.calls) await (0, import_promises32.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
26303
- for (const fit of plan.fits ?? []) await (0, import_promises32.writeFile)(import_node_path42.default.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
26587
+ await (0, import_promises33.mkdir)(plan.dir, { recursive: true });
26588
+ for (const entry of plan.calls) await (0, import_promises33.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
26589
+ 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);
26304
26590
  return plan;
26305
26591
  }
26306
26592
  async function generateModelNormals(model, opts, mapper, hooks = {}) {
26307
26593
  const prepared = await prepare(model, opts);
26308
26594
  const { plan, document: document2 } = prepared;
26309
- await (0, import_promises32.mkdir)(plan.dir, { recursive: true });
26595
+ await (0, import_promises33.mkdir)(plan.dir, { recursive: true });
26310
26596
  const request = {
26311
26597
  ...opts.mode ? { mode: opts.mode } : {},
26312
26598
  ...opts.kind ? { kind: opts.kind } : {},
@@ -26318,14 +26604,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
26318
26604
  let sent = 0;
26319
26605
  for (const entry of plan.calls) {
26320
26606
  hooks.onCall?.(entry.label, entry.cached);
26321
- await (0, import_promises32.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
26607
+ await (0, import_promises33.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
26322
26608
  if (entry.cached) {
26323
- answers.push(await (0, import_promises32.readFile)(entry.cache));
26609
+ answers.push(await (0, import_promises33.readFile)(entry.cache));
26324
26610
  continue;
26325
26611
  }
26326
26612
  const answer = await mapper(entry.png, request);
26327
26613
  sent++;
26328
- await (0, import_promises32.writeFile)(entry.cache, answer);
26614
+ await (0, import_promises33.writeFile)(entry.cache, answer);
26329
26615
  answers.push(answer);
26330
26616
  }
26331
26617
  let result = null;
@@ -26343,14 +26629,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
26343
26629
  field = detailFromViews(surface, prepared.views, answers);
26344
26630
  }
26345
26631
  bleed(field);
26346
- const detail = import_node_path42.default.join(plan.dir, `image-${image}.detail.png`);
26347
- await (0, import_promises32.writeFile)(detail, encodeImage(fieldImage(field)));
26632
+ const detail = import_node_path43.default.join(plan.dir, `image-${image}.detail.png`);
26633
+ await (0, import_promises33.writeFile)(detail, encodeImage(fieldImage(field)));
26348
26634
  details.push(detail);
26349
- const basePath = import_node_path42.default.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
26635
+ const basePath = import_node_path43.default.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
26350
26636
  const record = companion?.textures.find((entry) => entry.image === image);
26351
- const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && (0, import_node_fs39.existsSync)(basePath);
26352
- const existing = ours ? decodeImage(await (0, import_promises32.readFile)(basePath)) : decodeImage(glbImageBytes(document2, image).bytes);
26353
- if (!ours) await (0, import_promises32.writeFile)(basePath, encodeImage(existing));
26637
+ const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && (0, import_node_fs40.existsSync)(basePath);
26638
+ const existing = ours ? decodeImage(await (0, import_promises33.readFile)(basePath)) : decodeImage(glbImageBytes(document2, image).bytes);
26639
+ if (!ours) await (0, import_promises33.writeFile)(basePath, encodeImage(existing));
26354
26640
  const png = encodeImage(applyDetail(existing, field, opts));
26355
26641
  result = await saveModelTexture(model, {
26356
26642
  image,
@@ -26379,7 +26665,7 @@ function modelNormalMapper(client2) {
26379
26665
  // src/gallery/models.ts
26380
26666
  var MODEL_FILE_TYPE = "model/gltf-binary";
26381
26667
  async function describeFile(media, mediaId, root, file, bytes) {
26382
- const info = await (0, import_promises33.stat)(file);
26668
+ const info = await (0, import_promises34.stat)(file);
26383
26669
  const id = mediaId(file);
26384
26670
  const hash = sha256(bytes);
26385
26671
  media.set(id, { path: file, contentType: MODEL_FILE_TYPE });
@@ -26398,11 +26684,11 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
26398
26684
  for (const model of await discoverModels(loaded, opts)) {
26399
26685
  let bytes;
26400
26686
  try {
26401
- bytes = await (0, import_promises33.readFile)(model.file);
26687
+ bytes = await (0, import_promises34.readFile)(model.file);
26402
26688
  } catch {
26403
26689
  continue;
26404
26690
  }
26405
- const outDir = import_node_path43.default.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
26691
+ const outDir = import_node_path44.default.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
26406
26692
  let summary = null;
26407
26693
  let error = null;
26408
26694
  if (bytes.length > MAX_MODEL_BYTES) error = `the file is ${bytes.length} bytes; models over ${MAX_MODEL_BYTES} are listed but not opened`;
@@ -26416,16 +26702,16 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
26416
26702
  const file = await describeFile(media, mediaId, root, model.file, bytes);
26417
26703
  let edit = null;
26418
26704
  let adoptedExport = null;
26419
- if ((0, import_node_fs40.existsSync)(model.editFile)) {
26705
+ if ((0, import_node_fs41.existsSync)(model.editFile)) {
26420
26706
  try {
26421
- const editBytes = await (0, import_promises33.readFile)(model.editFile);
26707
+ const editBytes = await (0, import_promises34.readFile)(model.editFile);
26422
26708
  const described = await describeFile(media, mediaId, root, model.editFile, editBytes);
26423
26709
  const companion = await readModelCompanion(model.editFile);
26424
26710
  adoptedExport = companion?.adoptedExport ?? null;
26425
26711
  const textures = (companion?.textures ?? []).map((texture) => {
26426
26712
  const projectPath = texture.project ? modelTextureProjectPath(model.editFile, texture.image) : null;
26427
26713
  let projectUrl = null;
26428
- if (projectPath && (0, import_node_fs40.existsSync)(projectPath)) {
26714
+ if (projectPath && (0, import_node_fs41.existsSync)(projectPath)) {
26429
26715
  const id = mediaId(projectPath);
26430
26716
  media.set(id, { path: projectPath, contentType: "application/octet-stream" });
26431
26717
  projectUrl = `/media/${id}?v=${texture.sha256.slice(0, 24)}`;
@@ -26454,26 +26740,26 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
26454
26740
  const exportFile = modelExportPath(model.editFile);
26455
26741
  let exportWaiting = null;
26456
26742
  try {
26457
- const info = await (0, import_promises33.stat)(exportFile);
26458
- if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await (0, import_promises33.readFile)(exportFile)) !== adoptedExport) {
26743
+ const info = await (0, import_promises34.stat)(exportFile);
26744
+ if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await (0, import_promises34.readFile)(exportFile)) !== adoptedExport) {
26459
26745
  exportWaiting = { bytes: info.size, modifiedAt: info.mtime.toISOString() };
26460
26746
  }
26461
26747
  } catch {
26462
26748
  }
26463
26749
  const spritesDir = modelSpritesDir(model.file);
26464
26750
  let sprites = null;
26465
- if ((0, import_node_fs40.existsSync)(spritesDir)) {
26751
+ if ((0, import_node_fs41.existsSync)(spritesDir)) {
26466
26752
  try {
26467
26753
  sprites = { path: portableOutputPath(spritesDir, root), directions: (await readSpriteFolder(spritesDir)).map((sprite) => sprite.direction) };
26468
26754
  } catch {
26469
26755
  }
26470
26756
  }
26471
- const relative = import_node_path43.default.relative(outDir, model.file).split(import_node_path43.default.sep).join("/");
26757
+ const relative = import_node_path44.default.relative(outDir, model.file).split(import_node_path44.default.sep).join("/");
26472
26758
  models.push({
26473
26759
  id: `model:${model.styleId}/${relative}`,
26474
26760
  project: null,
26475
26761
  styleId: model.styleId,
26476
- name: import_node_path43.default.basename(model.file, import_node_path43.default.extname(model.file)),
26762
+ name: import_node_path44.default.basename(model.file, import_node_path44.default.extname(model.file)),
26477
26763
  file,
26478
26764
  summary,
26479
26765
  error,
@@ -26487,41 +26773,41 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
26487
26773
  }
26488
26774
  return models;
26489
26775
  }
26490
- var Base64 = import_zod11.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
26491
- var ModelRequestSchema = import_zod11.z.discriminatedUnion("action", [
26492
- import_zod11.z.object({
26493
- action: import_zod11.z.literal("save-model-texture"),
26494
- project: import_zod11.z.string().min(1).optional(),
26776
+ var Base64 = import_zod12.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
26777
+ var ModelRequestSchema = import_zod12.z.discriminatedUnion("action", [
26778
+ import_zod12.z.object({
26779
+ action: import_zod12.z.literal("save-model-texture"),
26780
+ project: import_zod12.z.string().min(1).optional(),
26495
26781
  /** Manifest-relative path of the model as built. */
26496
- path: import_zod11.z.string().min(1).max(1024),
26497
- image: import_zod11.z.number().int().nonnegative(),
26782
+ path: import_zod12.z.string().min(1).max(1024),
26783
+ image: import_zod12.z.number().int().nonnegative(),
26498
26784
  png: Base64.min(1),
26499
26785
  pxo: Base64.optional(),
26500
- editor: import_zod11.z.string().min(1).max(200),
26501
- protocol: import_zod11.z.number().int().positive()
26786
+ editor: import_zod12.z.string().min(1).max(200),
26787
+ protocol: import_zod12.z.number().int().positive()
26502
26788
  }).strict(),
26503
- import_zod11.z.object({
26504
- action: import_zod11.z.literal("adopt-model-export"),
26505
- project: import_zod11.z.string().min(1).optional(),
26506
- path: import_zod11.z.string().min(1).max(1024),
26507
- mode: import_zod11.z.enum(["textures", "whole"]).optional()
26789
+ import_zod12.z.object({
26790
+ action: import_zod12.z.literal("adopt-model-export"),
26791
+ project: import_zod12.z.string().min(1).optional(),
26792
+ path: import_zod12.z.string().min(1).max(1024),
26793
+ mode: import_zod12.z.enum(["textures", "whole"]).optional()
26508
26794
  }).strict(),
26509
- import_zod11.z.object({
26510
- action: import_zod11.z.literal("generate-model-normals"),
26511
- project: import_zod11.z.string().min(1).optional(),
26512
- path: import_zod11.z.string().min(1).max(1024),
26513
- source: import_zod11.z.enum(MODEL_NORMAL_SOURCES),
26795
+ import_zod12.z.object({
26796
+ action: import_zod12.z.literal("generate-model-normals"),
26797
+ project: import_zod12.z.string().min(1).optional(),
26798
+ path: import_zod12.z.string().min(1).max(1024),
26799
+ source: import_zod12.z.enum(MODEL_NORMAL_SOURCES),
26514
26800
  /** Normal map images; all of the model's when left out. */
26515
- images: import_zod11.z.array(import_zod11.z.number().int().nonnegative()).max(64).optional(),
26516
- amount: import_zod11.z.number().min(0).max(2).optional(),
26517
- replace: import_zod11.z.boolean().optional(),
26801
+ images: import_zod12.z.array(import_zod12.z.number().int().nonnegative()).max(64).optional(),
26802
+ amount: import_zod12.z.number().min(0).max(2).optional(),
26803
+ replace: import_zod12.z.boolean().optional(),
26518
26804
  /** The price the person agreed to on the page; a run that would cost more is refused. */
26519
- maxCost: import_zod11.z.number().nonnegative().max(100)
26805
+ maxCost: import_zod12.z.number().nonnegative().max(100)
26520
26806
  }).strict(),
26521
- import_zod11.z.object({
26522
- action: import_zod11.z.literal("open-model"),
26523
- project: import_zod11.z.string().min(1).optional(),
26524
- path: import_zod11.z.string().min(1).max(1024)
26807
+ import_zod12.z.object({
26808
+ action: import_zod12.z.literal("open-model"),
26809
+ project: import_zod12.z.string().min(1).optional(),
26810
+ path: import_zod12.z.string().min(1).max(1024)
26525
26811
  }).strict()
26526
26812
  ]);
26527
26813
  var MODEL_ACTIONS = ["save-model-texture", "adopt-model-export", "generate-model-normals", "open-model"];
@@ -26568,23 +26854,23 @@ function blenderAvailable() {
26568
26854
  }
26569
26855
 
26570
26856
  // src/workspace.ts
26571
- var import_promises34 = require("fs/promises");
26572
- var import_node_fs41 = require("fs");
26573
- var import_node_path44 = __toESM(require("path"), 1);
26574
- var import_zod12 = require("zod");
26575
- var WorkspaceProjectSchema = import_zod12.z.object({
26576
- id: import_zod12.z.string().min(1),
26857
+ var import_promises35 = require("fs/promises");
26858
+ var import_node_fs42 = require("fs");
26859
+ var import_node_path45 = __toESM(require("path"), 1);
26860
+ var import_zod13 = require("zod");
26861
+ var WorkspaceProjectSchema = import_zod13.z.object({
26862
+ id: import_zod13.z.string().min(1),
26577
26863
  /** Manifest path, relative to the catalog file's own directory. */
26578
- manifest: import_zod12.z.string().min(1),
26864
+ manifest: import_zod13.z.string().min(1),
26579
26865
  /** Lockfile path, relative to the catalog file's own directory. */
26580
- lock: import_zod12.z.string().min(1),
26581
- provider: import_zod12.z.string().min(1).default("pixellab"),
26866
+ lock: import_zod13.z.string().min(1),
26867
+ provider: import_zod13.z.string().min(1).default("pixellab"),
26582
26868
  /** Free-form label for a shared account, e.g. distinguishing sandboxes. */
26583
- account: import_zod12.z.string().optional()
26869
+ account: import_zod13.z.string().optional()
26584
26870
  }).strict();
26585
- var WorkspaceSchema = import_zod12.z.object({
26586
- version: import_zod12.z.literal(1),
26587
- projects: import_zod12.z.array(WorkspaceProjectSchema).default([])
26871
+ var WorkspaceSchema = import_zod13.z.object({
26872
+ version: import_zod13.z.literal(1),
26873
+ projects: import_zod13.z.array(WorkspaceProjectSchema).default([])
26588
26874
  }).strict();
26589
26875
  function parseWorkspace(raw) {
26590
26876
  const parsed = WorkspaceSchema.safeParse(raw);
@@ -26595,10 +26881,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
26595
26881
  );
26596
26882
  }
26597
26883
  async function loadWorkspace(workspacePath) {
26598
- if (!(0, import_node_fs41.existsSync)(workspacePath)) return { version: 1, projects: [] };
26884
+ if (!(0, import_node_fs42.existsSync)(workspacePath)) return { version: 1, projects: [] };
26599
26885
  let raw;
26600
26886
  try {
26601
- raw = JSON.parse(await (0, import_promises34.readFile)(workspacePath, "utf8"));
26887
+ raw = JSON.parse(await (0, import_promises35.readFile)(workspacePath, "utf8"));
26602
26888
  } catch (err) {
26603
26889
  throw new ProjectError(
26604
26890
  `Workspace catalog at ${workspacePath} is malformed:
@@ -26612,22 +26898,22 @@ async function saveWorkspace(workspacePath, ws) {
26612
26898
  version: 1,
26613
26899
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
26614
26900
  };
26615
- await (0, import_promises34.mkdir)(import_node_path44.default.dirname(import_node_path44.default.resolve(workspacePath)), { recursive: true });
26901
+ await (0, import_promises35.mkdir)(import_node_path45.default.dirname(import_node_path45.default.resolve(workspacePath)), { recursive: true });
26616
26902
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
26617
26903
  try {
26618
- await (0, import_promises34.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
26619
- await (0, import_promises34.rename)(tmp, workspacePath);
26904
+ await (0, import_promises35.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
26905
+ await (0, import_promises35.rename)(tmp, workspacePath);
26620
26906
  } finally {
26621
- await (0, import_promises34.rm)(tmp, { force: true });
26907
+ await (0, import_promises35.rm)(tmp, { force: true });
26622
26908
  }
26623
26909
  }
26624
26910
  function toPortablePath(dir, absolute) {
26625
- return import_node_path44.default.relative(dir, absolute).split(import_node_path44.default.sep).join("/");
26911
+ return import_node_path45.default.relative(dir, absolute).split(import_node_path45.default.sep).join("/");
26626
26912
  }
26627
26913
  function resolveProject(dir, project2) {
26628
26914
  return {
26629
- manifestPath: import_node_path44.default.resolve(dir, project2.manifest.split("/").join(import_node_path44.default.sep)),
26630
- lockPath: import_node_path44.default.resolve(dir, project2.lock.split("/").join(import_node_path44.default.sep))
26915
+ manifestPath: import_node_path45.default.resolve(dir, project2.manifest.split("/").join(import_node_path45.default.sep)),
26916
+ lockPath: import_node_path45.default.resolve(dir, project2.lock.split("/").join(import_node_path45.default.sep))
26631
26917
  };
26632
26918
  }
26633
26919
  function validateWorkspace(ws, dir) {
@@ -26640,21 +26926,21 @@ function validateWorkspace(ws, dir) {
26640
26926
  const { manifestPath, lockPath } = resolveProject(dir, project2);
26641
26927
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project2.id]);
26642
26928
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project2.id]);
26643
- if (import_node_path44.default.isAbsolute(project2.manifest) || import_node_path44.default.isAbsolute(project2.lock)) {
26929
+ if (import_node_path45.default.isAbsolute(project2.manifest) || import_node_path45.default.isAbsolute(project2.lock)) {
26644
26930
  diagnostics.push({
26645
26931
  id: "absolute-path",
26646
26932
  level: "warning",
26647
26933
  message: `project "${project2.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
26648
26934
  });
26649
26935
  }
26650
- if (!(0, import_node_fs41.existsSync)(manifestPath)) {
26936
+ if (!(0, import_node_fs42.existsSync)(manifestPath)) {
26651
26937
  diagnostics.push({
26652
26938
  id: "missing-manifest",
26653
26939
  level: "error",
26654
26940
  message: `project "${project2.id}" manifest not found: ${manifestPath}`
26655
26941
  });
26656
26942
  }
26657
- if (!(0, import_node_fs41.existsSync)(lockPath)) {
26943
+ if (!(0, import_node_fs42.existsSync)(lockPath)) {
26658
26944
  diagnostics.push({
26659
26945
  id: "missing-lock",
26660
26946
  level: "error",
@@ -26701,32 +26987,32 @@ function validateWorkspace(ws, dir) {
26701
26987
  }
26702
26988
 
26703
26989
  // src/gallery/edit.ts
26704
- var import_promises38 = require("fs/promises");
26705
- var import_node_path48 = __toESM(require("path"), 1);
26706
- var import_zod16 = require("zod");
26990
+ var import_promises39 = require("fs/promises");
26991
+ var import_node_path49 = __toESM(require("path"), 1);
26992
+ var import_zod17 = require("zod");
26707
26993
 
26708
26994
  // src/gallery/upload.ts
26709
- var import_node_fs42 = require("fs");
26710
- var import_promises35 = require("fs/promises");
26711
- var import_node_path45 = __toESM(require("path"), 1);
26712
- var import_zod13 = require("zod");
26995
+ var import_node_fs43 = require("fs");
26996
+ var import_promises36 = require("fs/promises");
26997
+ var import_node_path46 = __toESM(require("path"), 1);
26998
+ var import_zod14 = require("zod");
26713
26999
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
26714
- var UploadImageSchema = import_zod13.z.object({
26715
- action: import_zod13.z.literal("upload-image"),
26716
- project: import_zod13.z.string().min(1).optional(),
27000
+ var UploadImageSchema = import_zod14.z.object({
27001
+ action: import_zod14.z.literal("upload-image"),
27002
+ project: import_zod14.z.string().min(1).optional(),
26717
27003
  /** Manifest-relative destination, ending .png, .jpg, or .jpeg. */
26718
- path: import_zod13.z.string().min(1),
26719
- base64: import_zod13.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_UPLOAD_BYTES / 3) * 4),
27004
+ path: import_zod14.z.string().min(1),
27005
+ base64: import_zod14.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_UPLOAD_BYTES / 3) * 4),
26720
27006
  /** Replace a file already at `path`. */
26721
- overwrite: import_zod13.z.boolean().optional()
27007
+ overwrite: import_zod14.z.boolean().optional()
26722
27008
  }).strict();
26723
27009
  async function saveProjectImage(root, request) {
26724
- const file = import_node_path45.default.resolve(root, request.path);
26725
- const relative = import_node_path45.default.relative(root, file);
26726
- if (relative.startsWith("..") || import_node_path45.default.isAbsolute(relative)) {
27010
+ const file = import_node_path46.default.resolve(root, request.path);
27011
+ const relative = import_node_path46.default.relative(root, file);
27012
+ if (relative.startsWith("..") || import_node_path46.default.isAbsolute(relative)) {
26727
27013
  throw new ManifestEditError("an upload must stay inside the project");
26728
27014
  }
26729
- const extension = import_node_path45.default.extname(file).toLowerCase();
27015
+ const extension = import_node_path46.default.extname(file).toLowerCase();
26730
27016
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
26731
27017
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
26732
27018
  const bytes = Buffer.from(request.base64, "base64");
@@ -26738,45 +27024,45 @@ async function saveProjectImage(root, request) {
26738
27024
  if (metadata.format !== expected) {
26739
27025
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
26740
27026
  }
26741
- if ((0, import_node_fs42.existsSync)(file) && !request.overwrite) {
26742
- throw new ManifestEditError(`${relative.split(import_node_path45.default.sep).join("/")} already exists; choose another name, or replace it`);
27027
+ if ((0, import_node_fs43.existsSync)(file) && !request.overwrite) {
27028
+ throw new ManifestEditError(`${relative.split(import_node_path46.default.sep).join("/")} already exists; choose another name, or replace it`);
26743
27029
  }
26744
- await (0, import_promises35.mkdir)(import_node_path45.default.dirname(file), { recursive: true });
26745
- await (0, import_promises35.writeFile)(file, bytes);
26746
- return relative.split(import_node_path45.default.sep).join("/");
27030
+ await (0, import_promises36.mkdir)(import_node_path46.default.dirname(file), { recursive: true });
27031
+ await (0, import_promises36.writeFile)(file, bytes);
27032
+ return relative.split(import_node_path46.default.sep).join("/");
26747
27033
  }
26748
27034
 
26749
27035
  // src/gallery/image-revision.ts
26750
- var import_node_fs43 = require("fs");
26751
- var import_promises36 = require("fs/promises");
26752
- var import_node_path46 = __toESM(require("path"), 1);
26753
- var import_zod14 = require("zod");
26754
- var InpaintRevisionRequestSchema = import_zod14.z.object({
26755
- action: import_zod14.z.literal("create-inpaint-revision"),
26756
- project: import_zod14.z.string().min(1).optional(),
26757
- expectedSha256: import_zod14.z.string().regex(/^[0-9a-f]{64}$/),
26758
- styleId: import_zod14.z.string().min(1),
27036
+ var import_node_fs44 = require("fs");
27037
+ var import_promises37 = require("fs/promises");
27038
+ var import_node_path47 = __toESM(require("path"), 1);
27039
+ var import_zod15 = require("zod");
27040
+ var InpaintRevisionRequestSchema = import_zod15.z.object({
27041
+ action: import_zod15.z.literal("create-inpaint-revision"),
27042
+ project: import_zod15.z.string().min(1).optional(),
27043
+ expectedSha256: import_zod15.z.string().regex(/^[0-9a-f]{64}$/),
27044
+ styleId: import_zod15.z.string().min(1),
26759
27045
  /** The sprite being repainted. */
26760
- from: import_zod14.z.string().min(1),
26761
- assetId: import_zod14.z.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
27046
+ from: import_zod15.z.string().min(1),
27047
+ assetId: import_zod15.z.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
26762
27048
  /** What to paint into the masked area. */
26763
- prompt: import_zod14.z.string().min(1),
27049
+ prompt: import_zod15.z.string().min(1),
26764
27050
  /** Manifest-relative `.png` destination for the mask. */
26765
- maskPath: import_zod14.z.string().min(1),
26766
- maskBase64: import_zod14.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/),
27051
+ maskPath: import_zod15.z.string().min(1),
27052
+ maskBase64: import_zod15.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/),
26767
27053
  /** Replace a file already at `maskPath`. */
26768
- overwrite: import_zod14.z.boolean().optional()
27054
+ overwrite: import_zod15.z.boolean().optional()
26769
27055
  }).strict();
26770
27056
  async function createInpaintRevision(manifestPath, request) {
26771
- const root = import_node_path46.default.dirname(import_node_path46.default.resolve(manifestPath));
26772
- if (import_node_path46.default.extname(request.maskPath).toLowerCase() !== ".png") {
27057
+ const root = import_node_path47.default.dirname(import_node_path47.default.resolve(manifestPath));
27058
+ if (import_node_path47.default.extname(request.maskPath).toLowerCase() !== ".png") {
26773
27059
  throw new ManifestEditError("the mask must be a .png path inside the project");
26774
27060
  }
26775
27061
  const bytes = Buffer.from(request.maskBase64, "base64");
26776
27062
  const metadata = imageMetadata(bytes);
26777
27063
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
26778
- const file = import_node_path46.default.resolve(root, request.maskPath);
26779
- const previous = (0, import_node_fs43.existsSync)(file) ? await (0, import_promises36.readFile)(file) : null;
27064
+ const file = import_node_path47.default.resolve(root, request.maskPath);
27065
+ const previous = (0, import_node_fs44.existsSync)(file) ? await (0, import_promises37.readFile)(file) : null;
26780
27066
  const mask = await saveProjectImage(root, {
26781
27067
  action: "upload-image",
26782
27068
  path: request.maskPath,
@@ -26795,70 +27081,70 @@ async function createInpaintRevision(manifestPath, request) {
26795
27081
  }
26796
27082
  });
26797
27083
  } catch (error) {
26798
- if (previous) await (0, import_promises36.writeFile)(file, previous);
26799
- else await (0, import_promises36.rm)(file, { force: true });
27084
+ if (previous) await (0, import_promises37.writeFile)(file, previous);
27085
+ else await (0, import_promises37.rm)(file, { force: true });
26800
27086
  throw error;
26801
27087
  }
26802
27088
  return mask;
26803
27089
  }
26804
27090
 
26805
27091
  // src/gallery/skeleton.ts
26806
- var import_node_fs44 = require("fs");
26807
- var import_promises37 = require("fs/promises");
26808
- var import_node_path47 = __toESM(require("path"), 1);
26809
- var import_zod15 = require("zod");
26810
- var SkeletonEstimateRequestSchema = import_zod15.z.object({
26811
- project: import_zod15.z.string().min(1).optional(),
26812
- styleId: import_zod15.z.string().min(1),
26813
- assetId: import_zod15.z.string().min(1),
26814
- frames: import_zod15.z.number().int().min(3).max(15).optional()
27092
+ var import_node_fs45 = require("fs");
27093
+ var import_promises38 = require("fs/promises");
27094
+ var import_node_path48 = __toESM(require("path"), 1);
27095
+ var import_zod16 = require("zod");
27096
+ var SkeletonEstimateRequestSchema = import_zod16.z.object({
27097
+ project: import_zod16.z.string().min(1).optional(),
27098
+ styleId: import_zod16.z.string().min(1),
27099
+ assetId: import_zod16.z.string().min(1),
27100
+ frames: import_zod16.z.number().int().min(3).max(15).optional()
26815
27101
  }).strict();
26816
- var SkeletonAnimationRequestSchema = import_zod15.z.object({
26817
- action: import_zod15.z.literal("create-skeleton-animation"),
26818
- project: import_zod15.z.string().min(1).optional(),
26819
- expectedSha256: import_zod15.z.string().regex(/^[0-9a-f]{64}$/),
26820
- styleId: import_zod15.z.string().min(1),
27102
+ var SkeletonAnimationRequestSchema = import_zod16.z.object({
27103
+ action: import_zod16.z.literal("create-skeleton-animation"),
27104
+ project: import_zod16.z.string().min(1).optional(),
27105
+ expectedSha256: import_zod16.z.string().regex(/^[0-9a-f]{64}$/),
27106
+ styleId: import_zod16.z.string().min(1),
26821
27107
  /** The sprite the animation poses. */
26822
- from: import_zod15.z.string().min(1),
26823
- assetId: import_zod15.z.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
27108
+ from: import_zod16.z.string().min(1),
27109
+ assetId: import_zod16.z.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
26824
27110
  /** The motion, sent as PixelLab's `action`. */
26825
- prompt: import_zod15.z.string().min(1),
27111
+ prompt: import_zod16.z.string().min(1),
26826
27112
  direction: CharacterDirectionSchema,
26827
27113
  /** What the character looks like; PixelLab refuses the request without it. */
26828
- description: import_zod15.z.string().min(1),
26829
- skeletonTemplate: import_zod15.z.string().min(1).optional(),
27114
+ description: import_zod16.z.string().min(1),
27115
+ skeletonTemplate: import_zod16.z.string().min(1).optional(),
26830
27116
  /** Manifest-relative JSON path inside the project. */
26831
- keypointsFile: import_zod15.z.string().min(1),
27117
+ keypointsFile: import_zod16.z.string().min(1),
26832
27118
  /** Poses to write to `keypointsFile`; omitted to use a file that already exists. */
26833
27119
  set: SkeletonSetSchema.optional(),
26834
27120
  /** Replace an existing `keypointsFile` with `set`. */
26835
- overwrite: import_zod15.z.boolean().optional()
27121
+ overwrite: import_zod16.z.boolean().optional()
26836
27122
  }).strict();
26837
- var SkeletonKeypointsUpdateSchema = import_zod15.z.object({
26838
- action: import_zod15.z.literal("update-skeleton-keypoints"),
26839
- project: import_zod15.z.string().min(1).optional(),
26840
- styleId: import_zod15.z.string().min(1),
26841
- assetId: import_zod15.z.string().min(1),
27123
+ var SkeletonKeypointsUpdateSchema = import_zod16.z.object({
27124
+ action: import_zod16.z.literal("update-skeleton-keypoints"),
27125
+ project: import_zod16.z.string().min(1).optional(),
27126
+ styleId: import_zod16.z.string().min(1),
27127
+ assetId: import_zod16.z.string().min(1),
26842
27128
  /** The file's SHA-256 when the page loaded it; anything else on disk is a concurrent edit. */
26843
- expectedSha256: import_zod15.z.string().regex(/^[0-9a-f]{64}$/),
27129
+ expectedSha256: import_zod16.z.string().regex(/^[0-9a-f]{64}$/),
26844
27130
  set: SkeletonSetSchema
26845
27131
  }).strict();
26846
27132
  async function createSkeletonAnimation(manifestPath, request) {
26847
- const root = import_node_path47.default.dirname(import_node_path47.default.resolve(manifestPath));
26848
- const file = import_node_path47.default.resolve(root, request.keypointsFile);
26849
- const relative = import_node_path47.default.relative(root, file);
26850
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path47.default.isAbsolute(relative)) {
27133
+ const root = import_node_path48.default.dirname(import_node_path48.default.resolve(manifestPath));
27134
+ const file = import_node_path48.default.resolve(root, request.keypointsFile);
27135
+ const relative = import_node_path48.default.relative(root, file);
27136
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path48.default.isAbsolute(relative)) {
26851
27137
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
26852
27138
  }
26853
- const existed = (0, import_node_fs44.existsSync)(file);
27139
+ const existed = (0, import_node_fs45.existsSync)(file);
26854
27140
  let previous = null;
26855
27141
  if (request.set) {
26856
27142
  if (existed && !request.overwrite) {
26857
27143
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
26858
27144
  }
26859
- if (existed) previous = await (0, import_promises37.readFile)(file);
26860
- await (0, import_promises37.mkdir)(import_node_path47.default.dirname(file), { recursive: true });
26861
- await (0, import_promises37.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
27145
+ if (existed) previous = await (0, import_promises38.readFile)(file);
27146
+ await (0, import_promises38.mkdir)(import_node_path48.default.dirname(file), { recursive: true });
27147
+ await (0, import_promises38.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
26862
27148
  } else if (!existed) {
26863
27149
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
26864
27150
  }
@@ -26873,7 +27159,7 @@ async function createSkeletonAnimation(manifestPath, request) {
26873
27159
  revision: {
26874
27160
  mode: "animate-skeleton",
26875
27161
  from: request.from,
26876
- keypointsFile: relative.split(import_node_path47.default.sep).join("/"),
27162
+ keypointsFile: relative.split(import_node_path48.default.sep).join("/"),
26877
27163
  direction: request.direction,
26878
27164
  description: request.description,
26879
27165
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -26882,8 +27168,8 @@ async function createSkeletonAnimation(manifestPath, request) {
26882
27168
  });
26883
27169
  } catch (error) {
26884
27170
  if (request.set) {
26885
- if (previous) await (0, import_promises37.writeFile)(file, previous);
26886
- else await (0, import_promises37.rm)(file, { force: true });
27171
+ if (previous) await (0, import_promises38.writeFile)(file, previous);
27172
+ else await (0, import_promises38.rm)(file, { force: true });
26887
27173
  }
26888
27174
  throw error;
26889
27175
  }
@@ -26894,64 +27180,64 @@ async function updateSkeletonKeypoints(ctx, request) {
26894
27180
  if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
26895
27181
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
26896
27182
  if (!file) throw new ManifestEditError(`${key3} is not an animate-skeleton revision`);
26897
- const relative = import_node_path47.default.relative(ctx.loaded.root, file);
26898
- if (relative.startsWith("..") || import_node_path47.default.isAbsolute(relative)) {
27183
+ const relative = import_node_path48.default.relative(ctx.loaded.root, file);
27184
+ if (relative.startsWith("..") || import_node_path48.default.isAbsolute(relative)) {
26899
27185
  throw new ManifestEditError(`${key3}'s keypoints file is outside the project; edit it by hand`);
26900
27186
  }
26901
- const current = (0, import_node_fs44.existsSync)(file) ? sha256(await (0, import_promises37.readFile)(file)) : null;
27187
+ const current = (0, import_node_fs45.existsSync)(file) ? sha256(await (0, import_promises38.readFile)(file)) : null;
26902
27188
  if (current !== request.expectedSha256) {
26903
27189
  throw Object.assign(
26904
- new Error(`${relative.split(import_node_path47.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
27190
+ new Error(`${relative.split(import_node_path48.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
26905
27191
  { status: 409 }
26906
27192
  );
26907
27193
  }
26908
- await (0, import_promises37.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
26909
- return relative.split(import_node_path47.default.sep).join("/");
27194
+ await (0, import_promises38.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
27195
+ return relative.split(import_node_path48.default.sep).join("/");
26910
27196
  }
26911
27197
 
26912
27198
  // src/gallery/edit.ts
26913
- var Base642 = import_zod16.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
26914
- var HandEditRequestSchema = import_zod16.z.discriminatedUnion("action", [
26915
- import_zod16.z.object({
26916
- action: import_zod16.z.literal("start-edit"),
26917
- project: import_zod16.z.string().min(1).optional(),
26918
- assetId: import_zod16.z.string().min(1),
26919
- styleId: import_zod16.z.string().min(1),
26920
- expectedSha256: import_zod16.z.string().regex(/^[0-9a-f]{64}$/),
27199
+ var Base642 = import_zod17.z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
27200
+ var HandEditRequestSchema = import_zod17.z.discriminatedUnion("action", [
27201
+ import_zod17.z.object({
27202
+ action: import_zod17.z.literal("start-edit"),
27203
+ project: import_zod17.z.string().min(1).optional(),
27204
+ assetId: import_zod17.z.string().min(1),
27205
+ styleId: import_zod17.z.string().min(1),
27206
+ expectedSha256: import_zod17.z.string().regex(/^[0-9a-f]{64}$/),
26921
27207
  /** Also launch the author's editor on the file. */
26922
- open: import_zod16.z.boolean().optional()
27208
+ open: import_zod17.z.boolean().optional()
26923
27209
  }).strict(),
26924
- import_zod16.z.object({
26925
- action: import_zod16.z.literal("detach-edit"),
26926
- project: import_zod16.z.string().min(1).optional(),
26927
- assetId: import_zod16.z.string().min(1),
26928
- styleId: import_zod16.z.string().min(1),
26929
- expectedSha256: import_zod16.z.string().regex(/^[0-9a-f]{64}$/)
27210
+ import_zod17.z.object({
27211
+ action: import_zod17.z.literal("detach-edit"),
27212
+ project: import_zod17.z.string().min(1).optional(),
27213
+ assetId: import_zod17.z.string().min(1),
27214
+ styleId: import_zod17.z.string().min(1),
27215
+ expectedSha256: import_zod17.z.string().regex(/^[0-9a-f]{64}$/)
26930
27216
  }).strict(),
26931
27217
  /** From the in-browser editor: the page holds the bytes, the server validates and writes. */
26932
- import_zod16.z.object({
26933
- action: import_zod16.z.literal("save-edit"),
26934
- project: import_zod16.z.string().min(1).optional(),
26935
- assetId: import_zod16.z.string().min(1),
26936
- styleId: import_zod16.z.string().min(1),
26937
- expectedSha256: import_zod16.z.string().regex(/^[0-9a-f]{64}$/),
27218
+ import_zod17.z.object({
27219
+ action: import_zod17.z.literal("save-edit"),
27220
+ project: import_zod17.z.string().min(1).optional(),
27221
+ assetId: import_zod17.z.string().min(1),
27222
+ styleId: import_zod17.z.string().min(1),
27223
+ expectedSha256: import_zod17.z.string().regex(/^[0-9a-f]{64}$/),
26938
27224
  /** The flattened image; for a frame set, `frames` instead. */
26939
27225
  png: Base642.min(1).optional(),
26940
27226
  /** Every frame of a set, tagged with the role it was opened under (null for one added in the editor). */
26941
- frames: import_zod16.z.array(import_zod16.z.object({ role: import_zod16.z.string().min(1).nullable(), png: Base642.min(1) }).strict()).min(1).max(256).optional(),
27227
+ frames: import_zod17.z.array(import_zod17.z.object({ role: import_zod17.z.string().min(1).nullable(), png: Base642.min(1) }).strict()).min(1).max(256).optional(),
26942
27228
  /** The editor's layered project file, kept beside the edit. */
26943
27229
  pxo: Base642.optional(),
26944
27230
  /** Editor identity from the bridge's ready message. */
26945
- editor: import_zod16.z.string().min(1).max(200),
26946
- protocol: import_zod16.z.number().int().positive()
27231
+ editor: import_zod17.z.string().min(1).max(200),
27232
+ protocol: import_zod17.z.number().int().positive()
26947
27233
  }).strict()
26948
27234
  ]);
26949
27235
  var UNDO_DEPTH = 20;
26950
- var UndoRequestSchema = import_zod16.z.object({
26951
- action: import_zod16.z.literal("undo-edit"),
26952
- project: import_zod16.z.string().min(1).optional(),
27236
+ var UndoRequestSchema = import_zod17.z.object({
27237
+ action: import_zod17.z.literal("undo-edit"),
27238
+ project: import_zod17.z.string().min(1).optional(),
26953
27239
  /** The manifest as the page last saw it; undo refuses a manifest someone else has changed since. */
26954
- expectedSha256: import_zod16.z.string().regex(/^[0-9a-f]{64}$/)
27240
+ expectedSha256: import_zod17.z.string().regex(/^[0-9a-f]{64}$/)
26955
27241
  }).strict();
26956
27242
  function createGalleryEditHandler(opts) {
26957
27243
  const log = opts.onProgress ?? (() => {
@@ -26960,7 +27246,7 @@ function createGalleryEditHandler(opts) {
26960
27246
  const history = /* @__PURE__ */ new Map();
26961
27247
  const manifestOf = async (project2) => {
26962
27248
  try {
26963
- return import_node_path48.default.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
27249
+ return import_node_path49.default.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
26964
27250
  } catch {
26965
27251
  return null;
26966
27252
  }
@@ -26970,7 +27256,7 @@ function createGalleryEditHandler(opts) {
26970
27256
  if (undo.success) {
26971
27257
  const manifestPath2 = await manifestOf(undo.data.project);
26972
27258
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
26973
- const current = await (0, import_promises38.readFile)(manifestPath2, "utf8");
27259
+ const current = await (0, import_promises39.readFile)(manifestPath2, "utf8");
26974
27260
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
26975
27261
  const stack = history.get(manifestPath2) ?? [];
26976
27262
  const last = stack[stack.length - 1];
@@ -26980,17 +27266,17 @@ function createGalleryEditHandler(opts) {
26980
27266
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
26981
27267
  }
26982
27268
  const tmp = manifestPath2 + ".pixelkiln-undo";
26983
- await (0, import_promises38.writeFile)(tmp, last.before);
26984
- await (0, import_promises38.rename)(tmp, manifestPath2);
27269
+ await (0, import_promises39.writeFile)(tmp, last.before);
27270
+ await (0, import_promises39.rename)(tmp, manifestPath2);
26985
27271
  stack.pop();
26986
- log(` manifest edit undone in ${import_node_path48.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
27272
+ log(` manifest edit undone in ${import_node_path49.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
26987
27273
  return opts.reload();
26988
27274
  }
26989
27275
  const manifestPath = await manifestOf(body?.project);
26990
- const before = manifestPath ? await (0, import_promises38.readFile)(manifestPath, "utf8").catch(() => null) : null;
27276
+ const before = manifestPath ? await (0, import_promises39.readFile)(manifestPath, "utf8").catch(() => null) : null;
26991
27277
  const build = await apply(body);
26992
27278
  if (manifestPath && before !== null) {
26993
- const after = await (0, import_promises38.readFile)(manifestPath, "utf8").catch(() => null);
27279
+ const after = await (0, import_promises39.readFile)(manifestPath, "utf8").catch(() => null);
26994
27280
  if (after !== null && after !== before) {
26995
27281
  const stack = history.get(manifestPath) ?? [];
26996
27282
  stack.push({ before, afterSha: sha256(after) });
@@ -27069,7 +27355,7 @@ function createEditApplier(opts, log) {
27069
27355
  } catch (error) {
27070
27356
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
27071
27357
  }
27072
- const written = await saveProjectImage(import_node_path48.default.dirname(import_node_path48.default.resolve(manifestPath2)), upload.data);
27358
+ const written = await saveProjectImage(import_node_path49.default.dirname(import_node_path49.default.resolve(manifestPath2)), upload.data);
27073
27359
  log(` image added: ${written}`);
27074
27360
  return opts.reload();
27075
27361
  }
@@ -27136,7 +27422,7 @@ function createEditApplier(opts, log) {
27136
27422
  }
27137
27423
  const result = await applyManifestEdit(manifestPath, parsed.data);
27138
27424
  if (result.changed) {
27139
- const relative = import_node_path48.default.relative(process.cwd(), result.manifestPath);
27425
+ const relative = import_node_path49.default.relative(process.cwd(), result.manifestPath);
27140
27426
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
27141
27427
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
27142
27428
  }
@@ -27164,7 +27450,7 @@ function describeEdit(edit) {
27164
27450
  // src/gallery/snapshot.ts
27165
27451
  var PROJECT_FILE_TYPE = "application/octet-stream";
27166
27452
  function galleryMediaId(absolutePath) {
27167
- return (0, import_node_crypto10.createHash)("sha256").update(import_node_path49.default.resolve(absolutePath)).digest("hex").slice(0, 24);
27453
+ return (0, import_node_crypto10.createHash)("sha256").update(import_node_path50.default.resolve(absolutePath)).digest("hex").slice(0, 24);
27168
27454
  }
27169
27455
  function galleryMediaRoute(id) {
27170
27456
  return `/media/${id}`;
@@ -27188,9 +27474,9 @@ function describeHistory(media, entry, cacheDir) {
27188
27474
  return (entry.history ?? []).map((generation, i) => {
27189
27475
  const outputs = generation.outputs.map((output) => {
27190
27476
  const mediaType = output.mediaType ?? MediaType.PNG;
27191
- const file = import_node_path49.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
27477
+ const file = import_node_path50.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
27192
27478
  let url = null;
27193
- if ((0, import_node_fs45.existsSync)(file)) {
27479
+ if ((0, import_node_fs46.existsSync)(file)) {
27194
27480
  const id = galleryMediaId(file);
27195
27481
  media.set(id, { path: file, contentType: mediaType });
27196
27482
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -27222,7 +27508,7 @@ function describeHistory(media, entry, cacheDir) {
27222
27508
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
27223
27509
  async function samePixels(a, b) {
27224
27510
  try {
27225
- const [left, right] = await Promise.all([(0, import_promises39.readFile)(a), (0, import_promises39.readFile)(b)]);
27511
+ const [left, right] = await Promise.all([(0, import_promises40.readFile)(a), (0, import_promises40.readFile)(b)]);
27226
27512
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
27227
27513
  const x = decodePng(left);
27228
27514
  const y = decodePng(right);
@@ -27288,7 +27574,7 @@ function describeCharacter(spec, entry) {
27288
27574
  }
27289
27575
  async function fileInfo(absolutePath) {
27290
27576
  try {
27291
- const info = await (0, import_promises39.stat)(absolutePath);
27577
+ const info = await (0, import_promises40.stat)(absolutePath);
27292
27578
  return info.isFile() ? { bytes: info.size, modifiedAt: info.mtime.toISOString() } : null;
27293
27579
  } catch {
27294
27580
  return null;
@@ -27320,10 +27606,10 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
27320
27606
  async function describeQuality(media, root, inspection) {
27321
27607
  const outputPaths = inspection.outputs ?? [inspection.output];
27322
27608
  const outputs = await Promise.all(
27323
- outputPaths.map((file) => describeOutput(media, root, import_node_path49.default.resolve(root, file)))
27609
+ outputPaths.map((file) => describeOutput(media, root, import_node_path50.default.resolve(root, file)))
27324
27610
  );
27325
- const recordPath = import_node_path49.default.resolve(root, inspection.record);
27326
- const recordExists = (0, import_node_fs45.existsSync)(recordPath);
27611
+ const recordPath = import_node_path50.default.resolve(root, inspection.record);
27612
+ const recordExists = (0, import_node_fs46.existsSync)(recordPath);
27327
27613
  let options = null;
27328
27614
  let check = null;
27329
27615
  if (recordExists) {
@@ -27342,7 +27628,7 @@ async function describeQuality(media, root, inspection) {
27342
27628
  return {
27343
27629
  state: inspection.state,
27344
27630
  reason: inspection.reason,
27345
- output: portableOutputPath(import_node_path49.default.resolve(root, inspection.output), root),
27631
+ output: portableOutputPath(import_node_path50.default.resolve(root, inspection.output), root),
27346
27632
  record: portableOutputPath(recordPath, root),
27347
27633
  recordExists,
27348
27634
  outputs,
@@ -27380,9 +27666,9 @@ async function buildGallerySnapshot(opts) {
27380
27666
  const media = /* @__PURE__ */ new Map();
27381
27667
  const plan = await buildPlan(specs, lock);
27382
27668
  const items = [];
27383
- const manifestText = await (0, import_promises39.readFile)(loaded.path, "utf8");
27669
+ const manifestText = await (0, import_promises40.readFile)(loaded.path, "utf8");
27384
27670
  const manifestSha256 = sha256(manifestText);
27385
- const cacheDir = import_node_path49.default.resolve(import_node_path49.default.dirname(opts.lockPath), ".pixelkiln", "cache");
27671
+ const cacheDir = import_node_path50.default.resolve(import_node_path50.default.dirname(opts.lockPath), ".pixelkiln", "cache");
27386
27672
  let rawStyles = {};
27387
27673
  try {
27388
27674
  const raw = JSON.parse(manifestText);
@@ -27406,12 +27692,12 @@ async function buildGallerySnapshot(opts) {
27406
27692
  )
27407
27693
  );
27408
27694
  if (spec.source) {
27409
- const editPath = import_node_path49.default.resolve(root, spec.source);
27695
+ const editPath = import_node_path50.default.resolve(root, spec.source);
27410
27696
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
27411
27697
  const editShas = await Promise.all(
27412
27698
  Array.from({ length: memberCount }, async (_, index) => {
27413
27699
  const file = sourceOutputPath(spec.source, entry, index, root);
27414
- return { file, sha256: (0, import_node_fs45.existsSync)(file) ? await sha256File(file) : null };
27700
+ return { file, sha256: (0, import_node_fs46.existsSync)(file) ? await sha256File(file) : null };
27415
27701
  })
27416
27702
  );
27417
27703
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -27419,7 +27705,7 @@ async function buildGallerySnapshot(opts) {
27419
27705
  const companion = await readHandEditCompanion(editPath);
27420
27706
  if (companion) {
27421
27707
  const projectPath = handEditProjectPath(editPath);
27422
- const project2 = companion.project && (0, import_node_fs45.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
27708
+ const project2 = companion.project && (0, import_node_fs46.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
27423
27709
  let projectUrl = null;
27424
27710
  if (project2) {
27425
27711
  const id = galleryMediaId(projectPath);
@@ -27455,8 +27741,8 @@ async function buildGallerySnapshot(opts) {
27455
27741
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
27456
27742
  }
27457
27743
  } else if (spec.source) {
27458
- outputs = [await describeOutput(media, root, import_node_path49.default.resolve(root, spec.source))];
27459
- } else if (!entry && (0, import_node_fs45.existsSync)(spec.outFile)) {
27744
+ outputs = [await describeOutput(media, root, import_node_path50.default.resolve(root, spec.source))];
27745
+ } else if (!entry && (0, import_node_fs46.existsSync)(spec.outFile)) {
27460
27746
  outputs = [await describeOutput(media, root, spec.outFile)];
27461
27747
  } else {
27462
27748
  outputs = [];
@@ -27660,7 +27946,7 @@ async function buildGallerySnapshot(opts) {
27660
27946
  id: loaded.manifest.name,
27661
27947
  name: loaded.manifest.name,
27662
27948
  manifest: loaded.path,
27663
- lock: import_node_path49.default.resolve(opts.lockPath),
27949
+ lock: import_node_path50.default.resolve(opts.lockPath),
27664
27950
  root,
27665
27951
  provider: loaded.manifest.provider,
27666
27952
  account: null,
@@ -27689,7 +27975,7 @@ async function buildGallerySnapshot(opts) {
27689
27975
  return { snapshot, media };
27690
27976
  }
27691
27977
  async function buildWorkspaceGallerySnapshot(opts) {
27692
- const dir = import_node_path49.default.dirname(import_node_path49.default.resolve(opts.workspacePath));
27978
+ const dir = import_node_path50.default.dirname(import_node_path50.default.resolve(opts.workspacePath));
27693
27979
  const media = /* @__PURE__ */ new Map();
27694
27980
  const projects = [];
27695
27981
  const items = [];
@@ -27734,11 +28020,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
27734
28020
  id: project2.id,
27735
28021
  name: loaded.manifest.name,
27736
28022
  manifest: manifestPath,
27737
- lock: import_node_path49.default.resolve(lockPath),
28023
+ lock: import_node_path50.default.resolve(lockPath),
27738
28024
  root: loaded.root,
27739
28025
  provider: loaded.manifest.provider,
27740
28026
  account: project2.account ?? null,
27741
- manifestSha256: manifestSha256 ?? sha256(await (0, import_promises39.readFile)(manifestPath, "utf8")),
28027
+ manifestSha256: manifestSha256 ?? sha256(await (0, import_promises40.readFile)(manifestPath, "utf8")),
27742
28028
  historyLimit: historyLimit(loaded.manifest),
27743
28029
  entries: Object.keys(lock.entries).length,
27744
28030
  items: projectItems.length,
@@ -27750,8 +28036,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
27750
28036
  id: project2.id,
27751
28037
  name: project2.id,
27752
28038
  manifest: manifestPath,
27753
- lock: import_node_path49.default.resolve(lockPath),
27754
- root: import_node_path49.default.dirname(manifestPath),
28039
+ lock: import_node_path50.default.resolve(lockPath),
28040
+ root: import_node_path50.default.dirname(manifestPath),
27755
28041
  provider: project2.provider,
27756
28042
  account: project2.account ?? null,
27757
28043
  manifestSha256: null,
@@ -27778,7 +28064,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
27778
28064
  version: 1,
27779
28065
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
27780
28066
  project: null,
27781
- workspace: { path: import_node_path49.default.resolve(opts.workspacePath), dir, projects },
28067
+ workspace: { path: import_node_path50.default.resolve(opts.workspacePath), dir, projects },
27782
28068
  filter,
27783
28069
  totals: {
27784
28070
  entries: projects.reduce((sum, project2) => sum + project2.entries, 0),
@@ -27797,7 +28083,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
27797
28083
  }
27798
28084
 
27799
28085
  // src/gallery/page.ts
27800
- var import_node_fs46 = require("fs");
28086
+ var import_node_fs47 = require("fs");
27801
28087
 
27802
28088
  // src/gallery/client-bundle.ts
27803
28089
  var import_node_module3 = require("module");
@@ -27837,8 +28123,8 @@ var client;
27837
28123
  function clientAssets() {
27838
28124
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
27839
28125
  client ??= {
27840
- css: (0, import_node_fs46.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
27841
- js: (0, import_node_fs46.existsSync)(prebuilt) ? (0, import_node_fs46.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
28126
+ css: (0, import_node_fs47.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
28127
+ js: (0, import_node_fs47.existsSync)(prebuilt) ? (0, import_node_fs47.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
27842
28128
  };
27843
28129
  return client;
27844
28130
  }
@@ -27981,10 +28267,10 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
27981
28267
 
27982
28268
  // src/editor/install.ts
27983
28269
  var import_node_crypto11 = require("crypto");
27984
- var import_node_fs47 = require("fs");
27985
- var import_promises40 = require("fs/promises");
28270
+ var import_node_fs48 = require("fs");
28271
+ var import_promises41 = require("fs/promises");
27986
28272
  var import_node_os4 = __toESM(require("os"), 1);
27987
- var import_node_path50 = __toESM(require("path"), 1);
28273
+ var import_node_path51 = __toESM(require("path"), 1);
27988
28274
  var EditorInstallError = class extends Error {
27989
28275
  constructor(message6, file) {
27990
28276
  super(message6);
@@ -27995,15 +28281,15 @@ var EditorInstallError = class extends Error {
27995
28281
  };
27996
28282
  function editorToolsRoot() {
27997
28283
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
27998
- if (override) return import_node_path50.default.resolve(override);
27999
- if (process.platform === "darwin") return import_node_path50.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
28284
+ if (override) return import_node_path51.default.resolve(override);
28285
+ if (process.platform === "darwin") return import_node_path51.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
28000
28286
  if (process.platform === "win32") {
28001
- return import_node_path50.default.join(process.env.LOCALAPPDATA ?? import_node_path50.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
28287
+ return import_node_path51.default.join(process.env.LOCALAPPDATA ?? import_node_path51.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
28002
28288
  }
28003
- return import_node_path50.default.join(process.env.XDG_CACHE_HOME ?? import_node_path50.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
28289
+ return import_node_path51.default.join(process.env.XDG_CACHE_HOME ?? import_node_path51.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
28004
28290
  }
28005
28291
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
28006
- return import_node_path50.default.join(root, "pixelorama", pin.release ?? "unpublished");
28292
+ return import_node_path51.default.join(root, "pixelorama", pin.release ?? "unpublished");
28007
28293
  }
28008
28294
  function editorBaseUrl(pin = EDITOR_PIN) {
28009
28295
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -28013,7 +28299,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
28013
28299
  }
28014
28300
  async function sha256Of(file) {
28015
28301
  try {
28016
- return (0, import_node_crypto11.createHash)("sha256").update(await (0, import_promises40.readFile)(file)).digest("hex");
28302
+ return (0, import_node_crypto11.createHash)("sha256").update(await (0, import_promises41.readFile)(file)).digest("hex");
28017
28303
  } catch {
28018
28304
  return null;
28019
28305
  }
@@ -28026,8 +28312,8 @@ async function editorStatus(opts = {}) {
28026
28312
  let totalBytes = 0;
28027
28313
  for (const [name, expected] of Object.entries(pin.files)) {
28028
28314
  totalBytes += expected.bytes;
28029
- const file = import_node_path50.default.join(dir, name);
28030
- const info = (0, import_node_fs47.existsSync)(file) ? await (0, import_promises40.stat)(file).catch(() => null) : null;
28315
+ const file = import_node_path51.default.join(dir, name);
28316
+ const info = (0, import_node_fs48.existsSync)(file) ? await (0, import_promises41.stat)(file).catch(() => null) : null;
28031
28317
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
28032
28318
  installedBytes += expected.bytes;
28033
28319
  } else {
@@ -28056,7 +28342,7 @@ async function installEditor(opts = {}) {
28056
28342
  );
28057
28343
  }
28058
28344
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
28059
- await (0, import_promises40.mkdir)(dir, { recursive: true });
28345
+ await (0, import_promises41.mkdir)(dir, { recursive: true });
28060
28346
  const downloaded = [];
28061
28347
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
28062
28348
  let fetchedBytes = before.installedBytes;
@@ -28084,13 +28370,13 @@ async function installEditor(opts = {}) {
28084
28370
  if (digest2 !== expected.sha256) {
28085
28371
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
28086
28372
  }
28087
- const final = import_node_path50.default.join(dir, name);
28373
+ const final = import_node_path51.default.join(dir, name);
28088
28374
  const tmp = `${final}.${process.pid}.part`;
28089
28375
  try {
28090
- await (0, import_promises40.writeFile)(tmp, bytes);
28091
- await (0, import_promises40.rename)(tmp, final);
28376
+ await (0, import_promises41.writeFile)(tmp, bytes);
28377
+ await (0, import_promises41.rename)(tmp, final);
28092
28378
  } finally {
28093
- await (0, import_promises40.rm)(tmp, { force: true });
28379
+ await (0, import_promises41.rm)(tmp, { force: true });
28094
28380
  }
28095
28381
  fetchedBytes += bytes.length;
28096
28382
  downloaded.push(name);
@@ -28130,12 +28416,12 @@ var EDITOR_CONTENT_TYPES = {
28130
28416
  ".json": "application/json; charset=utf-8"
28131
28417
  };
28132
28418
  function editorContentType(name) {
28133
- return EDITOR_CONTENT_TYPES[import_node_path50.default.extname(name).toLowerCase()] ?? null;
28419
+ return EDITOR_CONTENT_TYPES[import_node_path51.default.extname(name).toLowerCase()] ?? null;
28134
28420
  }
28135
28421
 
28136
28422
  // src/gallery/editor.ts
28137
- var import_promises41 = require("fs/promises");
28138
- var import_node_path51 = __toESM(require("path"), 1);
28423
+ var import_promises42 = require("fs/promises");
28424
+ var import_node_path52 = __toESM(require("path"), 1);
28139
28425
  function editorRoute(release, name = "index.html") {
28140
28426
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
28141
28427
  }
@@ -28208,7 +28494,7 @@ function createGalleryEditorHandlers(opts = {}) {
28208
28494
  if (!status.installed) return null;
28209
28495
  let bytes;
28210
28496
  try {
28211
- bytes = await (0, import_promises41.readFile)(import_node_path51.default.join(dir, name));
28497
+ bytes = await (0, import_promises42.readFile)(import_node_path52.default.join(dir, name));
28212
28498
  } catch {
28213
28499
  verified = null;
28214
28500
  return null;
@@ -28225,7 +28511,7 @@ function createGalleryEditorHandlers(opts = {}) {
28225
28511
  // src/gallery/server.ts
28226
28512
  var import_node_crypto12 = require("crypto");
28227
28513
  var import_node_http2 = require("http");
28228
- var import_promises42 = require("fs/promises");
28514
+ var import_promises43 = require("fs/promises");
28229
28515
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
28230
28516
  var EDITOR_CSP = [
28231
28517
  "default-src 'self'",
@@ -28406,7 +28692,7 @@ async function serveGallery(opts) {
28406
28692
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
28407
28693
  if (!asset) return fail(404, "no such review asset");
28408
28694
  try {
28409
- const bytes = await (0, import_promises42.readFile)(asset.path);
28695
+ const bytes = await (0, import_promises43.readFile)(asset.path);
28410
28696
  res.writeHead(200, {
28411
28697
  "Content-Type": asset.contentType,
28412
28698
  "Cache-Control": "no-store",
@@ -28489,7 +28775,7 @@ async function serveGallery(opts) {
28489
28775
  if (!asset) return fail(404, "no such gallery media");
28490
28776
  let bytes;
28491
28777
  try {
28492
- bytes = await (0, import_promises42.readFile)(asset.path);
28778
+ bytes = await (0, import_promises43.readFile)(asset.path);
28493
28779
  } catch {
28494
28780
  return fail(404, "gallery media is no longer on disk; refresh the page");
28495
28781
  }
@@ -28533,27 +28819,27 @@ async function serveGallery(opts) {
28533
28819
 
28534
28820
  // src/gallery/generate.ts
28535
28821
  var import_node_crypto13 = require("crypto");
28536
- var import_zod17 = require("zod");
28537
- var GenerateRequestSchema = import_zod17.z.object({
28538
- project: import_zod17.z.string().min(1).optional(),
28539
- keys: import_zod17.z.array(import_zod17.z.string().min(1)).min(1).max(500),
28822
+ var import_zod18 = require("zod");
28823
+ var GenerateRequestSchema = import_zod18.z.object({
28824
+ project: import_zod18.z.string().min(1).optional(),
28825
+ keys: import_zod18.z.array(import_zod18.z.string().min(1)).min(1).max(500),
28540
28826
  /**
28541
28827
  * Regenerate work that is up to date, as `gen --force` does, and let the
28542
28828
  * fetch replace a locally modified or untracked file. With `restore`, put
28543
28829
  * the recorded bytes back over a modified file.
28544
28830
  */
28545
- force: import_zod17.z.boolean().optional(),
28831
+ force: import_zod18.z.boolean().optional(),
28546
28832
  /** Advance in-flight, review, or selected work without submitting anything. */
28547
- resume: import_zod17.z.boolean().optional(),
28833
+ resume: import_zod18.z.boolean().optional(),
28548
28834
  /** Re-download downloaded outputs and replace files whose object changed upstream. */
28549
- refresh: import_zod17.z.boolean().optional(),
28835
+ refresh: import_zod18.z.boolean().optional(),
28550
28836
  /** Put recorded outputs back on disk from the cache or the provider, without generating. */
28551
- restore: import_zod17.z.boolean().optional(),
28837
+ restore: import_zod18.z.boolean().optional(),
28552
28838
  /**
28553
28839
  * Bring a replaced generation back: 1-based position in the record's
28554
28840
  * history (newest first) or an output hash prefix. One key at a time.
28555
28841
  */
28556
- revert: import_zod17.z.string().min(1).max(64).optional()
28842
+ revert: import_zod18.z.string().min(1).max(64).optional()
28557
28843
  }).strict().refine((request) => [request.resume, request.refresh, request.restore, request.revert !== void 0].filter(Boolean).length <= 1, {
28558
28844
  message: "resume, refresh, restore, and revert are exclusive"
28559
28845
  }).refine((request) => request.revert === void 0 || request.keys.length === 1, { message: "revert takes one key" });
@@ -28873,7 +29159,8 @@ function createGenerateHandlers(opts) {
28873
29159
  keys: job.review,
28874
29160
  specs,
28875
29161
  onProgress: (line) => say(job, line),
28876
- routePrefix: options.routePrefix
29162
+ routePrefix: options.routePrefix,
29163
+ lockPath: ctx.lockPath
28877
29164
  });
28878
29165
  if (session) reviews.set(jobId, session);
28879
29166
  return session;
@@ -28899,19 +29186,19 @@ function createGenerateHandlers(opts) {
28899
29186
  }
28900
29187
 
28901
29188
  // src/pipeline/salvage.ts
28902
- var import_promises43 = require("fs/promises");
28903
- var import_node_fs48 = require("fs");
28904
- var import_node_path52 = __toESM(require("path"), 1);
29189
+ var import_promises44 = require("fs/promises");
29190
+ var import_node_fs49 = require("fs");
29191
+ var import_node_path53 = __toESM(require("path"), 1);
28905
29192
  function providerClaimId(provider, objectId) {
28906
29193
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
28907
29194
  }
28908
29195
  async function loadClaims(lockPaths, opts = {}) {
28909
29196
  const claimed = /* @__PURE__ */ new Set();
28910
29197
  for (const p of lockPaths) {
28911
- if (!(0, import_node_fs48.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
29198
+ if (!(0, import_node_fs49.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
28912
29199
  let parsed;
28913
29200
  try {
28914
- parsed = parseLock(JSON.parse(await (0, import_promises43.readFile)(p, "utf8")));
29201
+ parsed = parseLock(JSON.parse(await (0, import_promises44.readFile)(p, "utf8")));
28915
29202
  } catch {
28916
29203
  throw new Error(`Claim lockfile is malformed: ${p}`);
28917
29204
  }
@@ -29015,20 +29302,20 @@ function matchOrphanStyle(prompt, manifest) {
29015
29302
  return matchStyleByPattern(prompt, manifest);
29016
29303
  }
29017
29304
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
29018
- const own = import_node_path52.default.resolve(ownManifestPath);
29305
+ const own = import_node_path53.default.resolve(ownManifestPath);
29019
29306
  const siblingManifestPaths = [
29020
29307
  .../* @__PURE__ */ new Set([
29021
29308
  ...workspaceManifestPaths,
29022
- ...claimPaths.map((c) => import_node_path52.default.join(import_node_path52.default.dirname(import_node_path52.default.resolve(c)), "pixelkiln.manifest.json"))
29309
+ ...claimPaths.map((c) => import_node_path53.default.join(import_node_path53.default.dirname(import_node_path53.default.resolve(c)), "pixelkiln.manifest.json"))
29023
29310
  ])
29024
29311
  ];
29025
29312
  const siblings = [];
29026
29313
  for (const siblingManifestPath of siblingManifestPaths) {
29027
- if (import_node_path52.default.resolve(siblingManifestPath) === own) continue;
29028
- if (!(0, import_node_fs48.existsSync)(siblingManifestPath)) continue;
29314
+ if (import_node_path53.default.resolve(siblingManifestPath) === own) continue;
29315
+ if (!(0, import_node_fs49.existsSync)(siblingManifestPath)) continue;
29029
29316
  try {
29030
29317
  const { manifest } = await loadManifest(siblingManifestPath);
29031
- siblings.push({ label: import_node_path52.default.basename(import_node_path52.default.dirname(siblingManifestPath)), manifest });
29318
+ siblings.push({ label: import_node_path53.default.basename(import_node_path53.default.dirname(siblingManifestPath)), manifest });
29032
29319
  } catch {
29033
29320
  }
29034
29321
  }
@@ -29148,8 +29435,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
29148
29435
  }
29149
29436
 
29150
29437
  // src/pick/salvage-server.ts
29151
- var import_promises44 = require("fs/promises");
29152
- var import_node_path53 = __toESM(require("path"), 1);
29438
+ var import_promises45 = require("fs/promises");
29439
+ var import_node_path54 = __toESM(require("path"), 1);
29153
29440
 
29154
29441
  // src/pick/salvage-sheet.ts
29155
29442
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -29315,7 +29602,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
29315
29602
  });
29316
29603
  const html = renderSalvageSheet(orphans, {
29317
29604
  styleId: ctx.styleId,
29318
- importDir: import_node_path53.default.relative(process.cwd(), ctx.importDir) || "."
29605
+ importDir: import_node_path54.default.relative(process.cwd(), ctx.importDir) || "."
29319
29606
  });
29320
29607
  const byId = new Map(orphans.map((o) => [o.id, o]));
29321
29608
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -29371,10 +29658,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
29371
29658
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
29372
29659
  decodePng(buf);
29373
29660
  const assetId = idFromPrompt(orphan.prompt, taken);
29374
- const rel = import_node_path53.default.join("_salvaged", `${assetId}.png`);
29375
- const outFile = import_node_path53.default.resolve(ctx.importDir, rel);
29376
- await (0, import_promises44.mkdir)(import_node_path53.default.dirname(outFile), { recursive: true });
29377
- await (0, import_promises44.writeFile)(outFile, buf);
29661
+ const rel = import_node_path54.default.join("_salvaged", `${assetId}.png`);
29662
+ const outFile = import_node_path54.default.resolve(ctx.importDir, rel);
29663
+ await (0, import_promises45.mkdir)(import_node_path54.default.dirname(outFile), { recursive: true });
29664
+ await (0, import_promises45.writeFile)(outFile, buf);
29378
29665
  ctx.manifest.assets[assetId] = {
29379
29666
  prompt: orphan.prompt,
29380
29667
  promptByStyle: {},
@@ -29406,7 +29693,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
29406
29693
  sourceUrl: durableSource,
29407
29694
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
29408
29695
  outputs: [{
29409
- path: portableOutputPath(outFile, import_node_path53.default.dirname(ctx.manifestPath)),
29696
+ path: portableOutputPath(outFile, import_node_path54.default.dirname(ctx.manifestPath)),
29410
29697
  sha256: sha256(buf)
29411
29698
  }],
29412
29699
  submittedAt: orphan.createdAt,
@@ -29430,9 +29717,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
29430
29717
  }
29431
29718
  }
29432
29719
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
29433
- const raw = JSON.parse(await (0, import_promises44.readFile)(ctx.manifestPath, "utf8"));
29720
+ const raw = JSON.parse(await (0, import_promises45.readFile)(ctx.manifestPath, "utf8"));
29434
29721
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
29435
- await (0, import_promises44.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
29722
+ await (0, import_promises45.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
29436
29723
  await saveLock(ctx.lockPath, ctx.lock);
29437
29724
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
29438
29725
  return result;