pixelkiln 0.93.0 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -283,12 +283,12 @@ var AssetVfxSchema = z.object({
283
283
  artist: z.enum(["lite", "pro"]).optional()
284
284
  }).strict().superRefine((vfx, context) => {
285
285
  if (vfx.description !== void 0) {
286
- for (const key of ["preset", "recipe", "parts", "fps"]) {
287
- if (vfx[key] !== void 0) {
286
+ for (const key2 of ["preset", "recipe", "parts", "fps"]) {
287
+ if (vfx[key2] !== void 0) {
288
288
  context.addIssue({
289
289
  code: z.ZodIssueCode.custom,
290
- message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key}; use a description or the workbench's preset/recipe/parts/fps, not both`,
291
- path: [key]
290
+ message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key2}; use a description or the workbench's preset/recipe/parts/fps, not both`,
291
+ path: [key2]
292
292
  });
293
293
  }
294
294
  }
@@ -407,18 +407,18 @@ var CharacterAnimationSchema = z.object({
407
407
  context.addIssue({ code: z.ZodIssueCode.custom, message: "a skeleton-v3 loop from a sentence takes 3 to 15 frames", path: ["frames"] });
408
408
  }
409
409
  const mode2 = animation.mode ?? (animation.template ? "template" : "v3");
410
- for (const key of ["startFrame", "endFrame", "enhancePrompt"]) {
411
- if (animation[key] !== void 0 && mode2 !== "v3") {
410
+ for (const key2 of ["startFrame", "endFrame", "enhancePrompt"]) {
411
+ if (animation[key2] !== void 0 && mode2 !== "v3") {
412
412
  context.addIssue({
413
413
  code: z.ZodIssueCode.custom,
414
- message: `${key} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
415
- path: [key]
414
+ message: `${key2} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
415
+ path: [key2]
416
416
  });
417
417
  }
418
418
  }
419
- for (const key of ["outline", "shading", "detail"]) {
420
- if (animation[key] !== void 0 && mode2 !== "template") {
421
- context.addIssue({ code: z.ZodIssueCode.custom, message: `${key} overrides apply to template loops only`, path: [key] });
419
+ for (const key2 of ["outline", "shading", "detail"]) {
420
+ if (animation[key2] !== void 0 && mode2 !== "template") {
421
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `${key2} overrides apply to template loops only`, path: [key2] });
422
422
  }
423
423
  }
424
424
  if (animation.template && animation.mode && animation.mode !== "template" && animation.mode !== "skeleton-v3") {
@@ -1107,6 +1107,46 @@ var InheritedStyleSchema = StyleObjectSchema.partial().extend({
1107
1107
  quality: QualityProfileObjectSchema.partial().optional()
1108
1108
  }).strict();
1109
1109
  var StyleInputSchema = z.union([StyleSchema, InheritedStyleSchema]);
1110
+ var AssetDeriveSchema = z.object({
1111
+ /** Another asset in the same style whose output is the input. */
1112
+ from: z.string().min(1).optional(),
1113
+ /** A committed PNG, relative to the manifest, as the input. */
1114
+ file: z.string().min(1).optional(),
1115
+ transform: z.enum(["recolor", "palette-snap", "scale"]),
1116
+ /** recolor: exact replacements, `#rrggbb` to `#rrggbb`. Unmapped colors and every alpha value stay. */
1117
+ map: z.record(HexColorSchema, HexColorSchema).optional(),
1118
+ /** palette-snap: the closed palette every visible pixel moves to. */
1119
+ palette: z.array(HexColorSchema).min(2).max(256).optional(),
1120
+ /** scale: the output size. */
1121
+ width: z.number().int().min(1).max(4096).optional(),
1122
+ height: z.number().int().min(1).max(4096).optional(),
1123
+ /** scale: `nearest` (default) keeps hard edges; `box` averages the covered pixels. */
1124
+ mode: z.enum(["nearest", "box"]).optional()
1125
+ }).strict().superRefine((derive, context) => {
1126
+ const issue = (message6, path42) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path42] });
1127
+ if (Boolean(derive.from) === Boolean(derive.file)) {
1128
+ issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1129
+ }
1130
+ const own = {
1131
+ recolor: ["map"],
1132
+ "palette-snap": ["palette"],
1133
+ scale: ["width", "height", "mode"]
1134
+ }[derive.transform];
1135
+ for (const field of ["map", "palette", "width", "height", "mode"]) {
1136
+ if (derive[field] !== void 0 && !own.includes(field)) {
1137
+ issue(`${field} does not apply to ${derive.transform}`, field);
1138
+ }
1139
+ }
1140
+ if (derive.transform === "recolor" && !Object.keys(derive.map ?? {}).length) issue("recolor needs a non-empty map", "map");
1141
+ if (derive.transform === "palette-snap" && !derive.palette) issue("palette-snap needs a palette", "palette");
1142
+ if (derive.transform === "scale" && (!derive.width || !derive.height)) issue("scale needs width and height", "width");
1143
+ });
1144
+ var AssetExternalSchema = z.object({
1145
+ /** The command that rebuilds the file. Documentation and identity; never executed. */
1146
+ builder: z.string().min(1),
1147
+ /** Files the builder reads, relative to the manifest. Their hashes are part of the asset's identity. */
1148
+ inputs: z.array(z.string().min(1)).optional()
1149
+ }).strict();
1110
1150
  var AssetSchema = z.object({
1111
1151
  /** The subject. Style wrapping comes from the style's prefix/suffix. Only a `mirror` may leave it out. */
1112
1152
  prompt: z.string().optional(),
@@ -1238,6 +1278,10 @@ var AssetSchema = z.object({
1238
1278
  * (a sword hand, a parted fringe) comes out the other way round.
1239
1279
  */
1240
1280
  mirror: z.string().min(1).optional(),
1281
+ /** Made from existing pixels by a local transform; see AssetDeriveSchema. Free; the provider is never called. */
1282
+ derive: AssetDeriveSchema.optional(),
1283
+ /** Built by a tool outside pixelkiln; see AssetExternalSchema. Never generated. */
1284
+ external: AssetExternalSchema.optional(),
1241
1285
  /**
1242
1286
  * Generated output role to place in `cell` when this asset expands to
1243
1287
  * several files. Omit for ordinary single-output assets. A structural set
@@ -1277,7 +1321,7 @@ var AssetSchema = z.object({
1277
1321
  path: ["revision"]
1278
1322
  });
1279
1323
  }
1280
- const shapes = [asset.revision && "revision", asset.state && "state", asset.animation && "animation", asset.mirror && "mirror", asset.batch && "batch", asset.portrait && "portrait", asset.outfit && "outfit", asset.scene && "scene", asset.vfx && "vfx", asset.connect && "connect"].filter(Boolean);
1324
+ const shapes = [asset.revision && "revision", asset.state && "state", asset.animation && "animation", asset.mirror && "mirror", asset.derive && "derive", asset.external && "external", asset.batch && "batch", asset.portrait && "portrait", asset.outfit && "outfit", asset.scene && "scene", asset.vfx && "vfx", asset.connect && "connect"].filter(Boolean);
1281
1325
  if (shapes.length > 1) {
1282
1326
  context.addIssue({
1283
1327
  code: z.ZodIssueCode.custom,
@@ -1285,6 +1329,15 @@ var AssetSchema = z.object({
1285
1329
  path: [shapes[1]]
1286
1330
  });
1287
1331
  }
1332
+ for (const shape of ["derive", "external"]) {
1333
+ if (asset[shape] && (asset.source || Object.keys(asset.sourceByStyle).length)) {
1334
+ context.addIssue({
1335
+ code: z.ZodIssueCode.custom,
1336
+ message: shape === "derive" ? "a derived asset is made from its derive source; it cannot also declare a source" : "an external asset is built outside pixelkiln; it cannot also declare a source",
1337
+ path: [shape]
1338
+ });
1339
+ }
1340
+ }
1288
1341
  if (asset.mirror && (asset.source || Object.keys(asset.sourceByStyle).length)) {
1289
1342
  context.addIssue({
1290
1343
  code: z.ZodIssueCode.custom,
@@ -1292,13 +1345,20 @@ var AssetSchema = z.object({
1292
1345
  path: ["mirror"]
1293
1346
  });
1294
1347
  }
1295
- if (asset.prompt === void 0 && !asset.mirror && !asset.portrait && !asset.outfit && !asset.animation?.template && !asset.vfx) {
1348
+ if (asset.prompt === void 0 && !asset.mirror && !asset.derive && !asset.external && !asset.portrait && !asset.outfit && !asset.animation?.template && !asset.vfx) {
1296
1349
  context.addIssue({
1297
1350
  code: z.ZodIssueCode.custom,
1298
1351
  message: "Required",
1299
1352
  path: ["prompt"]
1300
1353
  });
1301
1354
  }
1355
+ if ((asset.derive || asset.external) && (asset.reference || asset.concept)) {
1356
+ context.addIssue({
1357
+ code: z.ZodIssueCode.custom,
1358
+ message: "a derived or external asset is not drawn by a provider, so it takes no reference or concept image",
1359
+ path: [asset.reference ? "reference" : "concept"]
1360
+ });
1361
+ }
1302
1362
  if (asset.reference && (asset.state || asset.animation || asset.mirror || asset.portrait || asset.outfit)) {
1303
1363
  context.addIssue({
1304
1364
  code: z.ZodIssueCode.custom,
@@ -1590,6 +1650,24 @@ var LockEntrySchema = z.object({
1590
1650
  source: z.string().min(1),
1591
1651
  note: z.string().optional(),
1592
1652
  importedAt: z.string()
1653
+ }).strict().optional(),
1654
+ /**
1655
+ * For a derived asset: what it was made from, and a hash of that input when
1656
+ * this was made. Compared with the input's current bytes by the plan, so a
1657
+ * changed source re-derives it for free. Absent on every other entry.
1658
+ */
1659
+ derive: z.object({
1660
+ sourceAssetId: z.string().min(1).optional(),
1661
+ sourceFile: z.string().min(1).optional(),
1662
+ sourceSha256: z.string().regex(/^[0-9a-f]{64}$/)
1663
+ }).strict().optional(),
1664
+ /**
1665
+ * For an external asset: the builder command and the hashes of the declared
1666
+ * inputs when the file was recorded. Absent on every other entry.
1667
+ */
1668
+ external: z.object({
1669
+ builder: z.string().min(1),
1670
+ inputs: z.array(z.object({ path: z.string(), sha256: z.string().nullable() }).strict()).default([])
1593
1671
  }).strict().optional()
1594
1672
  });
1595
1673
  var LockSchema = z.object({
@@ -2139,9 +2217,9 @@ var PixelLabClient = class {
2139
2217
  apiKey;
2140
2218
  http;
2141
2219
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
2142
- async request(path39, init) {
2220
+ async request(path42, init) {
2143
2221
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
2144
- const res = await this.http(`${BASE}${path39}`, {
2222
+ const res = await this.http(`${BASE}${path42}`, {
2145
2223
  ...init,
2146
2224
  headers: {
2147
2225
  Authorization: auth,
@@ -2152,13 +2230,13 @@ var PixelLabClient = class {
2152
2230
  const text = await res.text();
2153
2231
  if (!res.ok) {
2154
2232
  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' : "";
2155
- throw new PixelLabError(`${init?.method ?? "GET"} ${path39} \u2192 ${res.status}${hint}`, res.status, text);
2233
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path42} \u2192 ${res.status}${hint}`, res.status, text);
2156
2234
  }
2157
2235
  if (!text) return {};
2158
2236
  try {
2159
2237
  return JSON.parse(text);
2160
2238
  } catch {
2161
- throw new Error(`${init?.method ?? "GET"} ${path39} returned invalid JSON`);
2239
+ throw new Error(`${init?.method ?? "GET"} ${path42} returned invalid JSON`);
2162
2240
  }
2163
2241
  }
2164
2242
  async balance() {
@@ -2611,10 +2689,10 @@ var PixelLabClient = class {
2611
2689
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
2612
2690
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
2613
2691
  const south = args.reference?.south;
2614
- let path39;
2692
+ let path42;
2615
2693
  let body;
2616
2694
  if (args.mode === "v3") {
2617
- path39 = "/create-character-v3";
2695
+ path42 = "/create-character-v3";
2618
2696
  body = {
2619
2697
  description: args.description,
2620
2698
  image_size: imageSize,
@@ -2628,7 +2706,7 @@ var PixelLabClient = class {
2628
2706
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
2629
2707
  };
2630
2708
  } else if (args.mode === "pro-flash") {
2631
- path39 = "/create-character-pro-flash";
2709
+ path42 = "/create-character-pro-flash";
2632
2710
  const traits = args.styleTraits;
2633
2711
  body = {
2634
2712
  description: args.description,
@@ -2652,7 +2730,7 @@ var PixelLabClient = class {
2652
2730
  } : {}
2653
2731
  };
2654
2732
  } else if (args.mode === "pro") {
2655
- path39 = "/create-character-pro";
2733
+ path42 = "/create-character-pro";
2656
2734
  body = {
2657
2735
  description: args.description,
2658
2736
  image_size: imageSize,
@@ -2666,7 +2744,7 @@ var PixelLabClient = class {
2666
2744
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
2667
2745
  };
2668
2746
  } else {
2669
- path39 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
2747
+ path42 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
2670
2748
  body = {
2671
2749
  description: args.description,
2672
2750
  image_size: imageSize,
@@ -2684,8 +2762,8 @@ var PixelLabClient = class {
2684
2762
  };
2685
2763
  }
2686
2764
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
2687
- const raw = await this.request(path39, { method: "POST", body: JSON.stringify(body) });
2688
- return validateResponse(CharacterSubmitSchema, raw, path39.slice(1));
2765
+ const raw = await this.request(path42, { method: "POST", body: JSON.stringify(body) });
2766
+ return validateResponse(CharacterSubmitSchema, raw, path42.slice(1));
2689
2767
  }
2690
2768
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
2691
2769
  async createCharacterState(args) {
@@ -3414,13 +3492,13 @@ var PixelLabClient = class {
3414
3492
  }
3415
3493
  };
3416
3494
  function clientFromEnv() {
3417
- const key = process.env.PIXELLAB_API_KEY;
3418
- if (!key) {
3495
+ const key2 = process.env.PIXELLAB_API_KEY;
3496
+ if (!key2) {
3419
3497
  throw new Error(
3420
3498
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
3421
3499
  );
3422
3500
  }
3423
- return new PixelLabClient(key);
3501
+ return new PixelLabClient(key2);
3424
3502
  }
3425
3503
 
3426
3504
  // src/open.ts
@@ -3760,14 +3838,14 @@ function extractPalette(png, topN = 8, alphaThreshold = 128) {
3760
3838
  const alpha = png.pixels[i + 3];
3761
3839
  if (alpha < alphaThreshold) continue;
3762
3840
  opaque++;
3763
- const key = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
3764
- counts.set(key, (counts.get(key) ?? 0) + 1);
3841
+ const key2 = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
3842
+ counts.set(key2, (counts.get(key2) ?? 0) + 1);
3765
3843
  }
3766
3844
  if (opaque === 0) return [];
3767
- return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key, n]) => ({
3768
- r: key >> 16 & 255,
3769
- g: key >> 8 & 255,
3770
- b: key & 255,
3845
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key2, n]) => ({
3846
+ r: key2 >> 16 & 255,
3847
+ g: key2 >> 8 & 255,
3848
+ b: key2 & 255,
3771
3849
  weight: n / opaque
3772
3850
  }));
3773
3851
  }
@@ -4019,13 +4097,17 @@ import path3 from "path";
4019
4097
  // src/hash.ts
4020
4098
  import { createHash } from "crypto";
4021
4099
  import { createReadStream } from "fs";
4100
+ function normalizeHex(value) {
4101
+ const { r, g, b } = parseHex(value);
4102
+ return `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
4103
+ }
4022
4104
  function sha256(data) {
4023
4105
  return createHash("sha256").update(data).digest("hex");
4024
4106
  }
4025
- async function sha256File(path39) {
4107
+ async function sha256File(path42) {
4026
4108
  return new Promise((resolve, reject) => {
4027
4109
  const hash = createHash("sha256");
4028
- const stream = createReadStream(path39);
4110
+ const stream = createReadStream(path42);
4029
4111
  stream.on("data", (chunk2) => hash.update(chunk2));
4030
4112
  stream.on("error", reject);
4031
4113
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -4167,6 +4249,22 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
4167
4249
  // A mirror's bytes come from its source's recorded outputs; the plan
4168
4250
  // compares those directly, so only the choice of source is identity.
4169
4251
  mirror: spec.mirror ? { of: spec.mirror.sourceAssetId } : void 0,
4252
+ // A derived asset's identity is its transform and what it reads: the
4253
+ // file source by its bytes' hash, an asset source by id (the plan
4254
+ // compares that asset's current output with the one recorded).
4255
+ derive: spec.derive ? {
4256
+ transform: spec.derive.transform,
4257
+ map: spec.derive.map ? Object.entries(spec.derive.map).map(([from, to]) => [normalizeHex(from), normalizeHex(to)]).sort(([a], [b]) => a.localeCompare(b)) : void 0,
4258
+ palette: spec.derive.palette?.map(normalizeHex),
4259
+ width: spec.derive.width,
4260
+ height: spec.derive.height,
4261
+ mode: spec.derive.transform === "scale" ? spec.derive.mode ?? "nearest" : void 0,
4262
+ from: spec.derive.source.kind === "asset" ? spec.derive.source.assetId : void 0,
4263
+ fileSha256: spec.derive.source.kind === "file" ? spec.derive.source.sha256 : void 0
4264
+ } : void 0,
4265
+ // An external asset: the builder text and each declared input's path
4266
+ // and bytes. The built file itself is checked by the plan.
4267
+ external: spec.external ? { builder: spec.external.builder, inputs: spec.external.inputs.length ? spec.external.inputs : void 0 } : void 0,
4170
4268
  // The whole group's ordered descriptions, not just this asset's own —
4171
4269
  // any sibling's prompt changing, or a member being added or removed,
4172
4270
  // must mark every member stale together, since they all ride on one
@@ -4294,13 +4392,13 @@ var PixelLabMcpClient = class {
4294
4392
  }
4295
4393
  };
4296
4394
  function mcpClientFromEnv() {
4297
- const key = process.env.PIXELLAB_API_KEY;
4298
- if (!key) {
4395
+ const key2 = process.env.PIXELLAB_API_KEY;
4396
+ if (!key2) {
4299
4397
  throw new Error(
4300
4398
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
4301
4399
  );
4302
4400
  }
4303
- return new PixelLabMcpClient(key);
4401
+ return new PixelLabMcpClient(key2);
4304
4402
  }
4305
4403
 
4306
4404
  // src/pixellab-vfx.ts
@@ -4584,27 +4682,27 @@ function vfxArtistFiles(raw) {
4584
4682
  const urlOf = (value) => {
4585
4683
  if (typeof value === "string") return /^https?:\/\//i.test(value) ? value : null;
4586
4684
  if (!value || typeof value !== "object") return null;
4587
- for (const key of ["url", "download_url", "href"]) {
4588
- const url = value[key];
4685
+ for (const key2 of ["url", "download_url", "href"]) {
4686
+ const url = value[key2];
4589
4687
  if (typeof url === "string" && /^https?:\/\//i.test(url)) return url;
4590
4688
  }
4591
4689
  return null;
4592
4690
  };
4593
- const nameOf = (value, url, key) => {
4691
+ const nameOf = (value, url, key2) => {
4594
4692
  if (value && typeof value === "object") {
4595
4693
  for (const field of ["name", "filename", "file"]) {
4596
4694
  const name = value[field];
4597
4695
  if (typeof name === "string" && name) return name;
4598
4696
  }
4599
4697
  }
4600
- if (key && /\.[a-z0-9]+$/i.test(key)) return key;
4698
+ if (key2 && /\.[a-z0-9]+$/i.test(key2)) return key2;
4601
4699
  return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
4602
4700
  };
4603
4701
  const entries = Array.isArray(raw) ? raw.map((value) => [void 0, value]) : raw && typeof raw === "object" ? Object.entries(raw) : [];
4604
4702
  const files = [];
4605
- for (const [key, value] of entries) {
4703
+ for (const [key2, value] of entries) {
4606
4704
  const url = urlOf(value);
4607
- if (url) files.push({ name: nameOf(value, url, key), url });
4705
+ if (url) files.push({ name: nameOf(value, url, key2), url });
4608
4706
  }
4609
4707
  return files;
4610
4708
  }
@@ -4705,14 +4803,14 @@ async function makeVfxWithArtist(client2, opts) {
4705
4803
  `);
4706
4804
  written.atlas = paths.atlas;
4707
4805
  }
4708
- for (const [file, target, key] of [
4806
+ for (const [file, target, key2] of [
4709
4807
  [result.gif, paths.gif, "gif"],
4710
4808
  [result.gamePack, paths.gamePack, "gamePack"],
4711
4809
  [result.normals, paths.normals, "normals"]
4712
4810
  ]) {
4713
4811
  if (!file) continue;
4714
4812
  await writeFile(target, await client2.download(file.url));
4715
- written[key] = target;
4813
+ written[key2] = target;
4716
4814
  }
4717
4815
  const facts = vfxArtistFrameFacts(result, atlas);
4718
4816
  const usage = job.usage ?? null;
@@ -4736,7 +4834,7 @@ async function makeVfxWithArtist(client2, opts) {
4736
4834
  anchor: result.anchor,
4737
4835
  parts: result.parts,
4738
4836
  files: Object.fromEntries(
4739
- ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key) => written[key]).map((key) => [key, path.basename(written[key])])
4837
+ ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key2) => written[key2]).map((key2) => [key2, path.basename(written[key2])])
4740
4838
  ),
4741
4839
  quotedGenerations: submitted.quoted_generations ?? null,
4742
4840
  usage,
@@ -4761,8 +4859,8 @@ async function makeVfxWithArtist(client2, opts) {
4761
4859
  };
4762
4860
  }
4763
4861
  function vfxJobFailure(done) {
4764
- for (const key of ["error", "detail", "message"]) {
4765
- const value = done?.[key];
4862
+ for (const key2 of ["error", "detail", "message"]) {
4863
+ const value = done?.[key2];
4766
4864
  if (typeof value === "string" && value) return `: ${value}`;
4767
4865
  }
4768
4866
  return "";
@@ -4797,8 +4895,8 @@ function isSensitiveSourceUrl(value) {
4797
4895
  return false;
4798
4896
  }
4799
4897
  if (parsed.username || parsed.password) return true;
4800
- for (const key of parsed.searchParams.keys()) {
4801
- const normalized = key.toLowerCase();
4898
+ for (const key2 of parsed.searchParams.keys()) {
4899
+ const normalized = key2.toLowerCase();
4802
4900
  if (SENSITIVE_QUERY_KEYS.has(normalized) || normalized.includes("credential") || normalized.includes("signature") || normalized.includes("security-token") || normalized.includes("token")) return true;
4803
4901
  }
4804
4902
  return false;
@@ -7193,8 +7291,8 @@ var PixelLabProvider = class _PixelLabProvider {
7193
7291
  billed
7194
7292
  };
7195
7293
  };
7196
- for (const key of ["frame_urls", "frames", "images"]) {
7197
- const list = done[key];
7294
+ for (const key2 of ["frame_urls", "frames", "images"]) {
7295
+ const list = done[key2];
7198
7296
  if (!Array.isArray(list) || !list.length) continue;
7199
7297
  const urls = [];
7200
7298
  for (const [index, item] of list.entries()) {
@@ -7249,15 +7347,15 @@ var PixelLabProvider = class _PixelLabProvider {
7249
7347
  const billed = billedFromUsage(job.usage);
7250
7348
  const done = job.last_response ?? {};
7251
7349
  const urlKeys = ["image_url", "download_url", "url", "output_url"];
7252
- for (const key of urlKeys) {
7253
- const url = done[key];
7350
+ for (const key2 of urlKeys) {
7351
+ const url = done[key2];
7254
7352
  if (typeof url === "string" && url) {
7255
7353
  return { status: "ready", objectId: jobId, sourceUrl: url, sources: [{ url }], billed };
7256
7354
  }
7257
7355
  }
7258
7356
  const imageKeys = ["image", "output_image", "result_image", "edited_image"];
7259
- for (const key of imageKeys) {
7260
- const candidate = done[key];
7357
+ for (const key2 of imageKeys) {
7358
+ const candidate = done[key2];
7261
7359
  const base64 = extractBase64(candidate);
7262
7360
  if (base64) {
7263
7361
  const file = path3.join(_PixelLabProvider.cacheDir(), `${jobId}.png`);
@@ -7682,7 +7780,7 @@ function requirePixelLabOption(generator, name, value, allowed) {
7682
7780
  }
7683
7781
  }
7684
7782
  function tilesInIndexOrder(urls) {
7685
- return Object.entries(urls).map(([key, url]) => ({ index: Number(key.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
7783
+ return Object.entries(urls).map(([key2, url]) => ({ index: Number(key2.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
7686
7784
  }
7687
7785
  function firstUrl(urls) {
7688
7786
  if (!urls) return null;
@@ -7844,9 +7942,9 @@ var RetroDiffusionClient = class {
7844
7942
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
7845
7943
  return Buffer.from(await response.arrayBuffer());
7846
7944
  }
7847
- async call(path39, init = {}) {
7945
+ async call(path42, init = {}) {
7848
7946
  if (!this.token) throw new Error("RD_API_KEY is not set");
7849
- const response = await this.request(`${this.baseUrl}${path39}`, {
7947
+ const response = await this.request(`${this.baseUrl}${path42}`, {
7850
7948
  ...init,
7851
7949
  headers: {
7852
7950
  "Content-Type": "application/json",
@@ -8315,8 +8413,8 @@ var ScenarioClient = class {
8315
8413
  throw new Error(`${missing.join(" and ")} ${missing.length > 1 ? "are" : "is"} not set`);
8316
8414
  }
8317
8415
  const url = new URL(`${this.baseUrl.replace(/\/$/, "")}${pathname}`);
8318
- for (const [key, value2] of Object.entries(query)) {
8319
- if (value2 != null) url.searchParams.set(key, value2);
8416
+ for (const [key2, value2] of Object.entries(query)) {
8417
+ if (value2 != null) url.searchParams.set(key2, value2);
8320
8418
  }
8321
8419
  const auth = Buffer.from(`${this.apiKey}:${this.apiSecret}`).toString("base64");
8322
8420
  const response = await this.request(url, {
@@ -8556,12 +8654,12 @@ function readUploadCache() {
8556
8654
  return {};
8557
8655
  }
8558
8656
  }
8559
- function writeUploadCache(key, assetId) {
8657
+ function writeUploadCache(key2, assetId) {
8560
8658
  try {
8561
8659
  const file = uploadCachePath();
8562
8660
  mkdirSync2(path4.dirname(file), { recursive: true });
8563
8661
  const tmp = `${file}.${process.pid}.tmp`;
8564
- writeFileSync2(tmp, JSON.stringify({ ...readUploadCache(), [key]: assetId }));
8662
+ writeFileSync2(tmp, JSON.stringify({ ...readUploadCache(), [key2]: assetId }));
8565
8663
  renameSync(tmp, file);
8566
8664
  } catch {
8567
8665
  }
@@ -8611,9 +8709,9 @@ function validateParameters(parameters) {
8611
8709
  if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
8612
8710
  throw new Error("Scenario parameters must be a JSON object");
8613
8711
  }
8614
- for (const key of Object.keys(parameters)) {
8615
- if (PROTECTED_PARAMETERS.has(key)) {
8616
- throw new Error(`Scenario parameters.${key} is managed by PixelKiln and cannot be overridden`);
8712
+ for (const key2 of Object.keys(parameters)) {
8713
+ if (PROTECTED_PARAMETERS.has(key2)) {
8714
+ throw new Error(`Scenario parameters.${key2} is managed by PixelKiln and cannot be overridden`);
8617
8715
  }
8618
8716
  }
8619
8717
  assertJsonValue(parameters, "Scenario parameters");
@@ -8636,8 +8734,8 @@ function assertJsonValue(value, label, seen = /* @__PURE__ */ new Set()) {
8636
8734
  if (Array.isArray(value)) {
8637
8735
  value.forEach((item, index) => assertJsonValue(item, `${label}[${index}]`, seen));
8638
8736
  } else {
8639
- for (const [key, item] of Object.entries(value)) {
8640
- assertJsonValue(item, `${label}.${key}`, seen);
8737
+ for (const [key2, item] of Object.entries(value)) {
8738
+ assertJsonValue(item, `${label}.${key2}`, seen);
8641
8739
  }
8642
8740
  }
8643
8741
  seen.delete(value);
@@ -8738,8 +8836,8 @@ function numericRecord(value) {
8738
8836
  throw new Error("Scenario returned invalid cost details");
8739
8837
  }
8740
8838
  const out = {};
8741
- for (const [key, amount] of Object.entries(value)) {
8742
- out[key] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key}"`);
8839
+ for (const [key2, amount] of Object.entries(value)) {
8840
+ out[key2] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key2}"`);
8743
8841
  }
8744
8842
  return out;
8745
8843
  }
@@ -9345,7 +9443,7 @@ function parseOptions(value) {
9345
9443
  "workflow",
9346
9444
  "workflowSha256"
9347
9445
  ]);
9348
- const extra = Object.keys(value).filter((key) => !allowed.has(key));
9446
+ const extra = Object.keys(value).filter((key2) => !allowed.has(key2));
9349
9447
  if (extra.length) throw new Error(`Unknown ComfyUI option(s): ${extra.join(", ")}`);
9350
9448
  const workflowFile = requiredString(value.workflowFile, "workflowFile");
9351
9449
  const outputNodeId = requiredString(value.outputNodeId, "outputNodeId");
@@ -9381,7 +9479,7 @@ function parseOptions(value) {
9381
9479
  }
9382
9480
  function parseFrames(value) {
9383
9481
  if (!isObject(value)) throw new Error("ComfyUI frames must be an object");
9384
- const extra = Object.keys(value).filter((key) => key !== "vary" && key !== "seedStep");
9482
+ const extra = Object.keys(value).filter((key2) => key2 !== "vary" && key2 !== "seedStep");
9385
9483
  if (extra.length) throw new Error(`Unknown ComfyUI frames field(s): ${extra.join(", ")}`);
9386
9484
  const vary = requiredString(value.vary, "frames.vary");
9387
9485
  const seedStep = value.seedStep ?? 0;
@@ -9399,7 +9497,7 @@ function resolvedOptions(spec) {
9399
9497
  }
9400
9498
  function parseBinding(value, name) {
9401
9499
  if (!isObject(value)) throw new Error(`ComfyUI bindings.${name} must be an object`);
9402
- const extra = Object.keys(value).filter((key) => key !== "nodeId" && key !== "input");
9500
+ const extra = Object.keys(value).filter((key2) => key2 !== "nodeId" && key2 !== "input");
9403
9501
  if (extra.length) throw new Error(`Unknown ComfyUI bindings.${name} field(s): ${extra.join(", ")}`);
9404
9502
  return {
9405
9503
  nodeId: requiredString(value.nodeId, `bindings.${name}.nodeId`),
@@ -9664,7 +9762,7 @@ function canonical(value) {
9664
9762
  if (Array.isArray(value)) return value.map(canonical);
9665
9763
  if (!isObject(value)) return value;
9666
9764
  return Object.fromEntries(
9667
- Object.keys(value).sort().map((key) => [key, canonical(value[key])])
9765
+ Object.keys(value).sort().map((key2) => [key2, canonical(value[key2])])
9668
9766
  );
9669
9767
  }
9670
9768
 
@@ -10073,22 +10171,22 @@ async function writeLockWhileHeld(file, lock) {
10073
10171
  }
10074
10172
  const dirty = dirtyPatches.get(lock) ?? /* @__PURE__ */ new Map();
10075
10173
  const snapshot = /* @__PURE__ */ new Map();
10076
- for (const [key, patch] of dirty) snapshot.set(key, { ...patch });
10174
+ for (const [key2, patch] of dirty) snapshot.set(key2, { ...patch });
10077
10175
  const merged = { ...disk.entries };
10078
- for (const [key, patch] of snapshot) {
10079
- const local = lock.entries[key];
10176
+ for (const [key2, patch] of snapshot) {
10177
+ const local = lock.entries[key2];
10080
10178
  if (!local) continue;
10081
- merged[key] = merged[key] ? { ...merged[key], ...patch } : local;
10179
+ merged[key2] = merged[key2] ? { ...merged[key2], ...patch } : local;
10082
10180
  }
10083
- for (const [key, entry] of Object.entries(lock.entries)) {
10084
- if (!merged[key]) merged[key] = entry;
10181
+ for (const [key2, entry] of Object.entries(lock.entries)) {
10182
+ if (!merged[key2]) merged[key2] = entry;
10085
10183
  }
10086
10184
  const deletes = dirtyDeletes.get(lock);
10087
10185
  const deleteSnapshot = deletes ? new Set(deletes) : /* @__PURE__ */ new Set();
10088
- for (const key of deleteSnapshot) delete merged[key];
10186
+ for (const key2 of deleteSnapshot) delete merged[key2];
10089
10187
  const sorted = {};
10090
- for (const key of Object.keys(merged).sort()) {
10091
- sorted[key] = merged[key];
10188
+ for (const key2 of Object.keys(merged).sort()) {
10189
+ sorted[key2] = merged[key2];
10092
10190
  }
10093
10191
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
10094
10192
  try {
@@ -10099,48 +10197,48 @@ async function writeLockWhileHeld(file, lock) {
10099
10197
  }
10100
10198
  const currentDirty = dirtyPatches.get(lock);
10101
10199
  if (currentDirty) {
10102
- for (const [key, patch] of snapshot) {
10103
- const current = currentDirty.get(key);
10200
+ for (const [key2, patch] of snapshot) {
10201
+ const current = currentDirty.get(key2);
10104
10202
  if (!current) continue;
10105
10203
  for (const [field, value] of Object.entries(patch)) {
10106
10204
  if (Object.is(current[field], value)) {
10107
10205
  delete current[field];
10108
10206
  }
10109
10207
  }
10110
- if (Object.keys(current).length === 0) currentDirty.delete(key);
10208
+ if (Object.keys(current).length === 0) currentDirty.delete(key2);
10111
10209
  }
10112
10210
  }
10113
10211
  const stillDirty = dirtyDeletes.get(lock);
10114
10212
  if (stillDirty) {
10115
- for (const key of deleteSnapshot) stillDirty.delete(key);
10213
+ for (const key2 of deleteSnapshot) stillDirty.delete(key2);
10116
10214
  if (stillDirty.size === 0) dirtyDeletes.delete(lock);
10117
10215
  }
10118
10216
  const localAfterWrite = lock.entries;
10119
10217
  lock.entries = { ...merged };
10120
- for (const [key, patch] of currentDirty ?? []) {
10121
- const base = lock.entries[key] ?? localAfterWrite[key];
10122
- if (base) lock.entries[key] = { ...base, ...patch };
10218
+ for (const [key2, patch] of currentDirty ?? []) {
10219
+ const base = lock.entries[key2] ?? localAfterWrite[key2];
10220
+ if (base) lock.entries[key2] = { ...base, ...patch };
10123
10221
  }
10124
10222
  }
10125
- function upsert(lock, key, patch) {
10126
- dirtyDeletes.get(lock)?.delete(key);
10127
- const existing = lock.entries[key];
10223
+ function upsert(lock, key2, patch) {
10224
+ dirtyDeletes.get(lock)?.delete(key2);
10225
+ const existing = lock.entries[key2];
10128
10226
  const next = { ...existing, ...patch };
10129
- lock.entries[key] = next;
10227
+ lock.entries[key2] = next;
10130
10228
  let dirty = dirtyPatches.get(lock);
10131
10229
  if (!dirty) {
10132
10230
  dirty = /* @__PURE__ */ new Map();
10133
10231
  dirtyPatches.set(lock, dirty);
10134
10232
  }
10135
- dirty.set(key, { ...dirty.get(key) ?? {}, ...patch });
10233
+ dirty.set(key2, { ...dirty.get(key2) ?? {}, ...patch });
10136
10234
  return next;
10137
10235
  }
10138
- function remove(lock, key) {
10139
- if (!lock.entries[key]) return false;
10140
- delete lock.entries[key];
10236
+ function remove(lock, key2) {
10237
+ if (!lock.entries[key2]) return false;
10238
+ delete lock.entries[key2];
10141
10239
  const patches = dirtyPatches.get(lock);
10142
10240
  if (patches) {
10143
- patches.delete(key);
10241
+ patches.delete(key2);
10144
10242
  if (patches.size === 0) dirtyPatches.delete(lock);
10145
10243
  }
10146
10244
  let deletes = dirtyDeletes.get(lock);
@@ -10148,7 +10246,7 @@ function remove(lock, key) {
10148
10246
  deletes = /* @__PURE__ */ new Set();
10149
10247
  dirtyDeletes.set(lock, deletes);
10150
10248
  }
10151
- deletes.add(key);
10249
+ deletes.add(key2);
10152
10250
  return true;
10153
10251
  }
10154
10252
  var FILE_LOCK_TIMEOUT_MS = 1e4;
@@ -10246,8 +10344,8 @@ function currentEntryOutputPath(entry, spec, index) {
10246
10344
  function normalizeLockOutputPaths(lock, specs) {
10247
10345
  const byKey = new Map(specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
10248
10346
  let changed = 0;
10249
- for (const [key, entry] of Object.entries(lock.entries)) {
10250
- const spec = byKey.get(key);
10347
+ for (const [key2, entry] of Object.entries(lock.entries)) {
10348
+ const spec = byKey.get(key2);
10251
10349
  if (!spec) continue;
10252
10350
  let entryChanged = false;
10253
10351
  const outputs = entry.outputs.map((output, index) => {
@@ -10258,7 +10356,7 @@ function normalizeLockOutputPaths(lock, specs) {
10258
10356
  entryChanged = true;
10259
10357
  return { ...output, path: portable };
10260
10358
  });
10261
- if (entryChanged) upsert(lock, key, { outputs });
10359
+ if (entryChanged) upsert(lock, key2, { outputs });
10262
10360
  }
10263
10361
  return changed;
10264
10362
  }
@@ -10289,8 +10387,8 @@ function resolveSpecEntryOutputs(entry, spec) {
10289
10387
  }
10290
10388
  function resolveStyleOutputs(lock, styleId, manifestDir) {
10291
10389
  const prefix = `${styleId}/`;
10292
- return Object.entries(lock.entries).filter(([key]) => key.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
10293
- ([key, entry]) => resolveEntryOutputs(entry, key.slice(prefix.length), manifestDir)
10390
+ return Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
10391
+ ([key2, entry]) => resolveEntryOutputs(entry, key2.slice(prefix.length), manifestDir)
10294
10392
  );
10295
10393
  }
10296
10394
  function selectEntryOutput(entry, role) {
@@ -10356,7 +10454,7 @@ function pixelkilnVersion() {
10356
10454
  }
10357
10455
 
10358
10456
  // src/manifest.ts
10359
- async function loadManifest(manifestPath) {
10457
+ async function loadManifest(manifestPath, opts = {}) {
10360
10458
  const abs = path8.resolve(manifestPath);
10361
10459
  if (!existsSync7(abs)) throw new ProjectError(`No manifest at ${abs}`);
10362
10460
  const expansion = expandLoopDirections(JSON.parse(await readFile5(abs, "utf8")));
@@ -10364,6 +10462,63 @@ async function loadManifest(manifestPath) {
10364
10462
  throw new ProjectError(`Manifest at ${abs} is invalid:
10365
10463
  ${expansion.issues.map((i) => ` ${i}`).join("\n")}`);
10366
10464
  }
10465
+ if (!opts.lenient) return loadExpanded(abs, expansion);
10466
+ const invalid = [];
10467
+ const raw = pruneInvalidEntries(expansion.raw, invalid);
10468
+ for (let round2 = 0; ; round2++) {
10469
+ try {
10470
+ const loaded = await loadExpanded(abs, { ...expansion, raw });
10471
+ return invalid.length ? { ...loaded, invalid } : loaded;
10472
+ } catch (error) {
10473
+ const culprits = round2 < 50 && error instanceof ProjectError ? culpritEntries(error.message) : [];
10474
+ const fresh = culprits.filter((entry) => dropEntry(raw, entry));
10475
+ if (!fresh.length) throw error;
10476
+ invalid.push(...fresh);
10477
+ }
10478
+ }
10479
+ }
10480
+ function entryRecord(raw, kind) {
10481
+ const record = raw?.[kind === "style" ? "styles" : "assets"];
10482
+ return record && typeof record === "object" && !Array.isArray(record) ? record : null;
10483
+ }
10484
+ function dropEntry(raw, entry) {
10485
+ const record = entryRecord(raw, entry.kind);
10486
+ if (!record || !(entry.id in record)) return false;
10487
+ delete record[entry.id];
10488
+ return true;
10489
+ }
10490
+ function pruneInvalidEntries(raw, invalid) {
10491
+ for (const [kind, schema] of [["style", StyleInputSchema], ["asset", AssetSchema]]) {
10492
+ const record = entryRecord(raw, kind);
10493
+ if (!record) continue;
10494
+ for (const [id, value] of Object.entries(record)) {
10495
+ const parsed = schema.safeParse(value);
10496
+ if (parsed.success) continue;
10497
+ const prefix = `${kind === "style" ? "styles" : "assets"}.${id}`;
10498
+ const lines = flattenManifestIssues(parsed.error.issues).lines.map((line) => {
10499
+ const [fieldPath, ...rest] = line.trim().split(": ");
10500
+ return `${prefix}${fieldPath === "(manifest)" || !fieldPath ? "" : `.${fieldPath}`}: ${rest.join(": ")}`;
10501
+ });
10502
+ invalid.push({ kind, id, issues: lines.length ? lines : [`${prefix}: invalid`] });
10503
+ delete record[id];
10504
+ }
10505
+ }
10506
+ return raw;
10507
+ }
10508
+ function culpritEntries(message6) {
10509
+ const found = /* @__PURE__ */ new Map();
10510
+ for (const line of message6.split("\n")) {
10511
+ const match = /^ {2}(assets|styles)\.([^.:\s]+)[.:]/.exec(line);
10512
+ if (!match) continue;
10513
+ const kind = match[1] === "styles" ? "style" : "asset";
10514
+ const key2 = `${kind}:${match[2]}`;
10515
+ const entry = found.get(key2) ?? { kind, id: match[2], issues: [] };
10516
+ entry.issues.push(line.trim());
10517
+ found.set(key2, entry);
10518
+ }
10519
+ return [...found.values()];
10520
+ }
10521
+ async function loadExpanded(abs, expansion) {
10367
10522
  const input = ManifestInputSchema.safeParse(expansion.raw);
10368
10523
  if (!input.success) {
10369
10524
  const issues = formatManifestIssues(input.error.issues);
@@ -10505,6 +10660,7 @@ function dependencyAssetIds(asset, styleAnchors = []) {
10505
10660
  asset?.connect?.upper?.of,
10506
10661
  asset?.animation?.motionFrom,
10507
10662
  asset?.mirror,
10663
+ asset?.derive?.from,
10508
10664
  asset?.styleCharacter,
10509
10665
  ...asset?.styleCharacter ? [] : styleAnchors
10510
10666
  ].filter((id) => Boolean(id))
@@ -10963,6 +11119,64 @@ async function resolveSpecs(loaded, filter) {
10963
11119
  }
10964
11120
  if (finalized.has(assetId)) return resolved;
10965
11121
  const asset = manifest.assets[assetId];
11122
+ if (asset.derive) {
11123
+ const derive = asset.derive;
11124
+ let source;
11125
+ let sourceSpec;
11126
+ if (derive.from) {
11127
+ if (derive.from === assetId) throw new Error(`assets.${assetId}: an asset cannot derive from itself`);
11128
+ sourceSpec = await finalize(derive.from);
11129
+ if (sourceSpec.generator === "tiles" || sourceSpec.generator === "terrain") {
11130
+ throw new Error(`assets.${assetId}: a tile set is several images; derive takes a single image`);
11131
+ }
11132
+ source = { kind: "asset", assetId: derive.from, spec: sourceSpec };
11133
+ } else {
11134
+ const file = path8.resolve(root, derive.file);
11135
+ source = { kind: "file", file: derive.file, sha256: existsSync7(file) ? await sha256File(file) : null };
11136
+ }
11137
+ if (derive.transform === "scale") {
11138
+ resolved.width = derive.width;
11139
+ resolved.height = derive.height;
11140
+ } else if (sourceSpec) {
11141
+ resolved.width = sourceSpec.width;
11142
+ resolved.height = sourceSpec.height;
11143
+ } else if (source.kind === "file" && source.sha256) {
11144
+ const metadata = imageMetadata(await readFile5(path8.resolve(root, source.file)));
11145
+ if (metadata?.width && metadata.height) {
11146
+ resolved.width = metadata.width;
11147
+ resolved.height = metadata.height;
11148
+ }
11149
+ }
11150
+ resolved.derive = {
11151
+ transform: derive.transform,
11152
+ ...derive.map ? { map: derive.map } : {},
11153
+ ...derive.palette ? { palette: derive.palette } : {},
11154
+ ...derive.width ? { width: derive.width } : {},
11155
+ ...derive.height ? { height: derive.height } : {},
11156
+ ...derive.mode ? { mode: derive.mode } : {},
11157
+ source
11158
+ };
11159
+ resolved.prompt = "";
11160
+ resolved.specHash = specHash(resolved, styleImageHashes, providerOptionIdentity, providerInputIdentities.get(assetId));
11161
+ resolved.cost = 0;
11162
+ resolved.candidates = 1;
11163
+ finalized.add(assetId);
11164
+ return resolved;
11165
+ }
11166
+ if (asset.external) {
11167
+ const inputs = [];
11168
+ for (const input of asset.external.inputs ?? []) {
11169
+ const file = path8.resolve(root, input);
11170
+ inputs.push({ path: input, sha256: existsSync7(file) ? await sha256File(file) : null });
11171
+ }
11172
+ resolved.external = { builder: asset.external.builder, inputs };
11173
+ resolved.prompt = "";
11174
+ resolved.specHash = specHash(resolved, styleImageHashes, providerOptionIdentity, providerInputIdentities.get(assetId));
11175
+ resolved.cost = 0;
11176
+ resolved.candidates = 1;
11177
+ finalized.add(assetId);
11178
+ return resolved;
11179
+ }
10966
11180
  if (asset.mirror) {
10967
11181
  if (asset.mirror === assetId) throw new Error(`assets.${assetId}: an asset cannot mirror itself`);
10968
11182
  const sourceSpec = await finalize(asset.mirror);
@@ -11124,8 +11338,8 @@ async function resolveSpecs(loaded, filter) {
11124
11338
  const sourceSpec = sourceStyleId ? await styleFinalizers.get(sourceStyleId)(asset.revision.from) : await finalize(asset.revision.from);
11125
11339
  const sourceStem = sourceSpec.quality?.outFile ?? (sourceSpec.source ? path8.resolve(root, sourceSpec.source) : sourceSpec.outFile);
11126
11340
  const sourceMembers = await revisionSourceMembers(sourceStem, `revision source ${asset.revision.from}`);
11127
- const sourceFile = sourceMembers?.[0]?.file ?? sourceStem;
11128
- const sourceImage = sourceMembers ? { ...sourceMembers[0], hash: sha256(JSON.stringify(sourceMembers.map((member) => member.sha256))) } : await optionalRevisionImage(sourceFile, "revision source");
11341
+ const sourceFile2 = sourceMembers?.[0]?.file ?? sourceStem;
11342
+ const sourceImage = sourceMembers ? { ...sourceMembers[0], hash: sha256(JSON.stringify(sourceMembers.map((member) => member.sha256))) } : await optionalRevisionImage(sourceFile2, "revision source");
11129
11343
  const sourceFps = sourceSpec.character?.animation?.fps ?? sourceSpec.objectPro?.animation?.fps ?? sourceSpec.revision?.fps ?? sourceSpec.revision?.sourceFps;
11130
11344
  const maskFile = asset.revision.mask ? path8.resolve(root, asset.revision.mask) : void 0;
11131
11345
  const maskImage = maskFile ? await optionalRevisionImage(maskFile, "revision mask", "png") : null;
@@ -11144,7 +11358,7 @@ async function resolveSpecs(loaded, filter) {
11144
11358
  mode: asset.revision.mode,
11145
11359
  sourceAssetId: asset.revision.from,
11146
11360
  ...sourceStyleId ? { sourceStyleId } : {},
11147
- sourceFile,
11361
+ sourceFile: sourceFile2,
11148
11362
  sourceSha256: sourceImage?.hash ?? null,
11149
11363
  sourceWidth: sourceImage?.width ?? null,
11150
11364
  sourceHeight: sourceImage?.height ?? null,
@@ -11298,7 +11512,16 @@ async function resolveSpecs(loaded, filter) {
11298
11512
  if (!emitStyles.has(styleId)) continue;
11299
11513
  for (const assetId of Object.keys(manifest.assets)) {
11300
11514
  if (!requestedAssetIds.has(assetId) || !styleSpecs.has(assetId)) continue;
11301
- specs.push(await finalize(assetId));
11515
+ if (!filter?.onInvalid) {
11516
+ specs.push(await finalize(assetId));
11517
+ continue;
11518
+ }
11519
+ try {
11520
+ specs.push(await finalize(assetId));
11521
+ } catch (error) {
11522
+ const message6 = error instanceof Error ? error.message : String(error);
11523
+ filter.onInvalid({ kind: "asset", id: assetId, issues: [message6] });
11524
+ }
11302
11525
  }
11303
11526
  }
11304
11527
  const byOutput = /* @__PURE__ */ new Map();
@@ -11310,8 +11533,8 @@ async function resolveSpecs(loaded, filter) {
11310
11533
  byOutput.set(file, owner);
11311
11534
  };
11312
11535
  for (const spec of specs) {
11313
- const key = `${spec.styleId}/${spec.assetId}`;
11314
- claimOutput(spec.outFile, key);
11536
+ const key2 = `${spec.styleId}/${spec.assetId}`;
11537
+ claimOutput(spec.outFile, key2);
11315
11538
  if (spec.quality) {
11316
11539
  if (spec.generator === "frames") {
11317
11540
  const frameInputs = Object.values(spec.providerInputs ?? {}).find(Array.isArray);
@@ -11326,11 +11549,11 @@ async function resolveSpecs(loaded, filter) {
11326
11549
  count,
11327
11550
  MediaType.PNG
11328
11551
  ),
11329
- `${key} quality ${role}`
11552
+ `${key2} quality ${role}`
11330
11553
  );
11331
11554
  }
11332
11555
  } else {
11333
- claimOutput(spec.quality.outFile, `${key} quality output`);
11556
+ claimOutput(spec.quality.outFile, `${key2} quality output`);
11334
11557
  }
11335
11558
  }
11336
11559
  }
@@ -11594,7 +11817,7 @@ function characterDirections(directions) {
11594
11817
  }
11595
11818
 
11596
11819
  // src/project.ts
11597
- import path16 from "path";
11820
+ import path18 from "path";
11598
11821
 
11599
11822
  // src/env.ts
11600
11823
  import { readFileSync as readFileSync4, existsSync as existsSync8 } from "fs";
@@ -11602,8 +11825,8 @@ import path9 from "path";
11602
11825
  function loadEnvFiles(dir) {
11603
11826
  const loaded = [];
11604
11827
  for (const [file, vars] of envFiles(dir)) {
11605
- for (const [key, value] of Object.entries(vars)) {
11606
- if (!(key in process.env)) process.env[key] = value;
11828
+ for (const [key2, value] of Object.entries(vars)) {
11829
+ if (!(key2 in process.env)) process.env[key2] = value;
11607
11830
  }
11608
11831
  loaded.push(file);
11609
11832
  }
@@ -11628,21 +11851,21 @@ function parseEnv(contents) {
11628
11851
  if (!line || line.startsWith("#")) continue;
11629
11852
  const eq = line.indexOf("=");
11630
11853
  if (eq <= 0) continue;
11631
- const key = line.slice(0, eq).replace(/^export\s+/, "").trim();
11632
- if (!key || key in vars) continue;
11854
+ const key2 = line.slice(0, eq).replace(/^export\s+/, "").trim();
11855
+ if (!key2 || key2 in vars) continue;
11633
11856
  let value = line.slice(eq + 1).trim();
11634
11857
  const quote = value[0];
11635
11858
  if ((quote === '"' || quote === "'") && value.endsWith(quote) && value.length >= 2) {
11636
11859
  value = value.slice(1, -1);
11637
11860
  }
11638
- vars[key] = value;
11861
+ vars[key2] = value;
11639
11862
  }
11640
11863
  return vars;
11641
11864
  }
11642
11865
 
11643
11866
  // src/pipeline/plan.ts
11644
- import { existsSync as existsSync11 } from "fs";
11645
- import path15 from "path";
11867
+ import { existsSync as existsSync13 } from "fs";
11868
+ import path17 from "path";
11646
11869
 
11647
11870
  // src/pipeline/mirror.ts
11648
11871
  import { mkdir as mkdir4, readFile as readFile6, rename as rename2, writeFile as writeFile4 } from "fs/promises";
@@ -11684,8 +11907,8 @@ function quantize(png, palette) {
11684
11907
  pixels[i + 2] = 0;
11685
11908
  continue;
11686
11909
  }
11687
- const key = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
11688
- let nearest = nearestOf.get(key);
11910
+ const key2 = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
11911
+ let nearest = nearestOf.get(key2);
11689
11912
  if (!nearest) {
11690
11913
  const pixel = { r: pixels[i], g: pixels[i + 1], b: pixels[i + 2] };
11691
11914
  nearest = colors[0];
@@ -11698,7 +11921,7 @@ function quantize(png, palette) {
11698
11921
  distance = candidateDistance;
11699
11922
  }
11700
11923
  }
11701
- nearestOf.set(key, nearest);
11924
+ nearestOf.set(key2, nearest);
11702
11925
  }
11703
11926
  if (pixels[i] !== nearest.r || pixels[i + 1] !== nearest.g || pixels[i + 2] !== nearest.b) changed++;
11704
11927
  pixels[i] = nearest.r;
@@ -11767,7 +11990,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
11767
11990
  const log = opts.onProgress ?? (() => {
11768
11991
  });
11769
11992
  const mirror = spec.mirror;
11770
- const key = lockKey(spec.styleId, spec.assetId);
11993
+ const key2 = lockKey(spec.styleId, spec.assetId);
11771
11994
  const sourceKey = lockKey(spec.styleId, mirror.sourceAssetId);
11772
11995
  const source = lock.entries[sourceKey];
11773
11996
  if (!source || source.status !== "downloaded" || !source.outputs.length) {
@@ -11799,7 +12022,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
11799
12022
  }
11800
12023
  const sourceMetadata = source.providerMetadata?.[source.provider] ?? {};
11801
12024
  const character = spec.character;
11802
- const entry = upsert(lock, key, {
12025
+ const entry = upsert(lock, key2, {
11803
12026
  styleId: spec.styleId,
11804
12027
  assetId: spec.assetId,
11805
12028
  specHash: spec.specHash,
@@ -11842,25 +12065,206 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
11842
12065
  postprocess: postprocessFor(spec)
11843
12066
  });
11844
12067
  await saveLock(lockPath, lock);
11845
- log(` mirror ${key} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
12068
+ log(` mirror ${key2} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
11846
12069
  return entry;
11847
12070
  }
11848
12071
 
11849
- // src/pipeline/quality-profile.ts
12072
+ // src/pipeline/derive.ts
11850
12073
  import { existsSync as existsSync9 } from "fs";
11851
- import path13 from "path";
12074
+ import { mkdir as mkdir5, readFile as readFile7, rename as rename3, writeFile as writeFile5 } from "fs/promises";
12075
+ import path11 from "path";
12076
+ var key = (r, g, b) => r << 16 | g << 8 | b;
12077
+ function recolor(png, map) {
12078
+ const { width, height, pixels } = decodePng(png);
12079
+ const table = /* @__PURE__ */ new Map();
12080
+ for (const [from, to] of Object.entries(map)) {
12081
+ const a = parseHex(from);
12082
+ const b = parseHex(to);
12083
+ table.set(key(a.r, a.g, a.b), [b.r, b.g, b.b]);
12084
+ }
12085
+ const out = Buffer.from(pixels);
12086
+ for (let i = 0; i < out.length; i += 4) {
12087
+ if (out[i + 3] === 0) continue;
12088
+ const hit = table.get(key(out[i], out[i + 1], out[i + 2]));
12089
+ if (hit) {
12090
+ out[i] = hit[0];
12091
+ out[i + 1] = hit[1];
12092
+ out[i + 2] = hit[2];
12093
+ }
12094
+ }
12095
+ return encodeRgbaPng(width, height, out);
12096
+ }
12097
+ function paletteSnap(png, palette) {
12098
+ const snapped = quantize(decodePng(png), normalizePalette(palette).map((color) => color.hex)).png;
12099
+ return encodeRgbaPng(snapped.width, snapped.height, snapped.pixels);
12100
+ }
12101
+ function scale(png, width, height, mode2 = "nearest") {
12102
+ const src = decodePng(png);
12103
+ const out = Buffer.alloc(width * height * 4);
12104
+ for (let y = 0; y < height; y++) {
12105
+ const y0 = Math.floor(y * src.height / height);
12106
+ const y1 = Math.max(y0 + 1, Math.ceil((y + 1) * src.height / height));
12107
+ for (let x = 0; x < width; x++) {
12108
+ const x0 = Math.floor(x * src.width / width);
12109
+ const x1 = Math.max(x0 + 1, Math.ceil((x + 1) * src.width / width));
12110
+ const at = (y * width + x) * 4;
12111
+ if (mode2 === "nearest") {
12112
+ src.pixels.copy(out, at, (y0 * src.width + x0) * 4, (y0 * src.width + x0) * 4 + 4);
12113
+ continue;
12114
+ }
12115
+ let a = 0;
12116
+ let r = 0;
12117
+ let g = 0;
12118
+ let b = 0;
12119
+ let n = 0;
12120
+ for (let sy = y0; sy < Math.min(y1, src.height); sy++) {
12121
+ for (let sx = x0; sx < Math.min(x1, src.width); sx++) {
12122
+ const i = (sy * src.width + sx) * 4;
12123
+ const alpha = src.pixels[i + 3];
12124
+ a += alpha;
12125
+ r += src.pixels[i] * alpha;
12126
+ g += src.pixels[i + 1] * alpha;
12127
+ b += src.pixels[i + 2] * alpha;
12128
+ n++;
12129
+ }
12130
+ }
12131
+ if (a > 0) {
12132
+ out[at] = Math.round(r / a);
12133
+ out[at + 1] = Math.round(g / a);
12134
+ out[at + 2] = Math.round(b / a);
12135
+ }
12136
+ out[at + 3] = Math.round(a / Math.max(1, n));
12137
+ }
12138
+ }
12139
+ return encodeRgbaPng(width, height, out);
12140
+ }
12141
+ function applyDerive(png, derive) {
12142
+ switch (derive.transform) {
12143
+ case "recolor":
12144
+ return recolor(png, derive.map);
12145
+ case "palette-snap":
12146
+ return paletteSnap(png, derive.palette);
12147
+ case "scale":
12148
+ return scale(png, derive.width, derive.height, derive.mode);
12149
+ }
12150
+ }
12151
+ async function sourceFile(spec, lock) {
12152
+ const derive = spec.derive;
12153
+ if (derive.source.kind === "file") {
12154
+ const file2 = path11.resolve(spec.root, derive.source.file);
12155
+ return existsSync9(file2) ? { file: file2, recorded: await sha256File(file2) } : { notReady: `source file ${derive.source.file} does not exist` };
12156
+ }
12157
+ const sourceKey = lockKey(spec.styleId, derive.source.assetId);
12158
+ const entry = lock.entries[sourceKey];
12159
+ if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
12160
+ return { notReady: `source ${sourceKey} has no downloaded output` };
12161
+ }
12162
+ if (entry.outputs.length !== 1) {
12163
+ return { notReady: `source ${sourceKey} has ${entry.outputs.length} outputs; derive takes a single image` };
12164
+ }
12165
+ const file = currentEntryOutputPath(entry, derive.source.spec, 0);
12166
+ if (!existsSync9(file)) return { notReady: `source ${sourceKey} is missing on disk: ${file}` };
12167
+ return { file, recorded: entry.outputs[0].sha256 };
12168
+ }
12169
+ async function deriveStale(spec, entry, lock) {
12170
+ const derive = spec.derive;
12171
+ if (derive.source.kind === "file") {
12172
+ const file = path11.resolve(spec.root, derive.source.file);
12173
+ if (!existsSync9(file)) return `source file ${derive.source.file} is missing`;
12174
+ return entry.derive?.sourceSha256 === await sha256File(file) ? null : `source file ${derive.source.file} changed`;
12175
+ }
12176
+ const source = lock.entries[lockKey(spec.styleId, derive.source.assetId)];
12177
+ const current = source?.outputs.length === 1 ? source.outputs[0].sha256 : void 0;
12178
+ return entry.derive?.sourceSha256 && entry.derive.sourceSha256 === current ? null : `source ${derive.source.assetId} changed`;
12179
+ }
12180
+ async function deriveAsset(spec, lock, lockPath, opts = {}) {
12181
+ const log = opts.onProgress ?? (() => {
12182
+ });
12183
+ const derive = spec.derive;
12184
+ const entryKey = lockKey(spec.styleId, spec.assetId);
12185
+ const source = await sourceFile(spec, lock);
12186
+ if ("notReady" in source) throw new Error(source.notReady);
12187
+ const bytes = applyDerive(await readFile7(source.file), derive);
12188
+ const target = expectedOutputPath(spec, void 0, 0, 1, MediaType.PNG);
12189
+ await mkdir5(path11.dirname(target), { recursive: true });
12190
+ const tmp = `${target}.pixelkiln.tmp`;
12191
+ await writeFile5(tmp, bytes);
12192
+ await rename3(tmp, target);
12193
+ const out = decodePng(bytes);
12194
+ const now = (/* @__PURE__ */ new Date()).toISOString();
12195
+ const entry = upsert(lock, entryKey, {
12196
+ styleId: spec.styleId,
12197
+ assetId: spec.assetId,
12198
+ specHash: spec.specHash,
12199
+ generator: spec.generator,
12200
+ tileFeature: null,
12201
+ prompt: "",
12202
+ width: out.width,
12203
+ height: out.height,
12204
+ revision: null,
12205
+ derive: derive.source.kind === "asset" ? { sourceAssetId: derive.source.assetId, sourceSha256: source.recorded } : { sourceFile: derive.source.file, sourceSha256: source.recorded },
12206
+ supersededOutputs: [],
12207
+ jobId: null,
12208
+ submissionComplete: void 0,
12209
+ reviewObjectId: null,
12210
+ objectId: null,
12211
+ candidateIndex: null,
12212
+ status: "downloaded",
12213
+ error: null,
12214
+ outputs: [{ path: portableOutputPath(target, spec.root), sha256: sha256(bytes), mediaType: MediaType.PNG }],
12215
+ sourceUrl: null,
12216
+ sourceUrls: [],
12217
+ submittedAt: now,
12218
+ downloadedAt: now,
12219
+ history: [],
12220
+ cost: 0,
12221
+ costUnit: spec.costUnit,
12222
+ provider: spec.provider,
12223
+ postprocess: void 0
12224
+ });
12225
+ await saveLock(lockPath, lock);
12226
+ log(` derive ${entryKey} \u2190 ${derive.source.kind === "asset" ? derive.source.assetId : derive.source.file} (${derive.transform}, no generation cost)`);
12227
+ return entry;
12228
+ }
11852
12229
 
11853
- // src/pipeline/refine.ts
12230
+ // src/pipeline/external.ts
12231
+ import { existsSync as existsSync10 } from "fs";
11854
12232
  import path12 from "path";
12233
+ async function inspectExternal(spec, entry) {
12234
+ const external = spec.external;
12235
+ const file = entry?.outputs.length ? currentEntryOutputPath(entry, spec, 0) : spec.outFile;
12236
+ const rebuild = `run \`${external.builder}\``;
12237
+ if (!existsSync10(file)) {
12238
+ return { state: "orphaned", reason: `built outside pixelkiln and not found at ${path12.relative(spec.root, file)}; ${rebuild}, then adopt --local` };
12239
+ }
12240
+ if (!entry) {
12241
+ return { state: "untracked", reason: `built outside pixelkiln; record it with adopt --local (builder: ${external.builder})` };
12242
+ }
12243
+ if (entry.specHash !== spec.specHash) {
12244
+ return { state: "orphaned", reason: `builder or an input changed since the file was recorded; ${rebuild}, then adopt --local --force` };
12245
+ }
12246
+ const recorded = entry.outputs[0]?.sha256;
12247
+ if (!recorded || await sha256File(file) !== recorded) {
12248
+ return { state: "orphaned", reason: "file changed since it was recorded; adopt --local --force to record it again" };
12249
+ }
12250
+ return { state: "ok", reason: "built outside pixelkiln; matches the recorded file" };
12251
+ }
12252
+
12253
+ // src/pipeline/quality-profile.ts
12254
+ import { existsSync as existsSync11 } from "fs";
12255
+ import path15 from "path";
12256
+
12257
+ // src/pipeline/refine.ts
12258
+ import path14 from "path";
11855
12259
  import { execFile } from "child_process";
11856
- import { mkdtemp, readFile as readFile8, rm as rm3 } from "fs/promises";
12260
+ import { mkdtemp, readFile as readFile9, rm as rm3 } from "fs/promises";
11857
12261
  import { tmpdir } from "os";
11858
12262
  import { promisify } from "util";
11859
12263
 
11860
12264
  // src/artifacts.ts
11861
- import path11 from "path";
12265
+ import path13 from "path";
11862
12266
  import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
11863
- import { mkdir as mkdir5, readFile as readFile7, rename as rename3, rm as rm2, writeFile as writeFile5 } from "fs/promises";
12267
+ import { mkdir as mkdir6, readFile as readFile8, rename as rename4, rm as rm2, writeFile as writeFile6 } from "fs/promises";
11864
12268
  var activeTransactions = /* @__PURE__ */ new Set();
11865
12269
  function message(error) {
11866
12270
  return error instanceof Error ? error.message : String(error);
@@ -11869,7 +12273,7 @@ function digest(data) {
11869
12273
  return createHash4("sha256").update(data).digest("hex");
11870
12274
  }
11871
12275
  function portableRelative(from, to) {
11872
- return path11.relative(from, path11.resolve(to)).split(path11.sep).join("/") || ".";
12276
+ return path13.relative(from, path13.resolve(to)).split(path13.sep).join("/") || ".";
11873
12277
  }
11874
12278
  function canonical2(value) {
11875
12279
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
@@ -11880,9 +12284,9 @@ function canonical2(value) {
11880
12284
  if (Array.isArray(value)) return value.map(canonical2);
11881
12285
  if (typeof value === "object") {
11882
12286
  const sorted = {};
11883
- for (const key of Object.keys(value).sort()) {
11884
- const item = value[key];
11885
- if (item !== void 0) sorted[key] = canonical2(item);
12287
+ for (const key2 of Object.keys(value).sort()) {
12288
+ const item = value[key2];
12289
+ if (item !== void 0) sorted[key2] = canonical2(item);
11886
12290
  }
11887
12291
  return sorted;
11888
12292
  }
@@ -11919,12 +12323,12 @@ function parseArtifactManifest(absolute, data) {
11919
12323
  return raw;
11920
12324
  }
11921
12325
  async function readArtifactBundleManifest(manifestPath) {
11922
- const absolute = path11.resolve(manifestPath);
11923
- return parseArtifactManifest(absolute, await readFile7(absolute, "utf8"));
12326
+ const absolute = path13.resolve(manifestPath);
12327
+ return parseArtifactManifest(absolute, await readFile8(absolute, "utf8"));
11924
12328
  }
11925
12329
  async function readOptional(file) {
11926
12330
  try {
11927
- return await readFile7(file);
12331
+ return await readFile8(file);
11928
12332
  } catch (error) {
11929
12333
  if (isCode(error, "ENOENT")) return null;
11930
12334
  throw error;
@@ -11943,8 +12347,8 @@ function processIsAlive(pid) {
11943
12347
  }
11944
12348
  }
11945
12349
  function validTemporaryPath(candidate, destination, type) {
11946
- return path11.dirname(candidate) === path11.dirname(destination) && path11.basename(candidate).startsWith(
11947
- `.${path11.basename(destination)}.pixelkiln-${type}-`
12350
+ return path13.dirname(candidate) === path13.dirname(destination) && path13.basename(candidate).startsWith(
12351
+ `.${path13.basename(destination)}.pixelkiln-${type}-`
11948
12352
  );
11949
12353
  }
11950
12354
  function parseTransaction(journal, data) {
@@ -11964,7 +12368,7 @@ async function removeTransactionFiles(journal) {
11964
12368
  await rm2(transactionMarker(journal), { force: true });
11965
12369
  }
11966
12370
  async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
11967
- const journal = path11.resolve(recoveryFile);
12371
+ const journal = path13.resolve(recoveryFile);
11968
12372
  const bytes = await readOptional(journal);
11969
12373
  if (!bytes) {
11970
12374
  await rm2(transactionMarker(journal), { force: true });
@@ -11980,7 +12384,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
11980
12384
  );
11981
12385
  }
11982
12386
  for (const entry of transaction.entries) {
11983
- if (typeof entry.destination !== "string" || typeof entry.stage !== "string" || typeof entry.sha256 !== "string" || entry.backup !== void 0 && typeof entry.backup !== "string" || !allowedDestinations.has(path11.resolve(entry.destination)) || !validTemporaryPath(entry.stage, entry.destination, "stage") || entry.backup !== void 0 && !validTemporaryPath(entry.backup, entry.destination, "backup")) {
12387
+ if (typeof entry.destination !== "string" || typeof entry.stage !== "string" || typeof entry.sha256 !== "string" || entry.backup !== void 0 && typeof entry.backup !== "string" || !allowedDestinations.has(path13.resolve(entry.destination)) || !validTemporaryPath(entry.stage, entry.destination, "stage") || entry.backup !== void 0 && !validTemporaryPath(entry.backup, entry.destination, "backup")) {
11984
12388
  throw new Error(
11985
12389
  `Refusing unsafe artifact recovery from ${journal}; its destinations or temporary paths do not match the current bundle.`
11986
12390
  );
@@ -12006,7 +12410,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12006
12410
  }
12007
12411
  await remove2(entry.destination, errors);
12008
12412
  try {
12009
- await rename3(entry.backup, entry.destination);
12413
+ await rename4(entry.backup, entry.destination);
12010
12414
  } catch (error) {
12011
12415
  errors.push(
12012
12416
  `could not restore ${entry.destination}; previous file remains at ${entry.backup}: ${message(error)}`
@@ -12026,7 +12430,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12026
12430
  await removeTransactionFiles(journal);
12027
12431
  }
12028
12432
  function createArtifactBundleManifest(manifestPath, outputs, provenance) {
12029
- const root = path11.dirname(path11.resolve(manifestPath));
12433
+ const root = path13.dirname(path13.resolve(manifestPath));
12030
12434
  const sources = provenance.sources.map((source) => ({
12031
12435
  ...source,
12032
12436
  path: portableRelative(root, source.path)
@@ -12056,11 +12460,11 @@ function withArtifactManifest(manifestPath, outputs, provenance) {
12056
12460
  ];
12057
12461
  }
12058
12462
  async function writeManagedArtifactBundle(manifestPath, outputs, provenance, options = {}) {
12059
- const absoluteManifest = path11.resolve(manifestPath);
12463
+ const absoluteManifest = path13.resolve(manifestPath);
12060
12464
  const recoveryFile = `${absoluteManifest}.transaction`;
12061
12465
  const allowedDestinations = /* @__PURE__ */ new Set([
12062
12466
  absoluteManifest,
12063
- ...outputs.map((output) => path11.resolve(output.path))
12467
+ ...outputs.map((output) => path13.resolve(output.path))
12064
12468
  ]);
12065
12469
  await recoverArtifactTransaction(recoveryFile, allowedDestinations);
12066
12470
  const existingManifestBytes = await readOptional(absoluteManifest);
@@ -12078,13 +12482,13 @@ async function writeManagedArtifactBundle(manifestPath, outputs, provenance, opt
12078
12482
  }
12079
12483
  }
12080
12484
  if (!options.force) {
12081
- const root = path11.dirname(absoluteManifest);
12485
+ const root = path13.dirname(absoluteManifest);
12082
12486
  const recorded = new Map(
12083
- previous?.outputs.map((output) => [path11.resolve(root, output.path), output.sha256]) ?? []
12487
+ previous?.outputs.map((output) => [path13.resolve(root, output.path), output.sha256]) ?? []
12084
12488
  );
12085
12489
  const conflicts = [];
12086
12490
  for (const output of outputs) {
12087
- const destination = path11.resolve(output.path);
12491
+ const destination = path13.resolve(output.path);
12088
12492
  const current = await readOptional(destination);
12089
12493
  if (!current || digest(current) === digest(output.data)) continue;
12090
12494
  const expected = recorded.get(destination);
@@ -12106,15 +12510,15 @@ Pass { force: true } (CLI: --force) to take ownership and replace the complete b
12106
12510
  );
12107
12511
  }
12108
12512
  async function verifyArtifactBundle(manifestPath) {
12109
- const absolute = path11.resolve(manifestPath);
12513
+ const absolute = path13.resolve(manifestPath);
12110
12514
  const raw = await readArtifactBundleManifest(absolute);
12111
- const root = path11.dirname(absolute);
12515
+ const root = path13.dirname(absolute);
12112
12516
  const changedSources = [];
12113
12517
  const changedOutputs = [];
12114
12518
  for (const source of raw.sources) {
12115
12519
  let actual = null;
12116
12520
  try {
12117
- actual = digest(await readFile7(path11.resolve(root, source.path)));
12521
+ actual = digest(await readFile8(path13.resolve(root, source.path)));
12118
12522
  } catch (error) {
12119
12523
  if (!isCode(error, "ENOENT")) throw error;
12120
12524
  }
@@ -12122,7 +12526,7 @@ async function verifyArtifactBundle(manifestPath) {
12122
12526
  }
12123
12527
  for (const output of raw.outputs) {
12124
12528
  try {
12125
- if (digest(await readFile7(path11.resolve(root, output.path))) !== output.sha256) {
12529
+ if (digest(await readFile8(path13.resolve(root, output.path))) !== output.sha256) {
12126
12530
  changedOutputs.push(output.path);
12127
12531
  }
12128
12532
  } catch (error) {
@@ -12161,7 +12565,7 @@ async function rollback(prepared) {
12161
12565
  for (const artifact of [...prepared].reverse()) {
12162
12566
  if (!artifact.backup || !artifact.backedUp) continue;
12163
12567
  try {
12164
- await rename3(artifact.backup, artifact.destination);
12568
+ await rename4(artifact.backup, artifact.destination);
12165
12569
  artifact.backedUp = false;
12166
12570
  } catch (error) {
12167
12571
  errors.push(
@@ -12178,7 +12582,7 @@ async function writeArtifactBundle(files, options = {}) {
12178
12582
  if (!files.length) throw new Error("An artifact bundle must contain at least one file.");
12179
12583
  const normalized = files.map((file) => {
12180
12584
  if (!file.path.trim()) throw new Error("Artifact paths cannot be empty.");
12181
- return { destination: path11.resolve(file.path), data: Buffer.from(file.data) };
12585
+ return { destination: path13.resolve(file.path), data: Buffer.from(file.data) };
12182
12586
  });
12183
12587
  const destinations = /* @__PURE__ */ new Set();
12184
12588
  for (const artifact of normalized) {
@@ -12194,7 +12598,7 @@ async function writeArtifactBundle(files, options = {}) {
12194
12598
  const unchanged = [];
12195
12599
  for (const artifact of normalized) {
12196
12600
  try {
12197
- const current = await readFile7(artifact.destination);
12601
+ const current = await readFile8(artifact.destination);
12198
12602
  if (current.equals(artifact.data)) {
12199
12603
  unchanged.push(artifact.destination);
12200
12604
  } else {
@@ -12208,21 +12612,21 @@ async function writeArtifactBundle(files, options = {}) {
12208
12612
  if (!changed.length) return { changed: [], unchanged };
12209
12613
  const token = randomUUID3();
12210
12614
  for (const [index, artifact] of changed.entries()) {
12211
- const basename = path11.basename(artifact.destination);
12212
- artifact.stage = path11.join(
12213
- path11.dirname(artifact.destination),
12615
+ const basename = path13.basename(artifact.destination);
12616
+ artifact.stage = path13.join(
12617
+ path13.dirname(artifact.destination),
12214
12618
  `.${basename}.pixelkiln-stage-${token}-${index}`
12215
12619
  );
12216
12620
  if (artifact.existed) {
12217
- artifact.backup = path11.join(
12218
- path11.dirname(artifact.destination),
12621
+ artifact.backup = path13.join(
12622
+ path13.dirname(artifact.destination),
12219
12623
  `.${basename}.pixelkiln-backup-${token}-${index}`
12220
12624
  );
12221
12625
  }
12222
12626
  }
12223
- const journal = options.recoveryFile ? path11.resolve(options.recoveryFile) : null;
12627
+ const journal = options.recoveryFile ? path13.resolve(options.recoveryFile) : null;
12224
12628
  if (journal) {
12225
- await mkdir5(path11.dirname(journal), { recursive: true });
12629
+ await mkdir6(path13.dirname(journal), { recursive: true });
12226
12630
  const transaction = {
12227
12631
  format: "pixelkiln-artifact-transaction",
12228
12632
  version: 1,
@@ -12236,7 +12640,7 @@ async function writeArtifactBundle(files, options = {}) {
12236
12640
  }))
12237
12641
  };
12238
12642
  try {
12239
- await writeFile5(journal, JSON.stringify(transaction, null, 2) + "\n", { flag: "wx" });
12643
+ await writeFile6(journal, JSON.stringify(transaction, null, 2) + "\n", { flag: "wx" });
12240
12644
  activeTransactions.add(journal);
12241
12645
  } catch (error) {
12242
12646
  throw new Error(
@@ -12247,9 +12651,9 @@ async function writeArtifactBundle(files, options = {}) {
12247
12651
  }
12248
12652
  try {
12249
12653
  for (const [index, artifact] of changed.entries()) {
12250
- await mkdir5(path11.dirname(artifact.destination), { recursive: true });
12654
+ await mkdir6(path13.dirname(artifact.destination), { recursive: true });
12251
12655
  await options.beforeStage?.(artifact.destination, index);
12252
- await writeFile5(artifact.stage, artifact.data, { flag: "wx" });
12656
+ await writeFile6(artifact.stage, artifact.data, { flag: "wx" });
12253
12657
  }
12254
12658
  } catch (error) {
12255
12659
  const cleanupErrors2 = await rollback(changed);
@@ -12262,17 +12666,17 @@ async function writeArtifactBundle(files, options = {}) {
12262
12666
  try {
12263
12667
  for (const artifact of changed) {
12264
12668
  if (!artifact.existed) continue;
12265
- await rename3(artifact.destination, artifact.backup);
12669
+ await rename4(artifact.destination, artifact.backup);
12266
12670
  artifact.backedUp = true;
12267
12671
  }
12268
12672
  for (const [index, artifact] of changed.entries()) {
12269
12673
  await options.beforePromote?.(artifact.destination, index);
12270
- await rename3(artifact.stage, artifact.destination);
12674
+ await rename4(artifact.stage, artifact.destination);
12271
12675
  artifact.stage = void 0;
12272
12676
  artifact.promoted = true;
12273
12677
  }
12274
12678
  if (journal) {
12275
- await writeFile5(transactionMarker(journal), `${token}
12679
+ await writeFile6(transactionMarker(journal), `${token}
12276
12680
  `, { flag: "wx" });
12277
12681
  durableCommit = true;
12278
12682
  await options.afterCommit?.();
@@ -12513,16 +12917,16 @@ function sameFrameGrid(first, next) {
12513
12917
  return next.detection.stepX === first.detection.stepX && next.detection.stepY === first.detection.stepY && next.detection.columns === first.detection.columns && next.detection.rows === first.detection.rows && phaseMatches(next.detection.phaseX, first.detection.phaseX, first.detection.stepX) && phaseMatches(next.detection.phaseY, first.detection.phaseY, first.detection.stepY) && next.audit.width === first.audit.width && next.audit.height === first.audit.height && next.sourceWidth === first.sourceWidth && next.sourceHeight === first.sourceHeight;
12514
12918
  }
12515
12919
  async function refineAsset(options) {
12516
- const source = path12.resolve(options.source);
12517
- const output = path12.resolve(options.output);
12920
+ const source = path14.resolve(options.source);
12921
+ const output = path14.resolve(options.output);
12518
12922
  if (source === output) throw new Error("Refinement source and output must be different files.");
12519
- const record = path12.resolve(qualityRecordPath(output));
12923
+ const record = path14.resolve(qualityRecordPath(output));
12520
12924
  const palette = normalizePalette(options.palette).map((color) => color.hex);
12521
12925
  const minGridConfidence = requireConfidence(options.minGridConfidence ?? "high");
12522
12926
  if (options.minTransparency !== void 0 && (!Number.isFinite(options.minTransparency) || options.minTransparency < 0 || options.minTransparency > 1)) throw new Error("minTransparency must be between 0 and 1.");
12523
12927
  let sourcePng;
12524
12928
  try {
12525
- sourcePng = decodePng(await readFile8(source));
12929
+ sourcePng = decodePng(await readFile9(source));
12526
12930
  } catch (error) {
12527
12931
  throw new Error(`Cannot read refinement source ${source}: ${message2(error)}`, { cause: error });
12528
12932
  }
@@ -12539,8 +12943,8 @@ async function refineAsset(options) {
12539
12943
  );
12540
12944
  }
12541
12945
  }
12542
- const temp = await mkdtemp(path12.join(tmpdir(), "pixelkiln-refine-"));
12543
- const recovered = path12.join(temp, "native.png");
12946
+ const temp = await mkdtemp(path14.join(tmpdir(), "pixelkiln-refine-"));
12947
+ const recovered = path14.join(temp, "native.png");
12544
12948
  const fixerCommand = compatibilityCommand ?? options.fixerPython ?? process.env.PIXELKILN_PIXEL_FIXER_PYTHON ?? "python3";
12545
12949
  const args = compatibilityCommand ? [...options.fixerArgsPrefix ?? [], source, "--extract", recovered] : ["-c", PYTHON_FIXER_BRIDGE, source, recovered];
12546
12950
  try {
@@ -12561,7 +12965,7 @@ async function refineAsset(options) {
12561
12965
  );
12562
12966
  }
12563
12967
  const detection = parseDetection(firstJsonObject(stdout));
12564
- const native = decodePng(await readFile8(recovered));
12968
+ const native = decodePng(await readFile9(recovered));
12565
12969
  const quantized = quantizeToPalette(native, palette);
12566
12970
  const png = encodeRgbaPng(quantized.width, quantized.height, quantized.pixels);
12567
12971
  const audit = auditRefinement(
@@ -12625,18 +13029,18 @@ async function refineFrameSet(options) {
12625
13029
  if (roles.some((role) => !role.trim()) || new Set(roles).size !== roles.length) {
12626
13030
  throw new Error("Frame-set roles must be non-empty and unique.");
12627
13031
  }
12628
- const output = path12.resolve(options.output);
12629
- const record = path12.resolve(qualityRecordPath(output));
13032
+ const output = path14.resolve(options.output);
13033
+ const record = path14.resolve(qualityRecordPath(output));
12630
13034
  const palette = normalizeRefinementPalette(options.palette);
12631
13035
  const finalOutputs = options.sources.map((source, index) => qualityFrameOutputPath(output, source.role, index));
12632
13036
  if (new Set(finalOutputs).size !== finalOutputs.length) {
12633
13037
  throw new Error("Frame-set roles resolve to duplicate output filenames.");
12634
13038
  }
12635
- const sourceSet = new Set(options.sources.map((source) => path12.resolve(source.path)));
13039
+ const sourceSet = new Set(options.sources.map((source) => path14.resolve(source.path)));
12636
13040
  if (finalOutputs.some((file) => sourceSet.has(file))) {
12637
13041
  throw new Error("Frame-set refinement sources and outputs must be different files.");
12638
13042
  }
12639
- const temp = await mkdtemp(path12.join(tmpdir(), "pixelkiln-refine-frames-"));
13043
+ const temp = await mkdtemp(path14.join(tmpdir(), "pixelkiln-refine-frames-"));
12640
13044
  try {
12641
13045
  const frames = [];
12642
13046
  const outputs = [];
@@ -12644,8 +13048,8 @@ async function refineFrameSet(options) {
12644
13048
  const sourcePaths = [];
12645
13049
  let firstOptions = null;
12646
13050
  for (const [index, sourceEntry] of options.sources.entries()) {
12647
- const source = path12.resolve(sourceEntry.path);
12648
- const temporaryOutput = path12.join(temp, `${String(index).padStart(2, "0")}.png`);
13051
+ const source = path14.resolve(sourceEntry.path);
13052
+ const temporaryOutput = path14.join(temp, `${String(index).padStart(2, "0")}.png`);
12649
13053
  const refined = await refineAsset({
12650
13054
  source,
12651
13055
  output: temporaryOutput,
@@ -12677,7 +13081,7 @@ async function refineFrameSet(options) {
12677
13081
  });
12678
13082
  outputs.push({
12679
13083
  path: finalOutputs[index],
12680
- data: await readFile8(temporaryOutput)
13084
+ data: await readFile9(temporaryOutput)
12681
13085
  });
12682
13086
  }
12683
13087
  const first = frames[0];
@@ -12720,7 +13124,7 @@ async function refineFrameSet(options) {
12720
13124
  );
12721
13125
  return {
12722
13126
  sources: sourcePaths,
12723
- outputs: outputs.map((item) => path12.resolve(item.path)),
13127
+ outputs: outputs.map((item) => path14.resolve(item.path)),
12724
13128
  record,
12725
13129
  frames,
12726
13130
  palette,
@@ -12731,12 +13135,12 @@ async function refineFrameSet(options) {
12731
13135
  }
12732
13136
  }
12733
13137
  async function checkQualityRecord(recordPath) {
12734
- const record = path12.resolve(recordPath);
13138
+ const record = path14.resolve(recordPath);
12735
13139
  const manifest = await readArtifactBundleManifest(record);
12736
13140
  const options = parseRecordOptions(manifest, record);
12737
13141
  const verification = await verifyArtifactBundle(record);
12738
- const sources = manifest.sources.map((source2) => path12.resolve(path12.dirname(record), source2.path));
12739
- const outputs = manifest.outputs.map((output2) => path12.resolve(path12.dirname(record), output2.path));
13142
+ const sources = manifest.sources.map((source2) => path14.resolve(path14.dirname(record), source2.path));
13143
+ const outputs = manifest.outputs.map((output2) => path14.resolve(path14.dirname(record), output2.path));
12740
13144
  const source = sources[0] ?? "";
12741
13145
  const output = outputs[0] ?? "";
12742
13146
  const expectedCount = options.frameSet?.count ?? 1;
@@ -12769,7 +13173,7 @@ async function checkQualityRecord(recordPath) {
12769
13173
  async function approveQualityRecord(recordPath, approval) {
12770
13174
  const reviewer = approval.reviewer.trim();
12771
13175
  if (!reviewer) throw new Error("A human reviewer name is required.");
12772
- const record = path12.resolve(recordPath);
13176
+ const record = path14.resolve(recordPath);
12773
13177
  const manifest = await readArtifactBundleManifest(record);
12774
13178
  const options = parseRecordOptions(manifest, record);
12775
13179
  const verification = await verifyArtifactBundle(record);
@@ -12790,14 +13194,14 @@ async function approveQualityRecord(recordPath, approval) {
12790
13194
  `A refinement record must contain exactly ${expectedCount} source(s) and output(s).`
12791
13195
  );
12792
13196
  }
12793
- const root = path12.dirname(record);
13197
+ const root = path14.dirname(record);
12794
13198
  const outputs = await Promise.all(manifest.outputs.map(async (entry) => {
12795
- const outputPath = path12.resolve(root, entry.path);
12796
- return { path: outputPath, data: await readFile8(outputPath) };
13199
+ const outputPath = path14.resolve(root, entry.path);
13200
+ return { path: outputPath, data: await readFile9(outputPath) };
12797
13201
  }));
12798
13202
  const sources = manifest.sources.map((source) => ({
12799
13203
  ...source,
12800
- path: path12.resolve(root, source.path)
13204
+ path: path14.resolve(root, source.path)
12801
13205
  }));
12802
13206
  const approved = {
12803
13207
  ...options,
@@ -12829,8 +13233,8 @@ async function qualitySource(spec, lock) {
12829
13233
  if (spec.generator === "frames") {
12830
13234
  return { items: null, reason: "frame-set quality requires ordered downloaded provider outputs" };
12831
13235
  }
12832
- const source = path13.resolve(spec.root, spec.source);
12833
- return existsSync9(source) ? { items: [{ role: "source", path: source }] } : { items: null, reason: `declared source is missing: ${spec.source}` };
13236
+ const source = path15.resolve(spec.root, spec.source);
13237
+ return existsSync11(source) ? { items: [{ role: "source", path: source }] } : { items: null, reason: `declared source is missing: ${spec.source}` };
12834
13238
  }
12835
13239
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
12836
13240
  if (!entry) return { items: null, reason: "raw provider output is not in the lockfile" };
@@ -12859,7 +13263,7 @@ async function qualitySource(spec, lock) {
12859
13263
  }
12860
13264
  if (role) roles.add(role);
12861
13265
  const source = currentEntryOutputPath(entry, spec, index);
12862
- if (!existsSync9(source)) return { items: null, reason: `raw provider output is missing: ${source}` };
13266
+ if (!existsSync11(source)) return { items: null, reason: `raw provider output is missing: ${source}` };
12863
13267
  if (await sha256File(source) !== output.sha256) {
12864
13268
  return { items: null, reason: "raw provider output was modified after download" };
12865
13269
  }
@@ -12869,18 +13273,18 @@ async function qualitySource(spec, lock) {
12869
13273
  }
12870
13274
  async function inspectQualityProfile(spec, lock) {
12871
13275
  if (!spec.quality) return null;
12872
- const key = lockKey(spec.styleId, spec.assetId);
13276
+ const key2 = lockKey(spec.styleId, spec.assetId);
12873
13277
  const output = spec.quality.outFile;
12874
13278
  const record = qualityRecordPath(output);
12875
13279
  const source = await qualitySource(spec, lock);
12876
13280
  if (!source.items) {
12877
- return { key, state: "blocked", reason: source.reason, source: null, output, record };
13281
+ return { key: key2, state: "blocked", reason: source.reason, source: null, output, record };
12878
13282
  }
12879
13283
  const sourcePaths = source.items.map((item) => item.path);
12880
13284
  const expectedOutputs = spec.generator === "frames" ? source.items.map((item, index) => qualityFrameOutputPath(output, item.role, index)) : [output];
12881
- if (!existsSync9(record)) {
13285
+ if (!existsSync11(record)) {
12882
13286
  return {
12883
- key,
13287
+ key: key2,
12884
13288
  state: "needs-refinement",
12885
13289
  reason: "no refinement record",
12886
13290
  source: sourcePaths[0],
@@ -12896,10 +13300,10 @@ async function inspectQualityProfile(spec, lock) {
12896
13300
  const expectedRevision = spec.quality.fixerRevision ?? PIXEL_ART_FIXER_REVISION;
12897
13301
  const expectedTransparency = spec.quality.minTransparency ?? null;
12898
13302
  const expectedFrameSet = spec.generator === "frames" ? { fps: spec.quality.fps ?? 12, count: source.items.length, roles: source.items.map((item) => item.role) } : null;
12899
- const contractChanged = JSON.stringify(check.sources.map((item) => path13.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => path13.resolve(item))) || JSON.stringify(check.outputs.map((item) => path13.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => path13.resolve(item))) || JSON.stringify(check.options.palette.colors) !== JSON.stringify(expectedPalette) || check.options.nativeGrid.revision !== expectedRevision || check.options.audit.thresholds.minGridConfidence !== spec.quality.minGridConfidence || check.options.audit.thresholds.minTransparency !== expectedTransparency || (expectedFrameSet ? !check.options.frameSet || check.options.frameSet.fps !== expectedFrameSet.fps || check.options.frameSet.count !== expectedFrameSet.count || JSON.stringify(check.options.frameSet.roles) !== JSON.stringify(expectedFrameSet.roles) : check.options.frameSet !== void 0);
13303
+ const contractChanged = JSON.stringify(check.sources.map((item) => path15.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => path15.resolve(item))) || JSON.stringify(check.outputs.map((item) => path15.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => path15.resolve(item))) || JSON.stringify(check.options.palette.colors) !== JSON.stringify(expectedPalette) || check.options.nativeGrid.revision !== expectedRevision || check.options.audit.thresholds.minGridConfidence !== spec.quality.minGridConfidence || check.options.audit.thresholds.minTransparency !== expectedTransparency || (expectedFrameSet ? !check.options.frameSet || check.options.frameSet.fps !== expectedFrameSet.fps || check.options.frameSet.count !== expectedFrameSet.count || JSON.stringify(check.options.frameSet.roles) !== JSON.stringify(expectedFrameSet.roles) : check.options.frameSet !== void 0);
12900
13304
  if (contractChanged) {
12901
13305
  return {
12902
- key,
13306
+ key: key2,
12903
13307
  state: "needs-refinement",
12904
13308
  reason: "quality profile changed",
12905
13309
  source: sourcePaths[0],
@@ -12911,7 +13315,7 @@ async function inspectQualityProfile(spec, lock) {
12911
13315
  }
12912
13316
  if (!check.current || !check.auditSafe) {
12913
13317
  return {
12914
- key,
13318
+ key: key2,
12915
13319
  state: "needs-refinement",
12916
13320
  reason: check.reasons.filter((reason) => reason !== "human 1\xD7 review is pending").join("; ") || "refinement record is stale",
12917
13321
  source: sourcePaths[0],
@@ -12923,7 +13327,7 @@ async function inspectQualityProfile(spec, lock) {
12923
13327
  }
12924
13328
  if (!check.approved) {
12925
13329
  return {
12926
- key,
13330
+ key: key2,
12927
13331
  state: "needs-approval",
12928
13332
  reason: "automated checks passed; human 1\xD7 review is pending",
12929
13333
  source: sourcePaths[0],
@@ -12934,7 +13338,7 @@ async function inspectQualityProfile(spec, lock) {
12934
13338
  };
12935
13339
  }
12936
13340
  return {
12937
- key,
13341
+ key: key2,
12938
13342
  state: "approved",
12939
13343
  reason: "refined output and human approval are current",
12940
13344
  source: sourcePaths[0],
@@ -12945,7 +13349,7 @@ async function inspectQualityProfile(spec, lock) {
12945
13349
  };
12946
13350
  } catch (error) {
12947
13351
  return {
12948
- key,
13352
+ key: key2,
12949
13353
  state: "needs-refinement",
12950
13354
  reason: `invalid refinement record: ${error instanceof Error ? error.message : String(error)}`,
12951
13355
  source: sourcePaths[0],
@@ -13059,10 +13463,11 @@ async function requireApprovedQualitySources(specs, lock, assetIds, outputRoles)
13059
13463
  }
13060
13464
 
13061
13465
  // src/pipeline/revision.ts
13062
- import { existsSync as existsSync10 } from "fs";
13063
- import path14 from "path";
13466
+ import { existsSync as existsSync12 } from "fs";
13467
+ import path16 from "path";
13064
13468
  async function inspectRevisionReadiness(spec, lock) {
13065
13469
  if (spec.mirror) return inspectMirror(spec, lock, /* @__PURE__ */ new Set());
13470
+ if (spec.derive) return inspectDerive(spec, lock, /* @__PURE__ */ new Set());
13066
13471
  if (spec.character?.kind === "outfit") return inspectOutfit(spec, lock, /* @__PURE__ */ new Set());
13067
13472
  if (spec.character?.parentSpec) {
13068
13473
  const parent = await inspectCharacterParent(spec, lock, /* @__PURE__ */ new Set());
@@ -13081,7 +13486,7 @@ async function inspectStyleAnchor(spec, lock, seen) {
13081
13486
  const label = `style anchor ${spec.styleId}/${anchor.assetId}`;
13082
13487
  const dependency = await inspectParent(anchor.spec, lock, seen);
13083
13488
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13084
- if (!anchor.sha256 || !existsSync10(anchor.file)) return { ready: false, reason: `${label} has no generated south-facing file yet` };
13489
+ if (!anchor.sha256 || !existsSync12(anchor.file)) return { ready: false, reason: `${label} has no generated south-facing file yet` };
13085
13490
  if (await sha256File(anchor.file) !== anchor.sha256) {
13086
13491
  return { ready: false, reason: `${label} changed after the manifest was resolved` };
13087
13492
  }
@@ -13118,14 +13523,14 @@ async function inspectScene(spec) {
13118
13523
  const files = [{ label: "scene image", file: scene.file, sha256: scene.sha256 }];
13119
13524
  if (scene.placement.type === "mask") files.push({ label: "scene mask", file: scene.placement.file, sha256: scene.placement.sha256 });
13120
13525
  for (const { label, file, sha256: sha2562 } of files) {
13121
- if (!sha2562 || !existsSync10(file)) return { ready: false, reason: `${label} does not exist yet: ${file}` };
13526
+ if (!sha2562 || !existsSync12(file)) return { ready: false, reason: `${label} does not exist yet: ${file}` };
13122
13527
  if (await sha256File(file) !== sha2562) return { ready: false, reason: `${label} changed after the manifest was resolved` };
13123
13528
  }
13124
13529
  return { ready: true, reason: "scene is current" };
13125
13530
  }
13126
13531
  async function inspectVfxSprite(spec) {
13127
13532
  const sprite = spec.vfx.sprite;
13128
- if (!sprite.sha256 || !existsSync10(sprite.file)) return { ready: false, reason: `vfx sprite does not exist yet: ${sprite.file}` };
13533
+ if (!sprite.sha256 || !existsSync12(sprite.file)) return { ready: false, reason: `vfx sprite does not exist yet: ${sprite.file}` };
13129
13534
  if (await sha256File(sprite.file) !== sprite.sha256) return { ready: false, reason: "vfx sprite changed after the manifest was resolved" };
13130
13535
  return { ready: true, reason: "vfx sprite is current" };
13131
13536
  }
@@ -13135,13 +13540,22 @@ async function inspectMirror(spec, lock, seen) {
13135
13540
  const dependency = await inspectParent(source, lock, seen);
13136
13541
  return dependency.ready ? { ready: true, reason: `${label} is current` } : { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13137
13542
  }
13543
+ async function inspectDerive(spec, lock, seen) {
13544
+ const source = spec.derive.source;
13545
+ if (source.kind === "file") {
13546
+ return existsSync12(path16.resolve(spec.root, source.file)) ? { ready: true, reason: `source file ${source.file} exists` } : { ready: false, reason: `derive source file does not exist: ${source.file}` };
13547
+ }
13548
+ const label = `derive source ${spec.styleId}/${source.assetId}`;
13549
+ const dependency = await inspectParent(source.spec, lock, seen);
13550
+ return dependency.ready ? { ready: true, reason: `${label} is current` } : { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13551
+ }
13138
13552
  async function inspectOutfit(spec, lock, seen) {
13139
13553
  const character = spec.character;
13140
13554
  const outfit = character.outfit;
13141
13555
  const label = `outfit source ${spec.styleId}/${character.parentAssetId}`;
13142
13556
  const dependency = await inspectParent(character.parentSpec, lock, seen);
13143
13557
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13144
- if (!existsSync10(outfit.reference.path)) {
13558
+ if (!existsSync12(outfit.reference.path)) {
13145
13559
  return { ready: false, reason: `outfit reference is missing: ${outfit.reference.path}` };
13146
13560
  }
13147
13561
  if (await sha256File(outfit.reference.path) !== outfit.reference.sha256) {
@@ -13155,7 +13569,7 @@ async function inspectCharacterParent(spec, lock, seen) {
13155
13569
  const label = `${character.kind} parent ${spec.styleId}/${character.parentAssetId}`;
13156
13570
  const dependency = await inspectParent(parentSpec, lock, seen);
13157
13571
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13158
- if (!character.parentSha256 || !character.parentFile || !existsSync10(character.parentFile)) {
13572
+ if (!character.parentSha256 || !character.parentFile || !existsSync12(character.parentFile)) {
13159
13573
  return { ready: false, reason: `${label} has no generated south-facing file yet` };
13160
13574
  }
13161
13575
  if (await sha256File(character.parentFile) !== character.parentSha256) {
@@ -13173,7 +13587,7 @@ async function inspectObjectProParent(spec, lock, seen) {
13173
13587
  const label = `${object.kind} parent ${spec.styleId}/${object.parentAssetId}`;
13174
13588
  const dependency = await inspectParent(parentSpec, lock, seen);
13175
13589
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13176
- if (!object.parentSha256 || !object.parentFile || !existsSync10(object.parentFile)) {
13590
+ if (!object.parentSha256 || !object.parentFile || !existsSync12(object.parentFile)) {
13177
13591
  return { ready: false, reason: `${label} has no generated south-facing file yet` };
13178
13592
  }
13179
13593
  if (await sha256File(object.parentFile) !== object.parentSha256) {
@@ -13199,7 +13613,7 @@ async function inspectRevision(spec, lock, seen) {
13199
13613
  const members = await inspectSourceMembers(spec, lock);
13200
13614
  if (!members.ready) return members;
13201
13615
  } else {
13202
- if (!revision.sourceSha256 || !existsSync10(revision.sourceFile)) {
13616
+ if (!revision.sourceSha256 || !existsSync12(revision.sourceFile)) {
13203
13617
  return { ready: false, reason: `revision source is missing: ${revision.sourceFile}` };
13204
13618
  }
13205
13619
  if (await sha256File(revision.sourceFile) !== revision.sourceSha256) {
@@ -13207,7 +13621,7 @@ async function inspectRevision(spec, lock, seen) {
13207
13621
  }
13208
13622
  }
13209
13623
  if (revision.maskFile) {
13210
- if (!revision.maskSha256 || !existsSync10(revision.maskFile)) {
13624
+ if (!revision.maskSha256 || !existsSync12(revision.maskFile)) {
13211
13625
  return { ready: false, reason: `revision mask is missing: ${revision.maskFile}` };
13212
13626
  }
13213
13627
  if (await sha256File(revision.maskFile) !== revision.maskSha256) {
@@ -13215,7 +13629,7 @@ async function inspectRevision(spec, lock, seen) {
13215
13629
  }
13216
13630
  }
13217
13631
  if (revision.lastFrameFile) {
13218
- if (!revision.lastFrameSha256 || !existsSync10(revision.lastFrameFile)) {
13632
+ if (!revision.lastFrameSha256 || !existsSync12(revision.lastFrameFile)) {
13219
13633
  return { ready: false, reason: `revision last frame is missing: ${revision.lastFrameFile}` };
13220
13634
  }
13221
13635
  if (await sha256File(revision.lastFrameFile) !== revision.lastFrameSha256) {
@@ -13228,7 +13642,7 @@ async function inspectSourceMembers(spec, lock) {
13228
13642
  const revision = spec.revision;
13229
13643
  const members = revision.sourceMembers;
13230
13644
  for (const member of members) {
13231
- if (!existsSync10(member.file)) return { ready: false, reason: `revision source member is missing: ${member.file}` };
13645
+ if (!existsSync12(member.file)) return { ready: false, reason: `revision source member is missing: ${member.file}` };
13232
13646
  if (await sha256File(member.file) !== member.sha256) {
13233
13647
  return { ready: false, reason: `revision source member changed after the manifest was resolved: ${member.file}` };
13234
13648
  }
@@ -13237,8 +13651,8 @@ async function inspectSourceMembers(spec, lock) {
13237
13651
  if (parent.source) return { ready: true, reason: "declared source set is present" };
13238
13652
  const entry = lock.entries[lockKey(parent.styleId, parent.assetId)];
13239
13653
  if (!entry) return { ready: false, reason: "revision source is not in the lockfile" };
13240
- const recorded = entry.outputs.map((_, index) => path14.resolve(currentEntryOutputPath(entry, parent, index))).sort();
13241
- const found = members.map((member) => path14.resolve(member.file)).sort();
13654
+ const recorded = entry.outputs.map((_, index) => path16.resolve(currentEntryOutputPath(entry, parent, index))).sort();
13655
+ const found = members.map((member) => path16.resolve(member.file)).sort();
13242
13656
  if (recorded.length !== found.length || recorded.some((file, index) => file !== found[index])) {
13243
13657
  return {
13244
13658
  ready: false,
@@ -13252,10 +13666,10 @@ async function requireRevisionReady(spec, lock) {
13252
13666
  if (inspection && !inspection.ready) throw new Error(inspection.reason);
13253
13667
  }
13254
13668
  async function inspectParent(spec, lock, seen) {
13255
- const key = lockKey(spec.styleId, spec.assetId);
13256
- if (seen.has(key)) return { ready: false, reason: `revision dependency cycle at ${key}` };
13669
+ const key2 = lockKey(spec.styleId, spec.assetId);
13670
+ if (seen.has(key2)) return { ready: false, reason: `revision dependency cycle at ${key2}` };
13257
13671
  const nextSeen = new Set(seen);
13258
- nextSeen.add(key);
13672
+ nextSeen.add(key2);
13259
13673
  if (spec.mirror) {
13260
13674
  const inputs = await inspectMirror(spec, lock, nextSeen);
13261
13675
  if (!inputs.ready) return inputs;
@@ -13295,10 +13709,10 @@ async function inspectParent(spec, lock, seen) {
13295
13709
  };
13296
13710
  }
13297
13711
  if (spec.source) {
13298
- const source = path14.resolve(spec.root, spec.source);
13299
- return existsSync10(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
13712
+ const source = path16.resolve(spec.root, spec.source);
13713
+ return existsSync12(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
13300
13714
  }
13301
- const entry = lock.entries[key];
13715
+ const entry = lock.entries[key2];
13302
13716
  if (!entry) return { ready: false, reason: "parent is not in the lockfile" };
13303
13717
  if (entry.specHash !== spec.specHash) {
13304
13718
  return { ready: false, reason: "parent generation spec is stale" };
@@ -13310,7 +13724,7 @@ async function inspectParent(spec, lock, seen) {
13310
13724
  for (let index = 0; index < entry.outputs.length; index++) {
13311
13725
  const output = entry.outputs[index];
13312
13726
  const file = currentEntryOutputPath(entry, spec, index);
13313
- if (!existsSync10(file)) return { ready: false, reason: `parent output is missing: ${file}` };
13727
+ if (!existsSync12(file)) return { ready: false, reason: `parent output is missing: ${file}` };
13314
13728
  if (await sha256File(file) !== output.sha256) {
13315
13729
  return { ready: false, reason: `parent output was modified: ${file}` };
13316
13730
  }
@@ -13329,6 +13743,7 @@ async function anyOutputModified(entry, spec) {
13329
13743
  function dependencies(spec) {
13330
13744
  return [
13331
13745
  spec.mirror?.sourceSpec,
13746
+ spec.derive?.source.kind === "asset" ? spec.derive.source.spec : void 0,
13332
13747
  spec.revision?.sourceSpec,
13333
13748
  spec.character?.parentSpec,
13334
13749
  spec.character?.motionLeader?.spec,
@@ -13372,15 +13787,15 @@ function resumeCommandForStatus(status) {
13372
13787
  function resumeActions(specs, lock) {
13373
13788
  const grouped = /* @__PURE__ */ new Map();
13374
13789
  for (const spec of specs) {
13375
- const key = lockKey(spec.styleId, spec.assetId);
13376
- const entry = lock.entries[key];
13790
+ const key2 = lockKey(spec.styleId, spec.assetId);
13791
+ const entry = lock.entries[key2];
13377
13792
  if (!entry || entry.specHash !== spec.specHash) continue;
13378
13793
  if (entry.submissionComplete === false) continue;
13379
13794
  const command = resumeCommandForStatus(entry.status) ?? (entry.status === "downloaded" && entry.outputs.length && !postprocessCurrent(entry, spec) ? "fetch" : null);
13380
13795
  if (!command) continue;
13381
13796
  if (command === "poll" && !entry.jobId) continue;
13382
13797
  if (command === "pick" && !entry.reviewObjectId) continue;
13383
- grouped.set(command, [...grouped.get(command) ?? [], key]);
13798
+ grouped.set(command, [...grouped.get(command) ?? [], key2]);
13384
13799
  }
13385
13800
  return ["poll", "pick", "fetch"].flatMap((command) => {
13386
13801
  const keys = grouped.get(command);
@@ -13390,22 +13805,26 @@ function resumeActions(specs, lock) {
13390
13805
  async function buildPlan(specs, lock, opts = {}) {
13391
13806
  const items = [];
13392
13807
  for (const spec of specs) {
13393
- const key = lockKey(spec.styleId, spec.assetId);
13394
- const entry = lock.entries[key];
13808
+ const key2 = lockKey(spec.styleId, spec.assetId);
13809
+ const entry = lock.entries[key2];
13395
13810
  let state;
13396
13811
  let reason;
13397
13812
  const changedConnection = entry ? changedTerrainConnection(spec, entry, lock) : null;
13398
13813
  const changedMotion = entry ? changedMotionLeader(spec, entry, lock) : null;
13399
13814
  const changedSettings = entry ? changedTerrainSettings(spec, entry) : null;
13815
+ const derivedStale = spec.derive && entry ? await deriveStale(spec, entry, lock) : null;
13400
13816
  const revision = await inspectRevisionReadiness(spec, lock);
13401
13817
  if (revision && !revision.ready) {
13402
13818
  state = "blocked";
13403
13819
  reason = revision.reason;
13820
+ } else if (spec.external) {
13821
+ ;
13822
+ ({ state, reason } = await inspectExternal(spec, entry));
13404
13823
  } else if (opts.force) {
13405
13824
  state = "missing";
13406
13825
  reason = "--force";
13407
13826
  } else if (!entry && spec.source && spec.generator !== "frames" && spec.generator !== "vfx") {
13408
- if (existsSync11(path15.resolve(spec.root, spec.source))) {
13827
+ if (existsSync13(path17.resolve(spec.root, spec.source))) {
13409
13828
  state = "ok";
13410
13829
  reason = `placed from ${spec.source}; not generated`;
13411
13830
  } else {
@@ -13413,20 +13832,26 @@ async function buildPlan(specs, lock, opts = {}) {
13413
13832
  reason = `declared source is missing: ${spec.source}`;
13414
13833
  }
13415
13834
  } else if (!entry) {
13416
- if (existsSync11(spec.outFile)) {
13835
+ if (existsSync13(spec.outFile)) {
13417
13836
  state = "untracked";
13418
13837
  reason = "file on disk, no provenance recorded";
13419
13838
  } else {
13420
13839
  state = "missing";
13421
- reason = spec.mirror ? `not made yet; flipped from ${spec.mirror.sourceAssetId} (no generation cost)` : "not in lockfile";
13840
+ reason = spec.mirror ? `not made yet; flipped from ${spec.mirror.sourceAssetId} (no generation cost)` : spec.derive ? `not made yet; derived from ${spec.derive.source.kind === "asset" ? spec.derive.source.assetId : spec.derive.source.file} (${spec.derive.transform}, no generation cost)` : "not in lockfile";
13422
13841
  }
13423
13842
  } else if (entry.specHash !== spec.specHash) {
13424
13843
  state = "stale";
13425
- reason = "prompt, size, or style changed";
13844
+ reason = spec.derive ? "transform, its parameters, or the source file changed; derive it again (no generation cost)" : "prompt, size, or style changed";
13845
+ } else if (derivedStale) {
13846
+ state = "stale";
13847
+ reason = `${derivedStale}; derive it again (no generation cost)`;
13848
+ } else if (spec.derive && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index)))) {
13849
+ state = "stale";
13850
+ reason = "derived output missing on disk; derive it again (no generation cost)";
13426
13851
  } else if (spec.mirror && !mirrorCurrent(entry, lock.entries[lockKey(spec.styleId, spec.mirror.sourceAssetId)])) {
13427
13852
  state = "stale";
13428
13853
  reason = `mirror source ${spec.mirror.sourceAssetId} changed; flip it again (no generation cost)`;
13429
- } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync11(currentEntryOutputPath(entry, spec, index)))) {
13854
+ } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index)))) {
13430
13855
  state = "stale";
13431
13856
  reason = "mirror output missing on disk; flip it again (no generation cost)";
13432
13857
  } else if (spec.character?.kind === "outfit" && entry.outfit?.sourceSha256 !== mirrorSourceHash(lock.entries[lockKey(spec.styleId, spec.character.parentAssetId)] ?? { outputs: [] })) {
@@ -13463,12 +13888,15 @@ async function buildPlan(specs, lock, opts = {}) {
13463
13888
  } else if (entry.status !== "downloaded") {
13464
13889
  state = "in-flight";
13465
13890
  reason = `awaiting ${entry.status}`;
13466
- } else if (entry.outputs.length === 0 || entry.outputs.some((_output, index) => !existsSync11(currentEntryOutputPath(entry, spec, index)))) {
13891
+ } else if (entry.outputs.length === 0 || entry.outputs.some((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index)))) {
13467
13892
  state = "orphaned";
13468
- reason = entry.outputs.length === 0 ? "no recorded output files" : `missing on disk: ${entry.outputs.filter((_output, index) => !existsSync11(currentEntryOutputPath(entry, spec, index))).map((o) => o.role ?? "asset").join(", ")}`;
13893
+ reason = entry.outputs.length === 0 ? "no recorded output files" : `missing on disk: ${entry.outputs.filter((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index))).map((o) => o.role ?? "asset").join(", ")}`;
13469
13894
  } else if (await anyOutputModified(entry, spec)) {
13470
13895
  state = "orphaned";
13471
13896
  reason = "output modified since download";
13897
+ } else if (spec.derive) {
13898
+ state = "ok";
13899
+ reason = "up to date";
13472
13900
  } else if (spec.mirror && !postprocessCurrent(entry, spec)) {
13473
13901
  state = "stale";
13474
13902
  reason = "palette enforcement changed; flip the source again once it is refreshed (no generation cost)";
@@ -13480,7 +13908,7 @@ async function buildPlan(specs, lock, opts = {}) {
13480
13908
  reason = "up to date";
13481
13909
  }
13482
13910
  const quality = await inspectQualityProfile(spec, lock);
13483
- items.push({ spec, key, state, reason, ...quality ? { quality } : {} });
13911
+ items.push({ spec, key: key2, state, reason, ...quality ? { quality } : {} });
13484
13912
  }
13485
13913
  const isActionable = (i) => i.state === "missing" || i.state === "stale" || i.state === "failed";
13486
13914
  const stateOf = new Map(items.map((i) => [i.key, i.state]));
@@ -13494,7 +13922,7 @@ async function buildPlan(specs, lock, opts = {}) {
13494
13922
  item.reason = `parent ${parentKey} is being generated in this run; this follows in the next wave`;
13495
13923
  break;
13496
13924
  }
13497
- if (item.spec.mirror && (parentState === "recoverable" || parentState === "in-flight")) {
13925
+ if ((item.spec.mirror || item.spec.derive) && (parentState === "recoverable" || parentState === "in-flight")) {
13498
13926
  item.state = "blocked";
13499
13927
  item.reason = `mirror source ${parentKey} is ${parentState}; this follows in the next wave`;
13500
13928
  break;
@@ -13515,6 +13943,12 @@ async function buildPlan(specs, lock, opts = {}) {
13515
13943
  const provider = item.spec.provider;
13516
13944
  const costUnit = item.spec.costUnit ?? "generations";
13517
13945
  const group = groupsByProvider.get(provider);
13946
+ if (group && item.spec.derive) {
13947
+ group.actionable.push(item);
13948
+ group.candidates += item.spec.candidates;
13949
+ continue;
13950
+ }
13951
+ if (group && group.cost === 0 && group.actionable.every((other) => other.spec.derive)) group.costUnit = costUnit;
13518
13952
  if (group && group.costUnit !== costUnit) {
13519
13953
  throw new Error(
13520
13954
  `Provider "${provider}" returned mixed cost units (${group.costUnit}, ${costUnit})`
@@ -13564,15 +13998,21 @@ function summarize(plan) {
13564
13998
 
13565
13999
  // src/project.ts
13566
14000
  async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {}) {
13567
- const absolute = path16.resolve(manifestPath);
13568
- const root = path16.dirname(absolute);
14001
+ const absolute = path18.resolve(manifestPath);
14002
+ const root = path18.dirname(absolute);
13569
14003
  if (opts.env !== false) {
13570
14004
  loadEnvFiles(root);
13571
- if (path16.resolve(process.cwd()) !== root) loadEnvFiles(process.cwd());
13572
- }
13573
- const lockPath = path16.resolve(opts.lockPath ?? path16.join(root, "pixelkiln.lock.json"));
13574
- const loaded = await loadManifest(absolute);
13575
- const specs = await resolveSpecs(loaded, { styles: opts.styles ?? [], assets: opts.assets ?? [] });
14005
+ if (path18.resolve(process.cwd()) !== root) loadEnvFiles(process.cwd());
14006
+ }
14007
+ const lockPath = path18.resolve(opts.lockPath ?? path18.join(root, "pixelkiln.lock.json"));
14008
+ let loaded = await loadManifest(absolute, { lenient: opts.lenient });
14009
+ const unresolved = [];
14010
+ const specs = await resolveSpecs(loaded, {
14011
+ styles: opts.styles ?? [],
14012
+ assets: opts.assets ?? [],
14013
+ ...opts.lenient ? { onInvalid: (entry) => unresolved.push(entry) } : {}
14014
+ });
14015
+ if (unresolved.length) loaded = { ...loaded, invalid: [...loaded.invalid ?? [], ...unresolved] };
13576
14016
  const lock = await loadLock(lockPath);
13577
14017
  normalizeLockOutputPaths(lock, specs);
13578
14018
  const adapters = /* @__PURE__ */ new Map();
@@ -13588,11 +14028,11 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
13588
14028
  reload: () => openProject(absolute, { ...opts, env: false }),
13589
14029
  providers: () => [...new Set(specs.map((spec) => spec.provider))].sort(),
13590
14030
  provider: (id, mode2 = "online") => {
13591
- const key = `${mode2}:${id}`;
13592
- let adapter = adapters.get(key);
14031
+ const key2 = `${mode2}:${id}`;
14032
+ let adapter = adapters.get(key2);
13593
14033
  if (!adapter) {
13594
14034
  adapter = createProvider(id, mode2);
13595
- adapters.set(key, adapter);
14035
+ adapters.set(key2, adapter);
13596
14036
  }
13597
14037
  return adapter;
13598
14038
  }
@@ -13600,9 +14040,9 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
13600
14040
  }
13601
14041
 
13602
14042
  // src/recipes.ts
13603
- import path17 from "path";
13604
- import { existsSync as existsSync12 } from "fs";
13605
- import { readdir, readFile as readFile9 } from "fs/promises";
14043
+ import path19 from "path";
14044
+ import { existsSync as existsSync14 } from "fs";
14045
+ import { readdir, readFile as readFile10 } from "fs/promises";
13606
14046
  import { fileURLToPath } from "url";
13607
14047
  import { z as z4 } from "zod";
13608
14048
  var SHA256_RE = /^[0-9a-f]{64}$/;
@@ -13611,7 +14051,7 @@ var VERSION_RE = /^\d+\.\d+\.\d+$/;
13611
14051
  var RECIPE_FILE = "pixelkiln.recipe.json";
13612
14052
  var RECIPE_DIR_TOKEN = "{{recipeDir}}";
13613
14053
  var PortablePathSchema = z4.string().min(1).refine((value) => {
13614
- if (value.includes("\\") || path17.posix.isAbsolute(value)) return false;
14054
+ if (value.includes("\\") || path19.posix.isAbsolute(value)) return false;
13615
14055
  const parts = value.split("/");
13616
14056
  return !parts.includes("") && !parts.includes(".") && !parts.includes("..");
13617
14057
  }, "expected a portable relative path without '.', '..', or backslashes");
@@ -13771,9 +14211,9 @@ function canonical3(value) {
13771
14211
  if (Array.isArray(value)) return value.map(canonical3);
13772
14212
  if (typeof value === "object") {
13773
14213
  const sorted = {};
13774
- for (const key of Object.keys(value).sort()) {
13775
- const item = value[key];
13776
- if (item !== void 0) sorted[key] = canonical3(item);
14214
+ for (const key2 of Object.keys(value).sort()) {
14215
+ const item = value[key2];
14216
+ if (item !== void 0) sorted[key2] = canonical3(item);
13777
14217
  }
13778
14218
  return sorted;
13779
14219
  }
@@ -13787,10 +14227,10 @@ function message3(error) {
13787
14227
  return error instanceof Error ? error.message : String(error);
13788
14228
  }
13789
14229
  async function readRecipeFile(recipePath, bundled) {
13790
- const absolute = path17.resolve(recipePath);
14230
+ const absolute = path19.resolve(recipePath);
13791
14231
  let raw;
13792
14232
  try {
13793
- raw = JSON.parse(await readFile9(absolute, "utf8"));
14233
+ raw = JSON.parse(await readFile10(absolute, "utf8"));
13794
14234
  } catch (error) {
13795
14235
  throw new Error(`Could not read recipe ${absolute}: ${message3(error)}`, { cause: error });
13796
14236
  }
@@ -13801,13 +14241,13 @@ async function readRecipeFile(recipePath, bundled) {
13801
14241
  ` + parsed.error.issues.map((issue) => ` ${issue.path.join(".") || "$"}: ${issue.message}`).join("\n")
13802
14242
  );
13803
14243
  }
13804
- return { recipe: parsed.data, authored: raw, path: absolute, dir: path17.dirname(absolute), bundled };
14244
+ return { recipe: parsed.data, authored: raw, path: absolute, dir: path19.dirname(absolute), bundled };
13805
14245
  }
13806
14246
  async function walkRecipeFiles(root) {
13807
- if (!existsSync12(root)) return [];
14247
+ if (!existsSync14(root)) return [];
13808
14248
  const out = [];
13809
14249
  for (const entry of await readdir(root, { withFileTypes: true })) {
13810
- const resolved = path17.join(root, entry.name);
14250
+ const resolved = path19.join(root, entry.name);
13811
14251
  if (entry.isDirectory()) out.push(...await walkRecipeFiles(resolved));
13812
14252
  else if (entry.isFile() && entry.name === RECIPE_FILE) out.push(resolved);
13813
14253
  }
@@ -13818,7 +14258,7 @@ function bundledRecipeRoot() {
13818
14258
  }
13819
14259
  async function listBundledRecipes(root = bundledRecipeRoot()) {
13820
14260
  const recipes = await Promise.all(
13821
- (await walkRecipeFiles(path17.resolve(root))).map((file) => readRecipeFile(file, true))
14261
+ (await walkRecipeFiles(path19.resolve(root))).map((file) => readRecipeFile(file, true))
13822
14262
  );
13823
14263
  return recipes.sort(
13824
14264
  (a, b) => a.recipe.id.localeCompare(b.recipe.id) || compareVersions(b.recipe.version, a.recipe.version)
@@ -13841,9 +14281,9 @@ function parseSelector(selector) {
13841
14281
  return { id: match[1], version: match[2] };
13842
14282
  }
13843
14283
  async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
13844
- const local = path17.resolve(target);
13845
- if (existsSync12(local)) {
13846
- const recipePath = path17.basename(local) === RECIPE_FILE ? local : path17.join(local, RECIPE_FILE);
14284
+ const local = path19.resolve(target);
14285
+ if (existsSync14(local)) {
14286
+ const recipePath = path19.basename(local) === RECIPE_FILE ? local : path19.join(local, RECIPE_FILE);
13847
14287
  return readRecipeFile(recipePath, false);
13848
14288
  }
13849
14289
  if (target.startsWith(".") || target.startsWith("/") || target.includes("\\")) {
@@ -13857,8 +14297,8 @@ async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
13857
14297
  return matches[0];
13858
14298
  }
13859
14299
  async function verifyFile(root, file) {
13860
- const absolute = path17.resolve(root, ...file.path.split("/"));
13861
- if (!existsSync12(absolute)) {
14300
+ const absolute = path19.resolve(root, ...file.path.split("/"));
14301
+ if (!existsSync14(absolute)) {
13862
14302
  return { path: file.path, expectedSha256: file.sha256, actualSha256: null, status: "missing" };
13863
14303
  }
13864
14304
  const actualSha256 = await sha256File(absolute);
@@ -13873,7 +14313,7 @@ async function verifyRecipe(target, options = {}) {
13873
14313
  const loaded = await resolveRecipe(target, options.bundledRoot);
13874
14314
  const actualIntegrity = recipeDigest(loaded.authored);
13875
14315
  const files = await Promise.all(loaded.recipe.files.map((file) => verifyFile(loaded.dir, file)));
13876
- const modelRoot = options.modelRoot ? path17.resolve(options.modelRoot) : null;
14316
+ const modelRoot = options.modelRoot ? path19.resolve(options.modelRoot) : null;
13877
14317
  const models = modelRoot ? await Promise.all(loaded.recipe.models.map(async (model) => ({
13878
14318
  ...await verifyFile(modelRoot, model),
13879
14319
  source: model.source,
@@ -13907,37 +14347,37 @@ async function verifyRecipe(target, options = {}) {
13907
14347
  };
13908
14348
  }
13909
14349
  function renderStyle(style, destination, cwd) {
13910
- const portableDir = path17.relative(cwd, destination).split(path17.sep).join("/") || ".";
14350
+ const portableDir = path19.relative(cwd, destination).split(path19.sep).join("/") || ".";
13911
14351
  const replace = (value) => {
13912
14352
  if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
13913
14353
  if (Array.isArray(value)) return value.map(replace);
13914
14354
  if (value && typeof value === "object") {
13915
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, replace(item)]));
14355
+ return Object.fromEntries(Object.entries(value).map(([key2, item]) => [key2, replace(item)]));
13916
14356
  }
13917
14357
  return value;
13918
14358
  };
13919
14359
  return replace(style);
13920
14360
  }
13921
14361
  async function installRecipe(target, options = {}) {
13922
- const cwd = path17.resolve(options.cwd ?? process.cwd());
14362
+ const cwd = path19.resolve(options.cwd ?? process.cwd());
13923
14363
  const loaded = await resolveRecipe(target, options.bundledRoot);
13924
14364
  const verification = await verifyRecipe(loaded.path);
13925
14365
  if (!verification.ok) {
13926
14366
  throw new Error(`Recipe ${loaded.recipe.id}@${loaded.recipe.version} failed integrity verification.`);
13927
14367
  }
13928
- const destination = options.out ? path17.resolve(cwd, options.out) : path17.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
14368
+ const destination = options.out ? path19.resolve(cwd, options.out) : path19.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
13929
14369
  const sources = [
13930
14370
  { path: RECIPE_FILE, source: loaded.path },
13931
- ...loaded.recipe.files.map((file) => ({ path: file.path, source: path17.join(loaded.dir, ...file.path.split("/")) }))
14371
+ ...loaded.recipe.files.map((file) => ({ path: file.path, source: path19.join(loaded.dir, ...file.path.split("/")) }))
13932
14372
  ];
13933
14373
  const files = await Promise.all(sources.map(async (file) => ({
13934
- path: path17.join(destination, ...file.path.split("/")),
13935
- data: await readFile9(file.source)
14374
+ path: path19.join(destination, ...file.path.split("/")),
14375
+ data: await readFile10(file.source)
13936
14376
  })));
13937
14377
  if (!options.force) {
13938
14378
  for (const file of files) {
13939
- if (!existsSync12(file.path)) continue;
13940
- const current = await readFile9(file.path);
14379
+ if (!existsSync14(file.path)) continue;
14380
+ const current = await readFile10(file.path);
13941
14381
  if (!current.equals(file.data)) {
13942
14382
  throw new OverwriteRefusedError(
13943
14383
  `Recipe destination has local changes: ${file.path}. Choose another --out or pass --force to replace declared recipe files.`,
@@ -13961,9 +14401,9 @@ async function installRecipe(target, options = {}) {
13961
14401
  }
13962
14402
 
13963
14403
  // src/pipeline/audit.ts
13964
- import { readFile as readFile10 } from "fs/promises";
13965
- import { existsSync as existsSync13 } from "fs";
13966
- import path18 from "path";
14404
+ import { readFile as readFile11 } from "fs/promises";
14405
+ import { existsSync as existsSync15 } from "fs";
14406
+ import path20 from "path";
13967
14407
  function paletteDistance(asset, reference) {
13968
14408
  if (!asset.length || !reference.length) return 0;
13969
14409
  let total = 0;
@@ -13980,10 +14420,10 @@ function mergePalettes(palettes, topN = 24) {
13980
14420
  const totals = /* @__PURE__ */ new Map();
13981
14421
  for (const palette of palettes) {
13982
14422
  for (const color of palette) {
13983
- const key = `${color.r},${color.g},${color.b}`;
13984
- const existing = totals.get(key);
14423
+ const key2 = `${color.r},${color.g},${color.b}`;
14424
+ const existing = totals.get(key2);
13985
14425
  if (existing) existing.weight += color.weight;
13986
- else totals.set(key, { ...color });
14426
+ else totals.set(key2, { ...color });
13987
14427
  }
13988
14428
  }
13989
14429
  const merged = [...totals.values()].sort((a, b) => b.weight - a.weight).slice(0, topN);
@@ -13999,12 +14439,12 @@ async function auditStyle(loaded, specs, styleId, lock) {
13999
14439
  const unreadable = [];
14000
14440
  for (const spec of mine) {
14001
14441
  for (const output of resolveSpecOutputs(spec, lock, loaded.root)) {
14002
- if (!existsSync13(output.absolutePath)) {
14442
+ if (!existsSync15(output.absolutePath)) {
14003
14443
  missing.push(output.id);
14004
14444
  continue;
14005
14445
  }
14006
14446
  try {
14007
- const png = decodePng(await readFile10(output.absolutePath));
14447
+ const png = decodePng(await readFile11(output.absolutePath));
14008
14448
  const palette = extractPalette(png, 12);
14009
14449
  assets.push({
14010
14450
  assetId: spec.assetId,
@@ -14028,10 +14468,10 @@ async function auditStyle(loaded, specs, styleId, lock) {
14028
14468
  let referenceFromStyleImages = false;
14029
14469
  const refPalettes = [];
14030
14470
  for (const img of style.styleImages) {
14031
- const abs = path18.resolve(loaded.root, img.path);
14032
- if (!existsSync13(abs)) continue;
14471
+ const abs = path20.resolve(loaded.root, img.path);
14472
+ if (!existsSync15(abs)) continue;
14033
14473
  try {
14034
- refPalettes.push(extractPalette(decodePng(await readFile10(abs)), 12));
14474
+ refPalettes.push(extractPalette(decodePng(await readFile11(abs)), 12));
14035
14475
  } catch {
14036
14476
  }
14037
14477
  }
@@ -14107,15 +14547,15 @@ function hex(c) {
14107
14547
  }
14108
14548
 
14109
14549
  // src/pipeline/quality-regression.ts
14110
- import path19 from "path";
14111
- import { existsSync as existsSync14 } from "fs";
14112
- import { readFile as readFile11 } from "fs/promises";
14550
+ import path21 from "path";
14551
+ import { existsSync as existsSync16 } from "fs";
14552
+ import { readFile as readFile12 } from "fs/promises";
14113
14553
  import { z as z5 } from "zod";
14114
14554
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
14115
14555
  var HEX_RE = /^#[0-9a-f]{6}$/;
14116
14556
  var MAX_REDMEAN_DISTANCE = 765;
14117
14557
  var QualityPathSchema = z5.string().min(1).refine(
14118
- (value) => !path19.posix.isAbsolute(value) && !value.includes("\\"),
14558
+ (value) => !path21.posix.isAbsolute(value) && !value.includes("\\"),
14119
14559
  "expected a portable relative path"
14120
14560
  );
14121
14561
  var DEFAULT_QUALITY_TOLERANCES = {
@@ -14217,8 +14657,8 @@ function measureDecodedImageQuality(png, digest2) {
14217
14657
  const index = offset / 4;
14218
14658
  const x = index % png.width;
14219
14659
  const y = Math.floor(index / png.width);
14220
- const key = pixelKey(png.pixels, offset);
14221
- const hasSameNeighbor = x > 0 && pixelKey(png.pixels, offset - 4) === key || x + 1 < png.width && pixelKey(png.pixels, offset + 4) === key || y > 0 && pixelKey(png.pixels, offset - png.width * 4) === key || y + 1 < png.height && pixelKey(png.pixels, offset + png.width * 4) === key;
14660
+ const key2 = pixelKey(png.pixels, offset);
14661
+ const hasSameNeighbor = x > 0 && pixelKey(png.pixels, offset - 4) === key2 || x + 1 < png.width && pixelKey(png.pixels, offset + 4) === key2 || y > 0 && pixelKey(png.pixels, offset - png.width * 4) === key2 || y + 1 < png.height && pixelKey(png.pixels, offset + png.width * 4) === key2;
14222
14662
  if (!hasSameNeighbor) {
14223
14663
  isolated++;
14224
14664
  }
@@ -14262,10 +14702,10 @@ function measureDecodedImageQuality(png, digest2) {
14262
14702
  };
14263
14703
  }
14264
14704
  async function measureImageQuality(file) {
14265
- const absolute = path19.resolve(file);
14705
+ const absolute = path21.resolve(file);
14266
14706
  let bytes;
14267
14707
  try {
14268
- bytes = await readFile11(absolute);
14708
+ bytes = await readFile12(absolute);
14269
14709
  } catch (error) {
14270
14710
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
14271
14711
  }
@@ -14284,11 +14724,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
14284
14724
  }
14285
14725
  const ids = parsed.data.map((entry) => entry.id);
14286
14726
  if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
14287
- const root = path19.dirname(path19.resolve(inputsFilePath));
14727
+ const root = path21.dirname(path21.resolve(inputsFilePath));
14288
14728
  return parsed.data.map((entry) => ({
14289
14729
  id: entry.id,
14290
- file: path19.resolve(root, entry.path),
14291
- ...entry.record ? { record: path19.resolve(root, entry.record) } : {},
14730
+ file: path21.resolve(root, entry.path),
14731
+ ...entry.record ? { record: path21.resolve(root, entry.record) } : {},
14292
14732
  tolerances: QualityToleranceSchema.parse({
14293
14733
  ...DEFAULT_QUALITY_TOLERANCES,
14294
14734
  ...entry.tolerances
@@ -14296,7 +14736,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
14296
14736
  }));
14297
14737
  }
14298
14738
  function portableRelative2(from, to) {
14299
- return path19.relative(from, path19.resolve(to)).split(path19.sep).join("/") || ".";
14739
+ return path21.relative(from, path21.resolve(to)).split(path21.sep).join("/") || ".";
14300
14740
  }
14301
14741
  async function verifyRecordForImage(recordPath, imagePath) {
14302
14742
  const verification = await verifyArtifactBundle(recordPath);
@@ -14311,20 +14751,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
14311
14751
  if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
14312
14752
  throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
14313
14753
  }
14314
- const outputs = record.outputs.map((output) => path19.resolve(path19.dirname(recordPath), output.path));
14315
- if (!outputs.includes(path19.resolve(imagePath))) {
14754
+ const outputs = record.outputs.map((output) => path21.resolve(path21.dirname(recordPath), output.path));
14755
+ if (!outputs.includes(path21.resolve(imagePath))) {
14316
14756
  throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
14317
14757
  }
14318
14758
  }
14319
14759
  async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14320
14760
  if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
14321
- const absolute = path19.resolve(baselinePath);
14761
+ const absolute = path21.resolve(baselinePath);
14322
14762
  for (const input of inputs) {
14323
- if (path19.resolve(input.file) === absolute || input.record && path19.resolve(input.record) === absolute) {
14763
+ if (path21.resolve(input.file) === absolute || input.record && path21.resolve(input.record) === absolute) {
14324
14764
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
14325
14765
  }
14326
14766
  }
14327
- const root = path19.dirname(absolute);
14767
+ const root = path21.dirname(absolute);
14328
14768
  const cases = [];
14329
14769
  for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
14330
14770
  const expected = await measureImageQuality(input.file);
@@ -14351,8 +14791,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14351
14791
  cases
14352
14792
  });
14353
14793
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
14354
- if (existsSync14(absolute) && !options.force) {
14355
- const current = await readFile11(absolute);
14794
+ if (existsSync16(absolute) && !options.force) {
14795
+ const current = await readFile12(absolute);
14356
14796
  if (!current.equals(data)) {
14357
14797
  throw new OverwriteRefusedError(
14358
14798
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -14364,13 +14804,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14364
14804
  return { baseline, path: absolute, changed: result.changed.length > 0 };
14365
14805
  }
14366
14806
  async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14367
- const absolute = path19.resolve(baselinePath);
14368
- if (!existsSync14(absolute)) {
14807
+ const absolute = path21.resolve(baselinePath);
14808
+ if (!existsSync16(absolute)) {
14369
14809
  throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
14370
14810
  }
14371
14811
  let raw;
14372
14812
  try {
14373
- raw = JSON.parse(await readFile11(absolute, "utf8"));
14813
+ raw = JSON.parse(await readFile12(absolute, "utf8"));
14374
14814
  } catch (error) {
14375
14815
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
14376
14816
  }
@@ -14380,12 +14820,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14380
14820
  if (unknown.length) {
14381
14821
  throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
14382
14822
  }
14383
- const root = path19.dirname(absolute);
14823
+ const root = path21.dirname(absolute);
14384
14824
  const cases = [...raw.cases];
14385
14825
  const report = [];
14386
14826
  for (const id of only) {
14387
14827
  const input = byId.get(id);
14388
- if (path19.resolve(input.file) === absolute || input.record && path19.resolve(input.record) === absolute) {
14828
+ if (path21.resolve(input.file) === absolute || input.record && path21.resolve(input.record) === absolute) {
14389
14829
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
14390
14830
  }
14391
14831
  const expected = await measureImageQuality(input.file);
@@ -14415,16 +14855,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14415
14855
  }
14416
14856
  const baseline = QualityBaselineSchema.parse({ ...raw, cases });
14417
14857
  const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
14418
- const current = await readFile11(absolute);
14858
+ const current = await readFile12(absolute);
14419
14859
  const changed = !current.equals(data);
14420
14860
  if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
14421
14861
  return { baseline, path: absolute, changed, cases: report };
14422
14862
  }
14423
14863
  async function readQualityBaseline(baselinePath) {
14424
- const absolute = path19.resolve(baselinePath);
14864
+ const absolute = path21.resolve(baselinePath);
14425
14865
  let raw;
14426
14866
  try {
14427
- raw = JSON.parse(await readFile11(absolute, "utf8"));
14867
+ raw = JSON.parse(await readFile12(absolute, "utf8"));
14428
14868
  } catch (error) {
14429
14869
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
14430
14870
  }
@@ -14446,7 +14886,7 @@ async function readQualityBaseline(baselinePath) {
14446
14886
  throw new Error(
14447
14887
  `Invalid quality baseline ${absolute}:
14448
14888
  ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
14449
- Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path19.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
14889
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path21.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
14450
14890
  );
14451
14891
  }
14452
14892
  return parsed.data;
@@ -14508,12 +14948,12 @@ function regressionViolations(expected, actual, tolerances) {
14508
14948
  return { violations, warnings };
14509
14949
  }
14510
14950
  async function checkQualityBaseline(baselinePath) {
14511
- const absolute = path19.resolve(baselinePath);
14951
+ const absolute = path21.resolve(baselinePath);
14512
14952
  const baseline = await readQualityBaseline(absolute);
14513
- const root = path19.dirname(absolute);
14953
+ const root = path21.dirname(absolute);
14514
14954
  const cases = [];
14515
14955
  for (const entry of baseline.cases) {
14516
- const file = path19.resolve(root, entry.file);
14956
+ const file = path21.resolve(root, entry.file);
14517
14957
  let actual = null;
14518
14958
  const violations = [];
14519
14959
  const warnings = [];
@@ -14526,7 +14966,7 @@ async function checkQualityBaseline(baselinePath) {
14526
14966
  violations.push(message4(error));
14527
14967
  }
14528
14968
  if (entry.record) {
14529
- const recordPath = path19.resolve(root, entry.record.path);
14969
+ const recordPath = path21.resolve(root, entry.record.path);
14530
14970
  try {
14531
14971
  const recordHash = await sha256File(recordPath);
14532
14972
  if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
@@ -14562,13 +15002,13 @@ async function checkQualityBaseline(baselinePath) {
14562
15002
  }
14563
15003
 
14564
15004
  // src/pipeline/cache-health.ts
14565
- import { existsSync as existsSync18 } from "fs";
14566
- import { readFile as readFile14, readdir as readdir2, rm as rm6 } from "fs/promises";
14567
- import path22 from "path";
15005
+ import { existsSync as existsSync20 } from "fs";
15006
+ import { readFile as readFile15, readdir as readdir2, rm as rm6 } from "fs/promises";
15007
+ import path24 from "path";
14568
15008
 
14569
15009
  // src/cache.ts
14570
- import { mkdir as mkdir6, readFile as readFile12, rename as rename4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
14571
- import { existsSync as existsSync15 } from "fs";
15010
+ import { mkdir as mkdir7, readFile as readFile13, rename as rename5, rm as rm4, writeFile as writeFile7 } from "fs/promises";
15011
+ import { existsSync as existsSync17 } from "fs";
14572
15012
  import pathModule from "path";
14573
15013
  import { z as z6 } from "zod";
14574
15014
  var HashCacheSchema = z6.object({
@@ -14583,10 +15023,10 @@ function isSha256Hash(value) {
14583
15023
  function parseCache(value) {
14584
15024
  return HashCacheSchema.parse(value);
14585
15025
  }
14586
- async function loadCache(path39) {
14587
- if (!existsSync15(path39)) return { version: 1, hashes: {} };
15026
+ async function loadCache(path42) {
15027
+ if (!existsSync17(path42)) return { version: 1, hashes: {} };
14588
15028
  try {
14589
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile12(path39, "utf8")));
15029
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile13(path42, "utf8")));
14590
15030
  if (!parsed.success) return { version: 1, hashes: {} };
14591
15031
  return {
14592
15032
  version: 1,
@@ -14598,30 +15038,30 @@ async function loadCache(path39) {
14598
15038
  return { version: 1, hashes: {} };
14599
15039
  }
14600
15040
  }
14601
- async function saveCache(path39, cache) {
15041
+ async function saveCache(path42, cache) {
14602
15042
  const sorted = {};
14603
- for (const key of Object.keys(cache.hashes).sort()) {
14604
- const hash = cache.hashes[key];
14605
- if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key}`);
14606
- sorted[key] = hash;
15043
+ for (const key2 of Object.keys(cache.hashes).sort()) {
15044
+ const hash = cache.hashes[key2];
15045
+ if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
15046
+ sorted[key2] = hash;
14607
15047
  }
14608
- await mkdir6(pathModule.dirname(pathModule.resolve(path39)), { recursive: true });
14609
- const tmp = `${path39}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
15048
+ await mkdir7(pathModule.dirname(pathModule.resolve(path42)), { recursive: true });
15049
+ const tmp = `${path42}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
14610
15050
  try {
14611
- await writeFile6(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
14612
- await rename4(tmp, path39);
15051
+ await writeFile7(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
15052
+ await rename5(tmp, path42);
14613
15053
  } finally {
14614
15054
  await rm4(tmp, { force: true });
14615
15055
  }
14616
15056
  }
14617
15057
  function pruneCache(cache, liveIds, namespace = "") {
14618
15058
  let removed = 0;
14619
- for (const key of Object.keys(cache.hashes)) {
14620
- const owned = namespace ? key.startsWith(namespace) : !key.includes(":");
15059
+ for (const key2 of Object.keys(cache.hashes)) {
15060
+ const owned = namespace ? key2.startsWith(namespace) : !key2.includes(":");
14621
15061
  if (!owned) continue;
14622
- const id = namespace ? key.slice(namespace.length) : key;
15062
+ const id = namespace ? key2.slice(namespace.length) : key2;
14623
15063
  if (!liveIds.has(id)) {
14624
- delete cache.hashes[key];
15064
+ delete cache.hashes[key2];
14625
15065
  removed++;
14626
15066
  }
14627
15067
  }
@@ -14633,38 +15073,39 @@ function cachePathFor(lockPath) {
14633
15073
  }
14634
15074
 
14635
15075
  // src/pipeline/history.ts
14636
- import { existsSync as existsSync17 } from "fs";
14637
- import path21 from "path";
15076
+ import { existsSync as existsSync19 } from "fs";
15077
+ import path23 from "path";
14638
15078
 
14639
15079
  // src/pipeline/fetch.ts
14640
- import { existsSync as existsSync16, readFileSync as readFileSync5 } from "fs";
14641
- import { mkdir as mkdir7, readFile as readFile13, rename as rename5, rm as rm5, writeFile as writeFile7 } from "fs/promises";
14642
- import path20 from "path";
15080
+ import { existsSync as existsSync18, readFileSync as readFileSync5 } from "fs";
15081
+ import { mkdir as mkdir8, readFile as readFile14, rename as rename6, rm as rm5, writeFile as writeFile8 } from "fs/promises";
15082
+ import path22 from "path";
14643
15083
  async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14644
15084
  const log = opts.onProgress ?? (() => {
14645
15085
  });
14646
15086
  const result = { downloaded: 0, skipped: 0, failed: 0, ...opts.refresh ? { unchanged: 0 } : {} };
14647
15087
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
14648
15088
  normalizeLockOutputPaths(lock, specs);
14649
- const cacheDir = opts.cacheDir === false ? null : path20.resolve(opts.cacheDir ?? path20.join(path20.dirname(lockPath), ".pixelkiln", "cache"));
14650
- const pending = Object.entries(lock.entries).filter(([key, e]) => {
14651
- if (e.provider !== provider.id || !specByKey.has(key)) return false;
14652
- if (specByKey.get(key)?.mirror) return false;
15089
+ const cacheDir = opts.cacheDir === false ? null : path22.resolve(opts.cacheDir ?? path22.join(path22.dirname(lockPath), ".pixelkiln", "cache"));
15090
+ const pending = Object.entries(lock.entries).filter(([key2, e]) => {
15091
+ if (e.provider !== provider.id || !specByKey.has(key2)) return false;
15092
+ if (specByKey.get(key2)?.mirror) return false;
15093
+ if (specByKey.get(key2)?.derive || specByKey.get(key2)?.external) return false;
14653
15094
  if (e.status === "selected" || e.status === "download-failed") return true;
14654
15095
  if (e.status !== "downloaded") return false;
14655
15096
  if (opts.refresh) return e.outputs.length > 0 && Boolean(e.sourceUrls?.length || e.sourceUrl);
14656
- const spec = specByKey.get(key);
15097
+ const spec = specByKey.get(key2);
14657
15098
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
14658
15099
  return Boolean(opts.force) || e.outputs.every((output) => {
14659
15100
  const file = resolveOutputPath(output.path, spec.root);
14660
- return existsSync16(file) && sha256(readFileSync5(file)) === output.sha256;
15101
+ return existsSync18(file) && sha256(readFileSync5(file)) === output.sha256;
14661
15102
  });
14662
15103
  }
14663
15104
  if (!opts.repair) return false;
14664
15105
  if (e.outputs.length === 0 || !spec) return true;
14665
15106
  return e.outputs.some((output) => {
14666
15107
  const file = resolveOutputPath(output.path, spec.root);
14667
- if (!existsSync16(file)) return true;
15108
+ if (!existsSync18(file)) return true;
14668
15109
  const current = sha256(readFileSync5(file));
14669
15110
  if (current === output.sha256) return false;
14670
15111
  return Boolean(opts.force) || (e.supersededOutputs ?? []).some((old) => old.sha256 === current);
@@ -14676,15 +15117,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14676
15117
  for (; ; ) {
14677
15118
  const next = pending[cursor++];
14678
15119
  if (!next) return;
14679
- const [key, entry] = next;
14680
- const spec = specByKey.get(key);
15120
+ const [key2, entry] = next;
15121
+ const spec = specByKey.get(key2);
14681
15122
  if (!spec) {
14682
- log(` skip ${key} (not in current manifest)`);
15123
+ log(` skip ${key2} (not in current manifest)`);
14683
15124
  result.skipped++;
14684
15125
  continue;
14685
15126
  }
14686
15127
  if (entry.specHash !== spec.specHash) {
14687
- log(` skip ${key} (source belongs to a stale spec)`);
15128
+ log(` skip ${key2} (source belongs to a stale spec)`);
14688
15129
  result.skipped++;
14689
15130
  continue;
14690
15131
  }
@@ -14701,16 +15142,16 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14701
15142
  });
14702
15143
  } catch (err) {
14703
15144
  const message6 = err instanceof Error ? err.message : String(err);
14704
- upsert(lock, key, { status: "download-failed", error: `download failed: ${message6}` });
15145
+ upsert(lock, key2, { status: "download-failed", error: `download failed: ${message6}` });
14705
15146
  result.failed++;
14706
- log(` FAILED ${key}: ${message6}`);
15147
+ log(` FAILED ${key2}: ${message6}`);
14707
15148
  await saveLock(lockPath, lock);
14708
15149
  continue;
14709
15150
  }
14710
15151
  if (current === null) {
14711
- upsert(lock, key, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
15152
+ upsert(lock, key2, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
14712
15153
  result.failed++;
14713
- log(` FAILED ${key}: ${entry.objectId} no longer exists upstream`);
15154
+ log(` FAILED ${key2}: ${entry.objectId} no longer exists upstream`);
14714
15155
  await saveLock(lockPath, lock);
14715
15156
  continue;
14716
15157
  }
@@ -14723,7 +15164,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14723
15164
  }
14724
15165
  }
14725
15166
  if (!sources.length) {
14726
- upsert(lock, key, {
15167
+ upsert(lock, key2, {
14727
15168
  status: "download-failed",
14728
15169
  error: "no persisted source URL to download; poll the job again if it still exists upstream"
14729
15170
  });
@@ -14748,21 +15189,21 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14748
15189
  if (!source.url) throw new Error(`no durable source URL to refresh ${source.role ?? "asset"} from`);
14749
15190
  fresh = await provider.download(source.url);
14750
15191
  if (recorded && sha256(fresh) === recordedRaw && !reapply) {
14751
- log(` current ${path20.relative(process.cwd(), target)}`);
15192
+ log(` current ${path22.relative(process.cwd(), target)}`);
14752
15193
  outputs.push({ ...recorded, path: portableOutputPath(target, spec.root) });
14753
15194
  continue;
14754
15195
  }
14755
15196
  }
14756
15197
  let raw = null;
14757
15198
  let final = null;
14758
- if (existsSync16(target)) {
15199
+ if (existsSync18(target)) {
14759
15200
  const currentHash = await sha256File(target);
14760
15201
  if (recorded && currentHash === recorded.sha256) {
14761
15202
  if (!fresh && !reapply) {
14762
15203
  if (cacheDir) {
14763
15204
  await cacheMedia(
14764
15205
  cacheDir,
14765
- await readFile13(target),
15206
+ await readFile14(target),
14766
15207
  recorded.mediaType ?? MediaType.PNG,
14767
15208
  recorded.sha256
14768
15209
  );
@@ -14771,10 +15212,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14771
15212
  continue;
14772
15213
  }
14773
15214
  if (reapply && !fresh) {
14774
- if (!recorded.raw) raw = await readFile13(target);
14775
- log(` reapply ${path20.relative(process.cwd(), target)}`);
15215
+ if (!recorded.raw) raw = await readFile14(target);
15216
+ log(` reapply ${path22.relative(process.cwd(), target)}`);
14776
15217
  } else {
14777
- log(` changed ${path20.relative(process.cwd(), target)} (upstream)`);
15218
+ log(` changed ${path22.relative(process.cwd(), target)} (upstream)`);
14778
15219
  }
14779
15220
  } else {
14780
15221
  const superseded = (entry.supersededOutputs ?? []).find(
@@ -14795,14 +15236,14 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14795
15236
  }
14796
15237
  if (outgoing && cacheDir) {
14797
15238
  try {
14798
- const oldBytes = await readFile13(target);
15239
+ const oldBytes = await readFile14(target);
14799
15240
  const oldMediaType = detectMediaType(oldBytes);
14800
15241
  if (oldMediaType) await cacheMedia(cacheDir, oldBytes, oldMediaType, currentHash);
14801
15242
  } catch {
14802
15243
  }
14803
15244
  }
14804
15245
  log(
14805
- ` replace ${path20.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
15246
+ ` replace ${path22.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
14806
15247
  );
14807
15248
  }
14808
15249
  }
@@ -14811,7 +15252,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14811
15252
  } else if (!raw && recorded && cacheDir) {
14812
15253
  if (!reapply) final = await readCachedMedia(cacheDir, recorded.sha256, expectedMediaType);
14813
15254
  if (!final && recordedRaw) raw = await readCachedMedia(cacheDir, recordedRaw, expectedMediaType);
14814
- if (final || raw) log(` cached ${path20.relative(process.cwd(), target)}`);
15255
+ if (final || raw) log(` cached ${path22.relative(process.cwd(), target)}`);
14815
15256
  }
14816
15257
  if (!final && !raw) {
14817
15258
  if (!source.url) {
@@ -14838,13 +15279,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14838
15279
  buf = processed.bytes;
14839
15280
  if (processed.changed) {
14840
15281
  rawHash = sha256(raw);
14841
- log(` snapped ${path20.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
15282
+ log(` snapped ${path22.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
14842
15283
  }
14843
15284
  }
14844
15285
  if (cacheDir) await cacheMedia(cacheDir, buf, mediaType);
14845
- await mkdir7(path20.dirname(target), { recursive: true });
15286
+ await mkdir8(path22.dirname(target), { recursive: true });
14846
15287
  const tmp = `${target}.pixelkiln.tmp`;
14847
- await writeFile7(tmp, buf);
15288
+ await writeFile8(tmp, buf);
14848
15289
  outputs.push({
14849
15290
  path: portableOutputPath(target, spec.root),
14850
15291
  sha256: sha256(buf),
@@ -14852,22 +15293,22 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14852
15293
  mediaType,
14853
15294
  ...rawHash ? { raw: rawHash } : {}
14854
15295
  });
14855
- upsert(lock, key, { outputs: mergeOutputs(entry.outputs, outputs) });
15296
+ upsert(lock, key2, { outputs: mergeOutputs(entry.outputs, outputs) });
14856
15297
  await saveLock(lockPath, lock);
14857
- await rename5(tmp, target);
15298
+ await rename6(tmp, target);
14858
15299
  wrote = true;
14859
- log(` wrote ${path20.relative(process.cwd(), target)}`);
15300
+ log(` wrote ${path22.relative(process.cwd(), target)}`);
14860
15301
  }
14861
15302
  if (opts.refresh && !wrote) {
14862
15303
  if (rotated) {
14863
15304
  const persistent = sources.filter((source) => shouldPersistSourceUrl(source.url));
14864
- upsert(lock, key, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
15305
+ upsert(lock, key2, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
14865
15306
  }
14866
15307
  result.unchanged = (result.unchanged ?? 0) + 1;
14867
15308
  continue;
14868
15309
  }
14869
15310
  const persistentSources = sources.filter((source) => shouldPersistSourceUrl(source.url));
14870
- upsert(lock, key, {
15311
+ upsert(lock, key2, {
14871
15312
  status: "downloaded",
14872
15313
  provider: provider.id,
14873
15314
  outputs,
@@ -14884,13 +15325,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14884
15325
  result.downloaded++;
14885
15326
  } catch (err) {
14886
15327
  const message6 = err instanceof Error ? err.message : String(err);
14887
- upsert(lock, key, {
15328
+ upsert(lock, key2, {
14888
15329
  status: "download-failed",
14889
15330
  outputs: mergeOutputs(entry.outputs, outputs),
14890
15331
  error: `download failed: ${message6}`
14891
15332
  });
14892
15333
  result.failed++;
14893
- log(` FAILED ${key}: ${message6}`);
15334
+ log(` FAILED ${key2}: ${message6}`);
14894
15335
  }
14895
15336
  await saveLock(lockPath, lock);
14896
15337
  }
@@ -14900,10 +15341,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14900
15341
  return result;
14901
15342
  }
14902
15343
  async function readCachedMedia(cacheDir, hash, mediaType) {
14903
- const file = path20.join(cacheDir, cacheFileName(hash, mediaType));
14904
- if (!existsSync16(file)) return null;
15344
+ const file = path22.join(cacheDir, cacheFileName(hash, mediaType));
15345
+ if (!existsSync18(file)) return null;
14905
15346
  try {
14906
- const buf = await readFile13(file);
15347
+ const buf = await readFile14(file);
14907
15348
  if (sha256(buf) !== hash) return null;
14908
15349
  validateMedia(buf, mediaType);
14909
15350
  return buf;
@@ -14914,15 +15355,15 @@ async function readCachedMedia(cacheDir, hash, mediaType) {
14914
15355
  async function cacheMedia(cacheDir, buf, mediaType, knownHash) {
14915
15356
  const hash = knownHash ?? sha256(buf);
14916
15357
  validateMedia(buf, mediaType);
14917
- const file = path20.join(cacheDir, cacheFileName(hash, mediaType));
15358
+ const file = path22.join(cacheDir, cacheFileName(hash, mediaType));
14918
15359
  if (await readCachedMedia(cacheDir, hash, mediaType)) return;
14919
- await mkdir7(cacheDir, { recursive: true });
15360
+ await mkdir8(cacheDir, { recursive: true });
14920
15361
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
14921
- await writeFile7(tmp, buf);
15362
+ await writeFile8(tmp, buf);
14922
15363
  try {
14923
- await rename5(tmp, file);
15364
+ await rename6(tmp, file);
14924
15365
  } catch (err) {
14925
- if (!existsSync16(file)) throw err;
15366
+ if (!existsSync18(file)) throw err;
14926
15367
  } finally {
14927
15368
  await rm5(tmp, { force: true });
14928
15369
  }
@@ -14939,8 +15380,8 @@ async function pushTags(provider, specs, lock, opts = {}) {
14939
15380
  });
14940
15381
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
14941
15382
  let tagged = 0;
14942
- for (const [key, entry] of Object.entries(lock.entries)) {
14943
- const spec = specByKey.get(key);
15383
+ for (const [key2, entry] of Object.entries(lock.entries)) {
15384
+ const spec = specByKey.get(key2);
14944
15385
  if (!spec || entry.provider !== provider.id || !entry.objectId) continue;
14945
15386
  if (entry.generator === "pixflux" || entry.generator === "vfx") continue;
14946
15387
  if (!provider.setTags) return tagged;
@@ -14948,7 +15389,7 @@ async function pushTags(provider, specs, lock, opts = {}) {
14948
15389
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
14949
15390
  tagged++;
14950
15391
  } catch (err) {
14951
- log(` tag failed ${key}: ${err instanceof Error ? err.message : String(err)}`);
15392
+ log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
14952
15393
  }
14953
15394
  }
14954
15395
  return tagged;
@@ -15032,22 +15473,22 @@ function pickHistory(entry, selector) {
15032
15473
  return matches[0];
15033
15474
  }
15034
15475
  async function revertGeneration(provider, spec, lock, lockPath, opts) {
15035
- const key = lockKey(spec.styleId, spec.assetId);
15036
- const entry = lock.entries[key];
15037
- if (!entry) throw new Error(`${key} is not in the lockfile`);
15476
+ const key2 = lockKey(spec.styleId, spec.assetId);
15477
+ const entry = lock.entries[key2];
15478
+ if (!entry) throw new Error(`${key2} is not in the lockfile`);
15038
15479
  if (entry.status !== "downloaded") {
15039
- throw new Error(`${key} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
15480
+ throw new Error(`${key2} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
15040
15481
  }
15041
15482
  const { index, generation } = pickHistory(entry, opts.generation);
15042
15483
  if (generation.provider !== provider.id) {
15043
- throw new Error(`${key}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
15484
+ throw new Error(`${key2}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
15044
15485
  }
15045
15486
  for (let i = 0; i < entry.outputs.length; i++) {
15046
15487
  const file = currentEntryOutputPath(entry, spec, i);
15047
- if (!existsSync17(file)) continue;
15488
+ if (!existsSync19(file)) continue;
15048
15489
  if (await sha256File(file) !== entry.outputs[i].sha256 && !opts.force) {
15049
15490
  throw new OverwriteRefusedError(
15050
- `${path21.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
15491
+ `${path23.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
15051
15492
  [file]
15052
15493
  );
15053
15494
  }
@@ -15055,7 +15496,7 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15055
15496
  const now = (/* @__PURE__ */ new Date()).toISOString();
15056
15497
  const remaining = (entry.history ?? []).filter((_, i) => i !== index - 1);
15057
15498
  const history = [retireGeneration(entry, now), ...remaining];
15058
- upsert(lock, key, {
15499
+ upsert(lock, key2, {
15059
15500
  specHash: generation.specHash,
15060
15501
  generator: generation.generator,
15061
15502
  tileFeature: generation.tileFeature,
@@ -15107,11 +15548,11 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15107
15548
 
15108
15549
  // src/pipeline/cache-health.ts
15109
15550
  async function inspectCaches(lock, lockPath, options = {}) {
15110
- if (options.prune && !existsSync18(lockPath)) {
15111
- throw new Error(`Refusing to prune without an existing lockfile at ${path22.resolve(lockPath)}`);
15551
+ if (options.prune && !existsSync20(lockPath)) {
15552
+ throw new Error(`Refusing to prune without an existing lockfile at ${path24.resolve(lockPath)}`);
15112
15553
  }
15113
- const contentDir = path22.resolve(path22.dirname(lockPath), ".pixelkiln", "cache");
15114
- const remotePath = path22.resolve(cachePathFor(lockPath));
15554
+ const contentDir = path24.resolve(path24.dirname(lockPath), ".pixelkiln", "cache");
15555
+ const remotePath = path24.resolve(cachePathFor(lockPath));
15115
15556
  const referenced = referencedHashes(lock);
15116
15557
  let content = await inspectContentCache(contentDir, referenced);
15117
15558
  let remoteHashes = await inspectRemoteHashCache(remotePath);
@@ -15123,7 +15564,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15123
15564
  ]);
15124
15565
  for (const name of names) {
15125
15566
  try {
15126
- await rm6(path22.join(contentDir, name), { force: true });
15567
+ await rm6(path24.join(contentDir, name), { force: true });
15127
15568
  removed.contentFiles++;
15128
15569
  } catch {
15129
15570
  }
@@ -15132,7 +15573,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15132
15573
  await saveCache(remotePath, { version: 1, hashes: {} });
15133
15574
  removed.resetRemoteHashCache = true;
15134
15575
  } else if (remoteHashes.invalidIds.length) {
15135
- const cache = parseCache(JSON.parse(await readFile14(remotePath, "utf8")));
15576
+ const cache = parseCache(JSON.parse(await readFile15(remotePath, "utf8")));
15136
15577
  for (const id of remoteHashes.invalidIds) delete cache.hashes[id];
15137
15578
  removed.remoteHashEntries = remoteHashes.invalidIds.length;
15138
15579
  await saveCache(remotePath, cache);
@@ -15150,7 +15591,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15150
15591
  async function inspectContentCache(contentDir, referenced) {
15151
15592
  const report = {
15152
15593
  path: contentDir,
15153
- exists: existsSync18(contentDir),
15594
+ exists: existsSync20(contentDir),
15154
15595
  files: 0,
15155
15596
  bytes: 0,
15156
15597
  valid: 0,
@@ -15171,12 +15612,12 @@ async function inspectContentCache(contentDir, referenced) {
15171
15612
  continue;
15172
15613
  }
15173
15614
  report.files++;
15174
- const file = path22.join(contentDir, entry.name);
15615
+ const file = path24.join(contentDir, entry.name);
15175
15616
  const mediaType = mediaTypeFromExtension(entry.name);
15176
15617
  const expected = mediaType ? entry.name.slice(0, -4) : "";
15177
15618
  let bytes;
15178
15619
  try {
15179
- bytes = await readFile14(file);
15620
+ bytes = await readFile15(file);
15180
15621
  report.bytes += bytes.length;
15181
15622
  } catch (err) {
15182
15623
  report.invalid.push({
@@ -15214,7 +15655,7 @@ async function inspectContentCache(contentDir, referenced) {
15214
15655
  async function inspectRemoteHashCache(remotePath) {
15215
15656
  const report = {
15216
15657
  path: remotePath,
15217
- exists: existsSync18(remotePath),
15658
+ exists: existsSync20(remotePath),
15218
15659
  entries: 0,
15219
15660
  valid: 0,
15220
15661
  invalidIds: [],
@@ -15223,7 +15664,7 @@ async function inspectRemoteHashCache(remotePath) {
15223
15664
  if (!report.exists) return report;
15224
15665
  let cache;
15225
15666
  try {
15226
- cache = parseCache(JSON.parse(await readFile14(remotePath, "utf8")));
15667
+ cache = parseCache(JSON.parse(await readFile15(remotePath, "utf8")));
15227
15668
  } catch (err) {
15228
15669
  report.error = err instanceof Error ? err.message : String(err);
15229
15670
  return report;
@@ -15239,19 +15680,19 @@ async function inspectRemoteHashCache(remotePath) {
15239
15680
 
15240
15681
  // src/pipeline/pack.ts
15241
15682
  import { readFileSync as readFileSync6 } from "fs";
15242
- import path23 from "path";
15683
+ import path25 from "path";
15243
15684
  var DEFAULT_FRAME_SET_FPS = 12;
15244
15685
  function resolvePackInputs(raw, inputsFilePath) {
15245
15686
  if (!Array.isArray(raw) || !raw.length) {
15246
15687
  throw new Error("--inputs must be a non-empty JSON array of { id, path }");
15247
15688
  }
15248
- const baseDir = path23.dirname(path23.resolve(inputsFilePath));
15689
+ const baseDir = path25.dirname(path25.resolve(inputsFilePath));
15249
15690
  return raw.map((entry, i) => {
15250
15691
  const e = entry;
15251
15692
  if (typeof e.id !== "string" || typeof e.path !== "string") {
15252
15693
  throw new Error(`--inputs[${i}] needs string "id" and "path"`);
15253
15694
  }
15254
- return { id: e.id, path: path23.resolve(baseDir, e.path) };
15695
+ return { id: e.id, path: path25.resolve(baseDir, e.path) };
15255
15696
  });
15256
15697
  }
15257
15698
  function packSprites(inputs, options = {}) {
@@ -15335,14 +15776,14 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15335
15776
  }
15336
15777
  const inputs2 = Object.entries(options.sourceOverrides).map(([id, source]) => ({
15337
15778
  id,
15338
- path: path23.resolve(source)
15779
+ path: path25.resolve(source)
15339
15780
  }));
15340
15781
  if (!inputs2.length) throw new Error(`No approved quality outputs for style "${styleId}".`);
15341
15782
  const packed2 = packSprites(inputs2, options);
15342
15783
  return { ...packed2, atlas: { ...packed2.atlas, style: styleId } };
15343
15784
  }
15344
15785
  const prefix = `${styleId}/`;
15345
- const entries = Object.entries(lock.entries).filter(([key]) => key.startsWith(prefix));
15786
+ const entries = Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix));
15346
15787
  const sources = options.sources ?? {};
15347
15788
  if (!entries.length && !Object.keys(sources).length) {
15348
15789
  throw new Error(
@@ -15353,13 +15794,13 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15353
15794
  const noOutput = [];
15354
15795
  const locked = /* @__PURE__ */ new Set();
15355
15796
  const sets = [];
15356
- for (const [key, entry] of entries) {
15357
- const id = key.slice(prefix.length);
15797
+ for (const [key2, entry] of entries) {
15798
+ const id = key2.slice(prefix.length);
15358
15799
  locked.add(id);
15359
15800
  let outputs = resolveEntryOutputs(entry, id, manifestDir);
15360
15801
  const source = sources[id];
15361
15802
  if (source && outputs.length <= 1) {
15362
- inputs.push({ id, path: path23.resolve(manifestDir, source) });
15803
+ inputs.push({ id, path: path25.resolve(manifestDir, source) });
15363
15804
  continue;
15364
15805
  }
15365
15806
  if (source && sourceIsStem(source, entry, manifestDir)) {
@@ -15394,7 +15835,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15394
15835
  }
15395
15836
  }
15396
15837
  for (const [id, source] of Object.entries(sources)) {
15397
- if (!locked.has(id)) inputs.push({ id, path: path23.resolve(manifestDir, source) });
15838
+ if (!locked.has(id)) inputs.push({ id, path: path25.resolve(manifestDir, source) });
15398
15839
  }
15399
15840
  if (!inputs.length) {
15400
15841
  throw new Error(`No readable sprites for style "${styleId}"; ${noOutput.length} skipped.`);
@@ -15416,14 +15857,14 @@ function mountSprites(placements, options) {
15416
15857
  }
15417
15858
  const byCell = /* @__PURE__ */ new Map();
15418
15859
  for (const p of placements) {
15419
- const key = `${p.cell[0]},${p.cell[1]}`;
15420
- const owner = byCell.get(key);
15860
+ const key2 = `${p.cell[0]},${p.cell[1]}`;
15861
+ const owner = byCell.get(key2);
15421
15862
  if (owner) {
15422
15863
  throw new Error(
15423
- `mountSprites: "${p.id}" and "${owner}" both claim cell ${key}; a cell has exactly one owner`
15864
+ `mountSprites: "${p.id}" and "${owner}" both claim cell ${key2}; a cell has exactly one owner`
15424
15865
  );
15425
15866
  }
15426
- byCell.set(key, p.id);
15867
+ byCell.set(key2, p.id);
15427
15868
  }
15428
15869
  const loaded = [];
15429
15870
  const skipped = [];
@@ -15502,7 +15943,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15502
15943
  const source = sources[id];
15503
15944
  const entry = lock.entries[`${styleId}/${id}`];
15504
15945
  if (source && !(entry && sourceIsStem(source, entry, manifestDir))) {
15505
- placements.push({ id, path: path23.resolve(manifestDir, source), cell });
15946
+ placements.push({ id, path: path25.resolve(manifestDir, source), cell });
15506
15947
  continue;
15507
15948
  }
15508
15949
  if (source && entry) {
@@ -15535,7 +15976,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15535
15976
  `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}`
15536
15977
  );
15537
15978
  }
15538
- const basePng = mount.base ? readFileSync6(path23.resolve(manifestDir, mount.base)) : void 0;
15979
+ const basePng = mount.base ? readFileSync6(path25.resolve(manifestDir, mount.base)) : void 0;
15539
15980
  const mounted = mountSprites(placements, {
15540
15981
  cellWidth: mount.cellWidth,
15541
15982
  cellHeight: mount.cellHeight,
@@ -15545,7 +15986,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15545
15986
  ...mounted,
15546
15987
  sources: mount.base ? [{
15547
15988
  id: "$base",
15548
- path: path23.resolve(manifestDir, mount.base),
15989
+ path: path25.resolve(manifestDir, mount.base),
15549
15990
  sha256: sha256(basePng),
15550
15991
  included: true
15551
15992
  }, ...mounted.sources] : mounted.sources,
@@ -15563,8 +16004,8 @@ function normalizeTileRules(raw) {
15563
16004
  if (arity !== 4 && arity !== 6) return null;
15564
16005
  const masks = {};
15565
16006
  if (isRecord2(raw.tiles)) {
15566
- for (const [key, value] of Object.entries(raw.tiles)) {
15567
- const index = tileIndex(key);
16007
+ for (const [key2, value] of Object.entries(raw.tiles)) {
16008
+ const index = tileIndex(key2);
15568
16009
  const mask = typeof value === "number" ? value : isRecord2(value) && typeof value.bitmask === "number" ? value.bitmask : isRecord2(value) && typeof value.mask === "number" ? value.mask : null;
15569
16010
  if (index !== null && mask !== null && Number.isInteger(mask) && mask >= 0) masks[index] = mask;
15570
16011
  }
@@ -15839,8 +16280,8 @@ function assertUniformTiles(generic) {
15839
16280
  );
15840
16281
  }
15841
16282
  }
15842
- function tileIndex(key) {
15843
- const match = key.match(/(?:^|[_-])(\d+)$/);
16283
+ function tileIndex(key2) {
16284
+ const match = key2.match(/(?:^|[_-])(\d+)$/);
15844
16285
  return match ? Number(match[1]) : null;
15845
16286
  }
15846
16287
  function isRecord2(value) {
@@ -15955,9 +16396,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
15955
16396
  });
15956
16397
  const estimates = new Map(items.map((item) => [
15957
16398
  item.key,
15958
- item.spec.mirror ? { amount: 0, unit: item.spec.costUnit, candidates: 1 } : validateCostEstimate(provider.id, provider.estimate(item.spec))
16399
+ item.spec.mirror || item.spec.derive ? { amount: 0, unit: item.spec.costUnit, candidates: 1 } : validateCostEstimate(provider.id, provider.estimate(item.spec))
15959
16400
  ]));
15960
- const units = new Set([...estimates.values()].map((estimate) => estimate.unit));
16401
+ const units = new Set(items.filter((item) => !item.spec.derive).map((item) => estimates.get(item.key).unit));
15961
16402
  if (units.size > 1) {
15962
16403
  throw new Error(`Provider "${provider.id}" returned mixed cost units for one submission batch`);
15963
16404
  }
@@ -16055,20 +16496,21 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16055
16496
  }
16056
16497
  }
16057
16498
  }
16058
- for (const { spec, key } of items) {
16059
- const estimate = estimates.get(key);
16499
+ for (const { spec, key: key2 } of items) {
16500
+ const estimate = estimates.get(key2);
16060
16501
  if (spec.batch?.role === "member") {
16061
16502
  continue;
16062
16503
  }
16063
- if (spec.mirror) {
16504
+ if (spec.mirror || spec.derive) {
16064
16505
  try {
16065
16506
  await requireRevisionReady(spec, lock);
16066
- await deriveMirror(spec, lock, lockPath, { onProgress: log });
16507
+ if (spec.derive) await deriveAsset(spec, lock, lockPath, { onProgress: log });
16508
+ else await deriveMirror(spec, lock, lockPath, { onProgress: log });
16067
16509
  submitted++;
16068
16510
  } catch (err) {
16069
16511
  const message6 = err instanceof Error ? err.message : String(err);
16070
16512
  failed++;
16071
- upsert(lock, key, {
16513
+ upsert(lock, key2, {
16072
16514
  styleId: spec.styleId,
16073
16515
  assetId: spec.assetId,
16074
16516
  specHash: spec.specHash,
@@ -16078,13 +16520,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16078
16520
  height: spec.height,
16079
16521
  status: "failed",
16080
16522
  error: message6,
16081
- outputs: lock.entries[key]?.outputs ?? [],
16523
+ outputs: lock.entries[key2]?.outputs ?? [],
16082
16524
  cost: 0,
16083
16525
  costUnit: spec.costUnit,
16084
16526
  provider: provider.id
16085
16527
  });
16086
16528
  await saveLock(lockPath, lock);
16087
- log(` FAILED ${key}: ${message6}`);
16529
+ log(` FAILED ${key2}: ${message6}`);
16088
16530
  }
16089
16531
  continue;
16090
16532
  }
@@ -16096,11 +16538,11 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16096
16538
  const missing = (spec.batch.memberAssetIds ?? []).filter((id) => !byKey.has(lockKey(spec.styleId, id)));
16097
16539
  if (missing.length) {
16098
16540
  throw new Error(
16099
- `${key}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
16541
+ `${key2}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
16100
16542
  );
16101
16543
  }
16102
16544
  }
16103
- const previousEntry = lock.entries[key];
16545
+ const previousEntry = lock.entries[key2];
16104
16546
  const resumesCheckpoint = Boolean(
16105
16547
  previousEntry?.specHash === spec.specHash && previousEntry.provider === provider.id && previousEntry.generator === spec.generator && previousEntry.submissionComplete === false && previousEntry.jobId
16106
16548
  );
@@ -16130,9 +16572,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16130
16572
  const leaderGroup = motionLeader ? recordedAnimationGroup(lock.entries[lockKey(motionLeader.spec.styleId, motionLeader.spec.assetId)]) : void 0;
16131
16573
  const motionGroup = leaderGroup?.animationGroupId && leaderGroup.animationName ? { animationGroupId: leaderGroup.animationGroupId, animationName: leaderGroup.animationName } : void 0;
16132
16574
  if (motionLeader && !motionGroup) {
16133
- log(` ${key}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
16575
+ log(` ${key2}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
16134
16576
  }
16135
- upsert(lock, key, {
16577
+ upsert(lock, key2, {
16136
16578
  styleId: spec.styleId,
16137
16579
  assetId: spec.assetId,
16138
16580
  specHash: spec.specHash,
@@ -16230,8 +16672,8 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16230
16672
  ...previousMetadata ? { previousMetadata } : {},
16231
16673
  checkpoint: async (checkpoint) => {
16232
16674
  if (!checkpoint.jobId) throw new Error("Provider checkpoint returned an empty job id");
16233
- const entry = lock.entries[key];
16234
- upsert(lock, key, {
16675
+ const entry = lock.entries[key2];
16676
+ upsert(lock, key2, {
16235
16677
  jobId: checkpoint.jobId,
16236
16678
  submissionComplete: checkpoint.complete,
16237
16679
  reviewObjectId: checkpoint.complete && (spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature) ? checkpoint.jobId : null,
@@ -16248,41 +16690,41 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16248
16690
  await saveLock(lockPath, lock);
16249
16691
  }
16250
16692
  });
16251
- upsert(lock, key, {
16693
+ upsert(lock, key2, {
16252
16694
  jobId,
16253
16695
  submissionComplete: true,
16254
16696
  // A multi-candidate generator routes through review; record the parent
16255
16697
  // so `pick` knows where to look.
16256
16698
  reviewObjectId: spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature ? jobId : null,
16257
16699
  status: "processing",
16258
- providerMetadata: metadata ? { ...lock.entries[key].providerMetadata, [provider.id]: metadata } : lock.entries[key].providerMetadata
16700
+ providerMetadata: metadata ? { ...lock.entries[key2].providerMetadata, [provider.id]: metadata } : lock.entries[key2].providerMetadata
16259
16701
  });
16260
16702
  inFlight.set(jobId, spec);
16261
16703
  submitted++;
16262
16704
  spent += estimate.amount;
16263
- writeBatchMembers(spec, key, null);
16705
+ writeBatchMembers(spec, key2, null);
16264
16706
  log(
16265
- ` ${key} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
16707
+ ` ${key2} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
16266
16708
  );
16267
16709
  } catch (err) {
16268
16710
  const message6 = err instanceof Error ? err.message : String(err);
16269
- const entry = lock.entries[key];
16711
+ const entry = lock.entries[key2];
16270
16712
  if (entry.jobId && entry.submissionComplete === true) {
16271
- upsert(lock, key, { status: "processing", error: null });
16713
+ upsert(lock, key2, { status: "processing", error: null });
16272
16714
  inFlight.set(entry.jobId, spec);
16273
16715
  submitted++;
16274
16716
  spent += estimate.amount;
16275
- writeBatchMembers(spec, key, null);
16276
- log(` ${key} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
16717
+ writeBatchMembers(spec, key2, null);
16718
+ log(` ${key2} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
16277
16719
  } else {
16278
16720
  failed++;
16279
- upsert(lock, key, {
16721
+ upsert(lock, key2, {
16280
16722
  status: "failed",
16281
16723
  error: message6,
16282
16724
  cost: entry.jobId ? estimate.amount : 0
16283
16725
  });
16284
- writeBatchMembers(spec, key, message6);
16285
- log(` FAILED ${key}: ${message6}`);
16726
+ writeBatchMembers(spec, key2, message6);
16727
+ log(` FAILED ${key2}: ${message6}`);
16286
16728
  }
16287
16729
  }
16288
16730
  await saveLock(lockPath, lock);
@@ -16313,14 +16755,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
16313
16755
  const selectedKeys = opts.specs ? new Set(specByKey.keys()) : null;
16314
16756
  const result = { review: 0, completed: 0, failed: 0, stillRunning: 0 };
16315
16757
  const incompleteSubmissions = Object.entries(lock.entries).filter(
16316
- ([key, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
16758
+ ([key2, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
16317
16759
  );
16318
- for (const [key] of incompleteSubmissions) {
16319
- log(` incomplete submission ${key}; rerun \`pixelkiln submit\` to resume`);
16760
+ for (const [key2] of incompleteSubmissions) {
16761
+ log(` incomplete submission ${key2}; rerun \`pixelkiln submit\` to resume`);
16320
16762
  }
16321
16763
  result.stillRunning = incompleteSubmissions.length;
16322
16764
  const pending = () => Object.entries(lock.entries).filter(
16323
- ([key, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
16765
+ ([key2, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
16324
16766
  );
16325
16767
  while (pending().length > 0) {
16326
16768
  if (Date.now() - started > timeout) {
@@ -16328,16 +16770,16 @@ async function poll(provider, lock, lockPath, opts = {}) {
16328
16770
  log(` timed out with ${result.stillRunning} job(s) still running; re-run \`poll\` to resume`);
16329
16771
  break;
16330
16772
  }
16331
- for (const [key, entry] of pending()) {
16773
+ for (const [key2, entry] of pending()) {
16332
16774
  try {
16333
- const currentSpec = specByKey.get(key);
16775
+ const currentSpec = specByKey.get(key2);
16334
16776
  const state = await provider.poll(entry.jobId, entry.generator, {
16335
16777
  tileFeature: entry.tileFeature ?? currentSpec?.tileFeature,
16336
16778
  spec: currentSpec,
16337
16779
  metadata: entry.providerMetadata?.[provider.id]
16338
16780
  });
16339
16781
  if (state.status === "review" || state.status === "review-set") {
16340
- upsert(lock, key, {
16782
+ upsert(lock, key2, {
16341
16783
  status: "review",
16342
16784
  reviewObjectId: entry.jobId,
16343
16785
  providerMetadata: state.metadata ? {
@@ -16351,11 +16793,11 @@ async function poll(provider, lock, lockPath, opts = {}) {
16351
16793
  });
16352
16794
  result.review++;
16353
16795
  log(
16354
- state.status === "review-set" ? ` review ${key} (${state.frameUrls.length} ordered frames)` : ` review ${key} (${state.candidateUrls.length} candidates)`
16796
+ state.status === "review-set" ? ` review ${key2} (${state.frameUrls.length} ordered frames)` : ` review ${key2} (${state.candidateUrls.length} candidates)`
16355
16797
  );
16356
16798
  } else if (state.status === "ready") {
16357
16799
  const sourceUrls = state.sources?.length ? state.sources : state.sourceUrl ? [{ url: state.sourceUrl }] : [];
16358
- upsert(lock, key, {
16800
+ upsert(lock, key2, {
16359
16801
  status: "selected",
16360
16802
  objectId: state.objectId,
16361
16803
  sourceUrl: sourceUrls[0]?.url ?? null,
@@ -16371,14 +16813,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
16371
16813
  billed: state.billed ?? entry.billed
16372
16814
  });
16373
16815
  result.completed++;
16374
- log(` ready ${key}`);
16816
+ log(` ready ${key2}`);
16375
16817
  } else if (state.status === "failed") {
16376
- upsert(lock, key, { status: "failed", error: state.error });
16818
+ upsert(lock, key2, { status: "failed", error: state.error });
16377
16819
  result.failed++;
16378
- log(` FAILED ${key}: ${state.error}`);
16820
+ log(` FAILED ${key2}: ${state.error}`);
16379
16821
  }
16380
16822
  } catch (err) {
16381
- log(` error polling ${key}: ${err instanceof Error ? err.message : String(err)}`);
16823
+ log(` error polling ${key2}: ${err instanceof Error ? err.message : String(err)}`);
16382
16824
  }
16383
16825
  }
16384
16826
  await saveLock(lockPath, lock);
@@ -16389,9 +16831,81 @@ async function poll(provider, lock, lockPath, opts = {}) {
16389
16831
  }
16390
16832
 
16391
16833
  // src/pipeline/doctor.ts
16392
- import { constants, existsSync as existsSync19 } from "fs";
16834
+ import { constants, existsSync as existsSync22 } from "fs";
16393
16835
  import { access, stat as stat2 } from "fs/promises";
16394
- import path24 from "path";
16836
+ import path27 from "path";
16837
+
16838
+ // src/pipeline/install-check.ts
16839
+ import { existsSync as existsSync21, readFileSync as readFileSync7 } from "fs";
16840
+ import path26 from "path";
16841
+ function readJson(file) {
16842
+ try {
16843
+ return JSON.parse(readFileSync7(file, "utf8"));
16844
+ } catch {
16845
+ return null;
16846
+ }
16847
+ }
16848
+ function readInstallFacts(manifestDir, running) {
16849
+ let dir = path26.resolve(manifestDir);
16850
+ for (let depth = 0; depth < 4; depth++) {
16851
+ const pkg = readJson(path26.join(dir, "package.json"));
16852
+ if (pkg) {
16853
+ const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
16854
+ if (pinned) {
16855
+ const installedPkg = readJson(path26.join(dir, "node_modules", "pixelkiln", "package.json"));
16856
+ const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
16857
+ return { pinned, installed, running };
16858
+ }
16859
+ }
16860
+ const parent = path26.dirname(dir);
16861
+ if (parent === dir || !existsSync21(parent)) break;
16862
+ dir = parent;
16863
+ }
16864
+ return null;
16865
+ }
16866
+ function parse(version) {
16867
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(version);
16868
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
16869
+ }
16870
+ function compare(a, b) {
16871
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
16872
+ }
16873
+ function checkInstall(facts) {
16874
+ const findings = [];
16875
+ const pin = parse(facts.pinned ?? "");
16876
+ const installed = facts.installed ? parse(facts.installed) : null;
16877
+ const running = facts.running ? parse(facts.running) : null;
16878
+ const exact = /^[=v]*\d+\.\d+\.\d+$/.test((facts.pinned ?? "").trim());
16879
+ if (pin && facts.installed && installed) {
16880
+ const behind = exact ? compare(installed, pin) !== 0 : compare(installed, pin) < 0;
16881
+ if (behind) {
16882
+ findings.push({
16883
+ level: "warning",
16884
+ message: `package.json asks for pixelkiln ${facts.pinned} but node_modules has ${facts.installed}; run \`npm install\` so the CLI matches the manifest.`
16885
+ });
16886
+ }
16887
+ } else if (pin && !facts.installed) {
16888
+ findings.push({
16889
+ level: "warning",
16890
+ message: `package.json asks for pixelkiln ${facts.pinned} but it is not installed in node_modules; run \`npm install\`.`
16891
+ });
16892
+ }
16893
+ if (running && installed && compare(running, installed) !== 0) {
16894
+ findings.push({
16895
+ level: "warning",
16896
+ message: `running pixelkiln ${facts.running}, but this project's node_modules has ${facts.installed}. Another install is first on your PATH; use \`npx pixelkiln\` or remove the global one.`
16897
+ });
16898
+ }
16899
+ if (!findings.length) {
16900
+ findings.push({
16901
+ level: "ok",
16902
+ message: `pixelkiln ${facts.running ?? facts.installed ?? "?"} matches package.json (${facts.pinned})`
16903
+ });
16904
+ }
16905
+ return findings;
16906
+ }
16907
+
16908
+ // src/pipeline/doctor.ts
16395
16909
  async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16396
16910
  const checks = [];
16397
16911
  const add = (id, level, message6) => checks.push({ id, level, message: message6 });
@@ -16400,10 +16914,19 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16400
16914
  "ok",
16401
16915
  `${Object.keys(loaded.manifest.styles).length} style(s), ${Object.keys(loaded.manifest.assets).length} asset(s), ${specs.length} resolved spec(s)`
16402
16916
  );
16917
+ for (const entry of loaded.invalid ?? []) {
16918
+ add(
16919
+ "invalid-entry",
16920
+ "error",
16921
+ `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
16922
+ );
16923
+ }
16924
+ const facts = readInstallFacts(path27.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
16925
+ if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
16403
16926
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
16404
16927
  const dirs = [...new Set(specs.flatMap((spec) => [
16405
- path24.dirname(spec.outFile),
16406
- ...spec.quality ? [path24.dirname(spec.quality.outFile)] : []
16928
+ path27.dirname(spec.outFile),
16929
+ ...spec.quality ? [path27.dirname(spec.quality.outFile)] : []
16407
16930
  ]))];
16408
16931
  const unwritable = [];
16409
16932
  for (const dir of dirs) {
@@ -16422,14 +16945,14 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16422
16945
  const outputOwners = /* @__PURE__ */ new Map();
16423
16946
  const duplicateOutputs = [];
16424
16947
  const specByKey = new Map(specs.map((spec) => [`${spec.styleId}/${spec.assetId}`, spec]));
16425
- for (const [key, entry] of Object.entries(lock.entries)) {
16948
+ for (const [key2, entry] of Object.entries(lock.entries)) {
16426
16949
  for (let index = 0; index < entry.outputs.length; index++) {
16427
16950
  const output = entry.outputs[index];
16428
- const spec = specByKey.get(key);
16429
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path24.dirname(lockPath));
16951
+ const spec = specByKey.get(key2);
16952
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path27.dirname(lockPath));
16430
16953
  const owner = outputOwners.get(absolute);
16431
- if (owner && owner !== key) duplicateOutputs.push(`${output.path} (${owner}, ${key})`);
16432
- outputOwners.set(absolute, key);
16954
+ if (owner && owner !== key2) duplicateOutputs.push(`${output.path} (${owner}, ${key2})`);
16955
+ outputOwners.set(absolute, key2);
16433
16956
  }
16434
16957
  }
16435
16958
  if (duplicateOutputs.length) {
@@ -16441,34 +16964,34 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16441
16964
  } else {
16442
16965
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
16443
16966
  }
16444
- const cacheDir = path24.join(path24.dirname(lockPath), ".pixelkiln", "cache");
16967
+ const cacheDir = path27.join(path27.dirname(lockPath), ".pixelkiln", "cache");
16445
16968
  const stranded = [];
16446
16969
  const invalidState = [];
16447
16970
  const staleMapUrls = [];
16448
16971
  const now = Date.now();
16449
- for (const [key, entry] of Object.entries(lock.entries)) {
16972
+ for (const [key2, entry] of Object.entries(lock.entries)) {
16450
16973
  if ((entry.status === "pending" || entry.status === "processing") && !entry.jobId) {
16451
- invalidState.push(`${key} (${entry.status} without job id)`);
16974
+ invalidState.push(`${key2} (${entry.status} without job id)`);
16452
16975
  }
16453
16976
  if (entry.status === "review" && !entry.reviewObjectId) {
16454
- invalidState.push(`${key} (review without review object id)`);
16977
+ invalidState.push(`${key2} (review without review object id)`);
16455
16978
  }
16456
16979
  if (entry.status !== "selected" && entry.status !== "download-failed") continue;
16457
16980
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
16458
16981
  let hasCache = false;
16459
16982
  for (const output of entry.outputs) {
16460
- const cached2 = path24.join(
16983
+ const cached2 = path27.join(
16461
16984
  cacheDir,
16462
16985
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
16463
16986
  );
16464
- if (existsSync19(cached2) && await sha256File(cached2) === output.sha256) {
16987
+ if (existsSync22(cached2) && await sha256File(cached2) === output.sha256) {
16465
16988
  hasCache = true;
16466
16989
  break;
16467
16990
  }
16468
16991
  }
16469
- if (!hasSource && !hasCache) stranded.push(key);
16992
+ if (!hasSource && !hasCache) stranded.push(key2);
16470
16993
  if (entry.generator === "map" && entry.submittedAt && now - Date.parse(entry.submittedAt) > 8 * 60 * 60 * 1e3) {
16471
- staleMapUrls.push(key);
16994
+ staleMapUrls.push(key2);
16472
16995
  }
16473
16996
  }
16474
16997
  add(
@@ -16557,16 +17080,16 @@ async function nearestExistingDirectory(start) {
16557
17080
  if ((await stat2(current)).isDirectory()) return current;
16558
17081
  } catch {
16559
17082
  }
16560
- const parent = path24.dirname(current);
17083
+ const parent = path27.dirname(current);
16561
17084
  if (parent === current) return current;
16562
17085
  current = parent;
16563
17086
  }
16564
17087
  }
16565
17088
 
16566
17089
  // src/pipeline/adopt.ts
16567
- import { existsSync as existsSync20 } from "fs";
16568
- import { readFile as readFile15, writeFile as writeFile8 } from "fs/promises";
16569
- import path25 from "path";
17090
+ import { existsSync as existsSync23 } from "fs";
17091
+ import { readFile as readFile16, writeFile as writeFile9 } from "fs/promises";
17092
+ import path28 from "path";
16570
17093
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
16571
17094
  const log = opts.onProgress ?? (() => {
16572
17095
  });
@@ -16577,11 +17100,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
16577
17100
  const localByHash = /* @__PURE__ */ new Map();
16578
17101
  const unmatchedLocal = [];
16579
17102
  for (const spec of specs) {
16580
- if (!existsSync20(spec.outFile)) {
17103
+ if (!existsSync23(spec.outFile)) {
16581
17104
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
16582
17105
  continue;
16583
17106
  }
16584
- const bytes = await readFile15(spec.outFile);
17107
+ const bytes = await readFile16(spec.outFile);
16585
17108
  try {
16586
17109
  decodePng(bytes);
16587
17110
  } catch (err) {
@@ -16626,14 +17149,14 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
16626
17149
  if (!hits?.length) continue;
16627
17150
  matchedRemote.add(obj.id);
16628
17151
  for (const spec of hits) {
16629
- const key = lockKey(spec.styleId, spec.assetId);
16630
- const existing = lock.entries[key];
17152
+ const key2 = lockKey(spec.styleId, spec.assetId);
17153
+ const existing = lock.entries[key2];
16631
17154
  if (existing?.objectId && existing.objectId !== obj.id) {
16632
- ambiguous.push(`${key}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
17155
+ ambiguous.push(`${key2}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
16633
17156
  continue;
16634
17157
  }
16635
17158
  const durableSource = shouldPersistSourceUrl(url) ? url : null;
16636
- upsert(lock, key, {
17159
+ upsert(lock, key2, {
16637
17160
  styleId: spec.styleId,
16638
17161
  assetId: spec.assetId,
16639
17162
  // Deliberately the CURRENT spec hash: adoption declares "the file on
@@ -16660,7 +17183,7 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
16660
17183
  provider: provider.id
16661
17184
  });
16662
17185
  matched++;
16663
- log(` adopted ${key} \u2190 ${obj.id}`);
17186
+ log(` adopted ${key2} \u2190 ${obj.id}`);
16664
17187
  }
16665
17188
  }
16666
17189
  }
@@ -16684,23 +17207,23 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
16684
17207
  });
16685
17208
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
16686
17209
  let count = 0;
16687
- for (const [key, entry] of Object.entries(lock.entries)) {
16688
- const spec = specByKey.get(key);
17210
+ for (const [key2, entry] of Object.entries(lock.entries)) {
17211
+ const spec = specByKey.get(key2);
16689
17212
  if (!spec || !entry.objectId) continue;
16690
17213
  if (!provider.setTags) return count;
16691
17214
  try {
16692
17215
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
16693
17216
  count++;
16694
17217
  } catch (err) {
16695
- log(` tag failed ${key}: ${err instanceof Error ? err.message : String(err)}`);
17218
+ log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
16696
17219
  }
16697
17220
  }
16698
17221
  return count;
16699
17222
  }
16700
17223
 
16701
17224
  // src/pipeline/import.ts
16702
- import { existsSync as existsSync21 } from "fs";
16703
- import { readFile as readFile16 } from "fs/promises";
17225
+ import { existsSync as existsSync24 } from "fs";
17226
+ import { readFile as readFile17 } from "fs/promises";
16704
17227
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
16705
17228
  const png = decodePng(bytes);
16706
17229
  const at = now.toISOString();
@@ -16726,6 +17249,7 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
16726
17249
  cost: 0,
16727
17250
  costUnit: spec.costUnit,
16728
17251
  provider: spec.provider,
17252
+ ...spec.external ? { external: { builder: spec.external.builder, inputs: spec.external.inputs } } : {},
16729
17253
  imported: {
16730
17254
  source: opts.source ?? "external",
16731
17255
  ...opts.note ? { note: opts.note } : {},
@@ -16746,32 +17270,32 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
16746
17270
  const imported = [];
16747
17271
  const skipped = [];
16748
17272
  for (const spec of specs) {
16749
- const key = lockKey(spec.styleId, spec.assetId);
17273
+ const key2 = lockKey(spec.styleId, spec.assetId);
16750
17274
  const reason = unimportable(spec);
16751
17275
  if (reason) {
16752
- skipped.push({ key, reason });
17276
+ skipped.push({ key: key2, reason });
16753
17277
  continue;
16754
17278
  }
16755
- if (!existsSync21(spec.outFile)) {
16756
- skipped.push({ key, reason: `no file at ${spec.outFile}` });
17279
+ if (!existsSync24(spec.outFile)) {
17280
+ skipped.push({ key: key2, reason: `no file at ${spec.outFile}` });
16757
17281
  continue;
16758
17282
  }
16759
- if (lock.entries[key] && !opts.force) {
16760
- skipped.push({ key, reason: "already in the lockfile (use --force to replace it)" });
17283
+ if (lock.entries[key2] && !opts.force) {
17284
+ skipped.push({ key: key2, reason: "already in the lockfile (use --force to replace it)" });
16761
17285
  continue;
16762
17286
  }
16763
17287
  let patch;
16764
17288
  try {
16765
- patch = buildImportedEntry(spec, await readFile16(spec.outFile), opts);
17289
+ patch = buildImportedEntry(spec, await readFile17(spec.outFile), opts);
16766
17290
  } catch (error) {
16767
- skipped.push({ key, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
17291
+ skipped.push({ key: key2, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
16768
17292
  continue;
16769
17293
  }
16770
17294
  if (opts.dryRun) {
16771
- imported.push({ key, entry: patch });
17295
+ imported.push({ key: key2, entry: patch });
16772
17296
  continue;
16773
17297
  }
16774
- imported.push({ key, entry: upsert(lock, key, patch) });
17298
+ imported.push({ key: key2, entry: upsert(lock, key2, patch) });
16775
17299
  }
16776
17300
  if (!opts.dryRun && imported.length) await saveLock(lockPath, lock);
16777
17301
  return { imported, skipped };
@@ -16779,9 +17303,9 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
16779
17303
  async function reportSpecHashes(specs, lock) {
16780
17304
  const reports = [];
16781
17305
  for (const spec of specs) {
16782
- const key = lockKey(spec.styleId, spec.assetId);
17306
+ const key2 = lockKey(spec.styleId, spec.assetId);
16783
17307
  let bytes = null;
16784
- if (existsSync21(spec.outFile)) bytes = await readFile16(spec.outFile);
17308
+ if (existsSync24(spec.outFile)) bytes = await readFile17(spec.outFile);
16785
17309
  let wouldImport = null;
16786
17310
  if (bytes && !unimportable(spec)) {
16787
17311
  try {
@@ -16790,11 +17314,11 @@ async function reportSpecHashes(specs, lock) {
16790
17314
  wouldImport = null;
16791
17315
  }
16792
17316
  }
16793
- const entry = lock.entries[key];
17317
+ const entry = lock.entries[key2];
16794
17318
  const fileSha256 = bytes ? sha256(bytes) : null;
16795
17319
  const outputSha256 = entry?.outputs[0]?.sha256 ?? null;
16796
17320
  reports.push({
16797
- key,
17321
+ key: key2,
16798
17322
  specHash: spec.specHash,
16799
17323
  file: spec.outFile,
16800
17324
  fileSha256,
@@ -16810,13 +17334,13 @@ async function reportSpecHashes(specs, lock) {
16810
17334
  }
16811
17335
 
16812
17336
  // src/pick/server.ts
16813
- import { existsSync as existsSync23 } from "fs";
16814
- import { readFile as readFile19 } from "fs/promises";
17337
+ import { existsSync as existsSync26 } from "fs";
17338
+ import { readFile as readFile20 } from "fs/promises";
16815
17339
 
16816
17340
  // src/pipeline/init.ts
16817
- import { readdir as readdir3, readFile as readFile17, writeFile as writeFile9 } from "fs/promises";
16818
- import { existsSync as existsSync22 } from "fs";
16819
- import path26 from "path";
17341
+ import { readdir as readdir3, readFile as readFile18, writeFile as writeFile10 } from "fs/promises";
17342
+ import { existsSync as existsSync25 } from "fs";
17343
+ import path29 from "path";
16820
17344
  function pngSize(buf) {
16821
17345
  if (buf.length < 24) return null;
16822
17346
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -16830,7 +17354,7 @@ function slugify(value) {
16830
17354
  async function walk(dir, exclude) {
16831
17355
  const out = [];
16832
17356
  for (const entry of await readdir3(dir, { withFileTypes: true })) {
16833
- const full = path26.join(dir, entry.name);
17357
+ const full = path29.join(dir, entry.name);
16834
17358
  if (exclude.some((x) => full.includes(x))) continue;
16835
17359
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
16836
17360
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -16844,14 +17368,14 @@ async function scanAssets(root, opts = {}) {
16844
17368
  const skipped = [];
16845
17369
  const seen = /* @__PURE__ */ new Map();
16846
17370
  for (const file of files.sort()) {
16847
- const size = pngSize(await readFile17(file));
17371
+ const size = pngSize(await readFile18(file));
16848
17372
  if (!size) {
16849
17373
  skipped.push(`${file} (not a readable PNG)`);
16850
17374
  continue;
16851
17375
  }
16852
- const rel = path26.relative(root, file);
16853
- const category = path26.dirname(rel) === "." ? "" : path26.dirname(rel);
16854
- let id = slugify(path26.basename(rel));
17376
+ const rel = path29.relative(root, file);
17377
+ const category = path29.dirname(rel) === "." ? "" : path29.dirname(rel);
17378
+ let id = slugify(path29.basename(rel));
16855
17379
  if (seen.has(id)) {
16856
17380
  const n = seen.get(id) + 1;
16857
17381
  seen.set(id, n);
@@ -17325,7 +17849,7 @@ document.getElementById('submit').onclick = async () => {
17325
17849
 
17326
17850
  // src/pick/review-server.ts
17327
17851
  import { createServer } from "http";
17328
- import { readFile as readFile18 } from "fs/promises";
17852
+ import { readFile as readFile19 } from "fs/promises";
17329
17853
  function serveReviewPage(opts) {
17330
17854
  const log = opts.onProgress ?? (() => {
17331
17855
  });
@@ -17334,7 +17858,7 @@ function serveReviewPage(opts) {
17334
17858
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
17335
17859
  try {
17336
17860
  const asset = opts.assets.get(req.url);
17337
- const bytes = await readFile18(asset.path);
17861
+ const bytes = await readFile19(asset.path);
17338
17862
  res.writeHead(200, {
17339
17863
  "Content-Type": asset.contentType,
17340
17864
  "Cache-Control": "no-store",
@@ -17410,13 +17934,13 @@ async function currentArt(entry, spec) {
17410
17934
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
17411
17935
  if (!previous) return null;
17412
17936
  const file = resolveOutputPath(previous.path, spec.root);
17413
- if (!existsSync23(file)) return null;
17937
+ if (!existsSync26(file)) return null;
17414
17938
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
17415
17939
  if (!contentType) return null;
17416
17940
  let width = entry.width;
17417
17941
  let height = entry.height;
17418
17942
  if (contentType === "image/png") {
17419
- const size = pngSize(await readFile19(file));
17943
+ const size = pngSize(await readFile20(file));
17420
17944
  if (size) ({ width, height } = size);
17421
17945
  }
17422
17946
  return { path: file, contentType, width, height };
@@ -17424,7 +17948,7 @@ async function currentArt(entry, spec) {
17424
17948
  async function cachedFrame(url) {
17425
17949
  if (!url.startsWith("file://")) return null;
17426
17950
  const file = url.slice("file://".length);
17427
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile19(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
17951
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile20(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
17428
17952
  return { path: file, contentType };
17429
17953
  }
17430
17954
  async function prepareReview(provider, lock, opts = {}) {
@@ -17438,11 +17962,11 @@ async function prepareReview(provider, lock, opts = {}) {
17438
17962
  const prefix = opts.routePrefix ?? "";
17439
17963
  const providerUrls = /* @__PURE__ */ new Map();
17440
17964
  const groups = [];
17441
- for (const [key, entry] of Object.entries(lock.entries)) {
17442
- if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key)) continue;
17965
+ for (const [key2, entry] of Object.entries(lock.entries)) {
17966
+ if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key2)) continue;
17443
17967
  if (entry.status !== "review" || !entry.reviewObjectId) continue;
17444
17968
  try {
17445
- const spec = specByKey.get(key);
17969
+ const spec = specByKey.get(key2);
17446
17970
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
17447
17971
  if (state.status !== "review" && state.status !== "review-set" || (state.status === "review" ? !state.candidateUrls.length : !state.frameUrls.length)) continue;
17448
17972
  const urls = state.status === "review" ? state.candidateUrls : state.frameUrls;
@@ -17456,7 +17980,7 @@ async function prepareReview(provider, lock, opts = {}) {
17456
17980
  frameSizes.push(null);
17457
17981
  continue;
17458
17982
  }
17459
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile19(cached2.path).catch(() => Buffer.alloc(0))) : null);
17983
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile20(cached2.path).catch(() => Buffer.alloc(0))) : null);
17460
17984
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
17461
17985
  frameAssets.push([route, cached2]);
17462
17986
  frameUrls.push(route);
@@ -17474,9 +17998,9 @@ async function prepareReview(provider, lock, opts = {}) {
17474
17998
  reviewAssets.set(currentRoute, { path: current.path, contentType: current.contentType });
17475
17999
  }
17476
18000
  for (const [route, asset] of frameAssets) reviewAssets.set(route, asset);
17477
- providerUrls.set(key, urls);
18001
+ providerUrls.set(key2, urls);
17478
18002
  groups.push({
17479
- key,
18003
+ key: key2,
17480
18004
  assetId: entry.assetId,
17481
18005
  styleId: entry.styleId,
17482
18006
  prompt: entry.prompt,
@@ -17506,7 +18030,7 @@ async function prepareReview(provider, lock, opts = {}) {
17506
18030
  ...entry.batch?.index != null ? { recommendedIndex: entry.batch.index } : {}
17507
18031
  });
17508
18032
  } catch (err) {
17509
- log(` could not load candidates for ${key}: ${err instanceof Error ? err.message : String(err)}`);
18033
+ log(` could not load candidates for ${key2}: ${err instanceof Error ? err.message : String(err)}`);
17510
18034
  }
17511
18035
  }
17512
18036
  if (groups.length === 0) return null;
@@ -17518,18 +18042,18 @@ async function prepareReview(provider, lock, opts = {}) {
17518
18042
  apply: async (body, lockPath) => {
17519
18043
  const { selections } = body;
17520
18044
  let selected = 0;
17521
- for (const { key, index } of selections) {
17522
- const group = byKey.get(key);
17523
- const entry = lock.entries[key];
18045
+ for (const { key: key2, index } of selections) {
18046
+ const group = byKey.get(key2);
18047
+ const entry = lock.entries[key2];
17524
18048
  if (!group || !entry?.reviewObjectId) continue;
17525
18049
  if (!Number.isInteger(index) || index < 0 || index >= group.frameUrls.length) continue;
17526
18050
  if (group.mode === "frame-set") {
17527
- const spec = specByKey.get(key);
18051
+ const spec = specByKey.get(key2);
17528
18052
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
17529
18053
  if (state.status !== "review-set") {
17530
- throw new Error(`Frame set ${key} is no longer ready for review`);
18054
+ throw new Error(`Frame set ${key2} is no longer ready for review`);
17531
18055
  }
17532
- upsert(lock, key, {
18056
+ upsert(lock, key2, {
17533
18057
  status: "selected",
17534
18058
  objectId: state.objectId,
17535
18059
  candidateIndex: null,
@@ -17545,7 +18069,7 @@ async function prepareReview(provider, lock, opts = {}) {
17545
18069
  } : entry.providerMetadata
17546
18070
  });
17547
18071
  selected++;
17548
- log(` accepted ${key} \u2192 ${state.sources.length} ordered frames`);
18072
+ log(` accepted ${key2} \u2192 ${state.sources.length} ordered frames`);
17549
18073
  continue;
17550
18074
  }
17551
18075
  const { objectId, sourceUrl, metadata } = await requireSelectCandidate(provider)(
@@ -17554,11 +18078,11 @@ async function prepareReview(provider, lock, opts = {}) {
17554
18078
  `asset:${entry.assetId}`,
17555
18079
  entry.generator
17556
18080
  );
17557
- upsert(lock, key, {
18081
+ upsert(lock, key2, {
17558
18082
  status: "selected",
17559
18083
  objectId,
17560
18084
  candidateIndex: index,
17561
- sourceUrl: sourceUrl ?? providerUrls.get(key)?.[index] ?? null,
18085
+ sourceUrl: sourceUrl ?? providerUrls.get(key2)?.[index] ?? null,
17562
18086
  sourceUrls: [],
17563
18087
  provider: provider.id,
17564
18088
  providerMetadata: metadata ? {
@@ -17570,7 +18094,7 @@ async function prepareReview(provider, lock, opts = {}) {
17570
18094
  } : entry.providerMetadata
17571
18095
  });
17572
18096
  selected++;
17573
- log(` picked ${key} \u2192 candidate ${index + 1}`);
18097
+ log(` picked ${key2} \u2192 candidate ${index + 1}`);
17574
18098
  }
17575
18099
  await saveLock(lockPath, lock);
17576
18100
  return { selected, skipped: groups.length - selected };
@@ -17610,14 +18134,14 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
17610
18134
 
17611
18135
  // src/gallery/snapshot.ts
17612
18136
  import { createHash as createHash5 } from "crypto";
17613
- import { existsSync as existsSync29 } from "fs";
17614
- import { readFile as readFile26, stat as stat3 } from "fs/promises";
17615
- import path34 from "path";
18137
+ import { existsSync as existsSync32 } from "fs";
18138
+ import { readFile as readFile27, stat as stat3 } from "fs/promises";
18139
+ import path37 from "path";
17616
18140
 
17617
18141
  // src/workspace.ts
17618
- import { mkdir as mkdir8, readFile as readFile20, rename as rename6, rm as rm7, writeFile as writeFile10 } from "fs/promises";
17619
- import { existsSync as existsSync24 } from "fs";
17620
- import path27 from "path";
18142
+ import { mkdir as mkdir9, readFile as readFile21, rename as rename7, rm as rm7, writeFile as writeFile11 } from "fs/promises";
18143
+ import { existsSync as existsSync27 } from "fs";
18144
+ import path30 from "path";
17621
18145
  import { z as z7 } from "zod";
17622
18146
  var WorkspaceProjectSchema = z7.object({
17623
18147
  id: z7.string().min(1),
@@ -17642,10 +18166,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
17642
18166
  );
17643
18167
  }
17644
18168
  async function loadWorkspace(workspacePath) {
17645
- if (!existsSync24(workspacePath)) return { version: 1, projects: [] };
18169
+ if (!existsSync27(workspacePath)) return { version: 1, projects: [] };
17646
18170
  let raw;
17647
18171
  try {
17648
- raw = JSON.parse(await readFile20(workspacePath, "utf8"));
18172
+ raw = JSON.parse(await readFile21(workspacePath, "utf8"));
17649
18173
  } catch (err) {
17650
18174
  throw new ProjectError(
17651
18175
  `Workspace catalog at ${workspacePath} is malformed:
@@ -17659,22 +18183,22 @@ async function saveWorkspace(workspacePath, ws) {
17659
18183
  version: 1,
17660
18184
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
17661
18185
  };
17662
- await mkdir8(path27.dirname(path27.resolve(workspacePath)), { recursive: true });
18186
+ await mkdir9(path30.dirname(path30.resolve(workspacePath)), { recursive: true });
17663
18187
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
17664
18188
  try {
17665
- await writeFile10(tmp, JSON.stringify(sorted, null, 2) + "\n");
17666
- await rename6(tmp, workspacePath);
18189
+ await writeFile11(tmp, JSON.stringify(sorted, null, 2) + "\n");
18190
+ await rename7(tmp, workspacePath);
17667
18191
  } finally {
17668
18192
  await rm7(tmp, { force: true });
17669
18193
  }
17670
18194
  }
17671
18195
  function toPortablePath(dir, absolute) {
17672
- return path27.relative(dir, absolute).split(path27.sep).join("/");
18196
+ return path30.relative(dir, absolute).split(path30.sep).join("/");
17673
18197
  }
17674
18198
  function resolveProject(dir, project) {
17675
18199
  return {
17676
- manifestPath: path27.resolve(dir, project.manifest.split("/").join(path27.sep)),
17677
- lockPath: path27.resolve(dir, project.lock.split("/").join(path27.sep))
18200
+ manifestPath: path30.resolve(dir, project.manifest.split("/").join(path30.sep)),
18201
+ lockPath: path30.resolve(dir, project.lock.split("/").join(path30.sep))
17678
18202
  };
17679
18203
  }
17680
18204
  function validateWorkspace(ws, dir) {
@@ -17687,21 +18211,21 @@ function validateWorkspace(ws, dir) {
17687
18211
  const { manifestPath, lockPath } = resolveProject(dir, project);
17688
18212
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project.id]);
17689
18213
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project.id]);
17690
- if (path27.isAbsolute(project.manifest) || path27.isAbsolute(project.lock)) {
18214
+ if (path30.isAbsolute(project.manifest) || path30.isAbsolute(project.lock)) {
17691
18215
  diagnostics.push({
17692
18216
  id: "absolute-path",
17693
18217
  level: "warning",
17694
18218
  message: `project "${project.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
17695
18219
  });
17696
18220
  }
17697
- if (!existsSync24(manifestPath)) {
18221
+ if (!existsSync27(manifestPath)) {
17698
18222
  diagnostics.push({
17699
18223
  id: "missing-manifest",
17700
18224
  level: "error",
17701
18225
  message: `project "${project.id}" manifest not found: ${manifestPath}`
17702
18226
  });
17703
18227
  }
17704
- if (!existsSync24(lockPath)) {
18228
+ if (!existsSync27(lockPath)) {
17705
18229
  diagnostics.push({
17706
18230
  id: "missing-lock",
17707
18231
  level: "error",
@@ -17748,16 +18272,16 @@ function validateWorkspace(ws, dir) {
17748
18272
  }
17749
18273
 
17750
18274
  // src/gallery/edit.ts
17751
- import { readFile as readFile25, rename as rename9, writeFile as writeFile16 } from "fs/promises";
17752
- import path33 from "path";
18275
+ import { readFile as readFile26, rename as rename10, writeFile as writeFile17 } from "fs/promises";
18276
+ import path36 from "path";
17753
18277
  import { z as z13 } from "zod";
17754
18278
 
17755
18279
  // src/manifest-edit.ts
17756
- import { readFile as readFile21, rename as rename7, rm as rm8, writeFile as writeFile11 } from "fs/promises";
17757
- import path28 from "path";
18280
+ import { readFile as readFile22, rename as rename8, rm as rm8, writeFile as writeFile12 } from "fs/promises";
18281
+ import path31 from "path";
17758
18282
  import { z as z8 } from "zod";
17759
18283
  var HexSha = z8.string().regex(/^[0-9a-f]{64}$/);
17760
- var ProjectFileSchema = z8.string().min(1).refine((file) => !path28.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
18284
+ var ProjectFileSchema = z8.string().min(1).refine((file) => !path31.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
17761
18285
  var AssetPatchSchema = z8.object({
17762
18286
  prompt: z8.string().optional(),
17763
18287
  /** Per-style override for the style being viewed; null removes it. */
@@ -18024,9 +18548,9 @@ function styleProvider(raw, styleId, seen = /* @__PURE__ */ new Set()) {
18024
18548
  seen.add(styleId);
18025
18549
  return style.extends ? styleProvider(raw, style.extends, seen) : raw.provider ?? "pixellab";
18026
18550
  }
18027
- function setOrDelete(target, key, value) {
18028
- if (value === null || value === void 0) delete target[key];
18029
- else target[key] = value;
18551
+ function setOrDelete(target, key2, value) {
18552
+ if (value === null || value === void 0) delete target[key2];
18553
+ else target[key2] = value;
18030
18554
  }
18031
18555
  function assetStyles(raw, asset) {
18032
18556
  const own = Array.isArray(asset.styles) ? asset.styles : [];
@@ -18177,8 +18701,8 @@ function applyEdit(raw, edit) {
18177
18701
  }
18178
18702
  }
18179
18703
  async function withCandidate(manifestPath, edit, use, unchanged) {
18180
- const absolute = path28.resolve(manifestPath);
18181
- const original = await readFile21(absolute, "utf8");
18704
+ const absolute = path31.resolve(manifestPath);
18705
+ const original = await readFile22(absolute, "utf8");
18182
18706
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
18183
18707
  let raw;
18184
18708
  try {
@@ -18191,12 +18715,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
18191
18715
  applyEdit(raw, edit);
18192
18716
  const next = serializeLike(original, raw);
18193
18717
  if (next === original) return unchanged(absolute, original);
18194
- const tmp = path28.join(
18195
- path28.dirname(absolute),
18196
- `.${path28.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
18718
+ const tmp = path31.join(
18719
+ path31.dirname(absolute),
18720
+ `.${path31.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
18197
18721
  );
18198
18722
  try {
18199
- await writeFile11(tmp, next);
18723
+ await writeFile12(tmp, next);
18200
18724
  let specs;
18201
18725
  try {
18202
18726
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -18214,7 +18738,7 @@ async function applyManifestEdit(manifestPath, edit) {
18214
18738
  manifestPath,
18215
18739
  edit,
18216
18740
  async ({ absolute, next, tmp }) => {
18217
- await rename7(tmp, absolute);
18741
+ await rename8(tmp, absolute);
18218
18742
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
18219
18743
  },
18220
18744
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -18222,18 +18746,18 @@ async function applyManifestEdit(manifestPath, edit) {
18222
18746
  }
18223
18747
 
18224
18748
  // src/pipeline/hand-edit.ts
18225
- import { existsSync as existsSync25 } from "fs";
18226
- import { copyFile, mkdir as mkdir9, readFile as readFile22, rename as rename8, rm as rm9, writeFile as writeFile12 } from "fs/promises";
18227
- import path29 from "path";
18749
+ import { existsSync as existsSync28 } from "fs";
18750
+ import { copyFile, mkdir as mkdir10, readFile as readFile23, rename as rename9, rm as rm9, writeFile as writeFile13 } from "fs/promises";
18751
+ import path32 from "path";
18228
18752
  import { z as z9 } from "zod";
18229
18753
  var HAND_EDIT_DIR = "edits";
18230
18754
  function handEditPath(loaded, spec) {
18231
18755
  const style = loaded.manifest.styles[spec.styleId];
18232
- const outDir = path29.resolve(loaded.root, style?.outDir ?? ".");
18233
- const relative = path29.relative(outDir, spec.outFile);
18234
- const inside = relative && !relative.startsWith("..") && !path29.isAbsolute(relative);
18235
- const file = inside ? relative : path29.basename(spec.outFile);
18236
- return path29.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
18756
+ const outDir = path32.resolve(loaded.root, style?.outDir ?? ".");
18757
+ const relative = path32.relative(outDir, spec.outFile);
18758
+ const inside = relative && !relative.startsWith("..") && !path32.isAbsolute(relative);
18759
+ const file = inside ? relative : path32.basename(spec.outFile);
18760
+ return path32.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
18237
18761
  }
18238
18762
  function handEditBases(spec, lock) {
18239
18763
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -18246,10 +18770,10 @@ function handEditBases(spec, lock) {
18246
18770
  }));
18247
18771
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
18248
18772
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
18249
- if (!members.every((member) => existsSync25(member.path))) return null;
18773
+ if (!members.every((member) => existsSync28(member.path))) return null;
18250
18774
  return members.map(({ role, path: file }) => ({ role, path: file }));
18251
18775
  }
18252
- return existsSync25(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
18776
+ return existsSync28(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
18253
18777
  }
18254
18778
  function handEditBase(spec, lock) {
18255
18779
  const bases = handEditBases(spec, lock);
@@ -18279,18 +18803,18 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
18279
18803
  `${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`
18280
18804
  );
18281
18805
  }
18282
- const existing = spec.source ? path29.resolve(loaded.root, spec.source) : null;
18806
+ const existing = spec.source ? path32.resolve(loaded.root, spec.source) : null;
18283
18807
  const editPath = existing ?? handEditPath(loaded, spec);
18284
18808
  const members = handEditMembers(loaded, spec, lock, editPath);
18285
18809
  let created = false;
18286
18810
  for (const member of members) {
18287
- if (existsSync25(member.path)) continue;
18811
+ if (existsSync28(member.path)) continue;
18288
18812
  if (!member.base) {
18289
18813
  throw new ManifestEditError(
18290
18814
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
18291
18815
  );
18292
18816
  }
18293
- await mkdir9(path29.dirname(member.path), { recursive: true });
18817
+ await mkdir10(path32.dirname(member.path), { recursive: true });
18294
18818
  await copyFile(member.base, member.path);
18295
18819
  created = true;
18296
18820
  }
@@ -18369,7 +18893,7 @@ function handEditProjectPath(editPath) {
18369
18893
  async function readHandEditCompanion(editPath) {
18370
18894
  let text;
18371
18895
  try {
18372
- text = await readFile22(handEditCompanionPath(editPath), "utf8");
18896
+ text = await readFile23(handEditCompanionPath(editPath), "utf8");
18373
18897
  } catch {
18374
18898
  return null;
18375
18899
  }
@@ -18412,7 +18936,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
18412
18936
  }
18413
18937
  });
18414
18938
  const bases = handEditBases(spec, lock);
18415
- const expectedSize = bases?.[0] ? decodePng(await readFile22(bases[0].path)) : { width: spec.width, height: spec.height };
18939
+ const expectedSize = bases?.[0] ? decodePng(await readFile23(bases[0].path)) : { width: spec.width, height: spec.height };
18416
18940
  for (const [index, image] of decoded.entries()) {
18417
18941
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
18418
18942
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -18428,7 +18952,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
18428
18952
  editor: input.editor,
18429
18953
  protocol: input.protocol,
18430
18954
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
18431
- project: projectPath ? path29.basename(projectPath) : null,
18955
+ project: projectPath ? path32.basename(projectPath) : null,
18432
18956
  outputs: incoming.map((frame, index) => ({
18433
18957
  role: frame.role,
18434
18958
  basedOn: basedOnHash(entry, index),
@@ -18458,8 +18982,8 @@ function basedOnHash(entry, index) {
18458
18982
  async function replaceFile(file, bytes) {
18459
18983
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18460
18984
  try {
18461
- await writeFile12(tmp, bytes);
18462
- await rename8(tmp, file);
18985
+ await writeFile13(tmp, bytes);
18986
+ await rename9(tmp, file);
18463
18987
  } finally {
18464
18988
  await rm9(tmp, { force: true });
18465
18989
  }
@@ -18470,9 +18994,9 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
18470
18994
  }
18471
18995
 
18472
18996
  // src/gallery/upload.ts
18473
- import { existsSync as existsSync26 } from "fs";
18474
- import { mkdir as mkdir10, writeFile as writeFile13 } from "fs/promises";
18475
- import path30 from "path";
18997
+ import { existsSync as existsSync29 } from "fs";
18998
+ import { mkdir as mkdir11, writeFile as writeFile14 } from "fs/promises";
18999
+ import path33 from "path";
18476
19000
  import { z as z10 } from "zod";
18477
19001
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
18478
19002
  var UploadImageSchema = z10.object({
@@ -18485,12 +19009,12 @@ var UploadImageSchema = z10.object({
18485
19009
  overwrite: z10.boolean().optional()
18486
19010
  }).strict();
18487
19011
  async function saveProjectImage(root, request) {
18488
- const file = path30.resolve(root, request.path);
18489
- const relative = path30.relative(root, file);
18490
- if (relative.startsWith("..") || path30.isAbsolute(relative)) {
19012
+ const file = path33.resolve(root, request.path);
19013
+ const relative = path33.relative(root, file);
19014
+ if (relative.startsWith("..") || path33.isAbsolute(relative)) {
18491
19015
  throw new ManifestEditError("an upload must stay inside the project");
18492
19016
  }
18493
- const extension = path30.extname(file).toLowerCase();
19017
+ const extension = path33.extname(file).toLowerCase();
18494
19018
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
18495
19019
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
18496
19020
  const bytes = Buffer.from(request.base64, "base64");
@@ -18502,18 +19026,18 @@ async function saveProjectImage(root, request) {
18502
19026
  if (metadata.format !== expected) {
18503
19027
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
18504
19028
  }
18505
- if (existsSync26(file) && !request.overwrite) {
18506
- throw new ManifestEditError(`${relative.split(path30.sep).join("/")} already exists; choose another name, or replace it`);
19029
+ if (existsSync29(file) && !request.overwrite) {
19030
+ throw new ManifestEditError(`${relative.split(path33.sep).join("/")} already exists; choose another name, or replace it`);
18507
19031
  }
18508
- await mkdir10(path30.dirname(file), { recursive: true });
18509
- await writeFile13(file, bytes);
18510
- return relative.split(path30.sep).join("/");
19032
+ await mkdir11(path33.dirname(file), { recursive: true });
19033
+ await writeFile14(file, bytes);
19034
+ return relative.split(path33.sep).join("/");
18511
19035
  }
18512
19036
 
18513
19037
  // src/gallery/image-revision.ts
18514
- import { existsSync as existsSync27 } from "fs";
18515
- import { readFile as readFile23, rm as rm10, writeFile as writeFile14 } from "fs/promises";
18516
- import path31 from "path";
19038
+ import { existsSync as existsSync30 } from "fs";
19039
+ import { readFile as readFile24, rm as rm10, writeFile as writeFile15 } from "fs/promises";
19040
+ import path34 from "path";
18517
19041
  import { z as z11 } from "zod";
18518
19042
  var InpaintRevisionRequestSchema = z11.object({
18519
19043
  action: z11.literal("create-inpaint-revision"),
@@ -18532,15 +19056,15 @@ var InpaintRevisionRequestSchema = z11.object({
18532
19056
  overwrite: z11.boolean().optional()
18533
19057
  }).strict();
18534
19058
  async function createInpaintRevision(manifestPath, request) {
18535
- const root = path31.dirname(path31.resolve(manifestPath));
18536
- if (path31.extname(request.maskPath).toLowerCase() !== ".png") {
19059
+ const root = path34.dirname(path34.resolve(manifestPath));
19060
+ if (path34.extname(request.maskPath).toLowerCase() !== ".png") {
18537
19061
  throw new ManifestEditError("the mask must be a .png path inside the project");
18538
19062
  }
18539
19063
  const bytes = Buffer.from(request.maskBase64, "base64");
18540
19064
  const metadata = imageMetadata(bytes);
18541
19065
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
18542
- const file = path31.resolve(root, request.maskPath);
18543
- const previous = existsSync27(file) ? await readFile23(file) : null;
19066
+ const file = path34.resolve(root, request.maskPath);
19067
+ const previous = existsSync30(file) ? await readFile24(file) : null;
18544
19068
  const mask = await saveProjectImage(root, {
18545
19069
  action: "upload-image",
18546
19070
  path: request.maskPath,
@@ -18559,7 +19083,7 @@ async function createInpaintRevision(manifestPath, request) {
18559
19083
  }
18560
19084
  });
18561
19085
  } catch (error) {
18562
- if (previous) await writeFile14(file, previous);
19086
+ if (previous) await writeFile15(file, previous);
18563
19087
  else await rm10(file, { force: true });
18564
19088
  throw error;
18565
19089
  }
@@ -18567,9 +19091,9 @@ async function createInpaintRevision(manifestPath, request) {
18567
19091
  }
18568
19092
 
18569
19093
  // src/gallery/skeleton.ts
18570
- import { existsSync as existsSync28 } from "fs";
18571
- import { mkdir as mkdir11, readFile as readFile24, rm as rm11, writeFile as writeFile15 } from "fs/promises";
18572
- import path32 from "path";
19094
+ import { existsSync as existsSync31 } from "fs";
19095
+ import { mkdir as mkdir12, readFile as readFile25, rm as rm11, writeFile as writeFile16 } from "fs/promises";
19096
+ import path35 from "path";
18573
19097
  import { z as z12 } from "zod";
18574
19098
  var SkeletonEstimateRequestSchema = z12.object({
18575
19099
  project: z12.string().min(1).optional(),
@@ -18608,21 +19132,21 @@ var SkeletonKeypointsUpdateSchema = z12.object({
18608
19132
  set: SkeletonSetSchema
18609
19133
  }).strict();
18610
19134
  async function createSkeletonAnimation(manifestPath, request) {
18611
- const root = path32.dirname(path32.resolve(manifestPath));
18612
- const file = path32.resolve(root, request.keypointsFile);
18613
- const relative = path32.relative(root, file);
18614
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path32.isAbsolute(relative)) {
19135
+ const root = path35.dirname(path35.resolve(manifestPath));
19136
+ const file = path35.resolve(root, request.keypointsFile);
19137
+ const relative = path35.relative(root, file);
19138
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path35.isAbsolute(relative)) {
18615
19139
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
18616
19140
  }
18617
- const existed = existsSync28(file);
19141
+ const existed = existsSync31(file);
18618
19142
  let previous = null;
18619
19143
  if (request.set) {
18620
19144
  if (existed && !request.overwrite) {
18621
19145
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
18622
19146
  }
18623
- if (existed) previous = await readFile24(file);
18624
- await mkdir11(path32.dirname(file), { recursive: true });
18625
- await writeFile15(file, JSON.stringify(request.set, null, 2) + "\n");
19147
+ if (existed) previous = await readFile25(file);
19148
+ await mkdir12(path35.dirname(file), { recursive: true });
19149
+ await writeFile16(file, JSON.stringify(request.set, null, 2) + "\n");
18626
19150
  } else if (!existed) {
18627
19151
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
18628
19152
  }
@@ -18637,7 +19161,7 @@ async function createSkeletonAnimation(manifestPath, request) {
18637
19161
  revision: {
18638
19162
  mode: "animate-skeleton",
18639
19163
  from: request.from,
18640
- keypointsFile: relative.split(path32.sep).join("/"),
19164
+ keypointsFile: relative.split(path35.sep).join("/"),
18641
19165
  direction: request.direction,
18642
19166
  description: request.description,
18643
19167
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -18646,31 +19170,31 @@ async function createSkeletonAnimation(manifestPath, request) {
18646
19170
  });
18647
19171
  } catch (error) {
18648
19172
  if (request.set) {
18649
- if (previous) await writeFile15(file, previous);
19173
+ if (previous) await writeFile16(file, previous);
18650
19174
  else await rm11(file, { force: true });
18651
19175
  }
18652
19176
  throw error;
18653
19177
  }
18654
19178
  }
18655
19179
  async function updateSkeletonKeypoints(ctx, request) {
18656
- const key = lockKey(request.styleId, request.assetId);
18657
- const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key);
18658
- if (!spec) throw new ManifestEditError(`"${key}" is not declared by the manifest`);
19180
+ const key2 = lockKey(request.styleId, request.assetId);
19181
+ const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key2);
19182
+ if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
18659
19183
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
18660
- if (!file) throw new ManifestEditError(`${key} is not an animate-skeleton revision`);
18661
- const relative = path32.relative(ctx.loaded.root, file);
18662
- if (relative.startsWith("..") || path32.isAbsolute(relative)) {
18663
- throw new ManifestEditError(`${key}'s keypoints file is outside the project; edit it by hand`);
19184
+ if (!file) throw new ManifestEditError(`${key2} is not an animate-skeleton revision`);
19185
+ const relative = path35.relative(ctx.loaded.root, file);
19186
+ if (relative.startsWith("..") || path35.isAbsolute(relative)) {
19187
+ throw new ManifestEditError(`${key2}'s keypoints file is outside the project; edit it by hand`);
18664
19188
  }
18665
- const current = existsSync28(file) ? sha256(await readFile24(file)) : null;
19189
+ const current = existsSync31(file) ? sha256(await readFile25(file)) : null;
18666
19190
  if (current !== request.expectedSha256) {
18667
19191
  throw Object.assign(
18668
- new Error(`${relative.split(path32.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
19192
+ new Error(`${relative.split(path35.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
18669
19193
  { status: 409 }
18670
19194
  );
18671
19195
  }
18672
- await writeFile15(file, JSON.stringify(request.set, null, 2) + "\n");
18673
- return relative.split(path32.sep).join("/");
19196
+ await writeFile16(file, JSON.stringify(request.set, null, 2) + "\n");
19197
+ return relative.split(path35.sep).join("/");
18674
19198
  }
18675
19199
 
18676
19200
  // src/gallery/edit.ts
@@ -18724,7 +19248,7 @@ function createGalleryEditHandler(opts) {
18724
19248
  const history = /* @__PURE__ */ new Map();
18725
19249
  const manifestOf = async (project) => {
18726
19250
  try {
18727
- return path33.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
19251
+ return path36.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
18728
19252
  } catch {
18729
19253
  return null;
18730
19254
  }
@@ -18734,7 +19258,7 @@ function createGalleryEditHandler(opts) {
18734
19258
  if (undo.success) {
18735
19259
  const manifestPath2 = await manifestOf(undo.data.project);
18736
19260
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
18737
- const current = await readFile25(manifestPath2, "utf8");
19261
+ const current = await readFile26(manifestPath2, "utf8");
18738
19262
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
18739
19263
  const stack = history.get(manifestPath2) ?? [];
18740
19264
  const last = stack[stack.length - 1];
@@ -18744,17 +19268,17 @@ function createGalleryEditHandler(opts) {
18744
19268
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
18745
19269
  }
18746
19270
  const tmp = manifestPath2 + ".pixelkiln-undo";
18747
- await writeFile16(tmp, last.before);
18748
- await rename9(tmp, manifestPath2);
19271
+ await writeFile17(tmp, last.before);
19272
+ await rename10(tmp, manifestPath2);
18749
19273
  stack.pop();
18750
- log(` manifest edit undone in ${path33.relative(process.cwd(), manifestPath2) || manifestPath2}`);
19274
+ log(` manifest edit undone in ${path36.relative(process.cwd(), manifestPath2) || manifestPath2}`);
18751
19275
  return opts.reload();
18752
19276
  }
18753
19277
  const manifestPath = await manifestOf(body?.project);
18754
- const before = manifestPath ? await readFile25(manifestPath, "utf8").catch(() => null) : null;
19278
+ const before = manifestPath ? await readFile26(manifestPath, "utf8").catch(() => null) : null;
18755
19279
  const build = await apply(body);
18756
19280
  if (manifestPath && before !== null) {
18757
- const after = await readFile25(manifestPath, "utf8").catch(() => null);
19281
+ const after = await readFile26(manifestPath, "utf8").catch(() => null);
18758
19282
  if (after !== null && after !== before) {
18759
19283
  const stack = history.get(manifestPath) ?? [];
18760
19284
  stack.push({ before, afterSha: sha256(after) });
@@ -18809,7 +19333,7 @@ function createEditApplier(opts, log) {
18809
19333
  } catch (error) {
18810
19334
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
18811
19335
  }
18812
- const written = await saveProjectImage(path33.dirname(path33.resolve(manifestPath2)), upload.data);
19336
+ const written = await saveProjectImage(path36.dirname(path36.resolve(manifestPath2)), upload.data);
18813
19337
  log(` image added: ${written}`);
18814
19338
  return opts.reload();
18815
19339
  }
@@ -18876,7 +19400,7 @@ function createEditApplier(opts, log) {
18876
19400
  }
18877
19401
  const result = await applyManifestEdit(manifestPath, parsed.data);
18878
19402
  if (result.changed) {
18879
- const relative = path33.relative(process.cwd(), result.manifestPath);
19403
+ const relative = path36.relative(process.cwd(), result.manifestPath);
18880
19404
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
18881
19405
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
18882
19406
  }
@@ -18904,7 +19428,7 @@ function describeEdit(edit) {
18904
19428
  // src/gallery/snapshot.ts
18905
19429
  var PROJECT_FILE_TYPE = "application/octet-stream";
18906
19430
  function galleryMediaId(absolutePath) {
18907
- return createHash5("sha256").update(path34.resolve(absolutePath)).digest("hex").slice(0, 24);
19431
+ return createHash5("sha256").update(path37.resolve(absolutePath)).digest("hex").slice(0, 24);
18908
19432
  }
18909
19433
  function galleryMediaRoute(id) {
18910
19434
  return `/media/${id}`;
@@ -18928,9 +19452,9 @@ function describeHistory(media, entry, cacheDir) {
18928
19452
  return (entry.history ?? []).map((generation, i) => {
18929
19453
  const outputs = generation.outputs.map((output) => {
18930
19454
  const mediaType = output.mediaType ?? MediaType.PNG;
18931
- const file = path34.join(cacheDir, cacheFileName(output.sha256, mediaType));
19455
+ const file = path37.join(cacheDir, cacheFileName(output.sha256, mediaType));
18932
19456
  let url = null;
18933
- if (existsSync29(file)) {
19457
+ if (existsSync32(file)) {
18934
19458
  const id = galleryMediaId(file);
18935
19459
  media.set(id, { path: file, contentType: mediaType });
18936
19460
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -18962,7 +19486,7 @@ function describeHistory(media, entry, cacheDir) {
18962
19486
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
18963
19487
  async function samePixels(a, b) {
18964
19488
  try {
18965
- const [left, right] = await Promise.all([readFile26(a), readFile26(b)]);
19489
+ const [left, right] = await Promise.all([readFile27(a), readFile27(b)]);
18966
19490
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
18967
19491
  const x = decodePng(left);
18968
19492
  const y = decodePng(right);
@@ -19060,10 +19584,10 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
19060
19584
  async function describeQuality(media, root, inspection) {
19061
19585
  const outputPaths = inspection.outputs ?? [inspection.output];
19062
19586
  const outputs = await Promise.all(
19063
- outputPaths.map((file) => describeOutput(media, root, path34.resolve(root, file)))
19587
+ outputPaths.map((file) => describeOutput(media, root, path37.resolve(root, file)))
19064
19588
  );
19065
- const recordPath = path34.resolve(root, inspection.record);
19066
- const recordExists = existsSync29(recordPath);
19589
+ const recordPath = path37.resolve(root, inspection.record);
19590
+ const recordExists = existsSync32(recordPath);
19067
19591
  let options = null;
19068
19592
  let check = null;
19069
19593
  if (recordExists) {
@@ -19082,7 +19606,7 @@ async function describeQuality(media, root, inspection) {
19082
19606
  return {
19083
19607
  state: inspection.state,
19084
19608
  reason: inspection.reason,
19085
- output: portableOutputPath(path34.resolve(root, inspection.output), root),
19609
+ output: portableOutputPath(path37.resolve(root, inspection.output), root),
19086
19610
  record: portableOutputPath(recordPath, root),
19087
19611
  recordExists,
19088
19612
  outputs,
@@ -19120,9 +19644,9 @@ async function buildGallerySnapshot(opts) {
19120
19644
  const media = /* @__PURE__ */ new Map();
19121
19645
  const plan = await buildPlan(specs, lock);
19122
19646
  const items = [];
19123
- const manifestText = await readFile26(loaded.path, "utf8");
19647
+ const manifestText = await readFile27(loaded.path, "utf8");
19124
19648
  const manifestSha256 = sha256(manifestText);
19125
- const cacheDir = path34.resolve(path34.dirname(opts.lockPath), ".pixelkiln", "cache");
19649
+ const cacheDir = path37.resolve(path37.dirname(opts.lockPath), ".pixelkiln", "cache");
19126
19650
  let rawStyles = {};
19127
19651
  try {
19128
19652
  const raw = JSON.parse(manifestText);
@@ -19130,8 +19654,8 @@ async function buildGallerySnapshot(opts) {
19130
19654
  } catch {
19131
19655
  }
19132
19656
  for (const planItem of plan.items) {
19133
- const { spec, key } = planItem;
19134
- const entry = lock.entries[key];
19657
+ const { spec, key: key2 } = planItem;
19658
+ const entry = lock.entries[key2];
19135
19659
  const asset = loaded.manifest.assets[spec.assetId] ?? null;
19136
19660
  let outputs;
19137
19661
  let edit = null;
@@ -19146,12 +19670,12 @@ async function buildGallerySnapshot(opts) {
19146
19670
  )
19147
19671
  );
19148
19672
  if (spec.source) {
19149
- const editPath = path34.resolve(root, spec.source);
19673
+ const editPath = path37.resolve(root, spec.source);
19150
19674
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
19151
19675
  const editShas = await Promise.all(
19152
19676
  Array.from({ length: memberCount }, async (_, index) => {
19153
19677
  const file = sourceOutputPath(spec.source, entry, index, root);
19154
- return { file, sha256: existsSync29(file) ? await sha256File(file) : null };
19678
+ return { file, sha256: existsSync32(file) ? await sha256File(file) : null };
19155
19679
  })
19156
19680
  );
19157
19681
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -19159,7 +19683,7 @@ async function buildGallerySnapshot(opts) {
19159
19683
  const companion = await readHandEditCompanion(editPath);
19160
19684
  if (companion) {
19161
19685
  const projectPath = handEditProjectPath(editPath);
19162
- const project = companion.project && existsSync29(projectPath) ? await fileInfo(projectPath) : null;
19686
+ const project = companion.project && existsSync32(projectPath) ? await fileInfo(projectPath) : null;
19163
19687
  let projectUrl = null;
19164
19688
  if (project) {
19165
19689
  const id = galleryMediaId(projectPath);
@@ -19195,17 +19719,17 @@ async function buildGallerySnapshot(opts) {
19195
19719
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
19196
19720
  }
19197
19721
  } else if (spec.source) {
19198
- outputs = [await describeOutput(media, root, path34.resolve(root, spec.source))];
19199
- } else if (!entry && existsSync29(spec.outFile)) {
19722
+ outputs = [await describeOutput(media, root, path37.resolve(root, spec.source))];
19723
+ } else if (!entry && existsSync32(spec.outFile)) {
19200
19724
  outputs = [await describeOutput(media, root, spec.outFile)];
19201
19725
  } else {
19202
19726
  outputs = [];
19203
19727
  }
19204
19728
  const quality = planItem.quality ? await describeQuality(media, root, planItem.quality) : null;
19205
19729
  items.push({
19206
- id: key,
19730
+ id: key2,
19207
19731
  project: null,
19208
- key,
19732
+ key: key2,
19209
19733
  styleId: spec.styleId,
19210
19734
  assetId: spec.assetId,
19211
19735
  declared: true,
@@ -19263,8 +19787,8 @@ async function buildGallerySnapshot(opts) {
19263
19787
  });
19264
19788
  }
19265
19789
  const shown = new Set(items.map((item) => item.key));
19266
- for (const [key, entry] of Object.entries(lock.entries)) {
19267
- if (shown.has(key)) continue;
19790
+ for (const [key2, entry] of Object.entries(lock.entries)) {
19791
+ if (shown.has(key2)) continue;
19268
19792
  if (isDeclared(loaded, entry.styleId, entry.assetId)) continue;
19269
19793
  if (!matchesFilter(filter, entry.styleId, entry.assetId)) continue;
19270
19794
  const outputs = await Promise.all(
@@ -19273,9 +19797,9 @@ async function buildGallerySnapshot(opts) {
19273
19797
  )
19274
19798
  );
19275
19799
  items.push({
19276
- id: key,
19800
+ id: key2,
19277
19801
  project: null,
19278
- key,
19802
+ key: key2,
19279
19803
  styleId: entry.styleId,
19280
19804
  assetId: entry.assetId,
19281
19805
  declared: false,
@@ -19376,7 +19900,7 @@ async function buildGallerySnapshot(opts) {
19376
19900
  } : null,
19377
19901
  tags: style?.tags ?? [],
19378
19902
  extends: typeof rawStyle?.extends === "string" ? rawStyle.extends : null,
19379
- ownFields: rawStyle ? Object.keys(rawStyle).filter((key) => key !== "extends") : [],
19903
+ ownFields: rawStyle ? Object.keys(rawStyle).filter((key2) => key2 !== "extends") : [],
19380
19904
  items: styleItems.length,
19381
19905
  spendByUnit: spend,
19382
19906
  regenerate: {
@@ -19400,7 +19924,7 @@ async function buildGallerySnapshot(opts) {
19400
19924
  id: loaded.manifest.name,
19401
19925
  name: loaded.manifest.name,
19402
19926
  manifest: loaded.path,
19403
- lock: path34.resolve(opts.lockPath),
19927
+ lock: path37.resolve(opts.lockPath),
19404
19928
  root,
19405
19929
  provider: loaded.manifest.provider,
19406
19930
  account: null,
@@ -19426,7 +19950,7 @@ async function buildGallerySnapshot(opts) {
19426
19950
  return { snapshot, media };
19427
19951
  }
19428
19952
  async function buildWorkspaceGallerySnapshot(opts) {
19429
- const dir = path34.dirname(path34.resolve(opts.workspacePath));
19953
+ const dir = path37.dirname(path37.resolve(opts.workspacePath));
19430
19954
  const media = /* @__PURE__ */ new Map();
19431
19955
  const projects = [];
19432
19956
  const items = [];
@@ -19469,11 +19993,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
19469
19993
  id: project.id,
19470
19994
  name: loaded.manifest.name,
19471
19995
  manifest: manifestPath,
19472
- lock: path34.resolve(lockPath),
19996
+ lock: path37.resolve(lockPath),
19473
19997
  root: loaded.root,
19474
19998
  provider: loaded.manifest.provider,
19475
19999
  account: project.account ?? null,
19476
- manifestSha256: manifestSha256 ?? sha256(await readFile26(manifestPath, "utf8")),
20000
+ manifestSha256: manifestSha256 ?? sha256(await readFile27(manifestPath, "utf8")),
19477
20001
  historyLimit: historyLimit(loaded.manifest),
19478
20002
  entries: Object.keys(lock.entries).length,
19479
20003
  items: projectItems.length,
@@ -19485,8 +20009,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
19485
20009
  id: project.id,
19486
20010
  name: project.id,
19487
20011
  manifest: manifestPath,
19488
- lock: path34.resolve(lockPath),
19489
- root: path34.dirname(manifestPath),
20012
+ lock: path37.resolve(lockPath),
20013
+ root: path37.dirname(manifestPath),
19490
20014
  provider: project.provider,
19491
20015
  account: project.account ?? null,
19492
20016
  manifestSha256: null,
@@ -19513,7 +20037,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
19513
20037
  version: 1,
19514
20038
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
19515
20039
  project: null,
19516
- workspace: { path: path34.resolve(opts.workspacePath), dir, projects },
20040
+ workspace: { path: path37.resolve(opts.workspacePath), dir, projects },
19517
20041
  filter,
19518
20042
  totals: {
19519
20043
  entries: projects.reduce((sum, project) => sum + project.entries, 0),
@@ -19530,7 +20054,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
19530
20054
  }
19531
20055
 
19532
20056
  // src/gallery/page.ts
19533
- import { existsSync as existsSync30, readFileSync as readFileSync7 } from "fs";
20057
+ import { existsSync as existsSync33, readFileSync as readFileSync8 } from "fs";
19534
20058
 
19535
20059
  // src/gallery/client-bundle.ts
19536
20060
  import { createRequire } from "module";
@@ -19570,8 +20094,8 @@ var client;
19570
20094
  function clientAssets() {
19571
20095
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
19572
20096
  client ??= {
19573
- css: readFileSync7(new URL("gallery.css", CLIENT_DIR), "utf8"),
19574
- js: existsSync30(prebuilt) ? readFileSync7(prebuilt, "utf8") : bundleGalleryClient()
20097
+ css: readFileSync8(new URL("gallery.css", CLIENT_DIR), "utf8"),
20098
+ js: existsSync33(prebuilt) ? readFileSync8(prebuilt, "utf8") : bundleGalleryClient()
19575
20099
  };
19576
20100
  return client;
19577
20101
  }
@@ -19714,10 +20238,10 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
19714
20238
 
19715
20239
  // src/editor/install.ts
19716
20240
  import { createHash as createHash6 } from "crypto";
19717
- import { existsSync as existsSync31 } from "fs";
19718
- import { mkdir as mkdir12, readFile as readFile27, rename as rename10, rm as rm12, stat as stat4, writeFile as writeFile17 } from "fs/promises";
20241
+ import { existsSync as existsSync34 } from "fs";
20242
+ import { mkdir as mkdir13, readFile as readFile28, rename as rename11, rm as rm12, stat as stat4, writeFile as writeFile18 } from "fs/promises";
19719
20243
  import os3 from "os";
19720
- import path35 from "path";
20244
+ import path38 from "path";
19721
20245
  var EditorInstallError = class extends Error {
19722
20246
  constructor(message6, file) {
19723
20247
  super(message6);
@@ -19728,15 +20252,15 @@ var EditorInstallError = class extends Error {
19728
20252
  };
19729
20253
  function editorToolsRoot() {
19730
20254
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
19731
- if (override) return path35.resolve(override);
19732
- if (process.platform === "darwin") return path35.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
20255
+ if (override) return path38.resolve(override);
20256
+ if (process.platform === "darwin") return path38.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
19733
20257
  if (process.platform === "win32") {
19734
- return path35.join(process.env.LOCALAPPDATA ?? path35.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
20258
+ return path38.join(process.env.LOCALAPPDATA ?? path38.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
19735
20259
  }
19736
- return path35.join(process.env.XDG_CACHE_HOME ?? path35.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
20260
+ return path38.join(process.env.XDG_CACHE_HOME ?? path38.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
19737
20261
  }
19738
20262
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
19739
- return path35.join(root, "pixelorama", pin.release ?? "unpublished");
20263
+ return path38.join(root, "pixelorama", pin.release ?? "unpublished");
19740
20264
  }
19741
20265
  function editorBaseUrl(pin = EDITOR_PIN) {
19742
20266
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -19746,7 +20270,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
19746
20270
  }
19747
20271
  async function sha256Of(file) {
19748
20272
  try {
19749
- return createHash6("sha256").update(await readFile27(file)).digest("hex");
20273
+ return createHash6("sha256").update(await readFile28(file)).digest("hex");
19750
20274
  } catch {
19751
20275
  return null;
19752
20276
  }
@@ -19759,8 +20283,8 @@ async function editorStatus(opts = {}) {
19759
20283
  let totalBytes = 0;
19760
20284
  for (const [name, expected] of Object.entries(pin.files)) {
19761
20285
  totalBytes += expected.bytes;
19762
- const file = path35.join(dir, name);
19763
- const info = existsSync31(file) ? await stat4(file).catch(() => null) : null;
20286
+ const file = path38.join(dir, name);
20287
+ const info = existsSync34(file) ? await stat4(file).catch(() => null) : null;
19764
20288
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
19765
20289
  installedBytes += expected.bytes;
19766
20290
  } else {
@@ -19789,7 +20313,7 @@ async function installEditor(opts = {}) {
19789
20313
  );
19790
20314
  }
19791
20315
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
19792
- await mkdir12(dir, { recursive: true });
20316
+ await mkdir13(dir, { recursive: true });
19793
20317
  const downloaded = [];
19794
20318
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
19795
20319
  let fetchedBytes = before.installedBytes;
@@ -19817,11 +20341,11 @@ async function installEditor(opts = {}) {
19817
20341
  if (digest2 !== expected.sha256) {
19818
20342
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
19819
20343
  }
19820
- const final = path35.join(dir, name);
20344
+ const final = path38.join(dir, name);
19821
20345
  const tmp = `${final}.${process.pid}.part`;
19822
20346
  try {
19823
- await writeFile17(tmp, bytes);
19824
- await rename10(tmp, final);
20347
+ await writeFile18(tmp, bytes);
20348
+ await rename11(tmp, final);
19825
20349
  } finally {
19826
20350
  await rm12(tmp, { force: true });
19827
20351
  }
@@ -19863,12 +20387,12 @@ var EDITOR_CONTENT_TYPES = {
19863
20387
  ".json": "application/json; charset=utf-8"
19864
20388
  };
19865
20389
  function editorContentType(name) {
19866
- return EDITOR_CONTENT_TYPES[path35.extname(name).toLowerCase()] ?? null;
20390
+ return EDITOR_CONTENT_TYPES[path38.extname(name).toLowerCase()] ?? null;
19867
20391
  }
19868
20392
 
19869
20393
  // src/gallery/editor.ts
19870
- import { readFile as readFile28 } from "fs/promises";
19871
- import path36 from "path";
20394
+ import { readFile as readFile29 } from "fs/promises";
20395
+ import path39 from "path";
19872
20396
  function editorRoute(release, name = "index.html") {
19873
20397
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
19874
20398
  }
@@ -19941,7 +20465,7 @@ function createGalleryEditorHandlers(opts = {}) {
19941
20465
  if (!status.installed) return null;
19942
20466
  let bytes;
19943
20467
  try {
19944
- bytes = await readFile28(path36.join(dir, name));
20468
+ bytes = await readFile29(path39.join(dir, name));
19945
20469
  } catch {
19946
20470
  verified = null;
19947
20471
  return null;
@@ -19958,7 +20482,7 @@ function createGalleryEditorHandlers(opts = {}) {
19958
20482
  // src/gallery/server.ts
19959
20483
  import { randomBytes } from "crypto";
19960
20484
  import { createServer as createServer2 } from "http";
19961
- import { readFile as readFile29 } from "fs/promises";
20485
+ import { readFile as readFile30 } from "fs/promises";
19962
20486
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
19963
20487
  var EDITOR_CSP = [
19964
20488
  "default-src 'self'",
@@ -20139,7 +20663,7 @@ async function serveGallery(opts) {
20139
20663
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
20140
20664
  if (!asset) return fail(404, "no such review asset");
20141
20665
  try {
20142
- const bytes = await readFile29(asset.path);
20666
+ const bytes = await readFile30(asset.path);
20143
20667
  res.writeHead(200, {
20144
20668
  "Content-Type": asset.contentType,
20145
20669
  "Cache-Control": "no-store",
@@ -20222,7 +20746,7 @@ async function serveGallery(opts) {
20222
20746
  if (!asset) return fail(404, "no such gallery media");
20223
20747
  let bytes;
20224
20748
  try {
20225
- bytes = await readFile29(asset.path);
20749
+ bytes = await readFile30(asset.path);
20226
20750
  } catch {
20227
20751
  return fail(404, "gallery media is no longer on disk; refresh the page");
20228
20752
  }
@@ -20329,7 +20853,7 @@ function createGenerateHandlers(opts) {
20329
20853
  const busy = /* @__PURE__ */ new Map();
20330
20854
  for (const job of jobs.values()) {
20331
20855
  if (job.phase === "done" || job.phase === "failed") continue;
20332
- for (const key of job.keys) busy.set(`${job.project ?? ""}:${key}`, job.id);
20856
+ for (const key2 of job.keys) busy.set(`${job.project ?? ""}:${key2}`, job.id);
20333
20857
  }
20334
20858
  return busy;
20335
20859
  };
@@ -20372,7 +20896,7 @@ function createGenerateHandlers(opts) {
20372
20896
  });
20373
20897
  say(job, `${providerId}: ${res.completed} completed, ${res.review} awaiting review, ${res.failed} failed, ${res.stillRunning} still running`);
20374
20898
  }
20375
- job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key) => ctx.lock.entries[key]?.status === "review");
20899
+ job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key2) => ctx.lock.entries[key2]?.status === "review");
20376
20900
  job.phase = "fetching";
20377
20901
  for (const [providerId, providerSpecs] of groupByRecordedProvider(specs, ctx.lock)) {
20378
20902
  const provider = opts.providerFor(job.project ?? void 0, providerId);
@@ -20457,7 +20981,7 @@ function createGenerateHandlers(opts) {
20457
20981
  job.finishedAt = null;
20458
20982
  const next = await opts.loadProject(job.project ?? void 0);
20459
20983
  const byKey = new Map(next.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
20460
- const nextSpecs = job.keys.map((key) => byKey.get(key)).filter((spec) => Boolean(spec));
20984
+ const nextSpecs = job.keys.map((key2) => byKey.get(key2)).filter((spec) => Boolean(spec));
20461
20985
  const plan = await buildPlan(nextSpecs, next.lock);
20462
20986
  if (!plan.actionable.length) return finish();
20463
20987
  for (const group of plan.groups) {
@@ -20524,21 +21048,21 @@ function createGenerateHandlers(opts) {
20524
21048
  const ctx = await opts.loadProject(request.project);
20525
21049
  const byKey = new Map(ctx.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
20526
21050
  const specs = [];
20527
- for (const key of request.keys) {
20528
- const spec = byKey.get(key);
20529
- if (!spec) throw new GenerateRequestError(`"${key}" is not declared by the manifest`);
21051
+ for (const key2 of request.keys) {
21052
+ const spec = byKey.get(key2);
21053
+ if (!spec) throw new GenerateRequestError(`"${key2}" is not declared by the manifest`);
20530
21054
  specs.push(spec);
20531
21055
  }
20532
21056
  const busy = busyKeys();
20533
- for (const key of request.keys) {
20534
- const holder = busy.get(`${request.project ?? ""}:${key}`);
20535
- if (holder) throw new GenerateRequestError(`"${key}" is already being worked on by job ${holder}`, 409);
21057
+ for (const key2 of request.keys) {
21058
+ const holder = busy.get(`${request.project ?? ""}:${key2}`);
21059
+ if (holder) throw new GenerateRequestError(`"${key2}" is already being worked on by job ${holder}`, 409);
20536
21060
  }
20537
21061
  if (request.restore) {
20538
- for (const key of request.keys) {
20539
- const entry = ctx.lock.entries[key];
21062
+ for (const key2 of request.keys) {
21063
+ const entry = ctx.lock.entries[key2];
20540
21064
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
20541
- throw new GenerateRequestError(`"${key}" has no downloaded output recorded to restore`);
21065
+ throw new GenerateRequestError(`"${key2}" has no downloaded output recorded to restore`);
20542
21066
  }
20543
21067
  }
20544
21068
  }
@@ -20632,19 +21156,19 @@ function createGenerateHandlers(opts) {
20632
21156
  }
20633
21157
 
20634
21158
  // src/pipeline/salvage.ts
20635
- import { readFile as readFile30 } from "fs/promises";
20636
- import { existsSync as existsSync32 } from "fs";
20637
- import path37 from "path";
21159
+ import { readFile as readFile31 } from "fs/promises";
21160
+ import { existsSync as existsSync35 } from "fs";
21161
+ import path40 from "path";
20638
21162
  function providerClaimId(provider, objectId) {
20639
21163
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
20640
21164
  }
20641
21165
  async function loadClaims(lockPaths, opts = {}) {
20642
21166
  const claimed = /* @__PURE__ */ new Set();
20643
21167
  for (const p of lockPaths) {
20644
- if (!existsSync32(p)) throw new Error(`Claim lockfile not found: ${p}`);
21168
+ if (!existsSync35(p)) throw new Error(`Claim lockfile not found: ${p}`);
20645
21169
  let parsed;
20646
21170
  try {
20647
- parsed = parseLock(JSON.parse(await readFile30(p, "utf8")));
21171
+ parsed = parseLock(JSON.parse(await readFile31(p, "utf8")));
20648
21172
  } catch {
20649
21173
  throw new Error(`Claim lockfile is malformed: ${p}`);
20650
21174
  }
@@ -20748,20 +21272,20 @@ function matchOrphanStyle(prompt, manifest) {
20748
21272
  return matchStyleByPattern(prompt, manifest);
20749
21273
  }
20750
21274
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
20751
- const own = path37.resolve(ownManifestPath);
21275
+ const own = path40.resolve(ownManifestPath);
20752
21276
  const siblingManifestPaths = [
20753
21277
  .../* @__PURE__ */ new Set([
20754
21278
  ...workspaceManifestPaths,
20755
- ...claimPaths.map((c) => path37.join(path37.dirname(path37.resolve(c)), "pixelkiln.manifest.json"))
21279
+ ...claimPaths.map((c) => path40.join(path40.dirname(path40.resolve(c)), "pixelkiln.manifest.json"))
20756
21280
  ])
20757
21281
  ];
20758
21282
  const siblings = [];
20759
21283
  for (const siblingManifestPath of siblingManifestPaths) {
20760
- if (path37.resolve(siblingManifestPath) === own) continue;
20761
- if (!existsSync32(siblingManifestPath)) continue;
21284
+ if (path40.resolve(siblingManifestPath) === own) continue;
21285
+ if (!existsSync35(siblingManifestPath)) continue;
20762
21286
  try {
20763
21287
  const { manifest } = await loadManifest(siblingManifestPath);
20764
- siblings.push({ label: path37.basename(path37.dirname(siblingManifestPath)), manifest });
21288
+ siblings.push({ label: path40.basename(path40.dirname(siblingManifestPath)), manifest });
20765
21289
  } catch {
20766
21290
  }
20767
21291
  }
@@ -20781,10 +21305,10 @@ function groupOrphansByStyle(orphans, manifest, siblings = []) {
20781
21305
  }
20782
21306
  const sibling = siblings.find((s) => matchStyleByPattern(o.prompt, s.manifest));
20783
21307
  if (sibling) {
20784
- const key = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
20785
- const list = elsewhere.get(key) ?? [];
21308
+ const key2 = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
21309
+ const list = elsewhere.get(key2) ?? [];
20786
21310
  list.push(o);
20787
- elsewhere.set(key, list);
21311
+ elsewhere.set(key2, list);
20788
21312
  continue;
20789
21313
  }
20790
21314
  if (ownStyleIds.length <= 1 && ownStyleIds[0]) matched.get(ownStyleIds[0]).push(o);
@@ -20881,8 +21405,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
20881
21405
  }
20882
21406
 
20883
21407
  // src/pick/salvage-server.ts
20884
- import { mkdir as mkdir13, writeFile as writeFile18, readFile as readFile31 } from "fs/promises";
20885
- import path38 from "path";
21408
+ import { mkdir as mkdir14, writeFile as writeFile19, readFile as readFile32 } from "fs/promises";
21409
+ import path41 from "path";
20886
21410
 
20887
21411
  // src/pick/salvage-sheet.ts
20888
21412
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -21048,7 +21572,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21048
21572
  });
21049
21573
  const html = renderSalvageSheet(orphans, {
21050
21574
  styleId: ctx.styleId,
21051
- importDir: path38.relative(process.cwd(), ctx.importDir) || "."
21575
+ importDir: path41.relative(process.cwd(), ctx.importDir) || "."
21052
21576
  });
21053
21577
  const byId = new Map(orphans.map((o) => [o.id, o]));
21054
21578
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -21104,10 +21628,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21104
21628
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
21105
21629
  decodePng(buf);
21106
21630
  const assetId = idFromPrompt(orphan.prompt, taken);
21107
- const rel = path38.join("_salvaged", `${assetId}.png`);
21108
- const outFile = path38.resolve(ctx.importDir, rel);
21109
- await mkdir13(path38.dirname(outFile), { recursive: true });
21110
- await writeFile18(outFile, buf);
21631
+ const rel = path41.join("_salvaged", `${assetId}.png`);
21632
+ const outFile = path41.resolve(ctx.importDir, rel);
21633
+ await mkdir14(path41.dirname(outFile), { recursive: true });
21634
+ await writeFile19(outFile, buf);
21111
21635
  ctx.manifest.assets[assetId] = {
21112
21636
  prompt: orphan.prompt,
21113
21637
  promptByStyle: {},
@@ -21139,7 +21663,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21139
21663
  sourceUrl: durableSource,
21140
21664
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
21141
21665
  outputs: [{
21142
- path: portableOutputPath(outFile, path38.dirname(ctx.manifestPath)),
21666
+ path: portableOutputPath(outFile, path41.dirname(ctx.manifestPath)),
21143
21667
  sha256: sha256(buf)
21144
21668
  }],
21145
21669
  submittedAt: orphan.createdAt,
@@ -21163,9 +21687,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21163
21687
  }
21164
21688
  }
21165
21689
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
21166
- const raw = JSON.parse(await readFile31(ctx.manifestPath, "utf8"));
21690
+ const raw = JSON.parse(await readFile32(ctx.manifestPath, "utf8"));
21167
21691
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
21168
- await writeFile18(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
21692
+ await writeFile19(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
21169
21693
  await saveLock(ctx.lockPath, ctx.lock);
21170
21694
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
21171
21695
  return result;
@@ -21274,6 +21798,8 @@ async function workspaceStatus(ws, dir) {
21274
21798
  }
21275
21799
  export {
21276
21800
  AssetBatchSchema,
21801
+ AssetDeriveSchema,
21802
+ AssetExternalSchema,
21277
21803
  AssetSchema,
21278
21804
  AssetVfxSchema,
21279
21805
  BudgetError,