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.js CHANGED
@@ -1430,7 +1430,7 @@ var AssetDeriveSchema = z.object({
1430
1430
  /** 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. */
1431
1431
  tolerance: z.number().min(0).max(442).optional()
1432
1432
  }).strict().superRefine((derive, context) => {
1433
- const issue = (message6, path53) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path53] });
1433
+ const issue = (message6, path54) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path54] });
1434
1434
  if (Boolean(derive.from) === Boolean(derive.file)) {
1435
1435
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1436
1436
  }
@@ -2857,9 +2857,9 @@ var PixelLabClient = class {
2857
2857
  apiKey;
2858
2858
  http;
2859
2859
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
2860
- async request(path53, init) {
2860
+ async request(path54, init) {
2861
2861
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
2862
- const res = await this.http(`${BASE}${path53}`, {
2862
+ const res = await this.http(`${BASE}${path54}`, {
2863
2863
  ...init,
2864
2864
  headers: {
2865
2865
  Authorization: auth,
@@ -2870,13 +2870,13 @@ var PixelLabClient = class {
2870
2870
  const text = await res.text();
2871
2871
  if (!res.ok) {
2872
2872
  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' : "";
2873
- throw new PixelLabError(`${init?.method ?? "GET"} ${path53} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
2873
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path54} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
2874
2874
  }
2875
2875
  if (!text) return {};
2876
2876
  try {
2877
2877
  return JSON.parse(text);
2878
2878
  } catch {
2879
- throw new Error(`${init?.method ?? "GET"} ${path53} returned invalid JSON`);
2879
+ throw new Error(`${init?.method ?? "GET"} ${path54} returned invalid JSON`);
2880
2880
  }
2881
2881
  }
2882
2882
  async balance() {
@@ -3423,10 +3423,10 @@ var PixelLabClient = class {
3423
3423
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
3424
3424
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
3425
3425
  const south = args.reference?.south;
3426
- let path53;
3426
+ let path54;
3427
3427
  let body;
3428
3428
  if (args.mode === "v3") {
3429
- path53 = "/create-character-v3";
3429
+ path54 = "/create-character-v3";
3430
3430
  body = {
3431
3431
  description: args.description,
3432
3432
  image_size: imageSize,
@@ -3440,7 +3440,7 @@ var PixelLabClient = class {
3440
3440
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
3441
3441
  };
3442
3442
  } else if (args.mode === "pro-flash") {
3443
- path53 = "/create-character-pro-flash";
3443
+ path54 = "/create-character-pro-flash";
3444
3444
  const traits = args.styleTraits;
3445
3445
  body = {
3446
3446
  description: args.description,
@@ -3464,7 +3464,7 @@ var PixelLabClient = class {
3464
3464
  } : {}
3465
3465
  };
3466
3466
  } else if (args.mode === "pro") {
3467
- path53 = "/create-character-pro";
3467
+ path54 = "/create-character-pro";
3468
3468
  body = {
3469
3469
  description: args.description,
3470
3470
  image_size: imageSize,
@@ -3478,7 +3478,7 @@ var PixelLabClient = class {
3478
3478
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
3479
3479
  };
3480
3480
  } else {
3481
- path53 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3481
+ path54 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3482
3482
  body = {
3483
3483
  description: args.description,
3484
3484
  image_size: imageSize,
@@ -3496,8 +3496,8 @@ var PixelLabClient = class {
3496
3496
  };
3497
3497
  }
3498
3498
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
3499
- const raw = await this.request(path53, { method: "POST", body: JSON.stringify(body) });
3500
- return validateResponse(CharacterSubmitSchema, raw, path53.slice(1));
3499
+ const raw = await this.request(path54, { method: "POST", body: JSON.stringify(body) });
3500
+ return validateResponse(CharacterSubmitSchema, raw, path54.slice(1));
3501
3501
  }
3502
3502
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
3503
3503
  async createCharacterState(args) {
@@ -5171,10 +5171,10 @@ function normalizeHex(value) {
5171
5171
  function sha256(data) {
5172
5172
  return createHash("sha256").update(data).digest("hex");
5173
5173
  }
5174
- async function sha256File(path53) {
5174
+ async function sha256File(path54) {
5175
5175
  return new Promise((resolve, reject) => {
5176
5176
  const hash = createHash("sha256");
5177
- const stream = createReadStream(path53);
5177
+ const stream = createReadStream(path54);
5178
5178
  stream.on("data", (chunk2) => hash.update(chunk2));
5179
5179
  stream.on("error", reject);
5180
5180
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -11001,9 +11001,9 @@ var RetroDiffusionClient = class {
11001
11001
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
11002
11002
  return Buffer.from(await response.arrayBuffer());
11003
11003
  }
11004
- async call(path53, init = {}) {
11004
+ async call(path54, init = {}) {
11005
11005
  if (!this.token) throw new Error("RD_API_KEY is not set");
11006
- const response = await this.request(`${this.baseUrl}${path53}`, {
11006
+ const response = await this.request(`${this.baseUrl}${path54}`, {
11007
11007
  ...init,
11008
11008
  headers: {
11009
11009
  "Content-Type": "application/json",
@@ -19212,10 +19212,10 @@ function isSha256Hash(value) {
19212
19212
  function parseCache(value) {
19213
19213
  return HashCacheSchema.parse(value);
19214
19214
  }
19215
- async function loadCache(path53) {
19216
- if (!existsSync24(path53)) return { version: 1, hashes: {} };
19215
+ async function loadCache(path54) {
19216
+ if (!existsSync24(path54)) return { version: 1, hashes: {} };
19217
19217
  try {
19218
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile17(path53, "utf8")));
19218
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile17(path54, "utf8")));
19219
19219
  if (!parsed.success) return { version: 1, hashes: {} };
19220
19220
  return {
19221
19221
  version: 1,
@@ -19227,18 +19227,18 @@ async function loadCache(path53) {
19227
19227
  return { version: 1, hashes: {} };
19228
19228
  }
19229
19229
  }
19230
- async function saveCache(path53, cache) {
19230
+ async function saveCache(path54, cache) {
19231
19231
  const sorted = {};
19232
19232
  for (const key3 of Object.keys(cache.hashes).sort()) {
19233
19233
  const hash = cache.hashes[key3];
19234
19234
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
19235
19235
  sorted[key3] = hash;
19236
19236
  }
19237
- await mkdir12(pathModule.dirname(pathModule.resolve(path53)), { recursive: true });
19238
- const tmp = `${path53}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19237
+ await mkdir12(pathModule.dirname(pathModule.resolve(path54)), { recursive: true });
19238
+ const tmp = `${path54}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19239
19239
  try {
19240
19240
  await writeFile12(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
19241
- await rename6(tmp, path53);
19241
+ await rename6(tmp, path54);
19242
19242
  } finally {
19243
19243
  await rm4(tmp, { force: true });
19244
19244
  }
@@ -19461,7 +19461,8 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19461
19461
  if (!source.url) {
19462
19462
  throw new Error(`no source URL or cached bytes remain for ${source.role ?? "asset"}`);
19463
19463
  }
19464
- raw = await provider.download(source.url);
19464
+ const localFile = source.url.startsWith("file://") ? source.url.slice("file://".length) : null;
19465
+ raw = localFile && existsSync25(localFile) ? await readFile18(localFile) : await provider.download(source.url);
19465
19466
  }
19466
19467
  let mediaType;
19467
19468
  const bytes = final ?? raw;
@@ -21778,6 +21779,193 @@ function ownedReferenceImageId(spec, lock, providerId) {
21778
21779
  return void 0;
21779
21780
  }
21780
21781
 
21782
+ // src/pick/candidates.ts
21783
+ import { existsSync as existsSync28 } from "fs";
21784
+ import { mkdir as mkdir14, readFile as readFile20, rename as rename8, rm as rm7, writeFile as writeFile14 } from "fs/promises";
21785
+ import path33 from "path";
21786
+ import { z as z8 } from "zod";
21787
+ var REVIEW_STATE_VERSION = 1;
21788
+ var CandidateSchema = z8.object({
21789
+ index: z8.number().int().nonnegative(),
21790
+ /** Frame role for a frame set (`frame-00`, ...); absent for candidates. */
21791
+ role: z8.string().optional(),
21792
+ /**
21793
+ * Where the provider served the bytes. Null when the URL carried a
21794
+ * credential or signature, which never settles on disk.
21795
+ */
21796
+ sourceUrl: z8.string().nullable(),
21797
+ /** sha256 of the cached bytes; null until the download succeeds. */
21798
+ sha256: z8.string().nullable(),
21799
+ mediaType: z8.string().nullable(),
21800
+ cachedAt: z8.string().nullable()
21801
+ });
21802
+ var ReviewAssetSchema = z8.object({
21803
+ provider: z8.string(),
21804
+ /** The provider job the candidates came from (the lock's `reviewObjectId`). */
21805
+ jobId: z8.string(),
21806
+ generator: z8.string().optional(),
21807
+ mode: z8.enum(["candidates", "frame-set"]),
21808
+ /** Frame-set playback rate. */
21809
+ fps: z8.number().optional(),
21810
+ /** Frame-set object id the provider reported. */
21811
+ objectId: z8.string().optional(),
21812
+ candidates: z8.array(CandidateSchema),
21813
+ /** "pending" while waiting on a choice, "applied" once one was committed. */
21814
+ status: z8.enum(["pending", "applied"]),
21815
+ /** The chosen candidate index, or null while nothing is chosen. */
21816
+ chosen: z8.number().int().nonnegative().nullable(),
21817
+ updatedAt: z8.string()
21818
+ });
21819
+ var ReviewStateSchema = z8.object({
21820
+ version: z8.literal(REVIEW_STATE_VERSION),
21821
+ /** Keyed by lock key (`<style>/<asset>`). */
21822
+ assets: z8.record(ReviewAssetSchema)
21823
+ });
21824
+ function candidateCacheDirFor(lockPath) {
21825
+ return path33.resolve(path33.dirname(lockPath), ".pixelkiln", "cache");
21826
+ }
21827
+ function reviewStatePathFor(lockPath) {
21828
+ const base = path33.basename(lockPath);
21829
+ const name = base === "pixelkiln.lock.json" ? "review-state.json" : `${base.replace(/\.json$/, "")}.review-state.json`;
21830
+ return path33.resolve(path33.dirname(lockPath), ".pixelkiln", name);
21831
+ }
21832
+ async function loadReviewState(file) {
21833
+ if (!existsSync28(file)) return { version: REVIEW_STATE_VERSION, assets: {} };
21834
+ try {
21835
+ const parsed = ReviewStateSchema.safeParse(JSON.parse(await readFile20(file, "utf8")));
21836
+ if (parsed.success) return parsed.data;
21837
+ } catch {
21838
+ }
21839
+ return { version: REVIEW_STATE_VERSION, assets: {} };
21840
+ }
21841
+ async function saveReviewState(file, state) {
21842
+ await mkdir14(path33.dirname(file), { recursive: true });
21843
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
21844
+ try {
21845
+ await writeFile14(tmp, JSON.stringify(state, null, 2) + "\n");
21846
+ await rename8(tmp, file);
21847
+ } finally {
21848
+ await rm7(tmp, { force: true });
21849
+ }
21850
+ }
21851
+ async function updateReviewAsset(file, key3, change) {
21852
+ const state = await loadReviewState(file);
21853
+ const asset = state.assets[key3];
21854
+ if (!asset) return null;
21855
+ const next = { ...change(asset), updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
21856
+ state.assets[key3] = next;
21857
+ await saveReviewState(file, state);
21858
+ return next;
21859
+ }
21860
+ function cachedCandidatePath(cacheDir, candidate) {
21861
+ if (!candidate.sha256 || !candidate.mediaType) return null;
21862
+ const file = path33.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
21863
+ return existsSync28(file) ? file : null;
21864
+ }
21865
+ function fullyCached(cacheDir, asset) {
21866
+ return asset.candidates.length > 0 && asset.candidates.every((c) => cachedCandidatePath(cacheDir, c));
21867
+ }
21868
+ function storableUrl(url) {
21869
+ return isSensitiveSourceUrl(url) ? null : url;
21870
+ }
21871
+ async function downloadCandidate(provider, cacheDir, url, label) {
21872
+ let bytes;
21873
+ try {
21874
+ bytes = await provider.download(url);
21875
+ } catch (err) {
21876
+ const message6 = err instanceof Error ? err.message : String(err);
21877
+ throw new Error(`${label} could not be downloaded (${message6}); the provider has likely expired it`);
21878
+ }
21879
+ const mediaType = detectMediaType(bytes) ?? MediaType.PNG;
21880
+ const hash = sha256(bytes);
21881
+ await cacheMedia(cacheDir, bytes, mediaType, hash);
21882
+ return { sha256: hash, mediaType };
21883
+ }
21884
+ async function cacheReviewCandidates(provider, key3, jobId, job, opts) {
21885
+ const state = await loadReviewState(opts.statePath);
21886
+ const previous = state.assets[key3]?.jobId === jobId ? state.assets[key3] : void 0;
21887
+ const sources = job.status === "review" ? job.candidateUrls.map((url) => ({ url, role: void 0 })) : job.sources.map((source) => ({ url: source.url, role: source.role }));
21888
+ const failed = [];
21889
+ const candidates = [];
21890
+ for (const [index, source] of sources.entries()) {
21891
+ 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));
21892
+ if (known) {
21893
+ candidates.push(known);
21894
+ continue;
21895
+ }
21896
+ try {
21897
+ const cached2 = await downloadCandidate(provider, opts.cacheDir, source.url, `${key3} candidate ${index + 1}`);
21898
+ candidates.push({
21899
+ index,
21900
+ ...source.role ? { role: source.role } : {},
21901
+ sourceUrl: storableUrl(source.url),
21902
+ ...cached2,
21903
+ cachedAt: (/* @__PURE__ */ new Date()).toISOString()
21904
+ });
21905
+ } catch (err) {
21906
+ failed.push(err instanceof Error ? err.message : String(err));
21907
+ candidates.push({
21908
+ index,
21909
+ ...source.role ? { role: source.role } : {},
21910
+ sourceUrl: storableUrl(source.url),
21911
+ sha256: null,
21912
+ mediaType: null,
21913
+ cachedAt: null
21914
+ });
21915
+ }
21916
+ }
21917
+ const asset = {
21918
+ provider: provider.id,
21919
+ jobId,
21920
+ ...opts.generator ? { generator: opts.generator } : {},
21921
+ mode: job.status === "review" ? "candidates" : "frame-set",
21922
+ ...job.status === "review-set" ? { fps: job.fps, objectId: job.objectId } : {},
21923
+ candidates,
21924
+ status: "pending",
21925
+ chosen: previous?.chosen ?? null,
21926
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
21927
+ };
21928
+ const latest = await loadReviewState(opts.statePath);
21929
+ latest.assets[key3] = asset;
21930
+ await saveReviewState(opts.statePath, latest);
21931
+ return { asset, failed };
21932
+ }
21933
+ async function ensureCandidatesCached(provider, key3, opts) {
21934
+ const state = await loadReviewState(opts.statePath);
21935
+ const asset = state.assets[key3];
21936
+ if (!asset) throw new Error(`${key3} has no recorded candidates to recover`);
21937
+ const missing = [];
21938
+ const candidates = [];
21939
+ for (const candidate of asset.candidates) {
21940
+ if (cachedCandidatePath(opts.cacheDir, candidate)) {
21941
+ candidates.push(candidate);
21942
+ continue;
21943
+ }
21944
+ if (!candidate.sourceUrl) {
21945
+ missing.push(`candidate ${candidate.index + 1} has no stored source URL`);
21946
+ candidates.push(candidate);
21947
+ continue;
21948
+ }
21949
+ try {
21950
+ const cached2 = await downloadCandidate(provider, opts.cacheDir, candidate.sourceUrl, `candidate ${candidate.index + 1}`);
21951
+ candidates.push({ ...candidate, ...cached2, cachedAt: (/* @__PURE__ */ new Date()).toISOString() });
21952
+ } catch (err) {
21953
+ missing.push(err instanceof Error ? err.message : String(err));
21954
+ candidates.push(candidate);
21955
+ }
21956
+ }
21957
+ const next = { ...asset, candidates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
21958
+ const latest = await loadReviewState(opts.statePath);
21959
+ latest.assets[key3] = next;
21960
+ await saveReviewState(opts.statePath, latest);
21961
+ if (missing.length) {
21962
+ throw new Error(
21963
+ `${key3}: job ${asset.jobId} expired on the provider before every candidate was cached (${missing.join("; ")}); re-run gen for this asset`
21964
+ );
21965
+ }
21966
+ return next;
21967
+ }
21968
+
21781
21969
  // src/pipeline/poll.ts
21782
21970
  var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
21783
21971
  async function poll(provider, lock, lockPath, opts = {}) {
@@ -21827,6 +22015,16 @@ async function poll(provider, lock, lockPath, opts = {}) {
21827
22015
  billed: state.billed ?? entry.billed
21828
22016
  });
21829
22017
  result.review++;
22018
+ try {
22019
+ const { failed } = await cacheReviewCandidates(provider, key3, entry.jobId, state, {
22020
+ cacheDir: candidateCacheDirFor(lockPath),
22021
+ statePath: reviewStatePathFor(lockPath),
22022
+ generator: entry.generator
22023
+ });
22024
+ for (const message6 of failed) log(` could not cache ${message6}`);
22025
+ } catch (err) {
22026
+ log(` could not cache candidates for ${key3}: ${err instanceof Error ? err.message : String(err)}`);
22027
+ }
21830
22028
  log(
21831
22029
  state.status === "review-set" ? ` review ${key3} (${state.frameUrls.length} ordered frames)` : ` review ${key3} (${state.candidateUrls.length} candidates)`
21832
22030
  );
@@ -21866,13 +22064,13 @@ async function poll(provider, lock, lockPath, opts = {}) {
21866
22064
  }
21867
22065
 
21868
22066
  // src/pipeline/doctor.ts
21869
- import { constants, existsSync as existsSync29 } from "fs";
22067
+ import { constants, existsSync as existsSync30 } from "fs";
21870
22068
  import { access, stat as stat3 } from "fs/promises";
21871
- import path34 from "path";
22069
+ import path35 from "path";
21872
22070
 
21873
22071
  // src/pipeline/install-check.ts
21874
- import { existsSync as existsSync28, readFileSync as readFileSync9 } from "fs";
21875
- import path33 from "path";
22072
+ import { existsSync as existsSync29, readFileSync as readFileSync9 } from "fs";
22073
+ import path34 from "path";
21876
22074
  function readJson(file) {
21877
22075
  try {
21878
22076
  return JSON.parse(readFileSync9(file, "utf8"));
@@ -21881,19 +22079,19 @@ function readJson(file) {
21881
22079
  }
21882
22080
  }
21883
22081
  function readInstallFacts(manifestDir, running) {
21884
- let dir = path33.resolve(manifestDir);
22082
+ let dir = path34.resolve(manifestDir);
21885
22083
  for (let depth = 0; depth < 4; depth++) {
21886
- const pkg = readJson(path33.join(dir, "package.json"));
22084
+ const pkg = readJson(path34.join(dir, "package.json"));
21887
22085
  if (pkg) {
21888
22086
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
21889
22087
  if (pinned) {
21890
- const installedPkg = readJson(path33.join(dir, "node_modules", "pixelkiln", "package.json"));
22088
+ const installedPkg = readJson(path34.join(dir, "node_modules", "pixelkiln", "package.json"));
21891
22089
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
21892
22090
  return { pinned, installed, running };
21893
22091
  }
21894
22092
  }
21895
- const parent = path33.dirname(dir);
21896
- if (parent === dir || !existsSync28(parent)) break;
22093
+ const parent = path34.dirname(dir);
22094
+ if (parent === dir || !existsSync29(parent)) break;
21897
22095
  dir = parent;
21898
22096
  }
21899
22097
  return null;
@@ -21956,12 +22154,12 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21956
22154
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
21957
22155
  );
21958
22156
  }
21959
- const facts = readInstallFacts(path34.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
22157
+ const facts = readInstallFacts(path35.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
21960
22158
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
21961
22159
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
21962
22160
  const dirs = [...new Set(specs.flatMap((spec) => [
21963
- path34.dirname(spec.outFile),
21964
- ...spec.quality ? [path34.dirname(spec.quality.outFile)] : []
22161
+ path35.dirname(spec.outFile),
22162
+ ...spec.quality ? [path35.dirname(spec.quality.outFile)] : []
21965
22163
  ]))];
21966
22164
  const unwritable = [];
21967
22165
  for (const dir of dirs) {
@@ -21984,7 +22182,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21984
22182
  for (let index = 0; index < entry.outputs.length; index++) {
21985
22183
  const output = entry.outputs[index];
21986
22184
  const spec = specByKey.get(key3);
21987
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path34.dirname(lockPath));
22185
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path35.dirname(lockPath));
21988
22186
  const owner = outputOwners.get(absolute);
21989
22187
  if (owner && owner !== key3) duplicateOutputs.push(`${output.path} (${owner}, ${key3})`);
21990
22188
  outputOwners.set(absolute, key3);
@@ -21999,7 +22197,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21999
22197
  } else {
22000
22198
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
22001
22199
  }
22002
- const cacheDir = path34.join(path34.dirname(lockPath), ".pixelkiln", "cache");
22200
+ const cacheDir = path35.join(path35.dirname(lockPath), ".pixelkiln", "cache");
22003
22201
  const stranded = [];
22004
22202
  const invalidState = [];
22005
22203
  const staleMapUrls = [];
@@ -22015,11 +22213,11 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22015
22213
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
22016
22214
  let hasCache = false;
22017
22215
  for (const output of entry.outputs) {
22018
- const cached2 = path34.join(
22216
+ const cached2 = path35.join(
22019
22217
  cacheDir,
22020
22218
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
22021
22219
  );
22022
- if (existsSync29(cached2) && await sha256File(cached2) === output.sha256) {
22220
+ if (existsSync30(cached2) && await sha256File(cached2) === output.sha256) {
22023
22221
  hasCache = true;
22024
22222
  break;
22025
22223
  }
@@ -22115,16 +22313,16 @@ async function nearestExistingDirectory(start) {
22115
22313
  if ((await stat3(current)).isDirectory()) return current;
22116
22314
  } catch {
22117
22315
  }
22118
- const parent = path34.dirname(current);
22316
+ const parent = path35.dirname(current);
22119
22317
  if (parent === current) return current;
22120
22318
  current = parent;
22121
22319
  }
22122
22320
  }
22123
22321
 
22124
22322
  // src/pipeline/adopt.ts
22125
- import { existsSync as existsSync30 } from "fs";
22126
- import { readFile as readFile20, writeFile as writeFile14 } from "fs/promises";
22127
- import path35 from "path";
22323
+ import { existsSync as existsSync31 } from "fs";
22324
+ import { readFile as readFile21, writeFile as writeFile15 } from "fs/promises";
22325
+ import path36 from "path";
22128
22326
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
22129
22327
  const log = opts.onProgress ?? (() => {
22130
22328
  });
@@ -22135,11 +22333,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
22135
22333
  const localByHash = /* @__PURE__ */ new Map();
22136
22334
  const unmatchedLocal = [];
22137
22335
  for (const spec of specs) {
22138
- if (!existsSync30(spec.outFile)) {
22336
+ if (!existsSync31(spec.outFile)) {
22139
22337
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
22140
22338
  continue;
22141
22339
  }
22142
- const bytes = await readFile20(spec.outFile);
22340
+ const bytes = await readFile21(spec.outFile);
22143
22341
  try {
22144
22342
  decodePng(bytes);
22145
22343
  } catch (err) {
@@ -22257,9 +22455,9 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
22257
22455
  }
22258
22456
 
22259
22457
  // src/pipeline/import.ts
22260
- import { existsSync as existsSync31 } from "fs";
22261
- import { readFile as readFile21 } from "fs/promises";
22262
- import path36 from "path";
22458
+ import { existsSync as existsSync32 } from "fs";
22459
+ import { readFile as readFile22 } from "fs/promises";
22460
+ import path37 from "path";
22263
22461
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
22264
22462
  const png = decodePng(bytes);
22265
22463
  const at2 = now.toISOString();
@@ -22311,13 +22509,13 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22311
22509
  if (opts.objectId && specs.length !== 1) {
22312
22510
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
22313
22511
  }
22314
- const cacheDir = opts.cacheDir === false ? null : path36.resolve(opts.cacheDir ?? path36.join(path36.dirname(lockPath), ".pixelkiln", "cache"));
22512
+ const cacheDir = opts.cacheDir === false ? null : path37.resolve(opts.cacheDir ?? path37.join(path37.dirname(lockPath), ".pixelkiln", "cache"));
22315
22513
  let rawSha256;
22316
22514
  let rawBytes;
22317
22515
  if (opts.raw) {
22318
22516
  if (specs.length !== 1) throw new Error(`--raw names one original; ${specs.length} assets are selected. Narrow with --only and --style.`);
22319
22517
  try {
22320
- rawBytes = await readFile21(opts.raw);
22518
+ rawBytes = await readFile22(opts.raw);
22321
22519
  decodePng(rawBytes);
22322
22520
  } catch (error) {
22323
22521
  throw new Error(`--raw ${opts.raw} is not a readable PNG: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
@@ -22333,7 +22531,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22333
22531
  skipped.push({ key: key3, reason });
22334
22532
  continue;
22335
22533
  }
22336
- if (!existsSync31(spec.outFile)) {
22534
+ if (!existsSync32(spec.outFile)) {
22337
22535
  skipped.push({ key: key3, reason: `no file at ${spec.outFile}` });
22338
22536
  continue;
22339
22537
  }
@@ -22344,7 +22542,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22344
22542
  let patch;
22345
22543
  let bytes;
22346
22544
  try {
22347
- bytes = await readFile21(spec.outFile);
22545
+ bytes = await readFile22(spec.outFile);
22348
22546
  patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
22349
22547
  } catch (error) {
22350
22548
  skipped.push({ key: key3, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
@@ -22376,7 +22574,7 @@ async function reportSpecHashes(specs, lock) {
22376
22574
  for (const spec of specs) {
22377
22575
  const key3 = lockKey(spec.styleId, spec.assetId);
22378
22576
  let bytes = null;
22379
- if (existsSync31(spec.outFile)) bytes = await readFile21(spec.outFile);
22577
+ if (existsSync32(spec.outFile)) bytes = await readFile22(spec.outFile);
22380
22578
  let wouldImport = null;
22381
22579
  if (bytes && !unimportable(spec)) {
22382
22580
  try {
@@ -22405,13 +22603,13 @@ async function reportSpecHashes(specs, lock) {
22405
22603
  }
22406
22604
 
22407
22605
  // src/pick/server.ts
22408
- import { existsSync as existsSync33 } from "fs";
22409
- import { readFile as readFile24 } from "fs/promises";
22606
+ import { existsSync as existsSync34 } from "fs";
22607
+ import { readFile as readFile25 } from "fs/promises";
22410
22608
 
22411
22609
  // src/pipeline/init.ts
22412
- import { readdir as readdir4, readFile as readFile22, writeFile as writeFile15 } from "fs/promises";
22413
- import { existsSync as existsSync32 } from "fs";
22414
- import path37 from "path";
22610
+ import { readdir as readdir4, readFile as readFile23, writeFile as writeFile16 } from "fs/promises";
22611
+ import { existsSync as existsSync33 } from "fs";
22612
+ import path38 from "path";
22415
22613
  function pngSize(buf) {
22416
22614
  if (buf.length < 24) return null;
22417
22615
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -22425,7 +22623,7 @@ function slugify(value) {
22425
22623
  async function walk(dir, exclude) {
22426
22624
  const out = [];
22427
22625
  for (const entry of await readdir4(dir, { withFileTypes: true })) {
22428
- const full = path37.join(dir, entry.name);
22626
+ const full = path38.join(dir, entry.name);
22429
22627
  if (exclude.some((x) => full.includes(x))) continue;
22430
22628
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
22431
22629
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -22439,14 +22637,14 @@ async function scanAssets(root, opts = {}) {
22439
22637
  const skipped = [];
22440
22638
  const seen = /* @__PURE__ */ new Map();
22441
22639
  for (const file of files.sort()) {
22442
- const size = pngSize(await readFile22(file));
22640
+ const size = pngSize(await readFile23(file));
22443
22641
  if (!size) {
22444
22642
  skipped.push(`${file} (not a readable PNG)`);
22445
22643
  continue;
22446
22644
  }
22447
- const rel = path37.relative(root, file);
22448
- const category = path37.dirname(rel) === "." ? "" : path37.dirname(rel);
22449
- let id = slugify(path37.basename(rel));
22645
+ const rel = path38.relative(root, file);
22646
+ const category = path38.dirname(rel) === "." ? "" : path38.dirname(rel);
22647
+ let id = slugify(path38.basename(rel));
22450
22648
  if (seen.has(id)) {
22451
22649
  const n = seen.get(id) + 1;
22452
22650
  seen.set(id, n);
@@ -22920,7 +23118,7 @@ document.getElementById('submit').onclick = async () => {
22920
23118
 
22921
23119
  // src/pick/review-server.ts
22922
23120
  import { createServer } from "http";
22923
- import { readFile as readFile23 } from "fs/promises";
23121
+ import { readFile as readFile24 } from "fs/promises";
22924
23122
  function serveReviewPage(opts) {
22925
23123
  const log = opts.onProgress ?? (() => {
22926
23124
  });
@@ -22929,7 +23127,7 @@ function serveReviewPage(opts) {
22929
23127
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
22930
23128
  try {
22931
23129
  const asset = opts.assets.get(req.url);
22932
- const bytes = await readFile23(asset.path);
23130
+ const bytes = await readFile24(asset.path);
22933
23131
  res.writeHead(200, {
22934
23132
  "Content-Type": asset.contentType,
22935
23133
  "Cache-Control": "no-store",
@@ -23005,13 +23203,13 @@ async function currentArt(entry, spec) {
23005
23203
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
23006
23204
  if (!previous) return null;
23007
23205
  const file = resolveOutputPath(previous.path, spec.root);
23008
- if (!existsSync33(file)) return null;
23206
+ if (!existsSync34(file)) return null;
23009
23207
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
23010
23208
  if (!contentType) return null;
23011
23209
  let width = entry.width;
23012
23210
  let height = entry.height;
23013
23211
  if (contentType === "image/png") {
23014
- const size = pngSize(await readFile24(file));
23212
+ const size = pngSize(await readFile25(file));
23015
23213
  if (size) ({ width, height } = size);
23016
23214
  }
23017
23215
  return { path: file, contentType, width, height };
@@ -23019,7 +23217,7 @@ async function currentArt(entry, spec) {
23019
23217
  async function cachedFrame(url) {
23020
23218
  if (!url.startsWith("file://")) return null;
23021
23219
  const file = url.slice("file://".length);
23022
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile24(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
23220
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile25(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
23023
23221
  return { path: file, contentType };
23024
23222
  }
23025
23223
  async function prepareReview(provider, lock, opts = {}) {
@@ -23032,26 +23230,56 @@ async function prepareReview(provider, lock, opts = {}) {
23032
23230
  const reviewAssets = /* @__PURE__ */ new Map();
23033
23231
  const prefix = opts.routePrefix ?? "";
23034
23232
  const providerUrls = /* @__PURE__ */ new Map();
23233
+ const store = opts.lockPath ? { cacheDir: candidateCacheDirFor(opts.lockPath), statePath: reviewStatePathFor(opts.lockPath) } : null;
23234
+ const records = /* @__PURE__ */ new Map();
23035
23235
  const groups = [];
23036
23236
  for (const [key3, entry] of Object.entries(lock.entries)) {
23037
23237
  if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key3)) continue;
23038
23238
  if (entry.status !== "review" || !entry.reviewObjectId) continue;
23039
23239
  try {
23040
23240
  const spec = specByKey.get(key3);
23041
- const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
23042
- if (state.status !== "review" && state.status !== "review-set" || (state.status === "review" ? !state.candidateUrls.length : !state.frameUrls.length)) continue;
23043
- const urls = state.status === "review" ? state.candidateUrls : state.frameUrls;
23241
+ const jobId = entry.reviewObjectId;
23242
+ let polled = null;
23243
+ let pollError = null;
23244
+ try {
23245
+ polled = await provider.poll(jobId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
23246
+ } catch (err) {
23247
+ pollError = err;
23248
+ }
23249
+ const live = polled && (polled.status === "review" && polled.candidateUrls.length || polled.status === "review-set" && polled.frameUrls.length) ? polled : null;
23250
+ let record = null;
23251
+ if (store) {
23252
+ if (live) {
23253
+ const cached2 = await cacheReviewCandidates(provider, key3, jobId, live, { ...store, generator: entry.generator });
23254
+ for (const message6 of cached2.failed) log(` could not cache ${message6}`);
23255
+ record = cached2.asset;
23256
+ } else {
23257
+ const saved = (await loadReviewState(store.statePath)).assets[key3];
23258
+ if (saved && saved.jobId === jobId && saved.provider === provider.id) {
23259
+ record = fullyCached(store.cacheDir, saved) ? saved : await ensureCandidatesCached(provider, key3, store);
23260
+ const why = pollError instanceof Error ? pollError.message : polled ? `job is ${polled.status}` : String(pollError);
23261
+ log(` ${key3}: job no longer available upstream (${why}); using the cached candidates`);
23262
+ }
23263
+ }
23264
+ }
23265
+ if (!live && !record) {
23266
+ if (pollError) throw pollError;
23267
+ continue;
23268
+ }
23269
+ if (record) records.set(key3, record);
23270
+ const urls = live ? live.status === "review" ? live.candidateUrls : live.frameUrls : record.candidates.map((c) => c.sourceUrl ?? `file://${cachedCandidatePath(store.cacheDir, c)}`);
23044
23271
  const frameUrls = [];
23045
23272
  const frameAssets = [];
23046
23273
  const frameSizes = [];
23047
23274
  for (const [index, url] of urls.entries()) {
23048
- const cached2 = await cachedFrame(url);
23275
+ const local = record?.candidates[index] && store ? cachedCandidatePath(store.cacheDir, record.candidates[index]) : null;
23276
+ const cached2 = local ? { path: local, contentType: record.candidates[index].mediaType ?? "application/octet-stream" } : await cachedFrame(url);
23049
23277
  if (!cached2) {
23050
23278
  frameUrls.push(url);
23051
23279
  frameSizes.push(null);
23052
23280
  continue;
23053
23281
  }
23054
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile24(cached2.path).catch(() => Buffer.alloc(0))) : null);
23282
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile25(cached2.path).catch(() => Buffer.alloc(0))) : null);
23055
23283
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
23056
23284
  frameAssets.push([route, cached2]);
23057
23285
  frameUrls.push(route);
@@ -23080,10 +23308,14 @@ async function prepareReview(provider, lock, opts = {}) {
23080
23308
  ...frameSizes.some(Boolean) ? { frameSizes } : {},
23081
23309
  width: entry.width,
23082
23310
  height: entry.height,
23083
- ...state.status === "review-set" ? {
23311
+ ...live?.status === "review-set" ? {
23312
+ mode: "frame-set",
23313
+ frameLabels: live.sources.map((source, index) => source.role ?? `frame-${index}`),
23314
+ fps: live.fps
23315
+ } : !live && record?.mode === "frame-set" ? {
23084
23316
  mode: "frame-set",
23085
- frameLabels: state.sources.map((source, index) => source.role ?? `frame-${index}`),
23086
- fps: state.fps
23317
+ frameLabels: record.candidates.map((c, index) => c.role ?? `frame-${index}`),
23318
+ fps: record.fps ?? 12
23087
23319
  } : { mode: "candidates" },
23088
23320
  ...sourceRoute && spec?.revision && spec.revision.sourceWidth && spec.revision.sourceHeight ? {
23089
23321
  revision: {
@@ -23106,6 +23338,30 @@ async function prepareReview(provider, lock, opts = {}) {
23106
23338
  }
23107
23339
  if (groups.length === 0) return null;
23108
23340
  const byKey = new Map(groups.map((g) => [g.key, g]));
23341
+ const localCandidate = (key3, jobId, index) => {
23342
+ const record = records.get(key3);
23343
+ const candidate = record?.jobId === jobId ? record.candidates[index] : void 0;
23344
+ const file = store && candidate ? cachedCandidatePath(store.cacheDir, candidate) : null;
23345
+ return file ? `file://${file}` : null;
23346
+ };
23347
+ const localFrameSet = (key3, jobId) => {
23348
+ const record = records.get(key3);
23349
+ if (!record || record.jobId !== jobId || record.mode !== "frame-set" || !store || !fullyCached(store.cacheDir, record)) return null;
23350
+ const sources = record.candidates.map((c) => ({
23351
+ url: `file://${cachedCandidatePath(store.cacheDir, c)}`,
23352
+ ...c.role ? { role: c.role } : {}
23353
+ }));
23354
+ return {
23355
+ status: "review-set",
23356
+ objectId: record.objectId ?? jobId,
23357
+ sources,
23358
+ metadata: void 0
23359
+ };
23360
+ };
23361
+ const markApplied = async (key3, index) => {
23362
+ if (!store || !records.has(key3)) return;
23363
+ await updateReviewAsset(store.statePath, key3, (asset) => ({ ...asset, status: "applied", chosen: index }));
23364
+ };
23109
23365
  return {
23110
23366
  groups,
23111
23367
  assets: reviewAssets,
@@ -23120,9 +23376,10 @@ async function prepareReview(provider, lock, opts = {}) {
23120
23376
  if (!Number.isInteger(index) || index < 0 || index >= group.frameUrls.length) continue;
23121
23377
  if (group.mode === "frame-set") {
23122
23378
  const spec = specByKey.get(key3);
23123
- const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
23124
- if (state.status !== "review-set") {
23125
- throw new Error(`Frame set ${key3} is no longer ready for review`);
23379
+ const live = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] }).catch(() => null);
23380
+ const state = live?.status === "review-set" ? live : localFrameSet(key3, entry.reviewObjectId);
23381
+ if (!state) {
23382
+ throw new Error(`Frame set ${key3} is no longer ready for review and has no cached frames`);
23126
23383
  }
23127
23384
  upsert(lock, key3, {
23128
23385
  status: "selected",
@@ -23140,15 +23397,28 @@ async function prepareReview(provider, lock, opts = {}) {
23140
23397
  } : entry.providerMetadata
23141
23398
  });
23142
23399
  selected++;
23143
- log(` accepted ${key3} \u2192 ${state.sources.length} ordered frames`);
23400
+ await markApplied(key3, index);
23401
+ log(` accepted ${key3} \u2192 ${state.sources.length} ordered frames${live?.status === "review-set" ? "" : " (from the local cache)"}`);
23144
23402
  continue;
23145
23403
  }
23146
- const { objectId, sourceUrl, metadata } = await requireSelectCandidate(provider)(
23147
- entry.reviewObjectId,
23148
- index,
23149
- `asset:${entry.assetId}`,
23150
- entry.generator
23151
- );
23404
+ let selection;
23405
+ let fromCache = false;
23406
+ try {
23407
+ selection = await requireSelectCandidate(provider)(
23408
+ entry.reviewObjectId,
23409
+ index,
23410
+ `asset:${entry.assetId}`,
23411
+ entry.generator
23412
+ );
23413
+ } catch (err) {
23414
+ const local = localCandidate(key3, entry.reviewObjectId, index);
23415
+ if (!local) throw err;
23416
+ log(` ${key3}: promotion failed upstream (${err instanceof Error ? err.message : String(err)}); using the cached candidate`);
23417
+ selection = { objectId: `${entry.reviewObjectId}#${index}`, sourceUrl: local };
23418
+ fromCache = true;
23419
+ }
23420
+ const { objectId, metadata } = selection;
23421
+ const sourceUrl = fromCache ? selection.sourceUrl : selection.sourceUrl ?? localCandidate(key3, entry.reviewObjectId, index);
23152
23422
  upsert(lock, key3, {
23153
23423
  status: "selected",
23154
23424
  objectId,
@@ -23165,7 +23435,8 @@ async function prepareReview(provider, lock, opts = {}) {
23165
23435
  } : entry.providerMetadata
23166
23436
  });
23167
23437
  selected++;
23168
- log(` picked ${key3} \u2192 candidate ${index + 1}`);
23438
+ await markApplied(key3, index);
23439
+ log(` picked ${key3} \u2192 candidate ${index + 1}${fromCache ? " (from the local cache)" : ""}`);
23169
23440
  }
23170
23441
  await saveLock(lockPath, lock);
23171
23442
  return { selected, skipped: groups.length - selected };
@@ -23175,19 +23446,33 @@ async function prepareReview(provider, lock, opts = {}) {
23175
23446
  async function runPicker(provider, lock, lockPath, opts = {}) {
23176
23447
  const log = opts.onProgress ?? (() => {
23177
23448
  });
23178
- const session = await prepareReview(provider, lock, {
23449
+ let session = await prepareReview(provider, lock, {
23179
23450
  onProgress: log,
23180
23451
  keys: opts.keys,
23181
- specs: opts.specs
23452
+ specs: opts.specs,
23453
+ lockPath
23182
23454
  });
23183
23455
  if (!session) return { selected: 0, skipped: 0 };
23184
- const groups = session.groups;
23185
- return serveReviewPage({
23186
- html: session.html(),
23456
+ let autoSelected = 0;
23457
+ if (opts.autoAcceptSingle) {
23458
+ const singles = session.groups.filter((g) => g.mode === "frame-set" || g.frameUrls.length === 1);
23459
+ if (singles.length) {
23460
+ const res = await session.apply({ selections: singles.map((g) => ({ key: g.key, index: 0 })) }, lockPath);
23461
+ autoSelected = res.selected;
23462
+ log(` --yes: accepted ${res.selected} single-candidate asset(s)`);
23463
+ const rest = session.groups.filter((g) => !singles.includes(g)).map((g) => g.key);
23464
+ session = rest.length ? await prepareReview(provider, lock, { onProgress: log, keys: rest, specs: opts.specs }) : null;
23465
+ if (!session) return { selected: autoSelected, skipped: 0 };
23466
+ }
23467
+ }
23468
+ const live = session;
23469
+ const groups = live.groups;
23470
+ const served = await serveReviewPage({
23471
+ html: live.html(),
23187
23472
  port: opts.port,
23188
23473
  open: opts.open,
23189
23474
  onProgress: log,
23190
- assets: session.assets,
23475
+ assets: live.assets,
23191
23476
  onReady: (url) => {
23192
23477
  const info = { url, keys: groups.map((group) => group.key) };
23193
23478
  if (opts.onReady) {
@@ -23199,21 +23484,22 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
23199
23484
  `);
23200
23485
  }
23201
23486
  },
23202
- handleApply: (body) => session.apply(body, lockPath)
23487
+ handleApply: (body) => live.apply(body, lockPath)
23203
23488
  });
23489
+ return { selected: served.selected + autoSelected, skipped: served.skipped };
23204
23490
  }
23205
23491
 
23206
23492
  // src/gallery/snapshot.ts
23207
23493
  import { createHash as createHash8 } from "crypto";
23208
- import { existsSync as existsSync42 } from "fs";
23209
- import { readFile as readFile34, stat as stat5 } from "fs/promises";
23210
- import path48 from "path";
23494
+ import { existsSync as existsSync43 } from "fs";
23495
+ import { readFile as readFile35, stat as stat5 } from "fs/promises";
23496
+ import path49 from "path";
23211
23497
 
23212
23498
  // src/gallery/models.ts
23213
- import { existsSync as existsSync37 } from "fs";
23214
- import { readFile as readFile29, stat as stat4 } from "fs/promises";
23215
- import path42 from "path";
23216
- import { z as z11 } from "zod";
23499
+ import { existsSync as existsSync38 } from "fs";
23500
+ import { readFile as readFile30, stat as stat4 } from "fs/promises";
23501
+ import path43 from "path";
23502
+ import { z as z12 } from "zod";
23217
23503
 
23218
23504
  // src/glb.ts
23219
23505
  var MAGIC = 1179937895;
@@ -23545,57 +23831,57 @@ function modelItems(json) {
23545
23831
  }
23546
23832
 
23547
23833
  // src/manifest-edit.ts
23548
- import { readFile as readFile25, rename as rename8, rm as rm7, writeFile as writeFile16 } from "fs/promises";
23549
- import path38 from "path";
23550
- import { z as z8 } from "zod";
23551
- var HexSha = z8.string().regex(/^[0-9a-f]{64}$/);
23552
- var ProjectFileSchema = z8.string().min(1).refine((file) => !path38.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
23553
- var AssetPatchSchema = z8.object({
23554
- prompt: z8.string().optional(),
23834
+ import { readFile as readFile26, rename as rename9, rm as rm8, writeFile as writeFile17 } from "fs/promises";
23835
+ import path39 from "path";
23836
+ import { z as z9 } from "zod";
23837
+ var HexSha = z9.string().regex(/^[0-9a-f]{64}$/);
23838
+ var ProjectFileSchema = z9.string().min(1).refine((file) => !path39.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
23839
+ var AssetPatchSchema = z9.object({
23840
+ prompt: z9.string().optional(),
23555
23841
  /** Per-style override for the style being viewed; null removes it. */
23556
- promptForStyle: z8.object({ styleId: z8.string().min(1), prompt: z8.string().nullable() }).optional(),
23557
- category: z8.string().nullable().optional(),
23558
- width: z8.number().int().nullable().optional(),
23559
- height: z8.number().int().nullable().optional(),
23560
- size: z8.number().int().nullable().optional(),
23561
- tags: z8.array(z8.string()).optional(),
23842
+ promptForStyle: z9.object({ styleId: z9.string().min(1), prompt: z9.string().nullable() }).optional(),
23843
+ category: z9.string().nullable().optional(),
23844
+ width: z9.number().int().nullable().optional(),
23845
+ height: z9.number().int().nullable().optional(),
23846
+ size: z9.number().int().nullable().optional(),
23847
+ tags: z9.array(z9.string()).optional(),
23562
23848
  /**
23563
23849
  * A loop shorthand's `animation.directions`, replaced whole: each named
23564
23850
  * direction is drawn, and each one's flip comes free as a mirror.
23565
23851
  */
23566
- loopDirections: z8.array(CharacterDirectionSchema).min(1).optional()
23852
+ loopDirections: z9.array(CharacterDirectionSchema).min(1).optional()
23567
23853
  }).strict();
23568
- var NewStateSchema = z8.object({
23854
+ var NewStateSchema = z9.object({
23569
23855
  /** Asset id of the parent this states; must already exist. */
23570
- of: z8.string().min(1),
23571
- paletteFromReference: z8.boolean().optional(),
23572
- canvas: z8.object({ width: z8.number().int().min(16).max(256), height: z8.number().int().min(16).max(256) }).strict().optional()
23856
+ of: z9.string().min(1),
23857
+ paletteFromReference: z9.boolean().optional(),
23858
+ canvas: z9.object({ width: z9.number().int().min(16).max(256), height: z9.number().int().min(16).max(256) }).strict().optional()
23573
23859
  }).strict();
23574
- var NewAnimationSchema = z8.object({
23860
+ var NewAnimationSchema = z9.object({
23575
23861
  /** Asset id of the parent this animates; must already exist. */
23576
- of: z8.string().min(1),
23862
+ of: z9.string().min(1),
23577
23863
  /** A PixelLab template id (`character` only; `objectPro` has no template concept). */
23578
- template: z8.string().min(1).optional(),
23864
+ template: z9.string().min(1).optional(),
23579
23865
  direction: CharacterDirectionSchema.optional(),
23580
- frames: z8.number().int().min(4).max(16).optional(),
23581
- fps: z8.number().int().min(1).max(60).optional(),
23866
+ frames: z9.number().int().min(4).max(16).optional(),
23867
+ fps: z9.number().int().min(1).max(60).optional(),
23582
23868
  /** One loop per named direction, plus free mirrors; expanded when the manifest loads. */
23583
- directions: z8.array(CharacterDirectionSchema).min(1).optional(),
23869
+ directions: z9.array(CharacterDirectionSchema).min(1).optional(),
23584
23870
  mode: CharacterAnimationModeSchema.optional(),
23585
23871
  /** What is being animated, when the parent's own description would mislead the model (`character` only). */
23586
- subject: z8.string().min(1).optional(),
23587
- enhancePrompt: z8.boolean().optional()
23872
+ subject: z9.string().min(1).optional(),
23873
+ enhancePrompt: z9.boolean().optional()
23588
23874
  }).strict();
23589
- var NewAssetSchema = z8.object({
23875
+ var NewAssetSchema = z9.object({
23590
23876
  /** A portrait, an outfit, or a mirror has none of its own; the loader says where one is needed. */
23591
- prompt: z8.string().optional(),
23592
- category: z8.string().optional(),
23593
- width: z8.number().int().optional(),
23594
- height: z8.number().int().optional(),
23595
- size: z8.number().int().optional(),
23596
- tags: z8.array(z8.string()).optional(),
23877
+ prompt: z9.string().optional(),
23878
+ category: z9.string().optional(),
23879
+ width: z9.number().int().optional(),
23880
+ height: z9.number().int().optional(),
23881
+ size: z9.number().int().optional(),
23882
+ tags: z9.array(z9.string()).optional(),
23597
23883
  /** Restrict to these styles; empty or omitted means every style. */
23598
- styles: z8.array(z8.string().min(1)).optional(),
23884
+ styles: z9.array(z9.string().min(1)).optional(),
23599
23885
  /**
23600
23886
  * A controlled regeneration of another asset in the same manifest,
23601
23887
  * instead of a fresh generation. Every mode but `outpaint` can be
@@ -23604,68 +23890,68 @@ var NewAssetSchema = z8.object({
23604
23890
  * keyframe, and `animate-skeleton` names the keypoints file the gallery
23605
23891
  * wrote first.
23606
23892
  */
23607
- revision: z8.discriminatedUnion("mode", [
23608
- z8.object({
23609
- mode: z8.literal("image-to-image"),
23893
+ revision: z9.discriminatedUnion("mode", [
23894
+ z9.object({
23895
+ mode: z9.literal("image-to-image"),
23610
23896
  /** Asset id of the parent this revises; must already exist. */
23611
- from: z8.string().min(1),
23612
- strength: z8.number().min(0).max(1).optional()
23897
+ from: z9.string().min(1),
23898
+ strength: z9.number().min(0).max(1).optional()
23613
23899
  }).strict(),
23614
- z8.object({
23615
- mode: z8.literal("reduce-colors"),
23616
- from: z8.string().min(1),
23900
+ z9.object({
23901
+ mode: z9.literal("reduce-colors"),
23902
+ from: z9.string().min(1),
23617
23903
  /** A target colour count; the gallery leaves PixelLab's default when this is omitted. */
23618
- numColors: z8.number().int().min(2).max(256).optional(),
23904
+ numColors: z9.number().int().min(2).max(256).optional(),
23619
23905
  dithering: RevisionDitheringSchema.optional(),
23620
- ditheringStrength: z8.number().min(0).max(10).optional()
23906
+ ditheringStrength: z9.number().min(0).max(10).optional()
23621
23907
  }).strict(),
23622
- z8.object({
23623
- mode: z8.literal("inpaint"),
23624
- from: z8.string().min(1),
23908
+ z9.object({
23909
+ mode: z9.literal("inpaint"),
23910
+ from: z9.string().min(1),
23625
23911
  /** Black-and-white PNG the same size as the parent; white is repainted. */
23626
23912
  mask: ProjectFileSchema
23627
23913
  }).strict(),
23628
- z8.object({
23629
- mode: z8.literal("interpolate"),
23630
- from: z8.string().min(1),
23914
+ z9.object({
23915
+ mode: z9.literal("interpolate"),
23916
+ from: z9.string().min(1),
23631
23917
  /** The ending keyframe: an image already in the project, the parent's size. */
23632
23918
  lastFrame: ProjectFileSchema,
23633
- fps: z8.number().int().min(1).max(60).optional()
23919
+ fps: z9.number().int().min(1).max(60).optional()
23634
23920
  }).strict(),
23635
- z8.object({ mode: z8.literal("correct-pixelart"), from: z8.string().min(1), strength: z8.number().min(0).max(1).optional() }).strict(),
23636
- z8.object({
23637
- mode: z8.literal("remove-background"),
23638
- from: z8.string().min(1),
23639
- removalTask: z8.enum(["simple", "complex"]).optional(),
23921
+ z9.object({ mode: z9.literal("correct-pixelart"), from: z9.string().min(1), strength: z9.number().min(0).max(1).optional() }).strict(),
23922
+ z9.object({
23923
+ mode: z9.literal("remove-background"),
23924
+ from: z9.string().min(1),
23925
+ removalTask: z9.enum(["simple", "complex"]).optional(),
23640
23926
  /** A short description of the foreground, sent as PixelLab's text hint. */
23641
- description: z8.string().min(1).optional()
23927
+ description: z9.string().min(1).optional()
23642
23928
  }).strict(),
23643
- z8.object({ mode: z8.literal("normal-map"), from: z8.string().min(1), convention: NormalMapConventionSchema.optional() }).strict(),
23644
- z8.object({
23645
- mode: z8.enum(["animate", "animate-pixminimax"]),
23646
- from: z8.string().min(1),
23647
- frames: z8.number().int().min(4).max(40).refine((n) => n % 2 === 0, "frames must be even").optional(),
23648
- fps: z8.number().int().min(1).max(60).optional(),
23649
- enhancePrompt: z8.boolean().optional(),
23650
- driftThreshold: z8.number().min(0).optional(),
23929
+ z9.object({ mode: z9.literal("normal-map"), from: z9.string().min(1), convention: NormalMapConventionSchema.optional() }).strict(),
23930
+ z9.object({
23931
+ mode: z9.enum(["animate", "animate-pixminimax"]),
23932
+ from: z9.string().min(1),
23933
+ frames: z9.number().int().min(4).max(40).refine((n) => n % 2 === 0, "frames must be even").optional(),
23934
+ fps: z9.number().int().min(1).max(60).optional(),
23935
+ enhancePrompt: z9.boolean().optional(),
23936
+ driftThreshold: z9.number().min(0).optional(),
23651
23937
  /** `animate-pixminimax` only; the loader refuses these on `animate`. */
23652
23938
  direction: CharacterDirectionSchema.optional(),
23653
- subjectDescription: z8.string().min(1).max(300).optional(),
23654
- initialPose: z8.string().min(1).max(300).optional()
23939
+ subjectDescription: z9.string().min(1).max(300).optional(),
23940
+ initialPose: z9.string().min(1).max(300).optional()
23655
23941
  }).strict(),
23656
- z8.object({
23657
- mode: z8.literal("edit-animation"),
23658
- from: z8.string().min(1),
23659
- fps: z8.number().int().min(1).max(60).optional()
23942
+ z9.object({
23943
+ mode: z9.literal("edit-animation"),
23944
+ from: z9.string().min(1),
23945
+ fps: z9.number().int().min(1).max(60).optional()
23660
23946
  }).strict(),
23661
- z8.object({
23662
- mode: z8.literal("animate-skeleton"),
23663
- from: z8.string().min(1),
23947
+ z9.object({
23948
+ mode: z9.literal("animate-skeleton"),
23949
+ from: z9.string().min(1),
23664
23950
  /** Manifest-relative; checked when the manifest is loaded, like every revision input. */
23665
- keypointsFile: z8.string().min(1),
23951
+ keypointsFile: z9.string().min(1),
23666
23952
  direction: CharacterDirectionSchema,
23667
- description: z8.string().min(1).optional(),
23668
- skeletonTemplate: z8.string().min(1).optional()
23953
+ description: z9.string().min(1).optional(),
23954
+ skeletonTemplate: z9.string().min(1).optional()
23669
23955
  }).strict()
23670
23956
  ]).optional(),
23671
23957
  /** A pose or outfit of an existing `character`/`objectPro` base or state. */
@@ -23677,16 +23963,16 @@ var NewAssetSchema = z8.object({
23677
23963
  /** An existing loop re-clothed from a reference image (uploaded first). */
23678
23964
  outfit: CharacterOutfitSchema.optional(),
23679
23965
  /** Another asset of the same style, flipped; free. */
23680
- mirror: z8.string().min(1).optional(),
23966
+ mirror: z9.string().min(1).optional(),
23681
23967
  /**
23682
23968
  * `character`/`objectPro` bases: the subject's own sprite (uploaded
23683
23969
  * first), or one per direction, which PixelLab rotates instead of drawing.
23684
23970
  */
23685
- reference: z8.union([z8.string().min(1), z8.record(CharacterDirectionSchema, z8.string().min(1))]).optional(),
23971
+ reference: z9.union([z9.string().min(1), z9.record(CharacterDirectionSchema, z9.string().min(1))]).optional(),
23686
23972
  /** `character` pro bases: a concept image that seeds the design. */
23687
- concept: z8.string().min(1).optional(),
23973
+ concept: z9.string().min(1).optional(),
23688
23974
  /** `character` pro bases: another character in the style whose look this one follows. */
23689
- styleCharacter: z8.string().min(1).optional(),
23975
+ styleCharacter: z9.string().min(1).optional(),
23690
23976
  /** `character` standard humanoid bases: this character's proportions, over the style's. */
23691
23977
  proportions: CharacterProportionsSchema.optional()
23692
23978
  }).strict().refine((asset) => !(asset.revision && (asset.state || asset.animation)), {
@@ -23699,79 +23985,79 @@ var CANDIDATE_OPTION = {
23699
23985
  comfyui: "numImages",
23700
23986
  scenario: "numOutputs"
23701
23987
  };
23702
- var NewStyleSchema = z8.object({
23703
- generator: z8.enum(["character", "objectPro"]),
23988
+ var NewStyleSchema = z9.object({
23989
+ generator: z9.enum(["character", "objectPro"]),
23704
23990
  /** Where the style's art is written, inside the project. */
23705
- outDir: z8.string().min(1).refine((dir) => !dir.split(/[\\/]/).includes("..") && !/^([a-z]:)?[\\/]/i.test(dir), {
23991
+ outDir: z9.string().min(1).refine((dir) => !dir.split(/[\\/]/).includes("..") && !/^([a-z]:)?[\\/]/i.test(dir), {
23706
23992
  message: "outDir must be a path inside the project"
23707
23993
  }),
23708
- size: z8.number().int().min(16).max(256).optional(),
23994
+ size: z9.number().int().min(16).max(256).optional(),
23709
23995
  mode: CharacterModeSchema.optional(),
23710
- directions: z8.union([z8.literal(4), z8.literal(8)]).optional(),
23711
- template: z8.string().min(1).optional(),
23712
- view: z8.string().min(1).max(64).optional(),
23996
+ directions: z9.union([z9.literal(4), z9.literal(8)]).optional(),
23997
+ template: z9.string().min(1).optional(),
23998
+ view: z9.string().min(1).max(64).optional(),
23713
23999
  proportions: CharacterProportionsSchema.optional(),
23714
- isometric: z8.boolean().optional(),
23715
- textGuidanceScale: z8.number().min(1).max(20).optional(),
23716
- enhancePrompt: z8.boolean().optional(),
23717
- promptPrefix: z8.string().optional(),
23718
- promptSuffix: z8.string().optional(),
23719
- palette: z8.array(z8.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).optional()
24000
+ isometric: z9.boolean().optional(),
24001
+ textGuidanceScale: z9.number().min(1).max(20).optional(),
24002
+ enhancePrompt: z9.boolean().optional(),
24003
+ promptPrefix: z9.string().optional(),
24004
+ promptSuffix: z9.string().optional(),
24005
+ palette: z9.array(z9.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).optional()
23720
24006
  }).strict();
23721
- var PatchAssetEdit = z8.object({
23722
- action: z8.literal("patch-asset"),
23723
- assetId: z8.string().min(1),
24007
+ var PatchAssetEdit = z9.object({
24008
+ action: z9.literal("patch-asset"),
24009
+ assetId: z9.string().min(1),
23724
24010
  patch: AssetPatchSchema
23725
24011
  }).strict();
23726
- var AddAssetEdit = z8.object({
23727
- action: z8.literal("add-asset"),
23728
- assetId: z8.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
24012
+ var AddAssetEdit = z9.object({
24013
+ action: z9.literal("add-asset"),
24014
+ assetId: z9.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
23729
24015
  asset: NewAssetSchema
23730
24016
  }).strict();
23731
- var SetSourceEdit = z8.object({
23732
- action: z8.literal("set-source"),
23733
- assetId: z8.string().min(1),
23734
- styleId: z8.string().min(1),
24017
+ var SetSourceEdit = z9.object({
24018
+ action: z9.literal("set-source"),
24019
+ assetId: z9.string().min(1),
24020
+ styleId: z9.string().min(1),
23735
24021
  /** Manifest-relative path of the art that stands in for this asset in this style. */
23736
- source: z8.string().min(1)
24022
+ source: z9.string().min(1)
23737
24023
  }).strict();
23738
- var ClearSourceEdit = z8.object({
23739
- action: z8.literal("clear-source"),
23740
- assetId: z8.string().min(1),
23741
- styleId: z8.string().min(1)
24024
+ var ClearSourceEdit = z9.object({
24025
+ action: z9.literal("clear-source"),
24026
+ assetId: z9.string().min(1),
24027
+ styleId: z9.string().min(1)
23742
24028
  }).strict();
23743
- var PatchStyleEdit = z8.object({
23744
- action: z8.literal("patch-style"),
23745
- styleId: z8.string().min(1),
23746
- patch: z8.object({
24029
+ var PatchStyleEdit = z9.object({
24030
+ action: z9.literal("patch-style"),
24031
+ styleId: z9.string().min(1),
24032
+ patch: z9.object({
23747
24033
  /** Candidates per generation, written to the provider's own option. */
23748
- candidates: z8.number().int().min(1).max(64).optional(),
24034
+ candidates: z9.number().int().min(1).max(64).optional(),
23749
24035
  /** Empty clears the style's own value (inherit, or the default). */
23750
- promptPrefix: z8.string().optional(),
23751
- promptSuffix: z8.string().optional(),
24036
+ promptPrefix: z9.string().optional(),
24037
+ promptSuffix: z9.string().optional(),
23752
24038
  /** `#rrggbb` values; null or empty clears the style's own palette. */
23753
- palette: z8.array(z8.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).nullable().optional(),
24039
+ palette: z9.array(z9.string().regex(/^#?[0-9a-f]{6}$/i, "expected a six-digit hex colour")).max(256).nullable().optional(),
23754
24040
  /** Snap downloaded art to the palette; false clears the style's own value. */
23755
- enforcePalette: z8.boolean().optional(),
24041
+ enforcePalette: z9.boolean().optional(),
23756
24042
  /** Provider view name (PixelLab: low top-down, high top-down, side); empty clears. */
23757
- view: z8.string().max(64).nullable().optional(),
24043
+ view: z9.string().max(64).nullable().optional(),
23758
24044
  /** pixflux only; null clears the style's own value. */
23759
- noBackground: z8.boolean().nullable().optional()
24045
+ noBackground: z9.boolean().nullable().optional()
23760
24046
  }).strict().refine((patch) => Object.keys(patch).length > 0, { message: "nothing to change" })
23761
24047
  }).strict();
23762
- var AddStyleEdit = z8.object({
23763
- action: z8.literal("add-style"),
23764
- styleId: z8.string().min(1).regex(/^[^/\\:]+$/, "style ids cannot contain slashes or colons"),
24048
+ var AddStyleEdit = z9.object({
24049
+ action: z9.literal("add-style"),
24050
+ styleId: z9.string().min(1).regex(/^[^/\\:]+$/, "style ids cannot contain slashes or colons"),
23765
24051
  style: NewStyleSchema
23766
24052
  }).strict();
23767
24053
  var Envelope = {
23768
24054
  /** Workspace project id; omitted for a single-project gallery. */
23769
- project: z8.string().min(1).optional(),
24055
+ project: z9.string().min(1).optional(),
23770
24056
  /** Manifest bytes the page last saw; a mismatch refuses the write. */
23771
24057
  expectedSha256: HexSha
23772
24058
  };
23773
- var SingleEdit = z8.discriminatedUnion("action", [PatchAssetEdit, AddAssetEdit, SetSourceEdit, ClearSourceEdit, PatchStyleEdit, AddStyleEdit]);
23774
- var ManifestEditSchema = z8.discriminatedUnion("action", [
24059
+ var SingleEdit = z9.discriminatedUnion("action", [PatchAssetEdit, AddAssetEdit, SetSourceEdit, ClearSourceEdit, PatchStyleEdit, AddStyleEdit]);
24060
+ var ManifestEditSchema = z9.discriminatedUnion("action", [
23775
24061
  PatchAssetEdit.extend(Envelope),
23776
24062
  AddAssetEdit.extend(Envelope),
23777
24063
  SetSourceEdit.extend(Envelope),
@@ -23784,10 +24070,10 @@ var ManifestEditSchema = z8.discriminatedUnion("action", [
23784
24070
  * Each edit sees the ones before it, so a base can name a style the same
23785
24071
  * batch adds.
23786
24072
  */
23787
- z8.object({
23788
- action: z8.literal("batch"),
24073
+ z9.object({
24074
+ action: z9.literal("batch"),
23789
24075
  ...Envelope,
23790
- edits: z8.array(SingleEdit).min(1).max(64)
24076
+ edits: z9.array(SingleEdit).min(1).max(64)
23791
24077
  }).strict()
23792
24078
  ]);
23793
24079
  var ManifestDriftError = class extends Error {
@@ -23969,8 +24255,8 @@ function applyEdit(raw, edit) {
23969
24255
  }
23970
24256
  }
23971
24257
  async function withCandidate(manifestPath, edit, use, unchanged) {
23972
- const absolute = path38.resolve(manifestPath);
23973
- const original = await readFile25(absolute, "utf8");
24258
+ const absolute = path39.resolve(manifestPath);
24259
+ const original = await readFile26(absolute, "utf8");
23974
24260
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
23975
24261
  let raw;
23976
24262
  try {
@@ -23983,12 +24269,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
23983
24269
  applyEdit(raw, edit);
23984
24270
  const next = serializeLike(original, raw);
23985
24271
  if (next === original) return unchanged(absolute, original);
23986
- const tmp = path38.join(
23987
- path38.dirname(absolute),
23988
- `.${path38.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
24272
+ const tmp = path39.join(
24273
+ path39.dirname(absolute),
24274
+ `.${path39.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
23989
24275
  );
23990
24276
  try {
23991
- await writeFile16(tmp, next);
24277
+ await writeFile17(tmp, next);
23992
24278
  let specs;
23993
24279
  try {
23994
24280
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -23998,7 +24284,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
23998
24284
  }
23999
24285
  return await use({ absolute, original, next, tmp, specs });
24000
24286
  } finally {
24001
- await rm7(tmp, { force: true });
24287
+ await rm8(tmp, { force: true });
24002
24288
  }
24003
24289
  }
24004
24290
  async function applyManifestEdit(manifestPath, edit) {
@@ -24006,7 +24292,7 @@ async function applyManifestEdit(manifestPath, edit) {
24006
24292
  manifestPath,
24007
24293
  edit,
24008
24294
  async ({ absolute, next, tmp }) => {
24009
- await rename8(tmp, absolute);
24295
+ await rename9(tmp, absolute);
24010
24296
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
24011
24297
  },
24012
24298
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -24014,18 +24300,18 @@ async function applyManifestEdit(manifestPath, edit) {
24014
24300
  }
24015
24301
 
24016
24302
  // src/pipeline/hand-edit.ts
24017
- import { existsSync as existsSync34 } from "fs";
24018
- import { copyFile, mkdir as mkdir14, readFile as readFile26, rename as rename9, rm as rm8, writeFile as writeFile17 } from "fs/promises";
24019
- import path39 from "path";
24020
- import { z as z9 } from "zod";
24303
+ import { existsSync as existsSync35 } from "fs";
24304
+ import { copyFile, mkdir as mkdir15, readFile as readFile27, rename as rename10, rm as rm9, writeFile as writeFile18 } from "fs/promises";
24305
+ import path40 from "path";
24306
+ import { z as z10 } from "zod";
24021
24307
  var HAND_EDIT_DIR = "edits";
24022
24308
  function handEditPath(loaded, spec) {
24023
24309
  const style = loaded.manifest.styles[spec.styleId];
24024
- const outDir = path39.resolve(loaded.root, style?.outDir ?? ".");
24025
- const relative = path39.relative(outDir, spec.outFile);
24026
- const inside2 = relative && !relative.startsWith("..") && !path39.isAbsolute(relative);
24027
- const file = inside2 ? relative : path39.basename(spec.outFile);
24028
- return path39.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
24310
+ const outDir = path40.resolve(loaded.root, style?.outDir ?? ".");
24311
+ const relative = path40.relative(outDir, spec.outFile);
24312
+ const inside2 = relative && !relative.startsWith("..") && !path40.isAbsolute(relative);
24313
+ const file = inside2 ? relative : path40.basename(spec.outFile);
24314
+ return path40.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
24029
24315
  }
24030
24316
  function handEditBases(spec, lock) {
24031
24317
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -24038,10 +24324,10 @@ function handEditBases(spec, lock) {
24038
24324
  }));
24039
24325
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
24040
24326
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
24041
- if (!members.every((member) => existsSync34(member.path))) return null;
24327
+ if (!members.every((member) => existsSync35(member.path))) return null;
24042
24328
  return members.map(({ role, path: file }) => ({ role, path: file }));
24043
24329
  }
24044
- return existsSync34(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
24330
+ return existsSync35(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
24045
24331
  }
24046
24332
  function handEditBase(spec, lock) {
24047
24333
  const bases = handEditBases(spec, lock);
@@ -24091,18 +24377,18 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
24091
24377
  `${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`
24092
24378
  );
24093
24379
  }
24094
- const existing = spec.source ? path39.resolve(loaded.root, spec.source) : null;
24380
+ const existing = spec.source ? path40.resolve(loaded.root, spec.source) : null;
24095
24381
  const editPath = existing ?? handEditPath(loaded, spec);
24096
24382
  const members = handEditMembers(loaded, spec, lock, editPath);
24097
24383
  let created = false;
24098
24384
  for (const member of members) {
24099
- if (existsSync34(member.path)) continue;
24385
+ if (existsSync35(member.path)) continue;
24100
24386
  if (!member.base) {
24101
24387
  throw new ManifestEditError(
24102
24388
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
24103
24389
  );
24104
24390
  }
24105
- await mkdir14(path39.dirname(member.path), { recursive: true });
24391
+ await mkdir15(path40.dirname(member.path), { recursive: true });
24106
24392
  await copyFile(member.base, member.path);
24107
24393
  created = true;
24108
24394
  }
@@ -24134,35 +24420,35 @@ async function detachHandEdit(loaded, spec, opts = {}) {
24134
24420
  });
24135
24421
  return { manifestSha256: result.sha256, changed: result.changed };
24136
24422
  }
24137
- var CompanionOutputSchema = z9.object({
24423
+ var CompanionOutputSchema = z10.object({
24138
24424
  /** Output role for a set member; null for a single image. */
24139
- role: z9.string().nullable(),
24425
+ role: z10.string().nullable(),
24140
24426
  /** sha256 of the generated file this member started from; null when it started from untracked art. */
24141
- basedOn: z9.string().regex(/^[0-9a-f]{64}$/).nullable(),
24427
+ basedOn: z10.string().regex(/^[0-9a-f]{64}$/).nullable(),
24142
24428
  /** sha256 of the member as saved, so a later change by another tool is visible. */
24143
- sha256: z9.string().regex(/^[0-9a-f]{64}$/)
24429
+ sha256: z10.string().regex(/^[0-9a-f]{64}$/)
24144
24430
  }).strict();
24145
- var CompanionV2Schema = z9.object({
24146
- version: z9.literal(2),
24431
+ var CompanionV2Schema = z10.object({
24432
+ version: z10.literal(2),
24147
24433
  /** Editor identity the bridge reported, e.g. `pixelorama@v1.2.2-stable`. */
24148
- editor: z9.string().min(1),
24149
- protocol: z9.number().int().positive(),
24150
- savedAt: z9.string().datetime(),
24434
+ editor: z10.string().min(1),
24435
+ protocol: z10.number().int().positive(),
24436
+ savedAt: z10.string().datetime(),
24151
24437
  /** Basename of the layered project file beside the edit, when one was kept. */
24152
- project: z9.string().min(1).nullable(),
24438
+ project: z10.string().min(1).nullable(),
24153
24439
  /** One entry per file, in output order. */
24154
- outputs: z9.array(CompanionOutputSchema).min(1)
24440
+ outputs: z10.array(CompanionOutputSchema).min(1)
24155
24441
  }).strict();
24156
- var CompanionV1Schema = z9.object({
24157
- version: z9.literal(1),
24158
- basedOn: z9.string().regex(/^[0-9a-f]{64}$/).nullable(),
24159
- sha256: z9.string().regex(/^[0-9a-f]{64}$/),
24160
- editor: z9.string().min(1),
24161
- protocol: z9.number().int().positive(),
24162
- savedAt: z9.string().datetime(),
24163
- project: z9.string().min(1).nullable()
24442
+ var CompanionV1Schema = z10.object({
24443
+ version: z10.literal(1),
24444
+ basedOn: z10.string().regex(/^[0-9a-f]{64}$/).nullable(),
24445
+ sha256: z10.string().regex(/^[0-9a-f]{64}$/),
24446
+ editor: z10.string().min(1),
24447
+ protocol: z10.number().int().positive(),
24448
+ savedAt: z10.string().datetime(),
24449
+ project: z10.string().min(1).nullable()
24164
24450
  }).strict();
24165
- var HandEditCompanionSchema = z9.union([CompanionV2Schema, CompanionV1Schema]).transform(
24451
+ var HandEditCompanionSchema = z10.union([CompanionV2Schema, CompanionV1Schema]).transform(
24166
24452
  (value) => value.version === 2 ? value : {
24167
24453
  version: 2,
24168
24454
  editor: value.editor,
@@ -24181,7 +24467,7 @@ function handEditProjectPath(editPath) {
24181
24467
  async function readHandEditCompanion(editPath) {
24182
24468
  let text;
24183
24469
  try {
24184
- text = await readFile26(handEditCompanionPath(editPath), "utf8");
24470
+ text = await readFile27(handEditCompanionPath(editPath), "utf8");
24185
24471
  } catch {
24186
24472
  return null;
24187
24473
  }
@@ -24225,7 +24511,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
24225
24511
  }
24226
24512
  });
24227
24513
  const bases = handEditBases(spec, lock);
24228
- const expectedSize = bases?.[0] ? decodePng(await readFile26(bases[0].path)) : { width: spec.width, height: spec.height };
24514
+ const expectedSize = bases?.[0] ? decodePng(await readFile27(bases[0].path)) : { width: spec.width, height: spec.height };
24229
24515
  for (const [index, image] of decoded.entries()) {
24230
24516
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
24231
24517
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -24241,7 +24527,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
24241
24527
  editor: input.editor,
24242
24528
  protocol: input.protocol,
24243
24529
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
24244
- project: projectPath ? path39.basename(projectPath) : null,
24530
+ project: projectPath ? path40.basename(projectPath) : null,
24245
24531
  outputs: incoming.map((frame, index) => ({
24246
24532
  role: frame.role,
24247
24533
  basedOn: basedOnHash(entry, index),
@@ -24271,10 +24557,10 @@ function basedOnHash(entry, index) {
24271
24557
  async function replaceFile(file, bytes) {
24272
24558
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
24273
24559
  try {
24274
- await writeFile17(tmp, bytes);
24275
- await rename9(tmp, file);
24560
+ await writeFile18(tmp, bytes);
24561
+ await rename10(tmp, file);
24276
24562
  } finally {
24277
- await rm8(tmp, { force: true });
24563
+ await rm9(tmp, { force: true });
24278
24564
  }
24279
24565
  }
24280
24566
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -24284,10 +24570,10 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
24284
24570
 
24285
24571
  // src/pipeline/model-edit.ts
24286
24572
  import { spawn as spawn2 } from "child_process";
24287
- import { existsSync as existsSync35, readdirSync as readdirSync2 } from "fs";
24288
- import { mkdir as mkdir15, readdir as readdir5, readFile as readFile27, rename as rename10, rm as rm9, writeFile as writeFile18 } from "fs/promises";
24289
- import path40 from "path";
24290
- import { z as z10 } from "zod";
24573
+ import { existsSync as existsSync36, readdirSync as readdirSync2 } from "fs";
24574
+ import { mkdir as mkdir16, readdir as readdir5, readFile as readFile28, rename as rename11, rm as rm10, writeFile as writeFile19 } from "fs/promises";
24575
+ import path41 from "path";
24576
+ import { z as z11 } from "zod";
24291
24577
 
24292
24578
  // src/jpeg.ts
24293
24579
  var ZIGZAG = [
@@ -24631,8 +24917,8 @@ function decodeScan(bytes, start, scan, frameComponents, hMax, vMax, width, heig
24631
24917
  }
24632
24918
  k += r;
24633
24919
  if (k > 63) break;
24634
- const z18 = ZIGZAG[k];
24635
- coefficients[z18] = extend(receive(s), s) * q[z18];
24920
+ const z19 = ZIGZAG[k];
24921
+ coefficients[z19] = extend(receive(s), s) * q[z19];
24636
24922
  k++;
24637
24923
  }
24638
24924
  if (blockRow >= c.blocksHigh || blockColumn >= c.blocksWide) return;
@@ -24668,7 +24954,7 @@ var MAX_MODELS = 200;
24668
24954
  var MAX_DEPTH = 8;
24669
24955
  var SKIPPED_DIRS = /* @__PURE__ */ new Set([HAND_EDIT_DIR, "node_modules"]);
24670
24956
  async function discoverModels(loaded, opts = {}) {
24671
- const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: path40.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
24957
+ const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: path41.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
24672
24958
  const seen = /* @__PURE__ */ new Set();
24673
24959
  const models = [];
24674
24960
  const walk2 = async (styleId, outDir, dir, depth) => {
@@ -24682,13 +24968,13 @@ async function discoverModels(loaded, opts = {}) {
24682
24968
  entries.sort((a, b) => a.name.localeCompare(b.name));
24683
24969
  for (const entry of entries) {
24684
24970
  if (models.length >= MAX_MODELS) return;
24685
- const full = path40.join(dir, entry.name);
24971
+ const full = path41.join(dir, entry.name);
24686
24972
  if (entry.isDirectory()) {
24687
24973
  if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
24688
24974
  await walk2(styleId, outDir, full, depth + 1);
24689
24975
  } else if (entry.isFile() && entry.name.toLowerCase().endsWith(MODEL_EXTENSION) && !seen.has(full)) {
24690
24976
  seen.add(full);
24691
- models.push({ styleId, file: full, editFile: path40.join(outDir, HAND_EDIT_DIR, path40.relative(outDir, full)) });
24977
+ models.push({ styleId, file: full, editFile: path41.join(outDir, HAND_EDIT_DIR, path41.relative(outDir, full)) });
24692
24978
  }
24693
24979
  }
24694
24980
  };
@@ -24696,12 +24982,12 @@ async function discoverModels(loaded, opts = {}) {
24696
24982
  return models.sort((a, b) => a.styleId.localeCompare(b.styleId) || a.file.localeCompare(b.file));
24697
24983
  }
24698
24984
  async function findModel(loaded, portablePath) {
24699
- const wanted = path40.resolve(loaded.root, portablePath);
24985
+ const wanted = path41.resolve(loaded.root, portablePath);
24700
24986
  const model = (await discoverModels(loaded)).find((candidate) => candidate.file === wanted);
24701
24987
  if (!model) throw new ManifestEditError(`"${portablePath}" is not a model under one of this project's output folders`);
24702
24988
  return model;
24703
24989
  }
24704
- var stem = (editFile) => editFile.slice(0, -path40.extname(editFile).length);
24990
+ var stem = (editFile) => editFile.slice(0, -path41.extname(editFile).length);
24705
24991
  function modelCompanionPath(editFile) {
24706
24992
  return stem(editFile) + ".edit.json";
24707
24993
  }
@@ -24711,28 +24997,28 @@ function modelTextureProjectPath(editFile, image) {
24711
24997
  function modelExportPath(editFile) {
24712
24998
  return stem(editFile) + ".export" + MODEL_EXTENSION;
24713
24999
  }
24714
- var Sha = z10.string().regex(/^[0-9a-f]{64}$/);
24715
- var ModelEditCompanionSchema = z10.object({
24716
- version: z10.literal(2),
25000
+ var Sha = z11.string().regex(/^[0-9a-f]{64}$/);
25001
+ var ModelEditCompanionSchema = z11.object({
25002
+ version: z11.literal(2),
24717
25003
  /** What made the latest change: the bridge's editor identity, or `blender`. */
24718
- editor: z10.string().min(1),
24719
- protocol: z10.number().int().nonnegative(),
24720
- savedAt: z10.string().datetime(),
25004
+ editor: z11.string().min(1),
25005
+ protocol: z11.number().int().nonnegative(),
25006
+ savedAt: z11.string().datetime(),
24721
25007
  /** Basename of the layer file of the texture saved last, when one was kept. */
24722
- project: z10.string().min(1).nullable(),
25008
+ project: z11.string().min(1).nullable(),
24723
25009
  /** One entry: the model. `basedOn` is the hash of the model as built when the edit was made. */
24724
- outputs: z10.array(z10.object({ role: z10.string().nullable(), basedOn: Sha.nullable(), sha256: Sha }).strict()).length(1),
25010
+ outputs: z11.array(z11.object({ role: z11.string().nullable(), basedOn: Sha.nullable(), sha256: Sha }).strict()).length(1),
24725
25011
  /** Every texture this edit replaced, by image index. */
24726
- textures: z10.array(
24727
- z10.object({
24728
- image: z10.number().int().nonnegative(),
25012
+ textures: z11.array(
25013
+ z11.object({
25014
+ image: z11.number().int().nonnegative(),
24729
25015
  /** The material the texture belongs to, for reading the file without the model. */
24730
- name: z10.string(),
25016
+ name: z11.string(),
24731
25017
  sha256: Sha,
24732
- editor: z10.string().min(1),
24733
- savedAt: z10.string().datetime(),
25018
+ editor: z11.string().min(1),
25019
+ savedAt: z11.string().datetime(),
24734
25020
  /** Basename of its layer file, when one was kept. */
24735
- project: z10.string().min(1).nullable()
25021
+ project: z11.string().min(1).nullable()
24736
25022
  }).strict()
24737
25023
  ),
24738
25024
  /** Hash of the exported file the edit was last adopted from, so the same export is not offered twice. */
@@ -24740,7 +25026,7 @@ var ModelEditCompanionSchema = z10.object({
24740
25026
  }).strict();
24741
25027
  async function readModelCompanion(editFile) {
24742
25028
  try {
24743
- return ModelEditCompanionSchema.parse(JSON.parse(await readFile27(modelCompanionPath(editFile), "utf8")));
25029
+ return ModelEditCompanionSchema.parse(JSON.parse(await readFile28(modelCompanionPath(editFile), "utf8")));
24744
25030
  } catch {
24745
25031
  return null;
24746
25032
  }
@@ -24750,19 +25036,19 @@ function modelEditStatus(companion, builtSha256) {
24750
25036
  return companion.outputs[0].basedOn === builtSha256 ? "edited" : "rebuilt-since";
24751
25037
  }
24752
25038
  async function replaceFile2(file, bytes) {
24753
- await mkdir15(path40.dirname(file), { recursive: true });
25039
+ await mkdir16(path41.dirname(file), { recursive: true });
24754
25040
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
24755
25041
  try {
24756
- await writeFile18(tmp, bytes);
24757
- await rename10(tmp, file);
25042
+ await writeFile19(tmp, bytes);
25043
+ await rename11(tmp, file);
24758
25044
  } finally {
24759
- await rm9(tmp, { force: true });
25045
+ await rm10(tmp, { force: true });
24760
25046
  }
24761
25047
  }
24762
25048
  async function readModel(file, what) {
24763
25049
  let bytes;
24764
25050
  try {
24765
- bytes = await readFile27(file);
25051
+ bytes = await readFile28(file);
24766
25052
  } catch {
24767
25053
  throw new ManifestEditError(`${what} is not on disk at ${file}`);
24768
25054
  }
@@ -24789,7 +25075,7 @@ async function saveModelTexture(model, input) {
24789
25075
  throw new ManifestEditError(`the texture is not a valid PNG: ${error instanceof Error ? error.message : String(error)}`);
24790
25076
  }
24791
25077
  const original = await readModel(model.file, "the model");
24792
- const created = !existsSync35(model.editFile);
25078
+ const created = !existsSync36(model.editFile);
24793
25079
  const base = created ? original : await readModel(model.editFile, "the model's edit");
24794
25080
  let current;
24795
25081
  try {
@@ -24811,7 +25097,7 @@ async function saveModelTexture(model, input) {
24811
25097
  sha256: sha256(input.png),
24812
25098
  editor: input.editor,
24813
25099
  savedAt,
24814
- project: projectPath ? path40.basename(projectPath) : null
25100
+ project: projectPath ? path41.basename(projectPath) : null
24815
25101
  };
24816
25102
  const companion = {
24817
25103
  version: 2,
@@ -24834,7 +25120,7 @@ async function adoptModelExport(model, opts = {}) {
24834
25120
  const mode2 = opts.mode ?? "textures";
24835
25121
  const exported = await readModel(from, "the exported model");
24836
25122
  const original = await readModel(model.file, "the model");
24837
- const created = !existsSync35(model.editFile);
25123
+ const created = !existsSync36(model.editFile);
24838
25124
  const savedAt = (opts.now ?? /* @__PURE__ */ new Date()).toISOString();
24839
25125
  const editor = opts.editor ?? "blender";
24840
25126
  const taken = [];
@@ -24903,7 +25189,7 @@ async function adoptModelExport(model, opts = {}) {
24903
25189
  await replaceFile2(companionPath, JSON.stringify(companion, null, 2) + "\n");
24904
25190
  return { editFile: model.editFile, companionPath, companion, created, mode: mode2, taken };
24905
25191
  }
24906
- function blenderCommand(env = process.env, platform = process.platform, exists = existsSync35, list = (dir) => {
25192
+ function blenderCommand(env = process.env, platform = process.platform, exists = existsSync36, list = (dir) => {
24907
25193
  try {
24908
25194
  return readdirSync2(dir);
24909
25195
  } catch {
@@ -24915,16 +25201,16 @@ function blenderCommand(env = process.env, platform = process.platform, exists =
24915
25201
  const candidates = [];
24916
25202
  if (platform === "darwin") {
24917
25203
  candidates.push("/Applications/Blender.app/Contents/MacOS/Blender");
24918
- if (env.HOME) candidates.push(path40.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
25204
+ if (env.HOME) candidates.push(path41.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
24919
25205
  } else if (platform === "win32") {
24920
25206
  for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((value) => Boolean(value))) {
24921
- const foundation = path40.win32.join(root, "Blender Foundation");
25207
+ const foundation = path41.win32.join(root, "Blender Foundation");
24922
25208
  const versions = list(foundation).filter((name) => /^Blender/i.test(name)).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
24923
- for (const version of versions) candidates.push(path40.win32.join(foundation, version, "blender.exe"));
25209
+ for (const version of versions) candidates.push(path41.win32.join(foundation, version, "blender.exe"));
24924
25210
  }
24925
25211
  } else {
24926
25212
  candidates.push("/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender", "/var/lib/flatpak/exports/bin/org.blender.Blender");
24927
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(path40.join(dir, "blender"));
25213
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(path41.join(dir, "blender"));
24928
25214
  }
24929
25215
  const found = candidates.find((candidate) => exists(candidate));
24930
25216
  return found ? [found] : null;
@@ -24957,7 +25243,7 @@ function openInBlender(model, opts = {}) {
24957
25243
  "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"
24958
25244
  );
24959
25245
  }
24960
- const file = existsSync35(model.editFile) ? model.editFile : model.file;
25246
+ const file = existsSync36(model.editFile) ? model.editFile : model.file;
24961
25247
  const [program, ...rest] = command;
24962
25248
  const args = [...rest, ...blenderArguments(file, modelExportPath(model.editFile))];
24963
25249
  const launch = opts.launch ?? ((bin, argv) => {
@@ -24967,14 +25253,14 @@ function openInBlender(model, opts = {}) {
24967
25253
  child.unref();
24968
25254
  });
24969
25255
  launch(program, args);
24970
- return `${command.join(" ")} (${path40.basename(file)})`;
25256
+ return `${command.join(" ")} (${path41.basename(file)})`;
24971
25257
  }
24972
25258
 
24973
25259
  // src/pipeline/model-normals.ts
24974
25260
  import { createHash as createHash7 } from "crypto";
24975
- import { existsSync as existsSync36 } from "fs";
24976
- import { mkdir as mkdir16, readdir as readdir6, readFile as readFile28, writeFile as writeFile19 } from "fs/promises";
24977
- import path41 from "path";
25261
+ import { existsSync as existsSync37 } from "fs";
25262
+ import { mkdir as mkdir17, readdir as readdir6, readFile as readFile29, writeFile as writeFile20 } from "fs/promises";
25263
+ import path42 from "path";
24978
25264
  var MODEL_NORMAL_SOURCES = ["texture", "views", "sprites"];
24979
25265
  var TILE_MAX = 512;
24980
25266
  function decodeImage(bytes) {
@@ -25018,18 +25304,18 @@ function localMatrix(node) {
25018
25304
  const [tx, ty, tz] = node.translation ?? [0, 0, 0];
25019
25305
  const [qx, qy, qz, qw] = node.rotation ?? [0, 0, 0, 1];
25020
25306
  const [sx, sy, sz] = node.scale ?? [1, 1, 1];
25021
- const x = qx, y = qy, z18 = qz, w = qw;
25307
+ const x = qx, y = qy, z19 = qz, w = qw;
25022
25308
  return Float64Array.from([
25023
- (1 - 2 * (y * y + z18 * z18)) * sx,
25024
- 2 * (x * y + z18 * w) * sx,
25025
- 2 * (x * z18 - y * w) * sx,
25309
+ (1 - 2 * (y * y + z19 * z19)) * sx,
25310
+ 2 * (x * y + z19 * w) * sx,
25311
+ 2 * (x * z19 - y * w) * sx,
25026
25312
  0,
25027
- 2 * (x * y - z18 * w) * sy,
25028
- (1 - 2 * (x * x + z18 * z18)) * sy,
25029
- 2 * (y * z18 + x * w) * sy,
25313
+ 2 * (x * y - z19 * w) * sy,
25314
+ (1 - 2 * (x * x + z19 * z19)) * sy,
25315
+ 2 * (y * z19 + x * w) * sy,
25030
25316
  0,
25031
- 2 * (x * z18 + y * w) * sz,
25032
- 2 * (y * z18 - x * w) * sz,
25317
+ 2 * (x * z19 + y * w) * sz,
25318
+ 2 * (y * z19 - x * w) * sz,
25033
25319
  (1 - 2 * (x * x + y * y)) * sz,
25034
25320
  0,
25035
25321
  tx,
@@ -25066,13 +25352,13 @@ function poseNodes(document, pose) {
25066
25352
  const posed = /* @__PURE__ */ new Map();
25067
25353
  for (const channel of animation.channels) {
25068
25354
  const node = channel.target.node;
25069
- const path53 = channel.target.path;
25070
- if (node === void 0 || !["translation", "rotation", "scale"].includes(path53)) continue;
25355
+ const path54 = channel.target.path;
25356
+ if (node === void 0 || !["translation", "rotation", "scale"].includes(path54)) continue;
25071
25357
  const sampler = animation.samplers[channel.sampler];
25072
25358
  if (!sampler) continue;
25073
25359
  const times = readAccessor(document, sampler.input).data;
25074
25360
  const values = readAccessor(document, sampler.output);
25075
- const width = path53 === "rotation" ? 4 : 3;
25361
+ const width = path54 === "rotation" ? 4 : 3;
25076
25362
  const cubic = sampler.interpolation === "CUBICSPLINE";
25077
25363
  const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
25078
25364
  const last = times.length - 1;
@@ -25084,16 +25370,16 @@ function poseNodes(document, pose) {
25084
25370
  const span = times[key3 + 1] - times[key3];
25085
25371
  const f = span > 0 ? (time - times[key3]) / span : 0;
25086
25372
  const next = valueAt(key3 + 1);
25087
- const sign = path53 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
25373
+ const sign = path54 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
25088
25374
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
25089
25375
  }
25090
- if (path53 === "rotation") {
25376
+ if (path54 === "rotation") {
25091
25377
  const length = Math.hypot(...value) || 1;
25092
25378
  value = value.map((v) => v / length);
25093
25379
  }
25094
25380
  const base = posed.get(node) ?? { ...document.json.nodes?.[node] ?? {} };
25095
25381
  if (base.matrix) delete base.matrix;
25096
- base[path53] = value;
25382
+ base[path54] = value;
25097
25383
  posed.set(node, base);
25098
25384
  }
25099
25385
  return posed;
@@ -25307,9 +25593,9 @@ function texelSurface(primitives, document, image, width, height) {
25307
25593
  return surface;
25308
25594
  }
25309
25595
  var decodeNormal = (pixels, at2) => {
25310
- const x = pixels[at2] / 127.5 - 1, y = pixels[at2 + 1] / 127.5 - 1, z18 = pixels[at2 + 2] / 127.5 - 1;
25311
- const length = Math.hypot(x, y, z18) || 1;
25312
- return [x / length, y / length, z18 / length];
25596
+ const x = pixels[at2] / 127.5 - 1, y = pixels[at2 + 1] / 127.5 - 1, z19 = pixels[at2 + 2] / 127.5 - 1;
25597
+ const length = Math.hypot(x, y, z19) || 1;
25598
+ return [x / length, y / length, z19 / length];
25313
25599
  };
25314
25600
  function textureTiles(base, surface) {
25315
25601
  const { width, height } = surface;
@@ -25375,12 +25661,12 @@ function basisOf(turn, tilt) {
25375
25661
  toward: [level[0] * Math.cos(e), Math.sin(e), level[2] * Math.cos(e)]
25376
25662
  };
25377
25663
  }
25378
- var dot = (v, x, y, z18) => v[0] * x + v[1] * y + v[2] * z18;
25379
- function project(camera, basis, x, y, z18) {
25664
+ var dot = (v, x, y, z19) => v[0] * x + v[1] * y + v[2] * z19;
25665
+ function project(camera, basis, x, y, z19) {
25380
25666
  return [
25381
- (dot(basis.right, x, y, z18) - camera.centreX) * camera.scale + camera.offsetX,
25382
- camera.offsetY - (dot(basis.up, x, y, z18) - camera.centreY) * camera.scale,
25383
- dot(basis.toward, x, y, z18)
25667
+ (dot(basis.right, x, y, z19) - camera.centreX) * camera.scale + camera.offsetX,
25668
+ camera.offsetY - (dot(basis.up, x, y, z19) - camera.centreY) * camera.scale,
25669
+ dot(basis.toward, x, y, z19)
25384
25670
  ];
25385
25671
  }
25386
25672
  function extent(primitives, basis) {
@@ -25430,10 +25716,10 @@ function drawView(document, primitives, camera, textures) {
25430
25716
  const l1 = ((c[1] - a[1]) * (px - c[0]) + (a[0] - c[0]) * (py - c[1])) / den;
25431
25717
  const l2 = 1 - l0 - l1;
25432
25718
  if (l0 < 0 || l1 < 0 || l2 < 0) continue;
25433
- const z18 = l0 * a[2] + l1 * b[2] + l2 * c[2];
25719
+ const z19 = l0 * a[2] + l1 * b[2] + l2 * c[2];
25434
25720
  const at3 = y * width + x;
25435
- if (z18 <= depth[at3]) continue;
25436
- depth[at3] = z18;
25721
+ if (z19 <= depth[at3]) continue;
25722
+ depth[at3] = z19;
25437
25723
  let rgb = flat;
25438
25724
  if (texture && uv) {
25439
25725
  const u = l0 * uv[corners[0] * 2] + l1 * uv[corners[1] * 2] + l2 * uv[corners[2] * 2];
@@ -25563,10 +25849,10 @@ function detailFromViews(surface, views, maps, opts = {}) {
25563
25849
  const basis = bases[index];
25564
25850
  const facing = dot(basis.toward, nx, ny, nz);
25565
25851
  if (facing < 0.15) return;
25566
- const [sx, sy, z19] = project(camera, basis, px, py, pz);
25852
+ const [sx, sy, z20] = project(camera, basis, px, py, pz);
25567
25853
  const ix = Math.floor(sx), iy = Math.floor(sy);
25568
25854
  if (ix < 0 || iy < 0 || ix >= camera.width || iy >= camera.height) return;
25569
- if (view.depth[iy * camera.width + ix] - z19 > 1.5 / camera.scale) return;
25855
+ if (view.depth[iy * camera.width + ix] - z20 > 1.5 / camera.scale) return;
25570
25856
  if (view.use && !view.use[iy * camera.width + ix]) return;
25571
25857
  const map = decoded[index];
25572
25858
  if (map.pixels[(iy * camera.width + ix) * 4 + 3] < 128) return;
@@ -25603,9 +25889,9 @@ function detailFromViews(surface, views, maps, opts = {}) {
25603
25889
  total += weight;
25604
25890
  });
25605
25891
  if (!(total > 0)) continue;
25606
- const x = sum[texel * 3] / total, y = sum[texel * 3 + 1] / total, z18 = Math.max(0.05, sum[texel * 3 + 2] / total);
25607
- const length = Math.hypot(x, y, z18);
25608
- field.normal.set([x / length, y / length, z18 / length], texel * 3);
25892
+ const x = sum[texel * 3] / total, y = sum[texel * 3 + 1] / total, z19 = Math.max(0.05, sum[texel * 3 + 2] / total);
25893
+ const length = Math.hypot(x, y, z19);
25894
+ field.normal.set([x / length, y / length, z19 / length], texel * 3);
25609
25895
  field.weight[texel] = 1;
25610
25896
  }
25611
25897
  return field;
@@ -25658,23 +25944,23 @@ function applyDetail(existing, field, opts = {}) {
25658
25944
  if (!field.weight[texel]) continue;
25659
25945
  let dx = field.normal[texel * 3] * amount, dy = field.normal[texel * 3 + 1] * amount;
25660
25946
  const dz = field.normal[texel * 3 + 2];
25661
- let x, y, z18;
25947
+ let x, y, z19;
25662
25948
  if (opts.replace) {
25663
25949
  x = dx;
25664
25950
  y = dy;
25665
- z18 = dz;
25951
+ z19 = dz;
25666
25952
  } else {
25667
25953
  const [bx, by, bz] = decodeNormal(base.pixels, texel * 4);
25668
25954
  x = bx + dx;
25669
25955
  y = by + dy;
25670
- z18 = bz * dz;
25956
+ z19 = bz * dz;
25671
25957
  }
25672
- const length = Math.hypot(x, y, z18) || 1;
25958
+ const length = Math.hypot(x, y, z19) || 1;
25673
25959
  dx = x / length;
25674
25960
  dy = y / length;
25675
25961
  pixels[texel * 4] = Math.round((dx * 0.5 + 0.5) * 255);
25676
25962
  pixels[texel * 4 + 1] = Math.round((dy * 0.5 + 0.5) * 255);
25677
- pixels[texel * 4 + 2] = Math.round((Math.max(0, z18 / length) * 0.5 + 0.5) * 255);
25963
+ pixels[texel * 4 + 2] = Math.round((Math.max(0, z19 / length) * 0.5 + 0.5) * 255);
25678
25964
  pixels[texel * 4 + 3] = 255;
25679
25965
  }
25680
25966
  return { width, height, pixels };
@@ -25703,9 +25989,9 @@ function modelSpritesDir(modelFile) {
25703
25989
  return modelFile.replace(/\.glb$/i, "") + ".sprites";
25704
25990
  }
25705
25991
  async function readSpriteFolder(dir) {
25706
- const folder = existsSync36(path41.join(dir, "rotations")) ? path41.join(dir, "rotations") : dir;
25992
+ const folder = existsSync37(path42.join(dir, "rotations")) ? path42.join(dir, "rotations") : dir;
25707
25993
  const names = (await readdir6(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
25708
- return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await readFile28(path41.join(folder, name)), file: path41.join(folder, name) })));
25994
+ return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await readFile29(path42.join(folder, name)), file: path42.join(folder, name) })));
25709
25995
  }
25710
25996
  function modelNormalDir(editFile) {
25711
25997
  return editFile.replace(/\.glb$/i, "") + ".normal-map";
@@ -25715,8 +26001,8 @@ function requestKey(png, options) {
25715
26001
  return createHash7("sha256").update(png).update(asked).digest("hex").slice(0, 16);
25716
26002
  }
25717
26003
  async function prepare(model, opts) {
25718
- const fromEdit = existsSync36(model.editFile);
25719
- const document = parseGlb(await readFile28(fromEdit ? model.editFile : model.file));
26004
+ const fromEdit = existsSync37(model.editFile);
26005
+ const document = parseGlb(await readFile29(fromEdit ? model.editFile : model.file));
25720
26006
  const summary = describeGlb(document);
25721
26007
  const normalImages = summary.images.filter((image) => image.roles.includes("normal"));
25722
26008
  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");
@@ -25725,14 +26011,14 @@ async function prepare(model, opts) {
25725
26011
  if (!normalImages.some((image) => image.index === index)) throw new Error(`image ${index} is not one of the model's normal maps`);
25726
26012
  }
25727
26013
  const primitives = restPrimitives(document, opts.pose);
25728
- const dir = path41.join(modelNormalDir(model.editFile), opts.source);
26014
+ const dir = path42.join(modelNormalDir(model.editFile), opts.source);
25729
26015
  const surfaces = /* @__PURE__ */ new Map();
25730
26016
  const tiles = /* @__PURE__ */ new Map();
25731
26017
  const calls = [];
25732
26018
  const images = [];
25733
26019
  const call = (label, png) => {
25734
- const cache = path41.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
25735
- calls.push({ label, png, cache, cached: existsSync36(cache) });
26020
+ const cache = path42.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
26021
+ calls.push({ label, png, cache, cached: existsSync37(cache) });
25736
26022
  };
25737
26023
  for (const index of wanted) {
25738
26024
  const summaryImage = summary.images[index];
@@ -25800,15 +26086,15 @@ async function prepare(model, opts) {
25800
26086
  }
25801
26087
  async function planModelNormals(model, opts) {
25802
26088
  const { plan } = await prepare(model, opts);
25803
- await mkdir16(plan.dir, { recursive: true });
25804
- for (const entry of plan.calls) await writeFile19(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
25805
- for (const fit of plan.fits ?? []) await writeFile19(path41.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
26089
+ await mkdir17(plan.dir, { recursive: true });
26090
+ for (const entry of plan.calls) await writeFile20(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
26091
+ for (const fit of plan.fits ?? []) await writeFile20(path42.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
25806
26092
  return plan;
25807
26093
  }
25808
26094
  async function generateModelNormals(model, opts, mapper, hooks = {}) {
25809
26095
  const prepared = await prepare(model, opts);
25810
26096
  const { plan, document } = prepared;
25811
- await mkdir16(plan.dir, { recursive: true });
26097
+ await mkdir17(plan.dir, { recursive: true });
25812
26098
  const request = {
25813
26099
  ...opts.mode ? { mode: opts.mode } : {},
25814
26100
  ...opts.kind ? { kind: opts.kind } : {},
@@ -25820,14 +26106,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
25820
26106
  let sent = 0;
25821
26107
  for (const entry of plan.calls) {
25822
26108
  hooks.onCall?.(entry.label, entry.cached);
25823
- await writeFile19(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
26109
+ await writeFile20(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
25824
26110
  if (entry.cached) {
25825
- answers.push(await readFile28(entry.cache));
26111
+ answers.push(await readFile29(entry.cache));
25826
26112
  continue;
25827
26113
  }
25828
26114
  const answer = await mapper(entry.png, request);
25829
26115
  sent++;
25830
- await writeFile19(entry.cache, answer);
26116
+ await writeFile20(entry.cache, answer);
25831
26117
  answers.push(answer);
25832
26118
  }
25833
26119
  let result = null;
@@ -25845,14 +26131,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
25845
26131
  field = detailFromViews(surface, prepared.views, answers);
25846
26132
  }
25847
26133
  bleed(field);
25848
- const detail = path41.join(plan.dir, `image-${image}.detail.png`);
25849
- await writeFile19(detail, encodeImage(fieldImage(field)));
26134
+ const detail = path42.join(plan.dir, `image-${image}.detail.png`);
26135
+ await writeFile20(detail, encodeImage(fieldImage(field)));
25850
26136
  details.push(detail);
25851
- const basePath = path41.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
26137
+ const basePath = path42.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
25852
26138
  const record = companion?.textures.find((entry) => entry.image === image);
25853
- const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && existsSync36(basePath);
25854
- const existing = ours ? decodeImage(await readFile28(basePath)) : decodeImage(glbImageBytes(document, image).bytes);
25855
- if (!ours) await writeFile19(basePath, encodeImage(existing));
26139
+ const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && existsSync37(basePath);
26140
+ const existing = ours ? decodeImage(await readFile29(basePath)) : decodeImage(glbImageBytes(document, image).bytes);
26141
+ if (!ours) await writeFile20(basePath, encodeImage(existing));
25856
26142
  const png = encodeImage(applyDetail(existing, field, opts));
25857
26143
  result = await saveModelTexture(model, {
25858
26144
  image,
@@ -25900,11 +26186,11 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25900
26186
  for (const model of await discoverModels(loaded, opts)) {
25901
26187
  let bytes;
25902
26188
  try {
25903
- bytes = await readFile29(model.file);
26189
+ bytes = await readFile30(model.file);
25904
26190
  } catch {
25905
26191
  continue;
25906
26192
  }
25907
- const outDir = path42.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
26193
+ const outDir = path43.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
25908
26194
  let summary = null;
25909
26195
  let error = null;
25910
26196
  if (bytes.length > MAX_MODEL_BYTES) error = `the file is ${bytes.length} bytes; models over ${MAX_MODEL_BYTES} are listed but not opened`;
@@ -25918,16 +26204,16 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25918
26204
  const file = await describeFile(media, mediaId, root, model.file, bytes);
25919
26205
  let edit = null;
25920
26206
  let adoptedExport = null;
25921
- if (existsSync37(model.editFile)) {
26207
+ if (existsSync38(model.editFile)) {
25922
26208
  try {
25923
- const editBytes = await readFile29(model.editFile);
26209
+ const editBytes = await readFile30(model.editFile);
25924
26210
  const described = await describeFile(media, mediaId, root, model.editFile, editBytes);
25925
26211
  const companion = await readModelCompanion(model.editFile);
25926
26212
  adoptedExport = companion?.adoptedExport ?? null;
25927
26213
  const textures = (companion?.textures ?? []).map((texture) => {
25928
26214
  const projectPath = texture.project ? modelTextureProjectPath(model.editFile, texture.image) : null;
25929
26215
  let projectUrl = null;
25930
- if (projectPath && existsSync37(projectPath)) {
26216
+ if (projectPath && existsSync38(projectPath)) {
25931
26217
  const id = mediaId(projectPath);
25932
26218
  media.set(id, { path: projectPath, contentType: "application/octet-stream" });
25933
26219
  projectUrl = `/media/${id}?v=${texture.sha256.slice(0, 24)}`;
@@ -25957,25 +26243,25 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25957
26243
  let exportWaiting = null;
25958
26244
  try {
25959
26245
  const info = await stat4(exportFile);
25960
- if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await readFile29(exportFile)) !== adoptedExport) {
26246
+ if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await readFile30(exportFile)) !== adoptedExport) {
25961
26247
  exportWaiting = { bytes: info.size, modifiedAt: info.mtime.toISOString() };
25962
26248
  }
25963
26249
  } catch {
25964
26250
  }
25965
26251
  const spritesDir = modelSpritesDir(model.file);
25966
26252
  let sprites = null;
25967
- if (existsSync37(spritesDir)) {
26253
+ if (existsSync38(spritesDir)) {
25968
26254
  try {
25969
26255
  sprites = { path: portableOutputPath(spritesDir, root), directions: (await readSpriteFolder(spritesDir)).map((sprite) => sprite.direction) };
25970
26256
  } catch {
25971
26257
  }
25972
26258
  }
25973
- const relative = path42.relative(outDir, model.file).split(path42.sep).join("/");
26259
+ const relative = path43.relative(outDir, model.file).split(path43.sep).join("/");
25974
26260
  models.push({
25975
26261
  id: `model:${model.styleId}/${relative}`,
25976
26262
  project: null,
25977
26263
  styleId: model.styleId,
25978
- name: path42.basename(model.file, path42.extname(model.file)),
26264
+ name: path43.basename(model.file, path43.extname(model.file)),
25979
26265
  file,
25980
26266
  summary,
25981
26267
  error,
@@ -25989,41 +26275,41 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25989
26275
  }
25990
26276
  return models;
25991
26277
  }
25992
- var Base64 = z11.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
25993
- var ModelRequestSchema = z11.discriminatedUnion("action", [
25994
- z11.object({
25995
- action: z11.literal("save-model-texture"),
25996
- project: z11.string().min(1).optional(),
26278
+ var Base64 = z12.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
26279
+ var ModelRequestSchema = z12.discriminatedUnion("action", [
26280
+ z12.object({
26281
+ action: z12.literal("save-model-texture"),
26282
+ project: z12.string().min(1).optional(),
25997
26283
  /** Manifest-relative path of the model as built. */
25998
- path: z11.string().min(1).max(1024),
25999
- image: z11.number().int().nonnegative(),
26284
+ path: z12.string().min(1).max(1024),
26285
+ image: z12.number().int().nonnegative(),
26000
26286
  png: Base64.min(1),
26001
26287
  pxo: Base64.optional(),
26002
- editor: z11.string().min(1).max(200),
26003
- protocol: z11.number().int().positive()
26288
+ editor: z12.string().min(1).max(200),
26289
+ protocol: z12.number().int().positive()
26004
26290
  }).strict(),
26005
- z11.object({
26006
- action: z11.literal("adopt-model-export"),
26007
- project: z11.string().min(1).optional(),
26008
- path: z11.string().min(1).max(1024),
26009
- mode: z11.enum(["textures", "whole"]).optional()
26291
+ z12.object({
26292
+ action: z12.literal("adopt-model-export"),
26293
+ project: z12.string().min(1).optional(),
26294
+ path: z12.string().min(1).max(1024),
26295
+ mode: z12.enum(["textures", "whole"]).optional()
26010
26296
  }).strict(),
26011
- z11.object({
26012
- action: z11.literal("generate-model-normals"),
26013
- project: z11.string().min(1).optional(),
26014
- path: z11.string().min(1).max(1024),
26015
- source: z11.enum(MODEL_NORMAL_SOURCES),
26297
+ z12.object({
26298
+ action: z12.literal("generate-model-normals"),
26299
+ project: z12.string().min(1).optional(),
26300
+ path: z12.string().min(1).max(1024),
26301
+ source: z12.enum(MODEL_NORMAL_SOURCES),
26016
26302
  /** Normal map images; all of the model's when left out. */
26017
- images: z11.array(z11.number().int().nonnegative()).max(64).optional(),
26018
- amount: z11.number().min(0).max(2).optional(),
26019
- replace: z11.boolean().optional(),
26303
+ images: z12.array(z12.number().int().nonnegative()).max(64).optional(),
26304
+ amount: z12.number().min(0).max(2).optional(),
26305
+ replace: z12.boolean().optional(),
26020
26306
  /** The price the person agreed to on the page; a run that would cost more is refused. */
26021
- maxCost: z11.number().nonnegative().max(100)
26307
+ maxCost: z12.number().nonnegative().max(100)
26022
26308
  }).strict(),
26023
- z11.object({
26024
- action: z11.literal("open-model"),
26025
- project: z11.string().min(1).optional(),
26026
- path: z11.string().min(1).max(1024)
26309
+ z12.object({
26310
+ action: z12.literal("open-model"),
26311
+ project: z12.string().min(1).optional(),
26312
+ path: z12.string().min(1).max(1024)
26027
26313
  }).strict()
26028
26314
  ]);
26029
26315
  var MODEL_ACTIONS = ["save-model-texture", "adopt-model-export", "generate-model-normals", "open-model"];
@@ -26070,23 +26356,23 @@ function blenderAvailable() {
26070
26356
  }
26071
26357
 
26072
26358
  // src/workspace.ts
26073
- import { mkdir as mkdir17, readFile as readFile30, rename as rename11, rm as rm10, writeFile as writeFile20 } from "fs/promises";
26074
- import { existsSync as existsSync38 } from "fs";
26075
- import path43 from "path";
26076
- import { z as z12 } from "zod";
26077
- var WorkspaceProjectSchema = z12.object({
26078
- id: z12.string().min(1),
26359
+ import { mkdir as mkdir18, readFile as readFile31, rename as rename12, rm as rm11, writeFile as writeFile21 } from "fs/promises";
26360
+ import { existsSync as existsSync39 } from "fs";
26361
+ import path44 from "path";
26362
+ import { z as z13 } from "zod";
26363
+ var WorkspaceProjectSchema = z13.object({
26364
+ id: z13.string().min(1),
26079
26365
  /** Manifest path, relative to the catalog file's own directory. */
26080
- manifest: z12.string().min(1),
26366
+ manifest: z13.string().min(1),
26081
26367
  /** Lockfile path, relative to the catalog file's own directory. */
26082
- lock: z12.string().min(1),
26083
- provider: z12.string().min(1).default("pixellab"),
26368
+ lock: z13.string().min(1),
26369
+ provider: z13.string().min(1).default("pixellab"),
26084
26370
  /** Free-form label for a shared account, e.g. distinguishing sandboxes. */
26085
- account: z12.string().optional()
26371
+ account: z13.string().optional()
26086
26372
  }).strict();
26087
- var WorkspaceSchema = z12.object({
26088
- version: z12.literal(1),
26089
- projects: z12.array(WorkspaceProjectSchema).default([])
26373
+ var WorkspaceSchema = z13.object({
26374
+ version: z13.literal(1),
26375
+ projects: z13.array(WorkspaceProjectSchema).default([])
26090
26376
  }).strict();
26091
26377
  function parseWorkspace(raw) {
26092
26378
  const parsed = WorkspaceSchema.safeParse(raw);
@@ -26097,10 +26383,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
26097
26383
  );
26098
26384
  }
26099
26385
  async function loadWorkspace(workspacePath) {
26100
- if (!existsSync38(workspacePath)) return { version: 1, projects: [] };
26386
+ if (!existsSync39(workspacePath)) return { version: 1, projects: [] };
26101
26387
  let raw;
26102
26388
  try {
26103
- raw = JSON.parse(await readFile30(workspacePath, "utf8"));
26389
+ raw = JSON.parse(await readFile31(workspacePath, "utf8"));
26104
26390
  } catch (err) {
26105
26391
  throw new ProjectError(
26106
26392
  `Workspace catalog at ${workspacePath} is malformed:
@@ -26114,22 +26400,22 @@ async function saveWorkspace(workspacePath, ws) {
26114
26400
  version: 1,
26115
26401
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
26116
26402
  };
26117
- await mkdir17(path43.dirname(path43.resolve(workspacePath)), { recursive: true });
26403
+ await mkdir18(path44.dirname(path44.resolve(workspacePath)), { recursive: true });
26118
26404
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
26119
26405
  try {
26120
- await writeFile20(tmp, JSON.stringify(sorted, null, 2) + "\n");
26121
- await rename11(tmp, workspacePath);
26406
+ await writeFile21(tmp, JSON.stringify(sorted, null, 2) + "\n");
26407
+ await rename12(tmp, workspacePath);
26122
26408
  } finally {
26123
- await rm10(tmp, { force: true });
26409
+ await rm11(tmp, { force: true });
26124
26410
  }
26125
26411
  }
26126
26412
  function toPortablePath(dir, absolute) {
26127
- return path43.relative(dir, absolute).split(path43.sep).join("/");
26413
+ return path44.relative(dir, absolute).split(path44.sep).join("/");
26128
26414
  }
26129
26415
  function resolveProject(dir, project2) {
26130
26416
  return {
26131
- manifestPath: path43.resolve(dir, project2.manifest.split("/").join(path43.sep)),
26132
- lockPath: path43.resolve(dir, project2.lock.split("/").join(path43.sep))
26417
+ manifestPath: path44.resolve(dir, project2.manifest.split("/").join(path44.sep)),
26418
+ lockPath: path44.resolve(dir, project2.lock.split("/").join(path44.sep))
26133
26419
  };
26134
26420
  }
26135
26421
  function validateWorkspace(ws, dir) {
@@ -26142,21 +26428,21 @@ function validateWorkspace(ws, dir) {
26142
26428
  const { manifestPath, lockPath } = resolveProject(dir, project2);
26143
26429
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project2.id]);
26144
26430
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project2.id]);
26145
- if (path43.isAbsolute(project2.manifest) || path43.isAbsolute(project2.lock)) {
26431
+ if (path44.isAbsolute(project2.manifest) || path44.isAbsolute(project2.lock)) {
26146
26432
  diagnostics.push({
26147
26433
  id: "absolute-path",
26148
26434
  level: "warning",
26149
26435
  message: `project "${project2.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
26150
26436
  });
26151
26437
  }
26152
- if (!existsSync38(manifestPath)) {
26438
+ if (!existsSync39(manifestPath)) {
26153
26439
  diagnostics.push({
26154
26440
  id: "missing-manifest",
26155
26441
  level: "error",
26156
26442
  message: `project "${project2.id}" manifest not found: ${manifestPath}`
26157
26443
  });
26158
26444
  }
26159
- if (!existsSync38(lockPath)) {
26445
+ if (!existsSync39(lockPath)) {
26160
26446
  diagnostics.push({
26161
26447
  id: "missing-lock",
26162
26448
  level: "error",
@@ -26203,32 +26489,32 @@ function validateWorkspace(ws, dir) {
26203
26489
  }
26204
26490
 
26205
26491
  // src/gallery/edit.ts
26206
- import { readFile as readFile33, rename as rename12, writeFile as writeFile24 } from "fs/promises";
26207
- import path47 from "path";
26208
- import { z as z16 } from "zod";
26492
+ import { readFile as readFile34, rename as rename13, writeFile as writeFile25 } from "fs/promises";
26493
+ import path48 from "path";
26494
+ import { z as z17 } from "zod";
26209
26495
 
26210
26496
  // src/gallery/upload.ts
26211
- import { existsSync as existsSync39 } from "fs";
26212
- import { mkdir as mkdir18, writeFile as writeFile21 } from "fs/promises";
26213
- import path44 from "path";
26214
- import { z as z13 } from "zod";
26497
+ import { existsSync as existsSync40 } from "fs";
26498
+ import { mkdir as mkdir19, writeFile as writeFile22 } from "fs/promises";
26499
+ import path45 from "path";
26500
+ import { z as z14 } from "zod";
26215
26501
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
26216
- var UploadImageSchema = z13.object({
26217
- action: z13.literal("upload-image"),
26218
- project: z13.string().min(1).optional(),
26502
+ var UploadImageSchema = z14.object({
26503
+ action: z14.literal("upload-image"),
26504
+ project: z14.string().min(1).optional(),
26219
26505
  /** Manifest-relative destination, ending .png, .jpg, or .jpeg. */
26220
- path: z13.string().min(1),
26221
- base64: z13.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_UPLOAD_BYTES / 3) * 4),
26506
+ path: z14.string().min(1),
26507
+ base64: z14.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_UPLOAD_BYTES / 3) * 4),
26222
26508
  /** Replace a file already at `path`. */
26223
- overwrite: z13.boolean().optional()
26509
+ overwrite: z14.boolean().optional()
26224
26510
  }).strict();
26225
26511
  async function saveProjectImage(root, request) {
26226
- const file = path44.resolve(root, request.path);
26227
- const relative = path44.relative(root, file);
26228
- if (relative.startsWith("..") || path44.isAbsolute(relative)) {
26512
+ const file = path45.resolve(root, request.path);
26513
+ const relative = path45.relative(root, file);
26514
+ if (relative.startsWith("..") || path45.isAbsolute(relative)) {
26229
26515
  throw new ManifestEditError("an upload must stay inside the project");
26230
26516
  }
26231
- const extension = path44.extname(file).toLowerCase();
26517
+ const extension = path45.extname(file).toLowerCase();
26232
26518
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
26233
26519
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
26234
26520
  const bytes = Buffer.from(request.base64, "base64");
@@ -26240,45 +26526,45 @@ async function saveProjectImage(root, request) {
26240
26526
  if (metadata.format !== expected) {
26241
26527
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
26242
26528
  }
26243
- if (existsSync39(file) && !request.overwrite) {
26244
- throw new ManifestEditError(`${relative.split(path44.sep).join("/")} already exists; choose another name, or replace it`);
26529
+ if (existsSync40(file) && !request.overwrite) {
26530
+ throw new ManifestEditError(`${relative.split(path45.sep).join("/")} already exists; choose another name, or replace it`);
26245
26531
  }
26246
- await mkdir18(path44.dirname(file), { recursive: true });
26247
- await writeFile21(file, bytes);
26248
- return relative.split(path44.sep).join("/");
26532
+ await mkdir19(path45.dirname(file), { recursive: true });
26533
+ await writeFile22(file, bytes);
26534
+ return relative.split(path45.sep).join("/");
26249
26535
  }
26250
26536
 
26251
26537
  // src/gallery/image-revision.ts
26252
- import { existsSync as existsSync40 } from "fs";
26253
- import { readFile as readFile31, rm as rm11, writeFile as writeFile22 } from "fs/promises";
26254
- import path45 from "path";
26255
- import { z as z14 } from "zod";
26256
- var InpaintRevisionRequestSchema = z14.object({
26257
- action: z14.literal("create-inpaint-revision"),
26258
- project: z14.string().min(1).optional(),
26259
- expectedSha256: z14.string().regex(/^[0-9a-f]{64}$/),
26260
- styleId: z14.string().min(1),
26538
+ import { existsSync as existsSync41 } from "fs";
26539
+ import { readFile as readFile32, rm as rm12, writeFile as writeFile23 } from "fs/promises";
26540
+ import path46 from "path";
26541
+ import { z as z15 } from "zod";
26542
+ var InpaintRevisionRequestSchema = z15.object({
26543
+ action: z15.literal("create-inpaint-revision"),
26544
+ project: z15.string().min(1).optional(),
26545
+ expectedSha256: z15.string().regex(/^[0-9a-f]{64}$/),
26546
+ styleId: z15.string().min(1),
26261
26547
  /** The sprite being repainted. */
26262
- from: z14.string().min(1),
26263
- assetId: z14.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
26548
+ from: z15.string().min(1),
26549
+ assetId: z15.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
26264
26550
  /** What to paint into the masked area. */
26265
- prompt: z14.string().min(1),
26551
+ prompt: z15.string().min(1),
26266
26552
  /** Manifest-relative `.png` destination for the mask. */
26267
- maskPath: z14.string().min(1),
26268
- maskBase64: z14.string().regex(/^[A-Za-z0-9+/]*={0,2}$/),
26553
+ maskPath: z15.string().min(1),
26554
+ maskBase64: z15.string().regex(/^[A-Za-z0-9+/]*={0,2}$/),
26269
26555
  /** Replace a file already at `maskPath`. */
26270
- overwrite: z14.boolean().optional()
26556
+ overwrite: z15.boolean().optional()
26271
26557
  }).strict();
26272
26558
  async function createInpaintRevision(manifestPath, request) {
26273
- const root = path45.dirname(path45.resolve(manifestPath));
26274
- if (path45.extname(request.maskPath).toLowerCase() !== ".png") {
26559
+ const root = path46.dirname(path46.resolve(manifestPath));
26560
+ if (path46.extname(request.maskPath).toLowerCase() !== ".png") {
26275
26561
  throw new ManifestEditError("the mask must be a .png path inside the project");
26276
26562
  }
26277
26563
  const bytes = Buffer.from(request.maskBase64, "base64");
26278
26564
  const metadata = imageMetadata(bytes);
26279
26565
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
26280
- const file = path45.resolve(root, request.maskPath);
26281
- const previous = existsSync40(file) ? await readFile31(file) : null;
26566
+ const file = path46.resolve(root, request.maskPath);
26567
+ const previous = existsSync41(file) ? await readFile32(file) : null;
26282
26568
  const mask = await saveProjectImage(root, {
26283
26569
  action: "upload-image",
26284
26570
  path: request.maskPath,
@@ -26297,70 +26583,70 @@ async function createInpaintRevision(manifestPath, request) {
26297
26583
  }
26298
26584
  });
26299
26585
  } catch (error) {
26300
- if (previous) await writeFile22(file, previous);
26301
- else await rm11(file, { force: true });
26586
+ if (previous) await writeFile23(file, previous);
26587
+ else await rm12(file, { force: true });
26302
26588
  throw error;
26303
26589
  }
26304
26590
  return mask;
26305
26591
  }
26306
26592
 
26307
26593
  // src/gallery/skeleton.ts
26308
- import { existsSync as existsSync41 } from "fs";
26309
- import { mkdir as mkdir19, readFile as readFile32, rm as rm12, writeFile as writeFile23 } from "fs/promises";
26310
- import path46 from "path";
26311
- import { z as z15 } from "zod";
26312
- var SkeletonEstimateRequestSchema = z15.object({
26313
- project: z15.string().min(1).optional(),
26314
- styleId: z15.string().min(1),
26315
- assetId: z15.string().min(1),
26316
- frames: z15.number().int().min(3).max(15).optional()
26594
+ import { existsSync as existsSync42 } from "fs";
26595
+ import { mkdir as mkdir20, readFile as readFile33, rm as rm13, writeFile as writeFile24 } from "fs/promises";
26596
+ import path47 from "path";
26597
+ import { z as z16 } from "zod";
26598
+ var SkeletonEstimateRequestSchema = z16.object({
26599
+ project: z16.string().min(1).optional(),
26600
+ styleId: z16.string().min(1),
26601
+ assetId: z16.string().min(1),
26602
+ frames: z16.number().int().min(3).max(15).optional()
26317
26603
  }).strict();
26318
- var SkeletonAnimationRequestSchema = z15.object({
26319
- action: z15.literal("create-skeleton-animation"),
26320
- project: z15.string().min(1).optional(),
26321
- expectedSha256: z15.string().regex(/^[0-9a-f]{64}$/),
26322
- styleId: z15.string().min(1),
26604
+ var SkeletonAnimationRequestSchema = z16.object({
26605
+ action: z16.literal("create-skeleton-animation"),
26606
+ project: z16.string().min(1).optional(),
26607
+ expectedSha256: z16.string().regex(/^[0-9a-f]{64}$/),
26608
+ styleId: z16.string().min(1),
26323
26609
  /** The sprite the animation poses. */
26324
- from: z15.string().min(1),
26325
- assetId: z15.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
26610
+ from: z16.string().min(1),
26611
+ assetId: z16.string().min(1).regex(/^[^/\\]+$/, "asset ids cannot contain slashes"),
26326
26612
  /** The motion, sent as PixelLab's `action`. */
26327
- prompt: z15.string().min(1),
26613
+ prompt: z16.string().min(1),
26328
26614
  direction: CharacterDirectionSchema,
26329
26615
  /** What the character looks like; PixelLab refuses the request without it. */
26330
- description: z15.string().min(1),
26331
- skeletonTemplate: z15.string().min(1).optional(),
26616
+ description: z16.string().min(1),
26617
+ skeletonTemplate: z16.string().min(1).optional(),
26332
26618
  /** Manifest-relative JSON path inside the project. */
26333
- keypointsFile: z15.string().min(1),
26619
+ keypointsFile: z16.string().min(1),
26334
26620
  /** Poses to write to `keypointsFile`; omitted to use a file that already exists. */
26335
26621
  set: SkeletonSetSchema.optional(),
26336
26622
  /** Replace an existing `keypointsFile` with `set`. */
26337
- overwrite: z15.boolean().optional()
26623
+ overwrite: z16.boolean().optional()
26338
26624
  }).strict();
26339
- var SkeletonKeypointsUpdateSchema = z15.object({
26340
- action: z15.literal("update-skeleton-keypoints"),
26341
- project: z15.string().min(1).optional(),
26342
- styleId: z15.string().min(1),
26343
- assetId: z15.string().min(1),
26625
+ var SkeletonKeypointsUpdateSchema = z16.object({
26626
+ action: z16.literal("update-skeleton-keypoints"),
26627
+ project: z16.string().min(1).optional(),
26628
+ styleId: z16.string().min(1),
26629
+ assetId: z16.string().min(1),
26344
26630
  /** The file's SHA-256 when the page loaded it; anything else on disk is a concurrent edit. */
26345
- expectedSha256: z15.string().regex(/^[0-9a-f]{64}$/),
26631
+ expectedSha256: z16.string().regex(/^[0-9a-f]{64}$/),
26346
26632
  set: SkeletonSetSchema
26347
26633
  }).strict();
26348
26634
  async function createSkeletonAnimation(manifestPath, request) {
26349
- const root = path46.dirname(path46.resolve(manifestPath));
26350
- const file = path46.resolve(root, request.keypointsFile);
26351
- const relative = path46.relative(root, file);
26352
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path46.isAbsolute(relative)) {
26635
+ const root = path47.dirname(path47.resolve(manifestPath));
26636
+ const file = path47.resolve(root, request.keypointsFile);
26637
+ const relative = path47.relative(root, file);
26638
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path47.isAbsolute(relative)) {
26353
26639
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
26354
26640
  }
26355
- const existed = existsSync41(file);
26641
+ const existed = existsSync42(file);
26356
26642
  let previous = null;
26357
26643
  if (request.set) {
26358
26644
  if (existed && !request.overwrite) {
26359
26645
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
26360
26646
  }
26361
- if (existed) previous = await readFile32(file);
26362
- await mkdir19(path46.dirname(file), { recursive: true });
26363
- await writeFile23(file, JSON.stringify(request.set, null, 2) + "\n");
26647
+ if (existed) previous = await readFile33(file);
26648
+ await mkdir20(path47.dirname(file), { recursive: true });
26649
+ await writeFile24(file, JSON.stringify(request.set, null, 2) + "\n");
26364
26650
  } else if (!existed) {
26365
26651
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
26366
26652
  }
@@ -26375,7 +26661,7 @@ async function createSkeletonAnimation(manifestPath, request) {
26375
26661
  revision: {
26376
26662
  mode: "animate-skeleton",
26377
26663
  from: request.from,
26378
- keypointsFile: relative.split(path46.sep).join("/"),
26664
+ keypointsFile: relative.split(path47.sep).join("/"),
26379
26665
  direction: request.direction,
26380
26666
  description: request.description,
26381
26667
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -26384,8 +26670,8 @@ async function createSkeletonAnimation(manifestPath, request) {
26384
26670
  });
26385
26671
  } catch (error) {
26386
26672
  if (request.set) {
26387
- if (previous) await writeFile23(file, previous);
26388
- else await rm12(file, { force: true });
26673
+ if (previous) await writeFile24(file, previous);
26674
+ else await rm13(file, { force: true });
26389
26675
  }
26390
26676
  throw error;
26391
26677
  }
@@ -26396,64 +26682,64 @@ async function updateSkeletonKeypoints(ctx, request) {
26396
26682
  if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
26397
26683
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
26398
26684
  if (!file) throw new ManifestEditError(`${key3} is not an animate-skeleton revision`);
26399
- const relative = path46.relative(ctx.loaded.root, file);
26400
- if (relative.startsWith("..") || path46.isAbsolute(relative)) {
26685
+ const relative = path47.relative(ctx.loaded.root, file);
26686
+ if (relative.startsWith("..") || path47.isAbsolute(relative)) {
26401
26687
  throw new ManifestEditError(`${key3}'s keypoints file is outside the project; edit it by hand`);
26402
26688
  }
26403
- const current = existsSync41(file) ? sha256(await readFile32(file)) : null;
26689
+ const current = existsSync42(file) ? sha256(await readFile33(file)) : null;
26404
26690
  if (current !== request.expectedSha256) {
26405
26691
  throw Object.assign(
26406
- new Error(`${relative.split(path46.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
26692
+ new Error(`${relative.split(path47.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
26407
26693
  { status: 409 }
26408
26694
  );
26409
26695
  }
26410
- await writeFile23(file, JSON.stringify(request.set, null, 2) + "\n");
26411
- return relative.split(path46.sep).join("/");
26696
+ await writeFile24(file, JSON.stringify(request.set, null, 2) + "\n");
26697
+ return relative.split(path47.sep).join("/");
26412
26698
  }
26413
26699
 
26414
26700
  // src/gallery/edit.ts
26415
- var Base642 = z16.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
26416
- var HandEditRequestSchema = z16.discriminatedUnion("action", [
26417
- z16.object({
26418
- action: z16.literal("start-edit"),
26419
- project: z16.string().min(1).optional(),
26420
- assetId: z16.string().min(1),
26421
- styleId: z16.string().min(1),
26422
- expectedSha256: z16.string().regex(/^[0-9a-f]{64}$/),
26701
+ var Base642 = z17.string().regex(/^[A-Za-z0-9+/]*={0,2}$/).max(Math.ceil(MAX_HAND_EDIT_BYTES / 3) * 4);
26702
+ var HandEditRequestSchema = z17.discriminatedUnion("action", [
26703
+ z17.object({
26704
+ action: z17.literal("start-edit"),
26705
+ project: z17.string().min(1).optional(),
26706
+ assetId: z17.string().min(1),
26707
+ styleId: z17.string().min(1),
26708
+ expectedSha256: z17.string().regex(/^[0-9a-f]{64}$/),
26423
26709
  /** Also launch the author's editor on the file. */
26424
- open: z16.boolean().optional()
26710
+ open: z17.boolean().optional()
26425
26711
  }).strict(),
26426
- z16.object({
26427
- action: z16.literal("detach-edit"),
26428
- project: z16.string().min(1).optional(),
26429
- assetId: z16.string().min(1),
26430
- styleId: z16.string().min(1),
26431
- expectedSha256: z16.string().regex(/^[0-9a-f]{64}$/)
26712
+ z17.object({
26713
+ action: z17.literal("detach-edit"),
26714
+ project: z17.string().min(1).optional(),
26715
+ assetId: z17.string().min(1),
26716
+ styleId: z17.string().min(1),
26717
+ expectedSha256: z17.string().regex(/^[0-9a-f]{64}$/)
26432
26718
  }).strict(),
26433
26719
  /** From the in-browser editor: the page holds the bytes, the server validates and writes. */
26434
- z16.object({
26435
- action: z16.literal("save-edit"),
26436
- project: z16.string().min(1).optional(),
26437
- assetId: z16.string().min(1),
26438
- styleId: z16.string().min(1),
26439
- expectedSha256: z16.string().regex(/^[0-9a-f]{64}$/),
26720
+ z17.object({
26721
+ action: z17.literal("save-edit"),
26722
+ project: z17.string().min(1).optional(),
26723
+ assetId: z17.string().min(1),
26724
+ styleId: z17.string().min(1),
26725
+ expectedSha256: z17.string().regex(/^[0-9a-f]{64}$/),
26440
26726
  /** The flattened image; for a frame set, `frames` instead. */
26441
26727
  png: Base642.min(1).optional(),
26442
26728
  /** Every frame of a set, tagged with the role it was opened under (null for one added in the editor). */
26443
- frames: z16.array(z16.object({ role: z16.string().min(1).nullable(), png: Base642.min(1) }).strict()).min(1).max(256).optional(),
26729
+ frames: z17.array(z17.object({ role: z17.string().min(1).nullable(), png: Base642.min(1) }).strict()).min(1).max(256).optional(),
26444
26730
  /** The editor's layered project file, kept beside the edit. */
26445
26731
  pxo: Base642.optional(),
26446
26732
  /** Editor identity from the bridge's ready message. */
26447
- editor: z16.string().min(1).max(200),
26448
- protocol: z16.number().int().positive()
26733
+ editor: z17.string().min(1).max(200),
26734
+ protocol: z17.number().int().positive()
26449
26735
  }).strict()
26450
26736
  ]);
26451
26737
  var UNDO_DEPTH = 20;
26452
- var UndoRequestSchema = z16.object({
26453
- action: z16.literal("undo-edit"),
26454
- project: z16.string().min(1).optional(),
26738
+ var UndoRequestSchema = z17.object({
26739
+ action: z17.literal("undo-edit"),
26740
+ project: z17.string().min(1).optional(),
26455
26741
  /** The manifest as the page last saw it; undo refuses a manifest someone else has changed since. */
26456
- expectedSha256: z16.string().regex(/^[0-9a-f]{64}$/)
26742
+ expectedSha256: z17.string().regex(/^[0-9a-f]{64}$/)
26457
26743
  }).strict();
26458
26744
  function createGalleryEditHandler(opts) {
26459
26745
  const log = opts.onProgress ?? (() => {
@@ -26462,7 +26748,7 @@ function createGalleryEditHandler(opts) {
26462
26748
  const history = /* @__PURE__ */ new Map();
26463
26749
  const manifestOf = async (project2) => {
26464
26750
  try {
26465
- return path47.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
26751
+ return path48.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
26466
26752
  } catch {
26467
26753
  return null;
26468
26754
  }
@@ -26472,7 +26758,7 @@ function createGalleryEditHandler(opts) {
26472
26758
  if (undo.success) {
26473
26759
  const manifestPath2 = await manifestOf(undo.data.project);
26474
26760
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
26475
- const current = await readFile33(manifestPath2, "utf8");
26761
+ const current = await readFile34(manifestPath2, "utf8");
26476
26762
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
26477
26763
  const stack = history.get(manifestPath2) ?? [];
26478
26764
  const last = stack[stack.length - 1];
@@ -26482,17 +26768,17 @@ function createGalleryEditHandler(opts) {
26482
26768
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
26483
26769
  }
26484
26770
  const tmp = manifestPath2 + ".pixelkiln-undo";
26485
- await writeFile24(tmp, last.before);
26486
- await rename12(tmp, manifestPath2);
26771
+ await writeFile25(tmp, last.before);
26772
+ await rename13(tmp, manifestPath2);
26487
26773
  stack.pop();
26488
- log(` manifest edit undone in ${path47.relative(process.cwd(), manifestPath2) || manifestPath2}`);
26774
+ log(` manifest edit undone in ${path48.relative(process.cwd(), manifestPath2) || manifestPath2}`);
26489
26775
  return opts.reload();
26490
26776
  }
26491
26777
  const manifestPath = await manifestOf(body?.project);
26492
- const before = manifestPath ? await readFile33(manifestPath, "utf8").catch(() => null) : null;
26778
+ const before = manifestPath ? await readFile34(manifestPath, "utf8").catch(() => null) : null;
26493
26779
  const build = await apply(body);
26494
26780
  if (manifestPath && before !== null) {
26495
- const after = await readFile33(manifestPath, "utf8").catch(() => null);
26781
+ const after = await readFile34(manifestPath, "utf8").catch(() => null);
26496
26782
  if (after !== null && after !== before) {
26497
26783
  const stack = history.get(manifestPath) ?? [];
26498
26784
  stack.push({ before, afterSha: sha256(after) });
@@ -26571,7 +26857,7 @@ function createEditApplier(opts, log) {
26571
26857
  } catch (error) {
26572
26858
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
26573
26859
  }
26574
- const written = await saveProjectImage(path47.dirname(path47.resolve(manifestPath2)), upload.data);
26860
+ const written = await saveProjectImage(path48.dirname(path48.resolve(manifestPath2)), upload.data);
26575
26861
  log(` image added: ${written}`);
26576
26862
  return opts.reload();
26577
26863
  }
@@ -26638,7 +26924,7 @@ function createEditApplier(opts, log) {
26638
26924
  }
26639
26925
  const result = await applyManifestEdit(manifestPath, parsed.data);
26640
26926
  if (result.changed) {
26641
- const relative = path47.relative(process.cwd(), result.manifestPath);
26927
+ const relative = path48.relative(process.cwd(), result.manifestPath);
26642
26928
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
26643
26929
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
26644
26930
  }
@@ -26666,7 +26952,7 @@ function describeEdit(edit) {
26666
26952
  // src/gallery/snapshot.ts
26667
26953
  var PROJECT_FILE_TYPE = "application/octet-stream";
26668
26954
  function galleryMediaId(absolutePath) {
26669
- return createHash8("sha256").update(path48.resolve(absolutePath)).digest("hex").slice(0, 24);
26955
+ return createHash8("sha256").update(path49.resolve(absolutePath)).digest("hex").slice(0, 24);
26670
26956
  }
26671
26957
  function galleryMediaRoute(id) {
26672
26958
  return `/media/${id}`;
@@ -26690,9 +26976,9 @@ function describeHistory(media, entry, cacheDir) {
26690
26976
  return (entry.history ?? []).map((generation, i) => {
26691
26977
  const outputs = generation.outputs.map((output) => {
26692
26978
  const mediaType = output.mediaType ?? MediaType.PNG;
26693
- const file = path48.join(cacheDir, cacheFileName(output.sha256, mediaType));
26979
+ const file = path49.join(cacheDir, cacheFileName(output.sha256, mediaType));
26694
26980
  let url = null;
26695
- if (existsSync42(file)) {
26981
+ if (existsSync43(file)) {
26696
26982
  const id = galleryMediaId(file);
26697
26983
  media.set(id, { path: file, contentType: mediaType });
26698
26984
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -26724,7 +27010,7 @@ function describeHistory(media, entry, cacheDir) {
26724
27010
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
26725
27011
  async function samePixels(a, b) {
26726
27012
  try {
26727
- const [left, right] = await Promise.all([readFile34(a), readFile34(b)]);
27013
+ const [left, right] = await Promise.all([readFile35(a), readFile35(b)]);
26728
27014
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
26729
27015
  const x = decodePng(left);
26730
27016
  const y = decodePng(right);
@@ -26822,10 +27108,10 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
26822
27108
  async function describeQuality(media, root, inspection) {
26823
27109
  const outputPaths = inspection.outputs ?? [inspection.output];
26824
27110
  const outputs = await Promise.all(
26825
- outputPaths.map((file) => describeOutput(media, root, path48.resolve(root, file)))
27111
+ outputPaths.map((file) => describeOutput(media, root, path49.resolve(root, file)))
26826
27112
  );
26827
- const recordPath = path48.resolve(root, inspection.record);
26828
- const recordExists = existsSync42(recordPath);
27113
+ const recordPath = path49.resolve(root, inspection.record);
27114
+ const recordExists = existsSync43(recordPath);
26829
27115
  let options = null;
26830
27116
  let check = null;
26831
27117
  if (recordExists) {
@@ -26844,7 +27130,7 @@ async function describeQuality(media, root, inspection) {
26844
27130
  return {
26845
27131
  state: inspection.state,
26846
27132
  reason: inspection.reason,
26847
- output: portableOutputPath(path48.resolve(root, inspection.output), root),
27133
+ output: portableOutputPath(path49.resolve(root, inspection.output), root),
26848
27134
  record: portableOutputPath(recordPath, root),
26849
27135
  recordExists,
26850
27136
  outputs,
@@ -26882,9 +27168,9 @@ async function buildGallerySnapshot(opts) {
26882
27168
  const media = /* @__PURE__ */ new Map();
26883
27169
  const plan = await buildPlan(specs, lock);
26884
27170
  const items = [];
26885
- const manifestText = await readFile34(loaded.path, "utf8");
27171
+ const manifestText = await readFile35(loaded.path, "utf8");
26886
27172
  const manifestSha256 = sha256(manifestText);
26887
- const cacheDir = path48.resolve(path48.dirname(opts.lockPath), ".pixelkiln", "cache");
27173
+ const cacheDir = path49.resolve(path49.dirname(opts.lockPath), ".pixelkiln", "cache");
26888
27174
  let rawStyles = {};
26889
27175
  try {
26890
27176
  const raw = JSON.parse(manifestText);
@@ -26908,12 +27194,12 @@ async function buildGallerySnapshot(opts) {
26908
27194
  )
26909
27195
  );
26910
27196
  if (spec.source) {
26911
- const editPath = path48.resolve(root, spec.source);
27197
+ const editPath = path49.resolve(root, spec.source);
26912
27198
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
26913
27199
  const editShas = await Promise.all(
26914
27200
  Array.from({ length: memberCount }, async (_, index) => {
26915
27201
  const file = sourceOutputPath(spec.source, entry, index, root);
26916
- return { file, sha256: existsSync42(file) ? await sha256File(file) : null };
27202
+ return { file, sha256: existsSync43(file) ? await sha256File(file) : null };
26917
27203
  })
26918
27204
  );
26919
27205
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -26921,7 +27207,7 @@ async function buildGallerySnapshot(opts) {
26921
27207
  const companion = await readHandEditCompanion(editPath);
26922
27208
  if (companion) {
26923
27209
  const projectPath = handEditProjectPath(editPath);
26924
- const project2 = companion.project && existsSync42(projectPath) ? await fileInfo(projectPath) : null;
27210
+ const project2 = companion.project && existsSync43(projectPath) ? await fileInfo(projectPath) : null;
26925
27211
  let projectUrl = null;
26926
27212
  if (project2) {
26927
27213
  const id = galleryMediaId(projectPath);
@@ -26957,8 +27243,8 @@ async function buildGallerySnapshot(opts) {
26957
27243
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
26958
27244
  }
26959
27245
  } else if (spec.source) {
26960
- outputs = [await describeOutput(media, root, path48.resolve(root, spec.source))];
26961
- } else if (!entry && existsSync42(spec.outFile)) {
27246
+ outputs = [await describeOutput(media, root, path49.resolve(root, spec.source))];
27247
+ } else if (!entry && existsSync43(spec.outFile)) {
26962
27248
  outputs = [await describeOutput(media, root, spec.outFile)];
26963
27249
  } else {
26964
27250
  outputs = [];
@@ -27162,7 +27448,7 @@ async function buildGallerySnapshot(opts) {
27162
27448
  id: loaded.manifest.name,
27163
27449
  name: loaded.manifest.name,
27164
27450
  manifest: loaded.path,
27165
- lock: path48.resolve(opts.lockPath),
27451
+ lock: path49.resolve(opts.lockPath),
27166
27452
  root,
27167
27453
  provider: loaded.manifest.provider,
27168
27454
  account: null,
@@ -27191,7 +27477,7 @@ async function buildGallerySnapshot(opts) {
27191
27477
  return { snapshot, media };
27192
27478
  }
27193
27479
  async function buildWorkspaceGallerySnapshot(opts) {
27194
- const dir = path48.dirname(path48.resolve(opts.workspacePath));
27480
+ const dir = path49.dirname(path49.resolve(opts.workspacePath));
27195
27481
  const media = /* @__PURE__ */ new Map();
27196
27482
  const projects = [];
27197
27483
  const items = [];
@@ -27236,11 +27522,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
27236
27522
  id: project2.id,
27237
27523
  name: loaded.manifest.name,
27238
27524
  manifest: manifestPath,
27239
- lock: path48.resolve(lockPath),
27525
+ lock: path49.resolve(lockPath),
27240
27526
  root: loaded.root,
27241
27527
  provider: loaded.manifest.provider,
27242
27528
  account: project2.account ?? null,
27243
- manifestSha256: manifestSha256 ?? sha256(await readFile34(manifestPath, "utf8")),
27529
+ manifestSha256: manifestSha256 ?? sha256(await readFile35(manifestPath, "utf8")),
27244
27530
  historyLimit: historyLimit(loaded.manifest),
27245
27531
  entries: Object.keys(lock.entries).length,
27246
27532
  items: projectItems.length,
@@ -27252,8 +27538,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
27252
27538
  id: project2.id,
27253
27539
  name: project2.id,
27254
27540
  manifest: manifestPath,
27255
- lock: path48.resolve(lockPath),
27256
- root: path48.dirname(manifestPath),
27541
+ lock: path49.resolve(lockPath),
27542
+ root: path49.dirname(manifestPath),
27257
27543
  provider: project2.provider,
27258
27544
  account: project2.account ?? null,
27259
27545
  manifestSha256: null,
@@ -27280,7 +27566,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
27280
27566
  version: 1,
27281
27567
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
27282
27568
  project: null,
27283
- workspace: { path: path48.resolve(opts.workspacePath), dir, projects },
27569
+ workspace: { path: path49.resolve(opts.workspacePath), dir, projects },
27284
27570
  filter,
27285
27571
  totals: {
27286
27572
  entries: projects.reduce((sum, project2) => sum + project2.entries, 0),
@@ -27299,7 +27585,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
27299
27585
  }
27300
27586
 
27301
27587
  // src/gallery/page.ts
27302
- import { existsSync as existsSync43, readFileSync as readFileSync10 } from "fs";
27588
+ import { existsSync as existsSync44, readFileSync as readFileSync10 } from "fs";
27303
27589
 
27304
27590
  // src/gallery/client-bundle.ts
27305
27591
  import { createRequire as createRequire3 } from "module";
@@ -27340,7 +27626,7 @@ function clientAssets() {
27340
27626
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
27341
27627
  client ??= {
27342
27628
  css: readFileSync10(new URL("gallery.css", CLIENT_DIR), "utf8"),
27343
- js: existsSync43(prebuilt) ? readFileSync10(prebuilt, "utf8") : bundleGalleryClient()
27629
+ js: existsSync44(prebuilt) ? readFileSync10(prebuilt, "utf8") : bundleGalleryClient()
27344
27630
  };
27345
27631
  return client;
27346
27632
  }
@@ -27483,10 +27769,10 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
27483
27769
 
27484
27770
  // src/editor/install.ts
27485
27771
  import { createHash as createHash9 } from "crypto";
27486
- import { existsSync as existsSync44 } from "fs";
27487
- import { mkdir as mkdir20, readFile as readFile35, rename as rename13, rm as rm13, stat as stat6, writeFile as writeFile25 } from "fs/promises";
27772
+ import { existsSync as existsSync45 } from "fs";
27773
+ import { mkdir as mkdir21, readFile as readFile36, rename as rename14, rm as rm14, stat as stat6, writeFile as writeFile26 } from "fs/promises";
27488
27774
  import os3 from "os";
27489
- import path49 from "path";
27775
+ import path50 from "path";
27490
27776
  var EditorInstallError = class extends Error {
27491
27777
  constructor(message6, file) {
27492
27778
  super(message6);
@@ -27497,15 +27783,15 @@ var EditorInstallError = class extends Error {
27497
27783
  };
27498
27784
  function editorToolsRoot() {
27499
27785
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
27500
- if (override) return path49.resolve(override);
27501
- if (process.platform === "darwin") return path49.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
27786
+ if (override) return path50.resolve(override);
27787
+ if (process.platform === "darwin") return path50.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
27502
27788
  if (process.platform === "win32") {
27503
- return path49.join(process.env.LOCALAPPDATA ?? path49.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
27789
+ return path50.join(process.env.LOCALAPPDATA ?? path50.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
27504
27790
  }
27505
- return path49.join(process.env.XDG_CACHE_HOME ?? path49.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
27791
+ return path50.join(process.env.XDG_CACHE_HOME ?? path50.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
27506
27792
  }
27507
27793
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
27508
- return path49.join(root, "pixelorama", pin.release ?? "unpublished");
27794
+ return path50.join(root, "pixelorama", pin.release ?? "unpublished");
27509
27795
  }
27510
27796
  function editorBaseUrl(pin = EDITOR_PIN) {
27511
27797
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -27515,7 +27801,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
27515
27801
  }
27516
27802
  async function sha256Of(file) {
27517
27803
  try {
27518
- return createHash9("sha256").update(await readFile35(file)).digest("hex");
27804
+ return createHash9("sha256").update(await readFile36(file)).digest("hex");
27519
27805
  } catch {
27520
27806
  return null;
27521
27807
  }
@@ -27528,8 +27814,8 @@ async function editorStatus(opts = {}) {
27528
27814
  let totalBytes = 0;
27529
27815
  for (const [name, expected] of Object.entries(pin.files)) {
27530
27816
  totalBytes += expected.bytes;
27531
- const file = path49.join(dir, name);
27532
- const info = existsSync44(file) ? await stat6(file).catch(() => null) : null;
27817
+ const file = path50.join(dir, name);
27818
+ const info = existsSync45(file) ? await stat6(file).catch(() => null) : null;
27533
27819
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
27534
27820
  installedBytes += expected.bytes;
27535
27821
  } else {
@@ -27558,7 +27844,7 @@ async function installEditor(opts = {}) {
27558
27844
  );
27559
27845
  }
27560
27846
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
27561
- await mkdir20(dir, { recursive: true });
27847
+ await mkdir21(dir, { recursive: true });
27562
27848
  const downloaded = [];
27563
27849
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
27564
27850
  let fetchedBytes = before.installedBytes;
@@ -27586,13 +27872,13 @@ async function installEditor(opts = {}) {
27586
27872
  if (digest2 !== expected.sha256) {
27587
27873
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
27588
27874
  }
27589
- const final = path49.join(dir, name);
27875
+ const final = path50.join(dir, name);
27590
27876
  const tmp = `${final}.${process.pid}.part`;
27591
27877
  try {
27592
- await writeFile25(tmp, bytes);
27593
- await rename13(tmp, final);
27878
+ await writeFile26(tmp, bytes);
27879
+ await rename14(tmp, final);
27594
27880
  } finally {
27595
- await rm13(tmp, { force: true });
27881
+ await rm14(tmp, { force: true });
27596
27882
  }
27597
27883
  fetchedBytes += bytes.length;
27598
27884
  downloaded.push(name);
@@ -27632,12 +27918,12 @@ var EDITOR_CONTENT_TYPES = {
27632
27918
  ".json": "application/json; charset=utf-8"
27633
27919
  };
27634
27920
  function editorContentType(name) {
27635
- return EDITOR_CONTENT_TYPES[path49.extname(name).toLowerCase()] ?? null;
27921
+ return EDITOR_CONTENT_TYPES[path50.extname(name).toLowerCase()] ?? null;
27636
27922
  }
27637
27923
 
27638
27924
  // src/gallery/editor.ts
27639
- import { readFile as readFile36 } from "fs/promises";
27640
- import path50 from "path";
27925
+ import { readFile as readFile37 } from "fs/promises";
27926
+ import path51 from "path";
27641
27927
  function editorRoute(release, name = "index.html") {
27642
27928
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
27643
27929
  }
@@ -27710,7 +27996,7 @@ function createGalleryEditorHandlers(opts = {}) {
27710
27996
  if (!status.installed) return null;
27711
27997
  let bytes;
27712
27998
  try {
27713
- bytes = await readFile36(path50.join(dir, name));
27999
+ bytes = await readFile37(path51.join(dir, name));
27714
28000
  } catch {
27715
28001
  verified = null;
27716
28002
  return null;
@@ -27727,7 +28013,7 @@ function createGalleryEditorHandlers(opts = {}) {
27727
28013
  // src/gallery/server.ts
27728
28014
  import { randomBytes } from "crypto";
27729
28015
  import { createServer as createServer2 } from "http";
27730
- import { readFile as readFile37 } from "fs/promises";
28016
+ import { readFile as readFile38 } from "fs/promises";
27731
28017
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
27732
28018
  var EDITOR_CSP = [
27733
28019
  "default-src 'self'",
@@ -27908,7 +28194,7 @@ async function serveGallery(opts) {
27908
28194
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
27909
28195
  if (!asset) return fail(404, "no such review asset");
27910
28196
  try {
27911
- const bytes = await readFile37(asset.path);
28197
+ const bytes = await readFile38(asset.path);
27912
28198
  res.writeHead(200, {
27913
28199
  "Content-Type": asset.contentType,
27914
28200
  "Cache-Control": "no-store",
@@ -27991,7 +28277,7 @@ async function serveGallery(opts) {
27991
28277
  if (!asset) return fail(404, "no such gallery media");
27992
28278
  let bytes;
27993
28279
  try {
27994
- bytes = await readFile37(asset.path);
28280
+ bytes = await readFile38(asset.path);
27995
28281
  } catch {
27996
28282
  return fail(404, "gallery media is no longer on disk; refresh the page");
27997
28283
  }
@@ -28035,27 +28321,27 @@ async function serveGallery(opts) {
28035
28321
 
28036
28322
  // src/gallery/generate.ts
28037
28323
  import { randomBytes as randomBytes2 } from "crypto";
28038
- import { z as z17 } from "zod";
28039
- var GenerateRequestSchema = z17.object({
28040
- project: z17.string().min(1).optional(),
28041
- keys: z17.array(z17.string().min(1)).min(1).max(500),
28324
+ import { z as z18 } from "zod";
28325
+ var GenerateRequestSchema = z18.object({
28326
+ project: z18.string().min(1).optional(),
28327
+ keys: z18.array(z18.string().min(1)).min(1).max(500),
28042
28328
  /**
28043
28329
  * Regenerate work that is up to date, as `gen --force` does, and let the
28044
28330
  * fetch replace a locally modified or untracked file. With `restore`, put
28045
28331
  * the recorded bytes back over a modified file.
28046
28332
  */
28047
- force: z17.boolean().optional(),
28333
+ force: z18.boolean().optional(),
28048
28334
  /** Advance in-flight, review, or selected work without submitting anything. */
28049
- resume: z17.boolean().optional(),
28335
+ resume: z18.boolean().optional(),
28050
28336
  /** Re-download downloaded outputs and replace files whose object changed upstream. */
28051
- refresh: z17.boolean().optional(),
28337
+ refresh: z18.boolean().optional(),
28052
28338
  /** Put recorded outputs back on disk from the cache or the provider, without generating. */
28053
- restore: z17.boolean().optional(),
28339
+ restore: z18.boolean().optional(),
28054
28340
  /**
28055
28341
  * Bring a replaced generation back: 1-based position in the record's
28056
28342
  * history (newest first) or an output hash prefix. One key at a time.
28057
28343
  */
28058
- revert: z17.string().min(1).max(64).optional()
28344
+ revert: z18.string().min(1).max(64).optional()
28059
28345
  }).strict().refine((request) => [request.resume, request.refresh, request.restore, request.revert !== void 0].filter(Boolean).length <= 1, {
28060
28346
  message: "resume, refresh, restore, and revert are exclusive"
28061
28347
  }).refine((request) => request.revert === void 0 || request.keys.length === 1, { message: "revert takes one key" });
@@ -28375,7 +28661,8 @@ function createGenerateHandlers(opts) {
28375
28661
  keys: job.review,
28376
28662
  specs,
28377
28663
  onProgress: (line) => say(job, line),
28378
- routePrefix: options.routePrefix
28664
+ routePrefix: options.routePrefix,
28665
+ lockPath: ctx.lockPath
28379
28666
  });
28380
28667
  if (session) reviews.set(jobId, session);
28381
28668
  return session;
@@ -28401,19 +28688,19 @@ function createGenerateHandlers(opts) {
28401
28688
  }
28402
28689
 
28403
28690
  // src/pipeline/salvage.ts
28404
- import { readFile as readFile38 } from "fs/promises";
28405
- import { existsSync as existsSync45 } from "fs";
28406
- import path51 from "path";
28691
+ import { readFile as readFile39 } from "fs/promises";
28692
+ import { existsSync as existsSync46 } from "fs";
28693
+ import path52 from "path";
28407
28694
  function providerClaimId(provider, objectId) {
28408
28695
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
28409
28696
  }
28410
28697
  async function loadClaims(lockPaths, opts = {}) {
28411
28698
  const claimed = /* @__PURE__ */ new Set();
28412
28699
  for (const p of lockPaths) {
28413
- if (!existsSync45(p)) throw new Error(`Claim lockfile not found: ${p}`);
28700
+ if (!existsSync46(p)) throw new Error(`Claim lockfile not found: ${p}`);
28414
28701
  let parsed;
28415
28702
  try {
28416
- parsed = parseLock(JSON.parse(await readFile38(p, "utf8")));
28703
+ parsed = parseLock(JSON.parse(await readFile39(p, "utf8")));
28417
28704
  } catch {
28418
28705
  throw new Error(`Claim lockfile is malformed: ${p}`);
28419
28706
  }
@@ -28517,20 +28804,20 @@ function matchOrphanStyle(prompt, manifest) {
28517
28804
  return matchStyleByPattern(prompt, manifest);
28518
28805
  }
28519
28806
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
28520
- const own = path51.resolve(ownManifestPath);
28807
+ const own = path52.resolve(ownManifestPath);
28521
28808
  const siblingManifestPaths = [
28522
28809
  .../* @__PURE__ */ new Set([
28523
28810
  ...workspaceManifestPaths,
28524
- ...claimPaths.map((c) => path51.join(path51.dirname(path51.resolve(c)), "pixelkiln.manifest.json"))
28811
+ ...claimPaths.map((c) => path52.join(path52.dirname(path52.resolve(c)), "pixelkiln.manifest.json"))
28525
28812
  ])
28526
28813
  ];
28527
28814
  const siblings = [];
28528
28815
  for (const siblingManifestPath of siblingManifestPaths) {
28529
- if (path51.resolve(siblingManifestPath) === own) continue;
28530
- if (!existsSync45(siblingManifestPath)) continue;
28816
+ if (path52.resolve(siblingManifestPath) === own) continue;
28817
+ if (!existsSync46(siblingManifestPath)) continue;
28531
28818
  try {
28532
28819
  const { manifest } = await loadManifest(siblingManifestPath);
28533
- siblings.push({ label: path51.basename(path51.dirname(siblingManifestPath)), manifest });
28820
+ siblings.push({ label: path52.basename(path52.dirname(siblingManifestPath)), manifest });
28534
28821
  } catch {
28535
28822
  }
28536
28823
  }
@@ -28650,8 +28937,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
28650
28937
  }
28651
28938
 
28652
28939
  // src/pick/salvage-server.ts
28653
- import { mkdir as mkdir21, writeFile as writeFile26, readFile as readFile39 } from "fs/promises";
28654
- import path52 from "path";
28940
+ import { mkdir as mkdir22, writeFile as writeFile27, readFile as readFile40 } from "fs/promises";
28941
+ import path53 from "path";
28655
28942
 
28656
28943
  // src/pick/salvage-sheet.ts
28657
28944
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -28817,7 +29104,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28817
29104
  });
28818
29105
  const html = renderSalvageSheet(orphans, {
28819
29106
  styleId: ctx.styleId,
28820
- importDir: path52.relative(process.cwd(), ctx.importDir) || "."
29107
+ importDir: path53.relative(process.cwd(), ctx.importDir) || "."
28821
29108
  });
28822
29109
  const byId = new Map(orphans.map((o) => [o.id, o]));
28823
29110
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -28873,10 +29160,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28873
29160
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
28874
29161
  decodePng(buf);
28875
29162
  const assetId = idFromPrompt(orphan.prompt, taken);
28876
- const rel = path52.join("_salvaged", `${assetId}.png`);
28877
- const outFile = path52.resolve(ctx.importDir, rel);
28878
- await mkdir21(path52.dirname(outFile), { recursive: true });
28879
- await writeFile26(outFile, buf);
29163
+ const rel = path53.join("_salvaged", `${assetId}.png`);
29164
+ const outFile = path53.resolve(ctx.importDir, rel);
29165
+ await mkdir22(path53.dirname(outFile), { recursive: true });
29166
+ await writeFile27(outFile, buf);
28880
29167
  ctx.manifest.assets[assetId] = {
28881
29168
  prompt: orphan.prompt,
28882
29169
  promptByStyle: {},
@@ -28908,7 +29195,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28908
29195
  sourceUrl: durableSource,
28909
29196
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
28910
29197
  outputs: [{
28911
- path: portableOutputPath(outFile, path52.dirname(ctx.manifestPath)),
29198
+ path: portableOutputPath(outFile, path53.dirname(ctx.manifestPath)),
28912
29199
  sha256: sha256(buf)
28913
29200
  }],
28914
29201
  submittedAt: orphan.createdAt,
@@ -28932,9 +29219,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28932
29219
  }
28933
29220
  }
28934
29221
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
28935
- const raw = JSON.parse(await readFile39(ctx.manifestPath, "utf8"));
29222
+ const raw = JSON.parse(await readFile40(ctx.manifestPath, "utf8"));
28936
29223
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
28937
- await writeFile26(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
29224
+ await writeFile27(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
28938
29225
  await saveLock(ctx.lockPath, ctx.lock);
28939
29226
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
28940
29227
  return result;