pixelkiln 0.110.0 → 0.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -41,6 +41,12 @@ __export(index_exports, {
41
41
  CHARACTER_DIRECTIONS_4: () => CHARACTER_DIRECTIONS_4,
42
42
  CHARACTER_DIRECTIONS_8: () => CHARACTER_DIRECTIONS_8,
43
43
  CHARACTER_PROPORTION_PRESETS: () => CHARACTER_PROPORTION_PRESETS,
44
+ CODEX_CAMERAS: () => CODEX_CAMERAS,
45
+ CODEX_ID: () => CODEX_ID,
46
+ CODEX_INSTALL: () => CODEX_INSTALL,
47
+ CODEX_PACKAGE: () => CODEX_PACKAGE,
48
+ CODEX_REPOSITORY: () => CODEX_REPOSITORY,
49
+ CODEX_TUNE_KEYS: () => CODEX_TUNE_KEYS,
44
50
  CharacterAnimationModeSchema: () => CharacterAnimationModeSchema,
45
51
  CharacterAnimationSchema: () => CharacterAnimationSchema,
46
52
  CharacterAttachSchema: () => CharacterAttachSchema,
@@ -180,6 +186,7 @@ __export(index_exports, {
180
186
  applyManifestEdit: () => applyManifestEdit,
181
187
  applyTags: () => applyTags,
182
188
  approveQualityRecord: () => approveQualityRecord,
189
+ assertFreshOutputs: () => assertFreshOutputs,
183
190
  assetInStyle: () => assetInStyle,
184
191
  auditStyle: () => auditStyle,
185
192
  availableProviders: () => availableProviders,
@@ -193,6 +200,7 @@ __export(index_exports, {
193
200
  cacheFileName: () => cacheFileName,
194
201
  candidateCount: () => candidateCount,
195
202
  characterDirections: () => characterDirections,
203
+ checkCodexRecipe: () => checkCodexRecipe,
196
204
  checkExportBytes: () => checkExportBytes,
197
205
  checkPixelfxRecipe: () => checkPixelfxRecipe,
198
206
  checkQualityBaseline: () => checkQualityBaseline,
@@ -238,6 +246,7 @@ __export(index_exports, {
238
246
  fetchWithRetry: () => fetchWithRetry,
239
247
  findOrphans: () => findOrphans,
240
248
  fontOutputPaths: () => fontOutputPaths,
249
+ formatCodexEffects: () => formatCodexEffects,
241
250
  formatCost: () => formatCost,
242
251
  formatPixelfxEffects: () => formatPixelfxEffects,
243
252
  frameSetFps: () => frameSetFps,
@@ -280,14 +289,18 @@ __export(index_exports, {
280
289
  isometricTileCost: () => isometricTileCost,
281
290
  layerOffsetFor: () => layerOffsetFor,
282
291
  listBundledRecipes: () => listBundledRecipes,
292
+ listCodexEffects: () => listCodexEffects,
283
293
  listPixelfxEffects: () => listPixelfxEffects,
284
294
  loadClaims: () => loadClaims,
295
+ loadCodex: () => loadCodex,
285
296
  loadLock: () => loadLock,
286
297
  loadManifest: () => loadManifest,
287
298
  loadPixelfx: () => loadPixelfx,
288
299
  loadSiblingManifests: () => loadSiblingManifests,
289
300
  loadWorkspace: () => loadWorkspace,
301
+ localSheet: () => localSheet,
290
302
  lockKey: () => lockKey,
303
+ makeCodexVfx: () => makeCodexVfx,
291
304
  makePixelfxVfx: () => makePixelfxVfx,
292
305
  makeVfx: () => makeVfx,
293
306
  makeVfxWithArtist: () => makeVfxWithArtist,
@@ -339,6 +352,7 @@ __export(index_exports, {
339
352
  pixMiniMaxCost: () => pixMiniMaxCost,
340
353
  pixelateFile: () => pixelateFile,
341
354
  pixelfxSheet: () => pixelfxSheet,
355
+ planCodex: () => planCodex,
342
356
  pngFilesAt: () => pngFilesAt,
343
357
  pngSize: () => pngSize,
344
358
  poll: () => poll,
@@ -356,6 +370,7 @@ __export(index_exports, {
356
370
  qualityRecordPath: () => qualityRecordPath,
357
371
  quantizeToPalette: () => quantizeToPalette,
358
372
  readArtifactBundleManifest: () => readArtifactBundleManifest,
373
+ readCodexRecipe: () => readCodexRecipe,
359
374
  readHandEditCompanion: () => readHandEditCompanion,
360
375
  readPixelfxRecipe: () => readPixelfxRecipe,
361
376
  readQualityBaseline: () => readQualityBaseline,
@@ -371,6 +386,7 @@ __export(index_exports, {
371
386
  registerProvider: () => registerProvider,
372
387
  remove: () => remove,
373
388
  renderAsepriteSheet: () => renderAsepriteSheet,
389
+ renderCodex: () => renderCodex,
374
390
  renderGallery: () => renderGallery,
375
391
  renderGodotSpriteFrames: () => renderGodotSpriteFrames,
376
392
  renderPixelfx: () => renderPixelfx,
@@ -465,6 +481,7 @@ __export(index_exports, {
465
481
  workspaceClaims: () => workspaceClaims,
466
482
  workspaceStatus: () => workspaceStatus,
467
483
  writeArtifactBundle: () => writeArtifactBundle,
484
+ writeLocalVfx: () => writeLocalVfx,
468
485
  writeManagedArtifactBundle: () => writeManagedArtifactBundle
469
486
  });
470
487
  module.exports = __toCommonJS(index_exports);
@@ -1886,7 +1903,7 @@ var AssetDeriveSchema = import_zod.z.object({
1886
1903
  /** 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. */
1887
1904
  tolerance: import_zod.z.number().min(0).max(442).optional()
1888
1905
  }).strict().superRefine((derive, context) => {
1889
- const issue = (message6, path51) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path51] });
1906
+ const issue = (message6, path53) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path53] });
1890
1907
  if (Boolean(derive.from) === Boolean(derive.file)) {
1891
1908
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1892
1909
  }
@@ -3239,9 +3256,9 @@ var PixelLabClient = class {
3239
3256
  apiKey;
3240
3257
  http;
3241
3258
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
3242
- async request(path51, init) {
3259
+ async request(path53, init) {
3243
3260
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
3244
- const res = await this.http(`${BASE}${path51}`, {
3261
+ const res = await this.http(`${BASE}${path53}`, {
3245
3262
  ...init,
3246
3263
  headers: {
3247
3264
  Authorization: auth,
@@ -3252,13 +3269,13 @@ var PixelLabClient = class {
3252
3269
  const text = await res.text();
3253
3270
  if (!res.ok) {
3254
3271
  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' : "";
3255
- throw new PixelLabError(`${init?.method ?? "GET"} ${path51} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3272
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path53} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3256
3273
  }
3257
3274
  if (!text) return {};
3258
3275
  try {
3259
3276
  return JSON.parse(text);
3260
3277
  } catch {
3261
- throw new Error(`${init?.method ?? "GET"} ${path51} returned invalid JSON`);
3278
+ throw new Error(`${init?.method ?? "GET"} ${path53} returned invalid JSON`);
3262
3279
  }
3263
3280
  }
3264
3281
  async balance() {
@@ -3805,10 +3822,10 @@ var PixelLabClient = class {
3805
3822
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
3806
3823
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
3807
3824
  const south = args.reference?.south;
3808
- let path51;
3825
+ let path53;
3809
3826
  let body;
3810
3827
  if (args.mode === "v3") {
3811
- path51 = "/create-character-v3";
3828
+ path53 = "/create-character-v3";
3812
3829
  body = {
3813
3830
  description: args.description,
3814
3831
  image_size: imageSize,
@@ -3822,7 +3839,7 @@ var PixelLabClient = class {
3822
3839
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
3823
3840
  };
3824
3841
  } else if (args.mode === "pro-flash") {
3825
- path51 = "/create-character-pro-flash";
3842
+ path53 = "/create-character-pro-flash";
3826
3843
  const traits = args.styleTraits;
3827
3844
  body = {
3828
3845
  description: args.description,
@@ -3846,7 +3863,7 @@ var PixelLabClient = class {
3846
3863
  } : {}
3847
3864
  };
3848
3865
  } else if (args.mode === "pro") {
3849
- path51 = "/create-character-pro";
3866
+ path53 = "/create-character-pro";
3850
3867
  body = {
3851
3868
  description: args.description,
3852
3869
  image_size: imageSize,
@@ -3860,7 +3877,7 @@ var PixelLabClient = class {
3860
3877
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
3861
3878
  };
3862
3879
  } else {
3863
- path51 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3880
+ path53 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3864
3881
  body = {
3865
3882
  description: args.description,
3866
3883
  image_size: imageSize,
@@ -3878,8 +3895,8 @@ var PixelLabClient = class {
3878
3895
  };
3879
3896
  }
3880
3897
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
3881
- const raw = await this.request(path51, { method: "POST", body: JSON.stringify(body) });
3882
- return validateResponse(CharacterSubmitSchema, raw, path51.slice(1));
3898
+ const raw = await this.request(path53, { method: "POST", body: JSON.stringify(body) });
3899
+ return validateResponse(CharacterSubmitSchema, raw, path53.slice(1));
3883
3900
  }
3884
3901
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
3885
3902
  async createCharacterState(args) {
@@ -5509,10 +5526,10 @@ function normalizeHex(value) {
5509
5526
  function sha256(data) {
5510
5527
  return (0, import_node_crypto.createHash)("sha256").update(data).digest("hex");
5511
5528
  }
5512
- async function sha256File(path51) {
5529
+ async function sha256File(path53) {
5513
5530
  return new Promise((resolve, reject) => {
5514
5531
  const hash = (0, import_node_crypto.createHash)("sha256");
5515
- const stream = (0, import_node_fs.createReadStream)(path51);
5532
+ const stream = (0, import_node_fs.createReadStream)(path53);
5516
5533
  stream.on("data", (chunk2) => hash.update(chunk2));
5517
5534
  stream.on("error", reject);
5518
5535
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -11311,9 +11328,9 @@ var RetroDiffusionClient = class {
11311
11328
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
11312
11329
  return Buffer.from(await response.arrayBuffer());
11313
11330
  }
11314
- async call(path51, init = {}) {
11331
+ async call(path53, init = {}) {
11315
11332
  if (!this.token) throw new Error("RD_API_KEY is not set");
11316
- const response = await this.request(`${this.baseUrl}${path51}`, {
11333
+ const response = await this.request(`${this.baseUrl}${path53}`, {
11317
11334
  ...init,
11318
11335
  headers: {
11319
11336
  "Content-Type": "application/json",
@@ -18414,11 +18431,108 @@ async function saveToAssetFile(client2, target, from, opts = {}) {
18414
18431
  }
18415
18432
 
18416
18433
  // src/pixelfx-vfx.ts
18434
+ var import_node_fs23 = require("fs");
18435
+ var import_promises17 = require("fs/promises");
18436
+ var import_node_module = require("module");
18437
+ var import_node_path26 = __toESM(require("path"), 1);
18438
+ var import_node_url2 = require("url");
18439
+
18440
+ // src/local-vfx.ts
18417
18441
  var import_node_fs22 = require("fs");
18418
18442
  var import_promises16 = require("fs/promises");
18419
- var import_node_module = require("module");
18420
18443
  var import_node_path25 = __toESM(require("path"), 1);
18421
- var import_node_url2 = require("url");
18444
+ function localSheet(render) {
18445
+ const { width, height, frames } = render;
18446
+ const columns = Math.min(frames.length, Math.max(1, Math.ceil(Math.sqrt(frames.length * height / width))));
18447
+ const rows = Math.ceil(frames.length / columns);
18448
+ const sheet = Buffer.alloc(columns * width * rows * height * 4);
18449
+ const rects = frames.map((rgba, index) => {
18450
+ const x = index % columns * width;
18451
+ const y = Math.floor(index / columns) * height;
18452
+ for (let row = 0; row < height; row++) {
18453
+ rgba.copy(sheet, ((y + row) * columns * width + x) * 4, row * width * 4, (row + 1) * width * 4);
18454
+ }
18455
+ return { x, y, w: width, h: height };
18456
+ });
18457
+ return { png: encodeRgbaPng(columns * width, rows * height, sheet), columns, rows, rects };
18458
+ }
18459
+ function assertFreshOutputs(out, force) {
18460
+ const paths = vfxOutputPaths(out);
18461
+ if (!force) {
18462
+ for (const file of [paths.sheet, paths.atlas, paths.provenance]) {
18463
+ if ((0, import_node_fs22.existsSync)(file)) throw new Error(`${file} already exists; pass --force to replace it`);
18464
+ }
18465
+ }
18466
+ return paths;
18467
+ }
18468
+ async function writeLocalVfx(opts) {
18469
+ const { paths, render } = opts;
18470
+ const sheet = localSheet(render);
18471
+ const clip = import_node_path25.default.basename(paths.sheet, ".png");
18472
+ const anchor = { kind: "origin", ...render.anchor };
18473
+ const size = { w: render.width, h: render.height };
18474
+ const atlas = {
18475
+ frames: sheet.rects.map((frame, index) => ({
18476
+ filename: `${clip} ${index}`,
18477
+ frame,
18478
+ rotated: false,
18479
+ trimmed: false,
18480
+ spriteSourceSize: { x: 0, y: 0, ...size },
18481
+ sourceSize: size,
18482
+ duration: Math.round(1e3 / render.fps)
18483
+ })),
18484
+ meta: {
18485
+ app: "pixelkiln",
18486
+ version: "1",
18487
+ image: import_node_path25.default.basename(paths.sheet),
18488
+ format: "RGBA8888",
18489
+ size: { w: sheet.columns * render.width, h: sheet.rows * render.height },
18490
+ scale: "1",
18491
+ frameTags: [{ name: clip, from: 0, to: render.frames.length - 1, direction: "forward" }],
18492
+ anchor,
18493
+ [opts.atlasKey]: {
18494
+ id: opts.effect,
18495
+ name: opts.name,
18496
+ ...opts.atlasFacts,
18497
+ fps: render.fps,
18498
+ loop: render.loop,
18499
+ frames: render.frames.length,
18500
+ frameSize: [render.width, render.height],
18501
+ pivot: [anchor.x, anchor.y],
18502
+ columns: sheet.columns
18503
+ }
18504
+ }
18505
+ };
18506
+ const sheetSha256 = sha256(sheet.png);
18507
+ const facts = {
18508
+ name: opts.name,
18509
+ effect: opts.effect,
18510
+ width: render.width,
18511
+ height: render.height,
18512
+ frames: render.frames.length,
18513
+ fps: render.fps,
18514
+ loop: render.loop,
18515
+ anchor
18516
+ };
18517
+ const record = {
18518
+ version: 1,
18519
+ ...opts.record,
18520
+ ...facts,
18521
+ files: { sheet: import_node_path25.default.basename(paths.sheet), atlas: import_node_path25.default.basename(paths.atlas) },
18522
+ sheetSha256,
18523
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
18524
+ recipe: opts.recipe
18525
+ };
18526
+ await (0, import_promises16.mkdir)(import_node_path25.default.dirname(paths.sheet), { recursive: true });
18527
+ await (0, import_promises16.writeFile)(paths.sheet, sheet.png);
18528
+ await (0, import_promises16.writeFile)(paths.atlas, `${JSON.stringify(atlas, null, 2)}
18529
+ `);
18530
+ await (0, import_promises16.writeFile)(paths.provenance, `${JSON.stringify(record, null, 2)}
18531
+ `);
18532
+ return { facts, columns: sheet.columns, sheetSha256, paths: { sheet: paths.sheet, atlas: paths.atlas, provenance: paths.provenance } };
18533
+ }
18534
+
18535
+ // src/pixelfx-vfx.ts
18422
18536
  var PIXELFX_TOOL = "pixelfx";
18423
18537
  var PIXELFX_REPOSITORY = "https://github.com/patch-gg/pixelfx";
18424
18538
  var PIXELFX_INSTALL = "npm i github:patch-gg/pixelfx";
@@ -18430,17 +18544,17 @@ function missingPixelfx(cause) {
18430
18544
  );
18431
18545
  }
18432
18546
  function pixelfxVersion(entry) {
18433
- for (let dir = import_node_path25.default.dirname(entry); dir !== import_node_path25.default.dirname(dir); dir = import_node_path25.default.dirname(dir)) {
18434
- const file = import_node_path25.default.join(dir, "package.json");
18435
- if (!(0, import_node_fs22.existsSync)(file)) continue;
18436
- const pkg = JSON.parse((0, import_node_fs22.readFileSync)(file, "utf8"));
18547
+ for (let dir = import_node_path26.default.dirname(entry); dir !== import_node_path26.default.dirname(dir); dir = import_node_path26.default.dirname(dir)) {
18548
+ const file = import_node_path26.default.join(dir, "package.json");
18549
+ if (!(0, import_node_fs23.existsSync)(file)) continue;
18550
+ const pkg = JSON.parse((0, import_node_fs23.readFileSync)(file, "utf8"));
18437
18551
  if (pkg.name === "pixelfx") return typeof pkg.version === "string" ? pkg.version : "unknown";
18438
18552
  }
18439
18553
  return "unknown";
18440
18554
  }
18441
18555
  async function loadPixelfx(from) {
18442
- const bases = from?.map((base) => (0, import_node_url2.pathToFileURL)(import_node_path25.default.resolve(base)).href) ?? [
18443
- (0, import_node_url2.pathToFileURL)(import_node_path25.default.join(process.cwd(), "package.json")).href,
18556
+ const bases = from?.map((base) => (0, import_node_url2.pathToFileURL)(import_node_path26.default.resolve(base)).href) ?? [
18557
+ (0, import_node_url2.pathToFileURL)(import_node_path26.default.join(process.cwd(), "package.json")).href,
18444
18558
  importMetaUrl
18445
18559
  ];
18446
18560
  let resolved;
@@ -18606,23 +18720,9 @@ function renderPixelfx(lib, recipe) {
18606
18720
  frames
18607
18721
  };
18608
18722
  }
18609
- function pixelfxSheet(render) {
18610
- const { width, height, frames } = render;
18611
- const columns = Math.min(frames.length, Math.max(1, Math.ceil(Math.sqrt(frames.length * height / width))));
18612
- const rows = Math.ceil(frames.length / columns);
18613
- const sheet = Buffer.alloc(columns * width * rows * height * 4);
18614
- const rects = frames.map((rgba, index) => {
18615
- const x = index % columns * width;
18616
- const y = Math.floor(index / columns) * height;
18617
- for (let row = 0; row < height; row++) {
18618
- rgba.copy(sheet, ((y + row) * columns * width + x) * 4, row * width * 4, (row + 1) * width * 4);
18619
- }
18620
- return { x, y, w: width, h: height };
18621
- });
18622
- return { png: encodeRgbaPng(columns * width, rows * height, sheet), columns, rows, rects };
18623
- }
18723
+ var pixelfxSheet = localSheet;
18624
18724
  async function readPixelfxRecipe(file) {
18625
- const parsed = JSON.parse(await (0, import_promises16.readFile)(file, "utf8"));
18725
+ const parsed = JSON.parse(await (0, import_promises17.readFile)(file, "utf8"));
18626
18726
  const record = parsed.tool === PIXELFX_TOOL;
18627
18727
  const raw = record ? parsed.recipe : parsed;
18628
18728
  if (!raw || typeof raw !== "object" || typeof raw.effect !== "string" || Array.isArray(raw.layers)) {
@@ -18644,7 +18744,6 @@ async function readPixelfxRecipe(file) {
18644
18744
  return { recipe, ...typeof version === "string" ? { libraryVersion: version } : {} };
18645
18745
  }
18646
18746
  async function makePixelfxVfx(lib, opts) {
18647
- const paths = vfxOutputPaths(opts.out);
18648
18747
  const recipe = {
18649
18748
  effect: opts.effect,
18650
18749
  ...opts.fps !== void 0 ? { fps: opts.fps } : {},
@@ -18652,98 +18751,314 @@ async function makePixelfxVfx(lib, opts) {
18652
18751
  ...opts.options && Object.keys(opts.options).length ? { options: opts.options } : {}
18653
18752
  };
18654
18753
  checkPixelfxRecipe(lib, recipe);
18655
- if (!opts.force) {
18656
- for (const file of [paths.sheet, paths.atlas, paths.provenance]) {
18657
- if ((0, import_node_fs22.existsSync)(file)) throw new Error(`${file} already exists; pass --force to replace it`);
18754
+ const paths = assertFreshOutputs(opts.out, opts.force);
18755
+ const render = renderPixelfx(lib, recipe);
18756
+ const written = await writeLocalVfx({
18757
+ paths,
18758
+ name: opts.name ?? render.effect.name,
18759
+ effect: opts.effect,
18760
+ render,
18761
+ atlasKey: "pixelfx",
18762
+ atlasFacts: { version: lib.version },
18763
+ record: {
18764
+ provider: "pixelfx",
18765
+ tool: PIXELFX_TOOL,
18766
+ library: { name: "pixelfx", version: lib.version, repository: PIXELFX_REPOSITORY, license: "MIT" }
18767
+ },
18768
+ recipe
18769
+ });
18770
+ return {
18771
+ provider: "pixelfx",
18772
+ library: { name: "pixelfx", version: lib.version },
18773
+ ...written.facts,
18774
+ columns: written.columns,
18775
+ sheetSha256: written.sheetSha256,
18776
+ paths: written.paths,
18777
+ recipe
18778
+ };
18779
+ }
18780
+
18781
+ // src/codex-vfx.ts
18782
+ var import_node_crypto7 = require("crypto");
18783
+ var import_node_fs24 = require("fs");
18784
+ var import_promises18 = require("fs/promises");
18785
+ var import_node_module2 = require("module");
18786
+ var import_node_path27 = __toESM(require("path"), 1);
18787
+ var import_node_url3 = require("url");
18788
+ var import_node_vm = __toESM(require("vm"), 1);
18789
+ var CODEX_ID = "codex";
18790
+ var CODEX_PACKAGE = "pixel-vfx-codex";
18791
+ var CODEX_REPOSITORY = "https://github.com/888wing/pixel-vfx-codex";
18792
+ var CODEX_INSTALL = "npm i github:888wing/pixel-vfx-codex";
18793
+ var CODEX_CAMERAS = ["2d", "25d", "3d"];
18794
+ var CANVAS = { "2d": [160, 100], "25d": [240, 150], "3d": [240, 150] };
18795
+ var CODEX_TUNE_KEYS = ["size", "gain", "density", "dither", "outline", "hitstop", "shake", "flash", "snap"];
18796
+ function missingCodex(cause) {
18797
+ return new PixelKilnError(
18798
+ "pixel-vfx-codex is not installed, so there is nothing to render these effects with",
18799
+ "capability",
18800
+ { hint: `Install it beside your project: ${CODEX_INSTALL} (${CODEX_REPOSITORY}, MIT; it is not on the npm registry)`, cause }
18801
+ );
18802
+ }
18803
+ function findCodexRoot(from) {
18804
+ const bases = from?.map((base) => (0, import_node_url3.pathToFileURL)(import_node_path27.default.resolve(base, "package.json")).href) ?? [
18805
+ (0, import_node_url3.pathToFileURL)(import_node_path27.default.join(process.cwd(), "package.json")).href,
18806
+ importMetaUrl
18807
+ ];
18808
+ let failure;
18809
+ for (const base of bases) {
18810
+ try {
18811
+ return import_node_path27.default.dirname((0, import_node_module2.createRequire)(base).resolve(`${CODEX_PACKAGE}/package.json`));
18812
+ } catch (error) {
18813
+ failure = error;
18658
18814
  }
18659
18815
  }
18660
- const render = renderPixelfx(lib, recipe);
18661
- const sheet = pixelfxSheet(render);
18662
- const name = opts.name ?? render.effect.name;
18663
- const clip = import_node_path25.default.basename(paths.sheet, ".png");
18664
- const anchor = { kind: "origin", ...render.anchor };
18665
- const size = { w: render.width, h: render.height };
18666
- const atlas = {
18667
- frames: sheet.rects.map((frame, index) => ({
18668
- filename: `${clip} ${index}`,
18669
- frame,
18670
- rotated: false,
18671
- trimmed: false,
18672
- spriteSourceSize: { x: 0, y: 0, ...size },
18673
- sourceSize: size,
18674
- duration: Math.round(1e3 / render.fps)
18675
- })),
18676
- meta: {
18677
- app: "pixelkiln",
18678
- version: "1",
18679
- image: import_node_path25.default.basename(paths.sheet),
18680
- format: "RGBA8888",
18681
- size: { w: sheet.columns * render.width, h: sheet.rows * render.height },
18682
- scale: "1",
18683
- frameTags: [{ name: clip, from: 0, to: render.frames.length - 1, direction: "forward" }],
18684
- anchor,
18685
- pixelfx: {
18686
- id: opts.effect,
18687
- name,
18688
- version: lib.version,
18689
- fps: render.fps,
18690
- loop: render.loop,
18691
- frames: render.frames.length,
18692
- frameSize: [render.width, render.height],
18693
- pivot: [anchor.x, anchor.y],
18694
- columns: sheet.columns
18816
+ throw missingCodex(failure);
18817
+ }
18818
+ function loadCodex(from) {
18819
+ const root = findCodexRoot(from);
18820
+ const read = (...parts) => (0, import_node_fs24.readFileSync)(import_node_path27.default.join(root, ...parts), "utf8");
18821
+ const pkg = JSON.parse(read("package.json"));
18822
+ const version = typeof pkg.version === "string" ? pkg.version : "unknown";
18823
+ for (const required of ["engine/pxfx.js", "engine/kit.js", "fx", "data/meta.json"]) {
18824
+ if (!(0, import_node_fs24.existsSync)(import_node_path27.default.join(root, required))) {
18825
+ throw new PixelKilnError(`The installed ${CODEX_PACKAGE} (${version}) has no ${required}; PixelKiln was written against its 1.0.0 layout`, "capability");
18826
+ }
18827
+ }
18828
+ const sources = [read("engine", "pxfx.js"), read("engine", "kit.js")];
18829
+ const context = import_node_vm.default.createContext({ console });
18830
+ sources.forEach((source, index) => import_node_vm.default.runInContext(source, context, { filename: index ? "engine/kit.js" : "engine/pxfx.js" }));
18831
+ const engine = context.PXFX;
18832
+ if (!engine || typeof engine.View !== "function" || typeof engine.get !== "function") {
18833
+ throw new PixelKilnError(`The installed ${CODEX_PACKAGE} (${version}) does not define PXFX.View and PXFX.get`, "capability");
18834
+ }
18835
+ const loadErrors = [];
18836
+ for (const file of (0, import_node_fs24.readdirSync)(import_node_path27.default.join(root, "fx")).filter((name) => name.endsWith(".js")).sort()) {
18837
+ try {
18838
+ import_node_vm.default.runInContext(read("fx", file), context, { filename: `fx/${file}` });
18839
+ } catch (error) {
18840
+ loadErrors.push(`${file}: ${error instanceof Error ? error.message : String(error)}`);
18841
+ }
18842
+ }
18843
+ const meta = JSON.parse(read("data", "meta.json"));
18844
+ const catalogue = meta.flatMap(
18845
+ (entry) => typeof entry.id === "string" && engine.get(entry.id) ? [{
18846
+ id: entry.id,
18847
+ en: typeof entry.en === "string" ? entry.en : entry.id,
18848
+ descEn: typeof entry.descEn === "string" ? entry.descEn : "",
18849
+ category: typeof entry.category === "string" ? entry.category : "other",
18850
+ schools: Array.isArray(entry.schools) ? entry.schools.filter((school) => typeof school === "string") : []
18851
+ }] : []
18852
+ );
18853
+ if (!catalogue.length) throw new PixelKilnError(`The installed ${CODEX_PACKAGE} (${version}) loaded no effects`, "capability");
18854
+ const engineSha256 = (0, import_node_crypto7.createHash)("sha256").update(sources.join("\n")).digest("hex").slice(0, 12);
18855
+ return { version, engineSha256, engine, catalogue, loadErrors };
18856
+ }
18857
+ function listCodexEffects(lib) {
18858
+ return lib.catalogue.map((entry) => {
18859
+ const def = lib.engine.get(entry.id);
18860
+ return {
18861
+ ...entry,
18862
+ loopSeconds: def.loop,
18863
+ params: Object.fromEntries(
18864
+ Object.entries(def.params ?? {}).map(([key2, param]) => [key2, { label: param.en ?? key2, min: param.min, max: param.max, value: param.value }])
18865
+ )
18866
+ };
18867
+ });
18868
+ }
18869
+ function formatCodexEffects(lib) {
18870
+ const effects = listCodexEffects(lib);
18871
+ const categories = [...new Set(effects.map((effect) => effect.category))];
18872
+ const lines = [`pixel-vfx-codex ${lib.version}: ${effects.length} effects (${CODEX_REPOSITORY}, MIT)`];
18873
+ for (const category of categories) {
18874
+ const inCategory = effects.filter((effect) => effect.category === category);
18875
+ lines.push("", `${category} (${inCategory.length})`);
18876
+ for (const effect of inCategory) lines.push(` ${effect.id.padEnd(28)} ${effect.en}`);
18877
+ }
18878
+ lines.push("", "--json lists every effect's parameters, with their ranges.");
18879
+ return lines.join("\n");
18880
+ }
18881
+ function findDef(lib, id) {
18882
+ const info = listCodexEffects(lib).find((entry) => entry.id === id);
18883
+ if (!info) {
18884
+ const near = lib.catalogue.map((entry) => entry.id).filter((other) => other.includes(id) || id.includes(other));
18885
+ throw new UsageError(
18886
+ `pixel-vfx-codex ${lib.version} has no effect "${id}"` + (near.length ? `; close: ${near.slice(0, 10).join(", ")}` : ""),
18887
+ { hint: "List them with: pixelkiln vfx effects --lib codex" }
18888
+ );
18889
+ }
18890
+ return { def: lib.engine.get(id), info };
18891
+ }
18892
+ function checkCodexRecipe(lib, recipe) {
18893
+ const { info } = findDef(lib, recipe.effect);
18894
+ const { camera, fps, margin, hue, params = {}, tune = {} } = recipe;
18895
+ if (camera !== void 0 && !CODEX_CAMERAS.includes(camera)) {
18896
+ throw new UsageError(`--camera must be ${CODEX_CAMERAS.join(", ")}, got "${camera}"`);
18897
+ }
18898
+ if (fps !== void 0 && (!Number.isInteger(fps) || fps < 1 || fps > 60)) throw new UsageError(`codex fps must be a whole number 1 to 60, got ${fps}`);
18899
+ if (margin !== void 0 && (!Number.isInteger(margin) || margin < 0 || margin > 64)) {
18900
+ throw new UsageError(`codex margin must be a whole number 0 to 64, got ${margin}`);
18901
+ }
18902
+ if (hue !== void 0 && (typeof hue !== "number" || !Number.isFinite(hue) || hue < -360 || hue > 360)) {
18903
+ throw new UsageError(`codex hue is degrees from -360 to 360, got ${JSON.stringify(hue)}`);
18904
+ }
18905
+ for (const [key2, value] of Object.entries(params)) {
18906
+ const param = info.params[key2];
18907
+ if (!param) {
18908
+ const known = Object.keys(info.params);
18909
+ throw new UsageError(`${recipe.effect} has no parameter "${key2}"${known.length ? `; it has ${known.join(", ")}` : " (it takes none)"}`);
18910
+ }
18911
+ if (typeof value !== "number" || !Number.isFinite(value) || value < param.min || value > param.max) {
18912
+ throw new UsageError(`${recipe.effect} ${key2} is a number from ${param.min} to ${param.max}, got ${JSON.stringify(value)}`);
18913
+ }
18914
+ }
18915
+ for (const [key2, value] of Object.entries(tune)) {
18916
+ if (!CODEX_TUNE_KEYS.includes(key2)) throw new UsageError(`unknown tune knob "${key2}"; they are ${CODEX_TUNE_KEYS.join(", ")}`);
18917
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new UsageError(`tune ${key2} is a number, got ${JSON.stringify(value)}`);
18918
+ }
18919
+ return info;
18920
+ }
18921
+ function cropFrames(frames, width, height, pivot, margin) {
18922
+ let x0 = Math.floor(pivot.x), x1 = Math.floor(pivot.x), y0 = Math.floor(pivot.y), y1 = Math.floor(pivot.y);
18923
+ x0 = Math.max(0, Math.min(x0, width - 1));
18924
+ x1 = Math.max(0, Math.min(x1, width - 1));
18925
+ y0 = Math.max(0, Math.min(y0, height - 1));
18926
+ y1 = Math.max(0, Math.min(y1, height - 1));
18927
+ for (const frame of frames) {
18928
+ for (let y = 0; y < height; y++) {
18929
+ for (let x = 0; x < width; x++) {
18930
+ if (frame[(y * width + x) * 4 + 3]) {
18931
+ if (x < x0) x0 = x;
18932
+ if (x > x1) x1 = x;
18933
+ if (y < y0) y0 = y;
18934
+ if (y > y1) y1 = y;
18935
+ }
18936
+ }
18937
+ }
18938
+ }
18939
+ const cropWidth = x1 - x0 + 1 + margin * 2;
18940
+ const cropHeight = y1 - y0 + 1 + margin * 2;
18941
+ const cropped = frames.map((frame) => {
18942
+ const out = Buffer.alloc(cropWidth * cropHeight * 4);
18943
+ for (let y = 0; y < cropHeight; y++) {
18944
+ const sy = y0 - margin + y;
18945
+ if (sy < 0 || sy >= height) continue;
18946
+ for (let x = 0; x < cropWidth; x++) {
18947
+ const sx = x0 - margin + x;
18948
+ if (sx < 0 || sx >= width) continue;
18949
+ frame.copy(out, (y * cropWidth + x) * 4, (sy * width + sx) * 4, (sy * width + sx) * 4 + 4);
18695
18950
  }
18696
18951
  }
18952
+ return out;
18953
+ });
18954
+ return { width: cropWidth, height: cropHeight, frames: cropped, anchor: { x: pivot.x - x0 + margin, y: pivot.y - y0 + margin } };
18955
+ }
18956
+ function planCodex(lib, recipe) {
18957
+ checkCodexRecipe(lib, recipe);
18958
+ const camera = recipe.camera ?? "2d";
18959
+ const fps = recipe.fps ?? lib.engine.MODES[camera]?.fps ?? 12;
18960
+ const seconds = lib.engine.timing(lib.engine.get(recipe.effect), { ...recipe.tune ?? {} }).length;
18961
+ return { camera, fps, frames: Math.max(1, Math.round(seconds * fps)), seconds };
18962
+ }
18963
+ function renderCodex(lib, recipe) {
18964
+ const info = checkCodexRecipe(lib, recipe);
18965
+ const def = lib.engine.get(recipe.effect);
18966
+ const camera = recipe.camera ?? "2d";
18967
+ const [canvasWidth, canvasHeight] = CANVAS[camera];
18968
+ const fps = recipe.fps ?? lib.engine.MODES[camera]?.fps ?? 12;
18969
+ const view = new lib.engine.View(null, canvasWidth, canvasHeight);
18970
+ view.mode = camera;
18971
+ view.night = false;
18972
+ view.hue = recipe.hue ?? 0;
18973
+ view.params = { ...recipe.params ?? {} };
18974
+ view.tune = { ...recipe.tune ?? {} };
18975
+ view.transparent = true;
18976
+ view.noProps = true;
18977
+ view.shakeX = 0;
18978
+ view.shakeY = 0;
18979
+ view.camera(def);
18980
+ view.P(0, 0, 0);
18981
+ const pivot = { x: Math.round(view.px), y: Math.round(view.py) };
18982
+ const timing = lib.engine.timing(def, view.tune);
18983
+ const count = Math.max(1, Math.round(timing.length * fps));
18984
+ const frames = [];
18985
+ for (let index = 0; index < count; index++) {
18986
+ view.renderAt(def, lib.engine.frameTime(index / count * timing.length, camera), timing);
18987
+ frames.push(Buffer.from(view.pix.buffer.slice(0)));
18988
+ }
18989
+ const cropped = cropFrames(frames, canvasWidth, canvasHeight, pivot, recipe.margin ?? 0);
18990
+ return { effect: info, fps, loop: true, ...cropped };
18991
+ }
18992
+ async function readCodexRecipe(file, opts = {}) {
18993
+ const parsed = JSON.parse(await (0, import_promises18.readFile)(file, "utf8"));
18994
+ const record = parsed.tool === CODEX_ID;
18995
+ if (!record && !(opts.bare && parsed.tool === void 0)) return null;
18996
+ const raw = record ? parsed.recipe : parsed;
18997
+ if (!raw || typeof raw !== "object" || typeof raw.effect !== "string" || Array.isArray(raw.layers)) {
18998
+ if (record) throw new Error(`${file} is a codex record with no recipe naming an effect`);
18999
+ return null;
19000
+ }
19001
+ const recipe = { effect: raw.effect };
19002
+ if (raw.camera !== void 0) recipe.camera = raw.camera;
19003
+ for (const key2 of ["fps", "margin", "hue"]) if (raw[key2] !== void 0) recipe[key2] = raw[key2];
19004
+ for (const key2 of ["params", "tune"]) {
19005
+ const value = raw[key2];
19006
+ if (value === void 0) continue;
19007
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${file}: a codex recipe's ${key2} is an object`);
19008
+ recipe[key2] = value;
19009
+ }
19010
+ const library = record ? parsed.library : void 0;
19011
+ return {
19012
+ recipe,
19013
+ ...typeof library?.version === "string" ? { libraryVersion: library.version } : {},
19014
+ ...typeof library?.engineSha256 === "string" ? { engineSha256: library.engineSha256 } : {}
18697
19015
  };
18698
- const sheetSha256 = sha256(sheet.png);
18699
- const facts = {
18700
- name,
19016
+ }
19017
+ async function makeCodexVfx(lib, opts) {
19018
+ const recipe = {
18701
19019
  effect: opts.effect,
18702
- width: render.width,
18703
- height: render.height,
18704
- frames: render.frames.length,
18705
- fps: render.fps,
18706
- loop: render.loop,
18707
- anchor
19020
+ ...opts.camera && opts.camera !== "2d" ? { camera: opts.camera } : {},
19021
+ ...opts.fps !== void 0 ? { fps: opts.fps } : {},
19022
+ ...opts.margin ? { margin: opts.margin } : {},
19023
+ ...opts.hue ? { hue: opts.hue } : {},
19024
+ ...opts.params && Object.keys(opts.params).length ? { params: opts.params } : {},
19025
+ ...opts.tune && Object.keys(opts.tune).length ? { tune: opts.tune } : {}
18708
19026
  };
18709
- const provenance = {
18710
- version: 1,
18711
- provider: "pixelfx",
18712
- tool: PIXELFX_TOOL,
18713
- library: { name: "pixelfx", version: lib.version, repository: PIXELFX_REPOSITORY, license: "MIT" },
18714
- ...facts,
18715
- files: { sheet: import_node_path25.default.basename(paths.sheet), atlas: import_node_path25.default.basename(paths.atlas) },
18716
- sheetSha256,
18717
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
19027
+ checkCodexRecipe(lib, recipe);
19028
+ const paths = assertFreshOutputs(opts.out, opts.force);
19029
+ const render = renderCodex(lib, recipe);
19030
+ const library = { name: CODEX_PACKAGE, version: lib.version, engineSha256: lib.engineSha256 };
19031
+ const written = await writeLocalVfx({
19032
+ paths,
19033
+ name: opts.name ?? render.effect.en,
19034
+ effect: opts.effect,
19035
+ render,
19036
+ atlasKey: CODEX_ID,
19037
+ atlasFacts: { version: lib.version, engineSha256: lib.engineSha256, camera: recipe.camera ?? "2d" },
19038
+ record: { provider: CODEX_ID, tool: CODEX_ID, library: { ...library, repository: CODEX_REPOSITORY, license: "MIT" } },
18718
19039
  recipe
18719
- };
18720
- await (0, import_promises16.mkdir)(import_node_path25.default.dirname(paths.sheet), { recursive: true });
18721
- await (0, import_promises16.writeFile)(paths.sheet, sheet.png);
18722
- await (0, import_promises16.writeFile)(paths.atlas, `${JSON.stringify(atlas, null, 2)}
18723
- `);
18724
- await (0, import_promises16.writeFile)(paths.provenance, `${JSON.stringify(provenance, null, 2)}
18725
- `);
19040
+ });
18726
19041
  return {
18727
- provider: "pixelfx",
18728
- library: { name: "pixelfx", version: lib.version },
18729
- ...facts,
18730
- columns: sheet.columns,
18731
- sheetSha256,
18732
- paths: { sheet: paths.sheet, atlas: paths.atlas, provenance: paths.provenance },
19042
+ provider: CODEX_ID,
19043
+ library,
19044
+ ...written.facts,
19045
+ columns: written.columns,
19046
+ sheetSha256: written.sheetSha256,
19047
+ paths: written.paths,
18733
19048
  recipe
18734
19049
  };
18735
19050
  }
18736
19051
 
18737
19052
  // src/pipeline/quality-regression.ts
18738
- var import_node_path26 = __toESM(require("path"), 1);
18739
- var import_node_fs23 = require("fs");
18740
- var import_promises17 = require("fs/promises");
19053
+ var import_node_path28 = __toESM(require("path"), 1);
19054
+ var import_node_fs25 = require("fs");
19055
+ var import_promises19 = require("fs/promises");
18741
19056
  var import_zod6 = require("zod");
18742
19057
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
18743
19058
  var HEX_RE = /^#[0-9a-f]{6}$/;
18744
19059
  var MAX_REDMEAN_DISTANCE = 765;
18745
19060
  var QualityPathSchema = import_zod6.z.string().min(1).refine(
18746
- (value) => !import_node_path26.default.posix.isAbsolute(value) && !value.includes("\\"),
19061
+ (value) => !import_node_path28.default.posix.isAbsolute(value) && !value.includes("\\"),
18747
19062
  "expected a portable relative path"
18748
19063
  );
18749
19064
  var DEFAULT_QUALITY_TOLERANCES = {
@@ -18890,10 +19205,10 @@ function measureDecodedImageQuality(png, digest2) {
18890
19205
  };
18891
19206
  }
18892
19207
  async function measureImageQuality(file) {
18893
- const absolute = import_node_path26.default.resolve(file);
19208
+ const absolute = import_node_path28.default.resolve(file);
18894
19209
  let bytes;
18895
19210
  try {
18896
- bytes = await (0, import_promises17.readFile)(absolute);
19211
+ bytes = await (0, import_promises19.readFile)(absolute);
18897
19212
  } catch (error) {
18898
19213
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
18899
19214
  }
@@ -18912,11 +19227,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
18912
19227
  }
18913
19228
  const ids = parsed.data.map((entry) => entry.id);
18914
19229
  if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
18915
- const root = import_node_path26.default.dirname(import_node_path26.default.resolve(inputsFilePath));
19230
+ const root = import_node_path28.default.dirname(import_node_path28.default.resolve(inputsFilePath));
18916
19231
  return parsed.data.map((entry) => ({
18917
19232
  id: entry.id,
18918
- file: import_node_path26.default.resolve(root, entry.path),
18919
- ...entry.record ? { record: import_node_path26.default.resolve(root, entry.record) } : {},
19233
+ file: import_node_path28.default.resolve(root, entry.path),
19234
+ ...entry.record ? { record: import_node_path28.default.resolve(root, entry.record) } : {},
18920
19235
  tolerances: QualityToleranceSchema.parse({
18921
19236
  ...DEFAULT_QUALITY_TOLERANCES,
18922
19237
  ...entry.tolerances
@@ -18924,7 +19239,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
18924
19239
  }));
18925
19240
  }
18926
19241
  function portableRelative2(from, to) {
18927
- return import_node_path26.default.relative(from, import_node_path26.default.resolve(to)).split(import_node_path26.default.sep).join("/") || ".";
19242
+ return import_node_path28.default.relative(from, import_node_path28.default.resolve(to)).split(import_node_path28.default.sep).join("/") || ".";
18928
19243
  }
18929
19244
  async function verifyRecordForImage(recordPath, imagePath) {
18930
19245
  const verification = await verifyArtifactBundle(recordPath);
@@ -18939,20 +19254,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
18939
19254
  if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
18940
19255
  throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
18941
19256
  }
18942
- const outputs = record.outputs.map((output) => import_node_path26.default.resolve(import_node_path26.default.dirname(recordPath), output.path));
18943
- if (!outputs.includes(import_node_path26.default.resolve(imagePath))) {
19257
+ const outputs = record.outputs.map((output) => import_node_path28.default.resolve(import_node_path28.default.dirname(recordPath), output.path));
19258
+ if (!outputs.includes(import_node_path28.default.resolve(imagePath))) {
18944
19259
  throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
18945
19260
  }
18946
19261
  }
18947
19262
  async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
18948
19263
  if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
18949
- const absolute = import_node_path26.default.resolve(baselinePath);
19264
+ const absolute = import_node_path28.default.resolve(baselinePath);
18950
19265
  for (const input of inputs) {
18951
- if (import_node_path26.default.resolve(input.file) === absolute || input.record && import_node_path26.default.resolve(input.record) === absolute) {
19266
+ if (import_node_path28.default.resolve(input.file) === absolute || input.record && import_node_path28.default.resolve(input.record) === absolute) {
18952
19267
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
18953
19268
  }
18954
19269
  }
18955
- const root = import_node_path26.default.dirname(absolute);
19270
+ const root = import_node_path28.default.dirname(absolute);
18956
19271
  const cases = [];
18957
19272
  for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
18958
19273
  const expected = await measureImageQuality(input.file);
@@ -18979,8 +19294,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
18979
19294
  cases
18980
19295
  });
18981
19296
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
18982
- if ((0, import_node_fs23.existsSync)(absolute) && !options.force) {
18983
- const current = await (0, import_promises17.readFile)(absolute);
19297
+ if ((0, import_node_fs25.existsSync)(absolute) && !options.force) {
19298
+ const current = await (0, import_promises19.readFile)(absolute);
18984
19299
  if (!current.equals(data)) {
18985
19300
  throw new OverwriteRefusedError(
18986
19301
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -18992,13 +19307,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
18992
19307
  return { baseline, path: absolute, changed: result.changed.length > 0 };
18993
19308
  }
18994
19309
  async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
18995
- const absolute = import_node_path26.default.resolve(baselinePath);
18996
- if (!(0, import_node_fs23.existsSync)(absolute)) {
19310
+ const absolute = import_node_path28.default.resolve(baselinePath);
19311
+ if (!(0, import_node_fs25.existsSync)(absolute)) {
18997
19312
  throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
18998
19313
  }
18999
19314
  let raw;
19000
19315
  try {
19001
- raw = JSON.parse(await (0, import_promises17.readFile)(absolute, "utf8"));
19316
+ raw = JSON.parse(await (0, import_promises19.readFile)(absolute, "utf8"));
19002
19317
  } catch (error) {
19003
19318
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
19004
19319
  }
@@ -19008,12 +19323,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
19008
19323
  if (unknown.length) {
19009
19324
  throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
19010
19325
  }
19011
- const root = import_node_path26.default.dirname(absolute);
19326
+ const root = import_node_path28.default.dirname(absolute);
19012
19327
  const cases = [...raw.cases];
19013
19328
  const report = [];
19014
19329
  for (const id of only) {
19015
19330
  const input = byId.get(id);
19016
- if (import_node_path26.default.resolve(input.file) === absolute || input.record && import_node_path26.default.resolve(input.record) === absolute) {
19331
+ if (import_node_path28.default.resolve(input.file) === absolute || input.record && import_node_path28.default.resolve(input.record) === absolute) {
19017
19332
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
19018
19333
  }
19019
19334
  const expected = await measureImageQuality(input.file);
@@ -19043,16 +19358,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
19043
19358
  }
19044
19359
  const baseline = QualityBaselineSchema.parse({ ...raw, cases });
19045
19360
  const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
19046
- const current = await (0, import_promises17.readFile)(absolute);
19361
+ const current = await (0, import_promises19.readFile)(absolute);
19047
19362
  const changed = !current.equals(data);
19048
19363
  if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
19049
19364
  return { baseline, path: absolute, changed, cases: report };
19050
19365
  }
19051
19366
  async function readQualityBaseline(baselinePath) {
19052
- const absolute = import_node_path26.default.resolve(baselinePath);
19367
+ const absolute = import_node_path28.default.resolve(baselinePath);
19053
19368
  let raw;
19054
19369
  try {
19055
- raw = JSON.parse(await (0, import_promises17.readFile)(absolute, "utf8"));
19370
+ raw = JSON.parse(await (0, import_promises19.readFile)(absolute, "utf8"));
19056
19371
  } catch (error) {
19057
19372
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
19058
19373
  }
@@ -19074,7 +19389,7 @@ async function readQualityBaseline(baselinePath) {
19074
19389
  throw new Error(
19075
19390
  `Invalid quality baseline ${absolute}:
19076
19391
  ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
19077
- Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${import_node_path26.default.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
19392
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${import_node_path28.default.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
19078
19393
  );
19079
19394
  }
19080
19395
  return parsed.data;
@@ -19136,12 +19451,12 @@ function regressionViolations(expected, actual, tolerances) {
19136
19451
  return { violations, warnings };
19137
19452
  }
19138
19453
  async function checkQualityBaseline(baselinePath) {
19139
- const absolute = import_node_path26.default.resolve(baselinePath);
19454
+ const absolute = import_node_path28.default.resolve(baselinePath);
19140
19455
  const baseline = await readQualityBaseline(absolute);
19141
- const root = import_node_path26.default.dirname(absolute);
19456
+ const root = import_node_path28.default.dirname(absolute);
19142
19457
  const cases = [];
19143
19458
  for (const entry of baseline.cases) {
19144
- const file = import_node_path26.default.resolve(root, entry.file);
19459
+ const file = import_node_path28.default.resolve(root, entry.file);
19145
19460
  let actual = null;
19146
19461
  const violations = [];
19147
19462
  const warnings = [];
@@ -19154,7 +19469,7 @@ async function checkQualityBaseline(baselinePath) {
19154
19469
  violations.push(message4(error));
19155
19470
  }
19156
19471
  if (entry.record) {
19157
- const recordPath = import_node_path26.default.resolve(root, entry.record.path);
19472
+ const recordPath = import_node_path28.default.resolve(root, entry.record.path);
19158
19473
  try {
19159
19474
  const recordHash = await sha256File(recordPath);
19160
19475
  if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
@@ -19190,14 +19505,14 @@ async function checkQualityBaseline(baselinePath) {
19190
19505
  }
19191
19506
 
19192
19507
  // src/pipeline/cache-health.ts
19193
- var import_node_fs27 = require("fs");
19194
- var import_promises20 = require("fs/promises");
19195
- var import_node_path30 = __toESM(require("path"), 1);
19508
+ var import_node_fs29 = require("fs");
19509
+ var import_promises22 = require("fs/promises");
19510
+ var import_node_path32 = __toESM(require("path"), 1);
19196
19511
 
19197
19512
  // src/cache.ts
19198
- var import_promises18 = require("fs/promises");
19199
- var import_node_fs24 = require("fs");
19200
- var import_node_path27 = __toESM(require("path"), 1);
19513
+ var import_promises20 = require("fs/promises");
19514
+ var import_node_fs26 = require("fs");
19515
+ var import_node_path29 = __toESM(require("path"), 1);
19201
19516
  var import_zod7 = require("zod");
19202
19517
  var HashCacheSchema = import_zod7.z.object({
19203
19518
  version: import_zod7.z.literal(1),
@@ -19211,10 +19526,10 @@ function isSha256Hash(value) {
19211
19526
  function parseCache(value) {
19212
19527
  return HashCacheSchema.parse(value);
19213
19528
  }
19214
- async function loadCache(path51) {
19215
- if (!(0, import_node_fs24.existsSync)(path51)) return { version: 1, hashes: {} };
19529
+ async function loadCache(path53) {
19530
+ if (!(0, import_node_fs26.existsSync)(path53)) return { version: 1, hashes: {} };
19216
19531
  try {
19217
- const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises18.readFile)(path51, "utf8")));
19532
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises20.readFile)(path53, "utf8")));
19218
19533
  if (!parsed.success) return { version: 1, hashes: {} };
19219
19534
  return {
19220
19535
  version: 1,
@@ -19226,20 +19541,20 @@ async function loadCache(path51) {
19226
19541
  return { version: 1, hashes: {} };
19227
19542
  }
19228
19543
  }
19229
- async function saveCache(path51, cache) {
19544
+ async function saveCache(path53, cache) {
19230
19545
  const sorted = {};
19231
19546
  for (const key2 of Object.keys(cache.hashes).sort()) {
19232
19547
  const hash = cache.hashes[key2];
19233
19548
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
19234
19549
  sorted[key2] = hash;
19235
19550
  }
19236
- await (0, import_promises18.mkdir)(import_node_path27.default.dirname(import_node_path27.default.resolve(path51)), { recursive: true });
19237
- const tmp = `${path51}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19551
+ await (0, import_promises20.mkdir)(import_node_path29.default.dirname(import_node_path29.default.resolve(path53)), { recursive: true });
19552
+ const tmp = `${path53}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19238
19553
  try {
19239
- await (0, import_promises18.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
19240
- await (0, import_promises18.rename)(tmp, path51);
19554
+ await (0, import_promises20.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
19555
+ await (0, import_promises20.rename)(tmp, path53);
19241
19556
  } finally {
19242
- await (0, import_promises18.rm)(tmp, { force: true });
19557
+ await (0, import_promises20.rm)(tmp, { force: true });
19243
19558
  }
19244
19559
  }
19245
19560
  function pruneCache(cache, liveIds, namespace = "") {
@@ -19261,20 +19576,20 @@ function cachePathFor(lockPath) {
19261
19576
  }
19262
19577
 
19263
19578
  // src/pipeline/history.ts
19264
- var import_node_fs26 = require("fs");
19265
- var import_node_path29 = __toESM(require("path"), 1);
19579
+ var import_node_fs28 = require("fs");
19580
+ var import_node_path31 = __toESM(require("path"), 1);
19266
19581
 
19267
19582
  // src/pipeline/fetch.ts
19268
- var import_node_fs25 = require("fs");
19269
- var import_promises19 = require("fs/promises");
19270
- var import_node_path28 = __toESM(require("path"), 1);
19583
+ var import_node_fs27 = require("fs");
19584
+ var import_promises21 = require("fs/promises");
19585
+ var import_node_path30 = __toESM(require("path"), 1);
19271
19586
  async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19272
19587
  const log = opts.onProgress ?? (() => {
19273
19588
  });
19274
19589
  const result = { downloaded: 0, skipped: 0, failed: 0, ...opts.refresh ? { unchanged: 0 } : {} };
19275
19590
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
19276
19591
  normalizeLockOutputPaths(lock, specs);
19277
- const cacheDir = opts.cacheDir === false ? null : import_node_path28.default.resolve(opts.cacheDir ?? import_node_path28.default.join(import_node_path28.default.dirname(lockPath), ".pixelkiln", "cache"));
19592
+ const cacheDir = opts.cacheDir === false ? null : import_node_path30.default.resolve(opts.cacheDir ?? import_node_path30.default.join(import_node_path30.default.dirname(lockPath), ".pixelkiln", "cache"));
19278
19593
  const pending = Object.entries(lock.entries).filter(([key2, e]) => {
19279
19594
  if (e.provider !== provider.id || !specByKey.has(key2)) return false;
19280
19595
  if (specByKey.get(key2)?.mirror) return false;
@@ -19287,15 +19602,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19287
19602
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
19288
19603
  return Boolean(opts.force) || e.outputs.every((output) => {
19289
19604
  const file = resolveOutputPath(output.path, spec.root);
19290
- return (0, import_node_fs25.existsSync)(file) && sha256((0, import_node_fs25.readFileSync)(file)) === output.sha256;
19605
+ return (0, import_node_fs27.existsSync)(file) && sha256((0, import_node_fs27.readFileSync)(file)) === output.sha256;
19291
19606
  });
19292
19607
  }
19293
19608
  if (!opts.repair) return false;
19294
19609
  if (e.outputs.length === 0 || !spec) return true;
19295
19610
  return e.outputs.some((output) => {
19296
19611
  const file = resolveOutputPath(output.path, spec.root);
19297
- if (!(0, import_node_fs25.existsSync)(file)) return true;
19298
- const current = sha256((0, import_node_fs25.readFileSync)(file));
19612
+ if (!(0, import_node_fs27.existsSync)(file)) return true;
19613
+ const current = sha256((0, import_node_fs27.readFileSync)(file));
19299
19614
  if (current === output.sha256) return false;
19300
19615
  return Boolean(opts.force) || (e.supersededOutputs ?? []).some((old) => old.sha256 === current);
19301
19616
  });
@@ -19374,8 +19689,8 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19374
19689
  }
19375
19690
  for (let index = 0; index < parentEntry.outputs.length; index++) {
19376
19691
  const file = currentEntryOutputPath(parentEntry, parentSpec, index);
19377
- if (!(0, import_node_fs25.existsSync)(file)) throw new Error(`cannot clean ${key2}: ${wanted.despeckle.of}'s rotation is missing on disk: ${file}`);
19378
- reference.push(await (0, import_promises19.readFile)(file));
19692
+ if (!(0, import_node_fs27.existsSync)(file)) throw new Error(`cannot clean ${key2}: ${wanted.despeckle.of}'s rotation is missing on disk: ${file}`);
19693
+ reference.push(await (0, import_promises21.readFile)(file));
19379
19694
  }
19380
19695
  }
19381
19696
  for (let index = 0; index < sources.length; index++) {
@@ -19391,21 +19706,21 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19391
19706
  if (!source.url) throw new Error(`no durable source URL to refresh ${source.role ?? "asset"} from`);
19392
19707
  fresh = await provider.download(source.url);
19393
19708
  if (recorded && sha256(fresh) === recordedRaw && !reapply) {
19394
- log(` current ${import_node_path28.default.relative(process.cwd(), target)}`);
19709
+ log(` current ${import_node_path30.default.relative(process.cwd(), target)}`);
19395
19710
  outputs.push({ ...recorded, path: portableOutputPath(target, spec.root) });
19396
19711
  continue;
19397
19712
  }
19398
19713
  }
19399
19714
  let raw = null;
19400
19715
  let final = null;
19401
- if ((0, import_node_fs25.existsSync)(target)) {
19716
+ if ((0, import_node_fs27.existsSync)(target)) {
19402
19717
  const currentHash = await sha256File(target);
19403
19718
  if (recorded && currentHash === recorded.sha256) {
19404
19719
  if (!fresh && !reapply) {
19405
19720
  if (cacheDir) {
19406
19721
  await cacheMedia(
19407
19722
  cacheDir,
19408
- await (0, import_promises19.readFile)(target),
19723
+ await (0, import_promises21.readFile)(target),
19409
19724
  recorded.mediaType ?? MediaType.PNG,
19410
19725
  recorded.sha256
19411
19726
  );
@@ -19414,10 +19729,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19414
19729
  continue;
19415
19730
  }
19416
19731
  if (reapply && !fresh) {
19417
- if (!recorded.raw) raw = await (0, import_promises19.readFile)(target);
19418
- log(` reapply ${import_node_path28.default.relative(process.cwd(), target)}`);
19732
+ if (!recorded.raw) raw = await (0, import_promises21.readFile)(target);
19733
+ log(` reapply ${import_node_path30.default.relative(process.cwd(), target)}`);
19419
19734
  } else {
19420
- log(` changed ${import_node_path28.default.relative(process.cwd(), target)} (upstream)`);
19735
+ log(` changed ${import_node_path30.default.relative(process.cwd(), target)} (upstream)`);
19421
19736
  }
19422
19737
  } else {
19423
19738
  const superseded = (entry.supersededOutputs ?? []).find(
@@ -19438,14 +19753,14 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19438
19753
  }
19439
19754
  if (outgoing && cacheDir) {
19440
19755
  try {
19441
- const oldBytes = await (0, import_promises19.readFile)(target);
19756
+ const oldBytes = await (0, import_promises21.readFile)(target);
19442
19757
  const oldMediaType = detectMediaType(oldBytes);
19443
19758
  if (oldMediaType) await cacheMedia(cacheDir, oldBytes, oldMediaType, currentHash);
19444
19759
  } catch {
19445
19760
  }
19446
19761
  }
19447
19762
  log(
19448
- ` replace ${import_node_path28.default.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
19763
+ ` replace ${import_node_path30.default.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
19449
19764
  );
19450
19765
  }
19451
19766
  }
@@ -19454,7 +19769,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19454
19769
  } else if (!raw && recorded && cacheDir) {
19455
19770
  if (!reapply) final = await readCachedMedia(cacheDir, recorded.sha256, expectedMediaType);
19456
19771
  if (!final && recordedRaw) raw = await readCachedMedia(cacheDir, recordedRaw, expectedMediaType);
19457
- if (final || raw) log(` cached ${import_node_path28.default.relative(process.cwd(), target)}`);
19772
+ if (final || raw) log(` cached ${import_node_path30.default.relative(process.cwd(), target)}`);
19458
19773
  }
19459
19774
  if (!final && !raw) {
19460
19775
  if (!source.url) {
@@ -19480,14 +19795,14 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19480
19795
  const processed = applyPostprocess(raw, mediaType, wanted, reference, source.role);
19481
19796
  buf = processed.bytes;
19482
19797
  if (processed.changed) rawHash = sha256(raw);
19483
- if (processed.moved?.clipped) log(` moved ${import_node_path28.default.relative(process.cwd(), target)}: ${processed.moved.clipped} pixels fell off the canvas; raise layer.padding to keep them`);
19484
- if (processed.removed) log(` cleaned ${import_node_path28.default.relative(process.cwd(), target)} (${processed.removed} ghost pixels)`);
19485
- if (processed.snapped) log(` snapped ${import_node_path28.default.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
19798
+ if (processed.moved?.clipped) log(` moved ${import_node_path30.default.relative(process.cwd(), target)}: ${processed.moved.clipped} pixels fell off the canvas; raise layer.padding to keep them`);
19799
+ if (processed.removed) log(` cleaned ${import_node_path30.default.relative(process.cwd(), target)} (${processed.removed} ghost pixels)`);
19800
+ if (processed.snapped) log(` snapped ${import_node_path30.default.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
19486
19801
  }
19487
19802
  if (cacheDir) await cacheMedia(cacheDir, buf, mediaType);
19488
- await (0, import_promises19.mkdir)(import_node_path28.default.dirname(target), { recursive: true });
19803
+ await (0, import_promises21.mkdir)(import_node_path30.default.dirname(target), { recursive: true });
19489
19804
  const tmp = `${target}.pixelkiln.tmp`;
19490
- await (0, import_promises19.writeFile)(tmp, buf);
19805
+ await (0, import_promises21.writeFile)(tmp, buf);
19491
19806
  outputs.push({
19492
19807
  path: portableOutputPath(target, spec.root),
19493
19808
  sha256: sha256(buf),
@@ -19497,9 +19812,9 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19497
19812
  });
19498
19813
  upsert(lock, key2, { outputs: mergeOutputs(entry.outputs, outputs) });
19499
19814
  await saveLock(lockPath, lock);
19500
- await (0, import_promises19.rename)(tmp, target);
19815
+ await (0, import_promises21.rename)(tmp, target);
19501
19816
  wrote = true;
19502
- log(` wrote ${import_node_path28.default.relative(process.cwd(), target)}`);
19817
+ log(` wrote ${import_node_path30.default.relative(process.cwd(), target)}`);
19503
19818
  }
19504
19819
  if (opts.refresh && !wrote) {
19505
19820
  if (rotated) {
@@ -19543,10 +19858,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19543
19858
  return result;
19544
19859
  }
19545
19860
  async function readCachedMedia(cacheDir, hash, mediaType) {
19546
- const file = import_node_path28.default.join(cacheDir, cacheFileName(hash, mediaType));
19547
- if (!(0, import_node_fs25.existsSync)(file)) return null;
19861
+ const file = import_node_path30.default.join(cacheDir, cacheFileName(hash, mediaType));
19862
+ if (!(0, import_node_fs27.existsSync)(file)) return null;
19548
19863
  try {
19549
- const buf = await (0, import_promises19.readFile)(file);
19864
+ const buf = await (0, import_promises21.readFile)(file);
19550
19865
  if (sha256(buf) !== hash) return null;
19551
19866
  validateMedia(buf, mediaType);
19552
19867
  return buf;
@@ -19557,17 +19872,17 @@ async function readCachedMedia(cacheDir, hash, mediaType) {
19557
19872
  async function cacheMedia(cacheDir, buf, mediaType, knownHash) {
19558
19873
  const hash = knownHash ?? sha256(buf);
19559
19874
  validateMedia(buf, mediaType);
19560
- const file = import_node_path28.default.join(cacheDir, cacheFileName(hash, mediaType));
19875
+ const file = import_node_path30.default.join(cacheDir, cacheFileName(hash, mediaType));
19561
19876
  if (await readCachedMedia(cacheDir, hash, mediaType)) return;
19562
- await (0, import_promises19.mkdir)(cacheDir, { recursive: true });
19877
+ await (0, import_promises21.mkdir)(cacheDir, { recursive: true });
19563
19878
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19564
- await (0, import_promises19.writeFile)(tmp, buf);
19879
+ await (0, import_promises21.writeFile)(tmp, buf);
19565
19880
  try {
19566
- await (0, import_promises19.rename)(tmp, file);
19881
+ await (0, import_promises21.rename)(tmp, file);
19567
19882
  } catch (err) {
19568
- if (!(0, import_node_fs25.existsSync)(file)) throw err;
19883
+ if (!(0, import_node_fs27.existsSync)(file)) throw err;
19569
19884
  } finally {
19570
- await (0, import_promises19.rm)(tmp, { force: true });
19885
+ await (0, import_promises21.rm)(tmp, { force: true });
19571
19886
  }
19572
19887
  }
19573
19888
  function mergeOutputs(previous, current) {
@@ -19689,10 +20004,10 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
19689
20004
  }
19690
20005
  for (let i = 0; i < entry.outputs.length; i++) {
19691
20006
  const file = currentEntryOutputPath(entry, spec, i);
19692
- if (!(0, import_node_fs26.existsSync)(file)) continue;
20007
+ if (!(0, import_node_fs28.existsSync)(file)) continue;
19693
20008
  if (await sha256File(file) !== entry.outputs[i].sha256 && !opts.force) {
19694
20009
  throw new OverwriteRefusedError(
19695
- `${import_node_path29.default.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
20010
+ `${import_node_path31.default.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
19696
20011
  [file]
19697
20012
  );
19698
20013
  }
@@ -19756,11 +20071,11 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
19756
20071
 
19757
20072
  // src/pipeline/cache-health.ts
19758
20073
  async function inspectCaches(lock, lockPath, options = {}) {
19759
- if (options.prune && !(0, import_node_fs27.existsSync)(lockPath)) {
19760
- throw new Error(`Refusing to prune without an existing lockfile at ${import_node_path30.default.resolve(lockPath)}`);
20074
+ if (options.prune && !(0, import_node_fs29.existsSync)(lockPath)) {
20075
+ throw new Error(`Refusing to prune without an existing lockfile at ${import_node_path32.default.resolve(lockPath)}`);
19761
20076
  }
19762
- const contentDir = import_node_path30.default.resolve(import_node_path30.default.dirname(lockPath), ".pixelkiln", "cache");
19763
- const remotePath = import_node_path30.default.resolve(cachePathFor(lockPath));
20077
+ const contentDir = import_node_path32.default.resolve(import_node_path32.default.dirname(lockPath), ".pixelkiln", "cache");
20078
+ const remotePath = import_node_path32.default.resolve(cachePathFor(lockPath));
19764
20079
  const referenced = referencedHashes(lock);
19765
20080
  let content = await inspectContentCache(contentDir, referenced);
19766
20081
  let remoteHashes = await inspectRemoteHashCache(remotePath);
@@ -19772,7 +20087,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
19772
20087
  ]);
19773
20088
  for (const name of names) {
19774
20089
  try {
19775
- await (0, import_promises20.rm)(import_node_path30.default.join(contentDir, name), { force: true });
20090
+ await (0, import_promises22.rm)(import_node_path32.default.join(contentDir, name), { force: true });
19776
20091
  removed.contentFiles++;
19777
20092
  } catch {
19778
20093
  }
@@ -19781,7 +20096,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
19781
20096
  await saveCache(remotePath, { version: 1, hashes: {} });
19782
20097
  removed.resetRemoteHashCache = true;
19783
20098
  } else if (remoteHashes.invalidIds.length) {
19784
- const cache = parseCache(JSON.parse(await (0, import_promises20.readFile)(remotePath, "utf8")));
20099
+ const cache = parseCache(JSON.parse(await (0, import_promises22.readFile)(remotePath, "utf8")));
19785
20100
  for (const id of remoteHashes.invalidIds) delete cache.hashes[id];
19786
20101
  removed.remoteHashEntries = remoteHashes.invalidIds.length;
19787
20102
  await saveCache(remotePath, cache);
@@ -19799,7 +20114,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
19799
20114
  async function inspectContentCache(contentDir, referenced) {
19800
20115
  const report = {
19801
20116
  path: contentDir,
19802
- exists: (0, import_node_fs27.existsSync)(contentDir),
20117
+ exists: (0, import_node_fs29.existsSync)(contentDir),
19803
20118
  files: 0,
19804
20119
  bytes: 0,
19805
20120
  valid: 0,
@@ -19813,19 +20128,19 @@ async function inspectContentCache(contentDir, referenced) {
19813
20128
  return report;
19814
20129
  }
19815
20130
  const present = /* @__PURE__ */ new Set();
19816
- const entries = await (0, import_promises20.readdir)(contentDir, { withFileTypes: true });
20131
+ const entries = await (0, import_promises22.readdir)(contentDir, { withFileTypes: true });
19817
20132
  for (const entry of entries) {
19818
20133
  if (!entry.isFile()) {
19819
20134
  report.invalid.push({ name: entry.name, reason: "not a regular file" });
19820
20135
  continue;
19821
20136
  }
19822
20137
  report.files++;
19823
- const file = import_node_path30.default.join(contentDir, entry.name);
20138
+ const file = import_node_path32.default.join(contentDir, entry.name);
19824
20139
  const mediaType = mediaTypeFromExtension(entry.name);
19825
20140
  const expected = mediaType ? entry.name.slice(0, -4) : "";
19826
20141
  let bytes;
19827
20142
  try {
19828
- bytes = await (0, import_promises20.readFile)(file);
20143
+ bytes = await (0, import_promises22.readFile)(file);
19829
20144
  report.bytes += bytes.length;
19830
20145
  } catch (err) {
19831
20146
  report.invalid.push({
@@ -19863,7 +20178,7 @@ async function inspectContentCache(contentDir, referenced) {
19863
20178
  async function inspectRemoteHashCache(remotePath) {
19864
20179
  const report = {
19865
20180
  path: remotePath,
19866
- exists: (0, import_node_fs27.existsSync)(remotePath),
20181
+ exists: (0, import_node_fs29.existsSync)(remotePath),
19867
20182
  entries: 0,
19868
20183
  valid: 0,
19869
20184
  invalidIds: [],
@@ -19872,7 +20187,7 @@ async function inspectRemoteHashCache(remotePath) {
19872
20187
  if (!report.exists) return report;
19873
20188
  let cache;
19874
20189
  try {
19875
- cache = parseCache(JSON.parse(await (0, import_promises20.readFile)(remotePath, "utf8")));
20190
+ cache = parseCache(JSON.parse(await (0, import_promises22.readFile)(remotePath, "utf8")));
19876
20191
  } catch (err) {
19877
20192
  report.error = err instanceof Error ? err.message : String(err);
19878
20193
  return report;
@@ -19887,20 +20202,20 @@ async function inspectRemoteHashCache(remotePath) {
19887
20202
  }
19888
20203
 
19889
20204
  // src/pipeline/pack.ts
19890
- var import_node_fs28 = require("fs");
19891
- var import_node_path31 = __toESM(require("path"), 1);
20205
+ var import_node_fs30 = require("fs");
20206
+ var import_node_path33 = __toESM(require("path"), 1);
19892
20207
  var DEFAULT_FRAME_SET_FPS = 12;
19893
20208
  function resolvePackInputs(raw, inputsFilePath) {
19894
20209
  if (!Array.isArray(raw) || !raw.length) {
19895
20210
  throw new Error("--inputs must be a non-empty JSON array of { id, path }");
19896
20211
  }
19897
- const baseDir = import_node_path31.default.dirname(import_node_path31.default.resolve(inputsFilePath));
20212
+ const baseDir = import_node_path33.default.dirname(import_node_path33.default.resolve(inputsFilePath));
19898
20213
  return raw.map((entry, i) => {
19899
20214
  const e = entry;
19900
20215
  if (typeof e.id !== "string" || typeof e.path !== "string") {
19901
20216
  throw new Error(`--inputs[${i}] needs string "id" and "path"`);
19902
20217
  }
19903
- return { id: e.id, path: import_node_path31.default.resolve(baseDir, e.path) };
20218
+ return { id: e.id, path: import_node_path33.default.resolve(baseDir, e.path) };
19904
20219
  });
19905
20220
  }
19906
20221
  function packSprites(inputs, options = {}) {
@@ -19921,7 +20236,7 @@ function packSprites(inputs, options = {}) {
19921
20236
  for (const input of ordered) {
19922
20237
  let sourceHash = null;
19923
20238
  try {
19924
- const bytes = (0, import_node_fs28.readFileSync)(input.path);
20239
+ const bytes = (0, import_node_fs30.readFileSync)(input.path);
19925
20240
  sourceHash = sha256(bytes);
19926
20241
  const png = decodePng(bytes);
19927
20242
  sprites.push({ id: input.id, width: png.width, height: png.height, pixels: png.pixels });
@@ -19984,7 +20299,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
19984
20299
  }
19985
20300
  const inputs2 = Object.entries(options.sourceOverrides).map(([id, source]) => ({
19986
20301
  id,
19987
- path: import_node_path31.default.resolve(source)
20302
+ path: import_node_path33.default.resolve(source)
19988
20303
  }));
19989
20304
  if (!inputs2.length) throw new Error(`No approved quality outputs for style "${styleId}".`);
19990
20305
  const packed2 = packSprites(inputs2, options);
@@ -20016,7 +20331,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
20016
20331
  let outputs = resolveEntryOutputs(entry, id, manifestDir);
20017
20332
  const source = sources[id];
20018
20333
  if (source && outputs.length <= 1) {
20019
- inputs.push({ id, path: import_node_path31.default.resolve(manifestDir, source) });
20334
+ inputs.push({ id, path: import_node_path33.default.resolve(manifestDir, source) });
20020
20335
  continue;
20021
20336
  }
20022
20337
  if (source && sourceIsStem(source, entry, manifestDir)) {
@@ -20053,7 +20368,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
20053
20368
  }
20054
20369
  }
20055
20370
  for (const [id, source] of Object.entries(sources)) {
20056
- if (!locked.has(id)) inputs.push({ id, path: import_node_path31.default.resolve(manifestDir, source) });
20371
+ if (!locked.has(id)) inputs.push({ id, path: import_node_path33.default.resolve(manifestDir, source) });
20057
20372
  }
20058
20373
  if (!inputs.length) {
20059
20374
  throw new Error(`No readable sprites for style "${styleId}"; ${noOutput.length} skipped.`);
@@ -20117,7 +20432,7 @@ function mountSprites(placements, options) {
20117
20432
  for (const p of placements) {
20118
20433
  let sourceHash = null;
20119
20434
  try {
20120
- const bytes = (0, import_node_fs28.readFileSync)(p.path);
20435
+ const bytes = (0, import_node_fs30.readFileSync)(p.path);
20121
20436
  sourceHash = sha256(bytes);
20122
20437
  const png = decodePng(bytes);
20123
20438
  if (png.width > cellWidth || png.height > cellHeight) {
@@ -20188,7 +20503,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
20188
20503
  const source = sources[id];
20189
20504
  const entry = lock.entries[`${styleId}/${id}`];
20190
20505
  if (source && !(entry && sourceIsStem(source, entry, manifestDir))) {
20191
- placements.push({ id, path: import_node_path31.default.resolve(manifestDir, source), cell });
20506
+ placements.push({ id, path: import_node_path33.default.resolve(manifestDir, source), cell });
20192
20507
  continue;
20193
20508
  }
20194
20509
  if (source && entry) {
@@ -20221,7 +20536,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
20221
20536
  `Nothing to mount for style "${styleId}": ${ids.length} asset(s) declare a cell, but none has generated output or a \`source\`. Run \`pixelkiln gen --style ${styleId}\`, or point each at a file.${detail}`
20222
20537
  );
20223
20538
  }
20224
- const basePng = mount.base ? (0, import_node_fs28.readFileSync)(import_node_path31.default.resolve(manifestDir, mount.base)) : void 0;
20539
+ const basePng = mount.base ? (0, import_node_fs30.readFileSync)(import_node_path33.default.resolve(manifestDir, mount.base)) : void 0;
20225
20540
  const mounted = mountSprites(placements, {
20226
20541
  cellWidth: mount.cellWidth,
20227
20542
  cellHeight: mount.cellHeight,
@@ -20231,7 +20546,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
20231
20546
  ...mounted,
20232
20547
  sources: mount.base ? [{
20233
20548
  id: "$base",
20234
- path: import_node_path31.default.resolve(manifestDir, mount.base),
20549
+ path: import_node_path33.default.resolve(manifestDir, mount.base),
20235
20550
  sha256: sha256(basePng),
20236
20551
  included: true
20237
20552
  }, ...mounted.sources] : mounted.sources,
@@ -21091,34 +21406,34 @@ async function poll(provider, lock, lockPath, opts = {}) {
21091
21406
  }
21092
21407
 
21093
21408
  // src/pipeline/doctor.ts
21094
- var import_node_fs30 = require("fs");
21095
- var import_promises21 = require("fs/promises");
21096
- var import_node_path33 = __toESM(require("path"), 1);
21409
+ var import_node_fs32 = require("fs");
21410
+ var import_promises23 = require("fs/promises");
21411
+ var import_node_path35 = __toESM(require("path"), 1);
21097
21412
 
21098
21413
  // src/pipeline/install-check.ts
21099
- var import_node_fs29 = require("fs");
21100
- var import_node_path32 = __toESM(require("path"), 1);
21414
+ var import_node_fs31 = require("fs");
21415
+ var import_node_path34 = __toESM(require("path"), 1);
21101
21416
  function readJson(file) {
21102
21417
  try {
21103
- return JSON.parse((0, import_node_fs29.readFileSync)(file, "utf8"));
21418
+ return JSON.parse((0, import_node_fs31.readFileSync)(file, "utf8"));
21104
21419
  } catch {
21105
21420
  return null;
21106
21421
  }
21107
21422
  }
21108
21423
  function readInstallFacts(manifestDir, running) {
21109
- let dir = import_node_path32.default.resolve(manifestDir);
21424
+ let dir = import_node_path34.default.resolve(manifestDir);
21110
21425
  for (let depth = 0; depth < 4; depth++) {
21111
- const pkg = readJson(import_node_path32.default.join(dir, "package.json"));
21426
+ const pkg = readJson(import_node_path34.default.join(dir, "package.json"));
21112
21427
  if (pkg) {
21113
21428
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
21114
21429
  if (pinned) {
21115
- const installedPkg = readJson(import_node_path32.default.join(dir, "node_modules", "pixelkiln", "package.json"));
21430
+ const installedPkg = readJson(import_node_path34.default.join(dir, "node_modules", "pixelkiln", "package.json"));
21116
21431
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
21117
21432
  return { pinned, installed, running };
21118
21433
  }
21119
21434
  }
21120
- const parent = import_node_path32.default.dirname(dir);
21121
- if (parent === dir || !(0, import_node_fs29.existsSync)(parent)) break;
21435
+ const parent = import_node_path34.default.dirname(dir);
21436
+ if (parent === dir || !(0, import_node_fs31.existsSync)(parent)) break;
21122
21437
  dir = parent;
21123
21438
  }
21124
21439
  return null;
@@ -21181,18 +21496,18 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21181
21496
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
21182
21497
  );
21183
21498
  }
21184
- const facts = readInstallFacts(import_node_path33.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
21499
+ const facts = readInstallFacts(import_node_path35.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
21185
21500
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
21186
21501
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
21187
21502
  const dirs = [...new Set(specs.flatMap((spec) => [
21188
- import_node_path33.default.dirname(spec.outFile),
21189
- ...spec.quality ? [import_node_path33.default.dirname(spec.quality.outFile)] : []
21503
+ import_node_path35.default.dirname(spec.outFile),
21504
+ ...spec.quality ? [import_node_path35.default.dirname(spec.quality.outFile)] : []
21190
21505
  ]))];
21191
21506
  const unwritable = [];
21192
21507
  for (const dir of dirs) {
21193
21508
  const ancestor = await nearestExistingDirectory(dir);
21194
21509
  try {
21195
- await (0, import_promises21.access)(ancestor, import_node_fs30.constants.W_OK);
21510
+ await (0, import_promises23.access)(ancestor, import_node_fs32.constants.W_OK);
21196
21511
  } catch {
21197
21512
  unwritable.push(dir);
21198
21513
  }
@@ -21209,7 +21524,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21209
21524
  for (let index = 0; index < entry.outputs.length; index++) {
21210
21525
  const output = entry.outputs[index];
21211
21526
  const spec = specByKey.get(key2);
21212
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path33.default.dirname(lockPath));
21527
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path35.default.dirname(lockPath));
21213
21528
  const owner = outputOwners.get(absolute);
21214
21529
  if (owner && owner !== key2) duplicateOutputs.push(`${output.path} (${owner}, ${key2})`);
21215
21530
  outputOwners.set(absolute, key2);
@@ -21224,7 +21539,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21224
21539
  } else {
21225
21540
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
21226
21541
  }
21227
- const cacheDir = import_node_path33.default.join(import_node_path33.default.dirname(lockPath), ".pixelkiln", "cache");
21542
+ const cacheDir = import_node_path35.default.join(import_node_path35.default.dirname(lockPath), ".pixelkiln", "cache");
21228
21543
  const stranded = [];
21229
21544
  const invalidState = [];
21230
21545
  const staleMapUrls = [];
@@ -21240,11 +21555,11 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
21240
21555
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
21241
21556
  let hasCache = false;
21242
21557
  for (const output of entry.outputs) {
21243
- const cached2 = import_node_path33.default.join(
21558
+ const cached2 = import_node_path35.default.join(
21244
21559
  cacheDir,
21245
21560
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
21246
21561
  );
21247
- if ((0, import_node_fs30.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
21562
+ if ((0, import_node_fs32.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
21248
21563
  hasCache = true;
21249
21564
  break;
21250
21565
  }
@@ -21337,19 +21652,19 @@ async function nearestExistingDirectory(start) {
21337
21652
  let current = start;
21338
21653
  for (; ; ) {
21339
21654
  try {
21340
- if ((await (0, import_promises21.stat)(current)).isDirectory()) return current;
21655
+ if ((await (0, import_promises23.stat)(current)).isDirectory()) return current;
21341
21656
  } catch {
21342
21657
  }
21343
- const parent = import_node_path33.default.dirname(current);
21658
+ const parent = import_node_path35.default.dirname(current);
21344
21659
  if (parent === current) return current;
21345
21660
  current = parent;
21346
21661
  }
21347
21662
  }
21348
21663
 
21349
21664
  // src/pipeline/adopt.ts
21350
- var import_node_fs31 = require("fs");
21351
- var import_promises22 = require("fs/promises");
21352
- var import_node_path34 = __toESM(require("path"), 1);
21665
+ var import_node_fs33 = require("fs");
21666
+ var import_promises24 = require("fs/promises");
21667
+ var import_node_path36 = __toESM(require("path"), 1);
21353
21668
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
21354
21669
  const log = opts.onProgress ?? (() => {
21355
21670
  });
@@ -21360,11 +21675,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
21360
21675
  const localByHash = /* @__PURE__ */ new Map();
21361
21676
  const unmatchedLocal = [];
21362
21677
  for (const spec of specs) {
21363
- if (!(0, import_node_fs31.existsSync)(spec.outFile)) {
21678
+ if (!(0, import_node_fs33.existsSync)(spec.outFile)) {
21364
21679
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
21365
21680
  continue;
21366
21681
  }
21367
- const bytes = await (0, import_promises22.readFile)(spec.outFile);
21682
+ const bytes = await (0, import_promises24.readFile)(spec.outFile);
21368
21683
  try {
21369
21684
  decodePng(bytes);
21370
21685
  } catch (err) {
@@ -21482,9 +21797,9 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
21482
21797
  }
21483
21798
 
21484
21799
  // src/pipeline/import.ts
21485
- var import_node_fs32 = require("fs");
21486
- var import_promises23 = require("fs/promises");
21487
- var import_node_path35 = __toESM(require("path"), 1);
21800
+ var import_node_fs34 = require("fs");
21801
+ var import_promises25 = require("fs/promises");
21802
+ var import_node_path37 = __toESM(require("path"), 1);
21488
21803
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
21489
21804
  const png = decodePng(bytes);
21490
21805
  const at2 = now.toISOString();
@@ -21536,13 +21851,13 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
21536
21851
  if (opts.objectId && specs.length !== 1) {
21537
21852
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
21538
21853
  }
21539
- const cacheDir = opts.cacheDir === false ? null : import_node_path35.default.resolve(opts.cacheDir ?? import_node_path35.default.join(import_node_path35.default.dirname(lockPath), ".pixelkiln", "cache"));
21854
+ const cacheDir = opts.cacheDir === false ? null : import_node_path37.default.resolve(opts.cacheDir ?? import_node_path37.default.join(import_node_path37.default.dirname(lockPath), ".pixelkiln", "cache"));
21540
21855
  let rawSha256;
21541
21856
  let rawBytes;
21542
21857
  if (opts.raw) {
21543
21858
  if (specs.length !== 1) throw new Error(`--raw names one original; ${specs.length} assets are selected. Narrow with --only and --style.`);
21544
21859
  try {
21545
- rawBytes = await (0, import_promises23.readFile)(opts.raw);
21860
+ rawBytes = await (0, import_promises25.readFile)(opts.raw);
21546
21861
  decodePng(rawBytes);
21547
21862
  } catch (error) {
21548
21863
  throw new Error(`--raw ${opts.raw} is not a readable PNG: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
@@ -21558,7 +21873,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
21558
21873
  skipped.push({ key: key2, reason });
21559
21874
  continue;
21560
21875
  }
21561
- if (!(0, import_node_fs32.existsSync)(spec.outFile)) {
21876
+ if (!(0, import_node_fs34.existsSync)(spec.outFile)) {
21562
21877
  skipped.push({ key: key2, reason: `no file at ${spec.outFile}` });
21563
21878
  continue;
21564
21879
  }
@@ -21569,7 +21884,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
21569
21884
  let patch;
21570
21885
  let bytes;
21571
21886
  try {
21572
- bytes = await (0, import_promises23.readFile)(spec.outFile);
21887
+ bytes = await (0, import_promises25.readFile)(spec.outFile);
21573
21888
  patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
21574
21889
  } catch (error) {
21575
21890
  skipped.push({ key: key2, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
@@ -21601,7 +21916,7 @@ async function reportSpecHashes(specs, lock) {
21601
21916
  for (const spec of specs) {
21602
21917
  const key2 = lockKey(spec.styleId, spec.assetId);
21603
21918
  let bytes = null;
21604
- if ((0, import_node_fs32.existsSync)(spec.outFile)) bytes = await (0, import_promises23.readFile)(spec.outFile);
21919
+ if ((0, import_node_fs34.existsSync)(spec.outFile)) bytes = await (0, import_promises25.readFile)(spec.outFile);
21605
21920
  let wouldImport = null;
21606
21921
  if (bytes && !unimportable(spec)) {
21607
21922
  try {
@@ -21630,13 +21945,13 @@ async function reportSpecHashes(specs, lock) {
21630
21945
  }
21631
21946
 
21632
21947
  // src/pick/server.ts
21633
- var import_node_fs34 = require("fs");
21634
- var import_promises26 = require("fs/promises");
21948
+ var import_node_fs36 = require("fs");
21949
+ var import_promises28 = require("fs/promises");
21635
21950
 
21636
21951
  // src/pipeline/init.ts
21637
- var import_promises24 = require("fs/promises");
21638
- var import_node_fs33 = require("fs");
21639
- var import_node_path36 = __toESM(require("path"), 1);
21952
+ var import_promises26 = require("fs/promises");
21953
+ var import_node_fs35 = require("fs");
21954
+ var import_node_path38 = __toESM(require("path"), 1);
21640
21955
  function pngSize(buf) {
21641
21956
  if (buf.length < 24) return null;
21642
21957
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -21649,8 +21964,8 @@ function slugify(value) {
21649
21964
  }
21650
21965
  async function walk(dir, exclude) {
21651
21966
  const out = [];
21652
- for (const entry of await (0, import_promises24.readdir)(dir, { withFileTypes: true })) {
21653
- const full = import_node_path36.default.join(dir, entry.name);
21967
+ for (const entry of await (0, import_promises26.readdir)(dir, { withFileTypes: true })) {
21968
+ const full = import_node_path38.default.join(dir, entry.name);
21654
21969
  if (exclude.some((x) => full.includes(x))) continue;
21655
21970
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
21656
21971
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -21664,14 +21979,14 @@ async function scanAssets(root, opts = {}) {
21664
21979
  const skipped = [];
21665
21980
  const seen = /* @__PURE__ */ new Map();
21666
21981
  for (const file of files.sort()) {
21667
- const size = pngSize(await (0, import_promises24.readFile)(file));
21982
+ const size = pngSize(await (0, import_promises26.readFile)(file));
21668
21983
  if (!size) {
21669
21984
  skipped.push(`${file} (not a readable PNG)`);
21670
21985
  continue;
21671
21986
  }
21672
- const rel = import_node_path36.default.relative(root, file);
21673
- const category = import_node_path36.default.dirname(rel) === "." ? "" : import_node_path36.default.dirname(rel);
21674
- let id = slugify(import_node_path36.default.basename(rel));
21987
+ const rel = import_node_path38.default.relative(root, file);
21988
+ const category = import_node_path38.default.dirname(rel) === "." ? "" : import_node_path38.default.dirname(rel);
21989
+ let id = slugify(import_node_path38.default.basename(rel));
21675
21990
  if (seen.has(id)) {
21676
21991
  const n = seen.get(id) + 1;
21677
21992
  seen.set(id, n);
@@ -22145,7 +22460,7 @@ document.getElementById('submit').onclick = async () => {
22145
22460
 
22146
22461
  // src/pick/review-server.ts
22147
22462
  var import_node_http = require("http");
22148
- var import_promises25 = require("fs/promises");
22463
+ var import_promises27 = require("fs/promises");
22149
22464
  function serveReviewPage(opts) {
22150
22465
  const log = opts.onProgress ?? (() => {
22151
22466
  });
@@ -22154,7 +22469,7 @@ function serveReviewPage(opts) {
22154
22469
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
22155
22470
  try {
22156
22471
  const asset = opts.assets.get(req.url);
22157
- const bytes = await (0, import_promises25.readFile)(asset.path);
22472
+ const bytes = await (0, import_promises27.readFile)(asset.path);
22158
22473
  res.writeHead(200, {
22159
22474
  "Content-Type": asset.contentType,
22160
22475
  "Cache-Control": "no-store",
@@ -22230,13 +22545,13 @@ async function currentArt(entry, spec) {
22230
22545
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
22231
22546
  if (!previous) return null;
22232
22547
  const file = resolveOutputPath(previous.path, spec.root);
22233
- if (!(0, import_node_fs34.existsSync)(file)) return null;
22548
+ if (!(0, import_node_fs36.existsSync)(file)) return null;
22234
22549
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
22235
22550
  if (!contentType) return null;
22236
22551
  let width = entry.width;
22237
22552
  let height = entry.height;
22238
22553
  if (contentType === "image/png") {
22239
- const size = pngSize(await (0, import_promises26.readFile)(file));
22554
+ const size = pngSize(await (0, import_promises28.readFile)(file));
22240
22555
  if (size) ({ width, height } = size);
22241
22556
  }
22242
22557
  return { path: file, contentType, width, height };
@@ -22244,7 +22559,7 @@ async function currentArt(entry, spec) {
22244
22559
  async function cachedFrame(url) {
22245
22560
  if (!url.startsWith("file://")) return null;
22246
22561
  const file = url.slice("file://".length);
22247
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises26.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
22562
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises28.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
22248
22563
  return { path: file, contentType };
22249
22564
  }
22250
22565
  async function prepareReview(provider, lock, opts = {}) {
@@ -22276,7 +22591,7 @@ async function prepareReview(provider, lock, opts = {}) {
22276
22591
  frameSizes.push(null);
22277
22592
  continue;
22278
22593
  }
22279
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises26.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
22594
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises28.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
22280
22595
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
22281
22596
  frameAssets.push([route, cached2]);
22282
22597
  frameUrls.push(route);
@@ -22429,15 +22744,15 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
22429
22744
  }
22430
22745
 
22431
22746
  // src/gallery/snapshot.ts
22432
- var import_node_crypto8 = require("crypto");
22433
- var import_node_fs43 = require("fs");
22434
- var import_promises37 = require("fs/promises");
22435
- var import_node_path47 = __toESM(require("path"), 1);
22747
+ var import_node_crypto9 = require("crypto");
22748
+ var import_node_fs45 = require("fs");
22749
+ var import_promises39 = require("fs/promises");
22750
+ var import_node_path49 = __toESM(require("path"), 1);
22436
22751
 
22437
22752
  // src/gallery/models.ts
22438
- var import_node_fs38 = require("fs");
22439
- var import_promises31 = require("fs/promises");
22440
- var import_node_path41 = __toESM(require("path"), 1);
22753
+ var import_node_fs40 = require("fs");
22754
+ var import_promises33 = require("fs/promises");
22755
+ var import_node_path43 = __toESM(require("path"), 1);
22441
22756
  var import_zod11 = require("zod");
22442
22757
 
22443
22758
  // src/glb.ts
@@ -22770,11 +23085,11 @@ function modelItems(json) {
22770
23085
  }
22771
23086
 
22772
23087
  // src/manifest-edit.ts
22773
- var import_promises27 = require("fs/promises");
22774
- var import_node_path37 = __toESM(require("path"), 1);
23088
+ var import_promises29 = require("fs/promises");
23089
+ var import_node_path39 = __toESM(require("path"), 1);
22775
23090
  var import_zod8 = require("zod");
22776
23091
  var HexSha = import_zod8.z.string().regex(/^[0-9a-f]{64}$/);
22777
- var ProjectFileSchema = import_zod8.z.string().min(1).refine((file) => !import_node_path37.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
23092
+ var ProjectFileSchema = import_zod8.z.string().min(1).refine((file) => !import_node_path39.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
22778
23093
  var AssetPatchSchema = import_zod8.z.object({
22779
23094
  prompt: import_zod8.z.string().optional(),
22780
23095
  /** Per-style override for the style being viewed; null removes it. */
@@ -23194,8 +23509,8 @@ function applyEdit(raw, edit) {
23194
23509
  }
23195
23510
  }
23196
23511
  async function withCandidate(manifestPath, edit, use, unchanged) {
23197
- const absolute = import_node_path37.default.resolve(manifestPath);
23198
- const original = await (0, import_promises27.readFile)(absolute, "utf8");
23512
+ const absolute = import_node_path39.default.resolve(manifestPath);
23513
+ const original = await (0, import_promises29.readFile)(absolute, "utf8");
23199
23514
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
23200
23515
  let raw;
23201
23516
  try {
@@ -23208,12 +23523,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
23208
23523
  applyEdit(raw, edit);
23209
23524
  const next = serializeLike(original, raw);
23210
23525
  if (next === original) return unchanged(absolute, original);
23211
- const tmp = import_node_path37.default.join(
23212
- import_node_path37.default.dirname(absolute),
23213
- `.${import_node_path37.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
23526
+ const tmp = import_node_path39.default.join(
23527
+ import_node_path39.default.dirname(absolute),
23528
+ `.${import_node_path39.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
23214
23529
  );
23215
23530
  try {
23216
- await (0, import_promises27.writeFile)(tmp, next);
23531
+ await (0, import_promises29.writeFile)(tmp, next);
23217
23532
  let specs;
23218
23533
  try {
23219
23534
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -23223,7 +23538,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
23223
23538
  }
23224
23539
  return await use({ absolute, original, next, tmp, specs });
23225
23540
  } finally {
23226
- await (0, import_promises27.rm)(tmp, { force: true });
23541
+ await (0, import_promises29.rm)(tmp, { force: true });
23227
23542
  }
23228
23543
  }
23229
23544
  async function applyManifestEdit(manifestPath, edit) {
@@ -23231,7 +23546,7 @@ async function applyManifestEdit(manifestPath, edit) {
23231
23546
  manifestPath,
23232
23547
  edit,
23233
23548
  async ({ absolute, next, tmp }) => {
23234
- await (0, import_promises27.rename)(tmp, absolute);
23549
+ await (0, import_promises29.rename)(tmp, absolute);
23235
23550
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
23236
23551
  },
23237
23552
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -23239,18 +23554,18 @@ async function applyManifestEdit(manifestPath, edit) {
23239
23554
  }
23240
23555
 
23241
23556
  // src/pipeline/hand-edit.ts
23242
- var import_node_fs35 = require("fs");
23243
- var import_promises28 = require("fs/promises");
23244
- var import_node_path38 = __toESM(require("path"), 1);
23557
+ var import_node_fs37 = require("fs");
23558
+ var import_promises30 = require("fs/promises");
23559
+ var import_node_path40 = __toESM(require("path"), 1);
23245
23560
  var import_zod9 = require("zod");
23246
23561
  var HAND_EDIT_DIR = "edits";
23247
23562
  function handEditPath(loaded, spec) {
23248
23563
  const style = loaded.manifest.styles[spec.styleId];
23249
- const outDir = import_node_path38.default.resolve(loaded.root, style?.outDir ?? ".");
23250
- const relative = import_node_path38.default.relative(outDir, spec.outFile);
23251
- const inside2 = relative && !relative.startsWith("..") && !import_node_path38.default.isAbsolute(relative);
23252
- const file = inside2 ? relative : import_node_path38.default.basename(spec.outFile);
23253
- return import_node_path38.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
23564
+ const outDir = import_node_path40.default.resolve(loaded.root, style?.outDir ?? ".");
23565
+ const relative = import_node_path40.default.relative(outDir, spec.outFile);
23566
+ const inside2 = relative && !relative.startsWith("..") && !import_node_path40.default.isAbsolute(relative);
23567
+ const file = inside2 ? relative : import_node_path40.default.basename(spec.outFile);
23568
+ return import_node_path40.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
23254
23569
  }
23255
23570
  function handEditBases(spec, lock) {
23256
23571
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -23263,10 +23578,10 @@ function handEditBases(spec, lock) {
23263
23578
  }));
23264
23579
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
23265
23580
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
23266
- if (!members.every((member) => (0, import_node_fs35.existsSync)(member.path))) return null;
23581
+ if (!members.every((member) => (0, import_node_fs37.existsSync)(member.path))) return null;
23267
23582
  return members.map(({ role, path: file }) => ({ role, path: file }));
23268
23583
  }
23269
- return (0, import_node_fs35.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
23584
+ return (0, import_node_fs37.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
23270
23585
  }
23271
23586
  function handEditBase(spec, lock) {
23272
23587
  const bases = handEditBases(spec, lock);
@@ -23316,19 +23631,19 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
23316
23631
  `${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`
23317
23632
  );
23318
23633
  }
23319
- const existing = spec.source ? import_node_path38.default.resolve(loaded.root, spec.source) : null;
23634
+ const existing = spec.source ? import_node_path40.default.resolve(loaded.root, spec.source) : null;
23320
23635
  const editPath = existing ?? handEditPath(loaded, spec);
23321
23636
  const members = handEditMembers(loaded, spec, lock, editPath);
23322
23637
  let created = false;
23323
23638
  for (const member of members) {
23324
- if ((0, import_node_fs35.existsSync)(member.path)) continue;
23639
+ if ((0, import_node_fs37.existsSync)(member.path)) continue;
23325
23640
  if (!member.base) {
23326
23641
  throw new ManifestEditError(
23327
23642
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
23328
23643
  );
23329
23644
  }
23330
- await (0, import_promises28.mkdir)(import_node_path38.default.dirname(member.path), { recursive: true });
23331
- await (0, import_promises28.copyFile)(member.base, member.path);
23645
+ await (0, import_promises30.mkdir)(import_node_path40.default.dirname(member.path), { recursive: true });
23646
+ await (0, import_promises30.copyFile)(member.base, member.path);
23332
23647
  created = true;
23333
23648
  }
23334
23649
  const source = portableOutputPath(editPath, loaded.root);
@@ -23406,7 +23721,7 @@ function handEditProjectPath(editPath) {
23406
23721
  async function readHandEditCompanion(editPath) {
23407
23722
  let text;
23408
23723
  try {
23409
- text = await (0, import_promises28.readFile)(handEditCompanionPath(editPath), "utf8");
23724
+ text = await (0, import_promises30.readFile)(handEditCompanionPath(editPath), "utf8");
23410
23725
  } catch {
23411
23726
  return null;
23412
23727
  }
@@ -23450,7 +23765,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
23450
23765
  }
23451
23766
  });
23452
23767
  const bases = handEditBases(spec, lock);
23453
- const expectedSize = bases?.[0] ? decodePng(await (0, import_promises28.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
23768
+ const expectedSize = bases?.[0] ? decodePng(await (0, import_promises30.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
23454
23769
  for (const [index, image] of decoded.entries()) {
23455
23770
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
23456
23771
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -23466,7 +23781,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
23466
23781
  editor: input.editor,
23467
23782
  protocol: input.protocol,
23468
23783
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
23469
- project: projectPath ? import_node_path38.default.basename(projectPath) : null,
23784
+ project: projectPath ? import_node_path40.default.basename(projectPath) : null,
23470
23785
  outputs: incoming.map((frame, index) => ({
23471
23786
  role: frame.role,
23472
23787
  basedOn: basedOnHash(entry, index),
@@ -23496,10 +23811,10 @@ function basedOnHash(entry, index) {
23496
23811
  async function replaceFile(file, bytes) {
23497
23812
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
23498
23813
  try {
23499
- await (0, import_promises28.writeFile)(tmp, bytes);
23500
- await (0, import_promises28.rename)(tmp, file);
23814
+ await (0, import_promises30.writeFile)(tmp, bytes);
23815
+ await (0, import_promises30.rename)(tmp, file);
23501
23816
  } finally {
23502
- await (0, import_promises28.rm)(tmp, { force: true });
23817
+ await (0, import_promises30.rm)(tmp, { force: true });
23503
23818
  }
23504
23819
  }
23505
23820
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -23509,9 +23824,9 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
23509
23824
 
23510
23825
  // src/pipeline/model-edit.ts
23511
23826
  var import_node_child_process3 = require("child_process");
23512
- var import_node_fs36 = require("fs");
23513
- var import_promises29 = require("fs/promises");
23514
- var import_node_path39 = __toESM(require("path"), 1);
23827
+ var import_node_fs38 = require("fs");
23828
+ var import_promises31 = require("fs/promises");
23829
+ var import_node_path41 = __toESM(require("path"), 1);
23515
23830
  var import_zod10 = require("zod");
23516
23831
 
23517
23832
  // src/jpeg.ts
@@ -23893,27 +24208,27 @@ var MAX_MODELS = 200;
23893
24208
  var MAX_DEPTH = 8;
23894
24209
  var SKIPPED_DIRS = /* @__PURE__ */ new Set([HAND_EDIT_DIR, "node_modules"]);
23895
24210
  async function discoverModels(loaded, opts = {}) {
23896
- const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: import_node_path39.default.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
24211
+ const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: import_node_path41.default.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
23897
24212
  const seen = /* @__PURE__ */ new Set();
23898
24213
  const models = [];
23899
24214
  const walk2 = async (styleId, outDir, dir, depth) => {
23900
24215
  if (depth > MAX_DEPTH || models.length >= MAX_MODELS) return;
23901
24216
  let entries;
23902
24217
  try {
23903
- entries = await (0, import_promises29.readdir)(dir, { withFileTypes: true });
24218
+ entries = await (0, import_promises31.readdir)(dir, { withFileTypes: true });
23904
24219
  } catch {
23905
24220
  return;
23906
24221
  }
23907
24222
  entries.sort((a, b) => a.name.localeCompare(b.name));
23908
24223
  for (const entry of entries) {
23909
24224
  if (models.length >= MAX_MODELS) return;
23910
- const full = import_node_path39.default.join(dir, entry.name);
24225
+ const full = import_node_path41.default.join(dir, entry.name);
23911
24226
  if (entry.isDirectory()) {
23912
24227
  if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
23913
24228
  await walk2(styleId, outDir, full, depth + 1);
23914
24229
  } else if (entry.isFile() && entry.name.toLowerCase().endsWith(MODEL_EXTENSION) && !seen.has(full)) {
23915
24230
  seen.add(full);
23916
- models.push({ styleId, file: full, editFile: import_node_path39.default.join(outDir, HAND_EDIT_DIR, import_node_path39.default.relative(outDir, full)) });
24231
+ models.push({ styleId, file: full, editFile: import_node_path41.default.join(outDir, HAND_EDIT_DIR, import_node_path41.default.relative(outDir, full)) });
23917
24232
  }
23918
24233
  }
23919
24234
  };
@@ -23921,12 +24236,12 @@ async function discoverModels(loaded, opts = {}) {
23921
24236
  return models.sort((a, b) => a.styleId.localeCompare(b.styleId) || a.file.localeCompare(b.file));
23922
24237
  }
23923
24238
  async function findModel(loaded, portablePath) {
23924
- const wanted = import_node_path39.default.resolve(loaded.root, portablePath);
24239
+ const wanted = import_node_path41.default.resolve(loaded.root, portablePath);
23925
24240
  const model = (await discoverModels(loaded)).find((candidate) => candidate.file === wanted);
23926
24241
  if (!model) throw new ManifestEditError(`"${portablePath}" is not a model under one of this project's output folders`);
23927
24242
  return model;
23928
24243
  }
23929
- var stem = (editFile) => editFile.slice(0, -import_node_path39.default.extname(editFile).length);
24244
+ var stem = (editFile) => editFile.slice(0, -import_node_path41.default.extname(editFile).length);
23930
24245
  function modelCompanionPath(editFile) {
23931
24246
  return stem(editFile) + ".edit.json";
23932
24247
  }
@@ -23965,25 +24280,29 @@ var ModelEditCompanionSchema = import_zod10.z.object({
23965
24280
  }).strict();
23966
24281
  async function readModelCompanion(editFile) {
23967
24282
  try {
23968
- return ModelEditCompanionSchema.parse(JSON.parse(await (0, import_promises29.readFile)(modelCompanionPath(editFile), "utf8")));
24283
+ return ModelEditCompanionSchema.parse(JSON.parse(await (0, import_promises31.readFile)(modelCompanionPath(editFile), "utf8")));
23969
24284
  } catch {
23970
24285
  return null;
23971
24286
  }
23972
24287
  }
24288
+ function modelEditStatus(companion, builtSha256) {
24289
+ if (!companion) return "unrecorded";
24290
+ return companion.outputs[0].basedOn === builtSha256 ? "edited" : "rebuilt-since";
24291
+ }
23973
24292
  async function replaceFile2(file, bytes) {
23974
- await (0, import_promises29.mkdir)(import_node_path39.default.dirname(file), { recursive: true });
24293
+ await (0, import_promises31.mkdir)(import_node_path41.default.dirname(file), { recursive: true });
23975
24294
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
23976
24295
  try {
23977
- await (0, import_promises29.writeFile)(tmp, bytes);
23978
- await (0, import_promises29.rename)(tmp, file);
24296
+ await (0, import_promises31.writeFile)(tmp, bytes);
24297
+ await (0, import_promises31.rename)(tmp, file);
23979
24298
  } finally {
23980
- await (0, import_promises29.rm)(tmp, { force: true });
24299
+ await (0, import_promises31.rm)(tmp, { force: true });
23981
24300
  }
23982
24301
  }
23983
24302
  async function readModel(file, what) {
23984
24303
  let bytes;
23985
24304
  try {
23986
- bytes = await (0, import_promises29.readFile)(file);
24305
+ bytes = await (0, import_promises31.readFile)(file);
23987
24306
  } catch {
23988
24307
  throw new ManifestEditError(`${what} is not on disk at ${file}`);
23989
24308
  }
@@ -24010,7 +24329,7 @@ async function saveModelTexture(model, input) {
24010
24329
  throw new ManifestEditError(`the texture is not a valid PNG: ${error instanceof Error ? error.message : String(error)}`);
24011
24330
  }
24012
24331
  const original = await readModel(model.file, "the model");
24013
- const created = !(0, import_node_fs36.existsSync)(model.editFile);
24332
+ const created = !(0, import_node_fs38.existsSync)(model.editFile);
24014
24333
  const base = created ? original : await readModel(model.editFile, "the model's edit");
24015
24334
  let current;
24016
24335
  try {
@@ -24032,7 +24351,7 @@ async function saveModelTexture(model, input) {
24032
24351
  sha256: sha256(input.png),
24033
24352
  editor: input.editor,
24034
24353
  savedAt,
24035
- project: projectPath ? import_node_path39.default.basename(projectPath) : null
24354
+ project: projectPath ? import_node_path41.default.basename(projectPath) : null
24036
24355
  };
24037
24356
  const companion = {
24038
24357
  version: 2,
@@ -24055,7 +24374,7 @@ async function adoptModelExport(model, opts = {}) {
24055
24374
  const mode2 = opts.mode ?? "textures";
24056
24375
  const exported = await readModel(from, "the exported model");
24057
24376
  const original = await readModel(model.file, "the model");
24058
- const created = !(0, import_node_fs36.existsSync)(model.editFile);
24377
+ const created = !(0, import_node_fs38.existsSync)(model.editFile);
24059
24378
  const savedAt = (opts.now ?? /* @__PURE__ */ new Date()).toISOString();
24060
24379
  const editor = opts.editor ?? "blender";
24061
24380
  const taken = [];
@@ -24124,9 +24443,9 @@ async function adoptModelExport(model, opts = {}) {
24124
24443
  await replaceFile2(companionPath, JSON.stringify(companion, null, 2) + "\n");
24125
24444
  return { editFile: model.editFile, companionPath, companion, created, mode: mode2, taken };
24126
24445
  }
24127
- function blenderCommand(env = process.env, platform = process.platform, exists = import_node_fs36.existsSync, list = (dir) => {
24446
+ function blenderCommand(env = process.env, platform = process.platform, exists = import_node_fs38.existsSync, list = (dir) => {
24128
24447
  try {
24129
- return (0, import_node_fs36.readdirSync)(dir);
24448
+ return (0, import_node_fs38.readdirSync)(dir);
24130
24449
  } catch {
24131
24450
  return [];
24132
24451
  }
@@ -24136,16 +24455,16 @@ function blenderCommand(env = process.env, platform = process.platform, exists =
24136
24455
  const candidates = [];
24137
24456
  if (platform === "darwin") {
24138
24457
  candidates.push("/Applications/Blender.app/Contents/MacOS/Blender");
24139
- if (env.HOME) candidates.push(import_node_path39.default.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
24458
+ if (env.HOME) candidates.push(import_node_path41.default.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
24140
24459
  } else if (platform === "win32") {
24141
24460
  for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((value) => Boolean(value))) {
24142
- const foundation = import_node_path39.default.win32.join(root, "Blender Foundation");
24461
+ const foundation = import_node_path41.default.win32.join(root, "Blender Foundation");
24143
24462
  const versions = list(foundation).filter((name) => /^Blender/i.test(name)).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
24144
- for (const version of versions) candidates.push(import_node_path39.default.win32.join(foundation, version, "blender.exe"));
24463
+ for (const version of versions) candidates.push(import_node_path41.default.win32.join(foundation, version, "blender.exe"));
24145
24464
  }
24146
24465
  } else {
24147
24466
  candidates.push("/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender", "/var/lib/flatpak/exports/bin/org.blender.Blender");
24148
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(import_node_path39.default.join(dir, "blender"));
24467
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(import_node_path41.default.join(dir, "blender"));
24149
24468
  }
24150
24469
  const found = candidates.find((candidate) => exists(candidate));
24151
24470
  return found ? [found] : null;
@@ -24178,7 +24497,7 @@ function openInBlender(model, opts = {}) {
24178
24497
  "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"
24179
24498
  );
24180
24499
  }
24181
- const file = (0, import_node_fs36.existsSync)(model.editFile) ? model.editFile : model.file;
24500
+ const file = (0, import_node_fs38.existsSync)(model.editFile) ? model.editFile : model.file;
24182
24501
  const [program, ...rest] = command;
24183
24502
  const args = [...rest, ...blenderArguments(file, modelExportPath(model.editFile))];
24184
24503
  const launch = opts.launch ?? ((bin, argv) => {
@@ -24188,14 +24507,14 @@ function openInBlender(model, opts = {}) {
24188
24507
  child.unref();
24189
24508
  });
24190
24509
  launch(program, args);
24191
- return `${command.join(" ")} (${import_node_path39.default.basename(file)})`;
24510
+ return `${command.join(" ")} (${import_node_path41.default.basename(file)})`;
24192
24511
  }
24193
24512
 
24194
24513
  // src/pipeline/model-normals.ts
24195
- var import_node_crypto7 = require("crypto");
24196
- var import_node_fs37 = require("fs");
24197
- var import_promises30 = require("fs/promises");
24198
- var import_node_path40 = __toESM(require("path"), 1);
24514
+ var import_node_crypto8 = require("crypto");
24515
+ var import_node_fs39 = require("fs");
24516
+ var import_promises32 = require("fs/promises");
24517
+ var import_node_path42 = __toESM(require("path"), 1);
24199
24518
  var MODEL_NORMAL_SOURCES = ["texture", "views", "sprites"];
24200
24519
  var TILE_MAX = 512;
24201
24520
  function decodeImage(bytes) {
@@ -24287,13 +24606,13 @@ function poseNodes(document2, pose) {
24287
24606
  const posed = /* @__PURE__ */ new Map();
24288
24607
  for (const channel of animation.channels) {
24289
24608
  const node = channel.target.node;
24290
- const path51 = channel.target.path;
24291
- if (node === void 0 || !["translation", "rotation", "scale"].includes(path51)) continue;
24609
+ const path53 = channel.target.path;
24610
+ if (node === void 0 || !["translation", "rotation", "scale"].includes(path53)) continue;
24292
24611
  const sampler = animation.samplers[channel.sampler];
24293
24612
  if (!sampler) continue;
24294
24613
  const times = readAccessor(document2, sampler.input).data;
24295
24614
  const values = readAccessor(document2, sampler.output);
24296
- const width = path51 === "rotation" ? 4 : 3;
24615
+ const width = path53 === "rotation" ? 4 : 3;
24297
24616
  const cubic = sampler.interpolation === "CUBICSPLINE";
24298
24617
  const valueAt = (key3) => Array.from(values.data.subarray((cubic ? key3 * 3 + 1 : key3) * width, (cubic ? key3 * 3 + 1 : key3) * width + width));
24299
24618
  const last = times.length - 1;
@@ -24305,16 +24624,16 @@ function poseNodes(document2, pose) {
24305
24624
  const span = times[key2 + 1] - times[key2];
24306
24625
  const f = span > 0 ? (time - times[key2]) / span : 0;
24307
24626
  const next = valueAt(key2 + 1);
24308
- const sign = path51 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
24627
+ const sign = path53 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
24309
24628
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
24310
24629
  }
24311
- if (path51 === "rotation") {
24630
+ if (path53 === "rotation") {
24312
24631
  const length = Math.hypot(...value) || 1;
24313
24632
  value = value.map((v) => v / length);
24314
24633
  }
24315
24634
  const base = posed.get(node) ?? { ...document2.json.nodes?.[node] ?? {} };
24316
24635
  if (base.matrix) delete base.matrix;
24317
- base[path51] = value;
24636
+ base[path53] = value;
24318
24637
  posed.set(node, base);
24319
24638
  }
24320
24639
  return posed;
@@ -24924,20 +25243,20 @@ function modelSpritesDir(modelFile) {
24924
25243
  return modelFile.replace(/\.glb$/i, "") + ".sprites";
24925
25244
  }
24926
25245
  async function readSpriteFolder(dir) {
24927
- const folder = (0, import_node_fs37.existsSync)(import_node_path40.default.join(dir, "rotations")) ? import_node_path40.default.join(dir, "rotations") : dir;
24928
- const names = (await (0, import_promises30.readdir)(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
24929
- return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await (0, import_promises30.readFile)(import_node_path40.default.join(folder, name)), file: import_node_path40.default.join(folder, name) })));
25246
+ const folder = (0, import_node_fs39.existsSync)(import_node_path42.default.join(dir, "rotations")) ? import_node_path42.default.join(dir, "rotations") : dir;
25247
+ const names = (await (0, import_promises32.readdir)(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
25248
+ return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await (0, import_promises32.readFile)(import_node_path42.default.join(folder, name)), file: import_node_path42.default.join(folder, name) })));
24930
25249
  }
24931
25250
  function modelNormalDir(editFile) {
24932
25251
  return editFile.replace(/\.glb$/i, "") + ".normal-map";
24933
25252
  }
24934
25253
  function requestKey(png, options) {
24935
25254
  const asked = JSON.stringify([options.mode ?? "lite", options.kind ?? null, options.surfaceDetail ?? null, options.detailSoftness ?? null, options.strength ?? null]);
24936
- return (0, import_node_crypto7.createHash)("sha256").update(png).update(asked).digest("hex").slice(0, 16);
25255
+ return (0, import_node_crypto8.createHash)("sha256").update(png).update(asked).digest("hex").slice(0, 16);
24937
25256
  }
24938
25257
  async function prepare(model, opts) {
24939
- const fromEdit = (0, import_node_fs37.existsSync)(model.editFile);
24940
- const document2 = parseGlb(await (0, import_promises30.readFile)(fromEdit ? model.editFile : model.file));
25258
+ const fromEdit = (0, import_node_fs39.existsSync)(model.editFile);
25259
+ const document2 = parseGlb(await (0, import_promises32.readFile)(fromEdit ? model.editFile : model.file));
24941
25260
  const summary = describeGlb(document2);
24942
25261
  const normalImages = summary.images.filter((image) => image.roles.includes("normal"));
24943
25262
  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");
@@ -24946,14 +25265,14 @@ async function prepare(model, opts) {
24946
25265
  if (!normalImages.some((image) => image.index === index)) throw new Error(`image ${index} is not one of the model's normal maps`);
24947
25266
  }
24948
25267
  const primitives = restPrimitives(document2, opts.pose);
24949
- const dir = import_node_path40.default.join(modelNormalDir(model.editFile), opts.source);
25268
+ const dir = import_node_path42.default.join(modelNormalDir(model.editFile), opts.source);
24950
25269
  const surfaces = /* @__PURE__ */ new Map();
24951
25270
  const tiles = /* @__PURE__ */ new Map();
24952
25271
  const calls = [];
24953
25272
  const images = [];
24954
25273
  const call = (label, png) => {
24955
- const cache = import_node_path40.default.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
24956
- calls.push({ label, png, cache, cached: (0, import_node_fs37.existsSync)(cache) });
25274
+ const cache = import_node_path42.default.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
25275
+ calls.push({ label, png, cache, cached: (0, import_node_fs39.existsSync)(cache) });
24957
25276
  };
24958
25277
  for (const index of wanted) {
24959
25278
  const summaryImage = summary.images[index];
@@ -25021,15 +25340,15 @@ async function prepare(model, opts) {
25021
25340
  }
25022
25341
  async function planModelNormals(model, opts) {
25023
25342
  const { plan } = await prepare(model, opts);
25024
- await (0, import_promises30.mkdir)(plan.dir, { recursive: true });
25025
- for (const entry of plan.calls) await (0, import_promises30.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
25026
- for (const fit of plan.fits ?? []) await (0, import_promises30.writeFile)(import_node_path40.default.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
25343
+ await (0, import_promises32.mkdir)(plan.dir, { recursive: true });
25344
+ for (const entry of plan.calls) await (0, import_promises32.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
25345
+ for (const fit of plan.fits ?? []) await (0, import_promises32.writeFile)(import_node_path42.default.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
25027
25346
  return plan;
25028
25347
  }
25029
25348
  async function generateModelNormals(model, opts, mapper, hooks = {}) {
25030
25349
  const prepared = await prepare(model, opts);
25031
25350
  const { plan, document: document2 } = prepared;
25032
- await (0, import_promises30.mkdir)(plan.dir, { recursive: true });
25351
+ await (0, import_promises32.mkdir)(plan.dir, { recursive: true });
25033
25352
  const request = {
25034
25353
  ...opts.mode ? { mode: opts.mode } : {},
25035
25354
  ...opts.kind ? { kind: opts.kind } : {},
@@ -25041,14 +25360,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
25041
25360
  let sent = 0;
25042
25361
  for (const entry of plan.calls) {
25043
25362
  hooks.onCall?.(entry.label, entry.cached);
25044
- await (0, import_promises30.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
25363
+ await (0, import_promises32.writeFile)(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
25045
25364
  if (entry.cached) {
25046
- answers.push(await (0, import_promises30.readFile)(entry.cache));
25365
+ answers.push(await (0, import_promises32.readFile)(entry.cache));
25047
25366
  continue;
25048
25367
  }
25049
25368
  const answer = await mapper(entry.png, request);
25050
25369
  sent++;
25051
- await (0, import_promises30.writeFile)(entry.cache, answer);
25370
+ await (0, import_promises32.writeFile)(entry.cache, answer);
25052
25371
  answers.push(answer);
25053
25372
  }
25054
25373
  let result = null;
@@ -25066,14 +25385,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
25066
25385
  field = detailFromViews(surface, prepared.views, answers);
25067
25386
  }
25068
25387
  bleed(field);
25069
- const detail = import_node_path40.default.join(plan.dir, `image-${image}.detail.png`);
25070
- await (0, import_promises30.writeFile)(detail, encodeImage(fieldImage(field)));
25388
+ const detail = import_node_path42.default.join(plan.dir, `image-${image}.detail.png`);
25389
+ await (0, import_promises32.writeFile)(detail, encodeImage(fieldImage(field)));
25071
25390
  details.push(detail);
25072
- const basePath = import_node_path40.default.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
25391
+ const basePath = import_node_path42.default.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
25073
25392
  const record = companion?.textures.find((entry) => entry.image === image);
25074
- const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && (0, import_node_fs37.existsSync)(basePath);
25075
- const existing = ours ? decodeImage(await (0, import_promises30.readFile)(basePath)) : decodeImage(glbImageBytes(document2, image).bytes);
25076
- if (!ours) await (0, import_promises30.writeFile)(basePath, encodeImage(existing));
25393
+ const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && (0, import_node_fs39.existsSync)(basePath);
25394
+ const existing = ours ? decodeImage(await (0, import_promises32.readFile)(basePath)) : decodeImage(glbImageBytes(document2, image).bytes);
25395
+ if (!ours) await (0, import_promises32.writeFile)(basePath, encodeImage(existing));
25077
25396
  const png = encodeImage(applyDetail(existing, field, opts));
25078
25397
  result = await saveModelTexture(model, {
25079
25398
  image,
@@ -25102,7 +25421,7 @@ function modelNormalMapper(client2) {
25102
25421
  // src/gallery/models.ts
25103
25422
  var MODEL_FILE_TYPE = "model/gltf-binary";
25104
25423
  async function describeFile(media, mediaId, root, file, bytes) {
25105
- const info = await (0, import_promises31.stat)(file);
25424
+ const info = await (0, import_promises33.stat)(file);
25106
25425
  const id = mediaId(file);
25107
25426
  const hash = sha256(bytes);
25108
25427
  media.set(id, { path: file, contentType: MODEL_FILE_TYPE });
@@ -25121,11 +25440,11 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25121
25440
  for (const model of await discoverModels(loaded, opts)) {
25122
25441
  let bytes;
25123
25442
  try {
25124
- bytes = await (0, import_promises31.readFile)(model.file);
25443
+ bytes = await (0, import_promises33.readFile)(model.file);
25125
25444
  } catch {
25126
25445
  continue;
25127
25446
  }
25128
- const outDir = import_node_path41.default.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
25447
+ const outDir = import_node_path43.default.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
25129
25448
  let summary = null;
25130
25449
  let error = null;
25131
25450
  if (bytes.length > MAX_MODEL_BYTES) error = `the file is ${bytes.length} bytes; models over ${MAX_MODEL_BYTES} are listed but not opened`;
@@ -25139,16 +25458,16 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25139
25458
  const file = await describeFile(media, mediaId, root, model.file, bytes);
25140
25459
  let edit = null;
25141
25460
  let adoptedExport = null;
25142
- if ((0, import_node_fs38.existsSync)(model.editFile)) {
25461
+ if ((0, import_node_fs40.existsSync)(model.editFile)) {
25143
25462
  try {
25144
- const editBytes = await (0, import_promises31.readFile)(model.editFile);
25463
+ const editBytes = await (0, import_promises33.readFile)(model.editFile);
25145
25464
  const described = await describeFile(media, mediaId, root, model.editFile, editBytes);
25146
25465
  const companion = await readModelCompanion(model.editFile);
25147
25466
  adoptedExport = companion?.adoptedExport ?? null;
25148
25467
  const textures = (companion?.textures ?? []).map((texture) => {
25149
25468
  const projectPath = texture.project ? modelTextureProjectPath(model.editFile, texture.image) : null;
25150
25469
  let projectUrl = null;
25151
- if (projectPath && (0, import_node_fs38.existsSync)(projectPath)) {
25470
+ if (projectPath && (0, import_node_fs40.existsSync)(projectPath)) {
25152
25471
  const id = mediaId(projectPath);
25153
25472
  media.set(id, { path: projectPath, contentType: "application/octet-stream" });
25154
25473
  projectUrl = `/media/${id}?v=${texture.sha256.slice(0, 24)}`;
@@ -25164,7 +25483,7 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25164
25483
  });
25165
25484
  edit = {
25166
25485
  ...described,
25167
- status: !companion ? "unrecorded" : companion.outputs[0].basedOn === file.sha256 ? "edited" : "rebuilt-since",
25486
+ status: modelEditStatus(companion, file.sha256),
25168
25487
  editor: companion?.editor ?? null,
25169
25488
  savedAt: companion?.savedAt ?? null,
25170
25489
  changedSince: companion ? companion.outputs[0].sha256 !== described.sha256 : false,
@@ -25177,26 +25496,26 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
25177
25496
  const exportFile = modelExportPath(model.editFile);
25178
25497
  let exportWaiting = null;
25179
25498
  try {
25180
- const info = await (0, import_promises31.stat)(exportFile);
25181
- if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await (0, import_promises31.readFile)(exportFile)) !== adoptedExport) {
25499
+ const info = await (0, import_promises33.stat)(exportFile);
25500
+ if (info.isFile() && info.size <= MAX_MODEL_BYTES && sha256(await (0, import_promises33.readFile)(exportFile)) !== adoptedExport) {
25182
25501
  exportWaiting = { bytes: info.size, modifiedAt: info.mtime.toISOString() };
25183
25502
  }
25184
25503
  } catch {
25185
25504
  }
25186
25505
  const spritesDir = modelSpritesDir(model.file);
25187
25506
  let sprites = null;
25188
- if ((0, import_node_fs38.existsSync)(spritesDir)) {
25507
+ if ((0, import_node_fs40.existsSync)(spritesDir)) {
25189
25508
  try {
25190
25509
  sprites = { path: portableOutputPath(spritesDir, root), directions: (await readSpriteFolder(spritesDir)).map((sprite) => sprite.direction) };
25191
25510
  } catch {
25192
25511
  }
25193
25512
  }
25194
- const relative = import_node_path41.default.relative(outDir, model.file).split(import_node_path41.default.sep).join("/");
25513
+ const relative = import_node_path43.default.relative(outDir, model.file).split(import_node_path43.default.sep).join("/");
25195
25514
  models.push({
25196
25515
  id: `model:${model.styleId}/${relative}`,
25197
25516
  project: null,
25198
25517
  styleId: model.styleId,
25199
- name: import_node_path41.default.basename(model.file, import_node_path41.default.extname(model.file)),
25518
+ name: import_node_path43.default.basename(model.file, import_node_path43.default.extname(model.file)),
25200
25519
  file,
25201
25520
  summary,
25202
25521
  error,
@@ -25291,9 +25610,9 @@ function blenderAvailable() {
25291
25610
  }
25292
25611
 
25293
25612
  // src/workspace.ts
25294
- var import_promises32 = require("fs/promises");
25295
- var import_node_fs39 = require("fs");
25296
- var import_node_path42 = __toESM(require("path"), 1);
25613
+ var import_promises34 = require("fs/promises");
25614
+ var import_node_fs41 = require("fs");
25615
+ var import_node_path44 = __toESM(require("path"), 1);
25297
25616
  var import_zod12 = require("zod");
25298
25617
  var WorkspaceProjectSchema = import_zod12.z.object({
25299
25618
  id: import_zod12.z.string().min(1),
@@ -25318,10 +25637,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
25318
25637
  );
25319
25638
  }
25320
25639
  async function loadWorkspace(workspacePath) {
25321
- if (!(0, import_node_fs39.existsSync)(workspacePath)) return { version: 1, projects: [] };
25640
+ if (!(0, import_node_fs41.existsSync)(workspacePath)) return { version: 1, projects: [] };
25322
25641
  let raw;
25323
25642
  try {
25324
- raw = JSON.parse(await (0, import_promises32.readFile)(workspacePath, "utf8"));
25643
+ raw = JSON.parse(await (0, import_promises34.readFile)(workspacePath, "utf8"));
25325
25644
  } catch (err) {
25326
25645
  throw new ProjectError(
25327
25646
  `Workspace catalog at ${workspacePath} is malformed:
@@ -25335,22 +25654,22 @@ async function saveWorkspace(workspacePath, ws) {
25335
25654
  version: 1,
25336
25655
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
25337
25656
  };
25338
- await (0, import_promises32.mkdir)(import_node_path42.default.dirname(import_node_path42.default.resolve(workspacePath)), { recursive: true });
25657
+ await (0, import_promises34.mkdir)(import_node_path44.default.dirname(import_node_path44.default.resolve(workspacePath)), { recursive: true });
25339
25658
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
25340
25659
  try {
25341
- await (0, import_promises32.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
25342
- await (0, import_promises32.rename)(tmp, workspacePath);
25660
+ await (0, import_promises34.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
25661
+ await (0, import_promises34.rename)(tmp, workspacePath);
25343
25662
  } finally {
25344
- await (0, import_promises32.rm)(tmp, { force: true });
25663
+ await (0, import_promises34.rm)(tmp, { force: true });
25345
25664
  }
25346
25665
  }
25347
25666
  function toPortablePath(dir, absolute) {
25348
- return import_node_path42.default.relative(dir, absolute).split(import_node_path42.default.sep).join("/");
25667
+ return import_node_path44.default.relative(dir, absolute).split(import_node_path44.default.sep).join("/");
25349
25668
  }
25350
25669
  function resolveProject(dir, project2) {
25351
25670
  return {
25352
- manifestPath: import_node_path42.default.resolve(dir, project2.manifest.split("/").join(import_node_path42.default.sep)),
25353
- lockPath: import_node_path42.default.resolve(dir, project2.lock.split("/").join(import_node_path42.default.sep))
25671
+ manifestPath: import_node_path44.default.resolve(dir, project2.manifest.split("/").join(import_node_path44.default.sep)),
25672
+ lockPath: import_node_path44.default.resolve(dir, project2.lock.split("/").join(import_node_path44.default.sep))
25354
25673
  };
25355
25674
  }
25356
25675
  function validateWorkspace(ws, dir) {
@@ -25363,21 +25682,21 @@ function validateWorkspace(ws, dir) {
25363
25682
  const { manifestPath, lockPath } = resolveProject(dir, project2);
25364
25683
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project2.id]);
25365
25684
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project2.id]);
25366
- if (import_node_path42.default.isAbsolute(project2.manifest) || import_node_path42.default.isAbsolute(project2.lock)) {
25685
+ if (import_node_path44.default.isAbsolute(project2.manifest) || import_node_path44.default.isAbsolute(project2.lock)) {
25367
25686
  diagnostics.push({
25368
25687
  id: "absolute-path",
25369
25688
  level: "warning",
25370
25689
  message: `project "${project2.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
25371
25690
  });
25372
25691
  }
25373
- if (!(0, import_node_fs39.existsSync)(manifestPath)) {
25692
+ if (!(0, import_node_fs41.existsSync)(manifestPath)) {
25374
25693
  diagnostics.push({
25375
25694
  id: "missing-manifest",
25376
25695
  level: "error",
25377
25696
  message: `project "${project2.id}" manifest not found: ${manifestPath}`
25378
25697
  });
25379
25698
  }
25380
- if (!(0, import_node_fs39.existsSync)(lockPath)) {
25699
+ if (!(0, import_node_fs41.existsSync)(lockPath)) {
25381
25700
  diagnostics.push({
25382
25701
  id: "missing-lock",
25383
25702
  level: "error",
@@ -25424,14 +25743,14 @@ function validateWorkspace(ws, dir) {
25424
25743
  }
25425
25744
 
25426
25745
  // src/gallery/edit.ts
25427
- var import_promises36 = require("fs/promises");
25428
- var import_node_path46 = __toESM(require("path"), 1);
25746
+ var import_promises38 = require("fs/promises");
25747
+ var import_node_path48 = __toESM(require("path"), 1);
25429
25748
  var import_zod16 = require("zod");
25430
25749
 
25431
25750
  // src/gallery/upload.ts
25432
- var import_node_fs40 = require("fs");
25433
- var import_promises33 = require("fs/promises");
25434
- var import_node_path43 = __toESM(require("path"), 1);
25751
+ var import_node_fs42 = require("fs");
25752
+ var import_promises35 = require("fs/promises");
25753
+ var import_node_path45 = __toESM(require("path"), 1);
25435
25754
  var import_zod13 = require("zod");
25436
25755
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
25437
25756
  var UploadImageSchema = import_zod13.z.object({
@@ -25444,12 +25763,12 @@ var UploadImageSchema = import_zod13.z.object({
25444
25763
  overwrite: import_zod13.z.boolean().optional()
25445
25764
  }).strict();
25446
25765
  async function saveProjectImage(root, request) {
25447
- const file = import_node_path43.default.resolve(root, request.path);
25448
- const relative = import_node_path43.default.relative(root, file);
25449
- if (relative.startsWith("..") || import_node_path43.default.isAbsolute(relative)) {
25766
+ const file = import_node_path45.default.resolve(root, request.path);
25767
+ const relative = import_node_path45.default.relative(root, file);
25768
+ if (relative.startsWith("..") || import_node_path45.default.isAbsolute(relative)) {
25450
25769
  throw new ManifestEditError("an upload must stay inside the project");
25451
25770
  }
25452
- const extension = import_node_path43.default.extname(file).toLowerCase();
25771
+ const extension = import_node_path45.default.extname(file).toLowerCase();
25453
25772
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
25454
25773
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
25455
25774
  const bytes = Buffer.from(request.base64, "base64");
@@ -25461,18 +25780,18 @@ async function saveProjectImage(root, request) {
25461
25780
  if (metadata.format !== expected) {
25462
25781
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
25463
25782
  }
25464
- if ((0, import_node_fs40.existsSync)(file) && !request.overwrite) {
25465
- throw new ManifestEditError(`${relative.split(import_node_path43.default.sep).join("/")} already exists; choose another name, or replace it`);
25783
+ if ((0, import_node_fs42.existsSync)(file) && !request.overwrite) {
25784
+ throw new ManifestEditError(`${relative.split(import_node_path45.default.sep).join("/")} already exists; choose another name, or replace it`);
25466
25785
  }
25467
- await (0, import_promises33.mkdir)(import_node_path43.default.dirname(file), { recursive: true });
25468
- await (0, import_promises33.writeFile)(file, bytes);
25469
- return relative.split(import_node_path43.default.sep).join("/");
25786
+ await (0, import_promises35.mkdir)(import_node_path45.default.dirname(file), { recursive: true });
25787
+ await (0, import_promises35.writeFile)(file, bytes);
25788
+ return relative.split(import_node_path45.default.sep).join("/");
25470
25789
  }
25471
25790
 
25472
25791
  // src/gallery/image-revision.ts
25473
- var import_node_fs41 = require("fs");
25474
- var import_promises34 = require("fs/promises");
25475
- var import_node_path44 = __toESM(require("path"), 1);
25792
+ var import_node_fs43 = require("fs");
25793
+ var import_promises36 = require("fs/promises");
25794
+ var import_node_path46 = __toESM(require("path"), 1);
25476
25795
  var import_zod14 = require("zod");
25477
25796
  var InpaintRevisionRequestSchema = import_zod14.z.object({
25478
25797
  action: import_zod14.z.literal("create-inpaint-revision"),
@@ -25491,15 +25810,15 @@ var InpaintRevisionRequestSchema = import_zod14.z.object({
25491
25810
  overwrite: import_zod14.z.boolean().optional()
25492
25811
  }).strict();
25493
25812
  async function createInpaintRevision(manifestPath, request) {
25494
- const root = import_node_path44.default.dirname(import_node_path44.default.resolve(manifestPath));
25495
- if (import_node_path44.default.extname(request.maskPath).toLowerCase() !== ".png") {
25813
+ const root = import_node_path46.default.dirname(import_node_path46.default.resolve(manifestPath));
25814
+ if (import_node_path46.default.extname(request.maskPath).toLowerCase() !== ".png") {
25496
25815
  throw new ManifestEditError("the mask must be a .png path inside the project");
25497
25816
  }
25498
25817
  const bytes = Buffer.from(request.maskBase64, "base64");
25499
25818
  const metadata = imageMetadata(bytes);
25500
25819
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
25501
- const file = import_node_path44.default.resolve(root, request.maskPath);
25502
- const previous = (0, import_node_fs41.existsSync)(file) ? await (0, import_promises34.readFile)(file) : null;
25820
+ const file = import_node_path46.default.resolve(root, request.maskPath);
25821
+ const previous = (0, import_node_fs43.existsSync)(file) ? await (0, import_promises36.readFile)(file) : null;
25503
25822
  const mask = await saveProjectImage(root, {
25504
25823
  action: "upload-image",
25505
25824
  path: request.maskPath,
@@ -25518,17 +25837,17 @@ async function createInpaintRevision(manifestPath, request) {
25518
25837
  }
25519
25838
  });
25520
25839
  } catch (error) {
25521
- if (previous) await (0, import_promises34.writeFile)(file, previous);
25522
- else await (0, import_promises34.rm)(file, { force: true });
25840
+ if (previous) await (0, import_promises36.writeFile)(file, previous);
25841
+ else await (0, import_promises36.rm)(file, { force: true });
25523
25842
  throw error;
25524
25843
  }
25525
25844
  return mask;
25526
25845
  }
25527
25846
 
25528
25847
  // src/gallery/skeleton.ts
25529
- var import_node_fs42 = require("fs");
25530
- var import_promises35 = require("fs/promises");
25531
- var import_node_path45 = __toESM(require("path"), 1);
25848
+ var import_node_fs44 = require("fs");
25849
+ var import_promises37 = require("fs/promises");
25850
+ var import_node_path47 = __toESM(require("path"), 1);
25532
25851
  var import_zod15 = require("zod");
25533
25852
  var SkeletonEstimateRequestSchema = import_zod15.z.object({
25534
25853
  project: import_zod15.z.string().min(1).optional(),
@@ -25567,21 +25886,21 @@ var SkeletonKeypointsUpdateSchema = import_zod15.z.object({
25567
25886
  set: SkeletonSetSchema
25568
25887
  }).strict();
25569
25888
  async function createSkeletonAnimation(manifestPath, request) {
25570
- const root = import_node_path45.default.dirname(import_node_path45.default.resolve(manifestPath));
25571
- const file = import_node_path45.default.resolve(root, request.keypointsFile);
25572
- const relative = import_node_path45.default.relative(root, file);
25573
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path45.default.isAbsolute(relative)) {
25889
+ const root = import_node_path47.default.dirname(import_node_path47.default.resolve(manifestPath));
25890
+ const file = import_node_path47.default.resolve(root, request.keypointsFile);
25891
+ const relative = import_node_path47.default.relative(root, file);
25892
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path47.default.isAbsolute(relative)) {
25574
25893
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
25575
25894
  }
25576
- const existed = (0, import_node_fs42.existsSync)(file);
25895
+ const existed = (0, import_node_fs44.existsSync)(file);
25577
25896
  let previous = null;
25578
25897
  if (request.set) {
25579
25898
  if (existed && !request.overwrite) {
25580
25899
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
25581
25900
  }
25582
- if (existed) previous = await (0, import_promises35.readFile)(file);
25583
- await (0, import_promises35.mkdir)(import_node_path45.default.dirname(file), { recursive: true });
25584
- await (0, import_promises35.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
25901
+ if (existed) previous = await (0, import_promises37.readFile)(file);
25902
+ await (0, import_promises37.mkdir)(import_node_path47.default.dirname(file), { recursive: true });
25903
+ await (0, import_promises37.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
25585
25904
  } else if (!existed) {
25586
25905
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
25587
25906
  }
@@ -25596,7 +25915,7 @@ async function createSkeletonAnimation(manifestPath, request) {
25596
25915
  revision: {
25597
25916
  mode: "animate-skeleton",
25598
25917
  from: request.from,
25599
- keypointsFile: relative.split(import_node_path45.default.sep).join("/"),
25918
+ keypointsFile: relative.split(import_node_path47.default.sep).join("/"),
25600
25919
  direction: request.direction,
25601
25920
  description: request.description,
25602
25921
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -25605,8 +25924,8 @@ async function createSkeletonAnimation(manifestPath, request) {
25605
25924
  });
25606
25925
  } catch (error) {
25607
25926
  if (request.set) {
25608
- if (previous) await (0, import_promises35.writeFile)(file, previous);
25609
- else await (0, import_promises35.rm)(file, { force: true });
25927
+ if (previous) await (0, import_promises37.writeFile)(file, previous);
25928
+ else await (0, import_promises37.rm)(file, { force: true });
25610
25929
  }
25611
25930
  throw error;
25612
25931
  }
@@ -25617,19 +25936,19 @@ async function updateSkeletonKeypoints(ctx, request) {
25617
25936
  if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
25618
25937
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
25619
25938
  if (!file) throw new ManifestEditError(`${key2} is not an animate-skeleton revision`);
25620
- const relative = import_node_path45.default.relative(ctx.loaded.root, file);
25621
- if (relative.startsWith("..") || import_node_path45.default.isAbsolute(relative)) {
25939
+ const relative = import_node_path47.default.relative(ctx.loaded.root, file);
25940
+ if (relative.startsWith("..") || import_node_path47.default.isAbsolute(relative)) {
25622
25941
  throw new ManifestEditError(`${key2}'s keypoints file is outside the project; edit it by hand`);
25623
25942
  }
25624
- const current = (0, import_node_fs42.existsSync)(file) ? sha256(await (0, import_promises35.readFile)(file)) : null;
25943
+ const current = (0, import_node_fs44.existsSync)(file) ? sha256(await (0, import_promises37.readFile)(file)) : null;
25625
25944
  if (current !== request.expectedSha256) {
25626
25945
  throw Object.assign(
25627
- new Error(`${relative.split(import_node_path45.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
25946
+ new Error(`${relative.split(import_node_path47.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
25628
25947
  { status: 409 }
25629
25948
  );
25630
25949
  }
25631
- await (0, import_promises35.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
25632
- return relative.split(import_node_path45.default.sep).join("/");
25950
+ await (0, import_promises37.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
25951
+ return relative.split(import_node_path47.default.sep).join("/");
25633
25952
  }
25634
25953
 
25635
25954
  // src/gallery/edit.ts
@@ -25683,7 +26002,7 @@ function createGalleryEditHandler(opts) {
25683
26002
  const history = /* @__PURE__ */ new Map();
25684
26003
  const manifestOf = async (project2) => {
25685
26004
  try {
25686
- return import_node_path46.default.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
26005
+ return import_node_path48.default.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
25687
26006
  } catch {
25688
26007
  return null;
25689
26008
  }
@@ -25693,7 +26012,7 @@ function createGalleryEditHandler(opts) {
25693
26012
  if (undo.success) {
25694
26013
  const manifestPath2 = await manifestOf(undo.data.project);
25695
26014
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
25696
- const current = await (0, import_promises36.readFile)(manifestPath2, "utf8");
26015
+ const current = await (0, import_promises38.readFile)(manifestPath2, "utf8");
25697
26016
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
25698
26017
  const stack = history.get(manifestPath2) ?? [];
25699
26018
  const last = stack[stack.length - 1];
@@ -25703,17 +26022,17 @@ function createGalleryEditHandler(opts) {
25703
26022
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
25704
26023
  }
25705
26024
  const tmp = manifestPath2 + ".pixelkiln-undo";
25706
- await (0, import_promises36.writeFile)(tmp, last.before);
25707
- await (0, import_promises36.rename)(tmp, manifestPath2);
26025
+ await (0, import_promises38.writeFile)(tmp, last.before);
26026
+ await (0, import_promises38.rename)(tmp, manifestPath2);
25708
26027
  stack.pop();
25709
- log(` manifest edit undone in ${import_node_path46.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
26028
+ log(` manifest edit undone in ${import_node_path48.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
25710
26029
  return opts.reload();
25711
26030
  }
25712
26031
  const manifestPath = await manifestOf(body?.project);
25713
- const before = manifestPath ? await (0, import_promises36.readFile)(manifestPath, "utf8").catch(() => null) : null;
26032
+ const before = manifestPath ? await (0, import_promises38.readFile)(manifestPath, "utf8").catch(() => null) : null;
25714
26033
  const build = await apply(body);
25715
26034
  if (manifestPath && before !== null) {
25716
- const after = await (0, import_promises36.readFile)(manifestPath, "utf8").catch(() => null);
26035
+ const after = await (0, import_promises38.readFile)(manifestPath, "utf8").catch(() => null);
25717
26036
  if (after !== null && after !== before) {
25718
26037
  const stack = history.get(manifestPath) ?? [];
25719
26038
  stack.push({ before, afterSha: sha256(after) });
@@ -25792,7 +26111,7 @@ function createEditApplier(opts, log) {
25792
26111
  } catch (error) {
25793
26112
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
25794
26113
  }
25795
- const written = await saveProjectImage(import_node_path46.default.dirname(import_node_path46.default.resolve(manifestPath2)), upload.data);
26114
+ const written = await saveProjectImage(import_node_path48.default.dirname(import_node_path48.default.resolve(manifestPath2)), upload.data);
25796
26115
  log(` image added: ${written}`);
25797
26116
  return opts.reload();
25798
26117
  }
@@ -25859,7 +26178,7 @@ function createEditApplier(opts, log) {
25859
26178
  }
25860
26179
  const result = await applyManifestEdit(manifestPath, parsed.data);
25861
26180
  if (result.changed) {
25862
- const relative = import_node_path46.default.relative(process.cwd(), result.manifestPath);
26181
+ const relative = import_node_path48.default.relative(process.cwd(), result.manifestPath);
25863
26182
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
25864
26183
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
25865
26184
  }
@@ -25887,7 +26206,7 @@ function describeEdit(edit) {
25887
26206
  // src/gallery/snapshot.ts
25888
26207
  var PROJECT_FILE_TYPE = "application/octet-stream";
25889
26208
  function galleryMediaId(absolutePath) {
25890
- return (0, import_node_crypto8.createHash)("sha256").update(import_node_path47.default.resolve(absolutePath)).digest("hex").slice(0, 24);
26209
+ return (0, import_node_crypto9.createHash)("sha256").update(import_node_path49.default.resolve(absolutePath)).digest("hex").slice(0, 24);
25891
26210
  }
25892
26211
  function galleryMediaRoute(id) {
25893
26212
  return `/media/${id}`;
@@ -25911,9 +26230,9 @@ function describeHistory(media, entry, cacheDir) {
25911
26230
  return (entry.history ?? []).map((generation, i) => {
25912
26231
  const outputs = generation.outputs.map((output) => {
25913
26232
  const mediaType = output.mediaType ?? MediaType.PNG;
25914
- const file = import_node_path47.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
26233
+ const file = import_node_path49.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
25915
26234
  let url = null;
25916
- if ((0, import_node_fs43.existsSync)(file)) {
26235
+ if ((0, import_node_fs45.existsSync)(file)) {
25917
26236
  const id = galleryMediaId(file);
25918
26237
  media.set(id, { path: file, contentType: mediaType });
25919
26238
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -25945,7 +26264,7 @@ function describeHistory(media, entry, cacheDir) {
25945
26264
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
25946
26265
  async function samePixels(a, b) {
25947
26266
  try {
25948
- const [left, right] = await Promise.all([(0, import_promises37.readFile)(a), (0, import_promises37.readFile)(b)]);
26267
+ const [left, right] = await Promise.all([(0, import_promises39.readFile)(a), (0, import_promises39.readFile)(b)]);
25949
26268
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
25950
26269
  const x = decodePng(left);
25951
26270
  const y = decodePng(right);
@@ -26011,7 +26330,7 @@ function describeCharacter(spec, entry) {
26011
26330
  }
26012
26331
  async function fileInfo(absolutePath) {
26013
26332
  try {
26014
- const info = await (0, import_promises37.stat)(absolutePath);
26333
+ const info = await (0, import_promises39.stat)(absolutePath);
26015
26334
  return info.isFile() ? { bytes: info.size, modifiedAt: info.mtime.toISOString() } : null;
26016
26335
  } catch {
26017
26336
  return null;
@@ -26043,10 +26362,10 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
26043
26362
  async function describeQuality(media, root, inspection) {
26044
26363
  const outputPaths = inspection.outputs ?? [inspection.output];
26045
26364
  const outputs = await Promise.all(
26046
- outputPaths.map((file) => describeOutput(media, root, import_node_path47.default.resolve(root, file)))
26365
+ outputPaths.map((file) => describeOutput(media, root, import_node_path49.default.resolve(root, file)))
26047
26366
  );
26048
- const recordPath = import_node_path47.default.resolve(root, inspection.record);
26049
- const recordExists = (0, import_node_fs43.existsSync)(recordPath);
26367
+ const recordPath = import_node_path49.default.resolve(root, inspection.record);
26368
+ const recordExists = (0, import_node_fs45.existsSync)(recordPath);
26050
26369
  let options = null;
26051
26370
  let check = null;
26052
26371
  if (recordExists) {
@@ -26065,7 +26384,7 @@ async function describeQuality(media, root, inspection) {
26065
26384
  return {
26066
26385
  state: inspection.state,
26067
26386
  reason: inspection.reason,
26068
- output: portableOutputPath(import_node_path47.default.resolve(root, inspection.output), root),
26387
+ output: portableOutputPath(import_node_path49.default.resolve(root, inspection.output), root),
26069
26388
  record: portableOutputPath(recordPath, root),
26070
26389
  recordExists,
26071
26390
  outputs,
@@ -26103,9 +26422,9 @@ async function buildGallerySnapshot(opts) {
26103
26422
  const media = /* @__PURE__ */ new Map();
26104
26423
  const plan = await buildPlan(specs, lock);
26105
26424
  const items = [];
26106
- const manifestText = await (0, import_promises37.readFile)(loaded.path, "utf8");
26425
+ const manifestText = await (0, import_promises39.readFile)(loaded.path, "utf8");
26107
26426
  const manifestSha256 = sha256(manifestText);
26108
- const cacheDir = import_node_path47.default.resolve(import_node_path47.default.dirname(opts.lockPath), ".pixelkiln", "cache");
26427
+ const cacheDir = import_node_path49.default.resolve(import_node_path49.default.dirname(opts.lockPath), ".pixelkiln", "cache");
26109
26428
  let rawStyles = {};
26110
26429
  try {
26111
26430
  const raw = JSON.parse(manifestText);
@@ -26129,12 +26448,12 @@ async function buildGallerySnapshot(opts) {
26129
26448
  )
26130
26449
  );
26131
26450
  if (spec.source) {
26132
- const editPath = import_node_path47.default.resolve(root, spec.source);
26451
+ const editPath = import_node_path49.default.resolve(root, spec.source);
26133
26452
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
26134
26453
  const editShas = await Promise.all(
26135
26454
  Array.from({ length: memberCount }, async (_, index) => {
26136
26455
  const file = sourceOutputPath(spec.source, entry, index, root);
26137
- return { file, sha256: (0, import_node_fs43.existsSync)(file) ? await sha256File(file) : null };
26456
+ return { file, sha256: (0, import_node_fs45.existsSync)(file) ? await sha256File(file) : null };
26138
26457
  })
26139
26458
  );
26140
26459
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -26142,7 +26461,7 @@ async function buildGallerySnapshot(opts) {
26142
26461
  const companion = await readHandEditCompanion(editPath);
26143
26462
  if (companion) {
26144
26463
  const projectPath = handEditProjectPath(editPath);
26145
- const project2 = companion.project && (0, import_node_fs43.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
26464
+ const project2 = companion.project && (0, import_node_fs45.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
26146
26465
  let projectUrl = null;
26147
26466
  if (project2) {
26148
26467
  const id = galleryMediaId(projectPath);
@@ -26178,8 +26497,8 @@ async function buildGallerySnapshot(opts) {
26178
26497
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
26179
26498
  }
26180
26499
  } else if (spec.source) {
26181
- outputs = [await describeOutput(media, root, import_node_path47.default.resolve(root, spec.source))];
26182
- } else if (!entry && (0, import_node_fs43.existsSync)(spec.outFile)) {
26500
+ outputs = [await describeOutput(media, root, import_node_path49.default.resolve(root, spec.source))];
26501
+ } else if (!entry && (0, import_node_fs45.existsSync)(spec.outFile)) {
26183
26502
  outputs = [await describeOutput(media, root, spec.outFile)];
26184
26503
  } else {
26185
26504
  outputs = [];
@@ -26383,7 +26702,7 @@ async function buildGallerySnapshot(opts) {
26383
26702
  id: loaded.manifest.name,
26384
26703
  name: loaded.manifest.name,
26385
26704
  manifest: loaded.path,
26386
- lock: import_node_path47.default.resolve(opts.lockPath),
26705
+ lock: import_node_path49.default.resolve(opts.lockPath),
26387
26706
  root,
26388
26707
  provider: loaded.manifest.provider,
26389
26708
  account: null,
@@ -26412,7 +26731,7 @@ async function buildGallerySnapshot(opts) {
26412
26731
  return { snapshot, media };
26413
26732
  }
26414
26733
  async function buildWorkspaceGallerySnapshot(opts) {
26415
- const dir = import_node_path47.default.dirname(import_node_path47.default.resolve(opts.workspacePath));
26734
+ const dir = import_node_path49.default.dirname(import_node_path49.default.resolve(opts.workspacePath));
26416
26735
  const media = /* @__PURE__ */ new Map();
26417
26736
  const projects = [];
26418
26737
  const items = [];
@@ -26457,11 +26776,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
26457
26776
  id: project2.id,
26458
26777
  name: loaded.manifest.name,
26459
26778
  manifest: manifestPath,
26460
- lock: import_node_path47.default.resolve(lockPath),
26779
+ lock: import_node_path49.default.resolve(lockPath),
26461
26780
  root: loaded.root,
26462
26781
  provider: loaded.manifest.provider,
26463
26782
  account: project2.account ?? null,
26464
- manifestSha256: manifestSha256 ?? sha256(await (0, import_promises37.readFile)(manifestPath, "utf8")),
26783
+ manifestSha256: manifestSha256 ?? sha256(await (0, import_promises39.readFile)(manifestPath, "utf8")),
26465
26784
  historyLimit: historyLimit(loaded.manifest),
26466
26785
  entries: Object.keys(lock.entries).length,
26467
26786
  items: projectItems.length,
@@ -26473,8 +26792,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
26473
26792
  id: project2.id,
26474
26793
  name: project2.id,
26475
26794
  manifest: manifestPath,
26476
- lock: import_node_path47.default.resolve(lockPath),
26477
- root: import_node_path47.default.dirname(manifestPath),
26795
+ lock: import_node_path49.default.resolve(lockPath),
26796
+ root: import_node_path49.default.dirname(manifestPath),
26478
26797
  provider: project2.provider,
26479
26798
  account: project2.account ?? null,
26480
26799
  manifestSha256: null,
@@ -26501,7 +26820,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
26501
26820
  version: 1,
26502
26821
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
26503
26822
  project: null,
26504
- workspace: { path: import_node_path47.default.resolve(opts.workspacePath), dir, projects },
26823
+ workspace: { path: import_node_path49.default.resolve(opts.workspacePath), dir, projects },
26505
26824
  filter,
26506
26825
  totals: {
26507
26826
  entries: projects.reduce((sum, project2) => sum + project2.entries, 0),
@@ -26520,13 +26839,13 @@ async function buildWorkspaceGallerySnapshot(opts) {
26520
26839
  }
26521
26840
 
26522
26841
  // src/gallery/page.ts
26523
- var import_node_fs44 = require("fs");
26842
+ var import_node_fs46 = require("fs");
26524
26843
 
26525
26844
  // src/gallery/client-bundle.ts
26526
- var import_node_module2 = require("module");
26527
- var import_node_url3 = require("url");
26528
- function bundleGalleryClient(entry = (0, import_node_url3.fileURLToPath)(new URL("./client/src/main.ts", importMetaUrl))) {
26529
- const esbuild = (0, import_node_module2.createRequire)(importMetaUrl)("esbuild");
26845
+ var import_node_module3 = require("module");
26846
+ var import_node_url4 = require("url");
26847
+ function bundleGalleryClient(entry = (0, import_node_url4.fileURLToPath)(new URL("./client/src/main.ts", importMetaUrl))) {
26848
+ const esbuild = (0, import_node_module3.createRequire)(importMetaUrl)("esbuild");
26530
26849
  const result = esbuild.buildSync({
26531
26850
  entryPoints: [entry],
26532
26851
  bundle: true,
@@ -26560,8 +26879,8 @@ var client;
26560
26879
  function clientAssets() {
26561
26880
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
26562
26881
  client ??= {
26563
- css: (0, import_node_fs44.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
26564
- js: (0, import_node_fs44.existsSync)(prebuilt) ? (0, import_node_fs44.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
26882
+ css: (0, import_node_fs46.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
26883
+ js: (0, import_node_fs46.existsSync)(prebuilt) ? (0, import_node_fs46.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
26565
26884
  };
26566
26885
  return client;
26567
26886
  }
@@ -26703,11 +27022,11 @@ var EDITOR_PIN = pin_default;
26703
27022
  var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download";
26704
27023
 
26705
27024
  // src/editor/install.ts
26706
- var import_node_crypto9 = require("crypto");
26707
- var import_node_fs45 = require("fs");
26708
- var import_promises38 = require("fs/promises");
27025
+ var import_node_crypto10 = require("crypto");
27026
+ var import_node_fs47 = require("fs");
27027
+ var import_promises40 = require("fs/promises");
26709
27028
  var import_node_os4 = __toESM(require("os"), 1);
26710
- var import_node_path48 = __toESM(require("path"), 1);
27029
+ var import_node_path50 = __toESM(require("path"), 1);
26711
27030
  var EditorInstallError = class extends Error {
26712
27031
  constructor(message6, file) {
26713
27032
  super(message6);
@@ -26718,15 +27037,15 @@ var EditorInstallError = class extends Error {
26718
27037
  };
26719
27038
  function editorToolsRoot() {
26720
27039
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
26721
- if (override) return import_node_path48.default.resolve(override);
26722
- if (process.platform === "darwin") return import_node_path48.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
27040
+ if (override) return import_node_path50.default.resolve(override);
27041
+ if (process.platform === "darwin") return import_node_path50.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
26723
27042
  if (process.platform === "win32") {
26724
- return import_node_path48.default.join(process.env.LOCALAPPDATA ?? import_node_path48.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
27043
+ return import_node_path50.default.join(process.env.LOCALAPPDATA ?? import_node_path50.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
26725
27044
  }
26726
- return import_node_path48.default.join(process.env.XDG_CACHE_HOME ?? import_node_path48.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
27045
+ return import_node_path50.default.join(process.env.XDG_CACHE_HOME ?? import_node_path50.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
26727
27046
  }
26728
27047
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
26729
- return import_node_path48.default.join(root, "pixelorama", pin.release ?? "unpublished");
27048
+ return import_node_path50.default.join(root, "pixelorama", pin.release ?? "unpublished");
26730
27049
  }
26731
27050
  function editorBaseUrl(pin = EDITOR_PIN) {
26732
27051
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -26736,7 +27055,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
26736
27055
  }
26737
27056
  async function sha256Of(file) {
26738
27057
  try {
26739
- return (0, import_node_crypto9.createHash)("sha256").update(await (0, import_promises38.readFile)(file)).digest("hex");
27058
+ return (0, import_node_crypto10.createHash)("sha256").update(await (0, import_promises40.readFile)(file)).digest("hex");
26740
27059
  } catch {
26741
27060
  return null;
26742
27061
  }
@@ -26749,8 +27068,8 @@ async function editorStatus(opts = {}) {
26749
27068
  let totalBytes = 0;
26750
27069
  for (const [name, expected] of Object.entries(pin.files)) {
26751
27070
  totalBytes += expected.bytes;
26752
- const file = import_node_path48.default.join(dir, name);
26753
- const info = (0, import_node_fs45.existsSync)(file) ? await (0, import_promises38.stat)(file).catch(() => null) : null;
27071
+ const file = import_node_path50.default.join(dir, name);
27072
+ const info = (0, import_node_fs47.existsSync)(file) ? await (0, import_promises40.stat)(file).catch(() => null) : null;
26754
27073
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
26755
27074
  installedBytes += expected.bytes;
26756
27075
  } else {
@@ -26779,7 +27098,7 @@ async function installEditor(opts = {}) {
26779
27098
  );
26780
27099
  }
26781
27100
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
26782
- await (0, import_promises38.mkdir)(dir, { recursive: true });
27101
+ await (0, import_promises40.mkdir)(dir, { recursive: true });
26783
27102
  const downloaded = [];
26784
27103
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
26785
27104
  let fetchedBytes = before.installedBytes;
@@ -26803,17 +27122,17 @@ async function installEditor(opts = {}) {
26803
27122
  if (bytes.length !== expected.bytes) {
26804
27123
  throw new EditorInstallError(`${name}: expected ${expected.bytes} bytes, got ${bytes.length}`, name);
26805
27124
  }
26806
- const digest2 = (0, import_node_crypto9.createHash)("sha256").update(bytes).digest("hex");
27125
+ const digest2 = (0, import_node_crypto10.createHash)("sha256").update(bytes).digest("hex");
26807
27126
  if (digest2 !== expected.sha256) {
26808
27127
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
26809
27128
  }
26810
- const final = import_node_path48.default.join(dir, name);
27129
+ const final = import_node_path50.default.join(dir, name);
26811
27130
  const tmp = `${final}.${process.pid}.part`;
26812
27131
  try {
26813
- await (0, import_promises38.writeFile)(tmp, bytes);
26814
- await (0, import_promises38.rename)(tmp, final);
27132
+ await (0, import_promises40.writeFile)(tmp, bytes);
27133
+ await (0, import_promises40.rename)(tmp, final);
26815
27134
  } finally {
26816
- await (0, import_promises38.rm)(tmp, { force: true });
27135
+ await (0, import_promises40.rm)(tmp, { force: true });
26817
27136
  }
26818
27137
  fetchedBytes += bytes.length;
26819
27138
  downloaded.push(name);
@@ -26853,12 +27172,12 @@ var EDITOR_CONTENT_TYPES = {
26853
27172
  ".json": "application/json; charset=utf-8"
26854
27173
  };
26855
27174
  function editorContentType(name) {
26856
- return EDITOR_CONTENT_TYPES[import_node_path48.default.extname(name).toLowerCase()] ?? null;
27175
+ return EDITOR_CONTENT_TYPES[import_node_path50.default.extname(name).toLowerCase()] ?? null;
26857
27176
  }
26858
27177
 
26859
27178
  // src/gallery/editor.ts
26860
- var import_promises39 = require("fs/promises");
26861
- var import_node_path49 = __toESM(require("path"), 1);
27179
+ var import_promises41 = require("fs/promises");
27180
+ var import_node_path51 = __toESM(require("path"), 1);
26862
27181
  function editorRoute(release, name = "index.html") {
26863
27182
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
26864
27183
  }
@@ -26931,7 +27250,7 @@ function createGalleryEditorHandlers(opts = {}) {
26931
27250
  if (!status.installed) return null;
26932
27251
  let bytes;
26933
27252
  try {
26934
- bytes = await (0, import_promises39.readFile)(import_node_path49.default.join(dir, name));
27253
+ bytes = await (0, import_promises41.readFile)(import_node_path51.default.join(dir, name));
26935
27254
  } catch {
26936
27255
  verified = null;
26937
27256
  return null;
@@ -26946,9 +27265,9 @@ function createGalleryEditorHandlers(opts = {}) {
26946
27265
  }
26947
27266
 
26948
27267
  // src/gallery/server.ts
26949
- var import_node_crypto10 = require("crypto");
27268
+ var import_node_crypto11 = require("crypto");
26950
27269
  var import_node_http2 = require("http");
26951
- var import_promises40 = require("fs/promises");
27270
+ var import_promises42 = require("fs/promises");
26952
27271
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
26953
27272
  var EDITOR_CSP = [
26954
27273
  "default-src 'self'",
@@ -26976,7 +27295,7 @@ async function readJsonBody(req) {
26976
27295
  async function serveGallery(opts) {
26977
27296
  const log = opts.onProgress ?? (() => {
26978
27297
  });
26979
- const session = opts.edit || opts.generate || opts.editor || opts.skeleton || opts.price ? (0, import_node_crypto10.randomBytes)(16).toString("hex") : null;
27298
+ const session = opts.edit || opts.generate || opts.editor || opts.skeleton || opts.price ? (0, import_node_crypto11.randomBytes)(16).toString("hex") : null;
26980
27299
  let media = /* @__PURE__ */ new Map();
26981
27300
  let loading = null;
26982
27301
  const reviewAssets = /* @__PURE__ */ new Map();
@@ -27129,7 +27448,7 @@ async function serveGallery(opts) {
27129
27448
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
27130
27449
  if (!asset) return fail(404, "no such review asset");
27131
27450
  try {
27132
- const bytes = await (0, import_promises40.readFile)(asset.path);
27451
+ const bytes = await (0, import_promises42.readFile)(asset.path);
27133
27452
  res.writeHead(200, {
27134
27453
  "Content-Type": asset.contentType,
27135
27454
  "Cache-Control": "no-store",
@@ -27180,7 +27499,7 @@ async function serveGallery(opts) {
27180
27499
  try {
27181
27500
  if (url2.pathname === "/") {
27182
27501
  const { snapshot } = await load();
27183
- const nonce = (0, import_node_crypto10.randomBytes)(16).toString("base64");
27502
+ const nonce = (0, import_node_crypto11.randomBytes)(16).toString("base64");
27184
27503
  res.writeHead(200, {
27185
27504
  "Content-Type": "text/html; charset=utf-8",
27186
27505
  "Cache-Control": "no-store",
@@ -27212,7 +27531,7 @@ async function serveGallery(opts) {
27212
27531
  if (!asset) return fail(404, "no such gallery media");
27213
27532
  let bytes;
27214
27533
  try {
27215
- bytes = await (0, import_promises40.readFile)(asset.path);
27534
+ bytes = await (0, import_promises42.readFile)(asset.path);
27216
27535
  } catch {
27217
27536
  return fail(404, "gallery media is no longer on disk; refresh the page");
27218
27537
  }
@@ -27255,7 +27574,7 @@ async function serveGallery(opts) {
27255
27574
  }
27256
27575
 
27257
27576
  // src/gallery/generate.ts
27258
- var import_node_crypto11 = require("crypto");
27577
+ var import_node_crypto12 = require("crypto");
27259
27578
  var import_zod17 = require("zod");
27260
27579
  var GenerateRequestSchema = import_zod17.z.object({
27261
27580
  project: import_zod17.z.string().min(1).optional(),
@@ -27555,7 +27874,7 @@ function createGenerateHandlers(opts) {
27555
27874
  }
27556
27875
  }
27557
27876
  const job = {
27558
- id: (0, import_node_crypto11.randomBytes)(8).toString("hex"),
27877
+ id: (0, import_node_crypto12.randomBytes)(8).toString("hex"),
27559
27878
  project: request.project ?? null,
27560
27879
  keys: request.keys,
27561
27880
  mode: request.refresh ? "refresh" : request.resume ? "resume" : request.restore ? "restore" : request.revert !== void 0 ? "revert" : "generate",
@@ -27622,19 +27941,19 @@ function createGenerateHandlers(opts) {
27622
27941
  }
27623
27942
 
27624
27943
  // src/pipeline/salvage.ts
27625
- var import_promises41 = require("fs/promises");
27626
- var import_node_fs46 = require("fs");
27627
- var import_node_path50 = __toESM(require("path"), 1);
27944
+ var import_promises43 = require("fs/promises");
27945
+ var import_node_fs48 = require("fs");
27946
+ var import_node_path52 = __toESM(require("path"), 1);
27628
27947
  function providerClaimId(provider, objectId) {
27629
27948
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
27630
27949
  }
27631
27950
  async function loadClaims(lockPaths, opts = {}) {
27632
27951
  const claimed = /* @__PURE__ */ new Set();
27633
27952
  for (const p of lockPaths) {
27634
- if (!(0, import_node_fs46.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
27953
+ if (!(0, import_node_fs48.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
27635
27954
  let parsed;
27636
27955
  try {
27637
- parsed = parseLock(JSON.parse(await (0, import_promises41.readFile)(p, "utf8")));
27956
+ parsed = parseLock(JSON.parse(await (0, import_promises43.readFile)(p, "utf8")));
27638
27957
  } catch {
27639
27958
  throw new Error(`Claim lockfile is malformed: ${p}`);
27640
27959
  }
@@ -27738,20 +28057,20 @@ function matchOrphanStyle(prompt, manifest) {
27738
28057
  return matchStyleByPattern(prompt, manifest);
27739
28058
  }
27740
28059
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
27741
- const own = import_node_path50.default.resolve(ownManifestPath);
28060
+ const own = import_node_path52.default.resolve(ownManifestPath);
27742
28061
  const siblingManifestPaths = [
27743
28062
  .../* @__PURE__ */ new Set([
27744
28063
  ...workspaceManifestPaths,
27745
- ...claimPaths.map((c) => import_node_path50.default.join(import_node_path50.default.dirname(import_node_path50.default.resolve(c)), "pixelkiln.manifest.json"))
28064
+ ...claimPaths.map((c) => import_node_path52.default.join(import_node_path52.default.dirname(import_node_path52.default.resolve(c)), "pixelkiln.manifest.json"))
27746
28065
  ])
27747
28066
  ];
27748
28067
  const siblings = [];
27749
28068
  for (const siblingManifestPath of siblingManifestPaths) {
27750
- if (import_node_path50.default.resolve(siblingManifestPath) === own) continue;
27751
- if (!(0, import_node_fs46.existsSync)(siblingManifestPath)) continue;
28069
+ if (import_node_path52.default.resolve(siblingManifestPath) === own) continue;
28070
+ if (!(0, import_node_fs48.existsSync)(siblingManifestPath)) continue;
27752
28071
  try {
27753
28072
  const { manifest } = await loadManifest(siblingManifestPath);
27754
- siblings.push({ label: import_node_path50.default.basename(import_node_path50.default.dirname(siblingManifestPath)), manifest });
28073
+ siblings.push({ label: import_node_path52.default.basename(import_node_path52.default.dirname(siblingManifestPath)), manifest });
27755
28074
  } catch {
27756
28075
  }
27757
28076
  }
@@ -27871,8 +28190,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
27871
28190
  }
27872
28191
 
27873
28192
  // src/pick/salvage-server.ts
27874
- var import_promises42 = require("fs/promises");
27875
- var import_node_path51 = __toESM(require("path"), 1);
28193
+ var import_promises44 = require("fs/promises");
28194
+ var import_node_path53 = __toESM(require("path"), 1);
27876
28195
 
27877
28196
  // src/pick/salvage-sheet.ts
27878
28197
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -28038,7 +28357,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28038
28357
  });
28039
28358
  const html = renderSalvageSheet(orphans, {
28040
28359
  styleId: ctx.styleId,
28041
- importDir: import_node_path51.default.relative(process.cwd(), ctx.importDir) || "."
28360
+ importDir: import_node_path53.default.relative(process.cwd(), ctx.importDir) || "."
28042
28361
  });
28043
28362
  const byId = new Map(orphans.map((o) => [o.id, o]));
28044
28363
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -28094,10 +28413,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28094
28413
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
28095
28414
  decodePng(buf);
28096
28415
  const assetId = idFromPrompt(orphan.prompt, taken);
28097
- const rel = import_node_path51.default.join("_salvaged", `${assetId}.png`);
28098
- const outFile = import_node_path51.default.resolve(ctx.importDir, rel);
28099
- await (0, import_promises42.mkdir)(import_node_path51.default.dirname(outFile), { recursive: true });
28100
- await (0, import_promises42.writeFile)(outFile, buf);
28416
+ const rel = import_node_path53.default.join("_salvaged", `${assetId}.png`);
28417
+ const outFile = import_node_path53.default.resolve(ctx.importDir, rel);
28418
+ await (0, import_promises44.mkdir)(import_node_path53.default.dirname(outFile), { recursive: true });
28419
+ await (0, import_promises44.writeFile)(outFile, buf);
28101
28420
  ctx.manifest.assets[assetId] = {
28102
28421
  prompt: orphan.prompt,
28103
28422
  promptByStyle: {},
@@ -28129,7 +28448,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28129
28448
  sourceUrl: durableSource,
28130
28449
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
28131
28450
  outputs: [{
28132
- path: portableOutputPath(outFile, import_node_path51.default.dirname(ctx.manifestPath)),
28451
+ path: portableOutputPath(outFile, import_node_path53.default.dirname(ctx.manifestPath)),
28133
28452
  sha256: sha256(buf)
28134
28453
  }],
28135
28454
  submittedAt: orphan.createdAt,
@@ -28153,9 +28472,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
28153
28472
  }
28154
28473
  }
28155
28474
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
28156
- const raw = JSON.parse(await (0, import_promises42.readFile)(ctx.manifestPath, "utf8"));
28475
+ const raw = JSON.parse(await (0, import_promises44.readFile)(ctx.manifestPath, "utf8"));
28157
28476
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
28158
- await (0, import_promises42.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
28477
+ await (0, import_promises44.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
28159
28478
  await saveLock(ctx.lockPath, ctx.lock);
28160
28479
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
28161
28480
  return result;
@@ -28275,6 +28594,12 @@ async function workspaceStatus(ws, dir) {
28275
28594
  CHARACTER_DIRECTIONS_4,
28276
28595
  CHARACTER_DIRECTIONS_8,
28277
28596
  CHARACTER_PROPORTION_PRESETS,
28597
+ CODEX_CAMERAS,
28598
+ CODEX_ID,
28599
+ CODEX_INSTALL,
28600
+ CODEX_PACKAGE,
28601
+ CODEX_REPOSITORY,
28602
+ CODEX_TUNE_KEYS,
28278
28603
  CharacterAnimationModeSchema,
28279
28604
  CharacterAnimationSchema,
28280
28605
  CharacterAttachSchema,
@@ -28414,6 +28739,7 @@ async function workspaceStatus(ws, dir) {
28414
28739
  applyManifestEdit,
28415
28740
  applyTags,
28416
28741
  approveQualityRecord,
28742
+ assertFreshOutputs,
28417
28743
  assetInStyle,
28418
28744
  auditStyle,
28419
28745
  availableProviders,
@@ -28427,6 +28753,7 @@ async function workspaceStatus(ws, dir) {
28427
28753
  cacheFileName,
28428
28754
  candidateCount,
28429
28755
  characterDirections,
28756
+ checkCodexRecipe,
28430
28757
  checkExportBytes,
28431
28758
  checkPixelfxRecipe,
28432
28759
  checkQualityBaseline,
@@ -28472,6 +28799,7 @@ async function workspaceStatus(ws, dir) {
28472
28799
  fetchWithRetry,
28473
28800
  findOrphans,
28474
28801
  fontOutputPaths,
28802
+ formatCodexEffects,
28475
28803
  formatCost,
28476
28804
  formatPixelfxEffects,
28477
28805
  frameSetFps,
@@ -28514,14 +28842,18 @@ async function workspaceStatus(ws, dir) {
28514
28842
  isometricTileCost,
28515
28843
  layerOffsetFor,
28516
28844
  listBundledRecipes,
28845
+ listCodexEffects,
28517
28846
  listPixelfxEffects,
28518
28847
  loadClaims,
28848
+ loadCodex,
28519
28849
  loadLock,
28520
28850
  loadManifest,
28521
28851
  loadPixelfx,
28522
28852
  loadSiblingManifests,
28523
28853
  loadWorkspace,
28854
+ localSheet,
28524
28855
  lockKey,
28856
+ makeCodexVfx,
28525
28857
  makePixelfxVfx,
28526
28858
  makeVfx,
28527
28859
  makeVfxWithArtist,
@@ -28573,6 +28905,7 @@ async function workspaceStatus(ws, dir) {
28573
28905
  pixMiniMaxCost,
28574
28906
  pixelateFile,
28575
28907
  pixelfxSheet,
28908
+ planCodex,
28576
28909
  pngFilesAt,
28577
28910
  pngSize,
28578
28911
  poll,
@@ -28590,6 +28923,7 @@ async function workspaceStatus(ws, dir) {
28590
28923
  qualityRecordPath,
28591
28924
  quantizeToPalette,
28592
28925
  readArtifactBundleManifest,
28926
+ readCodexRecipe,
28593
28927
  readHandEditCompanion,
28594
28928
  readPixelfxRecipe,
28595
28929
  readQualityBaseline,
@@ -28605,6 +28939,7 @@ async function workspaceStatus(ws, dir) {
28605
28939
  registerProvider,
28606
28940
  remove,
28607
28941
  renderAsepriteSheet,
28942
+ renderCodex,
28608
28943
  renderGallery,
28609
28944
  renderGodotSpriteFrames,
28610
28945
  renderPixelfx,
@@ -28699,6 +29034,7 @@ async function workspaceStatus(ws, dir) {
28699
29034
  workspaceClaims,
28700
29035
  workspaceStatus,
28701
29036
  writeArtifactBundle,
29037
+ writeLocalVfx,
28702
29038
  writeManagedArtifactBundle
28703
29039
  });
28704
29040
  //# sourceMappingURL=index.cjs.map