pixelkiln 0.94.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.cjs CHANGED
@@ -11,9 +11,9 @@ var __export = (target, all) => {
11
11
  };
12
12
  var __copyProps = (to, from, except, desc) => {
13
13
  if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ for (let key2 of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
16
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
17
17
  }
18
18
  return to;
19
19
  };
@@ -31,6 +31,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  AssetBatchSchema: () => AssetBatchSchema,
34
+ AssetDeriveSchema: () => AssetDeriveSchema,
35
+ AssetExternalSchema: () => AssetExternalSchema,
34
36
  AssetSchema: () => AssetSchema,
35
37
  AssetVfxSchema: () => AssetVfxSchema,
36
38
  BudgetError: () => BudgetError,
@@ -674,12 +676,12 @@ var AssetVfxSchema = import_zod.z.object({
674
676
  artist: import_zod.z.enum(["lite", "pro"]).optional()
675
677
  }).strict().superRefine((vfx, context) => {
676
678
  if (vfx.description !== void 0) {
677
- for (const key of ["preset", "recipe", "parts", "fps"]) {
678
- if (vfx[key] !== void 0) {
679
+ for (const key2 of ["preset", "recipe", "parts", "fps"]) {
680
+ if (vfx[key2] !== void 0) {
679
681
  context.addIssue({
680
682
  code: import_zod.z.ZodIssueCode.custom,
681
- 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`,
682
- path: [key]
683
+ 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`,
684
+ path: [key2]
683
685
  });
684
686
  }
685
687
  }
@@ -798,18 +800,18 @@ var CharacterAnimationSchema = import_zod.z.object({
798
800
  context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: "a skeleton-v3 loop from a sentence takes 3 to 15 frames", path: ["frames"] });
799
801
  }
800
802
  const mode2 = animation.mode ?? (animation.template ? "template" : "v3");
801
- for (const key of ["startFrame", "endFrame", "enhancePrompt"]) {
802
- if (animation[key] !== void 0 && mode2 !== "v3") {
803
+ for (const key2 of ["startFrame", "endFrame", "enhancePrompt"]) {
804
+ if (animation[key2] !== void 0 && mode2 !== "v3") {
803
805
  context.addIssue({
804
806
  code: import_zod.z.ZodIssueCode.custom,
805
- 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"}`,
806
- path: [key]
807
+ 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"}`,
808
+ path: [key2]
807
809
  });
808
810
  }
809
811
  }
810
- for (const key of ["outline", "shading", "detail"]) {
811
- if (animation[key] !== void 0 && mode2 !== "template") {
812
- context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key} overrides apply to template loops only`, path: [key] });
812
+ for (const key2 of ["outline", "shading", "detail"]) {
813
+ if (animation[key2] !== void 0 && mode2 !== "template") {
814
+ context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: `${key2} overrides apply to template loops only`, path: [key2] });
813
815
  }
814
816
  }
815
817
  if (animation.template && animation.mode && animation.mode !== "template" && animation.mode !== "skeleton-v3") {
@@ -1498,6 +1500,46 @@ var InheritedStyleSchema = StyleObjectSchema.partial().extend({
1498
1500
  quality: QualityProfileObjectSchema.partial().optional()
1499
1501
  }).strict();
1500
1502
  var StyleInputSchema = import_zod.z.union([StyleSchema, InheritedStyleSchema]);
1503
+ var AssetDeriveSchema = import_zod.z.object({
1504
+ /** Another asset in the same style whose output is the input. */
1505
+ from: import_zod.z.string().min(1).optional(),
1506
+ /** A committed PNG, relative to the manifest, as the input. */
1507
+ file: import_zod.z.string().min(1).optional(),
1508
+ transform: import_zod.z.enum(["recolor", "palette-snap", "scale"]),
1509
+ /** recolor: exact replacements, `#rrggbb` to `#rrggbb`. Unmapped colors and every alpha value stay. */
1510
+ map: import_zod.z.record(HexColorSchema, HexColorSchema).optional(),
1511
+ /** palette-snap: the closed palette every visible pixel moves to. */
1512
+ palette: import_zod.z.array(HexColorSchema).min(2).max(256).optional(),
1513
+ /** scale: the output size. */
1514
+ width: import_zod.z.number().int().min(1).max(4096).optional(),
1515
+ height: import_zod.z.number().int().min(1).max(4096).optional(),
1516
+ /** scale: `nearest` (default) keeps hard edges; `box` averages the covered pixels. */
1517
+ mode: import_zod.z.enum(["nearest", "box"]).optional()
1518
+ }).strict().superRefine((derive, context) => {
1519
+ const issue = (message6, path42) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path42] });
1520
+ if (Boolean(derive.from) === Boolean(derive.file)) {
1521
+ issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1522
+ }
1523
+ const own = {
1524
+ recolor: ["map"],
1525
+ "palette-snap": ["palette"],
1526
+ scale: ["width", "height", "mode"]
1527
+ }[derive.transform];
1528
+ for (const field of ["map", "palette", "width", "height", "mode"]) {
1529
+ if (derive[field] !== void 0 && !own.includes(field)) {
1530
+ issue(`${field} does not apply to ${derive.transform}`, field);
1531
+ }
1532
+ }
1533
+ if (derive.transform === "recolor" && !Object.keys(derive.map ?? {}).length) issue("recolor needs a non-empty map", "map");
1534
+ if (derive.transform === "palette-snap" && !derive.palette) issue("palette-snap needs a palette", "palette");
1535
+ if (derive.transform === "scale" && (!derive.width || !derive.height)) issue("scale needs width and height", "width");
1536
+ });
1537
+ var AssetExternalSchema = import_zod.z.object({
1538
+ /** The command that rebuilds the file. Documentation and identity; never executed. */
1539
+ builder: import_zod.z.string().min(1),
1540
+ /** Files the builder reads, relative to the manifest. Their hashes are part of the asset's identity. */
1541
+ inputs: import_zod.z.array(import_zod.z.string().min(1)).optional()
1542
+ }).strict();
1501
1543
  var AssetSchema = import_zod.z.object({
1502
1544
  /** The subject. Style wrapping comes from the style's prefix/suffix. Only a `mirror` may leave it out. */
1503
1545
  prompt: import_zod.z.string().optional(),
@@ -1629,6 +1671,10 @@ var AssetSchema = import_zod.z.object({
1629
1671
  * (a sword hand, a parted fringe) comes out the other way round.
1630
1672
  */
1631
1673
  mirror: import_zod.z.string().min(1).optional(),
1674
+ /** Made from existing pixels by a local transform; see AssetDeriveSchema. Free; the provider is never called. */
1675
+ derive: AssetDeriveSchema.optional(),
1676
+ /** Built by a tool outside pixelkiln; see AssetExternalSchema. Never generated. */
1677
+ external: AssetExternalSchema.optional(),
1632
1678
  /**
1633
1679
  * Generated output role to place in `cell` when this asset expands to
1634
1680
  * several files. Omit for ordinary single-output assets. A structural set
@@ -1668,7 +1714,7 @@ var AssetSchema = import_zod.z.object({
1668
1714
  path: ["revision"]
1669
1715
  });
1670
1716
  }
1671
- 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);
1717
+ 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);
1672
1718
  if (shapes.length > 1) {
1673
1719
  context.addIssue({
1674
1720
  code: import_zod.z.ZodIssueCode.custom,
@@ -1676,6 +1722,15 @@ var AssetSchema = import_zod.z.object({
1676
1722
  path: [shapes[1]]
1677
1723
  });
1678
1724
  }
1725
+ for (const shape of ["derive", "external"]) {
1726
+ if (asset[shape] && (asset.source || Object.keys(asset.sourceByStyle).length)) {
1727
+ context.addIssue({
1728
+ code: import_zod.z.ZodIssueCode.custom,
1729
+ 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",
1730
+ path: [shape]
1731
+ });
1732
+ }
1733
+ }
1679
1734
  if (asset.mirror && (asset.source || Object.keys(asset.sourceByStyle).length)) {
1680
1735
  context.addIssue({
1681
1736
  code: import_zod.z.ZodIssueCode.custom,
@@ -1683,13 +1738,20 @@ var AssetSchema = import_zod.z.object({
1683
1738
  path: ["mirror"]
1684
1739
  });
1685
1740
  }
1686
- if (asset.prompt === void 0 && !asset.mirror && !asset.portrait && !asset.outfit && !asset.animation?.template && !asset.vfx) {
1741
+ if (asset.prompt === void 0 && !asset.mirror && !asset.derive && !asset.external && !asset.portrait && !asset.outfit && !asset.animation?.template && !asset.vfx) {
1687
1742
  context.addIssue({
1688
1743
  code: import_zod.z.ZodIssueCode.custom,
1689
1744
  message: "Required",
1690
1745
  path: ["prompt"]
1691
1746
  });
1692
1747
  }
1748
+ if ((asset.derive || asset.external) && (asset.reference || asset.concept)) {
1749
+ context.addIssue({
1750
+ code: import_zod.z.ZodIssueCode.custom,
1751
+ message: "a derived or external asset is not drawn by a provider, so it takes no reference or concept image",
1752
+ path: [asset.reference ? "reference" : "concept"]
1753
+ });
1754
+ }
1693
1755
  if (asset.reference && (asset.state || asset.animation || asset.mirror || asset.portrait || asset.outfit)) {
1694
1756
  context.addIssue({
1695
1757
  code: import_zod.z.ZodIssueCode.custom,
@@ -1981,6 +2043,24 @@ var LockEntrySchema = import_zod.z.object({
1981
2043
  source: import_zod.z.string().min(1),
1982
2044
  note: import_zod.z.string().optional(),
1983
2045
  importedAt: import_zod.z.string()
2046
+ }).strict().optional(),
2047
+ /**
2048
+ * For a derived asset: what it was made from, and a hash of that input when
2049
+ * this was made. Compared with the input's current bytes by the plan, so a
2050
+ * changed source re-derives it for free. Absent on every other entry.
2051
+ */
2052
+ derive: import_zod.z.object({
2053
+ sourceAssetId: import_zod.z.string().min(1).optional(),
2054
+ sourceFile: import_zod.z.string().min(1).optional(),
2055
+ sourceSha256: import_zod.z.string().regex(/^[0-9a-f]{64}$/)
2056
+ }).strict().optional(),
2057
+ /**
2058
+ * For an external asset: the builder command and the hashes of the declared
2059
+ * inputs when the file was recorded. Absent on every other entry.
2060
+ */
2061
+ external: import_zod.z.object({
2062
+ builder: import_zod.z.string().min(1),
2063
+ inputs: import_zod.z.array(import_zod.z.object({ path: import_zod.z.string(), sha256: import_zod.z.string().nullable() }).strict()).default([])
1984
2064
  }).strict().optional()
1985
2065
  });
1986
2066
  var LockSchema = import_zod.z.object({
@@ -2530,9 +2610,9 @@ var PixelLabClient = class {
2530
2610
  apiKey;
2531
2611
  http;
2532
2612
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
2533
- async request(path40, init) {
2613
+ async request(path42, init) {
2534
2614
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
2535
- const res = await this.http(`${BASE}${path40}`, {
2615
+ const res = await this.http(`${BASE}${path42}`, {
2536
2616
  ...init,
2537
2617
  headers: {
2538
2618
  Authorization: auth,
@@ -2543,13 +2623,13 @@ var PixelLabClient = class {
2543
2623
  const text = await res.text();
2544
2624
  if (!res.ok) {
2545
2625
  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' : "";
2546
- throw new PixelLabError(`${init?.method ?? "GET"} ${path40} \u2192 ${res.status}${hint}`, res.status, text);
2626
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path42} \u2192 ${res.status}${hint}`, res.status, text);
2547
2627
  }
2548
2628
  if (!text) return {};
2549
2629
  try {
2550
2630
  return JSON.parse(text);
2551
2631
  } catch {
2552
- throw new Error(`${init?.method ?? "GET"} ${path40} returned invalid JSON`);
2632
+ throw new Error(`${init?.method ?? "GET"} ${path42} returned invalid JSON`);
2553
2633
  }
2554
2634
  }
2555
2635
  async balance() {
@@ -3002,10 +3082,10 @@ var PixelLabClient = class {
3002
3082
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
3003
3083
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
3004
3084
  const south = args.reference?.south;
3005
- let path40;
3085
+ let path42;
3006
3086
  let body;
3007
3087
  if (args.mode === "v3") {
3008
- path40 = "/create-character-v3";
3088
+ path42 = "/create-character-v3";
3009
3089
  body = {
3010
3090
  description: args.description,
3011
3091
  image_size: imageSize,
@@ -3019,7 +3099,7 @@ var PixelLabClient = class {
3019
3099
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
3020
3100
  };
3021
3101
  } else if (args.mode === "pro-flash") {
3022
- path40 = "/create-character-pro-flash";
3102
+ path42 = "/create-character-pro-flash";
3023
3103
  const traits = args.styleTraits;
3024
3104
  body = {
3025
3105
  description: args.description,
@@ -3043,7 +3123,7 @@ var PixelLabClient = class {
3043
3123
  } : {}
3044
3124
  };
3045
3125
  } else if (args.mode === "pro") {
3046
- path40 = "/create-character-pro";
3126
+ path42 = "/create-character-pro";
3047
3127
  body = {
3048
3128
  description: args.description,
3049
3129
  image_size: imageSize,
@@ -3057,7 +3137,7 @@ var PixelLabClient = class {
3057
3137
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
3058
3138
  };
3059
3139
  } else {
3060
- path40 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3140
+ path42 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3061
3141
  body = {
3062
3142
  description: args.description,
3063
3143
  image_size: imageSize,
@@ -3075,8 +3155,8 @@ var PixelLabClient = class {
3075
3155
  };
3076
3156
  }
3077
3157
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
3078
- const raw = await this.request(path40, { method: "POST", body: JSON.stringify(body) });
3079
- return validateResponse(CharacterSubmitSchema, raw, path40.slice(1));
3158
+ const raw = await this.request(path42, { method: "POST", body: JSON.stringify(body) });
3159
+ return validateResponse(CharacterSubmitSchema, raw, path42.slice(1));
3080
3160
  }
3081
3161
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
3082
3162
  async createCharacterState(args) {
@@ -3805,13 +3885,13 @@ var PixelLabClient = class {
3805
3885
  }
3806
3886
  };
3807
3887
  function clientFromEnv() {
3808
- const key = process.env.PIXELLAB_API_KEY;
3809
- if (!key) {
3888
+ const key2 = process.env.PIXELLAB_API_KEY;
3889
+ if (!key2) {
3810
3890
  throw new Error(
3811
3891
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
3812
3892
  );
3813
3893
  }
3814
- return new PixelLabClient(key);
3894
+ return new PixelLabClient(key2);
3815
3895
  }
3816
3896
 
3817
3897
  // src/open.ts
@@ -4151,14 +4231,14 @@ function extractPalette(png, topN = 8, alphaThreshold = 128) {
4151
4231
  const alpha = png.pixels[i + 3];
4152
4232
  if (alpha < alphaThreshold) continue;
4153
4233
  opaque++;
4154
- const key = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
4155
- counts.set(key, (counts.get(key) ?? 0) + 1);
4234
+ const key2 = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
4235
+ counts.set(key2, (counts.get(key2) ?? 0) + 1);
4156
4236
  }
4157
4237
  if (opaque === 0) return [];
4158
- return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key, n]) => ({
4159
- r: key >> 16 & 255,
4160
- g: key >> 8 & 255,
4161
- b: key & 255,
4238
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key2, n]) => ({
4239
+ r: key2 >> 16 & 255,
4240
+ g: key2 >> 8 & 255,
4241
+ b: key2 & 255,
4162
4242
  weight: n / opaque
4163
4243
  }));
4164
4244
  }
@@ -4410,13 +4490,17 @@ var import_node_path3 = __toESM(require("path"), 1);
4410
4490
  // src/hash.ts
4411
4491
  var import_node_crypto = require("crypto");
4412
4492
  var import_node_fs = require("fs");
4493
+ function normalizeHex(value) {
4494
+ const { r, g, b } = parseHex(value);
4495
+ return `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
4496
+ }
4413
4497
  function sha256(data) {
4414
4498
  return (0, import_node_crypto.createHash)("sha256").update(data).digest("hex");
4415
4499
  }
4416
- async function sha256File(path40) {
4500
+ async function sha256File(path42) {
4417
4501
  return new Promise((resolve, reject) => {
4418
4502
  const hash = (0, import_node_crypto.createHash)("sha256");
4419
- const stream = (0, import_node_fs.createReadStream)(path40);
4503
+ const stream = (0, import_node_fs.createReadStream)(path42);
4420
4504
  stream.on("data", (chunk2) => hash.update(chunk2));
4421
4505
  stream.on("error", reject);
4422
4506
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -4558,6 +4642,22 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
4558
4642
  // A mirror's bytes come from its source's recorded outputs; the plan
4559
4643
  // compares those directly, so only the choice of source is identity.
4560
4644
  mirror: spec.mirror ? { of: spec.mirror.sourceAssetId } : void 0,
4645
+ // A derived asset's identity is its transform and what it reads: the
4646
+ // file source by its bytes' hash, an asset source by id (the plan
4647
+ // compares that asset's current output with the one recorded).
4648
+ derive: spec.derive ? {
4649
+ transform: spec.derive.transform,
4650
+ map: spec.derive.map ? Object.entries(spec.derive.map).map(([from, to]) => [normalizeHex(from), normalizeHex(to)]).sort(([a], [b]) => a.localeCompare(b)) : void 0,
4651
+ palette: spec.derive.palette?.map(normalizeHex),
4652
+ width: spec.derive.width,
4653
+ height: spec.derive.height,
4654
+ mode: spec.derive.transform === "scale" ? spec.derive.mode ?? "nearest" : void 0,
4655
+ from: spec.derive.source.kind === "asset" ? spec.derive.source.assetId : void 0,
4656
+ fileSha256: spec.derive.source.kind === "file" ? spec.derive.source.sha256 : void 0
4657
+ } : void 0,
4658
+ // An external asset: the builder text and each declared input's path
4659
+ // and bytes. The built file itself is checked by the plan.
4660
+ external: spec.external ? { builder: spec.external.builder, inputs: spec.external.inputs.length ? spec.external.inputs : void 0 } : void 0,
4561
4661
  // The whole group's ordered descriptions, not just this asset's own —
4562
4662
  // any sibling's prompt changing, or a member being added or removed,
4563
4663
  // must mark every member stale together, since they all ride on one
@@ -4685,13 +4785,13 @@ var PixelLabMcpClient = class {
4685
4785
  }
4686
4786
  };
4687
4787
  function mcpClientFromEnv() {
4688
- const key = process.env.PIXELLAB_API_KEY;
4689
- if (!key) {
4788
+ const key2 = process.env.PIXELLAB_API_KEY;
4789
+ if (!key2) {
4690
4790
  throw new Error(
4691
4791
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
4692
4792
  );
4693
4793
  }
4694
- return new PixelLabMcpClient(key);
4794
+ return new PixelLabMcpClient(key2);
4695
4795
  }
4696
4796
 
4697
4797
  // src/pixellab-vfx.ts
@@ -4975,27 +5075,27 @@ function vfxArtistFiles(raw) {
4975
5075
  const urlOf = (value) => {
4976
5076
  if (typeof value === "string") return /^https?:\/\//i.test(value) ? value : null;
4977
5077
  if (!value || typeof value !== "object") return null;
4978
- for (const key of ["url", "download_url", "href"]) {
4979
- const url = value[key];
5078
+ for (const key2 of ["url", "download_url", "href"]) {
5079
+ const url = value[key2];
4980
5080
  if (typeof url === "string" && /^https?:\/\//i.test(url)) return url;
4981
5081
  }
4982
5082
  return null;
4983
5083
  };
4984
- const nameOf = (value, url, key) => {
5084
+ const nameOf = (value, url, key2) => {
4985
5085
  if (value && typeof value === "object") {
4986
5086
  for (const field of ["name", "filename", "file"]) {
4987
5087
  const name = value[field];
4988
5088
  if (typeof name === "string" && name) return name;
4989
5089
  }
4990
5090
  }
4991
- if (key && /\.[a-z0-9]+$/i.test(key)) return key;
5091
+ if (key2 && /\.[a-z0-9]+$/i.test(key2)) return key2;
4992
5092
  return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
4993
5093
  };
4994
5094
  const entries = Array.isArray(raw) ? raw.map((value) => [void 0, value]) : raw && typeof raw === "object" ? Object.entries(raw) : [];
4995
5095
  const files = [];
4996
- for (const [key, value] of entries) {
5096
+ for (const [key2, value] of entries) {
4997
5097
  const url = urlOf(value);
4998
- if (url) files.push({ name: nameOf(value, url, key), url });
5098
+ if (url) files.push({ name: nameOf(value, url, key2), url });
4999
5099
  }
5000
5100
  return files;
5001
5101
  }
@@ -5096,14 +5196,14 @@ async function makeVfxWithArtist(client2, opts) {
5096
5196
  `);
5097
5197
  written.atlas = paths.atlas;
5098
5198
  }
5099
- for (const [file, target, key] of [
5199
+ for (const [file, target, key2] of [
5100
5200
  [result.gif, paths.gif, "gif"],
5101
5201
  [result.gamePack, paths.gamePack, "gamePack"],
5102
5202
  [result.normals, paths.normals, "normals"]
5103
5203
  ]) {
5104
5204
  if (!file) continue;
5105
5205
  await (0, import_promises.writeFile)(target, await client2.download(file.url));
5106
- written[key] = target;
5206
+ written[key2] = target;
5107
5207
  }
5108
5208
  const facts = vfxArtistFrameFacts(result, atlas);
5109
5209
  const usage = job.usage ?? null;
@@ -5127,7 +5227,7 @@ async function makeVfxWithArtist(client2, opts) {
5127
5227
  anchor: result.anchor,
5128
5228
  parts: result.parts,
5129
5229
  files: Object.fromEntries(
5130
- ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key) => written[key]).map((key) => [key, import_node_path.default.basename(written[key])])
5230
+ ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key2) => written[key2]).map((key2) => [key2, import_node_path.default.basename(written[key2])])
5131
5231
  ),
5132
5232
  quotedGenerations: submitted.quoted_generations ?? null,
5133
5233
  usage,
@@ -5152,8 +5252,8 @@ async function makeVfxWithArtist(client2, opts) {
5152
5252
  };
5153
5253
  }
5154
5254
  function vfxJobFailure(done) {
5155
- for (const key of ["error", "detail", "message"]) {
5156
- const value = done?.[key];
5255
+ for (const key2 of ["error", "detail", "message"]) {
5256
+ const value = done?.[key2];
5157
5257
  if (typeof value === "string" && value) return `: ${value}`;
5158
5258
  }
5159
5259
  return "";
@@ -5188,8 +5288,8 @@ function isSensitiveSourceUrl(value) {
5188
5288
  return false;
5189
5289
  }
5190
5290
  if (parsed.username || parsed.password) return true;
5191
- for (const key of parsed.searchParams.keys()) {
5192
- const normalized = key.toLowerCase();
5291
+ for (const key2 of parsed.searchParams.keys()) {
5292
+ const normalized = key2.toLowerCase();
5193
5293
  if (SENSITIVE_QUERY_KEYS.has(normalized) || normalized.includes("credential") || normalized.includes("signature") || normalized.includes("security-token") || normalized.includes("token")) return true;
5194
5294
  }
5195
5295
  return false;
@@ -7584,8 +7684,8 @@ var PixelLabProvider = class _PixelLabProvider {
7584
7684
  billed
7585
7685
  };
7586
7686
  };
7587
- for (const key of ["frame_urls", "frames", "images"]) {
7588
- const list = done[key];
7687
+ for (const key2 of ["frame_urls", "frames", "images"]) {
7688
+ const list = done[key2];
7589
7689
  if (!Array.isArray(list) || !list.length) continue;
7590
7690
  const urls = [];
7591
7691
  for (const [index, item] of list.entries()) {
@@ -7640,15 +7740,15 @@ var PixelLabProvider = class _PixelLabProvider {
7640
7740
  const billed = billedFromUsage(job.usage);
7641
7741
  const done = job.last_response ?? {};
7642
7742
  const urlKeys = ["image_url", "download_url", "url", "output_url"];
7643
- for (const key of urlKeys) {
7644
- const url = done[key];
7743
+ for (const key2 of urlKeys) {
7744
+ const url = done[key2];
7645
7745
  if (typeof url === "string" && url) {
7646
7746
  return { status: "ready", objectId: jobId, sourceUrl: url, sources: [{ url }], billed };
7647
7747
  }
7648
7748
  }
7649
7749
  const imageKeys = ["image", "output_image", "result_image", "edited_image"];
7650
- for (const key of imageKeys) {
7651
- const candidate = done[key];
7750
+ for (const key2 of imageKeys) {
7751
+ const candidate = done[key2];
7652
7752
  const base64 = extractBase64(candidate);
7653
7753
  if (base64) {
7654
7754
  const file = import_node_path3.default.join(_PixelLabProvider.cacheDir(), `${jobId}.png`);
@@ -8073,7 +8173,7 @@ function requirePixelLabOption(generator, name, value, allowed) {
8073
8173
  }
8074
8174
  }
8075
8175
  function tilesInIndexOrder(urls) {
8076
- 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);
8176
+ 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);
8077
8177
  }
8078
8178
  function firstUrl(urls) {
8079
8179
  if (!urls) return null;
@@ -8235,9 +8335,9 @@ var RetroDiffusionClient = class {
8235
8335
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
8236
8336
  return Buffer.from(await response.arrayBuffer());
8237
8337
  }
8238
- async call(path40, init = {}) {
8338
+ async call(path42, init = {}) {
8239
8339
  if (!this.token) throw new Error("RD_API_KEY is not set");
8240
- const response = await this.request(`${this.baseUrl}${path40}`, {
8340
+ const response = await this.request(`${this.baseUrl}${path42}`, {
8241
8341
  ...init,
8242
8342
  headers: {
8243
8343
  "Content-Type": "application/json",
@@ -8706,8 +8806,8 @@ var ScenarioClient = class {
8706
8806
  throw new Error(`${missing.join(" and ")} ${missing.length > 1 ? "are" : "is"} not set`);
8707
8807
  }
8708
8808
  const url = new URL(`${this.baseUrl.replace(/\/$/, "")}${pathname}`);
8709
- for (const [key, value2] of Object.entries(query)) {
8710
- if (value2 != null) url.searchParams.set(key, value2);
8809
+ for (const [key2, value2] of Object.entries(query)) {
8810
+ if (value2 != null) url.searchParams.set(key2, value2);
8711
8811
  }
8712
8812
  const auth = Buffer.from(`${this.apiKey}:${this.apiSecret}`).toString("base64");
8713
8813
  const response = await this.request(url, {
@@ -8947,12 +9047,12 @@ function readUploadCache() {
8947
9047
  return {};
8948
9048
  }
8949
9049
  }
8950
- function writeUploadCache(key, assetId) {
9050
+ function writeUploadCache(key2, assetId) {
8951
9051
  try {
8952
9052
  const file = uploadCachePath();
8953
9053
  (0, import_node_fs5.mkdirSync)(import_node_path4.default.dirname(file), { recursive: true });
8954
9054
  const tmp = `${file}.${process.pid}.tmp`;
8955
- (0, import_node_fs5.writeFileSync)(tmp, JSON.stringify({ ...readUploadCache(), [key]: assetId }));
9055
+ (0, import_node_fs5.writeFileSync)(tmp, JSON.stringify({ ...readUploadCache(), [key2]: assetId }));
8956
9056
  (0, import_node_fs5.renameSync)(tmp, file);
8957
9057
  } catch {
8958
9058
  }
@@ -9002,9 +9102,9 @@ function validateParameters(parameters) {
9002
9102
  if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
9003
9103
  throw new Error("Scenario parameters must be a JSON object");
9004
9104
  }
9005
- for (const key of Object.keys(parameters)) {
9006
- if (PROTECTED_PARAMETERS.has(key)) {
9007
- throw new Error(`Scenario parameters.${key} is managed by PixelKiln and cannot be overridden`);
9105
+ for (const key2 of Object.keys(parameters)) {
9106
+ if (PROTECTED_PARAMETERS.has(key2)) {
9107
+ throw new Error(`Scenario parameters.${key2} is managed by PixelKiln and cannot be overridden`);
9008
9108
  }
9009
9109
  }
9010
9110
  assertJsonValue(parameters, "Scenario parameters");
@@ -9027,8 +9127,8 @@ function assertJsonValue(value, label, seen = /* @__PURE__ */ new Set()) {
9027
9127
  if (Array.isArray(value)) {
9028
9128
  value.forEach((item, index) => assertJsonValue(item, `${label}[${index}]`, seen));
9029
9129
  } else {
9030
- for (const [key, item] of Object.entries(value)) {
9031
- assertJsonValue(item, `${label}.${key}`, seen);
9130
+ for (const [key2, item] of Object.entries(value)) {
9131
+ assertJsonValue(item, `${label}.${key2}`, seen);
9032
9132
  }
9033
9133
  }
9034
9134
  seen.delete(value);
@@ -9129,8 +9229,8 @@ function numericRecord(value) {
9129
9229
  throw new Error("Scenario returned invalid cost details");
9130
9230
  }
9131
9231
  const out = {};
9132
- for (const [key, amount] of Object.entries(value)) {
9133
- out[key] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key}"`);
9232
+ for (const [key2, amount] of Object.entries(value)) {
9233
+ out[key2] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key2}"`);
9134
9234
  }
9135
9235
  return out;
9136
9236
  }
@@ -9736,7 +9836,7 @@ function parseOptions(value) {
9736
9836
  "workflow",
9737
9837
  "workflowSha256"
9738
9838
  ]);
9739
- const extra = Object.keys(value).filter((key) => !allowed.has(key));
9839
+ const extra = Object.keys(value).filter((key2) => !allowed.has(key2));
9740
9840
  if (extra.length) throw new Error(`Unknown ComfyUI option(s): ${extra.join(", ")}`);
9741
9841
  const workflowFile = requiredString(value.workflowFile, "workflowFile");
9742
9842
  const outputNodeId = requiredString(value.outputNodeId, "outputNodeId");
@@ -9772,7 +9872,7 @@ function parseOptions(value) {
9772
9872
  }
9773
9873
  function parseFrames(value) {
9774
9874
  if (!isObject(value)) throw new Error("ComfyUI frames must be an object");
9775
- const extra = Object.keys(value).filter((key) => key !== "vary" && key !== "seedStep");
9875
+ const extra = Object.keys(value).filter((key2) => key2 !== "vary" && key2 !== "seedStep");
9776
9876
  if (extra.length) throw new Error(`Unknown ComfyUI frames field(s): ${extra.join(", ")}`);
9777
9877
  const vary = requiredString(value.vary, "frames.vary");
9778
9878
  const seedStep = value.seedStep ?? 0;
@@ -9790,7 +9890,7 @@ function resolvedOptions(spec) {
9790
9890
  }
9791
9891
  function parseBinding(value, name) {
9792
9892
  if (!isObject(value)) throw new Error(`ComfyUI bindings.${name} must be an object`);
9793
- const extra = Object.keys(value).filter((key) => key !== "nodeId" && key !== "input");
9893
+ const extra = Object.keys(value).filter((key2) => key2 !== "nodeId" && key2 !== "input");
9794
9894
  if (extra.length) throw new Error(`Unknown ComfyUI bindings.${name} field(s): ${extra.join(", ")}`);
9795
9895
  return {
9796
9896
  nodeId: requiredString(value.nodeId, `bindings.${name}.nodeId`),
@@ -10055,7 +10155,7 @@ function canonical(value) {
10055
10155
  if (Array.isArray(value)) return value.map(canonical);
10056
10156
  if (!isObject(value)) return value;
10057
10157
  return Object.fromEntries(
10058
- Object.keys(value).sort().map((key) => [key, canonical(value[key])])
10158
+ Object.keys(value).sort().map((key2) => [key2, canonical(value[key2])])
10059
10159
  );
10060
10160
  }
10061
10161
 
@@ -10464,22 +10564,22 @@ async function writeLockWhileHeld(file, lock) {
10464
10564
  }
10465
10565
  const dirty = dirtyPatches.get(lock) ?? /* @__PURE__ */ new Map();
10466
10566
  const snapshot = /* @__PURE__ */ new Map();
10467
- for (const [key, patch] of dirty) snapshot.set(key, { ...patch });
10567
+ for (const [key2, patch] of dirty) snapshot.set(key2, { ...patch });
10468
10568
  const merged = { ...disk.entries };
10469
- for (const [key, patch] of snapshot) {
10470
- const local = lock.entries[key];
10569
+ for (const [key2, patch] of snapshot) {
10570
+ const local = lock.entries[key2];
10471
10571
  if (!local) continue;
10472
- merged[key] = merged[key] ? { ...merged[key], ...patch } : local;
10572
+ merged[key2] = merged[key2] ? { ...merged[key2], ...patch } : local;
10473
10573
  }
10474
- for (const [key, entry] of Object.entries(lock.entries)) {
10475
- if (!merged[key]) merged[key] = entry;
10574
+ for (const [key2, entry] of Object.entries(lock.entries)) {
10575
+ if (!merged[key2]) merged[key2] = entry;
10476
10576
  }
10477
10577
  const deletes = dirtyDeletes.get(lock);
10478
10578
  const deleteSnapshot = deletes ? new Set(deletes) : /* @__PURE__ */ new Set();
10479
- for (const key of deleteSnapshot) delete merged[key];
10579
+ for (const key2 of deleteSnapshot) delete merged[key2];
10480
10580
  const sorted = {};
10481
- for (const key of Object.keys(merged).sort()) {
10482
- sorted[key] = merged[key];
10581
+ for (const key2 of Object.keys(merged).sort()) {
10582
+ sorted[key2] = merged[key2];
10483
10583
  }
10484
10584
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
10485
10585
  try {
@@ -10490,48 +10590,48 @@ async function writeLockWhileHeld(file, lock) {
10490
10590
  }
10491
10591
  const currentDirty = dirtyPatches.get(lock);
10492
10592
  if (currentDirty) {
10493
- for (const [key, patch] of snapshot) {
10494
- const current = currentDirty.get(key);
10593
+ for (const [key2, patch] of snapshot) {
10594
+ const current = currentDirty.get(key2);
10495
10595
  if (!current) continue;
10496
10596
  for (const [field, value] of Object.entries(patch)) {
10497
10597
  if (Object.is(current[field], value)) {
10498
10598
  delete current[field];
10499
10599
  }
10500
10600
  }
10501
- if (Object.keys(current).length === 0) currentDirty.delete(key);
10601
+ if (Object.keys(current).length === 0) currentDirty.delete(key2);
10502
10602
  }
10503
10603
  }
10504
10604
  const stillDirty = dirtyDeletes.get(lock);
10505
10605
  if (stillDirty) {
10506
- for (const key of deleteSnapshot) stillDirty.delete(key);
10606
+ for (const key2 of deleteSnapshot) stillDirty.delete(key2);
10507
10607
  if (stillDirty.size === 0) dirtyDeletes.delete(lock);
10508
10608
  }
10509
10609
  const localAfterWrite = lock.entries;
10510
10610
  lock.entries = { ...merged };
10511
- for (const [key, patch] of currentDirty ?? []) {
10512
- const base = lock.entries[key] ?? localAfterWrite[key];
10513
- if (base) lock.entries[key] = { ...base, ...patch };
10611
+ for (const [key2, patch] of currentDirty ?? []) {
10612
+ const base = lock.entries[key2] ?? localAfterWrite[key2];
10613
+ if (base) lock.entries[key2] = { ...base, ...patch };
10514
10614
  }
10515
10615
  }
10516
- function upsert(lock, key, patch) {
10517
- dirtyDeletes.get(lock)?.delete(key);
10518
- const existing = lock.entries[key];
10616
+ function upsert(lock, key2, patch) {
10617
+ dirtyDeletes.get(lock)?.delete(key2);
10618
+ const existing = lock.entries[key2];
10519
10619
  const next = { ...existing, ...patch };
10520
- lock.entries[key] = next;
10620
+ lock.entries[key2] = next;
10521
10621
  let dirty = dirtyPatches.get(lock);
10522
10622
  if (!dirty) {
10523
10623
  dirty = /* @__PURE__ */ new Map();
10524
10624
  dirtyPatches.set(lock, dirty);
10525
10625
  }
10526
- dirty.set(key, { ...dirty.get(key) ?? {}, ...patch });
10626
+ dirty.set(key2, { ...dirty.get(key2) ?? {}, ...patch });
10527
10627
  return next;
10528
10628
  }
10529
- function remove(lock, key) {
10530
- if (!lock.entries[key]) return false;
10531
- delete lock.entries[key];
10629
+ function remove(lock, key2) {
10630
+ if (!lock.entries[key2]) return false;
10631
+ delete lock.entries[key2];
10532
10632
  const patches = dirtyPatches.get(lock);
10533
10633
  if (patches) {
10534
- patches.delete(key);
10634
+ patches.delete(key2);
10535
10635
  if (patches.size === 0) dirtyPatches.delete(lock);
10536
10636
  }
10537
10637
  let deletes = dirtyDeletes.get(lock);
@@ -10539,7 +10639,7 @@ function remove(lock, key) {
10539
10639
  deletes = /* @__PURE__ */ new Set();
10540
10640
  dirtyDeletes.set(lock, deletes);
10541
10641
  }
10542
- deletes.add(key);
10642
+ deletes.add(key2);
10543
10643
  return true;
10544
10644
  }
10545
10645
  var FILE_LOCK_TIMEOUT_MS = 1e4;
@@ -10637,8 +10737,8 @@ function currentEntryOutputPath(entry, spec, index) {
10637
10737
  function normalizeLockOutputPaths(lock, specs) {
10638
10738
  const byKey = new Map(specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
10639
10739
  let changed = 0;
10640
- for (const [key, entry] of Object.entries(lock.entries)) {
10641
- const spec = byKey.get(key);
10740
+ for (const [key2, entry] of Object.entries(lock.entries)) {
10741
+ const spec = byKey.get(key2);
10642
10742
  if (!spec) continue;
10643
10743
  let entryChanged = false;
10644
10744
  const outputs = entry.outputs.map((output, index) => {
@@ -10649,7 +10749,7 @@ function normalizeLockOutputPaths(lock, specs) {
10649
10749
  entryChanged = true;
10650
10750
  return { ...output, path: portable };
10651
10751
  });
10652
- if (entryChanged) upsert(lock, key, { outputs });
10752
+ if (entryChanged) upsert(lock, key2, { outputs });
10653
10753
  }
10654
10754
  return changed;
10655
10755
  }
@@ -10680,8 +10780,8 @@ function resolveSpecEntryOutputs(entry, spec) {
10680
10780
  }
10681
10781
  function resolveStyleOutputs(lock, styleId, manifestDir) {
10682
10782
  const prefix = `${styleId}/`;
10683
- return Object.entries(lock.entries).filter(([key]) => key.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
10684
- ([key, entry]) => resolveEntryOutputs(entry, key.slice(prefix.length), manifestDir)
10783
+ return Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
10784
+ ([key2, entry]) => resolveEntryOutputs(entry, key2.slice(prefix.length), manifestDir)
10685
10785
  );
10686
10786
  }
10687
10787
  function selectEntryOutput(entry, role) {
@@ -10804,10 +10904,10 @@ function culpritEntries(message6) {
10804
10904
  const match = /^ {2}(assets|styles)\.([^.:\s]+)[.:]/.exec(line);
10805
10905
  if (!match) continue;
10806
10906
  const kind = match[1] === "styles" ? "style" : "asset";
10807
- const key = `${kind}:${match[2]}`;
10808
- const entry = found.get(key) ?? { kind, id: match[2], issues: [] };
10907
+ const key2 = `${kind}:${match[2]}`;
10908
+ const entry = found.get(key2) ?? { kind, id: match[2], issues: [] };
10809
10909
  entry.issues.push(line.trim());
10810
- found.set(key, entry);
10910
+ found.set(key2, entry);
10811
10911
  }
10812
10912
  return [...found.values()];
10813
10913
  }
@@ -10953,6 +11053,7 @@ function dependencyAssetIds(asset, styleAnchors = []) {
10953
11053
  asset?.connect?.upper?.of,
10954
11054
  asset?.animation?.motionFrom,
10955
11055
  asset?.mirror,
11056
+ asset?.derive?.from,
10956
11057
  asset?.styleCharacter,
10957
11058
  ...asset?.styleCharacter ? [] : styleAnchors
10958
11059
  ].filter((id) => Boolean(id))
@@ -11411,6 +11512,64 @@ async function resolveSpecs(loaded, filter) {
11411
11512
  }
11412
11513
  if (finalized.has(assetId)) return resolved;
11413
11514
  const asset = manifest.assets[assetId];
11515
+ if (asset.derive) {
11516
+ const derive = asset.derive;
11517
+ let source;
11518
+ let sourceSpec;
11519
+ if (derive.from) {
11520
+ if (derive.from === assetId) throw new Error(`assets.${assetId}: an asset cannot derive from itself`);
11521
+ sourceSpec = await finalize(derive.from);
11522
+ if (sourceSpec.generator === "tiles" || sourceSpec.generator === "terrain") {
11523
+ throw new Error(`assets.${assetId}: a tile set is several images; derive takes a single image`);
11524
+ }
11525
+ source = { kind: "asset", assetId: derive.from, spec: sourceSpec };
11526
+ } else {
11527
+ const file = import_node_path8.default.resolve(root, derive.file);
11528
+ source = { kind: "file", file: derive.file, sha256: (0, import_node_fs9.existsSync)(file) ? await sha256File(file) : null };
11529
+ }
11530
+ if (derive.transform === "scale") {
11531
+ resolved.width = derive.width;
11532
+ resolved.height = derive.height;
11533
+ } else if (sourceSpec) {
11534
+ resolved.width = sourceSpec.width;
11535
+ resolved.height = sourceSpec.height;
11536
+ } else if (source.kind === "file" && source.sha256) {
11537
+ const metadata = imageMetadata(await (0, import_promises5.readFile)(import_node_path8.default.resolve(root, source.file)));
11538
+ if (metadata?.width && metadata.height) {
11539
+ resolved.width = metadata.width;
11540
+ resolved.height = metadata.height;
11541
+ }
11542
+ }
11543
+ resolved.derive = {
11544
+ transform: derive.transform,
11545
+ ...derive.map ? { map: derive.map } : {},
11546
+ ...derive.palette ? { palette: derive.palette } : {},
11547
+ ...derive.width ? { width: derive.width } : {},
11548
+ ...derive.height ? { height: derive.height } : {},
11549
+ ...derive.mode ? { mode: derive.mode } : {},
11550
+ source
11551
+ };
11552
+ resolved.prompt = "";
11553
+ resolved.specHash = specHash(resolved, styleImageHashes, providerOptionIdentity, providerInputIdentities.get(assetId));
11554
+ resolved.cost = 0;
11555
+ resolved.candidates = 1;
11556
+ finalized.add(assetId);
11557
+ return resolved;
11558
+ }
11559
+ if (asset.external) {
11560
+ const inputs = [];
11561
+ for (const input of asset.external.inputs ?? []) {
11562
+ const file = import_node_path8.default.resolve(root, input);
11563
+ inputs.push({ path: input, sha256: (0, import_node_fs9.existsSync)(file) ? await sha256File(file) : null });
11564
+ }
11565
+ resolved.external = { builder: asset.external.builder, inputs };
11566
+ resolved.prompt = "";
11567
+ resolved.specHash = specHash(resolved, styleImageHashes, providerOptionIdentity, providerInputIdentities.get(assetId));
11568
+ resolved.cost = 0;
11569
+ resolved.candidates = 1;
11570
+ finalized.add(assetId);
11571
+ return resolved;
11572
+ }
11414
11573
  if (asset.mirror) {
11415
11574
  if (asset.mirror === assetId) throw new Error(`assets.${assetId}: an asset cannot mirror itself`);
11416
11575
  const sourceSpec = await finalize(asset.mirror);
@@ -11572,8 +11731,8 @@ async function resolveSpecs(loaded, filter) {
11572
11731
  const sourceSpec = sourceStyleId ? await styleFinalizers.get(sourceStyleId)(asset.revision.from) : await finalize(asset.revision.from);
11573
11732
  const sourceStem = sourceSpec.quality?.outFile ?? (sourceSpec.source ? import_node_path8.default.resolve(root, sourceSpec.source) : sourceSpec.outFile);
11574
11733
  const sourceMembers = await revisionSourceMembers(sourceStem, `revision source ${asset.revision.from}`);
11575
- const sourceFile = sourceMembers?.[0]?.file ?? sourceStem;
11576
- const sourceImage = sourceMembers ? { ...sourceMembers[0], hash: sha256(JSON.stringify(sourceMembers.map((member) => member.sha256))) } : await optionalRevisionImage(sourceFile, "revision source");
11734
+ const sourceFile2 = sourceMembers?.[0]?.file ?? sourceStem;
11735
+ const sourceImage = sourceMembers ? { ...sourceMembers[0], hash: sha256(JSON.stringify(sourceMembers.map((member) => member.sha256))) } : await optionalRevisionImage(sourceFile2, "revision source");
11577
11736
  const sourceFps = sourceSpec.character?.animation?.fps ?? sourceSpec.objectPro?.animation?.fps ?? sourceSpec.revision?.fps ?? sourceSpec.revision?.sourceFps;
11578
11737
  const maskFile = asset.revision.mask ? import_node_path8.default.resolve(root, asset.revision.mask) : void 0;
11579
11738
  const maskImage = maskFile ? await optionalRevisionImage(maskFile, "revision mask", "png") : null;
@@ -11592,7 +11751,7 @@ async function resolveSpecs(loaded, filter) {
11592
11751
  mode: asset.revision.mode,
11593
11752
  sourceAssetId: asset.revision.from,
11594
11753
  ...sourceStyleId ? { sourceStyleId } : {},
11595
- sourceFile,
11754
+ sourceFile: sourceFile2,
11596
11755
  sourceSha256: sourceImage?.hash ?? null,
11597
11756
  sourceWidth: sourceImage?.width ?? null,
11598
11757
  sourceHeight: sourceImage?.height ?? null,
@@ -11767,8 +11926,8 @@ async function resolveSpecs(loaded, filter) {
11767
11926
  byOutput.set(file, owner);
11768
11927
  };
11769
11928
  for (const spec of specs) {
11770
- const key = `${spec.styleId}/${spec.assetId}`;
11771
- claimOutput(spec.outFile, key);
11929
+ const key2 = `${spec.styleId}/${spec.assetId}`;
11930
+ claimOutput(spec.outFile, key2);
11772
11931
  if (spec.quality) {
11773
11932
  if (spec.generator === "frames") {
11774
11933
  const frameInputs = Object.values(spec.providerInputs ?? {}).find(Array.isArray);
@@ -11783,11 +11942,11 @@ async function resolveSpecs(loaded, filter) {
11783
11942
  count,
11784
11943
  MediaType.PNG
11785
11944
  ),
11786
- `${key} quality ${role}`
11945
+ `${key2} quality ${role}`
11787
11946
  );
11788
11947
  }
11789
11948
  } else {
11790
- claimOutput(spec.quality.outFile, `${key} quality output`);
11949
+ claimOutput(spec.quality.outFile, `${key2} quality output`);
11791
11950
  }
11792
11951
  }
11793
11952
  }
@@ -12051,7 +12210,7 @@ function characterDirections(directions) {
12051
12210
  }
12052
12211
 
12053
12212
  // src/project.ts
12054
- var import_node_path16 = __toESM(require("path"), 1);
12213
+ var import_node_path18 = __toESM(require("path"), 1);
12055
12214
 
12056
12215
  // src/env.ts
12057
12216
  var import_node_fs10 = require("fs");
@@ -12059,8 +12218,8 @@ var import_node_path9 = __toESM(require("path"), 1);
12059
12218
  function loadEnvFiles(dir) {
12060
12219
  const loaded = [];
12061
12220
  for (const [file, vars] of envFiles(dir)) {
12062
- for (const [key, value] of Object.entries(vars)) {
12063
- if (!(key in process.env)) process.env[key] = value;
12221
+ for (const [key2, value] of Object.entries(vars)) {
12222
+ if (!(key2 in process.env)) process.env[key2] = value;
12064
12223
  }
12065
12224
  loaded.push(file);
12066
12225
  }
@@ -12085,21 +12244,21 @@ function parseEnv(contents) {
12085
12244
  if (!line || line.startsWith("#")) continue;
12086
12245
  const eq = line.indexOf("=");
12087
12246
  if (eq <= 0) continue;
12088
- const key = line.slice(0, eq).replace(/^export\s+/, "").trim();
12089
- if (!key || key in vars) continue;
12247
+ const key2 = line.slice(0, eq).replace(/^export\s+/, "").trim();
12248
+ if (!key2 || key2 in vars) continue;
12090
12249
  let value = line.slice(eq + 1).trim();
12091
12250
  const quote = value[0];
12092
12251
  if ((quote === '"' || quote === "'") && value.endsWith(quote) && value.length >= 2) {
12093
12252
  value = value.slice(1, -1);
12094
12253
  }
12095
- vars[key] = value;
12254
+ vars[key2] = value;
12096
12255
  }
12097
12256
  return vars;
12098
12257
  }
12099
12258
 
12100
12259
  // src/pipeline/plan.ts
12101
- var import_node_fs13 = require("fs");
12102
- var import_node_path15 = __toESM(require("path"), 1);
12260
+ var import_node_fs15 = require("fs");
12261
+ var import_node_path17 = __toESM(require("path"), 1);
12103
12262
 
12104
12263
  // src/pipeline/mirror.ts
12105
12264
  var import_promises6 = require("fs/promises");
@@ -12141,8 +12300,8 @@ function quantize(png, palette) {
12141
12300
  pixels[i + 2] = 0;
12142
12301
  continue;
12143
12302
  }
12144
- const key = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
12145
- let nearest = nearestOf.get(key);
12303
+ const key2 = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
12304
+ let nearest = nearestOf.get(key2);
12146
12305
  if (!nearest) {
12147
12306
  const pixel = { r: pixels[i], g: pixels[i + 1], b: pixels[i + 2] };
12148
12307
  nearest = colors[0];
@@ -12155,7 +12314,7 @@ function quantize(png, palette) {
12155
12314
  distance = candidateDistance;
12156
12315
  }
12157
12316
  }
12158
- nearestOf.set(key, nearest);
12317
+ nearestOf.set(key2, nearest);
12159
12318
  }
12160
12319
  if (pixels[i] !== nearest.r || pixels[i + 1] !== nearest.g || pixels[i + 2] !== nearest.b) changed++;
12161
12320
  pixels[i] = nearest.r;
@@ -12224,7 +12383,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
12224
12383
  const log = opts.onProgress ?? (() => {
12225
12384
  });
12226
12385
  const mirror = spec.mirror;
12227
- const key = lockKey(spec.styleId, spec.assetId);
12386
+ const key2 = lockKey(spec.styleId, spec.assetId);
12228
12387
  const sourceKey = lockKey(spec.styleId, mirror.sourceAssetId);
12229
12388
  const source = lock.entries[sourceKey];
12230
12389
  if (!source || source.status !== "downloaded" || !source.outputs.length) {
@@ -12256,7 +12415,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
12256
12415
  }
12257
12416
  const sourceMetadata = source.providerMetadata?.[source.provider] ?? {};
12258
12417
  const character = spec.character;
12259
- const entry = upsert(lock, key, {
12418
+ const entry = upsert(lock, key2, {
12260
12419
  styleId: spec.styleId,
12261
12420
  assetId: spec.assetId,
12262
12421
  specHash: spec.specHash,
@@ -12299,25 +12458,206 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
12299
12458
  postprocess: postprocessFor(spec)
12300
12459
  });
12301
12460
  await saveLock(lockPath, lock);
12302
- log(` mirror ${key} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
12461
+ log(` mirror ${key2} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
12303
12462
  return entry;
12304
12463
  }
12305
12464
 
12306
- // src/pipeline/quality-profile.ts
12465
+ // src/pipeline/derive.ts
12307
12466
  var import_node_fs11 = require("fs");
12308
- var import_node_path13 = __toESM(require("path"), 1);
12467
+ var import_promises7 = require("fs/promises");
12468
+ var import_node_path11 = __toESM(require("path"), 1);
12469
+ var key = (r, g, b) => r << 16 | g << 8 | b;
12470
+ function recolor(png, map) {
12471
+ const { width, height, pixels } = decodePng(png);
12472
+ const table = /* @__PURE__ */ new Map();
12473
+ for (const [from, to] of Object.entries(map)) {
12474
+ const a = parseHex(from);
12475
+ const b = parseHex(to);
12476
+ table.set(key(a.r, a.g, a.b), [b.r, b.g, b.b]);
12477
+ }
12478
+ const out = Buffer.from(pixels);
12479
+ for (let i = 0; i < out.length; i += 4) {
12480
+ if (out[i + 3] === 0) continue;
12481
+ const hit = table.get(key(out[i], out[i + 1], out[i + 2]));
12482
+ if (hit) {
12483
+ out[i] = hit[0];
12484
+ out[i + 1] = hit[1];
12485
+ out[i + 2] = hit[2];
12486
+ }
12487
+ }
12488
+ return encodeRgbaPng(width, height, out);
12489
+ }
12490
+ function paletteSnap(png, palette) {
12491
+ const snapped = quantize(decodePng(png), normalizePalette(palette).map((color) => color.hex)).png;
12492
+ return encodeRgbaPng(snapped.width, snapped.height, snapped.pixels);
12493
+ }
12494
+ function scale(png, width, height, mode2 = "nearest") {
12495
+ const src = decodePng(png);
12496
+ const out = Buffer.alloc(width * height * 4);
12497
+ for (let y = 0; y < height; y++) {
12498
+ const y0 = Math.floor(y * src.height / height);
12499
+ const y1 = Math.max(y0 + 1, Math.ceil((y + 1) * src.height / height));
12500
+ for (let x = 0; x < width; x++) {
12501
+ const x0 = Math.floor(x * src.width / width);
12502
+ const x1 = Math.max(x0 + 1, Math.ceil((x + 1) * src.width / width));
12503
+ const at = (y * width + x) * 4;
12504
+ if (mode2 === "nearest") {
12505
+ src.pixels.copy(out, at, (y0 * src.width + x0) * 4, (y0 * src.width + x0) * 4 + 4);
12506
+ continue;
12507
+ }
12508
+ let a = 0;
12509
+ let r = 0;
12510
+ let g = 0;
12511
+ let b = 0;
12512
+ let n = 0;
12513
+ for (let sy = y0; sy < Math.min(y1, src.height); sy++) {
12514
+ for (let sx = x0; sx < Math.min(x1, src.width); sx++) {
12515
+ const i = (sy * src.width + sx) * 4;
12516
+ const alpha = src.pixels[i + 3];
12517
+ a += alpha;
12518
+ r += src.pixels[i] * alpha;
12519
+ g += src.pixels[i + 1] * alpha;
12520
+ b += src.pixels[i + 2] * alpha;
12521
+ n++;
12522
+ }
12523
+ }
12524
+ if (a > 0) {
12525
+ out[at] = Math.round(r / a);
12526
+ out[at + 1] = Math.round(g / a);
12527
+ out[at + 2] = Math.round(b / a);
12528
+ }
12529
+ out[at + 3] = Math.round(a / Math.max(1, n));
12530
+ }
12531
+ }
12532
+ return encodeRgbaPng(width, height, out);
12533
+ }
12534
+ function applyDerive(png, derive) {
12535
+ switch (derive.transform) {
12536
+ case "recolor":
12537
+ return recolor(png, derive.map);
12538
+ case "palette-snap":
12539
+ return paletteSnap(png, derive.palette);
12540
+ case "scale":
12541
+ return scale(png, derive.width, derive.height, derive.mode);
12542
+ }
12543
+ }
12544
+ async function sourceFile(spec, lock) {
12545
+ const derive = spec.derive;
12546
+ if (derive.source.kind === "file") {
12547
+ const file2 = import_node_path11.default.resolve(spec.root, derive.source.file);
12548
+ return (0, import_node_fs11.existsSync)(file2) ? { file: file2, recorded: await sha256File(file2) } : { notReady: `source file ${derive.source.file} does not exist` };
12549
+ }
12550
+ const sourceKey = lockKey(spec.styleId, derive.source.assetId);
12551
+ const entry = lock.entries[sourceKey];
12552
+ if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
12553
+ return { notReady: `source ${sourceKey} has no downloaded output` };
12554
+ }
12555
+ if (entry.outputs.length !== 1) {
12556
+ return { notReady: `source ${sourceKey} has ${entry.outputs.length} outputs; derive takes a single image` };
12557
+ }
12558
+ const file = currentEntryOutputPath(entry, derive.source.spec, 0);
12559
+ if (!(0, import_node_fs11.existsSync)(file)) return { notReady: `source ${sourceKey} is missing on disk: ${file}` };
12560
+ return { file, recorded: entry.outputs[0].sha256 };
12561
+ }
12562
+ async function deriveStale(spec, entry, lock) {
12563
+ const derive = spec.derive;
12564
+ if (derive.source.kind === "file") {
12565
+ const file = import_node_path11.default.resolve(spec.root, derive.source.file);
12566
+ if (!(0, import_node_fs11.existsSync)(file)) return `source file ${derive.source.file} is missing`;
12567
+ return entry.derive?.sourceSha256 === await sha256File(file) ? null : `source file ${derive.source.file} changed`;
12568
+ }
12569
+ const source = lock.entries[lockKey(spec.styleId, derive.source.assetId)];
12570
+ const current = source?.outputs.length === 1 ? source.outputs[0].sha256 : void 0;
12571
+ return entry.derive?.sourceSha256 && entry.derive.sourceSha256 === current ? null : `source ${derive.source.assetId} changed`;
12572
+ }
12573
+ async function deriveAsset(spec, lock, lockPath, opts = {}) {
12574
+ const log = opts.onProgress ?? (() => {
12575
+ });
12576
+ const derive = spec.derive;
12577
+ const entryKey = lockKey(spec.styleId, spec.assetId);
12578
+ const source = await sourceFile(spec, lock);
12579
+ if ("notReady" in source) throw new Error(source.notReady);
12580
+ const bytes = applyDerive(await (0, import_promises7.readFile)(source.file), derive);
12581
+ const target = expectedOutputPath(spec, void 0, 0, 1, MediaType.PNG);
12582
+ await (0, import_promises7.mkdir)(import_node_path11.default.dirname(target), { recursive: true });
12583
+ const tmp = `${target}.pixelkiln.tmp`;
12584
+ await (0, import_promises7.writeFile)(tmp, bytes);
12585
+ await (0, import_promises7.rename)(tmp, target);
12586
+ const out = decodePng(bytes);
12587
+ const now = (/* @__PURE__ */ new Date()).toISOString();
12588
+ const entry = upsert(lock, entryKey, {
12589
+ styleId: spec.styleId,
12590
+ assetId: spec.assetId,
12591
+ specHash: spec.specHash,
12592
+ generator: spec.generator,
12593
+ tileFeature: null,
12594
+ prompt: "",
12595
+ width: out.width,
12596
+ height: out.height,
12597
+ revision: null,
12598
+ derive: derive.source.kind === "asset" ? { sourceAssetId: derive.source.assetId, sourceSha256: source.recorded } : { sourceFile: derive.source.file, sourceSha256: source.recorded },
12599
+ supersededOutputs: [],
12600
+ jobId: null,
12601
+ submissionComplete: void 0,
12602
+ reviewObjectId: null,
12603
+ objectId: null,
12604
+ candidateIndex: null,
12605
+ status: "downloaded",
12606
+ error: null,
12607
+ outputs: [{ path: portableOutputPath(target, spec.root), sha256: sha256(bytes), mediaType: MediaType.PNG }],
12608
+ sourceUrl: null,
12609
+ sourceUrls: [],
12610
+ submittedAt: now,
12611
+ downloadedAt: now,
12612
+ history: [],
12613
+ cost: 0,
12614
+ costUnit: spec.costUnit,
12615
+ provider: spec.provider,
12616
+ postprocess: void 0
12617
+ });
12618
+ await saveLock(lockPath, lock);
12619
+ log(` derive ${entryKey} \u2190 ${derive.source.kind === "asset" ? derive.source.assetId : derive.source.file} (${derive.transform}, no generation cost)`);
12620
+ return entry;
12621
+ }
12309
12622
 
12310
- // src/pipeline/refine.ts
12623
+ // src/pipeline/external.ts
12624
+ var import_node_fs12 = require("fs");
12311
12625
  var import_node_path12 = __toESM(require("path"), 1);
12626
+ async function inspectExternal(spec, entry) {
12627
+ const external = spec.external;
12628
+ const file = entry?.outputs.length ? currentEntryOutputPath(entry, spec, 0) : spec.outFile;
12629
+ const rebuild = `run \`${external.builder}\``;
12630
+ if (!(0, import_node_fs12.existsSync)(file)) {
12631
+ return { state: "orphaned", reason: `built outside pixelkiln and not found at ${import_node_path12.default.relative(spec.root, file)}; ${rebuild}, then adopt --local` };
12632
+ }
12633
+ if (!entry) {
12634
+ return { state: "untracked", reason: `built outside pixelkiln; record it with adopt --local (builder: ${external.builder})` };
12635
+ }
12636
+ if (entry.specHash !== spec.specHash) {
12637
+ return { state: "orphaned", reason: `builder or an input changed since the file was recorded; ${rebuild}, then adopt --local --force` };
12638
+ }
12639
+ const recorded = entry.outputs[0]?.sha256;
12640
+ if (!recorded || await sha256File(file) !== recorded) {
12641
+ return { state: "orphaned", reason: "file changed since it was recorded; adopt --local --force to record it again" };
12642
+ }
12643
+ return { state: "ok", reason: "built outside pixelkiln; matches the recorded file" };
12644
+ }
12645
+
12646
+ // src/pipeline/quality-profile.ts
12647
+ var import_node_fs13 = require("fs");
12648
+ var import_node_path15 = __toESM(require("path"), 1);
12649
+
12650
+ // src/pipeline/refine.ts
12651
+ var import_node_path14 = __toESM(require("path"), 1);
12312
12652
  var import_node_child_process2 = require("child_process");
12313
- var import_promises8 = require("fs/promises");
12653
+ var import_promises9 = require("fs/promises");
12314
12654
  var import_node_os3 = require("os");
12315
12655
  var import_node_util = require("util");
12316
12656
 
12317
12657
  // src/artifacts.ts
12318
- var import_node_path11 = __toESM(require("path"), 1);
12658
+ var import_node_path13 = __toESM(require("path"), 1);
12319
12659
  var import_node_crypto6 = require("crypto");
12320
- var import_promises7 = require("fs/promises");
12660
+ var import_promises8 = require("fs/promises");
12321
12661
  var activeTransactions = /* @__PURE__ */ new Set();
12322
12662
  function message(error) {
12323
12663
  return error instanceof Error ? error.message : String(error);
@@ -12326,7 +12666,7 @@ function digest(data) {
12326
12666
  return (0, import_node_crypto6.createHash)("sha256").update(data).digest("hex");
12327
12667
  }
12328
12668
  function portableRelative(from, to) {
12329
- return import_node_path11.default.relative(from, import_node_path11.default.resolve(to)).split(import_node_path11.default.sep).join("/") || ".";
12669
+ return import_node_path13.default.relative(from, import_node_path13.default.resolve(to)).split(import_node_path13.default.sep).join("/") || ".";
12330
12670
  }
12331
12671
  function canonical2(value) {
12332
12672
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
@@ -12337,9 +12677,9 @@ function canonical2(value) {
12337
12677
  if (Array.isArray(value)) return value.map(canonical2);
12338
12678
  if (typeof value === "object") {
12339
12679
  const sorted = {};
12340
- for (const key of Object.keys(value).sort()) {
12341
- const item = value[key];
12342
- if (item !== void 0) sorted[key] = canonical2(item);
12680
+ for (const key2 of Object.keys(value).sort()) {
12681
+ const item = value[key2];
12682
+ if (item !== void 0) sorted[key2] = canonical2(item);
12343
12683
  }
12344
12684
  return sorted;
12345
12685
  }
@@ -12376,12 +12716,12 @@ function parseArtifactManifest(absolute, data) {
12376
12716
  return raw;
12377
12717
  }
12378
12718
  async function readArtifactBundleManifest(manifestPath) {
12379
- const absolute = import_node_path11.default.resolve(manifestPath);
12380
- return parseArtifactManifest(absolute, await (0, import_promises7.readFile)(absolute, "utf8"));
12719
+ const absolute = import_node_path13.default.resolve(manifestPath);
12720
+ return parseArtifactManifest(absolute, await (0, import_promises8.readFile)(absolute, "utf8"));
12381
12721
  }
12382
12722
  async function readOptional(file) {
12383
12723
  try {
12384
- return await (0, import_promises7.readFile)(file);
12724
+ return await (0, import_promises8.readFile)(file);
12385
12725
  } catch (error) {
12386
12726
  if (isCode(error, "ENOENT")) return null;
12387
12727
  throw error;
@@ -12400,8 +12740,8 @@ function processIsAlive(pid) {
12400
12740
  }
12401
12741
  }
12402
12742
  function validTemporaryPath(candidate, destination, type) {
12403
- return import_node_path11.default.dirname(candidate) === import_node_path11.default.dirname(destination) && import_node_path11.default.basename(candidate).startsWith(
12404
- `.${import_node_path11.default.basename(destination)}.pixelkiln-${type}-`
12743
+ return import_node_path13.default.dirname(candidate) === import_node_path13.default.dirname(destination) && import_node_path13.default.basename(candidate).startsWith(
12744
+ `.${import_node_path13.default.basename(destination)}.pixelkiln-${type}-`
12405
12745
  );
12406
12746
  }
12407
12747
  function parseTransaction(journal, data) {
@@ -12417,14 +12757,14 @@ function parseTransaction(journal, data) {
12417
12757
  return raw;
12418
12758
  }
12419
12759
  async function removeTransactionFiles(journal) {
12420
- await (0, import_promises7.rm)(journal, { force: true });
12421
- await (0, import_promises7.rm)(transactionMarker(journal), { force: true });
12760
+ await (0, import_promises8.rm)(journal, { force: true });
12761
+ await (0, import_promises8.rm)(transactionMarker(journal), { force: true });
12422
12762
  }
12423
12763
  async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12424
- const journal = import_node_path11.default.resolve(recoveryFile);
12764
+ const journal = import_node_path13.default.resolve(recoveryFile);
12425
12765
  const bytes = await readOptional(journal);
12426
12766
  if (!bytes) {
12427
- await (0, import_promises7.rm)(transactionMarker(journal), { force: true });
12767
+ await (0, import_promises8.rm)(transactionMarker(journal), { force: true });
12428
12768
  return;
12429
12769
  }
12430
12770
  if (activeTransactions.has(journal)) {
@@ -12437,7 +12777,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12437
12777
  );
12438
12778
  }
12439
12779
  for (const entry of transaction.entries) {
12440
- if (typeof entry.destination !== "string" || typeof entry.stage !== "string" || typeof entry.sha256 !== "string" || entry.backup !== void 0 && typeof entry.backup !== "string" || !allowedDestinations.has(import_node_path11.default.resolve(entry.destination)) || !validTemporaryPath(entry.stage, entry.destination, "stage") || entry.backup !== void 0 && !validTemporaryPath(entry.backup, entry.destination, "backup")) {
12780
+ if (typeof entry.destination !== "string" || typeof entry.stage !== "string" || typeof entry.sha256 !== "string" || entry.backup !== void 0 && typeof entry.backup !== "string" || !allowedDestinations.has(import_node_path13.default.resolve(entry.destination)) || !validTemporaryPath(entry.stage, entry.destination, "stage") || entry.backup !== void 0 && !validTemporaryPath(entry.backup, entry.destination, "backup")) {
12441
12781
  throw new Error(
12442
12782
  `Refusing unsafe artifact recovery from ${journal}; its destinations or temporary paths do not match the current bundle.`
12443
12783
  );
@@ -12463,7 +12803,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12463
12803
  }
12464
12804
  await remove2(entry.destination, errors);
12465
12805
  try {
12466
- await (0, import_promises7.rename)(entry.backup, entry.destination);
12806
+ await (0, import_promises8.rename)(entry.backup, entry.destination);
12467
12807
  } catch (error) {
12468
12808
  errors.push(
12469
12809
  `could not restore ${entry.destination}; previous file remains at ${entry.backup}: ${message(error)}`
@@ -12483,7 +12823,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12483
12823
  await removeTransactionFiles(journal);
12484
12824
  }
12485
12825
  function createArtifactBundleManifest(manifestPath, outputs, provenance) {
12486
- const root = import_node_path11.default.dirname(import_node_path11.default.resolve(manifestPath));
12826
+ const root = import_node_path13.default.dirname(import_node_path13.default.resolve(manifestPath));
12487
12827
  const sources = provenance.sources.map((source) => ({
12488
12828
  ...source,
12489
12829
  path: portableRelative(root, source.path)
@@ -12513,11 +12853,11 @@ function withArtifactManifest(manifestPath, outputs, provenance) {
12513
12853
  ];
12514
12854
  }
12515
12855
  async function writeManagedArtifactBundle(manifestPath, outputs, provenance, options = {}) {
12516
- const absoluteManifest = import_node_path11.default.resolve(manifestPath);
12856
+ const absoluteManifest = import_node_path13.default.resolve(manifestPath);
12517
12857
  const recoveryFile = `${absoluteManifest}.transaction`;
12518
12858
  const allowedDestinations = /* @__PURE__ */ new Set([
12519
12859
  absoluteManifest,
12520
- ...outputs.map((output) => import_node_path11.default.resolve(output.path))
12860
+ ...outputs.map((output) => import_node_path13.default.resolve(output.path))
12521
12861
  ]);
12522
12862
  await recoverArtifactTransaction(recoveryFile, allowedDestinations);
12523
12863
  const existingManifestBytes = await readOptional(absoluteManifest);
@@ -12535,13 +12875,13 @@ async function writeManagedArtifactBundle(manifestPath, outputs, provenance, opt
12535
12875
  }
12536
12876
  }
12537
12877
  if (!options.force) {
12538
- const root = import_node_path11.default.dirname(absoluteManifest);
12878
+ const root = import_node_path13.default.dirname(absoluteManifest);
12539
12879
  const recorded = new Map(
12540
- previous?.outputs.map((output) => [import_node_path11.default.resolve(root, output.path), output.sha256]) ?? []
12880
+ previous?.outputs.map((output) => [import_node_path13.default.resolve(root, output.path), output.sha256]) ?? []
12541
12881
  );
12542
12882
  const conflicts = [];
12543
12883
  for (const output of outputs) {
12544
- const destination = import_node_path11.default.resolve(output.path);
12884
+ const destination = import_node_path13.default.resolve(output.path);
12545
12885
  const current = await readOptional(destination);
12546
12886
  if (!current || digest(current) === digest(output.data)) continue;
12547
12887
  const expected = recorded.get(destination);
@@ -12563,15 +12903,15 @@ Pass { force: true } (CLI: --force) to take ownership and replace the complete b
12563
12903
  );
12564
12904
  }
12565
12905
  async function verifyArtifactBundle(manifestPath) {
12566
- const absolute = import_node_path11.default.resolve(manifestPath);
12906
+ const absolute = import_node_path13.default.resolve(manifestPath);
12567
12907
  const raw = await readArtifactBundleManifest(absolute);
12568
- const root = import_node_path11.default.dirname(absolute);
12908
+ const root = import_node_path13.default.dirname(absolute);
12569
12909
  const changedSources = [];
12570
12910
  const changedOutputs = [];
12571
12911
  for (const source of raw.sources) {
12572
12912
  let actual = null;
12573
12913
  try {
12574
- actual = digest(await (0, import_promises7.readFile)(import_node_path11.default.resolve(root, source.path)));
12914
+ actual = digest(await (0, import_promises8.readFile)(import_node_path13.default.resolve(root, source.path)));
12575
12915
  } catch (error) {
12576
12916
  if (!isCode(error, "ENOENT")) throw error;
12577
12917
  }
@@ -12579,7 +12919,7 @@ async function verifyArtifactBundle(manifestPath) {
12579
12919
  }
12580
12920
  for (const output of raw.outputs) {
12581
12921
  try {
12582
- if (digest(await (0, import_promises7.readFile)(import_node_path11.default.resolve(root, output.path))) !== output.sha256) {
12922
+ if (digest(await (0, import_promises8.readFile)(import_node_path13.default.resolve(root, output.path))) !== output.sha256) {
12583
12923
  changedOutputs.push(output.path);
12584
12924
  }
12585
12925
  } catch (error) {
@@ -12605,7 +12945,7 @@ function isCode(error, code) {
12605
12945
  }
12606
12946
  async function remove2(file, errors) {
12607
12947
  try {
12608
- await (0, import_promises7.rm)(file, { force: true });
12948
+ await (0, import_promises8.rm)(file, { force: true });
12609
12949
  } catch (error) {
12610
12950
  errors?.push(`could not remove ${file}: ${message(error)}`);
12611
12951
  }
@@ -12618,7 +12958,7 @@ async function rollback(prepared) {
12618
12958
  for (const artifact of [...prepared].reverse()) {
12619
12959
  if (!artifact.backup || !artifact.backedUp) continue;
12620
12960
  try {
12621
- await (0, import_promises7.rename)(artifact.backup, artifact.destination);
12961
+ await (0, import_promises8.rename)(artifact.backup, artifact.destination);
12622
12962
  artifact.backedUp = false;
12623
12963
  } catch (error) {
12624
12964
  errors.push(
@@ -12635,7 +12975,7 @@ async function writeArtifactBundle(files, options = {}) {
12635
12975
  if (!files.length) throw new Error("An artifact bundle must contain at least one file.");
12636
12976
  const normalized = files.map((file) => {
12637
12977
  if (!file.path.trim()) throw new Error("Artifact paths cannot be empty.");
12638
- return { destination: import_node_path11.default.resolve(file.path), data: Buffer.from(file.data) };
12978
+ return { destination: import_node_path13.default.resolve(file.path), data: Buffer.from(file.data) };
12639
12979
  });
12640
12980
  const destinations = /* @__PURE__ */ new Set();
12641
12981
  for (const artifact of normalized) {
@@ -12651,7 +12991,7 @@ async function writeArtifactBundle(files, options = {}) {
12651
12991
  const unchanged = [];
12652
12992
  for (const artifact of normalized) {
12653
12993
  try {
12654
- const current = await (0, import_promises7.readFile)(artifact.destination);
12994
+ const current = await (0, import_promises8.readFile)(artifact.destination);
12655
12995
  if (current.equals(artifact.data)) {
12656
12996
  unchanged.push(artifact.destination);
12657
12997
  } else {
@@ -12665,21 +13005,21 @@ async function writeArtifactBundle(files, options = {}) {
12665
13005
  if (!changed.length) return { changed: [], unchanged };
12666
13006
  const token = (0, import_node_crypto6.randomUUID)();
12667
13007
  for (const [index, artifact] of changed.entries()) {
12668
- const basename = import_node_path11.default.basename(artifact.destination);
12669
- artifact.stage = import_node_path11.default.join(
12670
- import_node_path11.default.dirname(artifact.destination),
13008
+ const basename = import_node_path13.default.basename(artifact.destination);
13009
+ artifact.stage = import_node_path13.default.join(
13010
+ import_node_path13.default.dirname(artifact.destination),
12671
13011
  `.${basename}.pixelkiln-stage-${token}-${index}`
12672
13012
  );
12673
13013
  if (artifact.existed) {
12674
- artifact.backup = import_node_path11.default.join(
12675
- import_node_path11.default.dirname(artifact.destination),
13014
+ artifact.backup = import_node_path13.default.join(
13015
+ import_node_path13.default.dirname(artifact.destination),
12676
13016
  `.${basename}.pixelkiln-backup-${token}-${index}`
12677
13017
  );
12678
13018
  }
12679
13019
  }
12680
- const journal = options.recoveryFile ? import_node_path11.default.resolve(options.recoveryFile) : null;
13020
+ const journal = options.recoveryFile ? import_node_path13.default.resolve(options.recoveryFile) : null;
12681
13021
  if (journal) {
12682
- await (0, import_promises7.mkdir)(import_node_path11.default.dirname(journal), { recursive: true });
13022
+ await (0, import_promises8.mkdir)(import_node_path13.default.dirname(journal), { recursive: true });
12683
13023
  const transaction = {
12684
13024
  format: "pixelkiln-artifact-transaction",
12685
13025
  version: 1,
@@ -12693,7 +13033,7 @@ async function writeArtifactBundle(files, options = {}) {
12693
13033
  }))
12694
13034
  };
12695
13035
  try {
12696
- await (0, import_promises7.writeFile)(journal, JSON.stringify(transaction, null, 2) + "\n", { flag: "wx" });
13036
+ await (0, import_promises8.writeFile)(journal, JSON.stringify(transaction, null, 2) + "\n", { flag: "wx" });
12697
13037
  activeTransactions.add(journal);
12698
13038
  } catch (error) {
12699
13039
  throw new Error(
@@ -12704,9 +13044,9 @@ async function writeArtifactBundle(files, options = {}) {
12704
13044
  }
12705
13045
  try {
12706
13046
  for (const [index, artifact] of changed.entries()) {
12707
- await (0, import_promises7.mkdir)(import_node_path11.default.dirname(artifact.destination), { recursive: true });
13047
+ await (0, import_promises8.mkdir)(import_node_path13.default.dirname(artifact.destination), { recursive: true });
12708
13048
  await options.beforeStage?.(artifact.destination, index);
12709
- await (0, import_promises7.writeFile)(artifact.stage, artifact.data, { flag: "wx" });
13049
+ await (0, import_promises8.writeFile)(artifact.stage, artifact.data, { flag: "wx" });
12710
13050
  }
12711
13051
  } catch (error) {
12712
13052
  const cleanupErrors2 = await rollback(changed);
@@ -12719,17 +13059,17 @@ async function writeArtifactBundle(files, options = {}) {
12719
13059
  try {
12720
13060
  for (const artifact of changed) {
12721
13061
  if (!artifact.existed) continue;
12722
- await (0, import_promises7.rename)(artifact.destination, artifact.backup);
13062
+ await (0, import_promises8.rename)(artifact.destination, artifact.backup);
12723
13063
  artifact.backedUp = true;
12724
13064
  }
12725
13065
  for (const [index, artifact] of changed.entries()) {
12726
13066
  await options.beforePromote?.(artifact.destination, index);
12727
- await (0, import_promises7.rename)(artifact.stage, artifact.destination);
13067
+ await (0, import_promises8.rename)(artifact.stage, artifact.destination);
12728
13068
  artifact.stage = void 0;
12729
13069
  artifact.promoted = true;
12730
13070
  }
12731
13071
  if (journal) {
12732
- await (0, import_promises7.writeFile)(transactionMarker(journal), `${token}
13072
+ await (0, import_promises8.writeFile)(transactionMarker(journal), `${token}
12733
13073
  `, { flag: "wx" });
12734
13074
  durableCommit = true;
12735
13075
  await options.afterCommit?.();
@@ -12970,16 +13310,16 @@ function sameFrameGrid(first, next) {
12970
13310
  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;
12971
13311
  }
12972
13312
  async function refineAsset(options) {
12973
- const source = import_node_path12.default.resolve(options.source);
12974
- const output = import_node_path12.default.resolve(options.output);
13313
+ const source = import_node_path14.default.resolve(options.source);
13314
+ const output = import_node_path14.default.resolve(options.output);
12975
13315
  if (source === output) throw new Error("Refinement source and output must be different files.");
12976
- const record = import_node_path12.default.resolve(qualityRecordPath(output));
13316
+ const record = import_node_path14.default.resolve(qualityRecordPath(output));
12977
13317
  const palette = normalizePalette(options.palette).map((color) => color.hex);
12978
13318
  const minGridConfidence = requireConfidence(options.minGridConfidence ?? "high");
12979
13319
  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.");
12980
13320
  let sourcePng;
12981
13321
  try {
12982
- sourcePng = decodePng(await (0, import_promises8.readFile)(source));
13322
+ sourcePng = decodePng(await (0, import_promises9.readFile)(source));
12983
13323
  } catch (error) {
12984
13324
  throw new Error(`Cannot read refinement source ${source}: ${message2(error)}`, { cause: error });
12985
13325
  }
@@ -12996,8 +13336,8 @@ async function refineAsset(options) {
12996
13336
  );
12997
13337
  }
12998
13338
  }
12999
- const temp = await (0, import_promises8.mkdtemp)(import_node_path12.default.join((0, import_node_os3.tmpdir)(), "pixelkiln-refine-"));
13000
- const recovered = import_node_path12.default.join(temp, "native.png");
13339
+ const temp = await (0, import_promises9.mkdtemp)(import_node_path14.default.join((0, import_node_os3.tmpdir)(), "pixelkiln-refine-"));
13340
+ const recovered = import_node_path14.default.join(temp, "native.png");
13001
13341
  const fixerCommand = compatibilityCommand ?? options.fixerPython ?? process.env.PIXELKILN_PIXEL_FIXER_PYTHON ?? "python3";
13002
13342
  const args = compatibilityCommand ? [...options.fixerArgsPrefix ?? [], source, "--extract", recovered] : ["-c", PYTHON_FIXER_BRIDGE, source, recovered];
13003
13343
  try {
@@ -13018,7 +13358,7 @@ async function refineAsset(options) {
13018
13358
  );
13019
13359
  }
13020
13360
  const detection = parseDetection(firstJsonObject(stdout));
13021
- const native = decodePng(await (0, import_promises8.readFile)(recovered));
13361
+ const native = decodePng(await (0, import_promises9.readFile)(recovered));
13022
13362
  const quantized = quantizeToPalette(native, palette);
13023
13363
  const png = encodeRgbaPng(quantized.width, quantized.height, quantized.pixels);
13024
13364
  const audit = auditRefinement(
@@ -13068,7 +13408,7 @@ async function refineAsset(options) {
13068
13408
  );
13069
13409
  return { source, output, record, detection, palette, audit };
13070
13410
  } finally {
13071
- await (0, import_promises8.rm)(temp, { recursive: true, force: true });
13411
+ await (0, import_promises9.rm)(temp, { recursive: true, force: true });
13072
13412
  }
13073
13413
  }
13074
13414
  async function refineFrameSet(options) {
@@ -13082,18 +13422,18 @@ async function refineFrameSet(options) {
13082
13422
  if (roles.some((role) => !role.trim()) || new Set(roles).size !== roles.length) {
13083
13423
  throw new Error("Frame-set roles must be non-empty and unique.");
13084
13424
  }
13085
- const output = import_node_path12.default.resolve(options.output);
13086
- const record = import_node_path12.default.resolve(qualityRecordPath(output));
13425
+ const output = import_node_path14.default.resolve(options.output);
13426
+ const record = import_node_path14.default.resolve(qualityRecordPath(output));
13087
13427
  const palette = normalizeRefinementPalette(options.palette);
13088
13428
  const finalOutputs = options.sources.map((source, index) => qualityFrameOutputPath(output, source.role, index));
13089
13429
  if (new Set(finalOutputs).size !== finalOutputs.length) {
13090
13430
  throw new Error("Frame-set roles resolve to duplicate output filenames.");
13091
13431
  }
13092
- const sourceSet = new Set(options.sources.map((source) => import_node_path12.default.resolve(source.path)));
13432
+ const sourceSet = new Set(options.sources.map((source) => import_node_path14.default.resolve(source.path)));
13093
13433
  if (finalOutputs.some((file) => sourceSet.has(file))) {
13094
13434
  throw new Error("Frame-set refinement sources and outputs must be different files.");
13095
13435
  }
13096
- const temp = await (0, import_promises8.mkdtemp)(import_node_path12.default.join((0, import_node_os3.tmpdir)(), "pixelkiln-refine-frames-"));
13436
+ const temp = await (0, import_promises9.mkdtemp)(import_node_path14.default.join((0, import_node_os3.tmpdir)(), "pixelkiln-refine-frames-"));
13097
13437
  try {
13098
13438
  const frames = [];
13099
13439
  const outputs = [];
@@ -13101,8 +13441,8 @@ async function refineFrameSet(options) {
13101
13441
  const sourcePaths = [];
13102
13442
  let firstOptions = null;
13103
13443
  for (const [index, sourceEntry] of options.sources.entries()) {
13104
- const source = import_node_path12.default.resolve(sourceEntry.path);
13105
- const temporaryOutput = import_node_path12.default.join(temp, `${String(index).padStart(2, "0")}.png`);
13444
+ const source = import_node_path14.default.resolve(sourceEntry.path);
13445
+ const temporaryOutput = import_node_path14.default.join(temp, `${String(index).padStart(2, "0")}.png`);
13106
13446
  const refined = await refineAsset({
13107
13447
  source,
13108
13448
  output: temporaryOutput,
@@ -13134,7 +13474,7 @@ async function refineFrameSet(options) {
13134
13474
  });
13135
13475
  outputs.push({
13136
13476
  path: finalOutputs[index],
13137
- data: await (0, import_promises8.readFile)(temporaryOutput)
13477
+ data: await (0, import_promises9.readFile)(temporaryOutput)
13138
13478
  });
13139
13479
  }
13140
13480
  const first = frames[0];
@@ -13177,23 +13517,23 @@ async function refineFrameSet(options) {
13177
13517
  );
13178
13518
  return {
13179
13519
  sources: sourcePaths,
13180
- outputs: outputs.map((item) => import_node_path12.default.resolve(item.path)),
13520
+ outputs: outputs.map((item) => import_node_path14.default.resolve(item.path)),
13181
13521
  record,
13182
13522
  frames,
13183
13523
  palette,
13184
13524
  audit
13185
13525
  };
13186
13526
  } finally {
13187
- await (0, import_promises8.rm)(temp, { recursive: true, force: true });
13527
+ await (0, import_promises9.rm)(temp, { recursive: true, force: true });
13188
13528
  }
13189
13529
  }
13190
13530
  async function checkQualityRecord(recordPath) {
13191
- const record = import_node_path12.default.resolve(recordPath);
13531
+ const record = import_node_path14.default.resolve(recordPath);
13192
13532
  const manifest = await readArtifactBundleManifest(record);
13193
13533
  const options = parseRecordOptions(manifest, record);
13194
13534
  const verification = await verifyArtifactBundle(record);
13195
- const sources = manifest.sources.map((source2) => import_node_path12.default.resolve(import_node_path12.default.dirname(record), source2.path));
13196
- const outputs = manifest.outputs.map((output2) => import_node_path12.default.resolve(import_node_path12.default.dirname(record), output2.path));
13535
+ const sources = manifest.sources.map((source2) => import_node_path14.default.resolve(import_node_path14.default.dirname(record), source2.path));
13536
+ const outputs = manifest.outputs.map((output2) => import_node_path14.default.resolve(import_node_path14.default.dirname(record), output2.path));
13197
13537
  const source = sources[0] ?? "";
13198
13538
  const output = outputs[0] ?? "";
13199
13539
  const expectedCount = options.frameSet?.count ?? 1;
@@ -13226,7 +13566,7 @@ async function checkQualityRecord(recordPath) {
13226
13566
  async function approveQualityRecord(recordPath, approval) {
13227
13567
  const reviewer = approval.reviewer.trim();
13228
13568
  if (!reviewer) throw new Error("A human reviewer name is required.");
13229
- const record = import_node_path12.default.resolve(recordPath);
13569
+ const record = import_node_path14.default.resolve(recordPath);
13230
13570
  const manifest = await readArtifactBundleManifest(record);
13231
13571
  const options = parseRecordOptions(manifest, record);
13232
13572
  const verification = await verifyArtifactBundle(record);
@@ -13247,14 +13587,14 @@ async function approveQualityRecord(recordPath, approval) {
13247
13587
  `A refinement record must contain exactly ${expectedCount} source(s) and output(s).`
13248
13588
  );
13249
13589
  }
13250
- const root = import_node_path12.default.dirname(record);
13590
+ const root = import_node_path14.default.dirname(record);
13251
13591
  const outputs = await Promise.all(manifest.outputs.map(async (entry) => {
13252
- const outputPath = import_node_path12.default.resolve(root, entry.path);
13253
- return { path: outputPath, data: await (0, import_promises8.readFile)(outputPath) };
13592
+ const outputPath = import_node_path14.default.resolve(root, entry.path);
13593
+ return { path: outputPath, data: await (0, import_promises9.readFile)(outputPath) };
13254
13594
  }));
13255
13595
  const sources = manifest.sources.map((source) => ({
13256
13596
  ...source,
13257
- path: import_node_path12.default.resolve(root, source.path)
13597
+ path: import_node_path14.default.resolve(root, source.path)
13258
13598
  }));
13259
13599
  const approved = {
13260
13600
  ...options,
@@ -13286,8 +13626,8 @@ async function qualitySource(spec, lock) {
13286
13626
  if (spec.generator === "frames") {
13287
13627
  return { items: null, reason: "frame-set quality requires ordered downloaded provider outputs" };
13288
13628
  }
13289
- const source = import_node_path13.default.resolve(spec.root, spec.source);
13290
- return (0, import_node_fs11.existsSync)(source) ? { items: [{ role: "source", path: source }] } : { items: null, reason: `declared source is missing: ${spec.source}` };
13629
+ const source = import_node_path15.default.resolve(spec.root, spec.source);
13630
+ return (0, import_node_fs13.existsSync)(source) ? { items: [{ role: "source", path: source }] } : { items: null, reason: `declared source is missing: ${spec.source}` };
13291
13631
  }
13292
13632
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
13293
13633
  if (!entry) return { items: null, reason: "raw provider output is not in the lockfile" };
@@ -13316,7 +13656,7 @@ async function qualitySource(spec, lock) {
13316
13656
  }
13317
13657
  if (role) roles.add(role);
13318
13658
  const source = currentEntryOutputPath(entry, spec, index);
13319
- if (!(0, import_node_fs11.existsSync)(source)) return { items: null, reason: `raw provider output is missing: ${source}` };
13659
+ if (!(0, import_node_fs13.existsSync)(source)) return { items: null, reason: `raw provider output is missing: ${source}` };
13320
13660
  if (await sha256File(source) !== output.sha256) {
13321
13661
  return { items: null, reason: "raw provider output was modified after download" };
13322
13662
  }
@@ -13326,18 +13666,18 @@ async function qualitySource(spec, lock) {
13326
13666
  }
13327
13667
  async function inspectQualityProfile(spec, lock) {
13328
13668
  if (!spec.quality) return null;
13329
- const key = lockKey(spec.styleId, spec.assetId);
13669
+ const key2 = lockKey(spec.styleId, spec.assetId);
13330
13670
  const output = spec.quality.outFile;
13331
13671
  const record = qualityRecordPath(output);
13332
13672
  const source = await qualitySource(spec, lock);
13333
13673
  if (!source.items) {
13334
- return { key, state: "blocked", reason: source.reason, source: null, output, record };
13674
+ return { key: key2, state: "blocked", reason: source.reason, source: null, output, record };
13335
13675
  }
13336
13676
  const sourcePaths = source.items.map((item) => item.path);
13337
13677
  const expectedOutputs = spec.generator === "frames" ? source.items.map((item, index) => qualityFrameOutputPath(output, item.role, index)) : [output];
13338
- if (!(0, import_node_fs11.existsSync)(record)) {
13678
+ if (!(0, import_node_fs13.existsSync)(record)) {
13339
13679
  return {
13340
- key,
13680
+ key: key2,
13341
13681
  state: "needs-refinement",
13342
13682
  reason: "no refinement record",
13343
13683
  source: sourcePaths[0],
@@ -13353,10 +13693,10 @@ async function inspectQualityProfile(spec, lock) {
13353
13693
  const expectedRevision = spec.quality.fixerRevision ?? PIXEL_ART_FIXER_REVISION;
13354
13694
  const expectedTransparency = spec.quality.minTransparency ?? null;
13355
13695
  const expectedFrameSet = spec.generator === "frames" ? { fps: spec.quality.fps ?? 12, count: source.items.length, roles: source.items.map((item) => item.role) } : null;
13356
- const contractChanged = JSON.stringify(check.sources.map((item) => import_node_path13.default.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => import_node_path13.default.resolve(item))) || JSON.stringify(check.outputs.map((item) => import_node_path13.default.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => import_node_path13.default.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);
13696
+ const contractChanged = JSON.stringify(check.sources.map((item) => import_node_path15.default.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => import_node_path15.default.resolve(item))) || JSON.stringify(check.outputs.map((item) => import_node_path15.default.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => import_node_path15.default.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);
13357
13697
  if (contractChanged) {
13358
13698
  return {
13359
- key,
13699
+ key: key2,
13360
13700
  state: "needs-refinement",
13361
13701
  reason: "quality profile changed",
13362
13702
  source: sourcePaths[0],
@@ -13368,7 +13708,7 @@ async function inspectQualityProfile(spec, lock) {
13368
13708
  }
13369
13709
  if (!check.current || !check.auditSafe) {
13370
13710
  return {
13371
- key,
13711
+ key: key2,
13372
13712
  state: "needs-refinement",
13373
13713
  reason: check.reasons.filter((reason) => reason !== "human 1\xD7 review is pending").join("; ") || "refinement record is stale",
13374
13714
  source: sourcePaths[0],
@@ -13380,7 +13720,7 @@ async function inspectQualityProfile(spec, lock) {
13380
13720
  }
13381
13721
  if (!check.approved) {
13382
13722
  return {
13383
- key,
13723
+ key: key2,
13384
13724
  state: "needs-approval",
13385
13725
  reason: "automated checks passed; human 1\xD7 review is pending",
13386
13726
  source: sourcePaths[0],
@@ -13391,7 +13731,7 @@ async function inspectQualityProfile(spec, lock) {
13391
13731
  };
13392
13732
  }
13393
13733
  return {
13394
- key,
13734
+ key: key2,
13395
13735
  state: "approved",
13396
13736
  reason: "refined output and human approval are current",
13397
13737
  source: sourcePaths[0],
@@ -13402,7 +13742,7 @@ async function inspectQualityProfile(spec, lock) {
13402
13742
  };
13403
13743
  } catch (error) {
13404
13744
  return {
13405
- key,
13745
+ key: key2,
13406
13746
  state: "needs-refinement",
13407
13747
  reason: `invalid refinement record: ${error instanceof Error ? error.message : String(error)}`,
13408
13748
  source: sourcePaths[0],
@@ -13516,10 +13856,11 @@ async function requireApprovedQualitySources(specs, lock, assetIds, outputRoles)
13516
13856
  }
13517
13857
 
13518
13858
  // src/pipeline/revision.ts
13519
- var import_node_fs12 = require("fs");
13520
- var import_node_path14 = __toESM(require("path"), 1);
13859
+ var import_node_fs14 = require("fs");
13860
+ var import_node_path16 = __toESM(require("path"), 1);
13521
13861
  async function inspectRevisionReadiness(spec, lock) {
13522
13862
  if (spec.mirror) return inspectMirror(spec, lock, /* @__PURE__ */ new Set());
13863
+ if (spec.derive) return inspectDerive(spec, lock, /* @__PURE__ */ new Set());
13523
13864
  if (spec.character?.kind === "outfit") return inspectOutfit(spec, lock, /* @__PURE__ */ new Set());
13524
13865
  if (spec.character?.parentSpec) {
13525
13866
  const parent = await inspectCharacterParent(spec, lock, /* @__PURE__ */ new Set());
@@ -13538,7 +13879,7 @@ async function inspectStyleAnchor(spec, lock, seen) {
13538
13879
  const label = `style anchor ${spec.styleId}/${anchor.assetId}`;
13539
13880
  const dependency = await inspectParent(anchor.spec, lock, seen);
13540
13881
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13541
- if (!anchor.sha256 || !(0, import_node_fs12.existsSync)(anchor.file)) return { ready: false, reason: `${label} has no generated south-facing file yet` };
13882
+ if (!anchor.sha256 || !(0, import_node_fs14.existsSync)(anchor.file)) return { ready: false, reason: `${label} has no generated south-facing file yet` };
13542
13883
  if (await sha256File(anchor.file) !== anchor.sha256) {
13543
13884
  return { ready: false, reason: `${label} changed after the manifest was resolved` };
13544
13885
  }
@@ -13575,14 +13916,14 @@ async function inspectScene(spec) {
13575
13916
  const files = [{ label: "scene image", file: scene.file, sha256: scene.sha256 }];
13576
13917
  if (scene.placement.type === "mask") files.push({ label: "scene mask", file: scene.placement.file, sha256: scene.placement.sha256 });
13577
13918
  for (const { label, file, sha256: sha2562 } of files) {
13578
- if (!sha2562 || !(0, import_node_fs12.existsSync)(file)) return { ready: false, reason: `${label} does not exist yet: ${file}` };
13919
+ if (!sha2562 || !(0, import_node_fs14.existsSync)(file)) return { ready: false, reason: `${label} does not exist yet: ${file}` };
13579
13920
  if (await sha256File(file) !== sha2562) return { ready: false, reason: `${label} changed after the manifest was resolved` };
13580
13921
  }
13581
13922
  return { ready: true, reason: "scene is current" };
13582
13923
  }
13583
13924
  async function inspectVfxSprite(spec) {
13584
13925
  const sprite = spec.vfx.sprite;
13585
- if (!sprite.sha256 || !(0, import_node_fs12.existsSync)(sprite.file)) return { ready: false, reason: `vfx sprite does not exist yet: ${sprite.file}` };
13926
+ if (!sprite.sha256 || !(0, import_node_fs14.existsSync)(sprite.file)) return { ready: false, reason: `vfx sprite does not exist yet: ${sprite.file}` };
13586
13927
  if (await sha256File(sprite.file) !== sprite.sha256) return { ready: false, reason: "vfx sprite changed after the manifest was resolved" };
13587
13928
  return { ready: true, reason: "vfx sprite is current" };
13588
13929
  }
@@ -13592,13 +13933,22 @@ async function inspectMirror(spec, lock, seen) {
13592
13933
  const dependency = await inspectParent(source, lock, seen);
13593
13934
  return dependency.ready ? { ready: true, reason: `${label} is current` } : { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13594
13935
  }
13936
+ async function inspectDerive(spec, lock, seen) {
13937
+ const source = spec.derive.source;
13938
+ if (source.kind === "file") {
13939
+ return (0, import_node_fs14.existsSync)(import_node_path16.default.resolve(spec.root, source.file)) ? { ready: true, reason: `source file ${source.file} exists` } : { ready: false, reason: `derive source file does not exist: ${source.file}` };
13940
+ }
13941
+ const label = `derive source ${spec.styleId}/${source.assetId}`;
13942
+ const dependency = await inspectParent(source.spec, lock, seen);
13943
+ return dependency.ready ? { ready: true, reason: `${label} is current` } : { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13944
+ }
13595
13945
  async function inspectOutfit(spec, lock, seen) {
13596
13946
  const character = spec.character;
13597
13947
  const outfit = character.outfit;
13598
13948
  const label = `outfit source ${spec.styleId}/${character.parentAssetId}`;
13599
13949
  const dependency = await inspectParent(character.parentSpec, lock, seen);
13600
13950
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13601
- if (!(0, import_node_fs12.existsSync)(outfit.reference.path)) {
13951
+ if (!(0, import_node_fs14.existsSync)(outfit.reference.path)) {
13602
13952
  return { ready: false, reason: `outfit reference is missing: ${outfit.reference.path}` };
13603
13953
  }
13604
13954
  if (await sha256File(outfit.reference.path) !== outfit.reference.sha256) {
@@ -13612,7 +13962,7 @@ async function inspectCharacterParent(spec, lock, seen) {
13612
13962
  const label = `${character.kind} parent ${spec.styleId}/${character.parentAssetId}`;
13613
13963
  const dependency = await inspectParent(parentSpec, lock, seen);
13614
13964
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13615
- if (!character.parentSha256 || !character.parentFile || !(0, import_node_fs12.existsSync)(character.parentFile)) {
13965
+ if (!character.parentSha256 || !character.parentFile || !(0, import_node_fs14.existsSync)(character.parentFile)) {
13616
13966
  return { ready: false, reason: `${label} has no generated south-facing file yet` };
13617
13967
  }
13618
13968
  if (await sha256File(character.parentFile) !== character.parentSha256) {
@@ -13630,7 +13980,7 @@ async function inspectObjectProParent(spec, lock, seen) {
13630
13980
  const label = `${object.kind} parent ${spec.styleId}/${object.parentAssetId}`;
13631
13981
  const dependency = await inspectParent(parentSpec, lock, seen);
13632
13982
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13633
- if (!object.parentSha256 || !object.parentFile || !(0, import_node_fs12.existsSync)(object.parentFile)) {
13983
+ if (!object.parentSha256 || !object.parentFile || !(0, import_node_fs14.existsSync)(object.parentFile)) {
13634
13984
  return { ready: false, reason: `${label} has no generated south-facing file yet` };
13635
13985
  }
13636
13986
  if (await sha256File(object.parentFile) !== object.parentSha256) {
@@ -13656,7 +14006,7 @@ async function inspectRevision(spec, lock, seen) {
13656
14006
  const members = await inspectSourceMembers(spec, lock);
13657
14007
  if (!members.ready) return members;
13658
14008
  } else {
13659
- if (!revision.sourceSha256 || !(0, import_node_fs12.existsSync)(revision.sourceFile)) {
14009
+ if (!revision.sourceSha256 || !(0, import_node_fs14.existsSync)(revision.sourceFile)) {
13660
14010
  return { ready: false, reason: `revision source is missing: ${revision.sourceFile}` };
13661
14011
  }
13662
14012
  if (await sha256File(revision.sourceFile) !== revision.sourceSha256) {
@@ -13664,7 +14014,7 @@ async function inspectRevision(spec, lock, seen) {
13664
14014
  }
13665
14015
  }
13666
14016
  if (revision.maskFile) {
13667
- if (!revision.maskSha256 || !(0, import_node_fs12.existsSync)(revision.maskFile)) {
14017
+ if (!revision.maskSha256 || !(0, import_node_fs14.existsSync)(revision.maskFile)) {
13668
14018
  return { ready: false, reason: `revision mask is missing: ${revision.maskFile}` };
13669
14019
  }
13670
14020
  if (await sha256File(revision.maskFile) !== revision.maskSha256) {
@@ -13672,7 +14022,7 @@ async function inspectRevision(spec, lock, seen) {
13672
14022
  }
13673
14023
  }
13674
14024
  if (revision.lastFrameFile) {
13675
- if (!revision.lastFrameSha256 || !(0, import_node_fs12.existsSync)(revision.lastFrameFile)) {
14025
+ if (!revision.lastFrameSha256 || !(0, import_node_fs14.existsSync)(revision.lastFrameFile)) {
13676
14026
  return { ready: false, reason: `revision last frame is missing: ${revision.lastFrameFile}` };
13677
14027
  }
13678
14028
  if (await sha256File(revision.lastFrameFile) !== revision.lastFrameSha256) {
@@ -13685,7 +14035,7 @@ async function inspectSourceMembers(spec, lock) {
13685
14035
  const revision = spec.revision;
13686
14036
  const members = revision.sourceMembers;
13687
14037
  for (const member of members) {
13688
- if (!(0, import_node_fs12.existsSync)(member.file)) return { ready: false, reason: `revision source member is missing: ${member.file}` };
14038
+ if (!(0, import_node_fs14.existsSync)(member.file)) return { ready: false, reason: `revision source member is missing: ${member.file}` };
13689
14039
  if (await sha256File(member.file) !== member.sha256) {
13690
14040
  return { ready: false, reason: `revision source member changed after the manifest was resolved: ${member.file}` };
13691
14041
  }
@@ -13694,8 +14044,8 @@ async function inspectSourceMembers(spec, lock) {
13694
14044
  if (parent.source) return { ready: true, reason: "declared source set is present" };
13695
14045
  const entry = lock.entries[lockKey(parent.styleId, parent.assetId)];
13696
14046
  if (!entry) return { ready: false, reason: "revision source is not in the lockfile" };
13697
- const recorded = entry.outputs.map((_, index) => import_node_path14.default.resolve(currentEntryOutputPath(entry, parent, index))).sort();
13698
- const found = members.map((member) => import_node_path14.default.resolve(member.file)).sort();
14047
+ const recorded = entry.outputs.map((_, index) => import_node_path16.default.resolve(currentEntryOutputPath(entry, parent, index))).sort();
14048
+ const found = members.map((member) => import_node_path16.default.resolve(member.file)).sort();
13699
14049
  if (recorded.length !== found.length || recorded.some((file, index) => file !== found[index])) {
13700
14050
  return {
13701
14051
  ready: false,
@@ -13709,10 +14059,10 @@ async function requireRevisionReady(spec, lock) {
13709
14059
  if (inspection && !inspection.ready) throw new Error(inspection.reason);
13710
14060
  }
13711
14061
  async function inspectParent(spec, lock, seen) {
13712
- const key = lockKey(spec.styleId, spec.assetId);
13713
- if (seen.has(key)) return { ready: false, reason: `revision dependency cycle at ${key}` };
14062
+ const key2 = lockKey(spec.styleId, spec.assetId);
14063
+ if (seen.has(key2)) return { ready: false, reason: `revision dependency cycle at ${key2}` };
13714
14064
  const nextSeen = new Set(seen);
13715
- nextSeen.add(key);
14065
+ nextSeen.add(key2);
13716
14066
  if (spec.mirror) {
13717
14067
  const inputs = await inspectMirror(spec, lock, nextSeen);
13718
14068
  if (!inputs.ready) return inputs;
@@ -13752,10 +14102,10 @@ async function inspectParent(spec, lock, seen) {
13752
14102
  };
13753
14103
  }
13754
14104
  if (spec.source) {
13755
- const source = import_node_path14.default.resolve(spec.root, spec.source);
13756
- return (0, import_node_fs12.existsSync)(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
14105
+ const source = import_node_path16.default.resolve(spec.root, spec.source);
14106
+ return (0, import_node_fs14.existsSync)(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
13757
14107
  }
13758
- const entry = lock.entries[key];
14108
+ const entry = lock.entries[key2];
13759
14109
  if (!entry) return { ready: false, reason: "parent is not in the lockfile" };
13760
14110
  if (entry.specHash !== spec.specHash) {
13761
14111
  return { ready: false, reason: "parent generation spec is stale" };
@@ -13767,7 +14117,7 @@ async function inspectParent(spec, lock, seen) {
13767
14117
  for (let index = 0; index < entry.outputs.length; index++) {
13768
14118
  const output = entry.outputs[index];
13769
14119
  const file = currentEntryOutputPath(entry, spec, index);
13770
- if (!(0, import_node_fs12.existsSync)(file)) return { ready: false, reason: `parent output is missing: ${file}` };
14120
+ if (!(0, import_node_fs14.existsSync)(file)) return { ready: false, reason: `parent output is missing: ${file}` };
13771
14121
  if (await sha256File(file) !== output.sha256) {
13772
14122
  return { ready: false, reason: `parent output was modified: ${file}` };
13773
14123
  }
@@ -13786,6 +14136,7 @@ async function anyOutputModified(entry, spec) {
13786
14136
  function dependencies(spec) {
13787
14137
  return [
13788
14138
  spec.mirror?.sourceSpec,
14139
+ spec.derive?.source.kind === "asset" ? spec.derive.source.spec : void 0,
13789
14140
  spec.revision?.sourceSpec,
13790
14141
  spec.character?.parentSpec,
13791
14142
  spec.character?.motionLeader?.spec,
@@ -13829,15 +14180,15 @@ function resumeCommandForStatus(status) {
13829
14180
  function resumeActions(specs, lock) {
13830
14181
  const grouped = /* @__PURE__ */ new Map();
13831
14182
  for (const spec of specs) {
13832
- const key = lockKey(spec.styleId, spec.assetId);
13833
- const entry = lock.entries[key];
14183
+ const key2 = lockKey(spec.styleId, spec.assetId);
14184
+ const entry = lock.entries[key2];
13834
14185
  if (!entry || entry.specHash !== spec.specHash) continue;
13835
14186
  if (entry.submissionComplete === false) continue;
13836
14187
  const command = resumeCommandForStatus(entry.status) ?? (entry.status === "downloaded" && entry.outputs.length && !postprocessCurrent(entry, spec) ? "fetch" : null);
13837
14188
  if (!command) continue;
13838
14189
  if (command === "poll" && !entry.jobId) continue;
13839
14190
  if (command === "pick" && !entry.reviewObjectId) continue;
13840
- grouped.set(command, [...grouped.get(command) ?? [], key]);
14191
+ grouped.set(command, [...grouped.get(command) ?? [], key2]);
13841
14192
  }
13842
14193
  return ["poll", "pick", "fetch"].flatMap((command) => {
13843
14194
  const keys = grouped.get(command);
@@ -13847,22 +14198,26 @@ function resumeActions(specs, lock) {
13847
14198
  async function buildPlan(specs, lock, opts = {}) {
13848
14199
  const items = [];
13849
14200
  for (const spec of specs) {
13850
- const key = lockKey(spec.styleId, spec.assetId);
13851
- const entry = lock.entries[key];
14201
+ const key2 = lockKey(spec.styleId, spec.assetId);
14202
+ const entry = lock.entries[key2];
13852
14203
  let state;
13853
14204
  let reason;
13854
14205
  const changedConnection = entry ? changedTerrainConnection(spec, entry, lock) : null;
13855
14206
  const changedMotion = entry ? changedMotionLeader(spec, entry, lock) : null;
13856
14207
  const changedSettings = entry ? changedTerrainSettings(spec, entry) : null;
14208
+ const derivedStale = spec.derive && entry ? await deriveStale(spec, entry, lock) : null;
13857
14209
  const revision = await inspectRevisionReadiness(spec, lock);
13858
14210
  if (revision && !revision.ready) {
13859
14211
  state = "blocked";
13860
14212
  reason = revision.reason;
14213
+ } else if (spec.external) {
14214
+ ;
14215
+ ({ state, reason } = await inspectExternal(spec, entry));
13861
14216
  } else if (opts.force) {
13862
14217
  state = "missing";
13863
14218
  reason = "--force";
13864
14219
  } else if (!entry && spec.source && spec.generator !== "frames" && spec.generator !== "vfx") {
13865
- if ((0, import_node_fs13.existsSync)(import_node_path15.default.resolve(spec.root, spec.source))) {
14220
+ if ((0, import_node_fs15.existsSync)(import_node_path17.default.resolve(spec.root, spec.source))) {
13866
14221
  state = "ok";
13867
14222
  reason = `placed from ${spec.source}; not generated`;
13868
14223
  } else {
@@ -13870,20 +14225,26 @@ async function buildPlan(specs, lock, opts = {}) {
13870
14225
  reason = `declared source is missing: ${spec.source}`;
13871
14226
  }
13872
14227
  } else if (!entry) {
13873
- if ((0, import_node_fs13.existsSync)(spec.outFile)) {
14228
+ if ((0, import_node_fs15.existsSync)(spec.outFile)) {
13874
14229
  state = "untracked";
13875
14230
  reason = "file on disk, no provenance recorded";
13876
14231
  } else {
13877
14232
  state = "missing";
13878
- reason = spec.mirror ? `not made yet; flipped from ${spec.mirror.sourceAssetId} (no generation cost)` : "not in lockfile";
14233
+ 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";
13879
14234
  }
13880
14235
  } else if (entry.specHash !== spec.specHash) {
13881
14236
  state = "stale";
13882
- reason = "prompt, size, or style changed";
14237
+ reason = spec.derive ? "transform, its parameters, or the source file changed; derive it again (no generation cost)" : "prompt, size, or style changed";
14238
+ } else if (derivedStale) {
14239
+ state = "stale";
14240
+ reason = `${derivedStale}; derive it again (no generation cost)`;
14241
+ } else if (spec.derive && entry.status === "downloaded" && entry.outputs.some((_output, index) => !(0, import_node_fs15.existsSync)(currentEntryOutputPath(entry, spec, index)))) {
14242
+ state = "stale";
14243
+ reason = "derived output missing on disk; derive it again (no generation cost)";
13883
14244
  } else if (spec.mirror && !mirrorCurrent(entry, lock.entries[lockKey(spec.styleId, spec.mirror.sourceAssetId)])) {
13884
14245
  state = "stale";
13885
14246
  reason = `mirror source ${spec.mirror.sourceAssetId} changed; flip it again (no generation cost)`;
13886
- } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !(0, import_node_fs13.existsSync)(currentEntryOutputPath(entry, spec, index)))) {
14247
+ } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !(0, import_node_fs15.existsSync)(currentEntryOutputPath(entry, spec, index)))) {
13887
14248
  state = "stale";
13888
14249
  reason = "mirror output missing on disk; flip it again (no generation cost)";
13889
14250
  } else if (spec.character?.kind === "outfit" && entry.outfit?.sourceSha256 !== mirrorSourceHash(lock.entries[lockKey(spec.styleId, spec.character.parentAssetId)] ?? { outputs: [] })) {
@@ -13920,12 +14281,15 @@ async function buildPlan(specs, lock, opts = {}) {
13920
14281
  } else if (entry.status !== "downloaded") {
13921
14282
  state = "in-flight";
13922
14283
  reason = `awaiting ${entry.status}`;
13923
- } else if (entry.outputs.length === 0 || entry.outputs.some((_output, index) => !(0, import_node_fs13.existsSync)(currentEntryOutputPath(entry, spec, index)))) {
14284
+ } else if (entry.outputs.length === 0 || entry.outputs.some((_output, index) => !(0, import_node_fs15.existsSync)(currentEntryOutputPath(entry, spec, index)))) {
13924
14285
  state = "orphaned";
13925
- reason = entry.outputs.length === 0 ? "no recorded output files" : `missing on disk: ${entry.outputs.filter((_output, index) => !(0, import_node_fs13.existsSync)(currentEntryOutputPath(entry, spec, index))).map((o) => o.role ?? "asset").join(", ")}`;
14286
+ reason = entry.outputs.length === 0 ? "no recorded output files" : `missing on disk: ${entry.outputs.filter((_output, index) => !(0, import_node_fs15.existsSync)(currentEntryOutputPath(entry, spec, index))).map((o) => o.role ?? "asset").join(", ")}`;
13926
14287
  } else if (await anyOutputModified(entry, spec)) {
13927
14288
  state = "orphaned";
13928
14289
  reason = "output modified since download";
14290
+ } else if (spec.derive) {
14291
+ state = "ok";
14292
+ reason = "up to date";
13929
14293
  } else if (spec.mirror && !postprocessCurrent(entry, spec)) {
13930
14294
  state = "stale";
13931
14295
  reason = "palette enforcement changed; flip the source again once it is refreshed (no generation cost)";
@@ -13937,7 +14301,7 @@ async function buildPlan(specs, lock, opts = {}) {
13937
14301
  reason = "up to date";
13938
14302
  }
13939
14303
  const quality = await inspectQualityProfile(spec, lock);
13940
- items.push({ spec, key, state, reason, ...quality ? { quality } : {} });
14304
+ items.push({ spec, key: key2, state, reason, ...quality ? { quality } : {} });
13941
14305
  }
13942
14306
  const isActionable = (i) => i.state === "missing" || i.state === "stale" || i.state === "failed";
13943
14307
  const stateOf = new Map(items.map((i) => [i.key, i.state]));
@@ -13951,7 +14315,7 @@ async function buildPlan(specs, lock, opts = {}) {
13951
14315
  item.reason = `parent ${parentKey} is being generated in this run; this follows in the next wave`;
13952
14316
  break;
13953
14317
  }
13954
- if (item.spec.mirror && (parentState === "recoverable" || parentState === "in-flight")) {
14318
+ if ((item.spec.mirror || item.spec.derive) && (parentState === "recoverable" || parentState === "in-flight")) {
13955
14319
  item.state = "blocked";
13956
14320
  item.reason = `mirror source ${parentKey} is ${parentState}; this follows in the next wave`;
13957
14321
  break;
@@ -13972,6 +14336,12 @@ async function buildPlan(specs, lock, opts = {}) {
13972
14336
  const provider = item.spec.provider;
13973
14337
  const costUnit = item.spec.costUnit ?? "generations";
13974
14338
  const group = groupsByProvider.get(provider);
14339
+ if (group && item.spec.derive) {
14340
+ group.actionable.push(item);
14341
+ group.candidates += item.spec.candidates;
14342
+ continue;
14343
+ }
14344
+ if (group && group.cost === 0 && group.actionable.every((other) => other.spec.derive)) group.costUnit = costUnit;
13975
14345
  if (group && group.costUnit !== costUnit) {
13976
14346
  throw new Error(
13977
14347
  `Provider "${provider}" returned mixed cost units (${group.costUnit}, ${costUnit})`
@@ -14021,13 +14391,13 @@ function summarize(plan) {
14021
14391
 
14022
14392
  // src/project.ts
14023
14393
  async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {}) {
14024
- const absolute = import_node_path16.default.resolve(manifestPath);
14025
- const root = import_node_path16.default.dirname(absolute);
14394
+ const absolute = import_node_path18.default.resolve(manifestPath);
14395
+ const root = import_node_path18.default.dirname(absolute);
14026
14396
  if (opts.env !== false) {
14027
14397
  loadEnvFiles(root);
14028
- if (import_node_path16.default.resolve(process.cwd()) !== root) loadEnvFiles(process.cwd());
14398
+ if (import_node_path18.default.resolve(process.cwd()) !== root) loadEnvFiles(process.cwd());
14029
14399
  }
14030
- const lockPath = import_node_path16.default.resolve(opts.lockPath ?? import_node_path16.default.join(root, "pixelkiln.lock.json"));
14400
+ const lockPath = import_node_path18.default.resolve(opts.lockPath ?? import_node_path18.default.join(root, "pixelkiln.lock.json"));
14031
14401
  let loaded = await loadManifest(absolute, { lenient: opts.lenient });
14032
14402
  const unresolved = [];
14033
14403
  const specs = await resolveSpecs(loaded, {
@@ -14051,11 +14421,11 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
14051
14421
  reload: () => openProject(absolute, { ...opts, env: false }),
14052
14422
  providers: () => [...new Set(specs.map((spec) => spec.provider))].sort(),
14053
14423
  provider: (id, mode2 = "online") => {
14054
- const key = `${mode2}:${id}`;
14055
- let adapter = adapters.get(key);
14424
+ const key2 = `${mode2}:${id}`;
14425
+ let adapter = adapters.get(key2);
14056
14426
  if (!adapter) {
14057
14427
  adapter = createProvider(id, mode2);
14058
- adapters.set(key, adapter);
14428
+ adapters.set(key2, adapter);
14059
14429
  }
14060
14430
  return adapter;
14061
14431
  }
@@ -14063,9 +14433,9 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
14063
14433
  }
14064
14434
 
14065
14435
  // src/recipes.ts
14066
- var import_node_path17 = __toESM(require("path"), 1);
14067
- var import_node_fs14 = require("fs");
14068
- var import_promises9 = require("fs/promises");
14436
+ var import_node_path19 = __toESM(require("path"), 1);
14437
+ var import_node_fs16 = require("fs");
14438
+ var import_promises10 = require("fs/promises");
14069
14439
  var import_node_url = require("url");
14070
14440
  var import_zod4 = require("zod");
14071
14441
  var SHA256_RE = /^[0-9a-f]{64}$/;
@@ -14074,7 +14444,7 @@ var VERSION_RE = /^\d+\.\d+\.\d+$/;
14074
14444
  var RECIPE_FILE = "pixelkiln.recipe.json";
14075
14445
  var RECIPE_DIR_TOKEN = "{{recipeDir}}";
14076
14446
  var PortablePathSchema = import_zod4.z.string().min(1).refine((value) => {
14077
- if (value.includes("\\") || import_node_path17.default.posix.isAbsolute(value)) return false;
14447
+ if (value.includes("\\") || import_node_path19.default.posix.isAbsolute(value)) return false;
14078
14448
  const parts = value.split("/");
14079
14449
  return !parts.includes("") && !parts.includes(".") && !parts.includes("..");
14080
14450
  }, "expected a portable relative path without '.', '..', or backslashes");
@@ -14234,9 +14604,9 @@ function canonical3(value) {
14234
14604
  if (Array.isArray(value)) return value.map(canonical3);
14235
14605
  if (typeof value === "object") {
14236
14606
  const sorted = {};
14237
- for (const key of Object.keys(value).sort()) {
14238
- const item = value[key];
14239
- if (item !== void 0) sorted[key] = canonical3(item);
14607
+ for (const key2 of Object.keys(value).sort()) {
14608
+ const item = value[key2];
14609
+ if (item !== void 0) sorted[key2] = canonical3(item);
14240
14610
  }
14241
14611
  return sorted;
14242
14612
  }
@@ -14250,10 +14620,10 @@ function message3(error) {
14250
14620
  return error instanceof Error ? error.message : String(error);
14251
14621
  }
14252
14622
  async function readRecipeFile(recipePath, bundled) {
14253
- const absolute = import_node_path17.default.resolve(recipePath);
14623
+ const absolute = import_node_path19.default.resolve(recipePath);
14254
14624
  let raw;
14255
14625
  try {
14256
- raw = JSON.parse(await (0, import_promises9.readFile)(absolute, "utf8"));
14626
+ raw = JSON.parse(await (0, import_promises10.readFile)(absolute, "utf8"));
14257
14627
  } catch (error) {
14258
14628
  throw new Error(`Could not read recipe ${absolute}: ${message3(error)}`, { cause: error });
14259
14629
  }
@@ -14264,13 +14634,13 @@ async function readRecipeFile(recipePath, bundled) {
14264
14634
  ` + parsed.error.issues.map((issue) => ` ${issue.path.join(".") || "$"}: ${issue.message}`).join("\n")
14265
14635
  );
14266
14636
  }
14267
- return { recipe: parsed.data, authored: raw, path: absolute, dir: import_node_path17.default.dirname(absolute), bundled };
14637
+ return { recipe: parsed.data, authored: raw, path: absolute, dir: import_node_path19.default.dirname(absolute), bundled };
14268
14638
  }
14269
14639
  async function walkRecipeFiles(root) {
14270
- if (!(0, import_node_fs14.existsSync)(root)) return [];
14640
+ if (!(0, import_node_fs16.existsSync)(root)) return [];
14271
14641
  const out = [];
14272
- for (const entry of await (0, import_promises9.readdir)(root, { withFileTypes: true })) {
14273
- const resolved = import_node_path17.default.join(root, entry.name);
14642
+ for (const entry of await (0, import_promises10.readdir)(root, { withFileTypes: true })) {
14643
+ const resolved = import_node_path19.default.join(root, entry.name);
14274
14644
  if (entry.isDirectory()) out.push(...await walkRecipeFiles(resolved));
14275
14645
  else if (entry.isFile() && entry.name === RECIPE_FILE) out.push(resolved);
14276
14646
  }
@@ -14281,7 +14651,7 @@ function bundledRecipeRoot() {
14281
14651
  }
14282
14652
  async function listBundledRecipes(root = bundledRecipeRoot()) {
14283
14653
  const recipes = await Promise.all(
14284
- (await walkRecipeFiles(import_node_path17.default.resolve(root))).map((file) => readRecipeFile(file, true))
14654
+ (await walkRecipeFiles(import_node_path19.default.resolve(root))).map((file) => readRecipeFile(file, true))
14285
14655
  );
14286
14656
  return recipes.sort(
14287
14657
  (a, b) => a.recipe.id.localeCompare(b.recipe.id) || compareVersions(b.recipe.version, a.recipe.version)
@@ -14304,9 +14674,9 @@ function parseSelector(selector) {
14304
14674
  return { id: match[1], version: match[2] };
14305
14675
  }
14306
14676
  async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
14307
- const local = import_node_path17.default.resolve(target);
14308
- if ((0, import_node_fs14.existsSync)(local)) {
14309
- const recipePath = import_node_path17.default.basename(local) === RECIPE_FILE ? local : import_node_path17.default.join(local, RECIPE_FILE);
14677
+ const local = import_node_path19.default.resolve(target);
14678
+ if ((0, import_node_fs16.existsSync)(local)) {
14679
+ const recipePath = import_node_path19.default.basename(local) === RECIPE_FILE ? local : import_node_path19.default.join(local, RECIPE_FILE);
14310
14680
  return readRecipeFile(recipePath, false);
14311
14681
  }
14312
14682
  if (target.startsWith(".") || target.startsWith("/") || target.includes("\\")) {
@@ -14320,8 +14690,8 @@ async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
14320
14690
  return matches[0];
14321
14691
  }
14322
14692
  async function verifyFile(root, file) {
14323
- const absolute = import_node_path17.default.resolve(root, ...file.path.split("/"));
14324
- if (!(0, import_node_fs14.existsSync)(absolute)) {
14693
+ const absolute = import_node_path19.default.resolve(root, ...file.path.split("/"));
14694
+ if (!(0, import_node_fs16.existsSync)(absolute)) {
14325
14695
  return { path: file.path, expectedSha256: file.sha256, actualSha256: null, status: "missing" };
14326
14696
  }
14327
14697
  const actualSha256 = await sha256File(absolute);
@@ -14336,7 +14706,7 @@ async function verifyRecipe(target, options = {}) {
14336
14706
  const loaded = await resolveRecipe(target, options.bundledRoot);
14337
14707
  const actualIntegrity = recipeDigest(loaded.authored);
14338
14708
  const files = await Promise.all(loaded.recipe.files.map((file) => verifyFile(loaded.dir, file)));
14339
- const modelRoot = options.modelRoot ? import_node_path17.default.resolve(options.modelRoot) : null;
14709
+ const modelRoot = options.modelRoot ? import_node_path19.default.resolve(options.modelRoot) : null;
14340
14710
  const models = modelRoot ? await Promise.all(loaded.recipe.models.map(async (model) => ({
14341
14711
  ...await verifyFile(modelRoot, model),
14342
14712
  source: model.source,
@@ -14370,37 +14740,37 @@ async function verifyRecipe(target, options = {}) {
14370
14740
  };
14371
14741
  }
14372
14742
  function renderStyle(style, destination, cwd) {
14373
- const portableDir = import_node_path17.default.relative(cwd, destination).split(import_node_path17.default.sep).join("/") || ".";
14743
+ const portableDir = import_node_path19.default.relative(cwd, destination).split(import_node_path19.default.sep).join("/") || ".";
14374
14744
  const replace = (value) => {
14375
14745
  if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
14376
14746
  if (Array.isArray(value)) return value.map(replace);
14377
14747
  if (value && typeof value === "object") {
14378
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, replace(item)]));
14748
+ return Object.fromEntries(Object.entries(value).map(([key2, item]) => [key2, replace(item)]));
14379
14749
  }
14380
14750
  return value;
14381
14751
  };
14382
14752
  return replace(style);
14383
14753
  }
14384
14754
  async function installRecipe(target, options = {}) {
14385
- const cwd = import_node_path17.default.resolve(options.cwd ?? process.cwd());
14755
+ const cwd = import_node_path19.default.resolve(options.cwd ?? process.cwd());
14386
14756
  const loaded = await resolveRecipe(target, options.bundledRoot);
14387
14757
  const verification = await verifyRecipe(loaded.path);
14388
14758
  if (!verification.ok) {
14389
14759
  throw new Error(`Recipe ${loaded.recipe.id}@${loaded.recipe.version} failed integrity verification.`);
14390
14760
  }
14391
- const destination = options.out ? import_node_path17.default.resolve(cwd, options.out) : import_node_path17.default.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
14761
+ const destination = options.out ? import_node_path19.default.resolve(cwd, options.out) : import_node_path19.default.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
14392
14762
  const sources = [
14393
14763
  { path: RECIPE_FILE, source: loaded.path },
14394
- ...loaded.recipe.files.map((file) => ({ path: file.path, source: import_node_path17.default.join(loaded.dir, ...file.path.split("/")) }))
14764
+ ...loaded.recipe.files.map((file) => ({ path: file.path, source: import_node_path19.default.join(loaded.dir, ...file.path.split("/")) }))
14395
14765
  ];
14396
14766
  const files = await Promise.all(sources.map(async (file) => ({
14397
- path: import_node_path17.default.join(destination, ...file.path.split("/")),
14398
- data: await (0, import_promises9.readFile)(file.source)
14767
+ path: import_node_path19.default.join(destination, ...file.path.split("/")),
14768
+ data: await (0, import_promises10.readFile)(file.source)
14399
14769
  })));
14400
14770
  if (!options.force) {
14401
14771
  for (const file of files) {
14402
- if (!(0, import_node_fs14.existsSync)(file.path)) continue;
14403
- const current = await (0, import_promises9.readFile)(file.path);
14772
+ if (!(0, import_node_fs16.existsSync)(file.path)) continue;
14773
+ const current = await (0, import_promises10.readFile)(file.path);
14404
14774
  if (!current.equals(file.data)) {
14405
14775
  throw new OverwriteRefusedError(
14406
14776
  `Recipe destination has local changes: ${file.path}. Choose another --out or pass --force to replace declared recipe files.`,
@@ -14424,9 +14794,9 @@ async function installRecipe(target, options = {}) {
14424
14794
  }
14425
14795
 
14426
14796
  // src/pipeline/audit.ts
14427
- var import_promises10 = require("fs/promises");
14428
- var import_node_fs15 = require("fs");
14429
- var import_node_path18 = __toESM(require("path"), 1);
14797
+ var import_promises11 = require("fs/promises");
14798
+ var import_node_fs17 = require("fs");
14799
+ var import_node_path20 = __toESM(require("path"), 1);
14430
14800
  function paletteDistance(asset, reference) {
14431
14801
  if (!asset.length || !reference.length) return 0;
14432
14802
  let total = 0;
@@ -14443,10 +14813,10 @@ function mergePalettes(palettes, topN = 24) {
14443
14813
  const totals = /* @__PURE__ */ new Map();
14444
14814
  for (const palette of palettes) {
14445
14815
  for (const color of palette) {
14446
- const key = `${color.r},${color.g},${color.b}`;
14447
- const existing = totals.get(key);
14816
+ const key2 = `${color.r},${color.g},${color.b}`;
14817
+ const existing = totals.get(key2);
14448
14818
  if (existing) existing.weight += color.weight;
14449
- else totals.set(key, { ...color });
14819
+ else totals.set(key2, { ...color });
14450
14820
  }
14451
14821
  }
14452
14822
  const merged = [...totals.values()].sort((a, b) => b.weight - a.weight).slice(0, topN);
@@ -14462,12 +14832,12 @@ async function auditStyle(loaded, specs, styleId, lock) {
14462
14832
  const unreadable = [];
14463
14833
  for (const spec of mine) {
14464
14834
  for (const output of resolveSpecOutputs(spec, lock, loaded.root)) {
14465
- if (!(0, import_node_fs15.existsSync)(output.absolutePath)) {
14835
+ if (!(0, import_node_fs17.existsSync)(output.absolutePath)) {
14466
14836
  missing.push(output.id);
14467
14837
  continue;
14468
14838
  }
14469
14839
  try {
14470
- const png = decodePng(await (0, import_promises10.readFile)(output.absolutePath));
14840
+ const png = decodePng(await (0, import_promises11.readFile)(output.absolutePath));
14471
14841
  const palette = extractPalette(png, 12);
14472
14842
  assets.push({
14473
14843
  assetId: spec.assetId,
@@ -14491,10 +14861,10 @@ async function auditStyle(loaded, specs, styleId, lock) {
14491
14861
  let referenceFromStyleImages = false;
14492
14862
  const refPalettes = [];
14493
14863
  for (const img of style.styleImages) {
14494
- const abs = import_node_path18.default.resolve(loaded.root, img.path);
14495
- if (!(0, import_node_fs15.existsSync)(abs)) continue;
14864
+ const abs = import_node_path20.default.resolve(loaded.root, img.path);
14865
+ if (!(0, import_node_fs17.existsSync)(abs)) continue;
14496
14866
  try {
14497
- refPalettes.push(extractPalette(decodePng(await (0, import_promises10.readFile)(abs)), 12));
14867
+ refPalettes.push(extractPalette(decodePng(await (0, import_promises11.readFile)(abs)), 12));
14498
14868
  } catch {
14499
14869
  }
14500
14870
  }
@@ -14570,15 +14940,15 @@ function hex(c) {
14570
14940
  }
14571
14941
 
14572
14942
  // src/pipeline/quality-regression.ts
14573
- var import_node_path19 = __toESM(require("path"), 1);
14574
- var import_node_fs16 = require("fs");
14575
- var import_promises11 = require("fs/promises");
14943
+ var import_node_path21 = __toESM(require("path"), 1);
14944
+ var import_node_fs18 = require("fs");
14945
+ var import_promises12 = require("fs/promises");
14576
14946
  var import_zod5 = require("zod");
14577
14947
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
14578
14948
  var HEX_RE = /^#[0-9a-f]{6}$/;
14579
14949
  var MAX_REDMEAN_DISTANCE = 765;
14580
14950
  var QualityPathSchema = import_zod5.z.string().min(1).refine(
14581
- (value) => !import_node_path19.default.posix.isAbsolute(value) && !value.includes("\\"),
14951
+ (value) => !import_node_path21.default.posix.isAbsolute(value) && !value.includes("\\"),
14582
14952
  "expected a portable relative path"
14583
14953
  );
14584
14954
  var DEFAULT_QUALITY_TOLERANCES = {
@@ -14680,8 +15050,8 @@ function measureDecodedImageQuality(png, digest2) {
14680
15050
  const index = offset / 4;
14681
15051
  const x = index % png.width;
14682
15052
  const y = Math.floor(index / png.width);
14683
- const key = pixelKey(png.pixels, offset);
14684
- 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;
15053
+ const key2 = pixelKey(png.pixels, offset);
15054
+ 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;
14685
15055
  if (!hasSameNeighbor) {
14686
15056
  isolated++;
14687
15057
  }
@@ -14725,10 +15095,10 @@ function measureDecodedImageQuality(png, digest2) {
14725
15095
  };
14726
15096
  }
14727
15097
  async function measureImageQuality(file) {
14728
- const absolute = import_node_path19.default.resolve(file);
15098
+ const absolute = import_node_path21.default.resolve(file);
14729
15099
  let bytes;
14730
15100
  try {
14731
- bytes = await (0, import_promises11.readFile)(absolute);
15101
+ bytes = await (0, import_promises12.readFile)(absolute);
14732
15102
  } catch (error) {
14733
15103
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
14734
15104
  }
@@ -14747,11 +15117,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
14747
15117
  }
14748
15118
  const ids = parsed.data.map((entry) => entry.id);
14749
15119
  if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
14750
- const root = import_node_path19.default.dirname(import_node_path19.default.resolve(inputsFilePath));
15120
+ const root = import_node_path21.default.dirname(import_node_path21.default.resolve(inputsFilePath));
14751
15121
  return parsed.data.map((entry) => ({
14752
15122
  id: entry.id,
14753
- file: import_node_path19.default.resolve(root, entry.path),
14754
- ...entry.record ? { record: import_node_path19.default.resolve(root, entry.record) } : {},
15123
+ file: import_node_path21.default.resolve(root, entry.path),
15124
+ ...entry.record ? { record: import_node_path21.default.resolve(root, entry.record) } : {},
14755
15125
  tolerances: QualityToleranceSchema.parse({
14756
15126
  ...DEFAULT_QUALITY_TOLERANCES,
14757
15127
  ...entry.tolerances
@@ -14759,7 +15129,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
14759
15129
  }));
14760
15130
  }
14761
15131
  function portableRelative2(from, to) {
14762
- return import_node_path19.default.relative(from, import_node_path19.default.resolve(to)).split(import_node_path19.default.sep).join("/") || ".";
15132
+ return import_node_path21.default.relative(from, import_node_path21.default.resolve(to)).split(import_node_path21.default.sep).join("/") || ".";
14763
15133
  }
14764
15134
  async function verifyRecordForImage(recordPath, imagePath) {
14765
15135
  const verification = await verifyArtifactBundle(recordPath);
@@ -14774,20 +15144,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
14774
15144
  if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
14775
15145
  throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
14776
15146
  }
14777
- const outputs = record.outputs.map((output) => import_node_path19.default.resolve(import_node_path19.default.dirname(recordPath), output.path));
14778
- if (!outputs.includes(import_node_path19.default.resolve(imagePath))) {
15147
+ const outputs = record.outputs.map((output) => import_node_path21.default.resolve(import_node_path21.default.dirname(recordPath), output.path));
15148
+ if (!outputs.includes(import_node_path21.default.resolve(imagePath))) {
14779
15149
  throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
14780
15150
  }
14781
15151
  }
14782
15152
  async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14783
15153
  if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
14784
- const absolute = import_node_path19.default.resolve(baselinePath);
15154
+ const absolute = import_node_path21.default.resolve(baselinePath);
14785
15155
  for (const input of inputs) {
14786
- if (import_node_path19.default.resolve(input.file) === absolute || input.record && import_node_path19.default.resolve(input.record) === absolute) {
15156
+ if (import_node_path21.default.resolve(input.file) === absolute || input.record && import_node_path21.default.resolve(input.record) === absolute) {
14787
15157
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
14788
15158
  }
14789
15159
  }
14790
- const root = import_node_path19.default.dirname(absolute);
15160
+ const root = import_node_path21.default.dirname(absolute);
14791
15161
  const cases = [];
14792
15162
  for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
14793
15163
  const expected = await measureImageQuality(input.file);
@@ -14814,8 +15184,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14814
15184
  cases
14815
15185
  });
14816
15186
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
14817
- if ((0, import_node_fs16.existsSync)(absolute) && !options.force) {
14818
- const current = await (0, import_promises11.readFile)(absolute);
15187
+ if ((0, import_node_fs18.existsSync)(absolute) && !options.force) {
15188
+ const current = await (0, import_promises12.readFile)(absolute);
14819
15189
  if (!current.equals(data)) {
14820
15190
  throw new OverwriteRefusedError(
14821
15191
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -14827,13 +15197,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14827
15197
  return { baseline, path: absolute, changed: result.changed.length > 0 };
14828
15198
  }
14829
15199
  async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14830
- const absolute = import_node_path19.default.resolve(baselinePath);
14831
- if (!(0, import_node_fs16.existsSync)(absolute)) {
15200
+ const absolute = import_node_path21.default.resolve(baselinePath);
15201
+ if (!(0, import_node_fs18.existsSync)(absolute)) {
14832
15202
  throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
14833
15203
  }
14834
15204
  let raw;
14835
15205
  try {
14836
- raw = JSON.parse(await (0, import_promises11.readFile)(absolute, "utf8"));
15206
+ raw = JSON.parse(await (0, import_promises12.readFile)(absolute, "utf8"));
14837
15207
  } catch (error) {
14838
15208
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
14839
15209
  }
@@ -14843,12 +15213,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14843
15213
  if (unknown.length) {
14844
15214
  throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
14845
15215
  }
14846
- const root = import_node_path19.default.dirname(absolute);
15216
+ const root = import_node_path21.default.dirname(absolute);
14847
15217
  const cases = [...raw.cases];
14848
15218
  const report = [];
14849
15219
  for (const id of only) {
14850
15220
  const input = byId.get(id);
14851
- if (import_node_path19.default.resolve(input.file) === absolute || input.record && import_node_path19.default.resolve(input.record) === absolute) {
15221
+ if (import_node_path21.default.resolve(input.file) === absolute || input.record && import_node_path21.default.resolve(input.record) === absolute) {
14852
15222
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
14853
15223
  }
14854
15224
  const expected = await measureImageQuality(input.file);
@@ -14878,16 +15248,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14878
15248
  }
14879
15249
  const baseline = QualityBaselineSchema.parse({ ...raw, cases });
14880
15250
  const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
14881
- const current = await (0, import_promises11.readFile)(absolute);
15251
+ const current = await (0, import_promises12.readFile)(absolute);
14882
15252
  const changed = !current.equals(data);
14883
15253
  if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
14884
15254
  return { baseline, path: absolute, changed, cases: report };
14885
15255
  }
14886
15256
  async function readQualityBaseline(baselinePath) {
14887
- const absolute = import_node_path19.default.resolve(baselinePath);
15257
+ const absolute = import_node_path21.default.resolve(baselinePath);
14888
15258
  let raw;
14889
15259
  try {
14890
- raw = JSON.parse(await (0, import_promises11.readFile)(absolute, "utf8"));
15260
+ raw = JSON.parse(await (0, import_promises12.readFile)(absolute, "utf8"));
14891
15261
  } catch (error) {
14892
15262
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
14893
15263
  }
@@ -14909,7 +15279,7 @@ async function readQualityBaseline(baselinePath) {
14909
15279
  throw new Error(
14910
15280
  `Invalid quality baseline ${absolute}:
14911
15281
  ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
14912
- Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${import_node_path19.default.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
15282
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${import_node_path21.default.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
14913
15283
  );
14914
15284
  }
14915
15285
  return parsed.data;
@@ -14971,12 +15341,12 @@ function regressionViolations(expected, actual, tolerances) {
14971
15341
  return { violations, warnings };
14972
15342
  }
14973
15343
  async function checkQualityBaseline(baselinePath) {
14974
- const absolute = import_node_path19.default.resolve(baselinePath);
15344
+ const absolute = import_node_path21.default.resolve(baselinePath);
14975
15345
  const baseline = await readQualityBaseline(absolute);
14976
- const root = import_node_path19.default.dirname(absolute);
15346
+ const root = import_node_path21.default.dirname(absolute);
14977
15347
  const cases = [];
14978
15348
  for (const entry of baseline.cases) {
14979
- const file = import_node_path19.default.resolve(root, entry.file);
15349
+ const file = import_node_path21.default.resolve(root, entry.file);
14980
15350
  let actual = null;
14981
15351
  const violations = [];
14982
15352
  const warnings = [];
@@ -14989,7 +15359,7 @@ async function checkQualityBaseline(baselinePath) {
14989
15359
  violations.push(message4(error));
14990
15360
  }
14991
15361
  if (entry.record) {
14992
- const recordPath = import_node_path19.default.resolve(root, entry.record.path);
15362
+ const recordPath = import_node_path21.default.resolve(root, entry.record.path);
14993
15363
  try {
14994
15364
  const recordHash = await sha256File(recordPath);
14995
15365
  if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
@@ -15025,14 +15395,14 @@ async function checkQualityBaseline(baselinePath) {
15025
15395
  }
15026
15396
 
15027
15397
  // src/pipeline/cache-health.ts
15028
- var import_node_fs20 = require("fs");
15029
- var import_promises14 = require("fs/promises");
15030
- var import_node_path23 = __toESM(require("path"), 1);
15398
+ var import_node_fs22 = require("fs");
15399
+ var import_promises15 = require("fs/promises");
15400
+ var import_node_path25 = __toESM(require("path"), 1);
15031
15401
 
15032
15402
  // src/cache.ts
15033
- var import_promises12 = require("fs/promises");
15034
- var import_node_fs17 = require("fs");
15035
- var import_node_path20 = __toESM(require("path"), 1);
15403
+ var import_promises13 = require("fs/promises");
15404
+ var import_node_fs19 = require("fs");
15405
+ var import_node_path22 = __toESM(require("path"), 1);
15036
15406
  var import_zod6 = require("zod");
15037
15407
  var HashCacheSchema = import_zod6.z.object({
15038
15408
  version: import_zod6.z.literal(1),
@@ -15046,10 +15416,10 @@ function isSha256Hash(value) {
15046
15416
  function parseCache(value) {
15047
15417
  return HashCacheSchema.parse(value);
15048
15418
  }
15049
- async function loadCache(path40) {
15050
- if (!(0, import_node_fs17.existsSync)(path40)) return { version: 1, hashes: {} };
15419
+ async function loadCache(path42) {
15420
+ if (!(0, import_node_fs19.existsSync)(path42)) return { version: 1, hashes: {} };
15051
15421
  try {
15052
- const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises12.readFile)(path40, "utf8")));
15422
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises13.readFile)(path42, "utf8")));
15053
15423
  if (!parsed.success) return { version: 1, hashes: {} };
15054
15424
  return {
15055
15425
  version: 1,
@@ -15061,30 +15431,30 @@ async function loadCache(path40) {
15061
15431
  return { version: 1, hashes: {} };
15062
15432
  }
15063
15433
  }
15064
- async function saveCache(path40, cache) {
15434
+ async function saveCache(path42, cache) {
15065
15435
  const sorted = {};
15066
- for (const key of Object.keys(cache.hashes).sort()) {
15067
- const hash = cache.hashes[key];
15068
- if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key}`);
15069
- sorted[key] = hash;
15436
+ for (const key2 of Object.keys(cache.hashes).sort()) {
15437
+ const hash = cache.hashes[key2];
15438
+ if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
15439
+ sorted[key2] = hash;
15070
15440
  }
15071
- await (0, import_promises12.mkdir)(import_node_path20.default.dirname(import_node_path20.default.resolve(path40)), { recursive: true });
15072
- const tmp = `${path40}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
15441
+ await (0, import_promises13.mkdir)(import_node_path22.default.dirname(import_node_path22.default.resolve(path42)), { recursive: true });
15442
+ const tmp = `${path42}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
15073
15443
  try {
15074
- await (0, import_promises12.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
15075
- await (0, import_promises12.rename)(tmp, path40);
15444
+ await (0, import_promises13.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
15445
+ await (0, import_promises13.rename)(tmp, path42);
15076
15446
  } finally {
15077
- await (0, import_promises12.rm)(tmp, { force: true });
15447
+ await (0, import_promises13.rm)(tmp, { force: true });
15078
15448
  }
15079
15449
  }
15080
15450
  function pruneCache(cache, liveIds, namespace = "") {
15081
15451
  let removed = 0;
15082
- for (const key of Object.keys(cache.hashes)) {
15083
- const owned = namespace ? key.startsWith(namespace) : !key.includes(":");
15452
+ for (const key2 of Object.keys(cache.hashes)) {
15453
+ const owned = namespace ? key2.startsWith(namespace) : !key2.includes(":");
15084
15454
  if (!owned) continue;
15085
- const id = namespace ? key.slice(namespace.length) : key;
15455
+ const id = namespace ? key2.slice(namespace.length) : key2;
15086
15456
  if (!liveIds.has(id)) {
15087
- delete cache.hashes[key];
15457
+ delete cache.hashes[key2];
15088
15458
  removed++;
15089
15459
  }
15090
15460
  }
@@ -15096,39 +15466,40 @@ function cachePathFor(lockPath) {
15096
15466
  }
15097
15467
 
15098
15468
  // src/pipeline/history.ts
15099
- var import_node_fs19 = require("fs");
15100
- var import_node_path22 = __toESM(require("path"), 1);
15469
+ var import_node_fs21 = require("fs");
15470
+ var import_node_path24 = __toESM(require("path"), 1);
15101
15471
 
15102
15472
  // src/pipeline/fetch.ts
15103
- var import_node_fs18 = require("fs");
15104
- var import_promises13 = require("fs/promises");
15105
- var import_node_path21 = __toESM(require("path"), 1);
15473
+ var import_node_fs20 = require("fs");
15474
+ var import_promises14 = require("fs/promises");
15475
+ var import_node_path23 = __toESM(require("path"), 1);
15106
15476
  async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15107
15477
  const log = opts.onProgress ?? (() => {
15108
15478
  });
15109
15479
  const result = { downloaded: 0, skipped: 0, failed: 0, ...opts.refresh ? { unchanged: 0 } : {} };
15110
15480
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
15111
15481
  normalizeLockOutputPaths(lock, specs);
15112
- const cacheDir = opts.cacheDir === false ? null : import_node_path21.default.resolve(opts.cacheDir ?? import_node_path21.default.join(import_node_path21.default.dirname(lockPath), ".pixelkiln", "cache"));
15113
- const pending = Object.entries(lock.entries).filter(([key, e]) => {
15114
- if (e.provider !== provider.id || !specByKey.has(key)) return false;
15115
- if (specByKey.get(key)?.mirror) return false;
15482
+ const cacheDir = opts.cacheDir === false ? null : import_node_path23.default.resolve(opts.cacheDir ?? import_node_path23.default.join(import_node_path23.default.dirname(lockPath), ".pixelkiln", "cache"));
15483
+ const pending = Object.entries(lock.entries).filter(([key2, e]) => {
15484
+ if (e.provider !== provider.id || !specByKey.has(key2)) return false;
15485
+ if (specByKey.get(key2)?.mirror) return false;
15486
+ if (specByKey.get(key2)?.derive || specByKey.get(key2)?.external) return false;
15116
15487
  if (e.status === "selected" || e.status === "download-failed") return true;
15117
15488
  if (e.status !== "downloaded") return false;
15118
15489
  if (opts.refresh) return e.outputs.length > 0 && Boolean(e.sourceUrls?.length || e.sourceUrl);
15119
- const spec = specByKey.get(key);
15490
+ const spec = specByKey.get(key2);
15120
15491
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
15121
15492
  return Boolean(opts.force) || e.outputs.every((output) => {
15122
15493
  const file = resolveOutputPath(output.path, spec.root);
15123
- return (0, import_node_fs18.existsSync)(file) && sha256((0, import_node_fs18.readFileSync)(file)) === output.sha256;
15494
+ return (0, import_node_fs20.existsSync)(file) && sha256((0, import_node_fs20.readFileSync)(file)) === output.sha256;
15124
15495
  });
15125
15496
  }
15126
15497
  if (!opts.repair) return false;
15127
15498
  if (e.outputs.length === 0 || !spec) return true;
15128
15499
  return e.outputs.some((output) => {
15129
15500
  const file = resolveOutputPath(output.path, spec.root);
15130
- if (!(0, import_node_fs18.existsSync)(file)) return true;
15131
- const current = sha256((0, import_node_fs18.readFileSync)(file));
15501
+ if (!(0, import_node_fs20.existsSync)(file)) return true;
15502
+ const current = sha256((0, import_node_fs20.readFileSync)(file));
15132
15503
  if (current === output.sha256) return false;
15133
15504
  return Boolean(opts.force) || (e.supersededOutputs ?? []).some((old) => old.sha256 === current);
15134
15505
  });
@@ -15139,15 +15510,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15139
15510
  for (; ; ) {
15140
15511
  const next = pending[cursor++];
15141
15512
  if (!next) return;
15142
- const [key, entry] = next;
15143
- const spec = specByKey.get(key);
15513
+ const [key2, entry] = next;
15514
+ const spec = specByKey.get(key2);
15144
15515
  if (!spec) {
15145
- log(` skip ${key} (not in current manifest)`);
15516
+ log(` skip ${key2} (not in current manifest)`);
15146
15517
  result.skipped++;
15147
15518
  continue;
15148
15519
  }
15149
15520
  if (entry.specHash !== spec.specHash) {
15150
- log(` skip ${key} (source belongs to a stale spec)`);
15521
+ log(` skip ${key2} (source belongs to a stale spec)`);
15151
15522
  result.skipped++;
15152
15523
  continue;
15153
15524
  }
@@ -15164,16 +15535,16 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15164
15535
  });
15165
15536
  } catch (err) {
15166
15537
  const message6 = err instanceof Error ? err.message : String(err);
15167
- upsert(lock, key, { status: "download-failed", error: `download failed: ${message6}` });
15538
+ upsert(lock, key2, { status: "download-failed", error: `download failed: ${message6}` });
15168
15539
  result.failed++;
15169
- log(` FAILED ${key}: ${message6}`);
15540
+ log(` FAILED ${key2}: ${message6}`);
15170
15541
  await saveLock(lockPath, lock);
15171
15542
  continue;
15172
15543
  }
15173
15544
  if (current === null) {
15174
- upsert(lock, key, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
15545
+ upsert(lock, key2, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
15175
15546
  result.failed++;
15176
- log(` FAILED ${key}: ${entry.objectId} no longer exists upstream`);
15547
+ log(` FAILED ${key2}: ${entry.objectId} no longer exists upstream`);
15177
15548
  await saveLock(lockPath, lock);
15178
15549
  continue;
15179
15550
  }
@@ -15186,7 +15557,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15186
15557
  }
15187
15558
  }
15188
15559
  if (!sources.length) {
15189
- upsert(lock, key, {
15560
+ upsert(lock, key2, {
15190
15561
  status: "download-failed",
15191
15562
  error: "no persisted source URL to download; poll the job again if it still exists upstream"
15192
15563
  });
@@ -15211,21 +15582,21 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15211
15582
  if (!source.url) throw new Error(`no durable source URL to refresh ${source.role ?? "asset"} from`);
15212
15583
  fresh = await provider.download(source.url);
15213
15584
  if (recorded && sha256(fresh) === recordedRaw && !reapply) {
15214
- log(` current ${import_node_path21.default.relative(process.cwd(), target)}`);
15585
+ log(` current ${import_node_path23.default.relative(process.cwd(), target)}`);
15215
15586
  outputs.push({ ...recorded, path: portableOutputPath(target, spec.root) });
15216
15587
  continue;
15217
15588
  }
15218
15589
  }
15219
15590
  let raw = null;
15220
15591
  let final = null;
15221
- if ((0, import_node_fs18.existsSync)(target)) {
15592
+ if ((0, import_node_fs20.existsSync)(target)) {
15222
15593
  const currentHash = await sha256File(target);
15223
15594
  if (recorded && currentHash === recorded.sha256) {
15224
15595
  if (!fresh && !reapply) {
15225
15596
  if (cacheDir) {
15226
15597
  await cacheMedia(
15227
15598
  cacheDir,
15228
- await (0, import_promises13.readFile)(target),
15599
+ await (0, import_promises14.readFile)(target),
15229
15600
  recorded.mediaType ?? MediaType.PNG,
15230
15601
  recorded.sha256
15231
15602
  );
@@ -15234,10 +15605,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15234
15605
  continue;
15235
15606
  }
15236
15607
  if (reapply && !fresh) {
15237
- if (!recorded.raw) raw = await (0, import_promises13.readFile)(target);
15238
- log(` reapply ${import_node_path21.default.relative(process.cwd(), target)}`);
15608
+ if (!recorded.raw) raw = await (0, import_promises14.readFile)(target);
15609
+ log(` reapply ${import_node_path23.default.relative(process.cwd(), target)}`);
15239
15610
  } else {
15240
- log(` changed ${import_node_path21.default.relative(process.cwd(), target)} (upstream)`);
15611
+ log(` changed ${import_node_path23.default.relative(process.cwd(), target)} (upstream)`);
15241
15612
  }
15242
15613
  } else {
15243
15614
  const superseded = (entry.supersededOutputs ?? []).find(
@@ -15258,14 +15629,14 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15258
15629
  }
15259
15630
  if (outgoing && cacheDir) {
15260
15631
  try {
15261
- const oldBytes = await (0, import_promises13.readFile)(target);
15632
+ const oldBytes = await (0, import_promises14.readFile)(target);
15262
15633
  const oldMediaType = detectMediaType(oldBytes);
15263
15634
  if (oldMediaType) await cacheMedia(cacheDir, oldBytes, oldMediaType, currentHash);
15264
15635
  } catch {
15265
15636
  }
15266
15637
  }
15267
15638
  log(
15268
- ` replace ${import_node_path21.default.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
15639
+ ` replace ${import_node_path23.default.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
15269
15640
  );
15270
15641
  }
15271
15642
  }
@@ -15274,7 +15645,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15274
15645
  } else if (!raw && recorded && cacheDir) {
15275
15646
  if (!reapply) final = await readCachedMedia(cacheDir, recorded.sha256, expectedMediaType);
15276
15647
  if (!final && recordedRaw) raw = await readCachedMedia(cacheDir, recordedRaw, expectedMediaType);
15277
- if (final || raw) log(` cached ${import_node_path21.default.relative(process.cwd(), target)}`);
15648
+ if (final || raw) log(` cached ${import_node_path23.default.relative(process.cwd(), target)}`);
15278
15649
  }
15279
15650
  if (!final && !raw) {
15280
15651
  if (!source.url) {
@@ -15301,13 +15672,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15301
15672
  buf = processed.bytes;
15302
15673
  if (processed.changed) {
15303
15674
  rawHash = sha256(raw);
15304
- log(` snapped ${import_node_path21.default.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
15675
+ log(` snapped ${import_node_path23.default.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
15305
15676
  }
15306
15677
  }
15307
15678
  if (cacheDir) await cacheMedia(cacheDir, buf, mediaType);
15308
- await (0, import_promises13.mkdir)(import_node_path21.default.dirname(target), { recursive: true });
15679
+ await (0, import_promises14.mkdir)(import_node_path23.default.dirname(target), { recursive: true });
15309
15680
  const tmp = `${target}.pixelkiln.tmp`;
15310
- await (0, import_promises13.writeFile)(tmp, buf);
15681
+ await (0, import_promises14.writeFile)(tmp, buf);
15311
15682
  outputs.push({
15312
15683
  path: portableOutputPath(target, spec.root),
15313
15684
  sha256: sha256(buf),
@@ -15315,22 +15686,22 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15315
15686
  mediaType,
15316
15687
  ...rawHash ? { raw: rawHash } : {}
15317
15688
  });
15318
- upsert(lock, key, { outputs: mergeOutputs(entry.outputs, outputs) });
15689
+ upsert(lock, key2, { outputs: mergeOutputs(entry.outputs, outputs) });
15319
15690
  await saveLock(lockPath, lock);
15320
- await (0, import_promises13.rename)(tmp, target);
15691
+ await (0, import_promises14.rename)(tmp, target);
15321
15692
  wrote = true;
15322
- log(` wrote ${import_node_path21.default.relative(process.cwd(), target)}`);
15693
+ log(` wrote ${import_node_path23.default.relative(process.cwd(), target)}`);
15323
15694
  }
15324
15695
  if (opts.refresh && !wrote) {
15325
15696
  if (rotated) {
15326
15697
  const persistent = sources.filter((source) => shouldPersistSourceUrl(source.url));
15327
- upsert(lock, key, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
15698
+ upsert(lock, key2, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
15328
15699
  }
15329
15700
  result.unchanged = (result.unchanged ?? 0) + 1;
15330
15701
  continue;
15331
15702
  }
15332
15703
  const persistentSources = sources.filter((source) => shouldPersistSourceUrl(source.url));
15333
- upsert(lock, key, {
15704
+ upsert(lock, key2, {
15334
15705
  status: "downloaded",
15335
15706
  provider: provider.id,
15336
15707
  outputs,
@@ -15347,13 +15718,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15347
15718
  result.downloaded++;
15348
15719
  } catch (err) {
15349
15720
  const message6 = err instanceof Error ? err.message : String(err);
15350
- upsert(lock, key, {
15721
+ upsert(lock, key2, {
15351
15722
  status: "download-failed",
15352
15723
  outputs: mergeOutputs(entry.outputs, outputs),
15353
15724
  error: `download failed: ${message6}`
15354
15725
  });
15355
15726
  result.failed++;
15356
- log(` FAILED ${key}: ${message6}`);
15727
+ log(` FAILED ${key2}: ${message6}`);
15357
15728
  }
15358
15729
  await saveLock(lockPath, lock);
15359
15730
  }
@@ -15363,10 +15734,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15363
15734
  return result;
15364
15735
  }
15365
15736
  async function readCachedMedia(cacheDir, hash, mediaType) {
15366
- const file = import_node_path21.default.join(cacheDir, cacheFileName(hash, mediaType));
15367
- if (!(0, import_node_fs18.existsSync)(file)) return null;
15737
+ const file = import_node_path23.default.join(cacheDir, cacheFileName(hash, mediaType));
15738
+ if (!(0, import_node_fs20.existsSync)(file)) return null;
15368
15739
  try {
15369
- const buf = await (0, import_promises13.readFile)(file);
15740
+ const buf = await (0, import_promises14.readFile)(file);
15370
15741
  if (sha256(buf) !== hash) return null;
15371
15742
  validateMedia(buf, mediaType);
15372
15743
  return buf;
@@ -15377,17 +15748,17 @@ async function readCachedMedia(cacheDir, hash, mediaType) {
15377
15748
  async function cacheMedia(cacheDir, buf, mediaType, knownHash) {
15378
15749
  const hash = knownHash ?? sha256(buf);
15379
15750
  validateMedia(buf, mediaType);
15380
- const file = import_node_path21.default.join(cacheDir, cacheFileName(hash, mediaType));
15751
+ const file = import_node_path23.default.join(cacheDir, cacheFileName(hash, mediaType));
15381
15752
  if (await readCachedMedia(cacheDir, hash, mediaType)) return;
15382
- await (0, import_promises13.mkdir)(cacheDir, { recursive: true });
15753
+ await (0, import_promises14.mkdir)(cacheDir, { recursive: true });
15383
15754
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
15384
- await (0, import_promises13.writeFile)(tmp, buf);
15755
+ await (0, import_promises14.writeFile)(tmp, buf);
15385
15756
  try {
15386
- await (0, import_promises13.rename)(tmp, file);
15757
+ await (0, import_promises14.rename)(tmp, file);
15387
15758
  } catch (err) {
15388
- if (!(0, import_node_fs18.existsSync)(file)) throw err;
15759
+ if (!(0, import_node_fs20.existsSync)(file)) throw err;
15389
15760
  } finally {
15390
- await (0, import_promises13.rm)(tmp, { force: true });
15761
+ await (0, import_promises14.rm)(tmp, { force: true });
15391
15762
  }
15392
15763
  }
15393
15764
  function mergeOutputs(previous, current) {
@@ -15402,8 +15773,8 @@ async function pushTags(provider, specs, lock, opts = {}) {
15402
15773
  });
15403
15774
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
15404
15775
  let tagged = 0;
15405
- for (const [key, entry] of Object.entries(lock.entries)) {
15406
- const spec = specByKey.get(key);
15776
+ for (const [key2, entry] of Object.entries(lock.entries)) {
15777
+ const spec = specByKey.get(key2);
15407
15778
  if (!spec || entry.provider !== provider.id || !entry.objectId) continue;
15408
15779
  if (entry.generator === "pixflux" || entry.generator === "vfx") continue;
15409
15780
  if (!provider.setTags) return tagged;
@@ -15411,7 +15782,7 @@ async function pushTags(provider, specs, lock, opts = {}) {
15411
15782
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
15412
15783
  tagged++;
15413
15784
  } catch (err) {
15414
- log(` tag failed ${key}: ${err instanceof Error ? err.message : String(err)}`);
15785
+ log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
15415
15786
  }
15416
15787
  }
15417
15788
  return tagged;
@@ -15495,22 +15866,22 @@ function pickHistory(entry, selector) {
15495
15866
  return matches[0];
15496
15867
  }
15497
15868
  async function revertGeneration(provider, spec, lock, lockPath, opts) {
15498
- const key = lockKey(spec.styleId, spec.assetId);
15499
- const entry = lock.entries[key];
15500
- if (!entry) throw new Error(`${key} is not in the lockfile`);
15869
+ const key2 = lockKey(spec.styleId, spec.assetId);
15870
+ const entry = lock.entries[key2];
15871
+ if (!entry) throw new Error(`${key2} is not in the lockfile`);
15501
15872
  if (entry.status !== "downloaded") {
15502
- throw new Error(`${key} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
15873
+ throw new Error(`${key2} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
15503
15874
  }
15504
15875
  const { index, generation } = pickHistory(entry, opts.generation);
15505
15876
  if (generation.provider !== provider.id) {
15506
- throw new Error(`${key}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
15877
+ throw new Error(`${key2}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
15507
15878
  }
15508
15879
  for (let i = 0; i < entry.outputs.length; i++) {
15509
15880
  const file = currentEntryOutputPath(entry, spec, i);
15510
- if (!(0, import_node_fs19.existsSync)(file)) continue;
15881
+ if (!(0, import_node_fs21.existsSync)(file)) continue;
15511
15882
  if (await sha256File(file) !== entry.outputs[i].sha256 && !opts.force) {
15512
15883
  throw new OverwriteRefusedError(
15513
- `${import_node_path22.default.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
15884
+ `${import_node_path24.default.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
15514
15885
  [file]
15515
15886
  );
15516
15887
  }
@@ -15518,7 +15889,7 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15518
15889
  const now = (/* @__PURE__ */ new Date()).toISOString();
15519
15890
  const remaining = (entry.history ?? []).filter((_, i) => i !== index - 1);
15520
15891
  const history = [retireGeneration(entry, now), ...remaining];
15521
- upsert(lock, key, {
15892
+ upsert(lock, key2, {
15522
15893
  specHash: generation.specHash,
15523
15894
  generator: generation.generator,
15524
15895
  tileFeature: generation.tileFeature,
@@ -15570,11 +15941,11 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15570
15941
 
15571
15942
  // src/pipeline/cache-health.ts
15572
15943
  async function inspectCaches(lock, lockPath, options = {}) {
15573
- if (options.prune && !(0, import_node_fs20.existsSync)(lockPath)) {
15574
- throw new Error(`Refusing to prune without an existing lockfile at ${import_node_path23.default.resolve(lockPath)}`);
15944
+ if (options.prune && !(0, import_node_fs22.existsSync)(lockPath)) {
15945
+ throw new Error(`Refusing to prune without an existing lockfile at ${import_node_path25.default.resolve(lockPath)}`);
15575
15946
  }
15576
- const contentDir = import_node_path23.default.resolve(import_node_path23.default.dirname(lockPath), ".pixelkiln", "cache");
15577
- const remotePath = import_node_path23.default.resolve(cachePathFor(lockPath));
15947
+ const contentDir = import_node_path25.default.resolve(import_node_path25.default.dirname(lockPath), ".pixelkiln", "cache");
15948
+ const remotePath = import_node_path25.default.resolve(cachePathFor(lockPath));
15578
15949
  const referenced = referencedHashes(lock);
15579
15950
  let content = await inspectContentCache(contentDir, referenced);
15580
15951
  let remoteHashes = await inspectRemoteHashCache(remotePath);
@@ -15586,7 +15957,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15586
15957
  ]);
15587
15958
  for (const name of names) {
15588
15959
  try {
15589
- await (0, import_promises14.rm)(import_node_path23.default.join(contentDir, name), { force: true });
15960
+ await (0, import_promises15.rm)(import_node_path25.default.join(contentDir, name), { force: true });
15590
15961
  removed.contentFiles++;
15591
15962
  } catch {
15592
15963
  }
@@ -15595,7 +15966,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15595
15966
  await saveCache(remotePath, { version: 1, hashes: {} });
15596
15967
  removed.resetRemoteHashCache = true;
15597
15968
  } else if (remoteHashes.invalidIds.length) {
15598
- const cache = parseCache(JSON.parse(await (0, import_promises14.readFile)(remotePath, "utf8")));
15969
+ const cache = parseCache(JSON.parse(await (0, import_promises15.readFile)(remotePath, "utf8")));
15599
15970
  for (const id of remoteHashes.invalidIds) delete cache.hashes[id];
15600
15971
  removed.remoteHashEntries = remoteHashes.invalidIds.length;
15601
15972
  await saveCache(remotePath, cache);
@@ -15613,7 +15984,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15613
15984
  async function inspectContentCache(contentDir, referenced) {
15614
15985
  const report = {
15615
15986
  path: contentDir,
15616
- exists: (0, import_node_fs20.existsSync)(contentDir),
15987
+ exists: (0, import_node_fs22.existsSync)(contentDir),
15617
15988
  files: 0,
15618
15989
  bytes: 0,
15619
15990
  valid: 0,
@@ -15627,19 +15998,19 @@ async function inspectContentCache(contentDir, referenced) {
15627
15998
  return report;
15628
15999
  }
15629
16000
  const present = /* @__PURE__ */ new Set();
15630
- const entries = await (0, import_promises14.readdir)(contentDir, { withFileTypes: true });
16001
+ const entries = await (0, import_promises15.readdir)(contentDir, { withFileTypes: true });
15631
16002
  for (const entry of entries) {
15632
16003
  if (!entry.isFile()) {
15633
16004
  report.invalid.push({ name: entry.name, reason: "not a regular file" });
15634
16005
  continue;
15635
16006
  }
15636
16007
  report.files++;
15637
- const file = import_node_path23.default.join(contentDir, entry.name);
16008
+ const file = import_node_path25.default.join(contentDir, entry.name);
15638
16009
  const mediaType = mediaTypeFromExtension(entry.name);
15639
16010
  const expected = mediaType ? entry.name.slice(0, -4) : "";
15640
16011
  let bytes;
15641
16012
  try {
15642
- bytes = await (0, import_promises14.readFile)(file);
16013
+ bytes = await (0, import_promises15.readFile)(file);
15643
16014
  report.bytes += bytes.length;
15644
16015
  } catch (err) {
15645
16016
  report.invalid.push({
@@ -15677,7 +16048,7 @@ async function inspectContentCache(contentDir, referenced) {
15677
16048
  async function inspectRemoteHashCache(remotePath) {
15678
16049
  const report = {
15679
16050
  path: remotePath,
15680
- exists: (0, import_node_fs20.existsSync)(remotePath),
16051
+ exists: (0, import_node_fs22.existsSync)(remotePath),
15681
16052
  entries: 0,
15682
16053
  valid: 0,
15683
16054
  invalidIds: [],
@@ -15686,7 +16057,7 @@ async function inspectRemoteHashCache(remotePath) {
15686
16057
  if (!report.exists) return report;
15687
16058
  let cache;
15688
16059
  try {
15689
- cache = parseCache(JSON.parse(await (0, import_promises14.readFile)(remotePath, "utf8")));
16060
+ cache = parseCache(JSON.parse(await (0, import_promises15.readFile)(remotePath, "utf8")));
15690
16061
  } catch (err) {
15691
16062
  report.error = err instanceof Error ? err.message : String(err);
15692
16063
  return report;
@@ -15701,20 +16072,20 @@ async function inspectRemoteHashCache(remotePath) {
15701
16072
  }
15702
16073
 
15703
16074
  // src/pipeline/pack.ts
15704
- var import_node_fs21 = require("fs");
15705
- var import_node_path24 = __toESM(require("path"), 1);
16075
+ var import_node_fs23 = require("fs");
16076
+ var import_node_path26 = __toESM(require("path"), 1);
15706
16077
  var DEFAULT_FRAME_SET_FPS = 12;
15707
16078
  function resolvePackInputs(raw, inputsFilePath) {
15708
16079
  if (!Array.isArray(raw) || !raw.length) {
15709
16080
  throw new Error("--inputs must be a non-empty JSON array of { id, path }");
15710
16081
  }
15711
- const baseDir = import_node_path24.default.dirname(import_node_path24.default.resolve(inputsFilePath));
16082
+ const baseDir = import_node_path26.default.dirname(import_node_path26.default.resolve(inputsFilePath));
15712
16083
  return raw.map((entry, i) => {
15713
16084
  const e = entry;
15714
16085
  if (typeof e.id !== "string" || typeof e.path !== "string") {
15715
16086
  throw new Error(`--inputs[${i}] needs string "id" and "path"`);
15716
16087
  }
15717
- return { id: e.id, path: import_node_path24.default.resolve(baseDir, e.path) };
16088
+ return { id: e.id, path: import_node_path26.default.resolve(baseDir, e.path) };
15718
16089
  });
15719
16090
  }
15720
16091
  function packSprites(inputs, options = {}) {
@@ -15735,7 +16106,7 @@ function packSprites(inputs, options = {}) {
15735
16106
  for (const input of ordered) {
15736
16107
  let sourceHash = null;
15737
16108
  try {
15738
- const bytes = (0, import_node_fs21.readFileSync)(input.path);
16109
+ const bytes = (0, import_node_fs23.readFileSync)(input.path);
15739
16110
  sourceHash = sha256(bytes);
15740
16111
  const png = decodePng(bytes);
15741
16112
  sprites.push({ id: input.id, width: png.width, height: png.height, pixels: png.pixels });
@@ -15798,14 +16169,14 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15798
16169
  }
15799
16170
  const inputs2 = Object.entries(options.sourceOverrides).map(([id, source]) => ({
15800
16171
  id,
15801
- path: import_node_path24.default.resolve(source)
16172
+ path: import_node_path26.default.resolve(source)
15802
16173
  }));
15803
16174
  if (!inputs2.length) throw new Error(`No approved quality outputs for style "${styleId}".`);
15804
16175
  const packed2 = packSprites(inputs2, options);
15805
16176
  return { ...packed2, atlas: { ...packed2.atlas, style: styleId } };
15806
16177
  }
15807
16178
  const prefix = `${styleId}/`;
15808
- const entries = Object.entries(lock.entries).filter(([key]) => key.startsWith(prefix));
16179
+ const entries = Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix));
15809
16180
  const sources = options.sources ?? {};
15810
16181
  if (!entries.length && !Object.keys(sources).length) {
15811
16182
  throw new Error(
@@ -15816,13 +16187,13 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15816
16187
  const noOutput = [];
15817
16188
  const locked = /* @__PURE__ */ new Set();
15818
16189
  const sets = [];
15819
- for (const [key, entry] of entries) {
15820
- const id = key.slice(prefix.length);
16190
+ for (const [key2, entry] of entries) {
16191
+ const id = key2.slice(prefix.length);
15821
16192
  locked.add(id);
15822
16193
  let outputs = resolveEntryOutputs(entry, id, manifestDir);
15823
16194
  const source = sources[id];
15824
16195
  if (source && outputs.length <= 1) {
15825
- inputs.push({ id, path: import_node_path24.default.resolve(manifestDir, source) });
16196
+ inputs.push({ id, path: import_node_path26.default.resolve(manifestDir, source) });
15826
16197
  continue;
15827
16198
  }
15828
16199
  if (source && sourceIsStem(source, entry, manifestDir)) {
@@ -15857,7 +16228,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15857
16228
  }
15858
16229
  }
15859
16230
  for (const [id, source] of Object.entries(sources)) {
15860
- if (!locked.has(id)) inputs.push({ id, path: import_node_path24.default.resolve(manifestDir, source) });
16231
+ if (!locked.has(id)) inputs.push({ id, path: import_node_path26.default.resolve(manifestDir, source) });
15861
16232
  }
15862
16233
  if (!inputs.length) {
15863
16234
  throw new Error(`No readable sprites for style "${styleId}"; ${noOutput.length} skipped.`);
@@ -15879,14 +16250,14 @@ function mountSprites(placements, options) {
15879
16250
  }
15880
16251
  const byCell = /* @__PURE__ */ new Map();
15881
16252
  for (const p of placements) {
15882
- const key = `${p.cell[0]},${p.cell[1]}`;
15883
- const owner = byCell.get(key);
16253
+ const key2 = `${p.cell[0]},${p.cell[1]}`;
16254
+ const owner = byCell.get(key2);
15884
16255
  if (owner) {
15885
16256
  throw new Error(
15886
- `mountSprites: "${p.id}" and "${owner}" both claim cell ${key}; a cell has exactly one owner`
16257
+ `mountSprites: "${p.id}" and "${owner}" both claim cell ${key2}; a cell has exactly one owner`
15887
16258
  );
15888
16259
  }
15889
- byCell.set(key, p.id);
16260
+ byCell.set(key2, p.id);
15890
16261
  }
15891
16262
  const loaded = [];
15892
16263
  const skipped = [];
@@ -15894,7 +16265,7 @@ function mountSprites(placements, options) {
15894
16265
  for (const p of placements) {
15895
16266
  let sourceHash = null;
15896
16267
  try {
15897
- const bytes = (0, import_node_fs21.readFileSync)(p.path);
16268
+ const bytes = (0, import_node_fs23.readFileSync)(p.path);
15898
16269
  sourceHash = sha256(bytes);
15899
16270
  const png = decodePng(bytes);
15900
16271
  if (png.width > cellWidth || png.height > cellHeight) {
@@ -15965,7 +16336,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15965
16336
  const source = sources[id];
15966
16337
  const entry = lock.entries[`${styleId}/${id}`];
15967
16338
  if (source && !(entry && sourceIsStem(source, entry, manifestDir))) {
15968
- placements.push({ id, path: import_node_path24.default.resolve(manifestDir, source), cell });
16339
+ placements.push({ id, path: import_node_path26.default.resolve(manifestDir, source), cell });
15969
16340
  continue;
15970
16341
  }
15971
16342
  if (source && entry) {
@@ -15998,7 +16369,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15998
16369
  `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}`
15999
16370
  );
16000
16371
  }
16001
- const basePng = mount.base ? (0, import_node_fs21.readFileSync)(import_node_path24.default.resolve(manifestDir, mount.base)) : void 0;
16372
+ const basePng = mount.base ? (0, import_node_fs23.readFileSync)(import_node_path26.default.resolve(manifestDir, mount.base)) : void 0;
16002
16373
  const mounted = mountSprites(placements, {
16003
16374
  cellWidth: mount.cellWidth,
16004
16375
  cellHeight: mount.cellHeight,
@@ -16008,7 +16379,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
16008
16379
  ...mounted,
16009
16380
  sources: mount.base ? [{
16010
16381
  id: "$base",
16011
- path: import_node_path24.default.resolve(manifestDir, mount.base),
16382
+ path: import_node_path26.default.resolve(manifestDir, mount.base),
16012
16383
  sha256: sha256(basePng),
16013
16384
  included: true
16014
16385
  }, ...mounted.sources] : mounted.sources,
@@ -16026,8 +16397,8 @@ function normalizeTileRules(raw) {
16026
16397
  if (arity !== 4 && arity !== 6) return null;
16027
16398
  const masks = {};
16028
16399
  if (isRecord2(raw.tiles)) {
16029
- for (const [key, value] of Object.entries(raw.tiles)) {
16030
- const index = tileIndex(key);
16400
+ for (const [key2, value] of Object.entries(raw.tiles)) {
16401
+ const index = tileIndex(key2);
16031
16402
  const mask = typeof value === "number" ? value : isRecord2(value) && typeof value.bitmask === "number" ? value.bitmask : isRecord2(value) && typeof value.mask === "number" ? value.mask : null;
16032
16403
  if (index !== null && mask !== null && Number.isInteger(mask) && mask >= 0) masks[index] = mask;
16033
16404
  }
@@ -16302,8 +16673,8 @@ function assertUniformTiles(generic) {
16302
16673
  );
16303
16674
  }
16304
16675
  }
16305
- function tileIndex(key) {
16306
- const match = key.match(/(?:^|[_-])(\d+)$/);
16676
+ function tileIndex(key2) {
16677
+ const match = key2.match(/(?:^|[_-])(\d+)$/);
16307
16678
  return match ? Number(match[1]) : null;
16308
16679
  }
16309
16680
  function isRecord2(value) {
@@ -16418,9 +16789,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16418
16789
  });
16419
16790
  const estimates = new Map(items.map((item) => [
16420
16791
  item.key,
16421
- item.spec.mirror ? { amount: 0, unit: item.spec.costUnit, candidates: 1 } : validateCostEstimate(provider.id, provider.estimate(item.spec))
16792
+ item.spec.mirror || item.spec.derive ? { amount: 0, unit: item.spec.costUnit, candidates: 1 } : validateCostEstimate(provider.id, provider.estimate(item.spec))
16422
16793
  ]));
16423
- const units = new Set([...estimates.values()].map((estimate) => estimate.unit));
16794
+ const units = new Set(items.filter((item) => !item.spec.derive).map((item) => estimates.get(item.key).unit));
16424
16795
  if (units.size > 1) {
16425
16796
  throw new Error(`Provider "${provider.id}" returned mixed cost units for one submission batch`);
16426
16797
  }
@@ -16518,20 +16889,21 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16518
16889
  }
16519
16890
  }
16520
16891
  }
16521
- for (const { spec, key } of items) {
16522
- const estimate = estimates.get(key);
16892
+ for (const { spec, key: key2 } of items) {
16893
+ const estimate = estimates.get(key2);
16523
16894
  if (spec.batch?.role === "member") {
16524
16895
  continue;
16525
16896
  }
16526
- if (spec.mirror) {
16897
+ if (spec.mirror || spec.derive) {
16527
16898
  try {
16528
16899
  await requireRevisionReady(spec, lock);
16529
- await deriveMirror(spec, lock, lockPath, { onProgress: log });
16900
+ if (spec.derive) await deriveAsset(spec, lock, lockPath, { onProgress: log });
16901
+ else await deriveMirror(spec, lock, lockPath, { onProgress: log });
16530
16902
  submitted++;
16531
16903
  } catch (err) {
16532
16904
  const message6 = err instanceof Error ? err.message : String(err);
16533
16905
  failed++;
16534
- upsert(lock, key, {
16906
+ upsert(lock, key2, {
16535
16907
  styleId: spec.styleId,
16536
16908
  assetId: spec.assetId,
16537
16909
  specHash: spec.specHash,
@@ -16541,13 +16913,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16541
16913
  height: spec.height,
16542
16914
  status: "failed",
16543
16915
  error: message6,
16544
- outputs: lock.entries[key]?.outputs ?? [],
16916
+ outputs: lock.entries[key2]?.outputs ?? [],
16545
16917
  cost: 0,
16546
16918
  costUnit: spec.costUnit,
16547
16919
  provider: provider.id
16548
16920
  });
16549
16921
  await saveLock(lockPath, lock);
16550
- log(` FAILED ${key}: ${message6}`);
16922
+ log(` FAILED ${key2}: ${message6}`);
16551
16923
  }
16552
16924
  continue;
16553
16925
  }
@@ -16559,11 +16931,11 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16559
16931
  const missing = (spec.batch.memberAssetIds ?? []).filter((id) => !byKey.has(lockKey(spec.styleId, id)));
16560
16932
  if (missing.length) {
16561
16933
  throw new Error(
16562
- `${key}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
16934
+ `${key2}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
16563
16935
  );
16564
16936
  }
16565
16937
  }
16566
- const previousEntry = lock.entries[key];
16938
+ const previousEntry = lock.entries[key2];
16567
16939
  const resumesCheckpoint = Boolean(
16568
16940
  previousEntry?.specHash === spec.specHash && previousEntry.provider === provider.id && previousEntry.generator === spec.generator && previousEntry.submissionComplete === false && previousEntry.jobId
16569
16941
  );
@@ -16593,9 +16965,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16593
16965
  const leaderGroup = motionLeader ? recordedAnimationGroup(lock.entries[lockKey(motionLeader.spec.styleId, motionLeader.spec.assetId)]) : void 0;
16594
16966
  const motionGroup = leaderGroup?.animationGroupId && leaderGroup.animationName ? { animationGroupId: leaderGroup.animationGroupId, animationName: leaderGroup.animationName } : void 0;
16595
16967
  if (motionLeader && !motionGroup) {
16596
- log(` ${key}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
16968
+ log(` ${key2}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
16597
16969
  }
16598
- upsert(lock, key, {
16970
+ upsert(lock, key2, {
16599
16971
  styleId: spec.styleId,
16600
16972
  assetId: spec.assetId,
16601
16973
  specHash: spec.specHash,
@@ -16693,8 +17065,8 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16693
17065
  ...previousMetadata ? { previousMetadata } : {},
16694
17066
  checkpoint: async (checkpoint) => {
16695
17067
  if (!checkpoint.jobId) throw new Error("Provider checkpoint returned an empty job id");
16696
- const entry = lock.entries[key];
16697
- upsert(lock, key, {
17068
+ const entry = lock.entries[key2];
17069
+ upsert(lock, key2, {
16698
17070
  jobId: checkpoint.jobId,
16699
17071
  submissionComplete: checkpoint.complete,
16700
17072
  reviewObjectId: checkpoint.complete && (spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature) ? checkpoint.jobId : null,
@@ -16711,41 +17083,41 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16711
17083
  await saveLock(lockPath, lock);
16712
17084
  }
16713
17085
  });
16714
- upsert(lock, key, {
17086
+ upsert(lock, key2, {
16715
17087
  jobId,
16716
17088
  submissionComplete: true,
16717
17089
  // A multi-candidate generator routes through review; record the parent
16718
17090
  // so `pick` knows where to look.
16719
17091
  reviewObjectId: spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature ? jobId : null,
16720
17092
  status: "processing",
16721
- providerMetadata: metadata ? { ...lock.entries[key].providerMetadata, [provider.id]: metadata } : lock.entries[key].providerMetadata
17093
+ providerMetadata: metadata ? { ...lock.entries[key2].providerMetadata, [provider.id]: metadata } : lock.entries[key2].providerMetadata
16722
17094
  });
16723
17095
  inFlight.set(jobId, spec);
16724
17096
  submitted++;
16725
17097
  spent += estimate.amount;
16726
- writeBatchMembers(spec, key, null);
17098
+ writeBatchMembers(spec, key2, null);
16727
17099
  log(
16728
- ` ${key} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
17100
+ ` ${key2} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
16729
17101
  );
16730
17102
  } catch (err) {
16731
17103
  const message6 = err instanceof Error ? err.message : String(err);
16732
- const entry = lock.entries[key];
17104
+ const entry = lock.entries[key2];
16733
17105
  if (entry.jobId && entry.submissionComplete === true) {
16734
- upsert(lock, key, { status: "processing", error: null });
17106
+ upsert(lock, key2, { status: "processing", error: null });
16735
17107
  inFlight.set(entry.jobId, spec);
16736
17108
  submitted++;
16737
17109
  spent += estimate.amount;
16738
- writeBatchMembers(spec, key, null);
16739
- log(` ${key} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
17110
+ writeBatchMembers(spec, key2, null);
17111
+ log(` ${key2} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
16740
17112
  } else {
16741
17113
  failed++;
16742
- upsert(lock, key, {
17114
+ upsert(lock, key2, {
16743
17115
  status: "failed",
16744
17116
  error: message6,
16745
17117
  cost: entry.jobId ? estimate.amount : 0
16746
17118
  });
16747
- writeBatchMembers(spec, key, message6);
16748
- log(` FAILED ${key}: ${message6}`);
17119
+ writeBatchMembers(spec, key2, message6);
17120
+ log(` FAILED ${key2}: ${message6}`);
16749
17121
  }
16750
17122
  }
16751
17123
  await saveLock(lockPath, lock);
@@ -16776,14 +17148,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
16776
17148
  const selectedKeys = opts.specs ? new Set(specByKey.keys()) : null;
16777
17149
  const result = { review: 0, completed: 0, failed: 0, stillRunning: 0 };
16778
17150
  const incompleteSubmissions = Object.entries(lock.entries).filter(
16779
- ([key, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
17151
+ ([key2, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
16780
17152
  );
16781
- for (const [key] of incompleteSubmissions) {
16782
- log(` incomplete submission ${key}; rerun \`pixelkiln submit\` to resume`);
17153
+ for (const [key2] of incompleteSubmissions) {
17154
+ log(` incomplete submission ${key2}; rerun \`pixelkiln submit\` to resume`);
16783
17155
  }
16784
17156
  result.stillRunning = incompleteSubmissions.length;
16785
17157
  const pending = () => Object.entries(lock.entries).filter(
16786
- ([key, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
17158
+ ([key2, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
16787
17159
  );
16788
17160
  while (pending().length > 0) {
16789
17161
  if (Date.now() - started > timeout) {
@@ -16791,16 +17163,16 @@ async function poll(provider, lock, lockPath, opts = {}) {
16791
17163
  log(` timed out with ${result.stillRunning} job(s) still running; re-run \`poll\` to resume`);
16792
17164
  break;
16793
17165
  }
16794
- for (const [key, entry] of pending()) {
17166
+ for (const [key2, entry] of pending()) {
16795
17167
  try {
16796
- const currentSpec = specByKey.get(key);
17168
+ const currentSpec = specByKey.get(key2);
16797
17169
  const state = await provider.poll(entry.jobId, entry.generator, {
16798
17170
  tileFeature: entry.tileFeature ?? currentSpec?.tileFeature,
16799
17171
  spec: currentSpec,
16800
17172
  metadata: entry.providerMetadata?.[provider.id]
16801
17173
  });
16802
17174
  if (state.status === "review" || state.status === "review-set") {
16803
- upsert(lock, key, {
17175
+ upsert(lock, key2, {
16804
17176
  status: "review",
16805
17177
  reviewObjectId: entry.jobId,
16806
17178
  providerMetadata: state.metadata ? {
@@ -16814,11 +17186,11 @@ async function poll(provider, lock, lockPath, opts = {}) {
16814
17186
  });
16815
17187
  result.review++;
16816
17188
  log(
16817
- state.status === "review-set" ? ` review ${key} (${state.frameUrls.length} ordered frames)` : ` review ${key} (${state.candidateUrls.length} candidates)`
17189
+ state.status === "review-set" ? ` review ${key2} (${state.frameUrls.length} ordered frames)` : ` review ${key2} (${state.candidateUrls.length} candidates)`
16818
17190
  );
16819
17191
  } else if (state.status === "ready") {
16820
17192
  const sourceUrls = state.sources?.length ? state.sources : state.sourceUrl ? [{ url: state.sourceUrl }] : [];
16821
- upsert(lock, key, {
17193
+ upsert(lock, key2, {
16822
17194
  status: "selected",
16823
17195
  objectId: state.objectId,
16824
17196
  sourceUrl: sourceUrls[0]?.url ?? null,
@@ -16834,14 +17206,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
16834
17206
  billed: state.billed ?? entry.billed
16835
17207
  });
16836
17208
  result.completed++;
16837
- log(` ready ${key}`);
17209
+ log(` ready ${key2}`);
16838
17210
  } else if (state.status === "failed") {
16839
- upsert(lock, key, { status: "failed", error: state.error });
17211
+ upsert(lock, key2, { status: "failed", error: state.error });
16840
17212
  result.failed++;
16841
- log(` FAILED ${key}: ${state.error}`);
17213
+ log(` FAILED ${key2}: ${state.error}`);
16842
17214
  }
16843
17215
  } catch (err) {
16844
- log(` error polling ${key}: ${err instanceof Error ? err.message : String(err)}`);
17216
+ log(` error polling ${key2}: ${err instanceof Error ? err.message : String(err)}`);
16845
17217
  }
16846
17218
  }
16847
17219
  await saveLock(lockPath, lock);
@@ -16852,34 +17224,34 @@ async function poll(provider, lock, lockPath, opts = {}) {
16852
17224
  }
16853
17225
 
16854
17226
  // src/pipeline/doctor.ts
16855
- var import_node_fs23 = require("fs");
16856
- var import_promises15 = require("fs/promises");
16857
- var import_node_path26 = __toESM(require("path"), 1);
17227
+ var import_node_fs25 = require("fs");
17228
+ var import_promises16 = require("fs/promises");
17229
+ var import_node_path28 = __toESM(require("path"), 1);
16858
17230
 
16859
17231
  // src/pipeline/install-check.ts
16860
- var import_node_fs22 = require("fs");
16861
- var import_node_path25 = __toESM(require("path"), 1);
17232
+ var import_node_fs24 = require("fs");
17233
+ var import_node_path27 = __toESM(require("path"), 1);
16862
17234
  function readJson(file) {
16863
17235
  try {
16864
- return JSON.parse((0, import_node_fs22.readFileSync)(file, "utf8"));
17236
+ return JSON.parse((0, import_node_fs24.readFileSync)(file, "utf8"));
16865
17237
  } catch {
16866
17238
  return null;
16867
17239
  }
16868
17240
  }
16869
17241
  function readInstallFacts(manifestDir, running) {
16870
- let dir = import_node_path25.default.resolve(manifestDir);
17242
+ let dir = import_node_path27.default.resolve(manifestDir);
16871
17243
  for (let depth = 0; depth < 4; depth++) {
16872
- const pkg = readJson(import_node_path25.default.join(dir, "package.json"));
17244
+ const pkg = readJson(import_node_path27.default.join(dir, "package.json"));
16873
17245
  if (pkg) {
16874
17246
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
16875
17247
  if (pinned) {
16876
- const installedPkg = readJson(import_node_path25.default.join(dir, "node_modules", "pixelkiln", "package.json"));
17248
+ const installedPkg = readJson(import_node_path27.default.join(dir, "node_modules", "pixelkiln", "package.json"));
16877
17249
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
16878
17250
  return { pinned, installed, running };
16879
17251
  }
16880
17252
  }
16881
- const parent = import_node_path25.default.dirname(dir);
16882
- if (parent === dir || !(0, import_node_fs22.existsSync)(parent)) break;
17253
+ const parent = import_node_path27.default.dirname(dir);
17254
+ if (parent === dir || !(0, import_node_fs24.existsSync)(parent)) break;
16883
17255
  dir = parent;
16884
17256
  }
16885
17257
  return null;
@@ -16942,18 +17314,18 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16942
17314
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
16943
17315
  );
16944
17316
  }
16945
- const facts = readInstallFacts(import_node_path26.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
17317
+ const facts = readInstallFacts(import_node_path28.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
16946
17318
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
16947
17319
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
16948
17320
  const dirs = [...new Set(specs.flatMap((spec) => [
16949
- import_node_path26.default.dirname(spec.outFile),
16950
- ...spec.quality ? [import_node_path26.default.dirname(spec.quality.outFile)] : []
17321
+ import_node_path28.default.dirname(spec.outFile),
17322
+ ...spec.quality ? [import_node_path28.default.dirname(spec.quality.outFile)] : []
16951
17323
  ]))];
16952
17324
  const unwritable = [];
16953
17325
  for (const dir of dirs) {
16954
17326
  const ancestor = await nearestExistingDirectory(dir);
16955
17327
  try {
16956
- await (0, import_promises15.access)(ancestor, import_node_fs23.constants.W_OK);
17328
+ await (0, import_promises16.access)(ancestor, import_node_fs25.constants.W_OK);
16957
17329
  } catch {
16958
17330
  unwritable.push(dir);
16959
17331
  }
@@ -16966,14 +17338,14 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16966
17338
  const outputOwners = /* @__PURE__ */ new Map();
16967
17339
  const duplicateOutputs = [];
16968
17340
  const specByKey = new Map(specs.map((spec) => [`${spec.styleId}/${spec.assetId}`, spec]));
16969
- for (const [key, entry] of Object.entries(lock.entries)) {
17341
+ for (const [key2, entry] of Object.entries(lock.entries)) {
16970
17342
  for (let index = 0; index < entry.outputs.length; index++) {
16971
17343
  const output = entry.outputs[index];
16972
- const spec = specByKey.get(key);
16973
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path26.default.dirname(lockPath));
17344
+ const spec = specByKey.get(key2);
17345
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path28.default.dirname(lockPath));
16974
17346
  const owner = outputOwners.get(absolute);
16975
- if (owner && owner !== key) duplicateOutputs.push(`${output.path} (${owner}, ${key})`);
16976
- outputOwners.set(absolute, key);
17347
+ if (owner && owner !== key2) duplicateOutputs.push(`${output.path} (${owner}, ${key2})`);
17348
+ outputOwners.set(absolute, key2);
16977
17349
  }
16978
17350
  }
16979
17351
  if (duplicateOutputs.length) {
@@ -16985,34 +17357,34 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16985
17357
  } else {
16986
17358
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
16987
17359
  }
16988
- const cacheDir = import_node_path26.default.join(import_node_path26.default.dirname(lockPath), ".pixelkiln", "cache");
17360
+ const cacheDir = import_node_path28.default.join(import_node_path28.default.dirname(lockPath), ".pixelkiln", "cache");
16989
17361
  const stranded = [];
16990
17362
  const invalidState = [];
16991
17363
  const staleMapUrls = [];
16992
17364
  const now = Date.now();
16993
- for (const [key, entry] of Object.entries(lock.entries)) {
17365
+ for (const [key2, entry] of Object.entries(lock.entries)) {
16994
17366
  if ((entry.status === "pending" || entry.status === "processing") && !entry.jobId) {
16995
- invalidState.push(`${key} (${entry.status} without job id)`);
17367
+ invalidState.push(`${key2} (${entry.status} without job id)`);
16996
17368
  }
16997
17369
  if (entry.status === "review" && !entry.reviewObjectId) {
16998
- invalidState.push(`${key} (review without review object id)`);
17370
+ invalidState.push(`${key2} (review without review object id)`);
16999
17371
  }
17000
17372
  if (entry.status !== "selected" && entry.status !== "download-failed") continue;
17001
17373
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
17002
17374
  let hasCache = false;
17003
17375
  for (const output of entry.outputs) {
17004
- const cached2 = import_node_path26.default.join(
17376
+ const cached2 = import_node_path28.default.join(
17005
17377
  cacheDir,
17006
17378
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
17007
17379
  );
17008
- if ((0, import_node_fs23.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
17380
+ if ((0, import_node_fs25.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
17009
17381
  hasCache = true;
17010
17382
  break;
17011
17383
  }
17012
17384
  }
17013
- if (!hasSource && !hasCache) stranded.push(key);
17385
+ if (!hasSource && !hasCache) stranded.push(key2);
17014
17386
  if (entry.generator === "map" && entry.submittedAt && now - Date.parse(entry.submittedAt) > 8 * 60 * 60 * 1e3) {
17015
- staleMapUrls.push(key);
17387
+ staleMapUrls.push(key2);
17016
17388
  }
17017
17389
  }
17018
17390
  add(
@@ -17098,19 +17470,19 @@ async function nearestExistingDirectory(start) {
17098
17470
  let current = start;
17099
17471
  for (; ; ) {
17100
17472
  try {
17101
- if ((await (0, import_promises15.stat)(current)).isDirectory()) return current;
17473
+ if ((await (0, import_promises16.stat)(current)).isDirectory()) return current;
17102
17474
  } catch {
17103
17475
  }
17104
- const parent = import_node_path26.default.dirname(current);
17476
+ const parent = import_node_path28.default.dirname(current);
17105
17477
  if (parent === current) return current;
17106
17478
  current = parent;
17107
17479
  }
17108
17480
  }
17109
17481
 
17110
17482
  // src/pipeline/adopt.ts
17111
- var import_node_fs24 = require("fs");
17112
- var import_promises16 = require("fs/promises");
17113
- var import_node_path27 = __toESM(require("path"), 1);
17483
+ var import_node_fs26 = require("fs");
17484
+ var import_promises17 = require("fs/promises");
17485
+ var import_node_path29 = __toESM(require("path"), 1);
17114
17486
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
17115
17487
  const log = opts.onProgress ?? (() => {
17116
17488
  });
@@ -17121,11 +17493,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
17121
17493
  const localByHash = /* @__PURE__ */ new Map();
17122
17494
  const unmatchedLocal = [];
17123
17495
  for (const spec of specs) {
17124
- if (!(0, import_node_fs24.existsSync)(spec.outFile)) {
17496
+ if (!(0, import_node_fs26.existsSync)(spec.outFile)) {
17125
17497
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
17126
17498
  continue;
17127
17499
  }
17128
- const bytes = await (0, import_promises16.readFile)(spec.outFile);
17500
+ const bytes = await (0, import_promises17.readFile)(spec.outFile);
17129
17501
  try {
17130
17502
  decodePng(bytes);
17131
17503
  } catch (err) {
@@ -17170,14 +17542,14 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
17170
17542
  if (!hits?.length) continue;
17171
17543
  matchedRemote.add(obj.id);
17172
17544
  for (const spec of hits) {
17173
- const key = lockKey(spec.styleId, spec.assetId);
17174
- const existing = lock.entries[key];
17545
+ const key2 = lockKey(spec.styleId, spec.assetId);
17546
+ const existing = lock.entries[key2];
17175
17547
  if (existing?.objectId && existing.objectId !== obj.id) {
17176
- ambiguous.push(`${key}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
17548
+ ambiguous.push(`${key2}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
17177
17549
  continue;
17178
17550
  }
17179
17551
  const durableSource = shouldPersistSourceUrl(url) ? url : null;
17180
- upsert(lock, key, {
17552
+ upsert(lock, key2, {
17181
17553
  styleId: spec.styleId,
17182
17554
  assetId: spec.assetId,
17183
17555
  // Deliberately the CURRENT spec hash: adoption declares "the file on
@@ -17204,7 +17576,7 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
17204
17576
  provider: provider.id
17205
17577
  });
17206
17578
  matched++;
17207
- log(` adopted ${key} \u2190 ${obj.id}`);
17579
+ log(` adopted ${key2} \u2190 ${obj.id}`);
17208
17580
  }
17209
17581
  }
17210
17582
  }
@@ -17228,23 +17600,23 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
17228
17600
  });
17229
17601
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
17230
17602
  let count = 0;
17231
- for (const [key, entry] of Object.entries(lock.entries)) {
17232
- const spec = specByKey.get(key);
17603
+ for (const [key2, entry] of Object.entries(lock.entries)) {
17604
+ const spec = specByKey.get(key2);
17233
17605
  if (!spec || !entry.objectId) continue;
17234
17606
  if (!provider.setTags) return count;
17235
17607
  try {
17236
17608
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
17237
17609
  count++;
17238
17610
  } catch (err) {
17239
- log(` tag failed ${key}: ${err instanceof Error ? err.message : String(err)}`);
17611
+ log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
17240
17612
  }
17241
17613
  }
17242
17614
  return count;
17243
17615
  }
17244
17616
 
17245
17617
  // src/pipeline/import.ts
17246
- var import_node_fs25 = require("fs");
17247
- var import_promises17 = require("fs/promises");
17618
+ var import_node_fs27 = require("fs");
17619
+ var import_promises18 = require("fs/promises");
17248
17620
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
17249
17621
  const png = decodePng(bytes);
17250
17622
  const at = now.toISOString();
@@ -17270,6 +17642,7 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
17270
17642
  cost: 0,
17271
17643
  costUnit: spec.costUnit,
17272
17644
  provider: spec.provider,
17645
+ ...spec.external ? { external: { builder: spec.external.builder, inputs: spec.external.inputs } } : {},
17273
17646
  imported: {
17274
17647
  source: opts.source ?? "external",
17275
17648
  ...opts.note ? { note: opts.note } : {},
@@ -17290,32 +17663,32 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
17290
17663
  const imported = [];
17291
17664
  const skipped = [];
17292
17665
  for (const spec of specs) {
17293
- const key = lockKey(spec.styleId, spec.assetId);
17666
+ const key2 = lockKey(spec.styleId, spec.assetId);
17294
17667
  const reason = unimportable(spec);
17295
17668
  if (reason) {
17296
- skipped.push({ key, reason });
17669
+ skipped.push({ key: key2, reason });
17297
17670
  continue;
17298
17671
  }
17299
- if (!(0, import_node_fs25.existsSync)(spec.outFile)) {
17300
- skipped.push({ key, reason: `no file at ${spec.outFile}` });
17672
+ if (!(0, import_node_fs27.existsSync)(spec.outFile)) {
17673
+ skipped.push({ key: key2, reason: `no file at ${spec.outFile}` });
17301
17674
  continue;
17302
17675
  }
17303
- if (lock.entries[key] && !opts.force) {
17304
- skipped.push({ key, reason: "already in the lockfile (use --force to replace it)" });
17676
+ if (lock.entries[key2] && !opts.force) {
17677
+ skipped.push({ key: key2, reason: "already in the lockfile (use --force to replace it)" });
17305
17678
  continue;
17306
17679
  }
17307
17680
  let patch;
17308
17681
  try {
17309
- patch = buildImportedEntry(spec, await (0, import_promises17.readFile)(spec.outFile), opts);
17682
+ patch = buildImportedEntry(spec, await (0, import_promises18.readFile)(spec.outFile), opts);
17310
17683
  } catch (error) {
17311
- skipped.push({ key, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
17684
+ skipped.push({ key: key2, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
17312
17685
  continue;
17313
17686
  }
17314
17687
  if (opts.dryRun) {
17315
- imported.push({ key, entry: patch });
17688
+ imported.push({ key: key2, entry: patch });
17316
17689
  continue;
17317
17690
  }
17318
- imported.push({ key, entry: upsert(lock, key, patch) });
17691
+ imported.push({ key: key2, entry: upsert(lock, key2, patch) });
17319
17692
  }
17320
17693
  if (!opts.dryRun && imported.length) await saveLock(lockPath, lock);
17321
17694
  return { imported, skipped };
@@ -17323,9 +17696,9 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
17323
17696
  async function reportSpecHashes(specs, lock) {
17324
17697
  const reports = [];
17325
17698
  for (const spec of specs) {
17326
- const key = lockKey(spec.styleId, spec.assetId);
17699
+ const key2 = lockKey(spec.styleId, spec.assetId);
17327
17700
  let bytes = null;
17328
- if ((0, import_node_fs25.existsSync)(spec.outFile)) bytes = await (0, import_promises17.readFile)(spec.outFile);
17701
+ if ((0, import_node_fs27.existsSync)(spec.outFile)) bytes = await (0, import_promises18.readFile)(spec.outFile);
17329
17702
  let wouldImport = null;
17330
17703
  if (bytes && !unimportable(spec)) {
17331
17704
  try {
@@ -17334,11 +17707,11 @@ async function reportSpecHashes(specs, lock) {
17334
17707
  wouldImport = null;
17335
17708
  }
17336
17709
  }
17337
- const entry = lock.entries[key];
17710
+ const entry = lock.entries[key2];
17338
17711
  const fileSha256 = bytes ? sha256(bytes) : null;
17339
17712
  const outputSha256 = entry?.outputs[0]?.sha256 ?? null;
17340
17713
  reports.push({
17341
- key,
17714
+ key: key2,
17342
17715
  specHash: spec.specHash,
17343
17716
  file: spec.outFile,
17344
17717
  fileSha256,
@@ -17354,13 +17727,13 @@ async function reportSpecHashes(specs, lock) {
17354
17727
  }
17355
17728
 
17356
17729
  // src/pick/server.ts
17357
- var import_node_fs27 = require("fs");
17358
- var import_promises20 = require("fs/promises");
17730
+ var import_node_fs29 = require("fs");
17731
+ var import_promises21 = require("fs/promises");
17359
17732
 
17360
17733
  // src/pipeline/init.ts
17361
- var import_promises18 = require("fs/promises");
17362
- var import_node_fs26 = require("fs");
17363
- var import_node_path28 = __toESM(require("path"), 1);
17734
+ var import_promises19 = require("fs/promises");
17735
+ var import_node_fs28 = require("fs");
17736
+ var import_node_path30 = __toESM(require("path"), 1);
17364
17737
  function pngSize(buf) {
17365
17738
  if (buf.length < 24) return null;
17366
17739
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -17373,8 +17746,8 @@ function slugify(value) {
17373
17746
  }
17374
17747
  async function walk(dir, exclude) {
17375
17748
  const out = [];
17376
- for (const entry of await (0, import_promises18.readdir)(dir, { withFileTypes: true })) {
17377
- const full = import_node_path28.default.join(dir, entry.name);
17749
+ for (const entry of await (0, import_promises19.readdir)(dir, { withFileTypes: true })) {
17750
+ const full = import_node_path30.default.join(dir, entry.name);
17378
17751
  if (exclude.some((x) => full.includes(x))) continue;
17379
17752
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
17380
17753
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -17388,14 +17761,14 @@ async function scanAssets(root, opts = {}) {
17388
17761
  const skipped = [];
17389
17762
  const seen = /* @__PURE__ */ new Map();
17390
17763
  for (const file of files.sort()) {
17391
- const size = pngSize(await (0, import_promises18.readFile)(file));
17764
+ const size = pngSize(await (0, import_promises19.readFile)(file));
17392
17765
  if (!size) {
17393
17766
  skipped.push(`${file} (not a readable PNG)`);
17394
17767
  continue;
17395
17768
  }
17396
- const rel = import_node_path28.default.relative(root, file);
17397
- const category = import_node_path28.default.dirname(rel) === "." ? "" : import_node_path28.default.dirname(rel);
17398
- let id = slugify(import_node_path28.default.basename(rel));
17769
+ const rel = import_node_path30.default.relative(root, file);
17770
+ const category = import_node_path30.default.dirname(rel) === "." ? "" : import_node_path30.default.dirname(rel);
17771
+ let id = slugify(import_node_path30.default.basename(rel));
17399
17772
  if (seen.has(id)) {
17400
17773
  const n = seen.get(id) + 1;
17401
17774
  seen.set(id, n);
@@ -17869,7 +18242,7 @@ document.getElementById('submit').onclick = async () => {
17869
18242
 
17870
18243
  // src/pick/review-server.ts
17871
18244
  var import_node_http = require("http");
17872
- var import_promises19 = require("fs/promises");
18245
+ var import_promises20 = require("fs/promises");
17873
18246
  function serveReviewPage(opts) {
17874
18247
  const log = opts.onProgress ?? (() => {
17875
18248
  });
@@ -17878,7 +18251,7 @@ function serveReviewPage(opts) {
17878
18251
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
17879
18252
  try {
17880
18253
  const asset = opts.assets.get(req.url);
17881
- const bytes = await (0, import_promises19.readFile)(asset.path);
18254
+ const bytes = await (0, import_promises20.readFile)(asset.path);
17882
18255
  res.writeHead(200, {
17883
18256
  "Content-Type": asset.contentType,
17884
18257
  "Cache-Control": "no-store",
@@ -17954,13 +18327,13 @@ async function currentArt(entry, spec) {
17954
18327
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
17955
18328
  if (!previous) return null;
17956
18329
  const file = resolveOutputPath(previous.path, spec.root);
17957
- if (!(0, import_node_fs27.existsSync)(file)) return null;
18330
+ if (!(0, import_node_fs29.existsSync)(file)) return null;
17958
18331
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
17959
18332
  if (!contentType) return null;
17960
18333
  let width = entry.width;
17961
18334
  let height = entry.height;
17962
18335
  if (contentType === "image/png") {
17963
- const size = pngSize(await (0, import_promises20.readFile)(file));
18336
+ const size = pngSize(await (0, import_promises21.readFile)(file));
17964
18337
  if (size) ({ width, height } = size);
17965
18338
  }
17966
18339
  return { path: file, contentType, width, height };
@@ -17968,7 +18341,7 @@ async function currentArt(entry, spec) {
17968
18341
  async function cachedFrame(url) {
17969
18342
  if (!url.startsWith("file://")) return null;
17970
18343
  const file = url.slice("file://".length);
17971
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises20.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
18344
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises21.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
17972
18345
  return { path: file, contentType };
17973
18346
  }
17974
18347
  async function prepareReview(provider, lock, opts = {}) {
@@ -17982,11 +18355,11 @@ async function prepareReview(provider, lock, opts = {}) {
17982
18355
  const prefix = opts.routePrefix ?? "";
17983
18356
  const providerUrls = /* @__PURE__ */ new Map();
17984
18357
  const groups = [];
17985
- for (const [key, entry] of Object.entries(lock.entries)) {
17986
- if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key)) continue;
18358
+ for (const [key2, entry] of Object.entries(lock.entries)) {
18359
+ if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key2)) continue;
17987
18360
  if (entry.status !== "review" || !entry.reviewObjectId) continue;
17988
18361
  try {
17989
- const spec = specByKey.get(key);
18362
+ const spec = specByKey.get(key2);
17990
18363
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
17991
18364
  if (state.status !== "review" && state.status !== "review-set" || (state.status === "review" ? !state.candidateUrls.length : !state.frameUrls.length)) continue;
17992
18365
  const urls = state.status === "review" ? state.candidateUrls : state.frameUrls;
@@ -18000,7 +18373,7 @@ async function prepareReview(provider, lock, opts = {}) {
18000
18373
  frameSizes.push(null);
18001
18374
  continue;
18002
18375
  }
18003
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises20.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
18376
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises21.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
18004
18377
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
18005
18378
  frameAssets.push([route, cached2]);
18006
18379
  frameUrls.push(route);
@@ -18018,9 +18391,9 @@ async function prepareReview(provider, lock, opts = {}) {
18018
18391
  reviewAssets.set(currentRoute, { path: current.path, contentType: current.contentType });
18019
18392
  }
18020
18393
  for (const [route, asset] of frameAssets) reviewAssets.set(route, asset);
18021
- providerUrls.set(key, urls);
18394
+ providerUrls.set(key2, urls);
18022
18395
  groups.push({
18023
- key,
18396
+ key: key2,
18024
18397
  assetId: entry.assetId,
18025
18398
  styleId: entry.styleId,
18026
18399
  prompt: entry.prompt,
@@ -18050,7 +18423,7 @@ async function prepareReview(provider, lock, opts = {}) {
18050
18423
  ...entry.batch?.index != null ? { recommendedIndex: entry.batch.index } : {}
18051
18424
  });
18052
18425
  } catch (err) {
18053
- log(` could not load candidates for ${key}: ${err instanceof Error ? err.message : String(err)}`);
18426
+ log(` could not load candidates for ${key2}: ${err instanceof Error ? err.message : String(err)}`);
18054
18427
  }
18055
18428
  }
18056
18429
  if (groups.length === 0) return null;
@@ -18062,18 +18435,18 @@ async function prepareReview(provider, lock, opts = {}) {
18062
18435
  apply: async (body, lockPath) => {
18063
18436
  const { selections } = body;
18064
18437
  let selected = 0;
18065
- for (const { key, index } of selections) {
18066
- const group = byKey.get(key);
18067
- const entry = lock.entries[key];
18438
+ for (const { key: key2, index } of selections) {
18439
+ const group = byKey.get(key2);
18440
+ const entry = lock.entries[key2];
18068
18441
  if (!group || !entry?.reviewObjectId) continue;
18069
18442
  if (!Number.isInteger(index) || index < 0 || index >= group.frameUrls.length) continue;
18070
18443
  if (group.mode === "frame-set") {
18071
- const spec = specByKey.get(key);
18444
+ const spec = specByKey.get(key2);
18072
18445
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
18073
18446
  if (state.status !== "review-set") {
18074
- throw new Error(`Frame set ${key} is no longer ready for review`);
18447
+ throw new Error(`Frame set ${key2} is no longer ready for review`);
18075
18448
  }
18076
- upsert(lock, key, {
18449
+ upsert(lock, key2, {
18077
18450
  status: "selected",
18078
18451
  objectId: state.objectId,
18079
18452
  candidateIndex: null,
@@ -18089,7 +18462,7 @@ async function prepareReview(provider, lock, opts = {}) {
18089
18462
  } : entry.providerMetadata
18090
18463
  });
18091
18464
  selected++;
18092
- log(` accepted ${key} \u2192 ${state.sources.length} ordered frames`);
18465
+ log(` accepted ${key2} \u2192 ${state.sources.length} ordered frames`);
18093
18466
  continue;
18094
18467
  }
18095
18468
  const { objectId, sourceUrl, metadata } = await requireSelectCandidate(provider)(
@@ -18098,11 +18471,11 @@ async function prepareReview(provider, lock, opts = {}) {
18098
18471
  `asset:${entry.assetId}`,
18099
18472
  entry.generator
18100
18473
  );
18101
- upsert(lock, key, {
18474
+ upsert(lock, key2, {
18102
18475
  status: "selected",
18103
18476
  objectId,
18104
18477
  candidateIndex: index,
18105
- sourceUrl: sourceUrl ?? providerUrls.get(key)?.[index] ?? null,
18478
+ sourceUrl: sourceUrl ?? providerUrls.get(key2)?.[index] ?? null,
18106
18479
  sourceUrls: [],
18107
18480
  provider: provider.id,
18108
18481
  providerMetadata: metadata ? {
@@ -18114,7 +18487,7 @@ async function prepareReview(provider, lock, opts = {}) {
18114
18487
  } : entry.providerMetadata
18115
18488
  });
18116
18489
  selected++;
18117
- log(` picked ${key} \u2192 candidate ${index + 1}`);
18490
+ log(` picked ${key2} \u2192 candidate ${index + 1}`);
18118
18491
  }
18119
18492
  await saveLock(lockPath, lock);
18120
18493
  return { selected, skipped: groups.length - selected };
@@ -18154,14 +18527,14 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
18154
18527
 
18155
18528
  // src/gallery/snapshot.ts
18156
18529
  var import_node_crypto7 = require("crypto");
18157
- var import_node_fs33 = require("fs");
18158
- var import_promises28 = require("fs/promises");
18159
- var import_node_path36 = __toESM(require("path"), 1);
18530
+ var import_node_fs35 = require("fs");
18531
+ var import_promises29 = require("fs/promises");
18532
+ var import_node_path38 = __toESM(require("path"), 1);
18160
18533
 
18161
18534
  // src/workspace.ts
18162
- var import_promises21 = require("fs/promises");
18163
- var import_node_fs28 = require("fs");
18164
- var import_node_path29 = __toESM(require("path"), 1);
18535
+ var import_promises22 = require("fs/promises");
18536
+ var import_node_fs30 = require("fs");
18537
+ var import_node_path31 = __toESM(require("path"), 1);
18165
18538
  var import_zod7 = require("zod");
18166
18539
  var WorkspaceProjectSchema = import_zod7.z.object({
18167
18540
  id: import_zod7.z.string().min(1),
@@ -18186,10 +18559,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
18186
18559
  );
18187
18560
  }
18188
18561
  async function loadWorkspace(workspacePath) {
18189
- if (!(0, import_node_fs28.existsSync)(workspacePath)) return { version: 1, projects: [] };
18562
+ if (!(0, import_node_fs30.existsSync)(workspacePath)) return { version: 1, projects: [] };
18190
18563
  let raw;
18191
18564
  try {
18192
- raw = JSON.parse(await (0, import_promises21.readFile)(workspacePath, "utf8"));
18565
+ raw = JSON.parse(await (0, import_promises22.readFile)(workspacePath, "utf8"));
18193
18566
  } catch (err) {
18194
18567
  throw new ProjectError(
18195
18568
  `Workspace catalog at ${workspacePath} is malformed:
@@ -18203,22 +18576,22 @@ async function saveWorkspace(workspacePath, ws) {
18203
18576
  version: 1,
18204
18577
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
18205
18578
  };
18206
- await (0, import_promises21.mkdir)(import_node_path29.default.dirname(import_node_path29.default.resolve(workspacePath)), { recursive: true });
18579
+ await (0, import_promises22.mkdir)(import_node_path31.default.dirname(import_node_path31.default.resolve(workspacePath)), { recursive: true });
18207
18580
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18208
18581
  try {
18209
- await (0, import_promises21.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
18210
- await (0, import_promises21.rename)(tmp, workspacePath);
18582
+ await (0, import_promises22.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
18583
+ await (0, import_promises22.rename)(tmp, workspacePath);
18211
18584
  } finally {
18212
- await (0, import_promises21.rm)(tmp, { force: true });
18585
+ await (0, import_promises22.rm)(tmp, { force: true });
18213
18586
  }
18214
18587
  }
18215
18588
  function toPortablePath(dir, absolute) {
18216
- return import_node_path29.default.relative(dir, absolute).split(import_node_path29.default.sep).join("/");
18589
+ return import_node_path31.default.relative(dir, absolute).split(import_node_path31.default.sep).join("/");
18217
18590
  }
18218
18591
  function resolveProject(dir, project) {
18219
18592
  return {
18220
- manifestPath: import_node_path29.default.resolve(dir, project.manifest.split("/").join(import_node_path29.default.sep)),
18221
- lockPath: import_node_path29.default.resolve(dir, project.lock.split("/").join(import_node_path29.default.sep))
18593
+ manifestPath: import_node_path31.default.resolve(dir, project.manifest.split("/").join(import_node_path31.default.sep)),
18594
+ lockPath: import_node_path31.default.resolve(dir, project.lock.split("/").join(import_node_path31.default.sep))
18222
18595
  };
18223
18596
  }
18224
18597
  function validateWorkspace(ws, dir) {
@@ -18231,21 +18604,21 @@ function validateWorkspace(ws, dir) {
18231
18604
  const { manifestPath, lockPath } = resolveProject(dir, project);
18232
18605
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project.id]);
18233
18606
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project.id]);
18234
- if (import_node_path29.default.isAbsolute(project.manifest) || import_node_path29.default.isAbsolute(project.lock)) {
18607
+ if (import_node_path31.default.isAbsolute(project.manifest) || import_node_path31.default.isAbsolute(project.lock)) {
18235
18608
  diagnostics.push({
18236
18609
  id: "absolute-path",
18237
18610
  level: "warning",
18238
18611
  message: `project "${project.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
18239
18612
  });
18240
18613
  }
18241
- if (!(0, import_node_fs28.existsSync)(manifestPath)) {
18614
+ if (!(0, import_node_fs30.existsSync)(manifestPath)) {
18242
18615
  diagnostics.push({
18243
18616
  id: "missing-manifest",
18244
18617
  level: "error",
18245
18618
  message: `project "${project.id}" manifest not found: ${manifestPath}`
18246
18619
  });
18247
18620
  }
18248
- if (!(0, import_node_fs28.existsSync)(lockPath)) {
18621
+ if (!(0, import_node_fs30.existsSync)(lockPath)) {
18249
18622
  diagnostics.push({
18250
18623
  id: "missing-lock",
18251
18624
  level: "error",
@@ -18292,16 +18665,16 @@ function validateWorkspace(ws, dir) {
18292
18665
  }
18293
18666
 
18294
18667
  // src/gallery/edit.ts
18295
- var import_promises27 = require("fs/promises");
18296
- var import_node_path35 = __toESM(require("path"), 1);
18668
+ var import_promises28 = require("fs/promises");
18669
+ var import_node_path37 = __toESM(require("path"), 1);
18297
18670
  var import_zod13 = require("zod");
18298
18671
 
18299
18672
  // src/manifest-edit.ts
18300
- var import_promises22 = require("fs/promises");
18301
- var import_node_path30 = __toESM(require("path"), 1);
18673
+ var import_promises23 = require("fs/promises");
18674
+ var import_node_path32 = __toESM(require("path"), 1);
18302
18675
  var import_zod8 = require("zod");
18303
18676
  var HexSha = import_zod8.z.string().regex(/^[0-9a-f]{64}$/);
18304
- var ProjectFileSchema = import_zod8.z.string().min(1).refine((file) => !import_node_path30.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
18677
+ var ProjectFileSchema = import_zod8.z.string().min(1).refine((file) => !import_node_path32.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
18305
18678
  var AssetPatchSchema = import_zod8.z.object({
18306
18679
  prompt: import_zod8.z.string().optional(),
18307
18680
  /** Per-style override for the style being viewed; null removes it. */
@@ -18568,9 +18941,9 @@ function styleProvider(raw, styleId, seen = /* @__PURE__ */ new Set()) {
18568
18941
  seen.add(styleId);
18569
18942
  return style.extends ? styleProvider(raw, style.extends, seen) : raw.provider ?? "pixellab";
18570
18943
  }
18571
- function setOrDelete(target, key, value) {
18572
- if (value === null || value === void 0) delete target[key];
18573
- else target[key] = value;
18944
+ function setOrDelete(target, key2, value) {
18945
+ if (value === null || value === void 0) delete target[key2];
18946
+ else target[key2] = value;
18574
18947
  }
18575
18948
  function assetStyles(raw, asset) {
18576
18949
  const own = Array.isArray(asset.styles) ? asset.styles : [];
@@ -18721,8 +19094,8 @@ function applyEdit(raw, edit) {
18721
19094
  }
18722
19095
  }
18723
19096
  async function withCandidate(manifestPath, edit, use, unchanged) {
18724
- const absolute = import_node_path30.default.resolve(manifestPath);
18725
- const original = await (0, import_promises22.readFile)(absolute, "utf8");
19097
+ const absolute = import_node_path32.default.resolve(manifestPath);
19098
+ const original = await (0, import_promises23.readFile)(absolute, "utf8");
18726
19099
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
18727
19100
  let raw;
18728
19101
  try {
@@ -18735,12 +19108,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
18735
19108
  applyEdit(raw, edit);
18736
19109
  const next = serializeLike(original, raw);
18737
19110
  if (next === original) return unchanged(absolute, original);
18738
- const tmp = import_node_path30.default.join(
18739
- import_node_path30.default.dirname(absolute),
18740
- `.${import_node_path30.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
19111
+ const tmp = import_node_path32.default.join(
19112
+ import_node_path32.default.dirname(absolute),
19113
+ `.${import_node_path32.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
18741
19114
  );
18742
19115
  try {
18743
- await (0, import_promises22.writeFile)(tmp, next);
19116
+ await (0, import_promises23.writeFile)(tmp, next);
18744
19117
  let specs;
18745
19118
  try {
18746
19119
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -18750,7 +19123,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
18750
19123
  }
18751
19124
  return await use({ absolute, original, next, tmp, specs });
18752
19125
  } finally {
18753
- await (0, import_promises22.rm)(tmp, { force: true });
19126
+ await (0, import_promises23.rm)(tmp, { force: true });
18754
19127
  }
18755
19128
  }
18756
19129
  async function applyManifestEdit(manifestPath, edit) {
@@ -18758,7 +19131,7 @@ async function applyManifestEdit(manifestPath, edit) {
18758
19131
  manifestPath,
18759
19132
  edit,
18760
19133
  async ({ absolute, next, tmp }) => {
18761
- await (0, import_promises22.rename)(tmp, absolute);
19134
+ await (0, import_promises23.rename)(tmp, absolute);
18762
19135
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
18763
19136
  },
18764
19137
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -18766,18 +19139,18 @@ async function applyManifestEdit(manifestPath, edit) {
18766
19139
  }
18767
19140
 
18768
19141
  // src/pipeline/hand-edit.ts
18769
- var import_node_fs29 = require("fs");
18770
- var import_promises23 = require("fs/promises");
18771
- var import_node_path31 = __toESM(require("path"), 1);
19142
+ var import_node_fs31 = require("fs");
19143
+ var import_promises24 = require("fs/promises");
19144
+ var import_node_path33 = __toESM(require("path"), 1);
18772
19145
  var import_zod9 = require("zod");
18773
19146
  var HAND_EDIT_DIR = "edits";
18774
19147
  function handEditPath(loaded, spec) {
18775
19148
  const style = loaded.manifest.styles[spec.styleId];
18776
- const outDir = import_node_path31.default.resolve(loaded.root, style?.outDir ?? ".");
18777
- const relative = import_node_path31.default.relative(outDir, spec.outFile);
18778
- const inside = relative && !relative.startsWith("..") && !import_node_path31.default.isAbsolute(relative);
18779
- const file = inside ? relative : import_node_path31.default.basename(spec.outFile);
18780
- return import_node_path31.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
19149
+ const outDir = import_node_path33.default.resolve(loaded.root, style?.outDir ?? ".");
19150
+ const relative = import_node_path33.default.relative(outDir, spec.outFile);
19151
+ const inside = relative && !relative.startsWith("..") && !import_node_path33.default.isAbsolute(relative);
19152
+ const file = inside ? relative : import_node_path33.default.basename(spec.outFile);
19153
+ return import_node_path33.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
18781
19154
  }
18782
19155
  function handEditBases(spec, lock) {
18783
19156
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -18790,10 +19163,10 @@ function handEditBases(spec, lock) {
18790
19163
  }));
18791
19164
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
18792
19165
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
18793
- if (!members.every((member) => (0, import_node_fs29.existsSync)(member.path))) return null;
19166
+ if (!members.every((member) => (0, import_node_fs31.existsSync)(member.path))) return null;
18794
19167
  return members.map(({ role, path: file }) => ({ role, path: file }));
18795
19168
  }
18796
- return (0, import_node_fs29.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
19169
+ return (0, import_node_fs31.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
18797
19170
  }
18798
19171
  function handEditBase(spec, lock) {
18799
19172
  const bases = handEditBases(spec, lock);
@@ -18823,19 +19196,19 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
18823
19196
  `${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`
18824
19197
  );
18825
19198
  }
18826
- const existing = spec.source ? import_node_path31.default.resolve(loaded.root, spec.source) : null;
19199
+ const existing = spec.source ? import_node_path33.default.resolve(loaded.root, spec.source) : null;
18827
19200
  const editPath = existing ?? handEditPath(loaded, spec);
18828
19201
  const members = handEditMembers(loaded, spec, lock, editPath);
18829
19202
  let created = false;
18830
19203
  for (const member of members) {
18831
- if ((0, import_node_fs29.existsSync)(member.path)) continue;
19204
+ if ((0, import_node_fs31.existsSync)(member.path)) continue;
18832
19205
  if (!member.base) {
18833
19206
  throw new ManifestEditError(
18834
19207
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
18835
19208
  );
18836
19209
  }
18837
- await (0, import_promises23.mkdir)(import_node_path31.default.dirname(member.path), { recursive: true });
18838
- await (0, import_promises23.copyFile)(member.base, member.path);
19210
+ await (0, import_promises24.mkdir)(import_node_path33.default.dirname(member.path), { recursive: true });
19211
+ await (0, import_promises24.copyFile)(member.base, member.path);
18839
19212
  created = true;
18840
19213
  }
18841
19214
  const source = portableOutputPath(editPath, loaded.root);
@@ -18913,7 +19286,7 @@ function handEditProjectPath(editPath) {
18913
19286
  async function readHandEditCompanion(editPath) {
18914
19287
  let text;
18915
19288
  try {
18916
- text = await (0, import_promises23.readFile)(handEditCompanionPath(editPath), "utf8");
19289
+ text = await (0, import_promises24.readFile)(handEditCompanionPath(editPath), "utf8");
18917
19290
  } catch {
18918
19291
  return null;
18919
19292
  }
@@ -18956,7 +19329,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
18956
19329
  }
18957
19330
  });
18958
19331
  const bases = handEditBases(spec, lock);
18959
- const expectedSize = bases?.[0] ? decodePng(await (0, import_promises23.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
19332
+ const expectedSize = bases?.[0] ? decodePng(await (0, import_promises24.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
18960
19333
  for (const [index, image] of decoded.entries()) {
18961
19334
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
18962
19335
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -18972,7 +19345,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
18972
19345
  editor: input.editor,
18973
19346
  protocol: input.protocol,
18974
19347
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
18975
- project: projectPath ? import_node_path31.default.basename(projectPath) : null,
19348
+ project: projectPath ? import_node_path33.default.basename(projectPath) : null,
18976
19349
  outputs: incoming.map((frame, index) => ({
18977
19350
  role: frame.role,
18978
19351
  basedOn: basedOnHash(entry, index),
@@ -19002,10 +19375,10 @@ function basedOnHash(entry, index) {
19002
19375
  async function replaceFile(file, bytes) {
19003
19376
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19004
19377
  try {
19005
- await (0, import_promises23.writeFile)(tmp, bytes);
19006
- await (0, import_promises23.rename)(tmp, file);
19378
+ await (0, import_promises24.writeFile)(tmp, bytes);
19379
+ await (0, import_promises24.rename)(tmp, file);
19007
19380
  } finally {
19008
- await (0, import_promises23.rm)(tmp, { force: true });
19381
+ await (0, import_promises24.rm)(tmp, { force: true });
19009
19382
  }
19010
19383
  }
19011
19384
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -19014,9 +19387,9 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
19014
19387
  }
19015
19388
 
19016
19389
  // src/gallery/upload.ts
19017
- var import_node_fs30 = require("fs");
19018
- var import_promises24 = require("fs/promises");
19019
- var import_node_path32 = __toESM(require("path"), 1);
19390
+ var import_node_fs32 = require("fs");
19391
+ var import_promises25 = require("fs/promises");
19392
+ var import_node_path34 = __toESM(require("path"), 1);
19020
19393
  var import_zod10 = require("zod");
19021
19394
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
19022
19395
  var UploadImageSchema = import_zod10.z.object({
@@ -19029,12 +19402,12 @@ var UploadImageSchema = import_zod10.z.object({
19029
19402
  overwrite: import_zod10.z.boolean().optional()
19030
19403
  }).strict();
19031
19404
  async function saveProjectImage(root, request) {
19032
- const file = import_node_path32.default.resolve(root, request.path);
19033
- const relative = import_node_path32.default.relative(root, file);
19034
- if (relative.startsWith("..") || import_node_path32.default.isAbsolute(relative)) {
19405
+ const file = import_node_path34.default.resolve(root, request.path);
19406
+ const relative = import_node_path34.default.relative(root, file);
19407
+ if (relative.startsWith("..") || import_node_path34.default.isAbsolute(relative)) {
19035
19408
  throw new ManifestEditError("an upload must stay inside the project");
19036
19409
  }
19037
- const extension = import_node_path32.default.extname(file).toLowerCase();
19410
+ const extension = import_node_path34.default.extname(file).toLowerCase();
19038
19411
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
19039
19412
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
19040
19413
  const bytes = Buffer.from(request.base64, "base64");
@@ -19046,18 +19419,18 @@ async function saveProjectImage(root, request) {
19046
19419
  if (metadata.format !== expected) {
19047
19420
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
19048
19421
  }
19049
- if ((0, import_node_fs30.existsSync)(file) && !request.overwrite) {
19050
- throw new ManifestEditError(`${relative.split(import_node_path32.default.sep).join("/")} already exists; choose another name, or replace it`);
19422
+ if ((0, import_node_fs32.existsSync)(file) && !request.overwrite) {
19423
+ throw new ManifestEditError(`${relative.split(import_node_path34.default.sep).join("/")} already exists; choose another name, or replace it`);
19051
19424
  }
19052
- await (0, import_promises24.mkdir)(import_node_path32.default.dirname(file), { recursive: true });
19053
- await (0, import_promises24.writeFile)(file, bytes);
19054
- return relative.split(import_node_path32.default.sep).join("/");
19425
+ await (0, import_promises25.mkdir)(import_node_path34.default.dirname(file), { recursive: true });
19426
+ await (0, import_promises25.writeFile)(file, bytes);
19427
+ return relative.split(import_node_path34.default.sep).join("/");
19055
19428
  }
19056
19429
 
19057
19430
  // src/gallery/image-revision.ts
19058
- var import_node_fs31 = require("fs");
19059
- var import_promises25 = require("fs/promises");
19060
- var import_node_path33 = __toESM(require("path"), 1);
19431
+ var import_node_fs33 = require("fs");
19432
+ var import_promises26 = require("fs/promises");
19433
+ var import_node_path35 = __toESM(require("path"), 1);
19061
19434
  var import_zod11 = require("zod");
19062
19435
  var InpaintRevisionRequestSchema = import_zod11.z.object({
19063
19436
  action: import_zod11.z.literal("create-inpaint-revision"),
@@ -19076,15 +19449,15 @@ var InpaintRevisionRequestSchema = import_zod11.z.object({
19076
19449
  overwrite: import_zod11.z.boolean().optional()
19077
19450
  }).strict();
19078
19451
  async function createInpaintRevision(manifestPath, request) {
19079
- const root = import_node_path33.default.dirname(import_node_path33.default.resolve(manifestPath));
19080
- if (import_node_path33.default.extname(request.maskPath).toLowerCase() !== ".png") {
19452
+ const root = import_node_path35.default.dirname(import_node_path35.default.resolve(manifestPath));
19453
+ if (import_node_path35.default.extname(request.maskPath).toLowerCase() !== ".png") {
19081
19454
  throw new ManifestEditError("the mask must be a .png path inside the project");
19082
19455
  }
19083
19456
  const bytes = Buffer.from(request.maskBase64, "base64");
19084
19457
  const metadata = imageMetadata(bytes);
19085
19458
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
19086
- const file = import_node_path33.default.resolve(root, request.maskPath);
19087
- const previous = (0, import_node_fs31.existsSync)(file) ? await (0, import_promises25.readFile)(file) : null;
19459
+ const file = import_node_path35.default.resolve(root, request.maskPath);
19460
+ const previous = (0, import_node_fs33.existsSync)(file) ? await (0, import_promises26.readFile)(file) : null;
19088
19461
  const mask = await saveProjectImage(root, {
19089
19462
  action: "upload-image",
19090
19463
  path: request.maskPath,
@@ -19103,17 +19476,17 @@ async function createInpaintRevision(manifestPath, request) {
19103
19476
  }
19104
19477
  });
19105
19478
  } catch (error) {
19106
- if (previous) await (0, import_promises25.writeFile)(file, previous);
19107
- else await (0, import_promises25.rm)(file, { force: true });
19479
+ if (previous) await (0, import_promises26.writeFile)(file, previous);
19480
+ else await (0, import_promises26.rm)(file, { force: true });
19108
19481
  throw error;
19109
19482
  }
19110
19483
  return mask;
19111
19484
  }
19112
19485
 
19113
19486
  // src/gallery/skeleton.ts
19114
- var import_node_fs32 = require("fs");
19115
- var import_promises26 = require("fs/promises");
19116
- var import_node_path34 = __toESM(require("path"), 1);
19487
+ var import_node_fs34 = require("fs");
19488
+ var import_promises27 = require("fs/promises");
19489
+ var import_node_path36 = __toESM(require("path"), 1);
19117
19490
  var import_zod12 = require("zod");
19118
19491
  var SkeletonEstimateRequestSchema = import_zod12.z.object({
19119
19492
  project: import_zod12.z.string().min(1).optional(),
@@ -19152,21 +19525,21 @@ var SkeletonKeypointsUpdateSchema = import_zod12.z.object({
19152
19525
  set: SkeletonSetSchema
19153
19526
  }).strict();
19154
19527
  async function createSkeletonAnimation(manifestPath, request) {
19155
- const root = import_node_path34.default.dirname(import_node_path34.default.resolve(manifestPath));
19156
- const file = import_node_path34.default.resolve(root, request.keypointsFile);
19157
- const relative = import_node_path34.default.relative(root, file);
19158
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path34.default.isAbsolute(relative)) {
19528
+ const root = import_node_path36.default.dirname(import_node_path36.default.resolve(manifestPath));
19529
+ const file = import_node_path36.default.resolve(root, request.keypointsFile);
19530
+ const relative = import_node_path36.default.relative(root, file);
19531
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path36.default.isAbsolute(relative)) {
19159
19532
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
19160
19533
  }
19161
- const existed = (0, import_node_fs32.existsSync)(file);
19534
+ const existed = (0, import_node_fs34.existsSync)(file);
19162
19535
  let previous = null;
19163
19536
  if (request.set) {
19164
19537
  if (existed && !request.overwrite) {
19165
19538
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
19166
19539
  }
19167
- if (existed) previous = await (0, import_promises26.readFile)(file);
19168
- await (0, import_promises26.mkdir)(import_node_path34.default.dirname(file), { recursive: true });
19169
- await (0, import_promises26.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
19540
+ if (existed) previous = await (0, import_promises27.readFile)(file);
19541
+ await (0, import_promises27.mkdir)(import_node_path36.default.dirname(file), { recursive: true });
19542
+ await (0, import_promises27.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
19170
19543
  } else if (!existed) {
19171
19544
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
19172
19545
  }
@@ -19181,7 +19554,7 @@ async function createSkeletonAnimation(manifestPath, request) {
19181
19554
  revision: {
19182
19555
  mode: "animate-skeleton",
19183
19556
  from: request.from,
19184
- keypointsFile: relative.split(import_node_path34.default.sep).join("/"),
19557
+ keypointsFile: relative.split(import_node_path36.default.sep).join("/"),
19185
19558
  direction: request.direction,
19186
19559
  description: request.description,
19187
19560
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -19190,31 +19563,31 @@ async function createSkeletonAnimation(manifestPath, request) {
19190
19563
  });
19191
19564
  } catch (error) {
19192
19565
  if (request.set) {
19193
- if (previous) await (0, import_promises26.writeFile)(file, previous);
19194
- else await (0, import_promises26.rm)(file, { force: true });
19566
+ if (previous) await (0, import_promises27.writeFile)(file, previous);
19567
+ else await (0, import_promises27.rm)(file, { force: true });
19195
19568
  }
19196
19569
  throw error;
19197
19570
  }
19198
19571
  }
19199
19572
  async function updateSkeletonKeypoints(ctx, request) {
19200
- const key = lockKey(request.styleId, request.assetId);
19201
- const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key);
19202
- if (!spec) throw new ManifestEditError(`"${key}" is not declared by the manifest`);
19573
+ const key2 = lockKey(request.styleId, request.assetId);
19574
+ const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key2);
19575
+ if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
19203
19576
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
19204
- if (!file) throw new ManifestEditError(`${key} is not an animate-skeleton revision`);
19205
- const relative = import_node_path34.default.relative(ctx.loaded.root, file);
19206
- if (relative.startsWith("..") || import_node_path34.default.isAbsolute(relative)) {
19207
- throw new ManifestEditError(`${key}'s keypoints file is outside the project; edit it by hand`);
19577
+ if (!file) throw new ManifestEditError(`${key2} is not an animate-skeleton revision`);
19578
+ const relative = import_node_path36.default.relative(ctx.loaded.root, file);
19579
+ if (relative.startsWith("..") || import_node_path36.default.isAbsolute(relative)) {
19580
+ throw new ManifestEditError(`${key2}'s keypoints file is outside the project; edit it by hand`);
19208
19581
  }
19209
- const current = (0, import_node_fs32.existsSync)(file) ? sha256(await (0, import_promises26.readFile)(file)) : null;
19582
+ const current = (0, import_node_fs34.existsSync)(file) ? sha256(await (0, import_promises27.readFile)(file)) : null;
19210
19583
  if (current !== request.expectedSha256) {
19211
19584
  throw Object.assign(
19212
- new Error(`${relative.split(import_node_path34.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
19585
+ new Error(`${relative.split(import_node_path36.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
19213
19586
  { status: 409 }
19214
19587
  );
19215
19588
  }
19216
- await (0, import_promises26.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
19217
- return relative.split(import_node_path34.default.sep).join("/");
19589
+ await (0, import_promises27.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
19590
+ return relative.split(import_node_path36.default.sep).join("/");
19218
19591
  }
19219
19592
 
19220
19593
  // src/gallery/edit.ts
@@ -19268,7 +19641,7 @@ function createGalleryEditHandler(opts) {
19268
19641
  const history = /* @__PURE__ */ new Map();
19269
19642
  const manifestOf = async (project) => {
19270
19643
  try {
19271
- return import_node_path35.default.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
19644
+ return import_node_path37.default.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
19272
19645
  } catch {
19273
19646
  return null;
19274
19647
  }
@@ -19278,7 +19651,7 @@ function createGalleryEditHandler(opts) {
19278
19651
  if (undo.success) {
19279
19652
  const manifestPath2 = await manifestOf(undo.data.project);
19280
19653
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
19281
- const current = await (0, import_promises27.readFile)(manifestPath2, "utf8");
19654
+ const current = await (0, import_promises28.readFile)(manifestPath2, "utf8");
19282
19655
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
19283
19656
  const stack = history.get(manifestPath2) ?? [];
19284
19657
  const last = stack[stack.length - 1];
@@ -19288,17 +19661,17 @@ function createGalleryEditHandler(opts) {
19288
19661
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
19289
19662
  }
19290
19663
  const tmp = manifestPath2 + ".pixelkiln-undo";
19291
- await (0, import_promises27.writeFile)(tmp, last.before);
19292
- await (0, import_promises27.rename)(tmp, manifestPath2);
19664
+ await (0, import_promises28.writeFile)(tmp, last.before);
19665
+ await (0, import_promises28.rename)(tmp, manifestPath2);
19293
19666
  stack.pop();
19294
- log(` manifest edit undone in ${import_node_path35.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
19667
+ log(` manifest edit undone in ${import_node_path37.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
19295
19668
  return opts.reload();
19296
19669
  }
19297
19670
  const manifestPath = await manifestOf(body?.project);
19298
- const before = manifestPath ? await (0, import_promises27.readFile)(manifestPath, "utf8").catch(() => null) : null;
19671
+ const before = manifestPath ? await (0, import_promises28.readFile)(manifestPath, "utf8").catch(() => null) : null;
19299
19672
  const build = await apply(body);
19300
19673
  if (manifestPath && before !== null) {
19301
- const after = await (0, import_promises27.readFile)(manifestPath, "utf8").catch(() => null);
19674
+ const after = await (0, import_promises28.readFile)(manifestPath, "utf8").catch(() => null);
19302
19675
  if (after !== null && after !== before) {
19303
19676
  const stack = history.get(manifestPath) ?? [];
19304
19677
  stack.push({ before, afterSha: sha256(after) });
@@ -19353,7 +19726,7 @@ function createEditApplier(opts, log) {
19353
19726
  } catch (error) {
19354
19727
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
19355
19728
  }
19356
- const written = await saveProjectImage(import_node_path35.default.dirname(import_node_path35.default.resolve(manifestPath2)), upload.data);
19729
+ const written = await saveProjectImage(import_node_path37.default.dirname(import_node_path37.default.resolve(manifestPath2)), upload.data);
19357
19730
  log(` image added: ${written}`);
19358
19731
  return opts.reload();
19359
19732
  }
@@ -19420,7 +19793,7 @@ function createEditApplier(opts, log) {
19420
19793
  }
19421
19794
  const result = await applyManifestEdit(manifestPath, parsed.data);
19422
19795
  if (result.changed) {
19423
- const relative = import_node_path35.default.relative(process.cwd(), result.manifestPath);
19796
+ const relative = import_node_path37.default.relative(process.cwd(), result.manifestPath);
19424
19797
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
19425
19798
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
19426
19799
  }
@@ -19448,7 +19821,7 @@ function describeEdit(edit) {
19448
19821
  // src/gallery/snapshot.ts
19449
19822
  var PROJECT_FILE_TYPE = "application/octet-stream";
19450
19823
  function galleryMediaId(absolutePath) {
19451
- return (0, import_node_crypto7.createHash)("sha256").update(import_node_path36.default.resolve(absolutePath)).digest("hex").slice(0, 24);
19824
+ return (0, import_node_crypto7.createHash)("sha256").update(import_node_path38.default.resolve(absolutePath)).digest("hex").slice(0, 24);
19452
19825
  }
19453
19826
  function galleryMediaRoute(id) {
19454
19827
  return `/media/${id}`;
@@ -19472,9 +19845,9 @@ function describeHistory(media, entry, cacheDir) {
19472
19845
  return (entry.history ?? []).map((generation, i) => {
19473
19846
  const outputs = generation.outputs.map((output) => {
19474
19847
  const mediaType = output.mediaType ?? MediaType.PNG;
19475
- const file = import_node_path36.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
19848
+ const file = import_node_path38.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
19476
19849
  let url = null;
19477
- if ((0, import_node_fs33.existsSync)(file)) {
19850
+ if ((0, import_node_fs35.existsSync)(file)) {
19478
19851
  const id = galleryMediaId(file);
19479
19852
  media.set(id, { path: file, contentType: mediaType });
19480
19853
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -19506,7 +19879,7 @@ function describeHistory(media, entry, cacheDir) {
19506
19879
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
19507
19880
  async function samePixels(a, b) {
19508
19881
  try {
19509
- const [left, right] = await Promise.all([(0, import_promises28.readFile)(a), (0, import_promises28.readFile)(b)]);
19882
+ const [left, right] = await Promise.all([(0, import_promises29.readFile)(a), (0, import_promises29.readFile)(b)]);
19510
19883
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
19511
19884
  const x = decodePng(left);
19512
19885
  const y = decodePng(right);
@@ -19572,7 +19945,7 @@ function describeCharacter(spec, entry) {
19572
19945
  }
19573
19946
  async function fileInfo(absolutePath) {
19574
19947
  try {
19575
- const info = await (0, import_promises28.stat)(absolutePath);
19948
+ const info = await (0, import_promises29.stat)(absolutePath);
19576
19949
  return info.isFile() ? { bytes: info.size, modifiedAt: info.mtime.toISOString() } : null;
19577
19950
  } catch {
19578
19951
  return null;
@@ -19604,10 +19977,10 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
19604
19977
  async function describeQuality(media, root, inspection) {
19605
19978
  const outputPaths = inspection.outputs ?? [inspection.output];
19606
19979
  const outputs = await Promise.all(
19607
- outputPaths.map((file) => describeOutput(media, root, import_node_path36.default.resolve(root, file)))
19980
+ outputPaths.map((file) => describeOutput(media, root, import_node_path38.default.resolve(root, file)))
19608
19981
  );
19609
- const recordPath = import_node_path36.default.resolve(root, inspection.record);
19610
- const recordExists = (0, import_node_fs33.existsSync)(recordPath);
19982
+ const recordPath = import_node_path38.default.resolve(root, inspection.record);
19983
+ const recordExists = (0, import_node_fs35.existsSync)(recordPath);
19611
19984
  let options = null;
19612
19985
  let check = null;
19613
19986
  if (recordExists) {
@@ -19626,7 +19999,7 @@ async function describeQuality(media, root, inspection) {
19626
19999
  return {
19627
20000
  state: inspection.state,
19628
20001
  reason: inspection.reason,
19629
- output: portableOutputPath(import_node_path36.default.resolve(root, inspection.output), root),
20002
+ output: portableOutputPath(import_node_path38.default.resolve(root, inspection.output), root),
19630
20003
  record: portableOutputPath(recordPath, root),
19631
20004
  recordExists,
19632
20005
  outputs,
@@ -19664,9 +20037,9 @@ async function buildGallerySnapshot(opts) {
19664
20037
  const media = /* @__PURE__ */ new Map();
19665
20038
  const plan = await buildPlan(specs, lock);
19666
20039
  const items = [];
19667
- const manifestText = await (0, import_promises28.readFile)(loaded.path, "utf8");
20040
+ const manifestText = await (0, import_promises29.readFile)(loaded.path, "utf8");
19668
20041
  const manifestSha256 = sha256(manifestText);
19669
- const cacheDir = import_node_path36.default.resolve(import_node_path36.default.dirname(opts.lockPath), ".pixelkiln", "cache");
20042
+ const cacheDir = import_node_path38.default.resolve(import_node_path38.default.dirname(opts.lockPath), ".pixelkiln", "cache");
19670
20043
  let rawStyles = {};
19671
20044
  try {
19672
20045
  const raw = JSON.parse(manifestText);
@@ -19674,8 +20047,8 @@ async function buildGallerySnapshot(opts) {
19674
20047
  } catch {
19675
20048
  }
19676
20049
  for (const planItem of plan.items) {
19677
- const { spec, key } = planItem;
19678
- const entry = lock.entries[key];
20050
+ const { spec, key: key2 } = planItem;
20051
+ const entry = lock.entries[key2];
19679
20052
  const asset = loaded.manifest.assets[spec.assetId] ?? null;
19680
20053
  let outputs;
19681
20054
  let edit = null;
@@ -19690,12 +20063,12 @@ async function buildGallerySnapshot(opts) {
19690
20063
  )
19691
20064
  );
19692
20065
  if (spec.source) {
19693
- const editPath = import_node_path36.default.resolve(root, spec.source);
20066
+ const editPath = import_node_path38.default.resolve(root, spec.source);
19694
20067
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
19695
20068
  const editShas = await Promise.all(
19696
20069
  Array.from({ length: memberCount }, async (_, index) => {
19697
20070
  const file = sourceOutputPath(spec.source, entry, index, root);
19698
- return { file, sha256: (0, import_node_fs33.existsSync)(file) ? await sha256File(file) : null };
20071
+ return { file, sha256: (0, import_node_fs35.existsSync)(file) ? await sha256File(file) : null };
19699
20072
  })
19700
20073
  );
19701
20074
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -19703,7 +20076,7 @@ async function buildGallerySnapshot(opts) {
19703
20076
  const companion = await readHandEditCompanion(editPath);
19704
20077
  if (companion) {
19705
20078
  const projectPath = handEditProjectPath(editPath);
19706
- const project = companion.project && (0, import_node_fs33.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
20079
+ const project = companion.project && (0, import_node_fs35.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
19707
20080
  let projectUrl = null;
19708
20081
  if (project) {
19709
20082
  const id = galleryMediaId(projectPath);
@@ -19739,17 +20112,17 @@ async function buildGallerySnapshot(opts) {
19739
20112
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
19740
20113
  }
19741
20114
  } else if (spec.source) {
19742
- outputs = [await describeOutput(media, root, import_node_path36.default.resolve(root, spec.source))];
19743
- } else if (!entry && (0, import_node_fs33.existsSync)(spec.outFile)) {
20115
+ outputs = [await describeOutput(media, root, import_node_path38.default.resolve(root, spec.source))];
20116
+ } else if (!entry && (0, import_node_fs35.existsSync)(spec.outFile)) {
19744
20117
  outputs = [await describeOutput(media, root, spec.outFile)];
19745
20118
  } else {
19746
20119
  outputs = [];
19747
20120
  }
19748
20121
  const quality = planItem.quality ? await describeQuality(media, root, planItem.quality) : null;
19749
20122
  items.push({
19750
- id: key,
20123
+ id: key2,
19751
20124
  project: null,
19752
- key,
20125
+ key: key2,
19753
20126
  styleId: spec.styleId,
19754
20127
  assetId: spec.assetId,
19755
20128
  declared: true,
@@ -19807,8 +20180,8 @@ async function buildGallerySnapshot(opts) {
19807
20180
  });
19808
20181
  }
19809
20182
  const shown = new Set(items.map((item) => item.key));
19810
- for (const [key, entry] of Object.entries(lock.entries)) {
19811
- if (shown.has(key)) continue;
20183
+ for (const [key2, entry] of Object.entries(lock.entries)) {
20184
+ if (shown.has(key2)) continue;
19812
20185
  if (isDeclared(loaded, entry.styleId, entry.assetId)) continue;
19813
20186
  if (!matchesFilter(filter, entry.styleId, entry.assetId)) continue;
19814
20187
  const outputs = await Promise.all(
@@ -19817,9 +20190,9 @@ async function buildGallerySnapshot(opts) {
19817
20190
  )
19818
20191
  );
19819
20192
  items.push({
19820
- id: key,
20193
+ id: key2,
19821
20194
  project: null,
19822
- key,
20195
+ key: key2,
19823
20196
  styleId: entry.styleId,
19824
20197
  assetId: entry.assetId,
19825
20198
  declared: false,
@@ -19920,7 +20293,7 @@ async function buildGallerySnapshot(opts) {
19920
20293
  } : null,
19921
20294
  tags: style?.tags ?? [],
19922
20295
  extends: typeof rawStyle?.extends === "string" ? rawStyle.extends : null,
19923
- ownFields: rawStyle ? Object.keys(rawStyle).filter((key) => key !== "extends") : [],
20296
+ ownFields: rawStyle ? Object.keys(rawStyle).filter((key2) => key2 !== "extends") : [],
19924
20297
  items: styleItems.length,
19925
20298
  spendByUnit: spend,
19926
20299
  regenerate: {
@@ -19944,7 +20317,7 @@ async function buildGallerySnapshot(opts) {
19944
20317
  id: loaded.manifest.name,
19945
20318
  name: loaded.manifest.name,
19946
20319
  manifest: loaded.path,
19947
- lock: import_node_path36.default.resolve(opts.lockPath),
20320
+ lock: import_node_path38.default.resolve(opts.lockPath),
19948
20321
  root,
19949
20322
  provider: loaded.manifest.provider,
19950
20323
  account: null,
@@ -19970,7 +20343,7 @@ async function buildGallerySnapshot(opts) {
19970
20343
  return { snapshot, media };
19971
20344
  }
19972
20345
  async function buildWorkspaceGallerySnapshot(opts) {
19973
- const dir = import_node_path36.default.dirname(import_node_path36.default.resolve(opts.workspacePath));
20346
+ const dir = import_node_path38.default.dirname(import_node_path38.default.resolve(opts.workspacePath));
19974
20347
  const media = /* @__PURE__ */ new Map();
19975
20348
  const projects = [];
19976
20349
  const items = [];
@@ -20013,11 +20386,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
20013
20386
  id: project.id,
20014
20387
  name: loaded.manifest.name,
20015
20388
  manifest: manifestPath,
20016
- lock: import_node_path36.default.resolve(lockPath),
20389
+ lock: import_node_path38.default.resolve(lockPath),
20017
20390
  root: loaded.root,
20018
20391
  provider: loaded.manifest.provider,
20019
20392
  account: project.account ?? null,
20020
- manifestSha256: manifestSha256 ?? sha256(await (0, import_promises28.readFile)(manifestPath, "utf8")),
20393
+ manifestSha256: manifestSha256 ?? sha256(await (0, import_promises29.readFile)(manifestPath, "utf8")),
20021
20394
  historyLimit: historyLimit(loaded.manifest),
20022
20395
  entries: Object.keys(lock.entries).length,
20023
20396
  items: projectItems.length,
@@ -20029,8 +20402,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
20029
20402
  id: project.id,
20030
20403
  name: project.id,
20031
20404
  manifest: manifestPath,
20032
- lock: import_node_path36.default.resolve(lockPath),
20033
- root: import_node_path36.default.dirname(manifestPath),
20405
+ lock: import_node_path38.default.resolve(lockPath),
20406
+ root: import_node_path38.default.dirname(manifestPath),
20034
20407
  provider: project.provider,
20035
20408
  account: project.account ?? null,
20036
20409
  manifestSha256: null,
@@ -20057,7 +20430,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
20057
20430
  version: 1,
20058
20431
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
20059
20432
  project: null,
20060
- workspace: { path: import_node_path36.default.resolve(opts.workspacePath), dir, projects },
20433
+ workspace: { path: import_node_path38.default.resolve(opts.workspacePath), dir, projects },
20061
20434
  filter,
20062
20435
  totals: {
20063
20436
  entries: projects.reduce((sum, project) => sum + project.entries, 0),
@@ -20074,7 +20447,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
20074
20447
  }
20075
20448
 
20076
20449
  // src/gallery/page.ts
20077
- var import_node_fs34 = require("fs");
20450
+ var import_node_fs36 = require("fs");
20078
20451
 
20079
20452
  // src/gallery/client-bundle.ts
20080
20453
  var import_node_module = require("module");
@@ -20114,8 +20487,8 @@ var client;
20114
20487
  function clientAssets() {
20115
20488
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
20116
20489
  client ??= {
20117
- css: (0, import_node_fs34.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
20118
- js: (0, import_node_fs34.existsSync)(prebuilt) ? (0, import_node_fs34.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
20490
+ css: (0, import_node_fs36.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
20491
+ js: (0, import_node_fs36.existsSync)(prebuilt) ? (0, import_node_fs36.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
20119
20492
  };
20120
20493
  return client;
20121
20494
  }
@@ -20258,10 +20631,10 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
20258
20631
 
20259
20632
  // src/editor/install.ts
20260
20633
  var import_node_crypto8 = require("crypto");
20261
- var import_node_fs35 = require("fs");
20262
- var import_promises29 = require("fs/promises");
20634
+ var import_node_fs37 = require("fs");
20635
+ var import_promises30 = require("fs/promises");
20263
20636
  var import_node_os4 = __toESM(require("os"), 1);
20264
- var import_node_path37 = __toESM(require("path"), 1);
20637
+ var import_node_path39 = __toESM(require("path"), 1);
20265
20638
  var EditorInstallError = class extends Error {
20266
20639
  constructor(message6, file) {
20267
20640
  super(message6);
@@ -20272,15 +20645,15 @@ var EditorInstallError = class extends Error {
20272
20645
  };
20273
20646
  function editorToolsRoot() {
20274
20647
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
20275
- if (override) return import_node_path37.default.resolve(override);
20276
- if (process.platform === "darwin") return import_node_path37.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
20648
+ if (override) return import_node_path39.default.resolve(override);
20649
+ if (process.platform === "darwin") return import_node_path39.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
20277
20650
  if (process.platform === "win32") {
20278
- return import_node_path37.default.join(process.env.LOCALAPPDATA ?? import_node_path37.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
20651
+ return import_node_path39.default.join(process.env.LOCALAPPDATA ?? import_node_path39.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
20279
20652
  }
20280
- return import_node_path37.default.join(process.env.XDG_CACHE_HOME ?? import_node_path37.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
20653
+ return import_node_path39.default.join(process.env.XDG_CACHE_HOME ?? import_node_path39.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
20281
20654
  }
20282
20655
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
20283
- return import_node_path37.default.join(root, "pixelorama", pin.release ?? "unpublished");
20656
+ return import_node_path39.default.join(root, "pixelorama", pin.release ?? "unpublished");
20284
20657
  }
20285
20658
  function editorBaseUrl(pin = EDITOR_PIN) {
20286
20659
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -20290,7 +20663,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
20290
20663
  }
20291
20664
  async function sha256Of(file) {
20292
20665
  try {
20293
- return (0, import_node_crypto8.createHash)("sha256").update(await (0, import_promises29.readFile)(file)).digest("hex");
20666
+ return (0, import_node_crypto8.createHash)("sha256").update(await (0, import_promises30.readFile)(file)).digest("hex");
20294
20667
  } catch {
20295
20668
  return null;
20296
20669
  }
@@ -20303,8 +20676,8 @@ async function editorStatus(opts = {}) {
20303
20676
  let totalBytes = 0;
20304
20677
  for (const [name, expected] of Object.entries(pin.files)) {
20305
20678
  totalBytes += expected.bytes;
20306
- const file = import_node_path37.default.join(dir, name);
20307
- const info = (0, import_node_fs35.existsSync)(file) ? await (0, import_promises29.stat)(file).catch(() => null) : null;
20679
+ const file = import_node_path39.default.join(dir, name);
20680
+ const info = (0, import_node_fs37.existsSync)(file) ? await (0, import_promises30.stat)(file).catch(() => null) : null;
20308
20681
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
20309
20682
  installedBytes += expected.bytes;
20310
20683
  } else {
@@ -20333,7 +20706,7 @@ async function installEditor(opts = {}) {
20333
20706
  );
20334
20707
  }
20335
20708
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
20336
- await (0, import_promises29.mkdir)(dir, { recursive: true });
20709
+ await (0, import_promises30.mkdir)(dir, { recursive: true });
20337
20710
  const downloaded = [];
20338
20711
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
20339
20712
  let fetchedBytes = before.installedBytes;
@@ -20361,13 +20734,13 @@ async function installEditor(opts = {}) {
20361
20734
  if (digest2 !== expected.sha256) {
20362
20735
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
20363
20736
  }
20364
- const final = import_node_path37.default.join(dir, name);
20737
+ const final = import_node_path39.default.join(dir, name);
20365
20738
  const tmp = `${final}.${process.pid}.part`;
20366
20739
  try {
20367
- await (0, import_promises29.writeFile)(tmp, bytes);
20368
- await (0, import_promises29.rename)(tmp, final);
20740
+ await (0, import_promises30.writeFile)(tmp, bytes);
20741
+ await (0, import_promises30.rename)(tmp, final);
20369
20742
  } finally {
20370
- await (0, import_promises29.rm)(tmp, { force: true });
20743
+ await (0, import_promises30.rm)(tmp, { force: true });
20371
20744
  }
20372
20745
  fetchedBytes += bytes.length;
20373
20746
  downloaded.push(name);
@@ -20407,12 +20780,12 @@ var EDITOR_CONTENT_TYPES = {
20407
20780
  ".json": "application/json; charset=utf-8"
20408
20781
  };
20409
20782
  function editorContentType(name) {
20410
- return EDITOR_CONTENT_TYPES[import_node_path37.default.extname(name).toLowerCase()] ?? null;
20783
+ return EDITOR_CONTENT_TYPES[import_node_path39.default.extname(name).toLowerCase()] ?? null;
20411
20784
  }
20412
20785
 
20413
20786
  // src/gallery/editor.ts
20414
- var import_promises30 = require("fs/promises");
20415
- var import_node_path38 = __toESM(require("path"), 1);
20787
+ var import_promises31 = require("fs/promises");
20788
+ var import_node_path40 = __toESM(require("path"), 1);
20416
20789
  function editorRoute(release, name = "index.html") {
20417
20790
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
20418
20791
  }
@@ -20485,7 +20858,7 @@ function createGalleryEditorHandlers(opts = {}) {
20485
20858
  if (!status.installed) return null;
20486
20859
  let bytes;
20487
20860
  try {
20488
- bytes = await (0, import_promises30.readFile)(import_node_path38.default.join(dir, name));
20861
+ bytes = await (0, import_promises31.readFile)(import_node_path40.default.join(dir, name));
20489
20862
  } catch {
20490
20863
  verified = null;
20491
20864
  return null;
@@ -20502,7 +20875,7 @@ function createGalleryEditorHandlers(opts = {}) {
20502
20875
  // src/gallery/server.ts
20503
20876
  var import_node_crypto9 = require("crypto");
20504
20877
  var import_node_http2 = require("http");
20505
- var import_promises31 = require("fs/promises");
20878
+ var import_promises32 = require("fs/promises");
20506
20879
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
20507
20880
  var EDITOR_CSP = [
20508
20881
  "default-src 'self'",
@@ -20683,7 +21056,7 @@ async function serveGallery(opts) {
20683
21056
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
20684
21057
  if (!asset) return fail(404, "no such review asset");
20685
21058
  try {
20686
- const bytes = await (0, import_promises31.readFile)(asset.path);
21059
+ const bytes = await (0, import_promises32.readFile)(asset.path);
20687
21060
  res.writeHead(200, {
20688
21061
  "Content-Type": asset.contentType,
20689
21062
  "Cache-Control": "no-store",
@@ -20766,7 +21139,7 @@ async function serveGallery(opts) {
20766
21139
  if (!asset) return fail(404, "no such gallery media");
20767
21140
  let bytes;
20768
21141
  try {
20769
- bytes = await (0, import_promises31.readFile)(asset.path);
21142
+ bytes = await (0, import_promises32.readFile)(asset.path);
20770
21143
  } catch {
20771
21144
  return fail(404, "gallery media is no longer on disk; refresh the page");
20772
21145
  }
@@ -20873,7 +21246,7 @@ function createGenerateHandlers(opts) {
20873
21246
  const busy = /* @__PURE__ */ new Map();
20874
21247
  for (const job of jobs.values()) {
20875
21248
  if (job.phase === "done" || job.phase === "failed") continue;
20876
- for (const key of job.keys) busy.set(`${job.project ?? ""}:${key}`, job.id);
21249
+ for (const key2 of job.keys) busy.set(`${job.project ?? ""}:${key2}`, job.id);
20877
21250
  }
20878
21251
  return busy;
20879
21252
  };
@@ -20916,7 +21289,7 @@ function createGenerateHandlers(opts) {
20916
21289
  });
20917
21290
  say(job, `${providerId}: ${res.completed} completed, ${res.review} awaiting review, ${res.failed} failed, ${res.stillRunning} still running`);
20918
21291
  }
20919
- job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key) => ctx.lock.entries[key]?.status === "review");
21292
+ job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key2) => ctx.lock.entries[key2]?.status === "review");
20920
21293
  job.phase = "fetching";
20921
21294
  for (const [providerId, providerSpecs] of groupByRecordedProvider(specs, ctx.lock)) {
20922
21295
  const provider = opts.providerFor(job.project ?? void 0, providerId);
@@ -21001,7 +21374,7 @@ function createGenerateHandlers(opts) {
21001
21374
  job.finishedAt = null;
21002
21375
  const next = await opts.loadProject(job.project ?? void 0);
21003
21376
  const byKey = new Map(next.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
21004
- const nextSpecs = job.keys.map((key) => byKey.get(key)).filter((spec) => Boolean(spec));
21377
+ const nextSpecs = job.keys.map((key2) => byKey.get(key2)).filter((spec) => Boolean(spec));
21005
21378
  const plan = await buildPlan(nextSpecs, next.lock);
21006
21379
  if (!plan.actionable.length) return finish();
21007
21380
  for (const group of plan.groups) {
@@ -21068,21 +21441,21 @@ function createGenerateHandlers(opts) {
21068
21441
  const ctx = await opts.loadProject(request.project);
21069
21442
  const byKey = new Map(ctx.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
21070
21443
  const specs = [];
21071
- for (const key of request.keys) {
21072
- const spec = byKey.get(key);
21073
- if (!spec) throw new GenerateRequestError(`"${key}" is not declared by the manifest`);
21444
+ for (const key2 of request.keys) {
21445
+ const spec = byKey.get(key2);
21446
+ if (!spec) throw new GenerateRequestError(`"${key2}" is not declared by the manifest`);
21074
21447
  specs.push(spec);
21075
21448
  }
21076
21449
  const busy = busyKeys();
21077
- for (const key of request.keys) {
21078
- const holder = busy.get(`${request.project ?? ""}:${key}`);
21079
- if (holder) throw new GenerateRequestError(`"${key}" is already being worked on by job ${holder}`, 409);
21450
+ for (const key2 of request.keys) {
21451
+ const holder = busy.get(`${request.project ?? ""}:${key2}`);
21452
+ if (holder) throw new GenerateRequestError(`"${key2}" is already being worked on by job ${holder}`, 409);
21080
21453
  }
21081
21454
  if (request.restore) {
21082
- for (const key of request.keys) {
21083
- const entry = ctx.lock.entries[key];
21455
+ for (const key2 of request.keys) {
21456
+ const entry = ctx.lock.entries[key2];
21084
21457
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
21085
- throw new GenerateRequestError(`"${key}" has no downloaded output recorded to restore`);
21458
+ throw new GenerateRequestError(`"${key2}" has no downloaded output recorded to restore`);
21086
21459
  }
21087
21460
  }
21088
21461
  }
@@ -21176,19 +21549,19 @@ function createGenerateHandlers(opts) {
21176
21549
  }
21177
21550
 
21178
21551
  // src/pipeline/salvage.ts
21179
- var import_promises32 = require("fs/promises");
21180
- var import_node_fs36 = require("fs");
21181
- var import_node_path39 = __toESM(require("path"), 1);
21552
+ var import_promises33 = require("fs/promises");
21553
+ var import_node_fs38 = require("fs");
21554
+ var import_node_path41 = __toESM(require("path"), 1);
21182
21555
  function providerClaimId(provider, objectId) {
21183
21556
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
21184
21557
  }
21185
21558
  async function loadClaims(lockPaths, opts = {}) {
21186
21559
  const claimed = /* @__PURE__ */ new Set();
21187
21560
  for (const p of lockPaths) {
21188
- if (!(0, import_node_fs36.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
21561
+ if (!(0, import_node_fs38.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
21189
21562
  let parsed;
21190
21563
  try {
21191
- parsed = parseLock(JSON.parse(await (0, import_promises32.readFile)(p, "utf8")));
21564
+ parsed = parseLock(JSON.parse(await (0, import_promises33.readFile)(p, "utf8")));
21192
21565
  } catch {
21193
21566
  throw new Error(`Claim lockfile is malformed: ${p}`);
21194
21567
  }
@@ -21292,20 +21665,20 @@ function matchOrphanStyle(prompt, manifest) {
21292
21665
  return matchStyleByPattern(prompt, manifest);
21293
21666
  }
21294
21667
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
21295
- const own = import_node_path39.default.resolve(ownManifestPath);
21668
+ const own = import_node_path41.default.resolve(ownManifestPath);
21296
21669
  const siblingManifestPaths = [
21297
21670
  .../* @__PURE__ */ new Set([
21298
21671
  ...workspaceManifestPaths,
21299
- ...claimPaths.map((c) => import_node_path39.default.join(import_node_path39.default.dirname(import_node_path39.default.resolve(c)), "pixelkiln.manifest.json"))
21672
+ ...claimPaths.map((c) => import_node_path41.default.join(import_node_path41.default.dirname(import_node_path41.default.resolve(c)), "pixelkiln.manifest.json"))
21300
21673
  ])
21301
21674
  ];
21302
21675
  const siblings = [];
21303
21676
  for (const siblingManifestPath of siblingManifestPaths) {
21304
- if (import_node_path39.default.resolve(siblingManifestPath) === own) continue;
21305
- if (!(0, import_node_fs36.existsSync)(siblingManifestPath)) continue;
21677
+ if (import_node_path41.default.resolve(siblingManifestPath) === own) continue;
21678
+ if (!(0, import_node_fs38.existsSync)(siblingManifestPath)) continue;
21306
21679
  try {
21307
21680
  const { manifest } = await loadManifest(siblingManifestPath);
21308
- siblings.push({ label: import_node_path39.default.basename(import_node_path39.default.dirname(siblingManifestPath)), manifest });
21681
+ siblings.push({ label: import_node_path41.default.basename(import_node_path41.default.dirname(siblingManifestPath)), manifest });
21309
21682
  } catch {
21310
21683
  }
21311
21684
  }
@@ -21325,10 +21698,10 @@ function groupOrphansByStyle(orphans, manifest, siblings = []) {
21325
21698
  }
21326
21699
  const sibling = siblings.find((s) => matchStyleByPattern(o.prompt, s.manifest));
21327
21700
  if (sibling) {
21328
- const key = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
21329
- const list = elsewhere.get(key) ?? [];
21701
+ const key2 = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
21702
+ const list = elsewhere.get(key2) ?? [];
21330
21703
  list.push(o);
21331
- elsewhere.set(key, list);
21704
+ elsewhere.set(key2, list);
21332
21705
  continue;
21333
21706
  }
21334
21707
  if (ownStyleIds.length <= 1 && ownStyleIds[0]) matched.get(ownStyleIds[0]).push(o);
@@ -21425,8 +21798,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
21425
21798
  }
21426
21799
 
21427
21800
  // src/pick/salvage-server.ts
21428
- var import_promises33 = require("fs/promises");
21429
- var import_node_path40 = __toESM(require("path"), 1);
21801
+ var import_promises34 = require("fs/promises");
21802
+ var import_node_path42 = __toESM(require("path"), 1);
21430
21803
 
21431
21804
  // src/pick/salvage-sheet.ts
21432
21805
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -21592,7 +21965,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21592
21965
  });
21593
21966
  const html = renderSalvageSheet(orphans, {
21594
21967
  styleId: ctx.styleId,
21595
- importDir: import_node_path40.default.relative(process.cwd(), ctx.importDir) || "."
21968
+ importDir: import_node_path42.default.relative(process.cwd(), ctx.importDir) || "."
21596
21969
  });
21597
21970
  const byId = new Map(orphans.map((o) => [o.id, o]));
21598
21971
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -21648,10 +22021,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21648
22021
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
21649
22022
  decodePng(buf);
21650
22023
  const assetId = idFromPrompt(orphan.prompt, taken);
21651
- const rel = import_node_path40.default.join("_salvaged", `${assetId}.png`);
21652
- const outFile = import_node_path40.default.resolve(ctx.importDir, rel);
21653
- await (0, import_promises33.mkdir)(import_node_path40.default.dirname(outFile), { recursive: true });
21654
- await (0, import_promises33.writeFile)(outFile, buf);
22024
+ const rel = import_node_path42.default.join("_salvaged", `${assetId}.png`);
22025
+ const outFile = import_node_path42.default.resolve(ctx.importDir, rel);
22026
+ await (0, import_promises34.mkdir)(import_node_path42.default.dirname(outFile), { recursive: true });
22027
+ await (0, import_promises34.writeFile)(outFile, buf);
21655
22028
  ctx.manifest.assets[assetId] = {
21656
22029
  prompt: orphan.prompt,
21657
22030
  promptByStyle: {},
@@ -21683,7 +22056,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21683
22056
  sourceUrl: durableSource,
21684
22057
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
21685
22058
  outputs: [{
21686
- path: portableOutputPath(outFile, import_node_path40.default.dirname(ctx.manifestPath)),
22059
+ path: portableOutputPath(outFile, import_node_path42.default.dirname(ctx.manifestPath)),
21687
22060
  sha256: sha256(buf)
21688
22061
  }],
21689
22062
  submittedAt: orphan.createdAt,
@@ -21707,9 +22080,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21707
22080
  }
21708
22081
  }
21709
22082
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
21710
- const raw = JSON.parse(await (0, import_promises33.readFile)(ctx.manifestPath, "utf8"));
22083
+ const raw = JSON.parse(await (0, import_promises34.readFile)(ctx.manifestPath, "utf8"));
21711
22084
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
21712
- await (0, import_promises33.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
22085
+ await (0, import_promises34.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
21713
22086
  await saveLock(ctx.lockPath, ctx.lock);
21714
22087
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
21715
22088
  return result;
@@ -21819,6 +22192,8 @@ async function workspaceStatus(ws, dir) {
21819
22192
  // Annotate the CommonJS export names for ESM import in node:
21820
22193
  0 && (module.exports = {
21821
22194
  AssetBatchSchema,
22195
+ AssetDeriveSchema,
22196
+ AssetExternalSchema,
21822
22197
  AssetSchema,
21823
22198
  AssetVfxSchema,
21824
22199
  BudgetError,