pixelkiln 0.94.0 → 0.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -283,12 +283,12 @@ var AssetVfxSchema = z.object({
283
283
  artist: z.enum(["lite", "pro"]).optional()
284
284
  }).strict().superRefine((vfx, context) => {
285
285
  if (vfx.description !== void 0) {
286
- for (const key of ["preset", "recipe", "parts", "fps"]) {
287
- if (vfx[key] !== void 0) {
286
+ for (const key2 of ["preset", "recipe", "parts", "fps"]) {
287
+ if (vfx[key2] !== void 0) {
288
288
  context.addIssue({
289
289
  code: z.ZodIssueCode.custom,
290
- message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key}; use a description or the workbench's preset/recipe/parts/fps, not both`,
291
- path: [key]
290
+ message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key2}; use a description or the workbench's preset/recipe/parts/fps, not both`,
291
+ path: [key2]
292
292
  });
293
293
  }
294
294
  }
@@ -407,18 +407,18 @@ var CharacterAnimationSchema = z.object({
407
407
  context.addIssue({ code: z.ZodIssueCode.custom, message: "a skeleton-v3 loop from a sentence takes 3 to 15 frames", path: ["frames"] });
408
408
  }
409
409
  const mode2 = animation.mode ?? (animation.template ? "template" : "v3");
410
- for (const key of ["startFrame", "endFrame", "enhancePrompt"]) {
411
- if (animation[key] !== void 0 && mode2 !== "v3") {
410
+ for (const key2 of ["startFrame", "endFrame", "enhancePrompt"]) {
411
+ if (animation[key2] !== void 0 && mode2 !== "v3") {
412
412
  context.addIssue({
413
413
  code: z.ZodIssueCode.custom,
414
- message: `${key} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
415
- path: [key]
414
+ message: `${key2} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
415
+ path: [key2]
416
416
  });
417
417
  }
418
418
  }
419
- for (const key of ["outline", "shading", "detail"]) {
420
- if (animation[key] !== void 0 && mode2 !== "template") {
421
- context.addIssue({ code: z.ZodIssueCode.custom, message: `${key} overrides apply to template loops only`, path: [key] });
419
+ for (const key2 of ["outline", "shading", "detail"]) {
420
+ if (animation[key2] !== void 0 && mode2 !== "template") {
421
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `${key2} overrides apply to template loops only`, path: [key2] });
422
422
  }
423
423
  }
424
424
  if (animation.template && animation.mode && animation.mode !== "template" && animation.mode !== "skeleton-v3") {
@@ -1107,6 +1107,46 @@ var InheritedStyleSchema = StyleObjectSchema.partial().extend({
1107
1107
  quality: QualityProfileObjectSchema.partial().optional()
1108
1108
  }).strict();
1109
1109
  var StyleInputSchema = z.union([StyleSchema, InheritedStyleSchema]);
1110
+ var AssetDeriveSchema = z.object({
1111
+ /** Another asset in the same style whose output is the input. */
1112
+ from: z.string().min(1).optional(),
1113
+ /** A committed PNG, relative to the manifest, as the input. */
1114
+ file: z.string().min(1).optional(),
1115
+ transform: z.enum(["recolor", "palette-snap", "scale"]),
1116
+ /** recolor: exact replacements, `#rrggbb` to `#rrggbb`. Unmapped colors and every alpha value stay. */
1117
+ map: z.record(HexColorSchema, HexColorSchema).optional(),
1118
+ /** palette-snap: the closed palette every visible pixel moves to. */
1119
+ palette: z.array(HexColorSchema).min(2).max(256).optional(),
1120
+ /** scale: the output size. */
1121
+ width: z.number().int().min(1).max(4096).optional(),
1122
+ height: z.number().int().min(1).max(4096).optional(),
1123
+ /** scale: `nearest` (default) keeps hard edges; `box` averages the covered pixels. */
1124
+ mode: z.enum(["nearest", "box"]).optional()
1125
+ }).strict().superRefine((derive, context) => {
1126
+ const issue = (message6, path43) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path43] });
1127
+ if (Boolean(derive.from) === Boolean(derive.file)) {
1128
+ issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1129
+ }
1130
+ const own = {
1131
+ recolor: ["map"],
1132
+ "palette-snap": ["palette"],
1133
+ scale: ["width", "height", "mode"]
1134
+ }[derive.transform];
1135
+ for (const field of ["map", "palette", "width", "height", "mode"]) {
1136
+ if (derive[field] !== void 0 && !own.includes(field)) {
1137
+ issue(`${field} does not apply to ${derive.transform}`, field);
1138
+ }
1139
+ }
1140
+ if (derive.transform === "recolor" && !Object.keys(derive.map ?? {}).length) issue("recolor needs a non-empty map", "map");
1141
+ if (derive.transform === "palette-snap" && !derive.palette) issue("palette-snap needs a palette", "palette");
1142
+ if (derive.transform === "scale" && (!derive.width || !derive.height)) issue("scale needs width and height", "width");
1143
+ });
1144
+ var AssetExternalSchema = z.object({
1145
+ /** The command that rebuilds the file. Documentation and identity; never executed. */
1146
+ builder: z.string().min(1),
1147
+ /** Files the builder reads, relative to the manifest. Their hashes are part of the asset's identity. */
1148
+ inputs: z.array(z.string().min(1)).optional()
1149
+ }).strict();
1110
1150
  var AssetSchema = z.object({
1111
1151
  /** The subject. Style wrapping comes from the style's prefix/suffix. Only a `mirror` may leave it out. */
1112
1152
  prompt: z.string().optional(),
@@ -1238,6 +1278,10 @@ var AssetSchema = z.object({
1238
1278
  * (a sword hand, a parted fringe) comes out the other way round.
1239
1279
  */
1240
1280
  mirror: z.string().min(1).optional(),
1281
+ /** Made from existing pixels by a local transform; see AssetDeriveSchema. Free; the provider is never called. */
1282
+ derive: AssetDeriveSchema.optional(),
1283
+ /** Built by a tool outside pixelkiln; see AssetExternalSchema. Never generated. */
1284
+ external: AssetExternalSchema.optional(),
1241
1285
  /**
1242
1286
  * Generated output role to place in `cell` when this asset expands to
1243
1287
  * several files. Omit for ordinary single-output assets. A structural set
@@ -1277,7 +1321,7 @@ var AssetSchema = z.object({
1277
1321
  path: ["revision"]
1278
1322
  });
1279
1323
  }
1280
- const shapes = [asset.revision && "revision", asset.state && "state", asset.animation && "animation", asset.mirror && "mirror", asset.batch && "batch", asset.portrait && "portrait", asset.outfit && "outfit", asset.scene && "scene", asset.vfx && "vfx", asset.connect && "connect"].filter(Boolean);
1324
+ const shapes = [asset.revision && "revision", asset.state && "state", asset.animation && "animation", asset.mirror && "mirror", asset.derive && "derive", asset.external && "external", asset.batch && "batch", asset.portrait && "portrait", asset.outfit && "outfit", asset.scene && "scene", asset.vfx && "vfx", asset.connect && "connect"].filter(Boolean);
1281
1325
  if (shapes.length > 1) {
1282
1326
  context.addIssue({
1283
1327
  code: z.ZodIssueCode.custom,
@@ -1285,6 +1329,15 @@ var AssetSchema = z.object({
1285
1329
  path: [shapes[1]]
1286
1330
  });
1287
1331
  }
1332
+ for (const shape of ["derive", "external"]) {
1333
+ if (asset[shape] && (asset.source || Object.keys(asset.sourceByStyle).length)) {
1334
+ context.addIssue({
1335
+ code: z.ZodIssueCode.custom,
1336
+ message: shape === "derive" ? "a derived asset is made from its derive source; it cannot also declare a source" : "an external asset is built outside pixelkiln; it cannot also declare a source",
1337
+ path: [shape]
1338
+ });
1339
+ }
1340
+ }
1288
1341
  if (asset.mirror && (asset.source || Object.keys(asset.sourceByStyle).length)) {
1289
1342
  context.addIssue({
1290
1343
  code: z.ZodIssueCode.custom,
@@ -1292,13 +1345,20 @@ var AssetSchema = z.object({
1292
1345
  path: ["mirror"]
1293
1346
  });
1294
1347
  }
1295
- if (asset.prompt === void 0 && !asset.mirror && !asset.portrait && !asset.outfit && !asset.animation?.template && !asset.vfx) {
1348
+ if (asset.prompt === void 0 && !asset.mirror && !asset.derive && !asset.external && !asset.portrait && !asset.outfit && !asset.animation?.template && !asset.vfx) {
1296
1349
  context.addIssue({
1297
1350
  code: z.ZodIssueCode.custom,
1298
1351
  message: "Required",
1299
1352
  path: ["prompt"]
1300
1353
  });
1301
1354
  }
1355
+ if ((asset.derive || asset.external) && (asset.reference || asset.concept)) {
1356
+ context.addIssue({
1357
+ code: z.ZodIssueCode.custom,
1358
+ message: "a derived or external asset is not drawn by a provider, so it takes no reference or concept image",
1359
+ path: [asset.reference ? "reference" : "concept"]
1360
+ });
1361
+ }
1302
1362
  if (asset.reference && (asset.state || asset.animation || asset.mirror || asset.portrait || asset.outfit)) {
1303
1363
  context.addIssue({
1304
1364
  code: z.ZodIssueCode.custom,
@@ -1364,6 +1424,18 @@ var PostprocessSchema = z.object({
1364
1424
  distance: z.literal("redmean")
1365
1425
  }).optional()
1366
1426
  });
1427
+ var LockOriginSchema = z.object({
1428
+ tool: z.string().min(1).optional(),
1429
+ prompt: z.string().optional(),
1430
+ seed: z.number().int().optional(),
1431
+ steps: z.array(z.string().min(1)).optional(),
1432
+ raw: z.object({ sha256: z.string().regex(/^[0-9a-f]{64}$/) }).optional()
1433
+ });
1434
+ var LockImportedSchema = z.object({
1435
+ source: z.string().min(1),
1436
+ note: z.string().optional(),
1437
+ importedAt: z.string()
1438
+ }).strict();
1367
1439
  var LockSourceSchema = z.object({
1368
1440
  url: z.string(),
1369
1441
  role: z.string().optional(),
@@ -1414,6 +1486,9 @@ var LockHistoryEntrySchema = z.object({
1414
1486
  motionShare: LockMotionShareSchema.optional(),
1415
1487
  /** A terrain set's settings outside specHash; see LockEntrySchema.terrainSettings. */
1416
1488
  terrainSettings: LockTerrainSettingsSchema.optional(),
1489
+ /** Imported art keeps its provenance when it is replaced and when it comes back. */
1490
+ imported: LockImportedSchema.optional(),
1491
+ origin: LockOriginSchema.optional(),
1417
1492
  /** When the replacement was submitted. */
1418
1493
  retiredAt: z.string()
1419
1494
  });
@@ -1586,10 +1661,26 @@ var LockEntrySchema = z.object({
1586
1661
  * hand edit, another tool) and brought in with `adopt --local`: nothing was
1587
1662
  * submitted, so jobId and cost are empty. Absent on generated entries.
1588
1663
  */
1589
- imported: z.object({
1590
- source: z.string().min(1),
1591
- note: z.string().optional(),
1592
- importedAt: z.string()
1664
+ imported: LockImportedSchema.optional(),
1665
+ /** More on imported art: tool, prompt, seed, post-process steps, raw original. See LockOriginSchema. */
1666
+ origin: LockOriginSchema.optional(),
1667
+ /**
1668
+ * For a derived asset: what it was made from, and a hash of that input when
1669
+ * this was made. Compared with the input's current bytes by the plan, so a
1670
+ * changed source re-derives it for free. Absent on every other entry.
1671
+ */
1672
+ derive: z.object({
1673
+ sourceAssetId: z.string().min(1).optional(),
1674
+ sourceFile: z.string().min(1).optional(),
1675
+ sourceSha256: z.string().regex(/^[0-9a-f]{64}$/)
1676
+ }).strict().optional(),
1677
+ /**
1678
+ * For an external asset: the builder command and the hashes of the declared
1679
+ * inputs when the file was recorded. Absent on every other entry.
1680
+ */
1681
+ external: z.object({
1682
+ builder: z.string().min(1),
1683
+ inputs: z.array(z.object({ path: z.string(), sha256: z.string().nullable() }).strict()).default([])
1593
1684
  }).strict().optional()
1594
1685
  });
1595
1686
  var LockSchema = z.object({
@@ -2139,9 +2230,9 @@ var PixelLabClient = class {
2139
2230
  apiKey;
2140
2231
  http;
2141
2232
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
2142
- async request(path40, init) {
2233
+ async request(path43, init) {
2143
2234
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
2144
- const res = await this.http(`${BASE}${path40}`, {
2235
+ const res = await this.http(`${BASE}${path43}`, {
2145
2236
  ...init,
2146
2237
  headers: {
2147
2238
  Authorization: auth,
@@ -2152,13 +2243,13 @@ var PixelLabClient = class {
2152
2243
  const text = await res.text();
2153
2244
  if (!res.ok) {
2154
2245
  const hint = res.status === 500 && text.includes("Failed to start any animation jobs") ? '; a skeleton-v3 loop needs a character with a stored 3D skeleton (a v3 base), use mode: "template" on a standard one' : "";
2155
- throw new PixelLabError(`${init?.method ?? "GET"} ${path40} \u2192 ${res.status}${hint}`, res.status, text);
2246
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path43} \u2192 ${res.status}${hint}`, res.status, text);
2156
2247
  }
2157
2248
  if (!text) return {};
2158
2249
  try {
2159
2250
  return JSON.parse(text);
2160
2251
  } catch {
2161
- throw new Error(`${init?.method ?? "GET"} ${path40} returned invalid JSON`);
2252
+ throw new Error(`${init?.method ?? "GET"} ${path43} returned invalid JSON`);
2162
2253
  }
2163
2254
  }
2164
2255
  async balance() {
@@ -2611,10 +2702,10 @@ var PixelLabClient = class {
2611
2702
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
2612
2703
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
2613
2704
  const south = args.reference?.south;
2614
- let path40;
2705
+ let path43;
2615
2706
  let body;
2616
2707
  if (args.mode === "v3") {
2617
- path40 = "/create-character-v3";
2708
+ path43 = "/create-character-v3";
2618
2709
  body = {
2619
2710
  description: args.description,
2620
2711
  image_size: imageSize,
@@ -2628,7 +2719,7 @@ var PixelLabClient = class {
2628
2719
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
2629
2720
  };
2630
2721
  } else if (args.mode === "pro-flash") {
2631
- path40 = "/create-character-pro-flash";
2722
+ path43 = "/create-character-pro-flash";
2632
2723
  const traits = args.styleTraits;
2633
2724
  body = {
2634
2725
  description: args.description,
@@ -2652,7 +2743,7 @@ var PixelLabClient = class {
2652
2743
  } : {}
2653
2744
  };
2654
2745
  } else if (args.mode === "pro") {
2655
- path40 = "/create-character-pro";
2746
+ path43 = "/create-character-pro";
2656
2747
  body = {
2657
2748
  description: args.description,
2658
2749
  image_size: imageSize,
@@ -2666,7 +2757,7 @@ var PixelLabClient = class {
2666
2757
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
2667
2758
  };
2668
2759
  } else {
2669
- path40 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
2760
+ path43 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
2670
2761
  body = {
2671
2762
  description: args.description,
2672
2763
  image_size: imageSize,
@@ -2684,8 +2775,8 @@ var PixelLabClient = class {
2684
2775
  };
2685
2776
  }
2686
2777
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
2687
- const raw = await this.request(path40, { method: "POST", body: JSON.stringify(body) });
2688
- return validateResponse(CharacterSubmitSchema, raw, path40.slice(1));
2778
+ const raw = await this.request(path43, { method: "POST", body: JSON.stringify(body) });
2779
+ return validateResponse(CharacterSubmitSchema, raw, path43.slice(1));
2689
2780
  }
2690
2781
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
2691
2782
  async createCharacterState(args) {
@@ -3414,13 +3505,13 @@ var PixelLabClient = class {
3414
3505
  }
3415
3506
  };
3416
3507
  function clientFromEnv() {
3417
- const key = process.env.PIXELLAB_API_KEY;
3418
- if (!key) {
3508
+ const key2 = process.env.PIXELLAB_API_KEY;
3509
+ if (!key2) {
3419
3510
  throw new Error(
3420
3511
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
3421
3512
  );
3422
3513
  }
3423
- return new PixelLabClient(key);
3514
+ return new PixelLabClient(key2);
3424
3515
  }
3425
3516
 
3426
3517
  // src/open.ts
@@ -3760,14 +3851,14 @@ function extractPalette(png, topN = 8, alphaThreshold = 128) {
3760
3851
  const alpha = png.pixels[i + 3];
3761
3852
  if (alpha < alphaThreshold) continue;
3762
3853
  opaque++;
3763
- const key = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
3764
- counts.set(key, (counts.get(key) ?? 0) + 1);
3854
+ const key2 = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
3855
+ counts.set(key2, (counts.get(key2) ?? 0) + 1);
3765
3856
  }
3766
3857
  if (opaque === 0) return [];
3767
- return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key, n]) => ({
3768
- r: key >> 16 & 255,
3769
- g: key >> 8 & 255,
3770
- b: key & 255,
3858
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key2, n]) => ({
3859
+ r: key2 >> 16 & 255,
3860
+ g: key2 >> 8 & 255,
3861
+ b: key2 & 255,
3771
3862
  weight: n / opaque
3772
3863
  }));
3773
3864
  }
@@ -4019,13 +4110,17 @@ import path3 from "path";
4019
4110
  // src/hash.ts
4020
4111
  import { createHash } from "crypto";
4021
4112
  import { createReadStream } from "fs";
4113
+ function normalizeHex(value) {
4114
+ const { r, g, b } = parseHex(value);
4115
+ return `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
4116
+ }
4022
4117
  function sha256(data) {
4023
4118
  return createHash("sha256").update(data).digest("hex");
4024
4119
  }
4025
- async function sha256File(path40) {
4120
+ async function sha256File(path43) {
4026
4121
  return new Promise((resolve, reject) => {
4027
4122
  const hash = createHash("sha256");
4028
- const stream = createReadStream(path40);
4123
+ const stream = createReadStream(path43);
4029
4124
  stream.on("data", (chunk2) => hash.update(chunk2));
4030
4125
  stream.on("error", reject);
4031
4126
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -4167,6 +4262,22 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
4167
4262
  // A mirror's bytes come from its source's recorded outputs; the plan
4168
4263
  // compares those directly, so only the choice of source is identity.
4169
4264
  mirror: spec.mirror ? { of: spec.mirror.sourceAssetId } : void 0,
4265
+ // A derived asset's identity is its transform and what it reads: the
4266
+ // file source by its bytes' hash, an asset source by id (the plan
4267
+ // compares that asset's current output with the one recorded).
4268
+ derive: spec.derive ? {
4269
+ transform: spec.derive.transform,
4270
+ map: spec.derive.map ? Object.entries(spec.derive.map).map(([from, to]) => [normalizeHex(from), normalizeHex(to)]).sort(([a], [b]) => a.localeCompare(b)) : void 0,
4271
+ palette: spec.derive.palette?.map(normalizeHex),
4272
+ width: spec.derive.width,
4273
+ height: spec.derive.height,
4274
+ mode: spec.derive.transform === "scale" ? spec.derive.mode ?? "nearest" : void 0,
4275
+ from: spec.derive.source.kind === "asset" ? spec.derive.source.assetId : void 0,
4276
+ fileSha256: spec.derive.source.kind === "file" ? spec.derive.source.sha256 : void 0
4277
+ } : void 0,
4278
+ // An external asset: the builder text and each declared input's path
4279
+ // and bytes. The built file itself is checked by the plan.
4280
+ external: spec.external ? { builder: spec.external.builder, inputs: spec.external.inputs.length ? spec.external.inputs : void 0 } : void 0,
4170
4281
  // The whole group's ordered descriptions, not just this asset's own —
4171
4282
  // any sibling's prompt changing, or a member being added or removed,
4172
4283
  // must mark every member stale together, since they all ride on one
@@ -4294,13 +4405,13 @@ var PixelLabMcpClient = class {
4294
4405
  }
4295
4406
  };
4296
4407
  function mcpClientFromEnv() {
4297
- const key = process.env.PIXELLAB_API_KEY;
4298
- if (!key) {
4408
+ const key2 = process.env.PIXELLAB_API_KEY;
4409
+ if (!key2) {
4299
4410
  throw new Error(
4300
4411
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
4301
4412
  );
4302
4413
  }
4303
- return new PixelLabMcpClient(key);
4414
+ return new PixelLabMcpClient(key2);
4304
4415
  }
4305
4416
 
4306
4417
  // src/pixellab-vfx.ts
@@ -4584,27 +4695,27 @@ function vfxArtistFiles(raw) {
4584
4695
  const urlOf = (value) => {
4585
4696
  if (typeof value === "string") return /^https?:\/\//i.test(value) ? value : null;
4586
4697
  if (!value || typeof value !== "object") return null;
4587
- for (const key of ["url", "download_url", "href"]) {
4588
- const url = value[key];
4698
+ for (const key2 of ["url", "download_url", "href"]) {
4699
+ const url = value[key2];
4589
4700
  if (typeof url === "string" && /^https?:\/\//i.test(url)) return url;
4590
4701
  }
4591
4702
  return null;
4592
4703
  };
4593
- const nameOf = (value, url, key) => {
4704
+ const nameOf = (value, url, key2) => {
4594
4705
  if (value && typeof value === "object") {
4595
4706
  for (const field of ["name", "filename", "file"]) {
4596
4707
  const name = value[field];
4597
4708
  if (typeof name === "string" && name) return name;
4598
4709
  }
4599
4710
  }
4600
- if (key && /\.[a-z0-9]+$/i.test(key)) return key;
4711
+ if (key2 && /\.[a-z0-9]+$/i.test(key2)) return key2;
4601
4712
  return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
4602
4713
  };
4603
4714
  const entries = Array.isArray(raw) ? raw.map((value) => [void 0, value]) : raw && typeof raw === "object" ? Object.entries(raw) : [];
4604
4715
  const files = [];
4605
- for (const [key, value] of entries) {
4716
+ for (const [key2, value] of entries) {
4606
4717
  const url = urlOf(value);
4607
- if (url) files.push({ name: nameOf(value, url, key), url });
4718
+ if (url) files.push({ name: nameOf(value, url, key2), url });
4608
4719
  }
4609
4720
  return files;
4610
4721
  }
@@ -4705,14 +4816,14 @@ async function makeVfxWithArtist(client2, opts) {
4705
4816
  `);
4706
4817
  written.atlas = paths.atlas;
4707
4818
  }
4708
- for (const [file, target, key] of [
4819
+ for (const [file, target, key2] of [
4709
4820
  [result.gif, paths.gif, "gif"],
4710
4821
  [result.gamePack, paths.gamePack, "gamePack"],
4711
4822
  [result.normals, paths.normals, "normals"]
4712
4823
  ]) {
4713
4824
  if (!file) continue;
4714
4825
  await writeFile(target, await client2.download(file.url));
4715
- written[key] = target;
4826
+ written[key2] = target;
4716
4827
  }
4717
4828
  const facts = vfxArtistFrameFacts(result, atlas);
4718
4829
  const usage = job.usage ?? null;
@@ -4736,7 +4847,7 @@ async function makeVfxWithArtist(client2, opts) {
4736
4847
  anchor: result.anchor,
4737
4848
  parts: result.parts,
4738
4849
  files: Object.fromEntries(
4739
- ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key) => written[key]).map((key) => [key, path.basename(written[key])])
4850
+ ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key2) => written[key2]).map((key2) => [key2, path.basename(written[key2])])
4740
4851
  ),
4741
4852
  quotedGenerations: submitted.quoted_generations ?? null,
4742
4853
  usage,
@@ -4761,8 +4872,8 @@ async function makeVfxWithArtist(client2, opts) {
4761
4872
  };
4762
4873
  }
4763
4874
  function vfxJobFailure(done) {
4764
- for (const key of ["error", "detail", "message"]) {
4765
- const value = done?.[key];
4875
+ for (const key2 of ["error", "detail", "message"]) {
4876
+ const value = done?.[key2];
4766
4877
  if (typeof value === "string" && value) return `: ${value}`;
4767
4878
  }
4768
4879
  return "";
@@ -4797,8 +4908,8 @@ function isSensitiveSourceUrl(value) {
4797
4908
  return false;
4798
4909
  }
4799
4910
  if (parsed.username || parsed.password) return true;
4800
- for (const key of parsed.searchParams.keys()) {
4801
- const normalized = key.toLowerCase();
4911
+ for (const key2 of parsed.searchParams.keys()) {
4912
+ const normalized = key2.toLowerCase();
4802
4913
  if (SENSITIVE_QUERY_KEYS.has(normalized) || normalized.includes("credential") || normalized.includes("signature") || normalized.includes("security-token") || normalized.includes("token")) return true;
4803
4914
  }
4804
4915
  return false;
@@ -7193,8 +7304,8 @@ var PixelLabProvider = class _PixelLabProvider {
7193
7304
  billed
7194
7305
  };
7195
7306
  };
7196
- for (const key of ["frame_urls", "frames", "images"]) {
7197
- const list = done[key];
7307
+ for (const key2 of ["frame_urls", "frames", "images"]) {
7308
+ const list = done[key2];
7198
7309
  if (!Array.isArray(list) || !list.length) continue;
7199
7310
  const urls = [];
7200
7311
  for (const [index, item] of list.entries()) {
@@ -7249,15 +7360,15 @@ var PixelLabProvider = class _PixelLabProvider {
7249
7360
  const billed = billedFromUsage(job.usage);
7250
7361
  const done = job.last_response ?? {};
7251
7362
  const urlKeys = ["image_url", "download_url", "url", "output_url"];
7252
- for (const key of urlKeys) {
7253
- const url = done[key];
7363
+ for (const key2 of urlKeys) {
7364
+ const url = done[key2];
7254
7365
  if (typeof url === "string" && url) {
7255
7366
  return { status: "ready", objectId: jobId, sourceUrl: url, sources: [{ url }], billed };
7256
7367
  }
7257
7368
  }
7258
7369
  const imageKeys = ["image", "output_image", "result_image", "edited_image"];
7259
- for (const key of imageKeys) {
7260
- const candidate = done[key];
7370
+ for (const key2 of imageKeys) {
7371
+ const candidate = done[key2];
7261
7372
  const base64 = extractBase64(candidate);
7262
7373
  if (base64) {
7263
7374
  const file = path3.join(_PixelLabProvider.cacheDir(), `${jobId}.png`);
@@ -7682,7 +7793,7 @@ function requirePixelLabOption(generator, name, value, allowed) {
7682
7793
  }
7683
7794
  }
7684
7795
  function tilesInIndexOrder(urls) {
7685
- return Object.entries(urls).map(([key, url]) => ({ index: Number(key.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
7796
+ return Object.entries(urls).map(([key2, url]) => ({ index: Number(key2.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
7686
7797
  }
7687
7798
  function firstUrl(urls) {
7688
7799
  if (!urls) return null;
@@ -7844,9 +7955,9 @@ var RetroDiffusionClient = class {
7844
7955
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
7845
7956
  return Buffer.from(await response.arrayBuffer());
7846
7957
  }
7847
- async call(path40, init = {}) {
7958
+ async call(path43, init = {}) {
7848
7959
  if (!this.token) throw new Error("RD_API_KEY is not set");
7849
- const response = await this.request(`${this.baseUrl}${path40}`, {
7960
+ const response = await this.request(`${this.baseUrl}${path43}`, {
7850
7961
  ...init,
7851
7962
  headers: {
7852
7963
  "Content-Type": "application/json",
@@ -8315,8 +8426,8 @@ var ScenarioClient = class {
8315
8426
  throw new Error(`${missing.join(" and ")} ${missing.length > 1 ? "are" : "is"} not set`);
8316
8427
  }
8317
8428
  const url = new URL(`${this.baseUrl.replace(/\/$/, "")}${pathname}`);
8318
- for (const [key, value2] of Object.entries(query)) {
8319
- if (value2 != null) url.searchParams.set(key, value2);
8429
+ for (const [key2, value2] of Object.entries(query)) {
8430
+ if (value2 != null) url.searchParams.set(key2, value2);
8320
8431
  }
8321
8432
  const auth = Buffer.from(`${this.apiKey}:${this.apiSecret}`).toString("base64");
8322
8433
  const response = await this.request(url, {
@@ -8556,12 +8667,12 @@ function readUploadCache() {
8556
8667
  return {};
8557
8668
  }
8558
8669
  }
8559
- function writeUploadCache(key, assetId) {
8670
+ function writeUploadCache(key2, assetId) {
8560
8671
  try {
8561
8672
  const file = uploadCachePath();
8562
8673
  mkdirSync2(path4.dirname(file), { recursive: true });
8563
8674
  const tmp = `${file}.${process.pid}.tmp`;
8564
- writeFileSync2(tmp, JSON.stringify({ ...readUploadCache(), [key]: assetId }));
8675
+ writeFileSync2(tmp, JSON.stringify({ ...readUploadCache(), [key2]: assetId }));
8565
8676
  renameSync(tmp, file);
8566
8677
  } catch {
8567
8678
  }
@@ -8611,9 +8722,9 @@ function validateParameters(parameters) {
8611
8722
  if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
8612
8723
  throw new Error("Scenario parameters must be a JSON object");
8613
8724
  }
8614
- for (const key of Object.keys(parameters)) {
8615
- if (PROTECTED_PARAMETERS.has(key)) {
8616
- throw new Error(`Scenario parameters.${key} is managed by PixelKiln and cannot be overridden`);
8725
+ for (const key2 of Object.keys(parameters)) {
8726
+ if (PROTECTED_PARAMETERS.has(key2)) {
8727
+ throw new Error(`Scenario parameters.${key2} is managed by PixelKiln and cannot be overridden`);
8617
8728
  }
8618
8729
  }
8619
8730
  assertJsonValue(parameters, "Scenario parameters");
@@ -8636,8 +8747,8 @@ function assertJsonValue(value, label, seen = /* @__PURE__ */ new Set()) {
8636
8747
  if (Array.isArray(value)) {
8637
8748
  value.forEach((item, index) => assertJsonValue(item, `${label}[${index}]`, seen));
8638
8749
  } else {
8639
- for (const [key, item] of Object.entries(value)) {
8640
- assertJsonValue(item, `${label}.${key}`, seen);
8750
+ for (const [key2, item] of Object.entries(value)) {
8751
+ assertJsonValue(item, `${label}.${key2}`, seen);
8641
8752
  }
8642
8753
  }
8643
8754
  seen.delete(value);
@@ -8738,8 +8849,8 @@ function numericRecord(value) {
8738
8849
  throw new Error("Scenario returned invalid cost details");
8739
8850
  }
8740
8851
  const out = {};
8741
- for (const [key, amount] of Object.entries(value)) {
8742
- out[key] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key}"`);
8852
+ for (const [key2, amount] of Object.entries(value)) {
8853
+ out[key2] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key2}"`);
8743
8854
  }
8744
8855
  return out;
8745
8856
  }
@@ -9345,7 +9456,7 @@ function parseOptions(value) {
9345
9456
  "workflow",
9346
9457
  "workflowSha256"
9347
9458
  ]);
9348
- const extra = Object.keys(value).filter((key) => !allowed.has(key));
9459
+ const extra = Object.keys(value).filter((key2) => !allowed.has(key2));
9349
9460
  if (extra.length) throw new Error(`Unknown ComfyUI option(s): ${extra.join(", ")}`);
9350
9461
  const workflowFile = requiredString(value.workflowFile, "workflowFile");
9351
9462
  const outputNodeId = requiredString(value.outputNodeId, "outputNodeId");
@@ -9381,7 +9492,7 @@ function parseOptions(value) {
9381
9492
  }
9382
9493
  function parseFrames(value) {
9383
9494
  if (!isObject(value)) throw new Error("ComfyUI frames must be an object");
9384
- const extra = Object.keys(value).filter((key) => key !== "vary" && key !== "seedStep");
9495
+ const extra = Object.keys(value).filter((key2) => key2 !== "vary" && key2 !== "seedStep");
9385
9496
  if (extra.length) throw new Error(`Unknown ComfyUI frames field(s): ${extra.join(", ")}`);
9386
9497
  const vary = requiredString(value.vary, "frames.vary");
9387
9498
  const seedStep = value.seedStep ?? 0;
@@ -9399,7 +9510,7 @@ function resolvedOptions(spec) {
9399
9510
  }
9400
9511
  function parseBinding(value, name) {
9401
9512
  if (!isObject(value)) throw new Error(`ComfyUI bindings.${name} must be an object`);
9402
- const extra = Object.keys(value).filter((key) => key !== "nodeId" && key !== "input");
9513
+ const extra = Object.keys(value).filter((key2) => key2 !== "nodeId" && key2 !== "input");
9403
9514
  if (extra.length) throw new Error(`Unknown ComfyUI bindings.${name} field(s): ${extra.join(", ")}`);
9404
9515
  return {
9405
9516
  nodeId: requiredString(value.nodeId, `bindings.${name}.nodeId`),
@@ -9664,7 +9775,7 @@ function canonical(value) {
9664
9775
  if (Array.isArray(value)) return value.map(canonical);
9665
9776
  if (!isObject(value)) return value;
9666
9777
  return Object.fromEntries(
9667
- Object.keys(value).sort().map((key) => [key, canonical(value[key])])
9778
+ Object.keys(value).sort().map((key2) => [key2, canonical(value[key2])])
9668
9779
  );
9669
9780
  }
9670
9781
 
@@ -10073,22 +10184,22 @@ async function writeLockWhileHeld(file, lock) {
10073
10184
  }
10074
10185
  const dirty = dirtyPatches.get(lock) ?? /* @__PURE__ */ new Map();
10075
10186
  const snapshot = /* @__PURE__ */ new Map();
10076
- for (const [key, patch] of dirty) snapshot.set(key, { ...patch });
10187
+ for (const [key2, patch] of dirty) snapshot.set(key2, { ...patch });
10077
10188
  const merged = { ...disk.entries };
10078
- for (const [key, patch] of snapshot) {
10079
- const local = lock.entries[key];
10189
+ for (const [key2, patch] of snapshot) {
10190
+ const local = lock.entries[key2];
10080
10191
  if (!local) continue;
10081
- merged[key] = merged[key] ? { ...merged[key], ...patch } : local;
10192
+ merged[key2] = merged[key2] ? { ...merged[key2], ...patch } : local;
10082
10193
  }
10083
- for (const [key, entry] of Object.entries(lock.entries)) {
10084
- if (!merged[key]) merged[key] = entry;
10194
+ for (const [key2, entry] of Object.entries(lock.entries)) {
10195
+ if (!merged[key2]) merged[key2] = entry;
10085
10196
  }
10086
10197
  const deletes = dirtyDeletes.get(lock);
10087
10198
  const deleteSnapshot = deletes ? new Set(deletes) : /* @__PURE__ */ new Set();
10088
- for (const key of deleteSnapshot) delete merged[key];
10199
+ for (const key2 of deleteSnapshot) delete merged[key2];
10089
10200
  const sorted = {};
10090
- for (const key of Object.keys(merged).sort()) {
10091
- sorted[key] = merged[key];
10201
+ for (const key2 of Object.keys(merged).sort()) {
10202
+ sorted[key2] = merged[key2];
10092
10203
  }
10093
10204
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
10094
10205
  try {
@@ -10099,48 +10210,48 @@ async function writeLockWhileHeld(file, lock) {
10099
10210
  }
10100
10211
  const currentDirty = dirtyPatches.get(lock);
10101
10212
  if (currentDirty) {
10102
- for (const [key, patch] of snapshot) {
10103
- const current = currentDirty.get(key);
10213
+ for (const [key2, patch] of snapshot) {
10214
+ const current = currentDirty.get(key2);
10104
10215
  if (!current) continue;
10105
10216
  for (const [field, value] of Object.entries(patch)) {
10106
10217
  if (Object.is(current[field], value)) {
10107
10218
  delete current[field];
10108
10219
  }
10109
10220
  }
10110
- if (Object.keys(current).length === 0) currentDirty.delete(key);
10221
+ if (Object.keys(current).length === 0) currentDirty.delete(key2);
10111
10222
  }
10112
10223
  }
10113
10224
  const stillDirty = dirtyDeletes.get(lock);
10114
10225
  if (stillDirty) {
10115
- for (const key of deleteSnapshot) stillDirty.delete(key);
10226
+ for (const key2 of deleteSnapshot) stillDirty.delete(key2);
10116
10227
  if (stillDirty.size === 0) dirtyDeletes.delete(lock);
10117
10228
  }
10118
10229
  const localAfterWrite = lock.entries;
10119
10230
  lock.entries = { ...merged };
10120
- for (const [key, patch] of currentDirty ?? []) {
10121
- const base = lock.entries[key] ?? localAfterWrite[key];
10122
- if (base) lock.entries[key] = { ...base, ...patch };
10231
+ for (const [key2, patch] of currentDirty ?? []) {
10232
+ const base = lock.entries[key2] ?? localAfterWrite[key2];
10233
+ if (base) lock.entries[key2] = { ...base, ...patch };
10123
10234
  }
10124
10235
  }
10125
- function upsert(lock, key, patch) {
10126
- dirtyDeletes.get(lock)?.delete(key);
10127
- const existing = lock.entries[key];
10236
+ function upsert(lock, key2, patch) {
10237
+ dirtyDeletes.get(lock)?.delete(key2);
10238
+ const existing = lock.entries[key2];
10128
10239
  const next = { ...existing, ...patch };
10129
- lock.entries[key] = next;
10240
+ lock.entries[key2] = next;
10130
10241
  let dirty = dirtyPatches.get(lock);
10131
10242
  if (!dirty) {
10132
10243
  dirty = /* @__PURE__ */ new Map();
10133
10244
  dirtyPatches.set(lock, dirty);
10134
10245
  }
10135
- dirty.set(key, { ...dirty.get(key) ?? {}, ...patch });
10246
+ dirty.set(key2, { ...dirty.get(key2) ?? {}, ...patch });
10136
10247
  return next;
10137
10248
  }
10138
- function remove(lock, key) {
10139
- if (!lock.entries[key]) return false;
10140
- delete lock.entries[key];
10249
+ function remove(lock, key2) {
10250
+ if (!lock.entries[key2]) return false;
10251
+ delete lock.entries[key2];
10141
10252
  const patches = dirtyPatches.get(lock);
10142
10253
  if (patches) {
10143
- patches.delete(key);
10254
+ patches.delete(key2);
10144
10255
  if (patches.size === 0) dirtyPatches.delete(lock);
10145
10256
  }
10146
10257
  let deletes = dirtyDeletes.get(lock);
@@ -10148,7 +10259,7 @@ function remove(lock, key) {
10148
10259
  deletes = /* @__PURE__ */ new Set();
10149
10260
  dirtyDeletes.set(lock, deletes);
10150
10261
  }
10151
- deletes.add(key);
10262
+ deletes.add(key2);
10152
10263
  return true;
10153
10264
  }
10154
10265
  var FILE_LOCK_TIMEOUT_MS = 1e4;
@@ -10246,8 +10357,8 @@ function currentEntryOutputPath(entry, spec, index) {
10246
10357
  function normalizeLockOutputPaths(lock, specs) {
10247
10358
  const byKey = new Map(specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
10248
10359
  let changed = 0;
10249
- for (const [key, entry] of Object.entries(lock.entries)) {
10250
- const spec = byKey.get(key);
10360
+ for (const [key2, entry] of Object.entries(lock.entries)) {
10361
+ const spec = byKey.get(key2);
10251
10362
  if (!spec) continue;
10252
10363
  let entryChanged = false;
10253
10364
  const outputs = entry.outputs.map((output, index) => {
@@ -10258,7 +10369,7 @@ function normalizeLockOutputPaths(lock, specs) {
10258
10369
  entryChanged = true;
10259
10370
  return { ...output, path: portable };
10260
10371
  });
10261
- if (entryChanged) upsert(lock, key, { outputs });
10372
+ if (entryChanged) upsert(lock, key2, { outputs });
10262
10373
  }
10263
10374
  return changed;
10264
10375
  }
@@ -10289,8 +10400,8 @@ function resolveSpecEntryOutputs(entry, spec) {
10289
10400
  }
10290
10401
  function resolveStyleOutputs(lock, styleId, manifestDir) {
10291
10402
  const prefix = `${styleId}/`;
10292
- return Object.entries(lock.entries).filter(([key]) => key.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
10293
- ([key, entry]) => resolveEntryOutputs(entry, key.slice(prefix.length), manifestDir)
10403
+ return Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b)).flatMap(
10404
+ ([key2, entry]) => resolveEntryOutputs(entry, key2.slice(prefix.length), manifestDir)
10294
10405
  );
10295
10406
  }
10296
10407
  function selectEntryOutput(entry, role) {
@@ -10413,10 +10524,10 @@ function culpritEntries(message6) {
10413
10524
  const match = /^ {2}(assets|styles)\.([^.:\s]+)[.:]/.exec(line);
10414
10525
  if (!match) continue;
10415
10526
  const kind = match[1] === "styles" ? "style" : "asset";
10416
- const key = `${kind}:${match[2]}`;
10417
- const entry = found.get(key) ?? { kind, id: match[2], issues: [] };
10527
+ const key2 = `${kind}:${match[2]}`;
10528
+ const entry = found.get(key2) ?? { kind, id: match[2], issues: [] };
10418
10529
  entry.issues.push(line.trim());
10419
- found.set(key, entry);
10530
+ found.set(key2, entry);
10420
10531
  }
10421
10532
  return [...found.values()];
10422
10533
  }
@@ -10562,6 +10673,7 @@ function dependencyAssetIds(asset, styleAnchors = []) {
10562
10673
  asset?.connect?.upper?.of,
10563
10674
  asset?.animation?.motionFrom,
10564
10675
  asset?.mirror,
10676
+ asset?.derive?.from,
10565
10677
  asset?.styleCharacter,
10566
10678
  ...asset?.styleCharacter ? [] : styleAnchors
10567
10679
  ].filter((id) => Boolean(id))
@@ -11020,6 +11132,64 @@ async function resolveSpecs(loaded, filter) {
11020
11132
  }
11021
11133
  if (finalized.has(assetId)) return resolved;
11022
11134
  const asset = manifest.assets[assetId];
11135
+ if (asset.derive) {
11136
+ const derive = asset.derive;
11137
+ let source;
11138
+ let sourceSpec;
11139
+ if (derive.from) {
11140
+ if (derive.from === assetId) throw new Error(`assets.${assetId}: an asset cannot derive from itself`);
11141
+ sourceSpec = await finalize(derive.from);
11142
+ if (sourceSpec.generator === "tiles" || sourceSpec.generator === "terrain") {
11143
+ throw new Error(`assets.${assetId}: a tile set is several images; derive takes a single image`);
11144
+ }
11145
+ source = { kind: "asset", assetId: derive.from, spec: sourceSpec };
11146
+ } else {
11147
+ const file = path8.resolve(root, derive.file);
11148
+ source = { kind: "file", file: derive.file, sha256: existsSync7(file) ? await sha256File(file) : null };
11149
+ }
11150
+ if (derive.transform === "scale") {
11151
+ resolved.width = derive.width;
11152
+ resolved.height = derive.height;
11153
+ } else if (sourceSpec) {
11154
+ resolved.width = sourceSpec.width;
11155
+ resolved.height = sourceSpec.height;
11156
+ } else if (source.kind === "file" && source.sha256) {
11157
+ const metadata = imageMetadata(await readFile5(path8.resolve(root, source.file)));
11158
+ if (metadata?.width && metadata.height) {
11159
+ resolved.width = metadata.width;
11160
+ resolved.height = metadata.height;
11161
+ }
11162
+ }
11163
+ resolved.derive = {
11164
+ transform: derive.transform,
11165
+ ...derive.map ? { map: derive.map } : {},
11166
+ ...derive.palette ? { palette: derive.palette } : {},
11167
+ ...derive.width ? { width: derive.width } : {},
11168
+ ...derive.height ? { height: derive.height } : {},
11169
+ ...derive.mode ? { mode: derive.mode } : {},
11170
+ source
11171
+ };
11172
+ resolved.prompt = "";
11173
+ resolved.specHash = specHash(resolved, styleImageHashes, providerOptionIdentity, providerInputIdentities.get(assetId));
11174
+ resolved.cost = 0;
11175
+ resolved.candidates = 1;
11176
+ finalized.add(assetId);
11177
+ return resolved;
11178
+ }
11179
+ if (asset.external) {
11180
+ const inputs = [];
11181
+ for (const input of asset.external.inputs ?? []) {
11182
+ const file = path8.resolve(root, input);
11183
+ inputs.push({ path: input, sha256: existsSync7(file) ? await sha256File(file) : null });
11184
+ }
11185
+ resolved.external = { builder: asset.external.builder, inputs };
11186
+ resolved.prompt = "";
11187
+ resolved.specHash = specHash(resolved, styleImageHashes, providerOptionIdentity, providerInputIdentities.get(assetId));
11188
+ resolved.cost = 0;
11189
+ resolved.candidates = 1;
11190
+ finalized.add(assetId);
11191
+ return resolved;
11192
+ }
11023
11193
  if (asset.mirror) {
11024
11194
  if (asset.mirror === assetId) throw new Error(`assets.${assetId}: an asset cannot mirror itself`);
11025
11195
  const sourceSpec = await finalize(asset.mirror);
@@ -11181,8 +11351,8 @@ async function resolveSpecs(loaded, filter) {
11181
11351
  const sourceSpec = sourceStyleId ? await styleFinalizers.get(sourceStyleId)(asset.revision.from) : await finalize(asset.revision.from);
11182
11352
  const sourceStem = sourceSpec.quality?.outFile ?? (sourceSpec.source ? path8.resolve(root, sourceSpec.source) : sourceSpec.outFile);
11183
11353
  const sourceMembers = await revisionSourceMembers(sourceStem, `revision source ${asset.revision.from}`);
11184
- const sourceFile = sourceMembers?.[0]?.file ?? sourceStem;
11185
- const sourceImage = sourceMembers ? { ...sourceMembers[0], hash: sha256(JSON.stringify(sourceMembers.map((member) => member.sha256))) } : await optionalRevisionImage(sourceFile, "revision source");
11354
+ const sourceFile2 = sourceMembers?.[0]?.file ?? sourceStem;
11355
+ const sourceImage = sourceMembers ? { ...sourceMembers[0], hash: sha256(JSON.stringify(sourceMembers.map((member) => member.sha256))) } : await optionalRevisionImage(sourceFile2, "revision source");
11186
11356
  const sourceFps = sourceSpec.character?.animation?.fps ?? sourceSpec.objectPro?.animation?.fps ?? sourceSpec.revision?.fps ?? sourceSpec.revision?.sourceFps;
11187
11357
  const maskFile = asset.revision.mask ? path8.resolve(root, asset.revision.mask) : void 0;
11188
11358
  const maskImage = maskFile ? await optionalRevisionImage(maskFile, "revision mask", "png") : null;
@@ -11201,7 +11371,7 @@ async function resolveSpecs(loaded, filter) {
11201
11371
  mode: asset.revision.mode,
11202
11372
  sourceAssetId: asset.revision.from,
11203
11373
  ...sourceStyleId ? { sourceStyleId } : {},
11204
- sourceFile,
11374
+ sourceFile: sourceFile2,
11205
11375
  sourceSha256: sourceImage?.hash ?? null,
11206
11376
  sourceWidth: sourceImage?.width ?? null,
11207
11377
  sourceHeight: sourceImage?.height ?? null,
@@ -11376,8 +11546,8 @@ async function resolveSpecs(loaded, filter) {
11376
11546
  byOutput.set(file, owner);
11377
11547
  };
11378
11548
  for (const spec of specs) {
11379
- const key = `${spec.styleId}/${spec.assetId}`;
11380
- claimOutput(spec.outFile, key);
11549
+ const key2 = `${spec.styleId}/${spec.assetId}`;
11550
+ claimOutput(spec.outFile, key2);
11381
11551
  if (spec.quality) {
11382
11552
  if (spec.generator === "frames") {
11383
11553
  const frameInputs = Object.values(spec.providerInputs ?? {}).find(Array.isArray);
@@ -11392,11 +11562,11 @@ async function resolveSpecs(loaded, filter) {
11392
11562
  count,
11393
11563
  MediaType.PNG
11394
11564
  ),
11395
- `${key} quality ${role}`
11565
+ `${key2} quality ${role}`
11396
11566
  );
11397
11567
  }
11398
11568
  } else {
11399
- claimOutput(spec.quality.outFile, `${key} quality output`);
11569
+ claimOutput(spec.quality.outFile, `${key2} quality output`);
11400
11570
  }
11401
11571
  }
11402
11572
  }
@@ -11660,7 +11830,7 @@ function characterDirections(directions) {
11660
11830
  }
11661
11831
 
11662
11832
  // src/project.ts
11663
- import path16 from "path";
11833
+ import path18 from "path";
11664
11834
 
11665
11835
  // src/env.ts
11666
11836
  import { readFileSync as readFileSync4, existsSync as existsSync8 } from "fs";
@@ -11668,8 +11838,8 @@ import path9 from "path";
11668
11838
  function loadEnvFiles(dir) {
11669
11839
  const loaded = [];
11670
11840
  for (const [file, vars] of envFiles(dir)) {
11671
- for (const [key, value] of Object.entries(vars)) {
11672
- if (!(key in process.env)) process.env[key] = value;
11841
+ for (const [key2, value] of Object.entries(vars)) {
11842
+ if (!(key2 in process.env)) process.env[key2] = value;
11673
11843
  }
11674
11844
  loaded.push(file);
11675
11845
  }
@@ -11694,21 +11864,21 @@ function parseEnv(contents) {
11694
11864
  if (!line || line.startsWith("#")) continue;
11695
11865
  const eq = line.indexOf("=");
11696
11866
  if (eq <= 0) continue;
11697
- const key = line.slice(0, eq).replace(/^export\s+/, "").trim();
11698
- if (!key || key in vars) continue;
11867
+ const key2 = line.slice(0, eq).replace(/^export\s+/, "").trim();
11868
+ if (!key2 || key2 in vars) continue;
11699
11869
  let value = line.slice(eq + 1).trim();
11700
11870
  const quote = value[0];
11701
11871
  if ((quote === '"' || quote === "'") && value.endsWith(quote) && value.length >= 2) {
11702
11872
  value = value.slice(1, -1);
11703
11873
  }
11704
- vars[key] = value;
11874
+ vars[key2] = value;
11705
11875
  }
11706
11876
  return vars;
11707
11877
  }
11708
11878
 
11709
11879
  // src/pipeline/plan.ts
11710
- import { existsSync as existsSync11 } from "fs";
11711
- import path15 from "path";
11880
+ import { existsSync as existsSync13 } from "fs";
11881
+ import path17 from "path";
11712
11882
 
11713
11883
  // src/pipeline/mirror.ts
11714
11884
  import { mkdir as mkdir4, readFile as readFile6, rename as rename2, writeFile as writeFile4 } from "fs/promises";
@@ -11750,8 +11920,8 @@ function quantize(png, palette) {
11750
11920
  pixels[i + 2] = 0;
11751
11921
  continue;
11752
11922
  }
11753
- const key = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
11754
- let nearest = nearestOf.get(key);
11923
+ const key2 = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
11924
+ let nearest = nearestOf.get(key2);
11755
11925
  if (!nearest) {
11756
11926
  const pixel = { r: pixels[i], g: pixels[i + 1], b: pixels[i + 2] };
11757
11927
  nearest = colors[0];
@@ -11764,7 +11934,7 @@ function quantize(png, palette) {
11764
11934
  distance = candidateDistance;
11765
11935
  }
11766
11936
  }
11767
- nearestOf.set(key, nearest);
11937
+ nearestOf.set(key2, nearest);
11768
11938
  }
11769
11939
  if (pixels[i] !== nearest.r || pixels[i + 1] !== nearest.g || pixels[i + 2] !== nearest.b) changed++;
11770
11940
  pixels[i] = nearest.r;
@@ -11833,7 +12003,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
11833
12003
  const log = opts.onProgress ?? (() => {
11834
12004
  });
11835
12005
  const mirror = spec.mirror;
11836
- const key = lockKey(spec.styleId, spec.assetId);
12006
+ const key2 = lockKey(spec.styleId, spec.assetId);
11837
12007
  const sourceKey = lockKey(spec.styleId, mirror.sourceAssetId);
11838
12008
  const source = lock.entries[sourceKey];
11839
12009
  if (!source || source.status !== "downloaded" || !source.outputs.length) {
@@ -11865,7 +12035,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
11865
12035
  }
11866
12036
  const sourceMetadata = source.providerMetadata?.[source.provider] ?? {};
11867
12037
  const character = spec.character;
11868
- const entry = upsert(lock, key, {
12038
+ const entry = upsert(lock, key2, {
11869
12039
  styleId: spec.styleId,
11870
12040
  assetId: spec.assetId,
11871
12041
  specHash: spec.specHash,
@@ -11908,25 +12078,206 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
11908
12078
  postprocess: postprocessFor(spec)
11909
12079
  });
11910
12080
  await saveLock(lockPath, lock);
11911
- log(` mirror ${key} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
12081
+ log(` mirror ${key2} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
11912
12082
  return entry;
11913
12083
  }
11914
12084
 
11915
- // src/pipeline/quality-profile.ts
12085
+ // src/pipeline/derive.ts
11916
12086
  import { existsSync as existsSync9 } from "fs";
11917
- import path13 from "path";
12087
+ import { mkdir as mkdir5, readFile as readFile7, rename as rename3, writeFile as writeFile5 } from "fs/promises";
12088
+ import path11 from "path";
12089
+ var key = (r, g, b) => r << 16 | g << 8 | b;
12090
+ function recolor(png, map) {
12091
+ const { width, height, pixels } = decodePng(png);
12092
+ const table = /* @__PURE__ */ new Map();
12093
+ for (const [from, to] of Object.entries(map)) {
12094
+ const a = parseHex(from);
12095
+ const b = parseHex(to);
12096
+ table.set(key(a.r, a.g, a.b), [b.r, b.g, b.b]);
12097
+ }
12098
+ const out = Buffer.from(pixels);
12099
+ for (let i = 0; i < out.length; i += 4) {
12100
+ if (out[i + 3] === 0) continue;
12101
+ const hit = table.get(key(out[i], out[i + 1], out[i + 2]));
12102
+ if (hit) {
12103
+ out[i] = hit[0];
12104
+ out[i + 1] = hit[1];
12105
+ out[i + 2] = hit[2];
12106
+ }
12107
+ }
12108
+ return encodeRgbaPng(width, height, out);
12109
+ }
12110
+ function paletteSnap(png, palette) {
12111
+ const snapped = quantize(decodePng(png), normalizePalette(palette).map((color) => color.hex)).png;
12112
+ return encodeRgbaPng(snapped.width, snapped.height, snapped.pixels);
12113
+ }
12114
+ function scale(png, width, height, mode2 = "nearest") {
12115
+ const src = decodePng(png);
12116
+ const out = Buffer.alloc(width * height * 4);
12117
+ for (let y = 0; y < height; y++) {
12118
+ const y0 = Math.floor(y * src.height / height);
12119
+ const y1 = Math.max(y0 + 1, Math.ceil((y + 1) * src.height / height));
12120
+ for (let x = 0; x < width; x++) {
12121
+ const x0 = Math.floor(x * src.width / width);
12122
+ const x1 = Math.max(x0 + 1, Math.ceil((x + 1) * src.width / width));
12123
+ const at = (y * width + x) * 4;
12124
+ if (mode2 === "nearest") {
12125
+ src.pixels.copy(out, at, (y0 * src.width + x0) * 4, (y0 * src.width + x0) * 4 + 4);
12126
+ continue;
12127
+ }
12128
+ let a = 0;
12129
+ let r = 0;
12130
+ let g = 0;
12131
+ let b = 0;
12132
+ let n = 0;
12133
+ for (let sy = y0; sy < Math.min(y1, src.height); sy++) {
12134
+ for (let sx = x0; sx < Math.min(x1, src.width); sx++) {
12135
+ const i = (sy * src.width + sx) * 4;
12136
+ const alpha = src.pixels[i + 3];
12137
+ a += alpha;
12138
+ r += src.pixels[i] * alpha;
12139
+ g += src.pixels[i + 1] * alpha;
12140
+ b += src.pixels[i + 2] * alpha;
12141
+ n++;
12142
+ }
12143
+ }
12144
+ if (a > 0) {
12145
+ out[at] = Math.round(r / a);
12146
+ out[at + 1] = Math.round(g / a);
12147
+ out[at + 2] = Math.round(b / a);
12148
+ }
12149
+ out[at + 3] = Math.round(a / Math.max(1, n));
12150
+ }
12151
+ }
12152
+ return encodeRgbaPng(width, height, out);
12153
+ }
12154
+ function applyDerive(png, derive) {
12155
+ switch (derive.transform) {
12156
+ case "recolor":
12157
+ return recolor(png, derive.map);
12158
+ case "palette-snap":
12159
+ return paletteSnap(png, derive.palette);
12160
+ case "scale":
12161
+ return scale(png, derive.width, derive.height, derive.mode);
12162
+ }
12163
+ }
12164
+ async function sourceFile(spec, lock) {
12165
+ const derive = spec.derive;
12166
+ if (derive.source.kind === "file") {
12167
+ const file2 = path11.resolve(spec.root, derive.source.file);
12168
+ return existsSync9(file2) ? { file: file2, recorded: await sha256File(file2) } : { notReady: `source file ${derive.source.file} does not exist` };
12169
+ }
12170
+ const sourceKey = lockKey(spec.styleId, derive.source.assetId);
12171
+ const entry = lock.entries[sourceKey];
12172
+ if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
12173
+ return { notReady: `source ${sourceKey} has no downloaded output` };
12174
+ }
12175
+ if (entry.outputs.length !== 1) {
12176
+ return { notReady: `source ${sourceKey} has ${entry.outputs.length} outputs; derive takes a single image` };
12177
+ }
12178
+ const file = currentEntryOutputPath(entry, derive.source.spec, 0);
12179
+ if (!existsSync9(file)) return { notReady: `source ${sourceKey} is missing on disk: ${file}` };
12180
+ return { file, recorded: entry.outputs[0].sha256 };
12181
+ }
12182
+ async function deriveStale(spec, entry, lock) {
12183
+ const derive = spec.derive;
12184
+ if (derive.source.kind === "file") {
12185
+ const file = path11.resolve(spec.root, derive.source.file);
12186
+ if (!existsSync9(file)) return `source file ${derive.source.file} is missing`;
12187
+ return entry.derive?.sourceSha256 === await sha256File(file) ? null : `source file ${derive.source.file} changed`;
12188
+ }
12189
+ const source = lock.entries[lockKey(spec.styleId, derive.source.assetId)];
12190
+ const current = source?.outputs.length === 1 ? source.outputs[0].sha256 : void 0;
12191
+ return entry.derive?.sourceSha256 && entry.derive.sourceSha256 === current ? null : `source ${derive.source.assetId} changed`;
12192
+ }
12193
+ async function deriveAsset(spec, lock, lockPath, opts = {}) {
12194
+ const log = opts.onProgress ?? (() => {
12195
+ });
12196
+ const derive = spec.derive;
12197
+ const entryKey = lockKey(spec.styleId, spec.assetId);
12198
+ const source = await sourceFile(spec, lock);
12199
+ if ("notReady" in source) throw new Error(source.notReady);
12200
+ const bytes = applyDerive(await readFile7(source.file), derive);
12201
+ const target = expectedOutputPath(spec, void 0, 0, 1, MediaType.PNG);
12202
+ await mkdir5(path11.dirname(target), { recursive: true });
12203
+ const tmp = `${target}.pixelkiln.tmp`;
12204
+ await writeFile5(tmp, bytes);
12205
+ await rename3(tmp, target);
12206
+ const out = decodePng(bytes);
12207
+ const now = (/* @__PURE__ */ new Date()).toISOString();
12208
+ const entry = upsert(lock, entryKey, {
12209
+ styleId: spec.styleId,
12210
+ assetId: spec.assetId,
12211
+ specHash: spec.specHash,
12212
+ generator: spec.generator,
12213
+ tileFeature: null,
12214
+ prompt: "",
12215
+ width: out.width,
12216
+ height: out.height,
12217
+ revision: null,
12218
+ derive: derive.source.kind === "asset" ? { sourceAssetId: derive.source.assetId, sourceSha256: source.recorded } : { sourceFile: derive.source.file, sourceSha256: source.recorded },
12219
+ supersededOutputs: [],
12220
+ jobId: null,
12221
+ submissionComplete: void 0,
12222
+ reviewObjectId: null,
12223
+ objectId: null,
12224
+ candidateIndex: null,
12225
+ status: "downloaded",
12226
+ error: null,
12227
+ outputs: [{ path: portableOutputPath(target, spec.root), sha256: sha256(bytes), mediaType: MediaType.PNG }],
12228
+ sourceUrl: null,
12229
+ sourceUrls: [],
12230
+ submittedAt: now,
12231
+ downloadedAt: now,
12232
+ history: [],
12233
+ cost: 0,
12234
+ costUnit: spec.costUnit,
12235
+ provider: spec.provider,
12236
+ postprocess: void 0
12237
+ });
12238
+ await saveLock(lockPath, lock);
12239
+ log(` derive ${entryKey} \u2190 ${derive.source.kind === "asset" ? derive.source.assetId : derive.source.file} (${derive.transform}, no generation cost)`);
12240
+ return entry;
12241
+ }
11918
12242
 
11919
- // src/pipeline/refine.ts
12243
+ // src/pipeline/external.ts
12244
+ import { existsSync as existsSync10 } from "fs";
11920
12245
  import path12 from "path";
12246
+ async function inspectExternal(spec, entry) {
12247
+ const external = spec.external;
12248
+ const file = entry?.outputs.length ? currentEntryOutputPath(entry, spec, 0) : spec.outFile;
12249
+ const rebuild = `run \`${external.builder}\``;
12250
+ if (!existsSync10(file)) {
12251
+ return { state: "orphaned", reason: `built outside pixelkiln and not found at ${path12.relative(spec.root, file)}; ${rebuild}, then adopt --local` };
12252
+ }
12253
+ if (!entry) {
12254
+ return { state: "untracked", reason: `built outside pixelkiln; record it with adopt --local (builder: ${external.builder})` };
12255
+ }
12256
+ if (entry.specHash !== spec.specHash) {
12257
+ return { state: "orphaned", reason: `builder or an input changed since the file was recorded; ${rebuild}, then adopt --local --force` };
12258
+ }
12259
+ const recorded = entry.outputs[0]?.sha256;
12260
+ if (!recorded || await sha256File(file) !== recorded) {
12261
+ return { state: "orphaned", reason: "file changed since it was recorded; adopt --local --force to record it again" };
12262
+ }
12263
+ return { state: "ok", reason: "built outside pixelkiln; matches the recorded file" };
12264
+ }
12265
+
12266
+ // src/pipeline/quality-profile.ts
12267
+ import { existsSync as existsSync11 } from "fs";
12268
+ import path15 from "path";
12269
+
12270
+ // src/pipeline/refine.ts
12271
+ import path14 from "path";
11921
12272
  import { execFile } from "child_process";
11922
- import { mkdtemp, readFile as readFile8, rm as rm3 } from "fs/promises";
12273
+ import { mkdtemp, readFile as readFile9, rm as rm3 } from "fs/promises";
11923
12274
  import { tmpdir } from "os";
11924
12275
  import { promisify } from "util";
11925
12276
 
11926
12277
  // src/artifacts.ts
11927
- import path11 from "path";
12278
+ import path13 from "path";
11928
12279
  import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
11929
- import { mkdir as mkdir5, readFile as readFile7, rename as rename3, rm as rm2, writeFile as writeFile5 } from "fs/promises";
12280
+ import { mkdir as mkdir6, readFile as readFile8, rename as rename4, rm as rm2, writeFile as writeFile6 } from "fs/promises";
11930
12281
  var activeTransactions = /* @__PURE__ */ new Set();
11931
12282
  function message(error) {
11932
12283
  return error instanceof Error ? error.message : String(error);
@@ -11935,7 +12286,7 @@ function digest(data) {
11935
12286
  return createHash4("sha256").update(data).digest("hex");
11936
12287
  }
11937
12288
  function portableRelative(from, to) {
11938
- return path11.relative(from, path11.resolve(to)).split(path11.sep).join("/") || ".";
12289
+ return path13.relative(from, path13.resolve(to)).split(path13.sep).join("/") || ".";
11939
12290
  }
11940
12291
  function canonical2(value) {
11941
12292
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
@@ -11946,9 +12297,9 @@ function canonical2(value) {
11946
12297
  if (Array.isArray(value)) return value.map(canonical2);
11947
12298
  if (typeof value === "object") {
11948
12299
  const sorted = {};
11949
- for (const key of Object.keys(value).sort()) {
11950
- const item = value[key];
11951
- if (item !== void 0) sorted[key] = canonical2(item);
12300
+ for (const key2 of Object.keys(value).sort()) {
12301
+ const item = value[key2];
12302
+ if (item !== void 0) sorted[key2] = canonical2(item);
11952
12303
  }
11953
12304
  return sorted;
11954
12305
  }
@@ -11985,12 +12336,12 @@ function parseArtifactManifest(absolute, data) {
11985
12336
  return raw;
11986
12337
  }
11987
12338
  async function readArtifactBundleManifest(manifestPath) {
11988
- const absolute = path11.resolve(manifestPath);
11989
- return parseArtifactManifest(absolute, await readFile7(absolute, "utf8"));
12339
+ const absolute = path13.resolve(manifestPath);
12340
+ return parseArtifactManifest(absolute, await readFile8(absolute, "utf8"));
11990
12341
  }
11991
12342
  async function readOptional(file) {
11992
12343
  try {
11993
- return await readFile7(file);
12344
+ return await readFile8(file);
11994
12345
  } catch (error) {
11995
12346
  if (isCode(error, "ENOENT")) return null;
11996
12347
  throw error;
@@ -12009,8 +12360,8 @@ function processIsAlive(pid) {
12009
12360
  }
12010
12361
  }
12011
12362
  function validTemporaryPath(candidate, destination, type) {
12012
- return path11.dirname(candidate) === path11.dirname(destination) && path11.basename(candidate).startsWith(
12013
- `.${path11.basename(destination)}.pixelkiln-${type}-`
12363
+ return path13.dirname(candidate) === path13.dirname(destination) && path13.basename(candidate).startsWith(
12364
+ `.${path13.basename(destination)}.pixelkiln-${type}-`
12014
12365
  );
12015
12366
  }
12016
12367
  function parseTransaction(journal, data) {
@@ -12030,7 +12381,7 @@ async function removeTransactionFiles(journal) {
12030
12381
  await rm2(transactionMarker(journal), { force: true });
12031
12382
  }
12032
12383
  async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12033
- const journal = path11.resolve(recoveryFile);
12384
+ const journal = path13.resolve(recoveryFile);
12034
12385
  const bytes = await readOptional(journal);
12035
12386
  if (!bytes) {
12036
12387
  await rm2(transactionMarker(journal), { force: true });
@@ -12046,7 +12397,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12046
12397
  );
12047
12398
  }
12048
12399
  for (const entry of transaction.entries) {
12049
- if (typeof entry.destination !== "string" || typeof entry.stage !== "string" || typeof entry.sha256 !== "string" || entry.backup !== void 0 && typeof entry.backup !== "string" || !allowedDestinations.has(path11.resolve(entry.destination)) || !validTemporaryPath(entry.stage, entry.destination, "stage") || entry.backup !== void 0 && !validTemporaryPath(entry.backup, entry.destination, "backup")) {
12400
+ if (typeof entry.destination !== "string" || typeof entry.stage !== "string" || typeof entry.sha256 !== "string" || entry.backup !== void 0 && typeof entry.backup !== "string" || !allowedDestinations.has(path13.resolve(entry.destination)) || !validTemporaryPath(entry.stage, entry.destination, "stage") || entry.backup !== void 0 && !validTemporaryPath(entry.backup, entry.destination, "backup")) {
12050
12401
  throw new Error(
12051
12402
  `Refusing unsafe artifact recovery from ${journal}; its destinations or temporary paths do not match the current bundle.`
12052
12403
  );
@@ -12072,7 +12423,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12072
12423
  }
12073
12424
  await remove2(entry.destination, errors);
12074
12425
  try {
12075
- await rename3(entry.backup, entry.destination);
12426
+ await rename4(entry.backup, entry.destination);
12076
12427
  } catch (error) {
12077
12428
  errors.push(
12078
12429
  `could not restore ${entry.destination}; previous file remains at ${entry.backup}: ${message(error)}`
@@ -12092,7 +12443,7 @@ async function recoverArtifactTransaction(recoveryFile, allowedDestinations) {
12092
12443
  await removeTransactionFiles(journal);
12093
12444
  }
12094
12445
  function createArtifactBundleManifest(manifestPath, outputs, provenance) {
12095
- const root = path11.dirname(path11.resolve(manifestPath));
12446
+ const root = path13.dirname(path13.resolve(manifestPath));
12096
12447
  const sources = provenance.sources.map((source) => ({
12097
12448
  ...source,
12098
12449
  path: portableRelative(root, source.path)
@@ -12122,11 +12473,11 @@ function withArtifactManifest(manifestPath, outputs, provenance) {
12122
12473
  ];
12123
12474
  }
12124
12475
  async function writeManagedArtifactBundle(manifestPath, outputs, provenance, options = {}) {
12125
- const absoluteManifest = path11.resolve(manifestPath);
12476
+ const absoluteManifest = path13.resolve(manifestPath);
12126
12477
  const recoveryFile = `${absoluteManifest}.transaction`;
12127
12478
  const allowedDestinations = /* @__PURE__ */ new Set([
12128
12479
  absoluteManifest,
12129
- ...outputs.map((output) => path11.resolve(output.path))
12480
+ ...outputs.map((output) => path13.resolve(output.path))
12130
12481
  ]);
12131
12482
  await recoverArtifactTransaction(recoveryFile, allowedDestinations);
12132
12483
  const existingManifestBytes = await readOptional(absoluteManifest);
@@ -12144,13 +12495,13 @@ async function writeManagedArtifactBundle(manifestPath, outputs, provenance, opt
12144
12495
  }
12145
12496
  }
12146
12497
  if (!options.force) {
12147
- const root = path11.dirname(absoluteManifest);
12498
+ const root = path13.dirname(absoluteManifest);
12148
12499
  const recorded = new Map(
12149
- previous?.outputs.map((output) => [path11.resolve(root, output.path), output.sha256]) ?? []
12500
+ previous?.outputs.map((output) => [path13.resolve(root, output.path), output.sha256]) ?? []
12150
12501
  );
12151
12502
  const conflicts = [];
12152
12503
  for (const output of outputs) {
12153
- const destination = path11.resolve(output.path);
12504
+ const destination = path13.resolve(output.path);
12154
12505
  const current = await readOptional(destination);
12155
12506
  if (!current || digest(current) === digest(output.data)) continue;
12156
12507
  const expected = recorded.get(destination);
@@ -12172,15 +12523,15 @@ Pass { force: true } (CLI: --force) to take ownership and replace the complete b
12172
12523
  );
12173
12524
  }
12174
12525
  async function verifyArtifactBundle(manifestPath) {
12175
- const absolute = path11.resolve(manifestPath);
12526
+ const absolute = path13.resolve(manifestPath);
12176
12527
  const raw = await readArtifactBundleManifest(absolute);
12177
- const root = path11.dirname(absolute);
12528
+ const root = path13.dirname(absolute);
12178
12529
  const changedSources = [];
12179
12530
  const changedOutputs = [];
12180
12531
  for (const source of raw.sources) {
12181
12532
  let actual = null;
12182
12533
  try {
12183
- actual = digest(await readFile7(path11.resolve(root, source.path)));
12534
+ actual = digest(await readFile8(path13.resolve(root, source.path)));
12184
12535
  } catch (error) {
12185
12536
  if (!isCode(error, "ENOENT")) throw error;
12186
12537
  }
@@ -12188,7 +12539,7 @@ async function verifyArtifactBundle(manifestPath) {
12188
12539
  }
12189
12540
  for (const output of raw.outputs) {
12190
12541
  try {
12191
- if (digest(await readFile7(path11.resolve(root, output.path))) !== output.sha256) {
12542
+ if (digest(await readFile8(path13.resolve(root, output.path))) !== output.sha256) {
12192
12543
  changedOutputs.push(output.path);
12193
12544
  }
12194
12545
  } catch (error) {
@@ -12227,7 +12578,7 @@ async function rollback(prepared) {
12227
12578
  for (const artifact of [...prepared].reverse()) {
12228
12579
  if (!artifact.backup || !artifact.backedUp) continue;
12229
12580
  try {
12230
- await rename3(artifact.backup, artifact.destination);
12581
+ await rename4(artifact.backup, artifact.destination);
12231
12582
  artifact.backedUp = false;
12232
12583
  } catch (error) {
12233
12584
  errors.push(
@@ -12244,7 +12595,7 @@ async function writeArtifactBundle(files, options = {}) {
12244
12595
  if (!files.length) throw new Error("An artifact bundle must contain at least one file.");
12245
12596
  const normalized = files.map((file) => {
12246
12597
  if (!file.path.trim()) throw new Error("Artifact paths cannot be empty.");
12247
- return { destination: path11.resolve(file.path), data: Buffer.from(file.data) };
12598
+ return { destination: path13.resolve(file.path), data: Buffer.from(file.data) };
12248
12599
  });
12249
12600
  const destinations = /* @__PURE__ */ new Set();
12250
12601
  for (const artifact of normalized) {
@@ -12260,7 +12611,7 @@ async function writeArtifactBundle(files, options = {}) {
12260
12611
  const unchanged = [];
12261
12612
  for (const artifact of normalized) {
12262
12613
  try {
12263
- const current = await readFile7(artifact.destination);
12614
+ const current = await readFile8(artifact.destination);
12264
12615
  if (current.equals(artifact.data)) {
12265
12616
  unchanged.push(artifact.destination);
12266
12617
  } else {
@@ -12274,21 +12625,21 @@ async function writeArtifactBundle(files, options = {}) {
12274
12625
  if (!changed.length) return { changed: [], unchanged };
12275
12626
  const token = randomUUID3();
12276
12627
  for (const [index, artifact] of changed.entries()) {
12277
- const basename = path11.basename(artifact.destination);
12278
- artifact.stage = path11.join(
12279
- path11.dirname(artifact.destination),
12628
+ const basename = path13.basename(artifact.destination);
12629
+ artifact.stage = path13.join(
12630
+ path13.dirname(artifact.destination),
12280
12631
  `.${basename}.pixelkiln-stage-${token}-${index}`
12281
12632
  );
12282
12633
  if (artifact.existed) {
12283
- artifact.backup = path11.join(
12284
- path11.dirname(artifact.destination),
12634
+ artifact.backup = path13.join(
12635
+ path13.dirname(artifact.destination),
12285
12636
  `.${basename}.pixelkiln-backup-${token}-${index}`
12286
12637
  );
12287
12638
  }
12288
12639
  }
12289
- const journal = options.recoveryFile ? path11.resolve(options.recoveryFile) : null;
12640
+ const journal = options.recoveryFile ? path13.resolve(options.recoveryFile) : null;
12290
12641
  if (journal) {
12291
- await mkdir5(path11.dirname(journal), { recursive: true });
12642
+ await mkdir6(path13.dirname(journal), { recursive: true });
12292
12643
  const transaction = {
12293
12644
  format: "pixelkiln-artifact-transaction",
12294
12645
  version: 1,
@@ -12302,7 +12653,7 @@ async function writeArtifactBundle(files, options = {}) {
12302
12653
  }))
12303
12654
  };
12304
12655
  try {
12305
- await writeFile5(journal, JSON.stringify(transaction, null, 2) + "\n", { flag: "wx" });
12656
+ await writeFile6(journal, JSON.stringify(transaction, null, 2) + "\n", { flag: "wx" });
12306
12657
  activeTransactions.add(journal);
12307
12658
  } catch (error) {
12308
12659
  throw new Error(
@@ -12313,9 +12664,9 @@ async function writeArtifactBundle(files, options = {}) {
12313
12664
  }
12314
12665
  try {
12315
12666
  for (const [index, artifact] of changed.entries()) {
12316
- await mkdir5(path11.dirname(artifact.destination), { recursive: true });
12667
+ await mkdir6(path13.dirname(artifact.destination), { recursive: true });
12317
12668
  await options.beforeStage?.(artifact.destination, index);
12318
- await writeFile5(artifact.stage, artifact.data, { flag: "wx" });
12669
+ await writeFile6(artifact.stage, artifact.data, { flag: "wx" });
12319
12670
  }
12320
12671
  } catch (error) {
12321
12672
  const cleanupErrors2 = await rollback(changed);
@@ -12328,17 +12679,17 @@ async function writeArtifactBundle(files, options = {}) {
12328
12679
  try {
12329
12680
  for (const artifact of changed) {
12330
12681
  if (!artifact.existed) continue;
12331
- await rename3(artifact.destination, artifact.backup);
12682
+ await rename4(artifact.destination, artifact.backup);
12332
12683
  artifact.backedUp = true;
12333
12684
  }
12334
12685
  for (const [index, artifact] of changed.entries()) {
12335
12686
  await options.beforePromote?.(artifact.destination, index);
12336
- await rename3(artifact.stage, artifact.destination);
12687
+ await rename4(artifact.stage, artifact.destination);
12337
12688
  artifact.stage = void 0;
12338
12689
  artifact.promoted = true;
12339
12690
  }
12340
12691
  if (journal) {
12341
- await writeFile5(transactionMarker(journal), `${token}
12692
+ await writeFile6(transactionMarker(journal), `${token}
12342
12693
  `, { flag: "wx" });
12343
12694
  durableCommit = true;
12344
12695
  await options.afterCommit?.();
@@ -12579,16 +12930,16 @@ function sameFrameGrid(first, next) {
12579
12930
  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;
12580
12931
  }
12581
12932
  async function refineAsset(options) {
12582
- const source = path12.resolve(options.source);
12583
- const output = path12.resolve(options.output);
12933
+ const source = path14.resolve(options.source);
12934
+ const output = path14.resolve(options.output);
12584
12935
  if (source === output) throw new Error("Refinement source and output must be different files.");
12585
- const record = path12.resolve(qualityRecordPath(output));
12936
+ const record = path14.resolve(qualityRecordPath(output));
12586
12937
  const palette = normalizePalette(options.palette).map((color) => color.hex);
12587
12938
  const minGridConfidence = requireConfidence(options.minGridConfidence ?? "high");
12588
12939
  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.");
12589
12940
  let sourcePng;
12590
12941
  try {
12591
- sourcePng = decodePng(await readFile8(source));
12942
+ sourcePng = decodePng(await readFile9(source));
12592
12943
  } catch (error) {
12593
12944
  throw new Error(`Cannot read refinement source ${source}: ${message2(error)}`, { cause: error });
12594
12945
  }
@@ -12605,8 +12956,8 @@ async function refineAsset(options) {
12605
12956
  );
12606
12957
  }
12607
12958
  }
12608
- const temp = await mkdtemp(path12.join(tmpdir(), "pixelkiln-refine-"));
12609
- const recovered = path12.join(temp, "native.png");
12959
+ const temp = await mkdtemp(path14.join(tmpdir(), "pixelkiln-refine-"));
12960
+ const recovered = path14.join(temp, "native.png");
12610
12961
  const fixerCommand = compatibilityCommand ?? options.fixerPython ?? process.env.PIXELKILN_PIXEL_FIXER_PYTHON ?? "python3";
12611
12962
  const args = compatibilityCommand ? [...options.fixerArgsPrefix ?? [], source, "--extract", recovered] : ["-c", PYTHON_FIXER_BRIDGE, source, recovered];
12612
12963
  try {
@@ -12627,7 +12978,7 @@ async function refineAsset(options) {
12627
12978
  );
12628
12979
  }
12629
12980
  const detection = parseDetection(firstJsonObject(stdout));
12630
- const native = decodePng(await readFile8(recovered));
12981
+ const native = decodePng(await readFile9(recovered));
12631
12982
  const quantized = quantizeToPalette(native, palette);
12632
12983
  const png = encodeRgbaPng(quantized.width, quantized.height, quantized.pixels);
12633
12984
  const audit = auditRefinement(
@@ -12691,18 +13042,18 @@ async function refineFrameSet(options) {
12691
13042
  if (roles.some((role) => !role.trim()) || new Set(roles).size !== roles.length) {
12692
13043
  throw new Error("Frame-set roles must be non-empty and unique.");
12693
13044
  }
12694
- const output = path12.resolve(options.output);
12695
- const record = path12.resolve(qualityRecordPath(output));
13045
+ const output = path14.resolve(options.output);
13046
+ const record = path14.resolve(qualityRecordPath(output));
12696
13047
  const palette = normalizeRefinementPalette(options.palette);
12697
13048
  const finalOutputs = options.sources.map((source, index) => qualityFrameOutputPath(output, source.role, index));
12698
13049
  if (new Set(finalOutputs).size !== finalOutputs.length) {
12699
13050
  throw new Error("Frame-set roles resolve to duplicate output filenames.");
12700
13051
  }
12701
- const sourceSet = new Set(options.sources.map((source) => path12.resolve(source.path)));
13052
+ const sourceSet = new Set(options.sources.map((source) => path14.resolve(source.path)));
12702
13053
  if (finalOutputs.some((file) => sourceSet.has(file))) {
12703
13054
  throw new Error("Frame-set refinement sources and outputs must be different files.");
12704
13055
  }
12705
- const temp = await mkdtemp(path12.join(tmpdir(), "pixelkiln-refine-frames-"));
13056
+ const temp = await mkdtemp(path14.join(tmpdir(), "pixelkiln-refine-frames-"));
12706
13057
  try {
12707
13058
  const frames = [];
12708
13059
  const outputs = [];
@@ -12710,8 +13061,8 @@ async function refineFrameSet(options) {
12710
13061
  const sourcePaths = [];
12711
13062
  let firstOptions = null;
12712
13063
  for (const [index, sourceEntry] of options.sources.entries()) {
12713
- const source = path12.resolve(sourceEntry.path);
12714
- const temporaryOutput = path12.join(temp, `${String(index).padStart(2, "0")}.png`);
13064
+ const source = path14.resolve(sourceEntry.path);
13065
+ const temporaryOutput = path14.join(temp, `${String(index).padStart(2, "0")}.png`);
12715
13066
  const refined = await refineAsset({
12716
13067
  source,
12717
13068
  output: temporaryOutput,
@@ -12743,7 +13094,7 @@ async function refineFrameSet(options) {
12743
13094
  });
12744
13095
  outputs.push({
12745
13096
  path: finalOutputs[index],
12746
- data: await readFile8(temporaryOutput)
13097
+ data: await readFile9(temporaryOutput)
12747
13098
  });
12748
13099
  }
12749
13100
  const first = frames[0];
@@ -12786,7 +13137,7 @@ async function refineFrameSet(options) {
12786
13137
  );
12787
13138
  return {
12788
13139
  sources: sourcePaths,
12789
- outputs: outputs.map((item) => path12.resolve(item.path)),
13140
+ outputs: outputs.map((item) => path14.resolve(item.path)),
12790
13141
  record,
12791
13142
  frames,
12792
13143
  palette,
@@ -12797,12 +13148,12 @@ async function refineFrameSet(options) {
12797
13148
  }
12798
13149
  }
12799
13150
  async function checkQualityRecord(recordPath) {
12800
- const record = path12.resolve(recordPath);
13151
+ const record = path14.resolve(recordPath);
12801
13152
  const manifest = await readArtifactBundleManifest(record);
12802
13153
  const options = parseRecordOptions(manifest, record);
12803
13154
  const verification = await verifyArtifactBundle(record);
12804
- const sources = manifest.sources.map((source2) => path12.resolve(path12.dirname(record), source2.path));
12805
- const outputs = manifest.outputs.map((output2) => path12.resolve(path12.dirname(record), output2.path));
13155
+ const sources = manifest.sources.map((source2) => path14.resolve(path14.dirname(record), source2.path));
13156
+ const outputs = manifest.outputs.map((output2) => path14.resolve(path14.dirname(record), output2.path));
12806
13157
  const source = sources[0] ?? "";
12807
13158
  const output = outputs[0] ?? "";
12808
13159
  const expectedCount = options.frameSet?.count ?? 1;
@@ -12835,7 +13186,7 @@ async function checkQualityRecord(recordPath) {
12835
13186
  async function approveQualityRecord(recordPath, approval) {
12836
13187
  const reviewer = approval.reviewer.trim();
12837
13188
  if (!reviewer) throw new Error("A human reviewer name is required.");
12838
- const record = path12.resolve(recordPath);
13189
+ const record = path14.resolve(recordPath);
12839
13190
  const manifest = await readArtifactBundleManifest(record);
12840
13191
  const options = parseRecordOptions(manifest, record);
12841
13192
  const verification = await verifyArtifactBundle(record);
@@ -12856,14 +13207,14 @@ async function approveQualityRecord(recordPath, approval) {
12856
13207
  `A refinement record must contain exactly ${expectedCount} source(s) and output(s).`
12857
13208
  );
12858
13209
  }
12859
- const root = path12.dirname(record);
13210
+ const root = path14.dirname(record);
12860
13211
  const outputs = await Promise.all(manifest.outputs.map(async (entry) => {
12861
- const outputPath = path12.resolve(root, entry.path);
12862
- return { path: outputPath, data: await readFile8(outputPath) };
13212
+ const outputPath = path14.resolve(root, entry.path);
13213
+ return { path: outputPath, data: await readFile9(outputPath) };
12863
13214
  }));
12864
13215
  const sources = manifest.sources.map((source) => ({
12865
13216
  ...source,
12866
- path: path12.resolve(root, source.path)
13217
+ path: path14.resolve(root, source.path)
12867
13218
  }));
12868
13219
  const approved = {
12869
13220
  ...options,
@@ -12895,8 +13246,8 @@ async function qualitySource(spec, lock) {
12895
13246
  if (spec.generator === "frames") {
12896
13247
  return { items: null, reason: "frame-set quality requires ordered downloaded provider outputs" };
12897
13248
  }
12898
- const source = path13.resolve(spec.root, spec.source);
12899
- return existsSync9(source) ? { items: [{ role: "source", path: source }] } : { items: null, reason: `declared source is missing: ${spec.source}` };
13249
+ const source = path15.resolve(spec.root, spec.source);
13250
+ return existsSync11(source) ? { items: [{ role: "source", path: source }] } : { items: null, reason: `declared source is missing: ${spec.source}` };
12900
13251
  }
12901
13252
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
12902
13253
  if (!entry) return { items: null, reason: "raw provider output is not in the lockfile" };
@@ -12925,7 +13276,7 @@ async function qualitySource(spec, lock) {
12925
13276
  }
12926
13277
  if (role) roles.add(role);
12927
13278
  const source = currentEntryOutputPath(entry, spec, index);
12928
- if (!existsSync9(source)) return { items: null, reason: `raw provider output is missing: ${source}` };
13279
+ if (!existsSync11(source)) return { items: null, reason: `raw provider output is missing: ${source}` };
12929
13280
  if (await sha256File(source) !== output.sha256) {
12930
13281
  return { items: null, reason: "raw provider output was modified after download" };
12931
13282
  }
@@ -12935,18 +13286,18 @@ async function qualitySource(spec, lock) {
12935
13286
  }
12936
13287
  async function inspectQualityProfile(spec, lock) {
12937
13288
  if (!spec.quality) return null;
12938
- const key = lockKey(spec.styleId, spec.assetId);
13289
+ const key2 = lockKey(spec.styleId, spec.assetId);
12939
13290
  const output = spec.quality.outFile;
12940
13291
  const record = qualityRecordPath(output);
12941
13292
  const source = await qualitySource(spec, lock);
12942
13293
  if (!source.items) {
12943
- return { key, state: "blocked", reason: source.reason, source: null, output, record };
13294
+ return { key: key2, state: "blocked", reason: source.reason, source: null, output, record };
12944
13295
  }
12945
13296
  const sourcePaths = source.items.map((item) => item.path);
12946
13297
  const expectedOutputs = spec.generator === "frames" ? source.items.map((item, index) => qualityFrameOutputPath(output, item.role, index)) : [output];
12947
- if (!existsSync9(record)) {
13298
+ if (!existsSync11(record)) {
12948
13299
  return {
12949
- key,
13300
+ key: key2,
12950
13301
  state: "needs-refinement",
12951
13302
  reason: "no refinement record",
12952
13303
  source: sourcePaths[0],
@@ -12962,10 +13313,10 @@ async function inspectQualityProfile(spec, lock) {
12962
13313
  const expectedRevision = spec.quality.fixerRevision ?? PIXEL_ART_FIXER_REVISION;
12963
13314
  const expectedTransparency = spec.quality.minTransparency ?? null;
12964
13315
  const expectedFrameSet = spec.generator === "frames" ? { fps: spec.quality.fps ?? 12, count: source.items.length, roles: source.items.map((item) => item.role) } : null;
12965
- const contractChanged = JSON.stringify(check.sources.map((item) => path13.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => path13.resolve(item))) || JSON.stringify(check.outputs.map((item) => path13.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => path13.resolve(item))) || JSON.stringify(check.options.palette.colors) !== JSON.stringify(expectedPalette) || check.options.nativeGrid.revision !== expectedRevision || check.options.audit.thresholds.minGridConfidence !== spec.quality.minGridConfidence || check.options.audit.thresholds.minTransparency !== expectedTransparency || (expectedFrameSet ? !check.options.frameSet || check.options.frameSet.fps !== expectedFrameSet.fps || check.options.frameSet.count !== expectedFrameSet.count || JSON.stringify(check.options.frameSet.roles) !== JSON.stringify(expectedFrameSet.roles) : check.options.frameSet !== void 0);
13316
+ const contractChanged = JSON.stringify(check.sources.map((item) => path15.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => path15.resolve(item))) || JSON.stringify(check.outputs.map((item) => path15.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => path15.resolve(item))) || JSON.stringify(check.options.palette.colors) !== JSON.stringify(expectedPalette) || check.options.nativeGrid.revision !== expectedRevision || check.options.audit.thresholds.minGridConfidence !== spec.quality.minGridConfidence || check.options.audit.thresholds.minTransparency !== expectedTransparency || (expectedFrameSet ? !check.options.frameSet || check.options.frameSet.fps !== expectedFrameSet.fps || check.options.frameSet.count !== expectedFrameSet.count || JSON.stringify(check.options.frameSet.roles) !== JSON.stringify(expectedFrameSet.roles) : check.options.frameSet !== void 0);
12966
13317
  if (contractChanged) {
12967
13318
  return {
12968
- key,
13319
+ key: key2,
12969
13320
  state: "needs-refinement",
12970
13321
  reason: "quality profile changed",
12971
13322
  source: sourcePaths[0],
@@ -12977,7 +13328,7 @@ async function inspectQualityProfile(spec, lock) {
12977
13328
  }
12978
13329
  if (!check.current || !check.auditSafe) {
12979
13330
  return {
12980
- key,
13331
+ key: key2,
12981
13332
  state: "needs-refinement",
12982
13333
  reason: check.reasons.filter((reason) => reason !== "human 1\xD7 review is pending").join("; ") || "refinement record is stale",
12983
13334
  source: sourcePaths[0],
@@ -12989,7 +13340,7 @@ async function inspectQualityProfile(spec, lock) {
12989
13340
  }
12990
13341
  if (!check.approved) {
12991
13342
  return {
12992
- key,
13343
+ key: key2,
12993
13344
  state: "needs-approval",
12994
13345
  reason: "automated checks passed; human 1\xD7 review is pending",
12995
13346
  source: sourcePaths[0],
@@ -13000,7 +13351,7 @@ async function inspectQualityProfile(spec, lock) {
13000
13351
  };
13001
13352
  }
13002
13353
  return {
13003
- key,
13354
+ key: key2,
13004
13355
  state: "approved",
13005
13356
  reason: "refined output and human approval are current",
13006
13357
  source: sourcePaths[0],
@@ -13011,7 +13362,7 @@ async function inspectQualityProfile(spec, lock) {
13011
13362
  };
13012
13363
  } catch (error) {
13013
13364
  return {
13014
- key,
13365
+ key: key2,
13015
13366
  state: "needs-refinement",
13016
13367
  reason: `invalid refinement record: ${error instanceof Error ? error.message : String(error)}`,
13017
13368
  source: sourcePaths[0],
@@ -13125,10 +13476,11 @@ async function requireApprovedQualitySources(specs, lock, assetIds, outputRoles)
13125
13476
  }
13126
13477
 
13127
13478
  // src/pipeline/revision.ts
13128
- import { existsSync as existsSync10 } from "fs";
13129
- import path14 from "path";
13479
+ import { existsSync as existsSync12 } from "fs";
13480
+ import path16 from "path";
13130
13481
  async function inspectRevisionReadiness(spec, lock) {
13131
13482
  if (spec.mirror) return inspectMirror(spec, lock, /* @__PURE__ */ new Set());
13483
+ if (spec.derive) return inspectDerive(spec, lock, /* @__PURE__ */ new Set());
13132
13484
  if (spec.character?.kind === "outfit") return inspectOutfit(spec, lock, /* @__PURE__ */ new Set());
13133
13485
  if (spec.character?.parentSpec) {
13134
13486
  const parent = await inspectCharacterParent(spec, lock, /* @__PURE__ */ new Set());
@@ -13147,7 +13499,7 @@ async function inspectStyleAnchor(spec, lock, seen) {
13147
13499
  const label = `style anchor ${spec.styleId}/${anchor.assetId}`;
13148
13500
  const dependency = await inspectParent(anchor.spec, lock, seen);
13149
13501
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13150
- if (!anchor.sha256 || !existsSync10(anchor.file)) return { ready: false, reason: `${label} has no generated south-facing file yet` };
13502
+ if (!anchor.sha256 || !existsSync12(anchor.file)) return { ready: false, reason: `${label} has no generated south-facing file yet` };
13151
13503
  if (await sha256File(anchor.file) !== anchor.sha256) {
13152
13504
  return { ready: false, reason: `${label} changed after the manifest was resolved` };
13153
13505
  }
@@ -13184,14 +13536,14 @@ async function inspectScene(spec) {
13184
13536
  const files = [{ label: "scene image", file: scene.file, sha256: scene.sha256 }];
13185
13537
  if (scene.placement.type === "mask") files.push({ label: "scene mask", file: scene.placement.file, sha256: scene.placement.sha256 });
13186
13538
  for (const { label, file, sha256: sha2562 } of files) {
13187
- if (!sha2562 || !existsSync10(file)) return { ready: false, reason: `${label} does not exist yet: ${file}` };
13539
+ if (!sha2562 || !existsSync12(file)) return { ready: false, reason: `${label} does not exist yet: ${file}` };
13188
13540
  if (await sha256File(file) !== sha2562) return { ready: false, reason: `${label} changed after the manifest was resolved` };
13189
13541
  }
13190
13542
  return { ready: true, reason: "scene is current" };
13191
13543
  }
13192
13544
  async function inspectVfxSprite(spec) {
13193
13545
  const sprite = spec.vfx.sprite;
13194
- if (!sprite.sha256 || !existsSync10(sprite.file)) return { ready: false, reason: `vfx sprite does not exist yet: ${sprite.file}` };
13546
+ if (!sprite.sha256 || !existsSync12(sprite.file)) return { ready: false, reason: `vfx sprite does not exist yet: ${sprite.file}` };
13195
13547
  if (await sha256File(sprite.file) !== sprite.sha256) return { ready: false, reason: "vfx sprite changed after the manifest was resolved" };
13196
13548
  return { ready: true, reason: "vfx sprite is current" };
13197
13549
  }
@@ -13201,13 +13553,22 @@ async function inspectMirror(spec, lock, seen) {
13201
13553
  const dependency = await inspectParent(source, lock, seen);
13202
13554
  return dependency.ready ? { ready: true, reason: `${label} is current` } : { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13203
13555
  }
13556
+ async function inspectDerive(spec, lock, seen) {
13557
+ const source = spec.derive.source;
13558
+ if (source.kind === "file") {
13559
+ return existsSync12(path16.resolve(spec.root, source.file)) ? { ready: true, reason: `source file ${source.file} exists` } : { ready: false, reason: `derive source file does not exist: ${source.file}` };
13560
+ }
13561
+ const label = `derive source ${spec.styleId}/${source.assetId}`;
13562
+ const dependency = await inspectParent(source.spec, lock, seen);
13563
+ return dependency.ready ? { ready: true, reason: `${label} is current` } : { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13564
+ }
13204
13565
  async function inspectOutfit(spec, lock, seen) {
13205
13566
  const character = spec.character;
13206
13567
  const outfit = character.outfit;
13207
13568
  const label = `outfit source ${spec.styleId}/${character.parentAssetId}`;
13208
13569
  const dependency = await inspectParent(character.parentSpec, lock, seen);
13209
13570
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13210
- if (!existsSync10(outfit.reference.path)) {
13571
+ if (!existsSync12(outfit.reference.path)) {
13211
13572
  return { ready: false, reason: `outfit reference is missing: ${outfit.reference.path}` };
13212
13573
  }
13213
13574
  if (await sha256File(outfit.reference.path) !== outfit.reference.sha256) {
@@ -13221,7 +13582,7 @@ async function inspectCharacterParent(spec, lock, seen) {
13221
13582
  const label = `${character.kind} parent ${spec.styleId}/${character.parentAssetId}`;
13222
13583
  const dependency = await inspectParent(parentSpec, lock, seen);
13223
13584
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13224
- if (!character.parentSha256 || !character.parentFile || !existsSync10(character.parentFile)) {
13585
+ if (!character.parentSha256 || !character.parentFile || !existsSync12(character.parentFile)) {
13225
13586
  return { ready: false, reason: `${label} has no generated south-facing file yet` };
13226
13587
  }
13227
13588
  if (await sha256File(character.parentFile) !== character.parentSha256) {
@@ -13239,7 +13600,7 @@ async function inspectObjectProParent(spec, lock, seen) {
13239
13600
  const label = `${object.kind} parent ${spec.styleId}/${object.parentAssetId}`;
13240
13601
  const dependency = await inspectParent(parentSpec, lock, seen);
13241
13602
  if (!dependency.ready) return { ready: false, reason: `${label} is not ready: ${dependency.reason}` };
13242
- if (!object.parentSha256 || !object.parentFile || !existsSync10(object.parentFile)) {
13603
+ if (!object.parentSha256 || !object.parentFile || !existsSync12(object.parentFile)) {
13243
13604
  return { ready: false, reason: `${label} has no generated south-facing file yet` };
13244
13605
  }
13245
13606
  if (await sha256File(object.parentFile) !== object.parentSha256) {
@@ -13265,7 +13626,7 @@ async function inspectRevision(spec, lock, seen) {
13265
13626
  const members = await inspectSourceMembers(spec, lock);
13266
13627
  if (!members.ready) return members;
13267
13628
  } else {
13268
- if (!revision.sourceSha256 || !existsSync10(revision.sourceFile)) {
13629
+ if (!revision.sourceSha256 || !existsSync12(revision.sourceFile)) {
13269
13630
  return { ready: false, reason: `revision source is missing: ${revision.sourceFile}` };
13270
13631
  }
13271
13632
  if (await sha256File(revision.sourceFile) !== revision.sourceSha256) {
@@ -13273,7 +13634,7 @@ async function inspectRevision(spec, lock, seen) {
13273
13634
  }
13274
13635
  }
13275
13636
  if (revision.maskFile) {
13276
- if (!revision.maskSha256 || !existsSync10(revision.maskFile)) {
13637
+ if (!revision.maskSha256 || !existsSync12(revision.maskFile)) {
13277
13638
  return { ready: false, reason: `revision mask is missing: ${revision.maskFile}` };
13278
13639
  }
13279
13640
  if (await sha256File(revision.maskFile) !== revision.maskSha256) {
@@ -13281,7 +13642,7 @@ async function inspectRevision(spec, lock, seen) {
13281
13642
  }
13282
13643
  }
13283
13644
  if (revision.lastFrameFile) {
13284
- if (!revision.lastFrameSha256 || !existsSync10(revision.lastFrameFile)) {
13645
+ if (!revision.lastFrameSha256 || !existsSync12(revision.lastFrameFile)) {
13285
13646
  return { ready: false, reason: `revision last frame is missing: ${revision.lastFrameFile}` };
13286
13647
  }
13287
13648
  if (await sha256File(revision.lastFrameFile) !== revision.lastFrameSha256) {
@@ -13294,7 +13655,7 @@ async function inspectSourceMembers(spec, lock) {
13294
13655
  const revision = spec.revision;
13295
13656
  const members = revision.sourceMembers;
13296
13657
  for (const member of members) {
13297
- if (!existsSync10(member.file)) return { ready: false, reason: `revision source member is missing: ${member.file}` };
13658
+ if (!existsSync12(member.file)) return { ready: false, reason: `revision source member is missing: ${member.file}` };
13298
13659
  if (await sha256File(member.file) !== member.sha256) {
13299
13660
  return { ready: false, reason: `revision source member changed after the manifest was resolved: ${member.file}` };
13300
13661
  }
@@ -13303,8 +13664,8 @@ async function inspectSourceMembers(spec, lock) {
13303
13664
  if (parent.source) return { ready: true, reason: "declared source set is present" };
13304
13665
  const entry = lock.entries[lockKey(parent.styleId, parent.assetId)];
13305
13666
  if (!entry) return { ready: false, reason: "revision source is not in the lockfile" };
13306
- const recorded = entry.outputs.map((_, index) => path14.resolve(currentEntryOutputPath(entry, parent, index))).sort();
13307
- const found = members.map((member) => path14.resolve(member.file)).sort();
13667
+ const recorded = entry.outputs.map((_, index) => path16.resolve(currentEntryOutputPath(entry, parent, index))).sort();
13668
+ const found = members.map((member) => path16.resolve(member.file)).sort();
13308
13669
  if (recorded.length !== found.length || recorded.some((file, index) => file !== found[index])) {
13309
13670
  return {
13310
13671
  ready: false,
@@ -13318,10 +13679,10 @@ async function requireRevisionReady(spec, lock) {
13318
13679
  if (inspection && !inspection.ready) throw new Error(inspection.reason);
13319
13680
  }
13320
13681
  async function inspectParent(spec, lock, seen) {
13321
- const key = lockKey(spec.styleId, spec.assetId);
13322
- if (seen.has(key)) return { ready: false, reason: `revision dependency cycle at ${key}` };
13682
+ const key2 = lockKey(spec.styleId, spec.assetId);
13683
+ if (seen.has(key2)) return { ready: false, reason: `revision dependency cycle at ${key2}` };
13323
13684
  const nextSeen = new Set(seen);
13324
- nextSeen.add(key);
13685
+ nextSeen.add(key2);
13325
13686
  if (spec.mirror) {
13326
13687
  const inputs = await inspectMirror(spec, lock, nextSeen);
13327
13688
  if (!inputs.ready) return inputs;
@@ -13361,10 +13722,10 @@ async function inspectParent(spec, lock, seen) {
13361
13722
  };
13362
13723
  }
13363
13724
  if (spec.source) {
13364
- const source = path14.resolve(spec.root, spec.source);
13365
- return existsSync10(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
13725
+ const source = path16.resolve(spec.root, spec.source);
13726
+ return existsSync12(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
13366
13727
  }
13367
- const entry = lock.entries[key];
13728
+ const entry = lock.entries[key2];
13368
13729
  if (!entry) return { ready: false, reason: "parent is not in the lockfile" };
13369
13730
  if (entry.specHash !== spec.specHash) {
13370
13731
  return { ready: false, reason: "parent generation spec is stale" };
@@ -13376,7 +13737,7 @@ async function inspectParent(spec, lock, seen) {
13376
13737
  for (let index = 0; index < entry.outputs.length; index++) {
13377
13738
  const output = entry.outputs[index];
13378
13739
  const file = currentEntryOutputPath(entry, spec, index);
13379
- if (!existsSync10(file)) return { ready: false, reason: `parent output is missing: ${file}` };
13740
+ if (!existsSync12(file)) return { ready: false, reason: `parent output is missing: ${file}` };
13380
13741
  if (await sha256File(file) !== output.sha256) {
13381
13742
  return { ready: false, reason: `parent output was modified: ${file}` };
13382
13743
  }
@@ -13392,9 +13753,19 @@ async function anyOutputModified(entry, spec) {
13392
13753
  }
13393
13754
  return false;
13394
13755
  }
13756
+ async function modifiedReason(entry, spec) {
13757
+ if (!entry.imported) return "output modified since download";
13758
+ const raw = entry.origin?.raw?.sha256;
13759
+ if (raw && existsSync13(currentEntryOutputPath(entry, spec, 0)) && await sha256File(currentEntryOutputPath(entry, spec, 0)) === raw) {
13760
+ const steps = entry.origin?.steps?.length ? ` (${entry.origin.steps.join("; ")})` : "";
13761
+ return `file is the unprocessed original; apply the recorded post-processing again${steps}, or run adopt --local --force to record it as it is`;
13762
+ }
13763
+ return "file changed since it was imported; run adopt --local --force to record the new version";
13764
+ }
13395
13765
  function dependencies(spec) {
13396
13766
  return [
13397
13767
  spec.mirror?.sourceSpec,
13768
+ spec.derive?.source.kind === "asset" ? spec.derive.source.spec : void 0,
13398
13769
  spec.revision?.sourceSpec,
13399
13770
  spec.character?.parentSpec,
13400
13771
  spec.character?.motionLeader?.spec,
@@ -13438,15 +13809,15 @@ function resumeCommandForStatus(status) {
13438
13809
  function resumeActions(specs, lock) {
13439
13810
  const grouped = /* @__PURE__ */ new Map();
13440
13811
  for (const spec of specs) {
13441
- const key = lockKey(spec.styleId, spec.assetId);
13442
- const entry = lock.entries[key];
13812
+ const key2 = lockKey(spec.styleId, spec.assetId);
13813
+ const entry = lock.entries[key2];
13443
13814
  if (!entry || entry.specHash !== spec.specHash) continue;
13444
13815
  if (entry.submissionComplete === false) continue;
13445
13816
  const command = resumeCommandForStatus(entry.status) ?? (entry.status === "downloaded" && entry.outputs.length && !postprocessCurrent(entry, spec) ? "fetch" : null);
13446
13817
  if (!command) continue;
13447
13818
  if (command === "poll" && !entry.jobId) continue;
13448
13819
  if (command === "pick" && !entry.reviewObjectId) continue;
13449
- grouped.set(command, [...grouped.get(command) ?? [], key]);
13820
+ grouped.set(command, [...grouped.get(command) ?? [], key2]);
13450
13821
  }
13451
13822
  return ["poll", "pick", "fetch"].flatMap((command) => {
13452
13823
  const keys = grouped.get(command);
@@ -13456,22 +13827,26 @@ function resumeActions(specs, lock) {
13456
13827
  async function buildPlan(specs, lock, opts = {}) {
13457
13828
  const items = [];
13458
13829
  for (const spec of specs) {
13459
- const key = lockKey(spec.styleId, spec.assetId);
13460
- const entry = lock.entries[key];
13830
+ const key2 = lockKey(spec.styleId, spec.assetId);
13831
+ const entry = lock.entries[key2];
13461
13832
  let state;
13462
13833
  let reason;
13463
13834
  const changedConnection = entry ? changedTerrainConnection(spec, entry, lock) : null;
13464
13835
  const changedMotion = entry ? changedMotionLeader(spec, entry, lock) : null;
13465
13836
  const changedSettings = entry ? changedTerrainSettings(spec, entry) : null;
13837
+ const derivedStale = spec.derive && entry ? await deriveStale(spec, entry, lock) : null;
13466
13838
  const revision = await inspectRevisionReadiness(spec, lock);
13467
13839
  if (revision && !revision.ready) {
13468
13840
  state = "blocked";
13469
13841
  reason = revision.reason;
13842
+ } else if (spec.external) {
13843
+ ;
13844
+ ({ state, reason } = await inspectExternal(spec, entry));
13470
13845
  } else if (opts.force) {
13471
13846
  state = "missing";
13472
13847
  reason = "--force";
13473
13848
  } else if (!entry && spec.source && spec.generator !== "frames" && spec.generator !== "vfx") {
13474
- if (existsSync11(path15.resolve(spec.root, spec.source))) {
13849
+ if (existsSync13(path17.resolve(spec.root, spec.source))) {
13475
13850
  state = "ok";
13476
13851
  reason = `placed from ${spec.source}; not generated`;
13477
13852
  } else {
@@ -13479,20 +13854,26 @@ async function buildPlan(specs, lock, opts = {}) {
13479
13854
  reason = `declared source is missing: ${spec.source}`;
13480
13855
  }
13481
13856
  } else if (!entry) {
13482
- if (existsSync11(spec.outFile)) {
13857
+ if (existsSync13(spec.outFile)) {
13483
13858
  state = "untracked";
13484
13859
  reason = "file on disk, no provenance recorded";
13485
13860
  } else {
13486
13861
  state = "missing";
13487
- reason = spec.mirror ? `not made yet; flipped from ${spec.mirror.sourceAssetId} (no generation cost)` : "not in lockfile";
13862
+ 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";
13488
13863
  }
13489
13864
  } else if (entry.specHash !== spec.specHash) {
13490
13865
  state = "stale";
13491
- reason = "prompt, size, or style changed";
13866
+ reason = spec.derive ? "transform, its parameters, or the source file changed; derive it again (no generation cost)" : "prompt, size, or style changed";
13867
+ } else if (derivedStale) {
13868
+ state = "stale";
13869
+ reason = `${derivedStale}; derive it again (no generation cost)`;
13870
+ } else if (spec.derive && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index)))) {
13871
+ state = "stale";
13872
+ reason = "derived output missing on disk; derive it again (no generation cost)";
13492
13873
  } else if (spec.mirror && !mirrorCurrent(entry, lock.entries[lockKey(spec.styleId, spec.mirror.sourceAssetId)])) {
13493
13874
  state = "stale";
13494
13875
  reason = `mirror source ${spec.mirror.sourceAssetId} changed; flip it again (no generation cost)`;
13495
- } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync11(currentEntryOutputPath(entry, spec, index)))) {
13876
+ } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index)))) {
13496
13877
  state = "stale";
13497
13878
  reason = "mirror output missing on disk; flip it again (no generation cost)";
13498
13879
  } else if (spec.character?.kind === "outfit" && entry.outfit?.sourceSha256 !== mirrorSourceHash(lock.entries[lockKey(spec.styleId, spec.character.parentAssetId)] ?? { outputs: [] })) {
@@ -13529,12 +13910,15 @@ async function buildPlan(specs, lock, opts = {}) {
13529
13910
  } else if (entry.status !== "downloaded") {
13530
13911
  state = "in-flight";
13531
13912
  reason = `awaiting ${entry.status}`;
13532
- } else if (entry.outputs.length === 0 || entry.outputs.some((_output, index) => !existsSync11(currentEntryOutputPath(entry, spec, index)))) {
13913
+ } else if (entry.outputs.length === 0 || entry.outputs.some((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index)))) {
13533
13914
  state = "orphaned";
13534
- reason = entry.outputs.length === 0 ? "no recorded output files" : `missing on disk: ${entry.outputs.filter((_output, index) => !existsSync11(currentEntryOutputPath(entry, spec, index))).map((o) => o.role ?? "asset").join(", ")}`;
13915
+ reason = entry.outputs.length === 0 ? "no recorded output files" : `missing on disk: ${entry.outputs.filter((_output, index) => !existsSync13(currentEntryOutputPath(entry, spec, index))).map((o) => o.role ?? "asset").join(", ")}`;
13535
13916
  } else if (await anyOutputModified(entry, spec)) {
13536
13917
  state = "orphaned";
13537
- reason = "output modified since download";
13918
+ reason = await modifiedReason(entry, spec);
13919
+ } else if (spec.derive) {
13920
+ state = "ok";
13921
+ reason = "up to date";
13538
13922
  } else if (spec.mirror && !postprocessCurrent(entry, spec)) {
13539
13923
  state = "stale";
13540
13924
  reason = "palette enforcement changed; flip the source again once it is refreshed (no generation cost)";
@@ -13546,7 +13930,7 @@ async function buildPlan(specs, lock, opts = {}) {
13546
13930
  reason = "up to date";
13547
13931
  }
13548
13932
  const quality = await inspectQualityProfile(spec, lock);
13549
- items.push({ spec, key, state, reason, ...quality ? { quality } : {} });
13933
+ items.push({ spec, key: key2, state, reason, ...quality ? { quality } : {} });
13550
13934
  }
13551
13935
  const isActionable = (i) => i.state === "missing" || i.state === "stale" || i.state === "failed";
13552
13936
  const stateOf = new Map(items.map((i) => [i.key, i.state]));
@@ -13560,7 +13944,7 @@ async function buildPlan(specs, lock, opts = {}) {
13560
13944
  item.reason = `parent ${parentKey} is being generated in this run; this follows in the next wave`;
13561
13945
  break;
13562
13946
  }
13563
- if (item.spec.mirror && (parentState === "recoverable" || parentState === "in-flight")) {
13947
+ if ((item.spec.mirror || item.spec.derive) && (parentState === "recoverable" || parentState === "in-flight")) {
13564
13948
  item.state = "blocked";
13565
13949
  item.reason = `mirror source ${parentKey} is ${parentState}; this follows in the next wave`;
13566
13950
  break;
@@ -13581,6 +13965,12 @@ async function buildPlan(specs, lock, opts = {}) {
13581
13965
  const provider = item.spec.provider;
13582
13966
  const costUnit = item.spec.costUnit ?? "generations";
13583
13967
  const group = groupsByProvider.get(provider);
13968
+ if (group && item.spec.derive) {
13969
+ group.actionable.push(item);
13970
+ group.candidates += item.spec.candidates;
13971
+ continue;
13972
+ }
13973
+ if (group && group.cost === 0 && group.actionable.every((other) => other.spec.derive)) group.costUnit = costUnit;
13584
13974
  if (group && group.costUnit !== costUnit) {
13585
13975
  throw new Error(
13586
13976
  `Provider "${provider}" returned mixed cost units (${group.costUnit}, ${costUnit})`
@@ -13630,13 +14020,13 @@ function summarize(plan) {
13630
14020
 
13631
14021
  // src/project.ts
13632
14022
  async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {}) {
13633
- const absolute = path16.resolve(manifestPath);
13634
- const root = path16.dirname(absolute);
14023
+ const absolute = path18.resolve(manifestPath);
14024
+ const root = path18.dirname(absolute);
13635
14025
  if (opts.env !== false) {
13636
14026
  loadEnvFiles(root);
13637
- if (path16.resolve(process.cwd()) !== root) loadEnvFiles(process.cwd());
14027
+ if (path18.resolve(process.cwd()) !== root) loadEnvFiles(process.cwd());
13638
14028
  }
13639
- const lockPath = path16.resolve(opts.lockPath ?? path16.join(root, "pixelkiln.lock.json"));
14029
+ const lockPath = path18.resolve(opts.lockPath ?? path18.join(root, "pixelkiln.lock.json"));
13640
14030
  let loaded = await loadManifest(absolute, { lenient: opts.lenient });
13641
14031
  const unresolved = [];
13642
14032
  const specs = await resolveSpecs(loaded, {
@@ -13660,11 +14050,11 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
13660
14050
  reload: () => openProject(absolute, { ...opts, env: false }),
13661
14051
  providers: () => [...new Set(specs.map((spec) => spec.provider))].sort(),
13662
14052
  provider: (id, mode2 = "online") => {
13663
- const key = `${mode2}:${id}`;
13664
- let adapter = adapters.get(key);
14053
+ const key2 = `${mode2}:${id}`;
14054
+ let adapter = adapters.get(key2);
13665
14055
  if (!adapter) {
13666
14056
  adapter = createProvider(id, mode2);
13667
- adapters.set(key, adapter);
14057
+ adapters.set(key2, adapter);
13668
14058
  }
13669
14059
  return adapter;
13670
14060
  }
@@ -13672,9 +14062,9 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
13672
14062
  }
13673
14063
 
13674
14064
  // src/recipes.ts
13675
- import path17 from "path";
13676
- import { existsSync as existsSync12 } from "fs";
13677
- import { readdir, readFile as readFile9 } from "fs/promises";
14065
+ import path19 from "path";
14066
+ import { existsSync as existsSync14 } from "fs";
14067
+ import { readdir, readFile as readFile10 } from "fs/promises";
13678
14068
  import { fileURLToPath } from "url";
13679
14069
  import { z as z4 } from "zod";
13680
14070
  var SHA256_RE = /^[0-9a-f]{64}$/;
@@ -13683,7 +14073,7 @@ var VERSION_RE = /^\d+\.\d+\.\d+$/;
13683
14073
  var RECIPE_FILE = "pixelkiln.recipe.json";
13684
14074
  var RECIPE_DIR_TOKEN = "{{recipeDir}}";
13685
14075
  var PortablePathSchema = z4.string().min(1).refine((value) => {
13686
- if (value.includes("\\") || path17.posix.isAbsolute(value)) return false;
14076
+ if (value.includes("\\") || path19.posix.isAbsolute(value)) return false;
13687
14077
  const parts = value.split("/");
13688
14078
  return !parts.includes("") && !parts.includes(".") && !parts.includes("..");
13689
14079
  }, "expected a portable relative path without '.', '..', or backslashes");
@@ -13843,9 +14233,9 @@ function canonical3(value) {
13843
14233
  if (Array.isArray(value)) return value.map(canonical3);
13844
14234
  if (typeof value === "object") {
13845
14235
  const sorted = {};
13846
- for (const key of Object.keys(value).sort()) {
13847
- const item = value[key];
13848
- if (item !== void 0) sorted[key] = canonical3(item);
14236
+ for (const key2 of Object.keys(value).sort()) {
14237
+ const item = value[key2];
14238
+ if (item !== void 0) sorted[key2] = canonical3(item);
13849
14239
  }
13850
14240
  return sorted;
13851
14241
  }
@@ -13859,10 +14249,10 @@ function message3(error) {
13859
14249
  return error instanceof Error ? error.message : String(error);
13860
14250
  }
13861
14251
  async function readRecipeFile(recipePath, bundled) {
13862
- const absolute = path17.resolve(recipePath);
14252
+ const absolute = path19.resolve(recipePath);
13863
14253
  let raw;
13864
14254
  try {
13865
- raw = JSON.parse(await readFile9(absolute, "utf8"));
14255
+ raw = JSON.parse(await readFile10(absolute, "utf8"));
13866
14256
  } catch (error) {
13867
14257
  throw new Error(`Could not read recipe ${absolute}: ${message3(error)}`, { cause: error });
13868
14258
  }
@@ -13873,13 +14263,13 @@ async function readRecipeFile(recipePath, bundled) {
13873
14263
  ` + parsed.error.issues.map((issue) => ` ${issue.path.join(".") || "$"}: ${issue.message}`).join("\n")
13874
14264
  );
13875
14265
  }
13876
- return { recipe: parsed.data, authored: raw, path: absolute, dir: path17.dirname(absolute), bundled };
14266
+ return { recipe: parsed.data, authored: raw, path: absolute, dir: path19.dirname(absolute), bundled };
13877
14267
  }
13878
14268
  async function walkRecipeFiles(root) {
13879
- if (!existsSync12(root)) return [];
14269
+ if (!existsSync14(root)) return [];
13880
14270
  const out = [];
13881
14271
  for (const entry of await readdir(root, { withFileTypes: true })) {
13882
- const resolved = path17.join(root, entry.name);
14272
+ const resolved = path19.join(root, entry.name);
13883
14273
  if (entry.isDirectory()) out.push(...await walkRecipeFiles(resolved));
13884
14274
  else if (entry.isFile() && entry.name === RECIPE_FILE) out.push(resolved);
13885
14275
  }
@@ -13890,7 +14280,7 @@ function bundledRecipeRoot() {
13890
14280
  }
13891
14281
  async function listBundledRecipes(root = bundledRecipeRoot()) {
13892
14282
  const recipes = await Promise.all(
13893
- (await walkRecipeFiles(path17.resolve(root))).map((file) => readRecipeFile(file, true))
14283
+ (await walkRecipeFiles(path19.resolve(root))).map((file) => readRecipeFile(file, true))
13894
14284
  );
13895
14285
  return recipes.sort(
13896
14286
  (a, b) => a.recipe.id.localeCompare(b.recipe.id) || compareVersions(b.recipe.version, a.recipe.version)
@@ -13913,9 +14303,9 @@ function parseSelector(selector) {
13913
14303
  return { id: match[1], version: match[2] };
13914
14304
  }
13915
14305
  async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
13916
- const local = path17.resolve(target);
13917
- if (existsSync12(local)) {
13918
- const recipePath = path17.basename(local) === RECIPE_FILE ? local : path17.join(local, RECIPE_FILE);
14306
+ const local = path19.resolve(target);
14307
+ if (existsSync14(local)) {
14308
+ const recipePath = path19.basename(local) === RECIPE_FILE ? local : path19.join(local, RECIPE_FILE);
13919
14309
  return readRecipeFile(recipePath, false);
13920
14310
  }
13921
14311
  if (target.startsWith(".") || target.startsWith("/") || target.includes("\\")) {
@@ -13929,8 +14319,8 @@ async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
13929
14319
  return matches[0];
13930
14320
  }
13931
14321
  async function verifyFile(root, file) {
13932
- const absolute = path17.resolve(root, ...file.path.split("/"));
13933
- if (!existsSync12(absolute)) {
14322
+ const absolute = path19.resolve(root, ...file.path.split("/"));
14323
+ if (!existsSync14(absolute)) {
13934
14324
  return { path: file.path, expectedSha256: file.sha256, actualSha256: null, status: "missing" };
13935
14325
  }
13936
14326
  const actualSha256 = await sha256File(absolute);
@@ -13945,7 +14335,7 @@ async function verifyRecipe(target, options = {}) {
13945
14335
  const loaded = await resolveRecipe(target, options.bundledRoot);
13946
14336
  const actualIntegrity = recipeDigest(loaded.authored);
13947
14337
  const files = await Promise.all(loaded.recipe.files.map((file) => verifyFile(loaded.dir, file)));
13948
- const modelRoot = options.modelRoot ? path17.resolve(options.modelRoot) : null;
14338
+ const modelRoot = options.modelRoot ? path19.resolve(options.modelRoot) : null;
13949
14339
  const models = modelRoot ? await Promise.all(loaded.recipe.models.map(async (model) => ({
13950
14340
  ...await verifyFile(modelRoot, model),
13951
14341
  source: model.source,
@@ -13979,37 +14369,37 @@ async function verifyRecipe(target, options = {}) {
13979
14369
  };
13980
14370
  }
13981
14371
  function renderStyle(style, destination, cwd) {
13982
- const portableDir = path17.relative(cwd, destination).split(path17.sep).join("/") || ".";
14372
+ const portableDir = path19.relative(cwd, destination).split(path19.sep).join("/") || ".";
13983
14373
  const replace = (value) => {
13984
14374
  if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
13985
14375
  if (Array.isArray(value)) return value.map(replace);
13986
14376
  if (value && typeof value === "object") {
13987
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, replace(item)]));
14377
+ return Object.fromEntries(Object.entries(value).map(([key2, item]) => [key2, replace(item)]));
13988
14378
  }
13989
14379
  return value;
13990
14380
  };
13991
14381
  return replace(style);
13992
14382
  }
13993
14383
  async function installRecipe(target, options = {}) {
13994
- const cwd = path17.resolve(options.cwd ?? process.cwd());
14384
+ const cwd = path19.resolve(options.cwd ?? process.cwd());
13995
14385
  const loaded = await resolveRecipe(target, options.bundledRoot);
13996
14386
  const verification = await verifyRecipe(loaded.path);
13997
14387
  if (!verification.ok) {
13998
14388
  throw new Error(`Recipe ${loaded.recipe.id}@${loaded.recipe.version} failed integrity verification.`);
13999
14389
  }
14000
- const destination = options.out ? path17.resolve(cwd, options.out) : path17.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
14390
+ const destination = options.out ? path19.resolve(cwd, options.out) : path19.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
14001
14391
  const sources = [
14002
14392
  { path: RECIPE_FILE, source: loaded.path },
14003
- ...loaded.recipe.files.map((file) => ({ path: file.path, source: path17.join(loaded.dir, ...file.path.split("/")) }))
14393
+ ...loaded.recipe.files.map((file) => ({ path: file.path, source: path19.join(loaded.dir, ...file.path.split("/")) }))
14004
14394
  ];
14005
14395
  const files = await Promise.all(sources.map(async (file) => ({
14006
- path: path17.join(destination, ...file.path.split("/")),
14007
- data: await readFile9(file.source)
14396
+ path: path19.join(destination, ...file.path.split("/")),
14397
+ data: await readFile10(file.source)
14008
14398
  })));
14009
14399
  if (!options.force) {
14010
14400
  for (const file of files) {
14011
- if (!existsSync12(file.path)) continue;
14012
- const current = await readFile9(file.path);
14401
+ if (!existsSync14(file.path)) continue;
14402
+ const current = await readFile10(file.path);
14013
14403
  if (!current.equals(file.data)) {
14014
14404
  throw new OverwriteRefusedError(
14015
14405
  `Recipe destination has local changes: ${file.path}. Choose another --out or pass --force to replace declared recipe files.`,
@@ -14033,9 +14423,9 @@ async function installRecipe(target, options = {}) {
14033
14423
  }
14034
14424
 
14035
14425
  // src/pipeline/audit.ts
14036
- import { readFile as readFile10 } from "fs/promises";
14037
- import { existsSync as existsSync13 } from "fs";
14038
- import path18 from "path";
14426
+ import { readFile as readFile11 } from "fs/promises";
14427
+ import { existsSync as existsSync15 } from "fs";
14428
+ import path20 from "path";
14039
14429
  function paletteDistance(asset, reference) {
14040
14430
  if (!asset.length || !reference.length) return 0;
14041
14431
  let total = 0;
@@ -14052,10 +14442,10 @@ function mergePalettes(palettes, topN = 24) {
14052
14442
  const totals = /* @__PURE__ */ new Map();
14053
14443
  for (const palette of palettes) {
14054
14444
  for (const color of palette) {
14055
- const key = `${color.r},${color.g},${color.b}`;
14056
- const existing = totals.get(key);
14445
+ const key2 = `${color.r},${color.g},${color.b}`;
14446
+ const existing = totals.get(key2);
14057
14447
  if (existing) existing.weight += color.weight;
14058
- else totals.set(key, { ...color });
14448
+ else totals.set(key2, { ...color });
14059
14449
  }
14060
14450
  }
14061
14451
  const merged = [...totals.values()].sort((a, b) => b.weight - a.weight).slice(0, topN);
@@ -14071,12 +14461,12 @@ async function auditStyle(loaded, specs, styleId, lock) {
14071
14461
  const unreadable = [];
14072
14462
  for (const spec of mine) {
14073
14463
  for (const output of resolveSpecOutputs(spec, lock, loaded.root)) {
14074
- if (!existsSync13(output.absolutePath)) {
14464
+ if (!existsSync15(output.absolutePath)) {
14075
14465
  missing.push(output.id);
14076
14466
  continue;
14077
14467
  }
14078
14468
  try {
14079
- const png = decodePng(await readFile10(output.absolutePath));
14469
+ const png = decodePng(await readFile11(output.absolutePath));
14080
14470
  const palette = extractPalette(png, 12);
14081
14471
  assets.push({
14082
14472
  assetId: spec.assetId,
@@ -14100,10 +14490,10 @@ async function auditStyle(loaded, specs, styleId, lock) {
14100
14490
  let referenceFromStyleImages = false;
14101
14491
  const refPalettes = [];
14102
14492
  for (const img of style.styleImages) {
14103
- const abs = path18.resolve(loaded.root, img.path);
14104
- if (!existsSync13(abs)) continue;
14493
+ const abs = path20.resolve(loaded.root, img.path);
14494
+ if (!existsSync15(abs)) continue;
14105
14495
  try {
14106
- refPalettes.push(extractPalette(decodePng(await readFile10(abs)), 12));
14496
+ refPalettes.push(extractPalette(decodePng(await readFile11(abs)), 12));
14107
14497
  } catch {
14108
14498
  }
14109
14499
  }
@@ -14179,15 +14569,15 @@ function hex(c) {
14179
14569
  }
14180
14570
 
14181
14571
  // src/pipeline/quality-regression.ts
14182
- import path19 from "path";
14183
- import { existsSync as existsSync14 } from "fs";
14184
- import { readFile as readFile11 } from "fs/promises";
14572
+ import path21 from "path";
14573
+ import { existsSync as existsSync16 } from "fs";
14574
+ import { readFile as readFile12 } from "fs/promises";
14185
14575
  import { z as z5 } from "zod";
14186
14576
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
14187
14577
  var HEX_RE = /^#[0-9a-f]{6}$/;
14188
14578
  var MAX_REDMEAN_DISTANCE = 765;
14189
14579
  var QualityPathSchema = z5.string().min(1).refine(
14190
- (value) => !path19.posix.isAbsolute(value) && !value.includes("\\"),
14580
+ (value) => !path21.posix.isAbsolute(value) && !value.includes("\\"),
14191
14581
  "expected a portable relative path"
14192
14582
  );
14193
14583
  var DEFAULT_QUALITY_TOLERANCES = {
@@ -14289,8 +14679,8 @@ function measureDecodedImageQuality(png, digest2) {
14289
14679
  const index = offset / 4;
14290
14680
  const x = index % png.width;
14291
14681
  const y = Math.floor(index / png.width);
14292
- const key = pixelKey(png.pixels, offset);
14293
- 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;
14682
+ const key2 = pixelKey(png.pixels, offset);
14683
+ 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;
14294
14684
  if (!hasSameNeighbor) {
14295
14685
  isolated++;
14296
14686
  }
@@ -14334,10 +14724,10 @@ function measureDecodedImageQuality(png, digest2) {
14334
14724
  };
14335
14725
  }
14336
14726
  async function measureImageQuality(file) {
14337
- const absolute = path19.resolve(file);
14727
+ const absolute = path21.resolve(file);
14338
14728
  let bytes;
14339
14729
  try {
14340
- bytes = await readFile11(absolute);
14730
+ bytes = await readFile12(absolute);
14341
14731
  } catch (error) {
14342
14732
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
14343
14733
  }
@@ -14356,11 +14746,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
14356
14746
  }
14357
14747
  const ids = parsed.data.map((entry) => entry.id);
14358
14748
  if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
14359
- const root = path19.dirname(path19.resolve(inputsFilePath));
14749
+ const root = path21.dirname(path21.resolve(inputsFilePath));
14360
14750
  return parsed.data.map((entry) => ({
14361
14751
  id: entry.id,
14362
- file: path19.resolve(root, entry.path),
14363
- ...entry.record ? { record: path19.resolve(root, entry.record) } : {},
14752
+ file: path21.resolve(root, entry.path),
14753
+ ...entry.record ? { record: path21.resolve(root, entry.record) } : {},
14364
14754
  tolerances: QualityToleranceSchema.parse({
14365
14755
  ...DEFAULT_QUALITY_TOLERANCES,
14366
14756
  ...entry.tolerances
@@ -14368,7 +14758,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
14368
14758
  }));
14369
14759
  }
14370
14760
  function portableRelative2(from, to) {
14371
- return path19.relative(from, path19.resolve(to)).split(path19.sep).join("/") || ".";
14761
+ return path21.relative(from, path21.resolve(to)).split(path21.sep).join("/") || ".";
14372
14762
  }
14373
14763
  async function verifyRecordForImage(recordPath, imagePath) {
14374
14764
  const verification = await verifyArtifactBundle(recordPath);
@@ -14383,20 +14773,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
14383
14773
  if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
14384
14774
  throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
14385
14775
  }
14386
- const outputs = record.outputs.map((output) => path19.resolve(path19.dirname(recordPath), output.path));
14387
- if (!outputs.includes(path19.resolve(imagePath))) {
14776
+ const outputs = record.outputs.map((output) => path21.resolve(path21.dirname(recordPath), output.path));
14777
+ if (!outputs.includes(path21.resolve(imagePath))) {
14388
14778
  throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
14389
14779
  }
14390
14780
  }
14391
14781
  async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14392
14782
  if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
14393
- const absolute = path19.resolve(baselinePath);
14783
+ const absolute = path21.resolve(baselinePath);
14394
14784
  for (const input of inputs) {
14395
- if (path19.resolve(input.file) === absolute || input.record && path19.resolve(input.record) === absolute) {
14785
+ if (path21.resolve(input.file) === absolute || input.record && path21.resolve(input.record) === absolute) {
14396
14786
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
14397
14787
  }
14398
14788
  }
14399
- const root = path19.dirname(absolute);
14789
+ const root = path21.dirname(absolute);
14400
14790
  const cases = [];
14401
14791
  for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
14402
14792
  const expected = await measureImageQuality(input.file);
@@ -14423,8 +14813,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14423
14813
  cases
14424
14814
  });
14425
14815
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
14426
- if (existsSync14(absolute) && !options.force) {
14427
- const current = await readFile11(absolute);
14816
+ if (existsSync16(absolute) && !options.force) {
14817
+ const current = await readFile12(absolute);
14428
14818
  if (!current.equals(data)) {
14429
14819
  throw new OverwriteRefusedError(
14430
14820
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -14436,13 +14826,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
14436
14826
  return { baseline, path: absolute, changed: result.changed.length > 0 };
14437
14827
  }
14438
14828
  async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14439
- const absolute = path19.resolve(baselinePath);
14440
- if (!existsSync14(absolute)) {
14829
+ const absolute = path21.resolve(baselinePath);
14830
+ if (!existsSync16(absolute)) {
14441
14831
  throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
14442
14832
  }
14443
14833
  let raw;
14444
14834
  try {
14445
- raw = JSON.parse(await readFile11(absolute, "utf8"));
14835
+ raw = JSON.parse(await readFile12(absolute, "utf8"));
14446
14836
  } catch (error) {
14447
14837
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
14448
14838
  }
@@ -14452,12 +14842,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14452
14842
  if (unknown.length) {
14453
14843
  throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
14454
14844
  }
14455
- const root = path19.dirname(absolute);
14845
+ const root = path21.dirname(absolute);
14456
14846
  const cases = [...raw.cases];
14457
14847
  const report = [];
14458
14848
  for (const id of only) {
14459
14849
  const input = byId.get(id);
14460
- if (path19.resolve(input.file) === absolute || input.record && path19.resolve(input.record) === absolute) {
14850
+ if (path21.resolve(input.file) === absolute || input.record && path21.resolve(input.record) === absolute) {
14461
14851
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
14462
14852
  }
14463
14853
  const expected = await measureImageQuality(input.file);
@@ -14487,16 +14877,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
14487
14877
  }
14488
14878
  const baseline = QualityBaselineSchema.parse({ ...raw, cases });
14489
14879
  const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
14490
- const current = await readFile11(absolute);
14880
+ const current = await readFile12(absolute);
14491
14881
  const changed = !current.equals(data);
14492
14882
  if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
14493
14883
  return { baseline, path: absolute, changed, cases: report };
14494
14884
  }
14495
14885
  async function readQualityBaseline(baselinePath) {
14496
- const absolute = path19.resolve(baselinePath);
14886
+ const absolute = path21.resolve(baselinePath);
14497
14887
  let raw;
14498
14888
  try {
14499
- raw = JSON.parse(await readFile11(absolute, "utf8"));
14889
+ raw = JSON.parse(await readFile12(absolute, "utf8"));
14500
14890
  } catch (error) {
14501
14891
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
14502
14892
  }
@@ -14518,7 +14908,7 @@ async function readQualityBaseline(baselinePath) {
14518
14908
  throw new Error(
14519
14909
  `Invalid quality baseline ${absolute}:
14520
14910
  ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
14521
- Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path19.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
14911
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path21.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
14522
14912
  );
14523
14913
  }
14524
14914
  return parsed.data;
@@ -14580,12 +14970,12 @@ function regressionViolations(expected, actual, tolerances) {
14580
14970
  return { violations, warnings };
14581
14971
  }
14582
14972
  async function checkQualityBaseline(baselinePath) {
14583
- const absolute = path19.resolve(baselinePath);
14973
+ const absolute = path21.resolve(baselinePath);
14584
14974
  const baseline = await readQualityBaseline(absolute);
14585
- const root = path19.dirname(absolute);
14975
+ const root = path21.dirname(absolute);
14586
14976
  const cases = [];
14587
14977
  for (const entry of baseline.cases) {
14588
- const file = path19.resolve(root, entry.file);
14978
+ const file = path21.resolve(root, entry.file);
14589
14979
  let actual = null;
14590
14980
  const violations = [];
14591
14981
  const warnings = [];
@@ -14598,7 +14988,7 @@ async function checkQualityBaseline(baselinePath) {
14598
14988
  violations.push(message4(error));
14599
14989
  }
14600
14990
  if (entry.record) {
14601
- const recordPath = path19.resolve(root, entry.record.path);
14991
+ const recordPath = path21.resolve(root, entry.record.path);
14602
14992
  try {
14603
14993
  const recordHash = await sha256File(recordPath);
14604
14994
  if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
@@ -14634,13 +15024,13 @@ async function checkQualityBaseline(baselinePath) {
14634
15024
  }
14635
15025
 
14636
15026
  // src/pipeline/cache-health.ts
14637
- import { existsSync as existsSync18 } from "fs";
14638
- import { readFile as readFile14, readdir as readdir2, rm as rm6 } from "fs/promises";
14639
- import path22 from "path";
15027
+ import { existsSync as existsSync20 } from "fs";
15028
+ import { readFile as readFile15, readdir as readdir2, rm as rm6 } from "fs/promises";
15029
+ import path24 from "path";
14640
15030
 
14641
15031
  // src/cache.ts
14642
- import { mkdir as mkdir6, readFile as readFile12, rename as rename4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
14643
- import { existsSync as existsSync15 } from "fs";
15032
+ import { mkdir as mkdir7, readFile as readFile13, rename as rename5, rm as rm4, writeFile as writeFile7 } from "fs/promises";
15033
+ import { existsSync as existsSync17 } from "fs";
14644
15034
  import pathModule from "path";
14645
15035
  import { z as z6 } from "zod";
14646
15036
  var HashCacheSchema = z6.object({
@@ -14655,10 +15045,10 @@ function isSha256Hash(value) {
14655
15045
  function parseCache(value) {
14656
15046
  return HashCacheSchema.parse(value);
14657
15047
  }
14658
- async function loadCache(path40) {
14659
- if (!existsSync15(path40)) return { version: 1, hashes: {} };
15048
+ async function loadCache(path43) {
15049
+ if (!existsSync17(path43)) return { version: 1, hashes: {} };
14660
15050
  try {
14661
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile12(path40, "utf8")));
15051
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile13(path43, "utf8")));
14662
15052
  if (!parsed.success) return { version: 1, hashes: {} };
14663
15053
  return {
14664
15054
  version: 1,
@@ -14670,30 +15060,30 @@ async function loadCache(path40) {
14670
15060
  return { version: 1, hashes: {} };
14671
15061
  }
14672
15062
  }
14673
- async function saveCache(path40, cache) {
15063
+ async function saveCache(path43, cache) {
14674
15064
  const sorted = {};
14675
- for (const key of Object.keys(cache.hashes).sort()) {
14676
- const hash = cache.hashes[key];
14677
- if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key}`);
14678
- sorted[key] = hash;
15065
+ for (const key2 of Object.keys(cache.hashes).sort()) {
15066
+ const hash = cache.hashes[key2];
15067
+ if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
15068
+ sorted[key2] = hash;
14679
15069
  }
14680
- await mkdir6(pathModule.dirname(pathModule.resolve(path40)), { recursive: true });
14681
- const tmp = `${path40}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
15070
+ await mkdir7(pathModule.dirname(pathModule.resolve(path43)), { recursive: true });
15071
+ const tmp = `${path43}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
14682
15072
  try {
14683
- await writeFile6(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
14684
- await rename4(tmp, path40);
15073
+ await writeFile7(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
15074
+ await rename5(tmp, path43);
14685
15075
  } finally {
14686
15076
  await rm4(tmp, { force: true });
14687
15077
  }
14688
15078
  }
14689
15079
  function pruneCache(cache, liveIds, namespace = "") {
14690
15080
  let removed = 0;
14691
- for (const key of Object.keys(cache.hashes)) {
14692
- const owned = namespace ? key.startsWith(namespace) : !key.includes(":");
15081
+ for (const key2 of Object.keys(cache.hashes)) {
15082
+ const owned = namespace ? key2.startsWith(namespace) : !key2.includes(":");
14693
15083
  if (!owned) continue;
14694
- const id = namespace ? key.slice(namespace.length) : key;
15084
+ const id = namespace ? key2.slice(namespace.length) : key2;
14695
15085
  if (!liveIds.has(id)) {
14696
- delete cache.hashes[key];
15086
+ delete cache.hashes[key2];
14697
15087
  removed++;
14698
15088
  }
14699
15089
  }
@@ -14705,38 +15095,39 @@ function cachePathFor(lockPath) {
14705
15095
  }
14706
15096
 
14707
15097
  // src/pipeline/history.ts
14708
- import { existsSync as existsSync17 } from "fs";
14709
- import path21 from "path";
15098
+ import { existsSync as existsSync19 } from "fs";
15099
+ import path23 from "path";
14710
15100
 
14711
15101
  // src/pipeline/fetch.ts
14712
- import { existsSync as existsSync16, readFileSync as readFileSync5 } from "fs";
14713
- import { mkdir as mkdir7, readFile as readFile13, rename as rename5, rm as rm5, writeFile as writeFile7 } from "fs/promises";
14714
- import path20 from "path";
15102
+ import { existsSync as existsSync18, readFileSync as readFileSync5 } from "fs";
15103
+ import { mkdir as mkdir8, readFile as readFile14, rename as rename6, rm as rm5, writeFile as writeFile8 } from "fs/promises";
15104
+ import path22 from "path";
14715
15105
  async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14716
15106
  const log = opts.onProgress ?? (() => {
14717
15107
  });
14718
15108
  const result = { downloaded: 0, skipped: 0, failed: 0, ...opts.refresh ? { unchanged: 0 } : {} };
14719
15109
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
14720
15110
  normalizeLockOutputPaths(lock, specs);
14721
- const cacheDir = opts.cacheDir === false ? null : path20.resolve(opts.cacheDir ?? path20.join(path20.dirname(lockPath), ".pixelkiln", "cache"));
14722
- const pending = Object.entries(lock.entries).filter(([key, e]) => {
14723
- if (e.provider !== provider.id || !specByKey.has(key)) return false;
14724
- if (specByKey.get(key)?.mirror) return false;
15111
+ const cacheDir = opts.cacheDir === false ? null : path22.resolve(opts.cacheDir ?? path22.join(path22.dirname(lockPath), ".pixelkiln", "cache"));
15112
+ const pending = Object.entries(lock.entries).filter(([key2, e]) => {
15113
+ if (e.provider !== provider.id || !specByKey.has(key2)) return false;
15114
+ if (specByKey.get(key2)?.mirror) return false;
15115
+ if (specByKey.get(key2)?.derive || specByKey.get(key2)?.external) return false;
14725
15116
  if (e.status === "selected" || e.status === "download-failed") return true;
14726
15117
  if (e.status !== "downloaded") return false;
14727
15118
  if (opts.refresh) return e.outputs.length > 0 && Boolean(e.sourceUrls?.length || e.sourceUrl);
14728
- const spec = specByKey.get(key);
15119
+ const spec = specByKey.get(key2);
14729
15120
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
14730
15121
  return Boolean(opts.force) || e.outputs.every((output) => {
14731
15122
  const file = resolveOutputPath(output.path, spec.root);
14732
- return existsSync16(file) && sha256(readFileSync5(file)) === output.sha256;
15123
+ return existsSync18(file) && sha256(readFileSync5(file)) === output.sha256;
14733
15124
  });
14734
15125
  }
14735
15126
  if (!opts.repair) return false;
14736
15127
  if (e.outputs.length === 0 || !spec) return true;
14737
15128
  return e.outputs.some((output) => {
14738
15129
  const file = resolveOutputPath(output.path, spec.root);
14739
- if (!existsSync16(file)) return true;
15130
+ if (!existsSync18(file)) return true;
14740
15131
  const current = sha256(readFileSync5(file));
14741
15132
  if (current === output.sha256) return false;
14742
15133
  return Boolean(opts.force) || (e.supersededOutputs ?? []).some((old) => old.sha256 === current);
@@ -14748,15 +15139,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14748
15139
  for (; ; ) {
14749
15140
  const next = pending[cursor++];
14750
15141
  if (!next) return;
14751
- const [key, entry] = next;
14752
- const spec = specByKey.get(key);
15142
+ const [key2, entry] = next;
15143
+ const spec = specByKey.get(key2);
14753
15144
  if (!spec) {
14754
- log(` skip ${key} (not in current manifest)`);
15145
+ log(` skip ${key2} (not in current manifest)`);
14755
15146
  result.skipped++;
14756
15147
  continue;
14757
15148
  }
14758
15149
  if (entry.specHash !== spec.specHash) {
14759
- log(` skip ${key} (source belongs to a stale spec)`);
15150
+ log(` skip ${key2} (source belongs to a stale spec)`);
14760
15151
  result.skipped++;
14761
15152
  continue;
14762
15153
  }
@@ -14773,16 +15164,16 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14773
15164
  });
14774
15165
  } catch (err) {
14775
15166
  const message6 = err instanceof Error ? err.message : String(err);
14776
- upsert(lock, key, { status: "download-failed", error: `download failed: ${message6}` });
15167
+ upsert(lock, key2, { status: "download-failed", error: `download failed: ${message6}` });
14777
15168
  result.failed++;
14778
- log(` FAILED ${key}: ${message6}`);
15169
+ log(` FAILED ${key2}: ${message6}`);
14779
15170
  await saveLock(lockPath, lock);
14780
15171
  continue;
14781
15172
  }
14782
15173
  if (current === null) {
14783
- upsert(lock, key, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
15174
+ upsert(lock, key2, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
14784
15175
  result.failed++;
14785
- log(` FAILED ${key}: ${entry.objectId} no longer exists upstream`);
15176
+ log(` FAILED ${key2}: ${entry.objectId} no longer exists upstream`);
14786
15177
  await saveLock(lockPath, lock);
14787
15178
  continue;
14788
15179
  }
@@ -14795,7 +15186,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14795
15186
  }
14796
15187
  }
14797
15188
  if (!sources.length) {
14798
- upsert(lock, key, {
15189
+ upsert(lock, key2, {
14799
15190
  status: "download-failed",
14800
15191
  error: "no persisted source URL to download; poll the job again if it still exists upstream"
14801
15192
  });
@@ -14820,21 +15211,21 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14820
15211
  if (!source.url) throw new Error(`no durable source URL to refresh ${source.role ?? "asset"} from`);
14821
15212
  fresh = await provider.download(source.url);
14822
15213
  if (recorded && sha256(fresh) === recordedRaw && !reapply) {
14823
- log(` current ${path20.relative(process.cwd(), target)}`);
15214
+ log(` current ${path22.relative(process.cwd(), target)}`);
14824
15215
  outputs.push({ ...recorded, path: portableOutputPath(target, spec.root) });
14825
15216
  continue;
14826
15217
  }
14827
15218
  }
14828
15219
  let raw = null;
14829
15220
  let final = null;
14830
- if (existsSync16(target)) {
15221
+ if (existsSync18(target)) {
14831
15222
  const currentHash = await sha256File(target);
14832
15223
  if (recorded && currentHash === recorded.sha256) {
14833
15224
  if (!fresh && !reapply) {
14834
15225
  if (cacheDir) {
14835
15226
  await cacheMedia(
14836
15227
  cacheDir,
14837
- await readFile13(target),
15228
+ await readFile14(target),
14838
15229
  recorded.mediaType ?? MediaType.PNG,
14839
15230
  recorded.sha256
14840
15231
  );
@@ -14843,10 +15234,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14843
15234
  continue;
14844
15235
  }
14845
15236
  if (reapply && !fresh) {
14846
- if (!recorded.raw) raw = await readFile13(target);
14847
- log(` reapply ${path20.relative(process.cwd(), target)}`);
15237
+ if (!recorded.raw) raw = await readFile14(target);
15238
+ log(` reapply ${path22.relative(process.cwd(), target)}`);
14848
15239
  } else {
14849
- log(` changed ${path20.relative(process.cwd(), target)} (upstream)`);
15240
+ log(` changed ${path22.relative(process.cwd(), target)} (upstream)`);
14850
15241
  }
14851
15242
  } else {
14852
15243
  const superseded = (entry.supersededOutputs ?? []).find(
@@ -14867,14 +15258,14 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14867
15258
  }
14868
15259
  if (outgoing && cacheDir) {
14869
15260
  try {
14870
- const oldBytes = await readFile13(target);
15261
+ const oldBytes = await readFile14(target);
14871
15262
  const oldMediaType = detectMediaType(oldBytes);
14872
15263
  if (oldMediaType) await cacheMedia(cacheDir, oldBytes, oldMediaType, currentHash);
14873
15264
  } catch {
14874
15265
  }
14875
15266
  }
14876
15267
  log(
14877
- ` replace ${path20.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
15268
+ ` replace ${path22.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
14878
15269
  );
14879
15270
  }
14880
15271
  }
@@ -14883,7 +15274,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14883
15274
  } else if (!raw && recorded && cacheDir) {
14884
15275
  if (!reapply) final = await readCachedMedia(cacheDir, recorded.sha256, expectedMediaType);
14885
15276
  if (!final && recordedRaw) raw = await readCachedMedia(cacheDir, recordedRaw, expectedMediaType);
14886
- if (final || raw) log(` cached ${path20.relative(process.cwd(), target)}`);
15277
+ if (final || raw) log(` cached ${path22.relative(process.cwd(), target)}`);
14887
15278
  }
14888
15279
  if (!final && !raw) {
14889
15280
  if (!source.url) {
@@ -14910,13 +15301,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14910
15301
  buf = processed.bytes;
14911
15302
  if (processed.changed) {
14912
15303
  rawHash = sha256(raw);
14913
- log(` snapped ${path20.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
15304
+ log(` snapped ${path22.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
14914
15305
  }
14915
15306
  }
14916
15307
  if (cacheDir) await cacheMedia(cacheDir, buf, mediaType);
14917
- await mkdir7(path20.dirname(target), { recursive: true });
15308
+ await mkdir8(path22.dirname(target), { recursive: true });
14918
15309
  const tmp = `${target}.pixelkiln.tmp`;
14919
- await writeFile7(tmp, buf);
15310
+ await writeFile8(tmp, buf);
14920
15311
  outputs.push({
14921
15312
  path: portableOutputPath(target, spec.root),
14922
15313
  sha256: sha256(buf),
@@ -14924,22 +15315,22 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14924
15315
  mediaType,
14925
15316
  ...rawHash ? { raw: rawHash } : {}
14926
15317
  });
14927
- upsert(lock, key, { outputs: mergeOutputs(entry.outputs, outputs) });
15318
+ upsert(lock, key2, { outputs: mergeOutputs(entry.outputs, outputs) });
14928
15319
  await saveLock(lockPath, lock);
14929
- await rename5(tmp, target);
15320
+ await rename6(tmp, target);
14930
15321
  wrote = true;
14931
- log(` wrote ${path20.relative(process.cwd(), target)}`);
15322
+ log(` wrote ${path22.relative(process.cwd(), target)}`);
14932
15323
  }
14933
15324
  if (opts.refresh && !wrote) {
14934
15325
  if (rotated) {
14935
15326
  const persistent = sources.filter((source) => shouldPersistSourceUrl(source.url));
14936
- upsert(lock, key, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
15327
+ upsert(lock, key2, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
14937
15328
  }
14938
15329
  result.unchanged = (result.unchanged ?? 0) + 1;
14939
15330
  continue;
14940
15331
  }
14941
15332
  const persistentSources = sources.filter((source) => shouldPersistSourceUrl(source.url));
14942
- upsert(lock, key, {
15333
+ upsert(lock, key2, {
14943
15334
  status: "downloaded",
14944
15335
  provider: provider.id,
14945
15336
  outputs,
@@ -14956,13 +15347,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14956
15347
  result.downloaded++;
14957
15348
  } catch (err) {
14958
15349
  const message6 = err instanceof Error ? err.message : String(err);
14959
- upsert(lock, key, {
15350
+ upsert(lock, key2, {
14960
15351
  status: "download-failed",
14961
15352
  outputs: mergeOutputs(entry.outputs, outputs),
14962
15353
  error: `download failed: ${message6}`
14963
15354
  });
14964
15355
  result.failed++;
14965
- log(` FAILED ${key}: ${message6}`);
15356
+ log(` FAILED ${key2}: ${message6}`);
14966
15357
  }
14967
15358
  await saveLock(lockPath, lock);
14968
15359
  }
@@ -14972,10 +15363,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
14972
15363
  return result;
14973
15364
  }
14974
15365
  async function readCachedMedia(cacheDir, hash, mediaType) {
14975
- const file = path20.join(cacheDir, cacheFileName(hash, mediaType));
14976
- if (!existsSync16(file)) return null;
15366
+ const file = path22.join(cacheDir, cacheFileName(hash, mediaType));
15367
+ if (!existsSync18(file)) return null;
14977
15368
  try {
14978
- const buf = await readFile13(file);
15369
+ const buf = await readFile14(file);
14979
15370
  if (sha256(buf) !== hash) return null;
14980
15371
  validateMedia(buf, mediaType);
14981
15372
  return buf;
@@ -14986,15 +15377,15 @@ async function readCachedMedia(cacheDir, hash, mediaType) {
14986
15377
  async function cacheMedia(cacheDir, buf, mediaType, knownHash) {
14987
15378
  const hash = knownHash ?? sha256(buf);
14988
15379
  validateMedia(buf, mediaType);
14989
- const file = path20.join(cacheDir, cacheFileName(hash, mediaType));
15380
+ const file = path22.join(cacheDir, cacheFileName(hash, mediaType));
14990
15381
  if (await readCachedMedia(cacheDir, hash, mediaType)) return;
14991
- await mkdir7(cacheDir, { recursive: true });
15382
+ await mkdir8(cacheDir, { recursive: true });
14992
15383
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
14993
- await writeFile7(tmp, buf);
15384
+ await writeFile8(tmp, buf);
14994
15385
  try {
14995
- await rename5(tmp, file);
15386
+ await rename6(tmp, file);
14996
15387
  } catch (err) {
14997
- if (!existsSync16(file)) throw err;
15388
+ if (!existsSync18(file)) throw err;
14998
15389
  } finally {
14999
15390
  await rm5(tmp, { force: true });
15000
15391
  }
@@ -15011,8 +15402,8 @@ async function pushTags(provider, specs, lock, opts = {}) {
15011
15402
  });
15012
15403
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
15013
15404
  let tagged = 0;
15014
- for (const [key, entry] of Object.entries(lock.entries)) {
15015
- const spec = specByKey.get(key);
15405
+ for (const [key2, entry] of Object.entries(lock.entries)) {
15406
+ const spec = specByKey.get(key2);
15016
15407
  if (!spec || entry.provider !== provider.id || !entry.objectId) continue;
15017
15408
  if (entry.generator === "pixflux" || entry.generator === "vfx") continue;
15018
15409
  if (!provider.setTags) return tagged;
@@ -15020,7 +15411,7 @@ async function pushTags(provider, specs, lock, opts = {}) {
15020
15411
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
15021
15412
  tagged++;
15022
15413
  } catch (err) {
15023
- log(` tag failed ${key}: ${err instanceof Error ? err.message : String(err)}`);
15414
+ log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
15024
15415
  }
15025
15416
  }
15026
15417
  return tagged;
@@ -15063,6 +15454,8 @@ function retireGeneration(entry, retiredAt) {
15063
15454
  ...entry.terrainConnect ? { terrainConnect: entry.terrainConnect } : {},
15064
15455
  ...entry.motionShare ? { motionShare: entry.motionShare } : {},
15065
15456
  ...entry.terrainSettings ? { terrainSettings: entry.terrainSettings } : {},
15457
+ ...entry.imported ? { imported: entry.imported } : {},
15458
+ ...entry.origin ? { origin: entry.origin } : {},
15066
15459
  retiredAt
15067
15460
  };
15068
15461
  }
@@ -15104,22 +15497,22 @@ function pickHistory(entry, selector) {
15104
15497
  return matches[0];
15105
15498
  }
15106
15499
  async function revertGeneration(provider, spec, lock, lockPath, opts) {
15107
- const key = lockKey(spec.styleId, spec.assetId);
15108
- const entry = lock.entries[key];
15109
- if (!entry) throw new Error(`${key} is not in the lockfile`);
15500
+ const key2 = lockKey(spec.styleId, spec.assetId);
15501
+ const entry = lock.entries[key2];
15502
+ if (!entry) throw new Error(`${key2} is not in the lockfile`);
15110
15503
  if (entry.status !== "downloaded") {
15111
- throw new Error(`${key} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
15504
+ throw new Error(`${key2} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
15112
15505
  }
15113
15506
  const { index, generation } = pickHistory(entry, opts.generation);
15114
15507
  if (generation.provider !== provider.id) {
15115
- throw new Error(`${key}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
15508
+ throw new Error(`${key2}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
15116
15509
  }
15117
15510
  for (let i = 0; i < entry.outputs.length; i++) {
15118
15511
  const file = currentEntryOutputPath(entry, spec, i);
15119
- if (!existsSync17(file)) continue;
15512
+ if (!existsSync19(file)) continue;
15120
15513
  if (await sha256File(file) !== entry.outputs[i].sha256 && !opts.force) {
15121
15514
  throw new OverwriteRefusedError(
15122
- `${path21.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
15515
+ `${path23.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
15123
15516
  [file]
15124
15517
  );
15125
15518
  }
@@ -15127,7 +15520,7 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15127
15520
  const now = (/* @__PURE__ */ new Date()).toISOString();
15128
15521
  const remaining = (entry.history ?? []).filter((_, i) => i !== index - 1);
15129
15522
  const history = [retireGeneration(entry, now), ...remaining];
15130
- upsert(lock, key, {
15523
+ upsert(lock, key2, {
15131
15524
  specHash: generation.specHash,
15132
15525
  generator: generation.generator,
15133
15526
  tileFeature: generation.tileFeature,
@@ -15162,6 +15555,10 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15162
15555
  // Likewise its settings; a generation from before they were recorded
15163
15556
  // comes back with none and is taken as current.
15164
15557
  terrainSettings: generation.terrainSettings,
15558
+ // Imported art comes back as imported, with its provenance; a generated
15559
+ // one clears both, so the plan does not call it imported.
15560
+ imported: generation.imported,
15561
+ origin: generation.origin,
15165
15562
  history
15166
15563
  });
15167
15564
  await saveLock(lockPath, lock);
@@ -15179,11 +15576,11 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15179
15576
 
15180
15577
  // src/pipeline/cache-health.ts
15181
15578
  async function inspectCaches(lock, lockPath, options = {}) {
15182
- if (options.prune && !existsSync18(lockPath)) {
15183
- throw new Error(`Refusing to prune without an existing lockfile at ${path22.resolve(lockPath)}`);
15579
+ if (options.prune && !existsSync20(lockPath)) {
15580
+ throw new Error(`Refusing to prune without an existing lockfile at ${path24.resolve(lockPath)}`);
15184
15581
  }
15185
- const contentDir = path22.resolve(path22.dirname(lockPath), ".pixelkiln", "cache");
15186
- const remotePath = path22.resolve(cachePathFor(lockPath));
15582
+ const contentDir = path24.resolve(path24.dirname(lockPath), ".pixelkiln", "cache");
15583
+ const remotePath = path24.resolve(cachePathFor(lockPath));
15187
15584
  const referenced = referencedHashes(lock);
15188
15585
  let content = await inspectContentCache(contentDir, referenced);
15189
15586
  let remoteHashes = await inspectRemoteHashCache(remotePath);
@@ -15195,7 +15592,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15195
15592
  ]);
15196
15593
  for (const name of names) {
15197
15594
  try {
15198
- await rm6(path22.join(contentDir, name), { force: true });
15595
+ await rm6(path24.join(contentDir, name), { force: true });
15199
15596
  removed.contentFiles++;
15200
15597
  } catch {
15201
15598
  }
@@ -15204,7 +15601,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15204
15601
  await saveCache(remotePath, { version: 1, hashes: {} });
15205
15602
  removed.resetRemoteHashCache = true;
15206
15603
  } else if (remoteHashes.invalidIds.length) {
15207
- const cache = parseCache(JSON.parse(await readFile14(remotePath, "utf8")));
15604
+ const cache = parseCache(JSON.parse(await readFile15(remotePath, "utf8")));
15208
15605
  for (const id of remoteHashes.invalidIds) delete cache.hashes[id];
15209
15606
  removed.remoteHashEntries = remoteHashes.invalidIds.length;
15210
15607
  await saveCache(remotePath, cache);
@@ -15222,7 +15619,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15222
15619
  async function inspectContentCache(contentDir, referenced) {
15223
15620
  const report = {
15224
15621
  path: contentDir,
15225
- exists: existsSync18(contentDir),
15622
+ exists: existsSync20(contentDir),
15226
15623
  files: 0,
15227
15624
  bytes: 0,
15228
15625
  valid: 0,
@@ -15243,12 +15640,12 @@ async function inspectContentCache(contentDir, referenced) {
15243
15640
  continue;
15244
15641
  }
15245
15642
  report.files++;
15246
- const file = path22.join(contentDir, entry.name);
15643
+ const file = path24.join(contentDir, entry.name);
15247
15644
  const mediaType = mediaTypeFromExtension(entry.name);
15248
15645
  const expected = mediaType ? entry.name.slice(0, -4) : "";
15249
15646
  let bytes;
15250
15647
  try {
15251
- bytes = await readFile14(file);
15648
+ bytes = await readFile15(file);
15252
15649
  report.bytes += bytes.length;
15253
15650
  } catch (err) {
15254
15651
  report.invalid.push({
@@ -15286,7 +15683,7 @@ async function inspectContentCache(contentDir, referenced) {
15286
15683
  async function inspectRemoteHashCache(remotePath) {
15287
15684
  const report = {
15288
15685
  path: remotePath,
15289
- exists: existsSync18(remotePath),
15686
+ exists: existsSync20(remotePath),
15290
15687
  entries: 0,
15291
15688
  valid: 0,
15292
15689
  invalidIds: [],
@@ -15295,7 +15692,7 @@ async function inspectRemoteHashCache(remotePath) {
15295
15692
  if (!report.exists) return report;
15296
15693
  let cache;
15297
15694
  try {
15298
- cache = parseCache(JSON.parse(await readFile14(remotePath, "utf8")));
15695
+ cache = parseCache(JSON.parse(await readFile15(remotePath, "utf8")));
15299
15696
  } catch (err) {
15300
15697
  report.error = err instanceof Error ? err.message : String(err);
15301
15698
  return report;
@@ -15311,19 +15708,19 @@ async function inspectRemoteHashCache(remotePath) {
15311
15708
 
15312
15709
  // src/pipeline/pack.ts
15313
15710
  import { readFileSync as readFileSync6 } from "fs";
15314
- import path23 from "path";
15711
+ import path25 from "path";
15315
15712
  var DEFAULT_FRAME_SET_FPS = 12;
15316
15713
  function resolvePackInputs(raw, inputsFilePath) {
15317
15714
  if (!Array.isArray(raw) || !raw.length) {
15318
15715
  throw new Error("--inputs must be a non-empty JSON array of { id, path }");
15319
15716
  }
15320
- const baseDir = path23.dirname(path23.resolve(inputsFilePath));
15717
+ const baseDir = path25.dirname(path25.resolve(inputsFilePath));
15321
15718
  return raw.map((entry, i) => {
15322
15719
  const e = entry;
15323
15720
  if (typeof e.id !== "string" || typeof e.path !== "string") {
15324
15721
  throw new Error(`--inputs[${i}] needs string "id" and "path"`);
15325
15722
  }
15326
- return { id: e.id, path: path23.resolve(baseDir, e.path) };
15723
+ return { id: e.id, path: path25.resolve(baseDir, e.path) };
15327
15724
  });
15328
15725
  }
15329
15726
  function packSprites(inputs, options = {}) {
@@ -15407,14 +15804,14 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15407
15804
  }
15408
15805
  const inputs2 = Object.entries(options.sourceOverrides).map(([id, source]) => ({
15409
15806
  id,
15410
- path: path23.resolve(source)
15807
+ path: path25.resolve(source)
15411
15808
  }));
15412
15809
  if (!inputs2.length) throw new Error(`No approved quality outputs for style "${styleId}".`);
15413
15810
  const packed2 = packSprites(inputs2, options);
15414
15811
  return { ...packed2, atlas: { ...packed2.atlas, style: styleId } };
15415
15812
  }
15416
15813
  const prefix = `${styleId}/`;
15417
- const entries = Object.entries(lock.entries).filter(([key]) => key.startsWith(prefix));
15814
+ const entries = Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix));
15418
15815
  const sources = options.sources ?? {};
15419
15816
  if (!entries.length && !Object.keys(sources).length) {
15420
15817
  throw new Error(
@@ -15425,13 +15822,13 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15425
15822
  const noOutput = [];
15426
15823
  const locked = /* @__PURE__ */ new Set();
15427
15824
  const sets = [];
15428
- for (const [key, entry] of entries) {
15429
- const id = key.slice(prefix.length);
15825
+ for (const [key2, entry] of entries) {
15826
+ const id = key2.slice(prefix.length);
15430
15827
  locked.add(id);
15431
15828
  let outputs = resolveEntryOutputs(entry, id, manifestDir);
15432
15829
  const source = sources[id];
15433
15830
  if (source && outputs.length <= 1) {
15434
- inputs.push({ id, path: path23.resolve(manifestDir, source) });
15831
+ inputs.push({ id, path: path25.resolve(manifestDir, source) });
15435
15832
  continue;
15436
15833
  }
15437
15834
  if (source && sourceIsStem(source, entry, manifestDir)) {
@@ -15466,7 +15863,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
15466
15863
  }
15467
15864
  }
15468
15865
  for (const [id, source] of Object.entries(sources)) {
15469
- if (!locked.has(id)) inputs.push({ id, path: path23.resolve(manifestDir, source) });
15866
+ if (!locked.has(id)) inputs.push({ id, path: path25.resolve(manifestDir, source) });
15470
15867
  }
15471
15868
  if (!inputs.length) {
15472
15869
  throw new Error(`No readable sprites for style "${styleId}"; ${noOutput.length} skipped.`);
@@ -15488,14 +15885,14 @@ function mountSprites(placements, options) {
15488
15885
  }
15489
15886
  const byCell = /* @__PURE__ */ new Map();
15490
15887
  for (const p of placements) {
15491
- const key = `${p.cell[0]},${p.cell[1]}`;
15492
- const owner = byCell.get(key);
15888
+ const key2 = `${p.cell[0]},${p.cell[1]}`;
15889
+ const owner = byCell.get(key2);
15493
15890
  if (owner) {
15494
15891
  throw new Error(
15495
- `mountSprites: "${p.id}" and "${owner}" both claim cell ${key}; a cell has exactly one owner`
15892
+ `mountSprites: "${p.id}" and "${owner}" both claim cell ${key2}; a cell has exactly one owner`
15496
15893
  );
15497
15894
  }
15498
- byCell.set(key, p.id);
15895
+ byCell.set(key2, p.id);
15499
15896
  }
15500
15897
  const loaded = [];
15501
15898
  const skipped = [];
@@ -15574,7 +15971,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15574
15971
  const source = sources[id];
15575
15972
  const entry = lock.entries[`${styleId}/${id}`];
15576
15973
  if (source && !(entry && sourceIsStem(source, entry, manifestDir))) {
15577
- placements.push({ id, path: path23.resolve(manifestDir, source), cell });
15974
+ placements.push({ id, path: path25.resolve(manifestDir, source), cell });
15578
15975
  continue;
15579
15976
  }
15580
15977
  if (source && entry) {
@@ -15607,7 +16004,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15607
16004
  `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}`
15608
16005
  );
15609
16006
  }
15610
- const basePng = mount.base ? readFileSync6(path23.resolve(manifestDir, mount.base)) : void 0;
16007
+ const basePng = mount.base ? readFileSync6(path25.resolve(manifestDir, mount.base)) : void 0;
15611
16008
  const mounted = mountSprites(placements, {
15612
16009
  cellWidth: mount.cellWidth,
15613
16010
  cellHeight: mount.cellHeight,
@@ -15617,7 +16014,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
15617
16014
  ...mounted,
15618
16015
  sources: mount.base ? [{
15619
16016
  id: "$base",
15620
- path: path23.resolve(manifestDir, mount.base),
16017
+ path: path25.resolve(manifestDir, mount.base),
15621
16018
  sha256: sha256(basePng),
15622
16019
  included: true
15623
16020
  }, ...mounted.sources] : mounted.sources,
@@ -15635,8 +16032,8 @@ function normalizeTileRules(raw) {
15635
16032
  if (arity !== 4 && arity !== 6) return null;
15636
16033
  const masks = {};
15637
16034
  if (isRecord2(raw.tiles)) {
15638
- for (const [key, value] of Object.entries(raw.tiles)) {
15639
- const index = tileIndex(key);
16035
+ for (const [key2, value] of Object.entries(raw.tiles)) {
16036
+ const index = tileIndex(key2);
15640
16037
  const mask = typeof value === "number" ? value : isRecord2(value) && typeof value.bitmask === "number" ? value.bitmask : isRecord2(value) && typeof value.mask === "number" ? value.mask : null;
15641
16038
  if (index !== null && mask !== null && Number.isInteger(mask) && mask >= 0) masks[index] = mask;
15642
16039
  }
@@ -15911,8 +16308,8 @@ function assertUniformTiles(generic) {
15911
16308
  );
15912
16309
  }
15913
16310
  }
15914
- function tileIndex(key) {
15915
- const match = key.match(/(?:^|[_-])(\d+)$/);
16311
+ function tileIndex(key2) {
16312
+ const match = key2.match(/(?:^|[_-])(\d+)$/);
15916
16313
  return match ? Number(match[1]) : null;
15917
16314
  }
15918
16315
  function isRecord2(value) {
@@ -16027,9 +16424,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16027
16424
  });
16028
16425
  const estimates = new Map(items.map((item) => [
16029
16426
  item.key,
16030
- item.spec.mirror ? { amount: 0, unit: item.spec.costUnit, candidates: 1 } : validateCostEstimate(provider.id, provider.estimate(item.spec))
16427
+ item.spec.mirror || item.spec.derive ? { amount: 0, unit: item.spec.costUnit, candidates: 1 } : validateCostEstimate(provider.id, provider.estimate(item.spec))
16031
16428
  ]));
16032
- const units = new Set([...estimates.values()].map((estimate) => estimate.unit));
16429
+ const units = new Set(items.filter((item) => !item.spec.derive).map((item) => estimates.get(item.key).unit));
16033
16430
  if (units.size > 1) {
16034
16431
  throw new Error(`Provider "${provider.id}" returned mixed cost units for one submission batch`);
16035
16432
  }
@@ -16127,20 +16524,21 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16127
16524
  }
16128
16525
  }
16129
16526
  }
16130
- for (const { spec, key } of items) {
16131
- const estimate = estimates.get(key);
16527
+ for (const { spec, key: key2 } of items) {
16528
+ const estimate = estimates.get(key2);
16132
16529
  if (spec.batch?.role === "member") {
16133
16530
  continue;
16134
16531
  }
16135
- if (spec.mirror) {
16532
+ if (spec.mirror || spec.derive) {
16136
16533
  try {
16137
16534
  await requireRevisionReady(spec, lock);
16138
- await deriveMirror(spec, lock, lockPath, { onProgress: log });
16535
+ if (spec.derive) await deriveAsset(spec, lock, lockPath, { onProgress: log });
16536
+ else await deriveMirror(spec, lock, lockPath, { onProgress: log });
16139
16537
  submitted++;
16140
16538
  } catch (err) {
16141
16539
  const message6 = err instanceof Error ? err.message : String(err);
16142
16540
  failed++;
16143
- upsert(lock, key, {
16541
+ upsert(lock, key2, {
16144
16542
  styleId: spec.styleId,
16145
16543
  assetId: spec.assetId,
16146
16544
  specHash: spec.specHash,
@@ -16150,13 +16548,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16150
16548
  height: spec.height,
16151
16549
  status: "failed",
16152
16550
  error: message6,
16153
- outputs: lock.entries[key]?.outputs ?? [],
16551
+ outputs: lock.entries[key2]?.outputs ?? [],
16154
16552
  cost: 0,
16155
16553
  costUnit: spec.costUnit,
16156
16554
  provider: provider.id
16157
16555
  });
16158
16556
  await saveLock(lockPath, lock);
16159
- log(` FAILED ${key}: ${message6}`);
16557
+ log(` FAILED ${key2}: ${message6}`);
16160
16558
  }
16161
16559
  continue;
16162
16560
  }
@@ -16168,11 +16566,11 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16168
16566
  const missing = (spec.batch.memberAssetIds ?? []).filter((id) => !byKey.has(lockKey(spec.styleId, id)));
16169
16567
  if (missing.length) {
16170
16568
  throw new Error(
16171
- `${key}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
16569
+ `${key2}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
16172
16570
  );
16173
16571
  }
16174
16572
  }
16175
- const previousEntry = lock.entries[key];
16573
+ const previousEntry = lock.entries[key2];
16176
16574
  const resumesCheckpoint = Boolean(
16177
16575
  previousEntry?.specHash === spec.specHash && previousEntry.provider === provider.id && previousEntry.generator === spec.generator && previousEntry.submissionComplete === false && previousEntry.jobId
16178
16576
  );
@@ -16202,9 +16600,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16202
16600
  const leaderGroup = motionLeader ? recordedAnimationGroup(lock.entries[lockKey(motionLeader.spec.styleId, motionLeader.spec.assetId)]) : void 0;
16203
16601
  const motionGroup = leaderGroup?.animationGroupId && leaderGroup.animationName ? { animationGroupId: leaderGroup.animationGroupId, animationName: leaderGroup.animationName } : void 0;
16204
16602
  if (motionLeader && !motionGroup) {
16205
- log(` ${key}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
16603
+ log(` ${key2}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
16206
16604
  }
16207
- upsert(lock, key, {
16605
+ upsert(lock, key2, {
16208
16606
  styleId: spec.styleId,
16209
16607
  assetId: spec.assetId,
16210
16608
  specHash: spec.specHash,
@@ -16302,8 +16700,8 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16302
16700
  ...previousMetadata ? { previousMetadata } : {},
16303
16701
  checkpoint: async (checkpoint) => {
16304
16702
  if (!checkpoint.jobId) throw new Error("Provider checkpoint returned an empty job id");
16305
- const entry = lock.entries[key];
16306
- upsert(lock, key, {
16703
+ const entry = lock.entries[key2];
16704
+ upsert(lock, key2, {
16307
16705
  jobId: checkpoint.jobId,
16308
16706
  submissionComplete: checkpoint.complete,
16309
16707
  reviewObjectId: checkpoint.complete && (spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature) ? checkpoint.jobId : null,
@@ -16320,41 +16718,41 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
16320
16718
  await saveLock(lockPath, lock);
16321
16719
  }
16322
16720
  });
16323
- upsert(lock, key, {
16721
+ upsert(lock, key2, {
16324
16722
  jobId,
16325
16723
  submissionComplete: true,
16326
16724
  // A multi-candidate generator routes through review; record the parent
16327
16725
  // so `pick` knows where to look.
16328
16726
  reviewObjectId: spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature ? jobId : null,
16329
16727
  status: "processing",
16330
- providerMetadata: metadata ? { ...lock.entries[key].providerMetadata, [provider.id]: metadata } : lock.entries[key].providerMetadata
16728
+ providerMetadata: metadata ? { ...lock.entries[key2].providerMetadata, [provider.id]: metadata } : lock.entries[key2].providerMetadata
16331
16729
  });
16332
16730
  inFlight.set(jobId, spec);
16333
16731
  submitted++;
16334
16732
  spent += estimate.amount;
16335
- writeBatchMembers(spec, key, null);
16733
+ writeBatchMembers(spec, key2, null);
16336
16734
  log(
16337
- ` ${key} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
16735
+ ` ${key2} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
16338
16736
  );
16339
16737
  } catch (err) {
16340
16738
  const message6 = err instanceof Error ? err.message : String(err);
16341
- const entry = lock.entries[key];
16739
+ const entry = lock.entries[key2];
16342
16740
  if (entry.jobId && entry.submissionComplete === true) {
16343
- upsert(lock, key, { status: "processing", error: null });
16741
+ upsert(lock, key2, { status: "processing", error: null });
16344
16742
  inFlight.set(entry.jobId, spec);
16345
16743
  submitted++;
16346
16744
  spent += estimate.amount;
16347
- writeBatchMembers(spec, key, null);
16348
- log(` ${key} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
16745
+ writeBatchMembers(spec, key2, null);
16746
+ log(` ${key2} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
16349
16747
  } else {
16350
16748
  failed++;
16351
- upsert(lock, key, {
16749
+ upsert(lock, key2, {
16352
16750
  status: "failed",
16353
16751
  error: message6,
16354
16752
  cost: entry.jobId ? estimate.amount : 0
16355
16753
  });
16356
- writeBatchMembers(spec, key, message6);
16357
- log(` FAILED ${key}: ${message6}`);
16754
+ writeBatchMembers(spec, key2, message6);
16755
+ log(` FAILED ${key2}: ${message6}`);
16358
16756
  }
16359
16757
  }
16360
16758
  await saveLock(lockPath, lock);
@@ -16385,14 +16783,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
16385
16783
  const selectedKeys = opts.specs ? new Set(specByKey.keys()) : null;
16386
16784
  const result = { review: 0, completed: 0, failed: 0, stillRunning: 0 };
16387
16785
  const incompleteSubmissions = Object.entries(lock.entries).filter(
16388
- ([key, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
16786
+ ([key2, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
16389
16787
  );
16390
- for (const [key] of incompleteSubmissions) {
16391
- log(` incomplete submission ${key}; rerun \`pixelkiln submit\` to resume`);
16788
+ for (const [key2] of incompleteSubmissions) {
16789
+ log(` incomplete submission ${key2}; rerun \`pixelkiln submit\` to resume`);
16392
16790
  }
16393
16791
  result.stillRunning = incompleteSubmissions.length;
16394
16792
  const pending = () => Object.entries(lock.entries).filter(
16395
- ([key, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
16793
+ ([key2, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
16396
16794
  );
16397
16795
  while (pending().length > 0) {
16398
16796
  if (Date.now() - started > timeout) {
@@ -16400,16 +16798,16 @@ async function poll(provider, lock, lockPath, opts = {}) {
16400
16798
  log(` timed out with ${result.stillRunning} job(s) still running; re-run \`poll\` to resume`);
16401
16799
  break;
16402
16800
  }
16403
- for (const [key, entry] of pending()) {
16801
+ for (const [key2, entry] of pending()) {
16404
16802
  try {
16405
- const currentSpec = specByKey.get(key);
16803
+ const currentSpec = specByKey.get(key2);
16406
16804
  const state = await provider.poll(entry.jobId, entry.generator, {
16407
16805
  tileFeature: entry.tileFeature ?? currentSpec?.tileFeature,
16408
16806
  spec: currentSpec,
16409
16807
  metadata: entry.providerMetadata?.[provider.id]
16410
16808
  });
16411
16809
  if (state.status === "review" || state.status === "review-set") {
16412
- upsert(lock, key, {
16810
+ upsert(lock, key2, {
16413
16811
  status: "review",
16414
16812
  reviewObjectId: entry.jobId,
16415
16813
  providerMetadata: state.metadata ? {
@@ -16423,11 +16821,11 @@ async function poll(provider, lock, lockPath, opts = {}) {
16423
16821
  });
16424
16822
  result.review++;
16425
16823
  log(
16426
- state.status === "review-set" ? ` review ${key} (${state.frameUrls.length} ordered frames)` : ` review ${key} (${state.candidateUrls.length} candidates)`
16824
+ state.status === "review-set" ? ` review ${key2} (${state.frameUrls.length} ordered frames)` : ` review ${key2} (${state.candidateUrls.length} candidates)`
16427
16825
  );
16428
16826
  } else if (state.status === "ready") {
16429
16827
  const sourceUrls = state.sources?.length ? state.sources : state.sourceUrl ? [{ url: state.sourceUrl }] : [];
16430
- upsert(lock, key, {
16828
+ upsert(lock, key2, {
16431
16829
  status: "selected",
16432
16830
  objectId: state.objectId,
16433
16831
  sourceUrl: sourceUrls[0]?.url ?? null,
@@ -16443,14 +16841,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
16443
16841
  billed: state.billed ?? entry.billed
16444
16842
  });
16445
16843
  result.completed++;
16446
- log(` ready ${key}`);
16844
+ log(` ready ${key2}`);
16447
16845
  } else if (state.status === "failed") {
16448
- upsert(lock, key, { status: "failed", error: state.error });
16846
+ upsert(lock, key2, { status: "failed", error: state.error });
16449
16847
  result.failed++;
16450
- log(` FAILED ${key}: ${state.error}`);
16848
+ log(` FAILED ${key2}: ${state.error}`);
16451
16849
  }
16452
16850
  } catch (err) {
16453
- log(` error polling ${key}: ${err instanceof Error ? err.message : String(err)}`);
16851
+ log(` error polling ${key2}: ${err instanceof Error ? err.message : String(err)}`);
16454
16852
  }
16455
16853
  }
16456
16854
  await saveLock(lockPath, lock);
@@ -16461,13 +16859,13 @@ async function poll(provider, lock, lockPath, opts = {}) {
16461
16859
  }
16462
16860
 
16463
16861
  // src/pipeline/doctor.ts
16464
- import { constants, existsSync as existsSync20 } from "fs";
16862
+ import { constants, existsSync as existsSync22 } from "fs";
16465
16863
  import { access, stat as stat2 } from "fs/promises";
16466
- import path25 from "path";
16864
+ import path27 from "path";
16467
16865
 
16468
16866
  // src/pipeline/install-check.ts
16469
- import { existsSync as existsSync19, readFileSync as readFileSync7 } from "fs";
16470
- import path24 from "path";
16867
+ import { existsSync as existsSync21, readFileSync as readFileSync7 } from "fs";
16868
+ import path26 from "path";
16471
16869
  function readJson(file) {
16472
16870
  try {
16473
16871
  return JSON.parse(readFileSync7(file, "utf8"));
@@ -16476,19 +16874,19 @@ function readJson(file) {
16476
16874
  }
16477
16875
  }
16478
16876
  function readInstallFacts(manifestDir, running) {
16479
- let dir = path24.resolve(manifestDir);
16877
+ let dir = path26.resolve(manifestDir);
16480
16878
  for (let depth = 0; depth < 4; depth++) {
16481
- const pkg = readJson(path24.join(dir, "package.json"));
16879
+ const pkg = readJson(path26.join(dir, "package.json"));
16482
16880
  if (pkg) {
16483
16881
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
16484
16882
  if (pinned) {
16485
- const installedPkg = readJson(path24.join(dir, "node_modules", "pixelkiln", "package.json"));
16883
+ const installedPkg = readJson(path26.join(dir, "node_modules", "pixelkiln", "package.json"));
16486
16884
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
16487
16885
  return { pinned, installed, running };
16488
16886
  }
16489
16887
  }
16490
- const parent = path24.dirname(dir);
16491
- if (parent === dir || !existsSync19(parent)) break;
16888
+ const parent = path26.dirname(dir);
16889
+ if (parent === dir || !existsSync21(parent)) break;
16492
16890
  dir = parent;
16493
16891
  }
16494
16892
  return null;
@@ -16551,12 +16949,12 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16551
16949
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
16552
16950
  );
16553
16951
  }
16554
- const facts = readInstallFacts(path25.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
16952
+ const facts = readInstallFacts(path27.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
16555
16953
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
16556
16954
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
16557
16955
  const dirs = [...new Set(specs.flatMap((spec) => [
16558
- path25.dirname(spec.outFile),
16559
- ...spec.quality ? [path25.dirname(spec.quality.outFile)] : []
16956
+ path27.dirname(spec.outFile),
16957
+ ...spec.quality ? [path27.dirname(spec.quality.outFile)] : []
16560
16958
  ]))];
16561
16959
  const unwritable = [];
16562
16960
  for (const dir of dirs) {
@@ -16575,14 +16973,14 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16575
16973
  const outputOwners = /* @__PURE__ */ new Map();
16576
16974
  const duplicateOutputs = [];
16577
16975
  const specByKey = new Map(specs.map((spec) => [`${spec.styleId}/${spec.assetId}`, spec]));
16578
- for (const [key, entry] of Object.entries(lock.entries)) {
16976
+ for (const [key2, entry] of Object.entries(lock.entries)) {
16579
16977
  for (let index = 0; index < entry.outputs.length; index++) {
16580
16978
  const output = entry.outputs[index];
16581
- const spec = specByKey.get(key);
16582
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path25.dirname(lockPath));
16979
+ const spec = specByKey.get(key2);
16980
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path27.dirname(lockPath));
16583
16981
  const owner = outputOwners.get(absolute);
16584
- if (owner && owner !== key) duplicateOutputs.push(`${output.path} (${owner}, ${key})`);
16585
- outputOwners.set(absolute, key);
16982
+ if (owner && owner !== key2) duplicateOutputs.push(`${output.path} (${owner}, ${key2})`);
16983
+ outputOwners.set(absolute, key2);
16586
16984
  }
16587
16985
  }
16588
16986
  if (duplicateOutputs.length) {
@@ -16594,34 +16992,34 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
16594
16992
  } else {
16595
16993
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
16596
16994
  }
16597
- const cacheDir = path25.join(path25.dirname(lockPath), ".pixelkiln", "cache");
16995
+ const cacheDir = path27.join(path27.dirname(lockPath), ".pixelkiln", "cache");
16598
16996
  const stranded = [];
16599
16997
  const invalidState = [];
16600
16998
  const staleMapUrls = [];
16601
16999
  const now = Date.now();
16602
- for (const [key, entry] of Object.entries(lock.entries)) {
17000
+ for (const [key2, entry] of Object.entries(lock.entries)) {
16603
17001
  if ((entry.status === "pending" || entry.status === "processing") && !entry.jobId) {
16604
- invalidState.push(`${key} (${entry.status} without job id)`);
17002
+ invalidState.push(`${key2} (${entry.status} without job id)`);
16605
17003
  }
16606
17004
  if (entry.status === "review" && !entry.reviewObjectId) {
16607
- invalidState.push(`${key} (review without review object id)`);
17005
+ invalidState.push(`${key2} (review without review object id)`);
16608
17006
  }
16609
17007
  if (entry.status !== "selected" && entry.status !== "download-failed") continue;
16610
17008
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
16611
17009
  let hasCache = false;
16612
17010
  for (const output of entry.outputs) {
16613
- const cached2 = path25.join(
17011
+ const cached2 = path27.join(
16614
17012
  cacheDir,
16615
17013
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
16616
17014
  );
16617
- if (existsSync20(cached2) && await sha256File(cached2) === output.sha256) {
17015
+ if (existsSync22(cached2) && await sha256File(cached2) === output.sha256) {
16618
17016
  hasCache = true;
16619
17017
  break;
16620
17018
  }
16621
17019
  }
16622
- if (!hasSource && !hasCache) stranded.push(key);
17020
+ if (!hasSource && !hasCache) stranded.push(key2);
16623
17021
  if (entry.generator === "map" && entry.submittedAt && now - Date.parse(entry.submittedAt) > 8 * 60 * 60 * 1e3) {
16624
- staleMapUrls.push(key);
17022
+ staleMapUrls.push(key2);
16625
17023
  }
16626
17024
  }
16627
17025
  add(
@@ -16710,16 +17108,16 @@ async function nearestExistingDirectory(start) {
16710
17108
  if ((await stat2(current)).isDirectory()) return current;
16711
17109
  } catch {
16712
17110
  }
16713
- const parent = path25.dirname(current);
17111
+ const parent = path27.dirname(current);
16714
17112
  if (parent === current) return current;
16715
17113
  current = parent;
16716
17114
  }
16717
17115
  }
16718
17116
 
16719
17117
  // src/pipeline/adopt.ts
16720
- import { existsSync as existsSync21 } from "fs";
16721
- import { readFile as readFile15, writeFile as writeFile8 } from "fs/promises";
16722
- import path26 from "path";
17118
+ import { existsSync as existsSync23 } from "fs";
17119
+ import { readFile as readFile16, writeFile as writeFile9 } from "fs/promises";
17120
+ import path28 from "path";
16723
17121
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
16724
17122
  const log = opts.onProgress ?? (() => {
16725
17123
  });
@@ -16730,11 +17128,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
16730
17128
  const localByHash = /* @__PURE__ */ new Map();
16731
17129
  const unmatchedLocal = [];
16732
17130
  for (const spec of specs) {
16733
- if (!existsSync21(spec.outFile)) {
17131
+ if (!existsSync23(spec.outFile)) {
16734
17132
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
16735
17133
  continue;
16736
17134
  }
16737
- const bytes = await readFile15(spec.outFile);
17135
+ const bytes = await readFile16(spec.outFile);
16738
17136
  try {
16739
17137
  decodePng(bytes);
16740
17138
  } catch (err) {
@@ -16779,14 +17177,14 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
16779
17177
  if (!hits?.length) continue;
16780
17178
  matchedRemote.add(obj.id);
16781
17179
  for (const spec of hits) {
16782
- const key = lockKey(spec.styleId, spec.assetId);
16783
- const existing = lock.entries[key];
17180
+ const key2 = lockKey(spec.styleId, spec.assetId);
17181
+ const existing = lock.entries[key2];
16784
17182
  if (existing?.objectId && existing.objectId !== obj.id) {
16785
- ambiguous.push(`${key}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
17183
+ ambiguous.push(`${key2}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
16786
17184
  continue;
16787
17185
  }
16788
17186
  const durableSource = shouldPersistSourceUrl(url) ? url : null;
16789
- upsert(lock, key, {
17187
+ upsert(lock, key2, {
16790
17188
  styleId: spec.styleId,
16791
17189
  assetId: spec.assetId,
16792
17190
  // Deliberately the CURRENT spec hash: adoption declares "the file on
@@ -16813,7 +17211,7 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
16813
17211
  provider: provider.id
16814
17212
  });
16815
17213
  matched++;
16816
- log(` adopted ${key} \u2190 ${obj.id}`);
17214
+ log(` adopted ${key2} \u2190 ${obj.id}`);
16817
17215
  }
16818
17216
  }
16819
17217
  }
@@ -16837,32 +17235,40 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
16837
17235
  });
16838
17236
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
16839
17237
  let count = 0;
16840
- for (const [key, entry] of Object.entries(lock.entries)) {
16841
- const spec = specByKey.get(key);
17238
+ for (const [key2, entry] of Object.entries(lock.entries)) {
17239
+ const spec = specByKey.get(key2);
16842
17240
  if (!spec || !entry.objectId) continue;
16843
17241
  if (!provider.setTags) return count;
16844
17242
  try {
16845
17243
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
16846
17244
  count++;
16847
17245
  } catch (err) {
16848
- log(` tag failed ${key}: ${err instanceof Error ? err.message : String(err)}`);
17246
+ log(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
16849
17247
  }
16850
17248
  }
16851
17249
  return count;
16852
17250
  }
16853
17251
 
16854
17252
  // src/pipeline/import.ts
16855
- import { existsSync as existsSync22 } from "fs";
16856
- import { readFile as readFile16 } from "fs/promises";
17253
+ import { existsSync as existsSync24 } from "fs";
17254
+ import { readFile as readFile17 } from "fs/promises";
17255
+ import path29 from "path";
16857
17256
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
16858
17257
  const png = decodePng(bytes);
16859
17258
  const at = now.toISOString();
17259
+ const origin = {
17260
+ ...opts.tool ? { tool: opts.tool } : {},
17261
+ ...opts.prompt ? { prompt: opts.prompt } : {},
17262
+ ...opts.seed !== void 0 ? { seed: opts.seed } : {},
17263
+ ...opts.steps?.length ? { steps: opts.steps } : {},
17264
+ ...opts.rawSha256 ? { raw: { sha256: opts.rawSha256 } } : {}
17265
+ };
16860
17266
  return {
16861
17267
  styleId: spec.styleId,
16862
17268
  assetId: spec.assetId,
16863
17269
  specHash: spec.specHash,
16864
17270
  generator: spec.generator,
16865
- prompt: spec.prompt,
17271
+ prompt: opts.prompt ?? spec.prompt,
16866
17272
  width: png.width,
16867
17273
  height: png.height,
16868
17274
  jobId: opts.objectId ?? null,
@@ -16876,9 +17282,11 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
16876
17282
  outputs: [{ path: portableOutputPath(spec.outFile, spec.root), sha256: sha256(bytes) }],
16877
17283
  submittedAt: null,
16878
17284
  downloadedAt: at,
16879
- cost: 0,
17285
+ cost: opts.cost ?? 0,
16880
17286
  costUnit: spec.costUnit,
16881
17287
  provider: spec.provider,
17288
+ ...Object.keys(origin).length ? { origin } : {},
17289
+ ...spec.external ? { external: { builder: spec.external.builder, inputs: spec.external.inputs } } : {},
16882
17290
  imported: {
16883
17291
  source: opts.source ?? "external",
16884
17292
  ...opts.note ? { note: opts.note } : {},
@@ -16896,35 +17304,62 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
16896
17304
  if (opts.objectId && specs.length !== 1) {
16897
17305
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
16898
17306
  }
17307
+ const cacheDir = opts.cacheDir === false ? null : path29.resolve(opts.cacheDir ?? path29.join(path29.dirname(lockPath), ".pixelkiln", "cache"));
17308
+ let rawSha256;
17309
+ let rawBytes;
17310
+ if (opts.raw) {
17311
+ if (specs.length !== 1) throw new Error(`--raw names one original; ${specs.length} assets are selected. Narrow with --only and --style.`);
17312
+ try {
17313
+ rawBytes = await readFile17(opts.raw);
17314
+ decodePng(rawBytes);
17315
+ } catch (error) {
17316
+ throw new Error(`--raw ${opts.raw} is not a readable PNG: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
17317
+ }
17318
+ rawSha256 = sha256(rawBytes);
17319
+ }
16899
17320
  const imported = [];
16900
17321
  const skipped = [];
16901
17322
  for (const spec of specs) {
16902
- const key = lockKey(spec.styleId, spec.assetId);
17323
+ const key2 = lockKey(spec.styleId, spec.assetId);
16903
17324
  const reason = unimportable(spec);
16904
17325
  if (reason) {
16905
- skipped.push({ key, reason });
17326
+ skipped.push({ key: key2, reason });
16906
17327
  continue;
16907
17328
  }
16908
- if (!existsSync22(spec.outFile)) {
16909
- skipped.push({ key, reason: `no file at ${spec.outFile}` });
17329
+ if (!existsSync24(spec.outFile)) {
17330
+ skipped.push({ key: key2, reason: `no file at ${spec.outFile}` });
16910
17331
  continue;
16911
17332
  }
16912
- if (lock.entries[key] && !opts.force) {
16913
- skipped.push({ key, reason: "already in the lockfile (use --force to replace it)" });
17333
+ if (lock.entries[key2] && !opts.force) {
17334
+ skipped.push({ key: key2, reason: "already in the lockfile (use --force to replace it)" });
16914
17335
  continue;
16915
17336
  }
16916
17337
  let patch;
17338
+ let bytes;
16917
17339
  try {
16918
- patch = buildImportedEntry(spec, await readFile16(spec.outFile), opts);
17340
+ bytes = await readFile17(spec.outFile);
17341
+ patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
16919
17342
  } catch (error) {
16920
- skipped.push({ key, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
17343
+ skipped.push({ key: key2, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
16921
17344
  continue;
16922
17345
  }
16923
17346
  if (opts.dryRun) {
16924
- imported.push({ key, entry: patch });
17347
+ imported.push({ key: key2, entry: patch });
16925
17348
  continue;
16926
17349
  }
16927
- imported.push({ key, entry: upsert(lock, key, patch) });
17350
+ const existing = lock.entries[key2];
17351
+ const history = existing?.outputs[0]?.sha256 === sha256(bytes) ? existing.history : historyAfterReplacing(existing, opts.historyLimit ?? DEFAULT_HISTORY_LIMIT, patch.downloadedAt ?? (/* @__PURE__ */ new Date()).toISOString());
17352
+ if (cacheDir) {
17353
+ await cacheMedia(cacheDir, bytes, MediaType.PNG);
17354
+ if (rawBytes) await cacheMedia(cacheDir, rawBytes, MediaType.PNG);
17355
+ }
17356
+ imported.push({ key: key2, entry: upsert(lock, key2, {
17357
+ ...patch,
17358
+ // An import replaces the whole record: clear what the entry held that
17359
+ // an import never has, or a regenerated entry would keep stale links.
17360
+ origin: patch.origin,
17361
+ history
17362
+ }) });
16928
17363
  }
16929
17364
  if (!opts.dryRun && imported.length) await saveLock(lockPath, lock);
16930
17365
  return { imported, skipped };
@@ -16932,9 +17367,9 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
16932
17367
  async function reportSpecHashes(specs, lock) {
16933
17368
  const reports = [];
16934
17369
  for (const spec of specs) {
16935
- const key = lockKey(spec.styleId, spec.assetId);
17370
+ const key2 = lockKey(spec.styleId, spec.assetId);
16936
17371
  let bytes = null;
16937
- if (existsSync22(spec.outFile)) bytes = await readFile16(spec.outFile);
17372
+ if (existsSync24(spec.outFile)) bytes = await readFile17(spec.outFile);
16938
17373
  let wouldImport = null;
16939
17374
  if (bytes && !unimportable(spec)) {
16940
17375
  try {
@@ -16943,11 +17378,11 @@ async function reportSpecHashes(specs, lock) {
16943
17378
  wouldImport = null;
16944
17379
  }
16945
17380
  }
16946
- const entry = lock.entries[key];
17381
+ const entry = lock.entries[key2];
16947
17382
  const fileSha256 = bytes ? sha256(bytes) : null;
16948
17383
  const outputSha256 = entry?.outputs[0]?.sha256 ?? null;
16949
17384
  reports.push({
16950
- key,
17385
+ key: key2,
16951
17386
  specHash: spec.specHash,
16952
17387
  file: spec.outFile,
16953
17388
  fileSha256,
@@ -16963,13 +17398,13 @@ async function reportSpecHashes(specs, lock) {
16963
17398
  }
16964
17399
 
16965
17400
  // src/pick/server.ts
16966
- import { existsSync as existsSync24 } from "fs";
16967
- import { readFile as readFile19 } from "fs/promises";
17401
+ import { existsSync as existsSync26 } from "fs";
17402
+ import { readFile as readFile20 } from "fs/promises";
16968
17403
 
16969
17404
  // src/pipeline/init.ts
16970
- import { readdir as readdir3, readFile as readFile17, writeFile as writeFile9 } from "fs/promises";
16971
- import { existsSync as existsSync23 } from "fs";
16972
- import path27 from "path";
17405
+ import { readdir as readdir3, readFile as readFile18, writeFile as writeFile10 } from "fs/promises";
17406
+ import { existsSync as existsSync25 } from "fs";
17407
+ import path30 from "path";
16973
17408
  function pngSize(buf) {
16974
17409
  if (buf.length < 24) return null;
16975
17410
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -16983,7 +17418,7 @@ function slugify(value) {
16983
17418
  async function walk(dir, exclude) {
16984
17419
  const out = [];
16985
17420
  for (const entry of await readdir3(dir, { withFileTypes: true })) {
16986
- const full = path27.join(dir, entry.name);
17421
+ const full = path30.join(dir, entry.name);
16987
17422
  if (exclude.some((x) => full.includes(x))) continue;
16988
17423
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
16989
17424
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -16997,14 +17432,14 @@ async function scanAssets(root, opts = {}) {
16997
17432
  const skipped = [];
16998
17433
  const seen = /* @__PURE__ */ new Map();
16999
17434
  for (const file of files.sort()) {
17000
- const size = pngSize(await readFile17(file));
17435
+ const size = pngSize(await readFile18(file));
17001
17436
  if (!size) {
17002
17437
  skipped.push(`${file} (not a readable PNG)`);
17003
17438
  continue;
17004
17439
  }
17005
- const rel = path27.relative(root, file);
17006
- const category = path27.dirname(rel) === "." ? "" : path27.dirname(rel);
17007
- let id = slugify(path27.basename(rel));
17440
+ const rel = path30.relative(root, file);
17441
+ const category = path30.dirname(rel) === "." ? "" : path30.dirname(rel);
17442
+ let id = slugify(path30.basename(rel));
17008
17443
  if (seen.has(id)) {
17009
17444
  const n = seen.get(id) + 1;
17010
17445
  seen.set(id, n);
@@ -17478,7 +17913,7 @@ document.getElementById('submit').onclick = async () => {
17478
17913
 
17479
17914
  // src/pick/review-server.ts
17480
17915
  import { createServer } from "http";
17481
- import { readFile as readFile18 } from "fs/promises";
17916
+ import { readFile as readFile19 } from "fs/promises";
17482
17917
  function serveReviewPage(opts) {
17483
17918
  const log = opts.onProgress ?? (() => {
17484
17919
  });
@@ -17487,7 +17922,7 @@ function serveReviewPage(opts) {
17487
17922
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
17488
17923
  try {
17489
17924
  const asset = opts.assets.get(req.url);
17490
- const bytes = await readFile18(asset.path);
17925
+ const bytes = await readFile19(asset.path);
17491
17926
  res.writeHead(200, {
17492
17927
  "Content-Type": asset.contentType,
17493
17928
  "Cache-Control": "no-store",
@@ -17563,13 +17998,13 @@ async function currentArt(entry, spec) {
17563
17998
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
17564
17999
  if (!previous) return null;
17565
18000
  const file = resolveOutputPath(previous.path, spec.root);
17566
- if (!existsSync24(file)) return null;
18001
+ if (!existsSync26(file)) return null;
17567
18002
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
17568
18003
  if (!contentType) return null;
17569
18004
  let width = entry.width;
17570
18005
  let height = entry.height;
17571
18006
  if (contentType === "image/png") {
17572
- const size = pngSize(await readFile19(file));
18007
+ const size = pngSize(await readFile20(file));
17573
18008
  if (size) ({ width, height } = size);
17574
18009
  }
17575
18010
  return { path: file, contentType, width, height };
@@ -17577,7 +18012,7 @@ async function currentArt(entry, spec) {
17577
18012
  async function cachedFrame(url) {
17578
18013
  if (!url.startsWith("file://")) return null;
17579
18014
  const file = url.slice("file://".length);
17580
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile19(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
18015
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await readFile20(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
17581
18016
  return { path: file, contentType };
17582
18017
  }
17583
18018
  async function prepareReview(provider, lock, opts = {}) {
@@ -17591,11 +18026,11 @@ async function prepareReview(provider, lock, opts = {}) {
17591
18026
  const prefix = opts.routePrefix ?? "";
17592
18027
  const providerUrls = /* @__PURE__ */ new Map();
17593
18028
  const groups = [];
17594
- for (const [key, entry] of Object.entries(lock.entries)) {
17595
- if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key)) continue;
18029
+ for (const [key2, entry] of Object.entries(lock.entries)) {
18030
+ if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key2)) continue;
17596
18031
  if (entry.status !== "review" || !entry.reviewObjectId) continue;
17597
18032
  try {
17598
- const spec = specByKey.get(key);
18033
+ const spec = specByKey.get(key2);
17599
18034
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
17600
18035
  if (state.status !== "review" && state.status !== "review-set" || (state.status === "review" ? !state.candidateUrls.length : !state.frameUrls.length)) continue;
17601
18036
  const urls = state.status === "review" ? state.candidateUrls : state.frameUrls;
@@ -17609,7 +18044,7 @@ async function prepareReview(provider, lock, opts = {}) {
17609
18044
  frameSizes.push(null);
17610
18045
  continue;
17611
18046
  }
17612
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile19(cached2.path).catch(() => Buffer.alloc(0))) : null);
18047
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await readFile20(cached2.path).catch(() => Buffer.alloc(0))) : null);
17613
18048
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
17614
18049
  frameAssets.push([route, cached2]);
17615
18050
  frameUrls.push(route);
@@ -17627,9 +18062,9 @@ async function prepareReview(provider, lock, opts = {}) {
17627
18062
  reviewAssets.set(currentRoute, { path: current.path, contentType: current.contentType });
17628
18063
  }
17629
18064
  for (const [route, asset] of frameAssets) reviewAssets.set(route, asset);
17630
- providerUrls.set(key, urls);
18065
+ providerUrls.set(key2, urls);
17631
18066
  groups.push({
17632
- key,
18067
+ key: key2,
17633
18068
  assetId: entry.assetId,
17634
18069
  styleId: entry.styleId,
17635
18070
  prompt: entry.prompt,
@@ -17659,7 +18094,7 @@ async function prepareReview(provider, lock, opts = {}) {
17659
18094
  ...entry.batch?.index != null ? { recommendedIndex: entry.batch.index } : {}
17660
18095
  });
17661
18096
  } catch (err) {
17662
- log(` could not load candidates for ${key}: ${err instanceof Error ? err.message : String(err)}`);
18097
+ log(` could not load candidates for ${key2}: ${err instanceof Error ? err.message : String(err)}`);
17663
18098
  }
17664
18099
  }
17665
18100
  if (groups.length === 0) return null;
@@ -17671,18 +18106,18 @@ async function prepareReview(provider, lock, opts = {}) {
17671
18106
  apply: async (body, lockPath) => {
17672
18107
  const { selections } = body;
17673
18108
  let selected = 0;
17674
- for (const { key, index } of selections) {
17675
- const group = byKey.get(key);
17676
- const entry = lock.entries[key];
18109
+ for (const { key: key2, index } of selections) {
18110
+ const group = byKey.get(key2);
18111
+ const entry = lock.entries[key2];
17677
18112
  if (!group || !entry?.reviewObjectId) continue;
17678
18113
  if (!Number.isInteger(index) || index < 0 || index >= group.frameUrls.length) continue;
17679
18114
  if (group.mode === "frame-set") {
17680
- const spec = specByKey.get(key);
18115
+ const spec = specByKey.get(key2);
17681
18116
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
17682
18117
  if (state.status !== "review-set") {
17683
- throw new Error(`Frame set ${key} is no longer ready for review`);
18118
+ throw new Error(`Frame set ${key2} is no longer ready for review`);
17684
18119
  }
17685
- upsert(lock, key, {
18120
+ upsert(lock, key2, {
17686
18121
  status: "selected",
17687
18122
  objectId: state.objectId,
17688
18123
  candidateIndex: null,
@@ -17698,7 +18133,7 @@ async function prepareReview(provider, lock, opts = {}) {
17698
18133
  } : entry.providerMetadata
17699
18134
  });
17700
18135
  selected++;
17701
- log(` accepted ${key} \u2192 ${state.sources.length} ordered frames`);
18136
+ log(` accepted ${key2} \u2192 ${state.sources.length} ordered frames`);
17702
18137
  continue;
17703
18138
  }
17704
18139
  const { objectId, sourceUrl, metadata } = await requireSelectCandidate(provider)(
@@ -17707,11 +18142,11 @@ async function prepareReview(provider, lock, opts = {}) {
17707
18142
  `asset:${entry.assetId}`,
17708
18143
  entry.generator
17709
18144
  );
17710
- upsert(lock, key, {
18145
+ upsert(lock, key2, {
17711
18146
  status: "selected",
17712
18147
  objectId,
17713
18148
  candidateIndex: index,
17714
- sourceUrl: sourceUrl ?? providerUrls.get(key)?.[index] ?? null,
18149
+ sourceUrl: sourceUrl ?? providerUrls.get(key2)?.[index] ?? null,
17715
18150
  sourceUrls: [],
17716
18151
  provider: provider.id,
17717
18152
  providerMetadata: metadata ? {
@@ -17723,7 +18158,7 @@ async function prepareReview(provider, lock, opts = {}) {
17723
18158
  } : entry.providerMetadata
17724
18159
  });
17725
18160
  selected++;
17726
- log(` picked ${key} \u2192 candidate ${index + 1}`);
18161
+ log(` picked ${key2} \u2192 candidate ${index + 1}`);
17727
18162
  }
17728
18163
  await saveLock(lockPath, lock);
17729
18164
  return { selected, skipped: groups.length - selected };
@@ -17763,14 +18198,14 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
17763
18198
 
17764
18199
  // src/gallery/snapshot.ts
17765
18200
  import { createHash as createHash5 } from "crypto";
17766
- import { existsSync as existsSync30 } from "fs";
17767
- import { readFile as readFile26, stat as stat3 } from "fs/promises";
17768
- import path35 from "path";
18201
+ import { existsSync as existsSync32 } from "fs";
18202
+ import { readFile as readFile27, stat as stat3 } from "fs/promises";
18203
+ import path38 from "path";
17769
18204
 
17770
18205
  // src/workspace.ts
17771
- import { mkdir as mkdir8, readFile as readFile20, rename as rename6, rm as rm7, writeFile as writeFile10 } from "fs/promises";
17772
- import { existsSync as existsSync25 } from "fs";
17773
- import path28 from "path";
18206
+ import { mkdir as mkdir9, readFile as readFile21, rename as rename7, rm as rm7, writeFile as writeFile11 } from "fs/promises";
18207
+ import { existsSync as existsSync27 } from "fs";
18208
+ import path31 from "path";
17774
18209
  import { z as z7 } from "zod";
17775
18210
  var WorkspaceProjectSchema = z7.object({
17776
18211
  id: z7.string().min(1),
@@ -17795,10 +18230,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
17795
18230
  );
17796
18231
  }
17797
18232
  async function loadWorkspace(workspacePath) {
17798
- if (!existsSync25(workspacePath)) return { version: 1, projects: [] };
18233
+ if (!existsSync27(workspacePath)) return { version: 1, projects: [] };
17799
18234
  let raw;
17800
18235
  try {
17801
- raw = JSON.parse(await readFile20(workspacePath, "utf8"));
18236
+ raw = JSON.parse(await readFile21(workspacePath, "utf8"));
17802
18237
  } catch (err) {
17803
18238
  throw new ProjectError(
17804
18239
  `Workspace catalog at ${workspacePath} is malformed:
@@ -17812,22 +18247,22 @@ async function saveWorkspace(workspacePath, ws) {
17812
18247
  version: 1,
17813
18248
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
17814
18249
  };
17815
- await mkdir8(path28.dirname(path28.resolve(workspacePath)), { recursive: true });
18250
+ await mkdir9(path31.dirname(path31.resolve(workspacePath)), { recursive: true });
17816
18251
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
17817
18252
  try {
17818
- await writeFile10(tmp, JSON.stringify(sorted, null, 2) + "\n");
17819
- await rename6(tmp, workspacePath);
18253
+ await writeFile11(tmp, JSON.stringify(sorted, null, 2) + "\n");
18254
+ await rename7(tmp, workspacePath);
17820
18255
  } finally {
17821
18256
  await rm7(tmp, { force: true });
17822
18257
  }
17823
18258
  }
17824
18259
  function toPortablePath(dir, absolute) {
17825
- return path28.relative(dir, absolute).split(path28.sep).join("/");
18260
+ return path31.relative(dir, absolute).split(path31.sep).join("/");
17826
18261
  }
17827
18262
  function resolveProject(dir, project) {
17828
18263
  return {
17829
- manifestPath: path28.resolve(dir, project.manifest.split("/").join(path28.sep)),
17830
- lockPath: path28.resolve(dir, project.lock.split("/").join(path28.sep))
18264
+ manifestPath: path31.resolve(dir, project.manifest.split("/").join(path31.sep)),
18265
+ lockPath: path31.resolve(dir, project.lock.split("/").join(path31.sep))
17831
18266
  };
17832
18267
  }
17833
18268
  function validateWorkspace(ws, dir) {
@@ -17840,21 +18275,21 @@ function validateWorkspace(ws, dir) {
17840
18275
  const { manifestPath, lockPath } = resolveProject(dir, project);
17841
18276
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project.id]);
17842
18277
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project.id]);
17843
- if (path28.isAbsolute(project.manifest) || path28.isAbsolute(project.lock)) {
18278
+ if (path31.isAbsolute(project.manifest) || path31.isAbsolute(project.lock)) {
17844
18279
  diagnostics.push({
17845
18280
  id: "absolute-path",
17846
18281
  level: "warning",
17847
18282
  message: `project "${project.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
17848
18283
  });
17849
18284
  }
17850
- if (!existsSync25(manifestPath)) {
18285
+ if (!existsSync27(manifestPath)) {
17851
18286
  diagnostics.push({
17852
18287
  id: "missing-manifest",
17853
18288
  level: "error",
17854
18289
  message: `project "${project.id}" manifest not found: ${manifestPath}`
17855
18290
  });
17856
18291
  }
17857
- if (!existsSync25(lockPath)) {
18292
+ if (!existsSync27(lockPath)) {
17858
18293
  diagnostics.push({
17859
18294
  id: "missing-lock",
17860
18295
  level: "error",
@@ -17901,16 +18336,16 @@ function validateWorkspace(ws, dir) {
17901
18336
  }
17902
18337
 
17903
18338
  // src/gallery/edit.ts
17904
- import { readFile as readFile25, rename as rename9, writeFile as writeFile16 } from "fs/promises";
17905
- import path34 from "path";
18339
+ import { readFile as readFile26, rename as rename10, writeFile as writeFile17 } from "fs/promises";
18340
+ import path37 from "path";
17906
18341
  import { z as z13 } from "zod";
17907
18342
 
17908
18343
  // src/manifest-edit.ts
17909
- import { readFile as readFile21, rename as rename7, rm as rm8, writeFile as writeFile11 } from "fs/promises";
17910
- import path29 from "path";
18344
+ import { readFile as readFile22, rename as rename8, rm as rm8, writeFile as writeFile12 } from "fs/promises";
18345
+ import path32 from "path";
17911
18346
  import { z as z8 } from "zod";
17912
18347
  var HexSha = z8.string().regex(/^[0-9a-f]{64}$/);
17913
- var ProjectFileSchema = z8.string().min(1).refine((file) => !path29.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
18348
+ var ProjectFileSchema = z8.string().min(1).refine((file) => !path32.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
17914
18349
  var AssetPatchSchema = z8.object({
17915
18350
  prompt: z8.string().optional(),
17916
18351
  /** Per-style override for the style being viewed; null removes it. */
@@ -18177,9 +18612,9 @@ function styleProvider(raw, styleId, seen = /* @__PURE__ */ new Set()) {
18177
18612
  seen.add(styleId);
18178
18613
  return style.extends ? styleProvider(raw, style.extends, seen) : raw.provider ?? "pixellab";
18179
18614
  }
18180
- function setOrDelete(target, key, value) {
18181
- if (value === null || value === void 0) delete target[key];
18182
- else target[key] = value;
18615
+ function setOrDelete(target, key2, value) {
18616
+ if (value === null || value === void 0) delete target[key2];
18617
+ else target[key2] = value;
18183
18618
  }
18184
18619
  function assetStyles(raw, asset) {
18185
18620
  const own = Array.isArray(asset.styles) ? asset.styles : [];
@@ -18330,8 +18765,8 @@ function applyEdit(raw, edit) {
18330
18765
  }
18331
18766
  }
18332
18767
  async function withCandidate(manifestPath, edit, use, unchanged) {
18333
- const absolute = path29.resolve(manifestPath);
18334
- const original = await readFile21(absolute, "utf8");
18768
+ const absolute = path32.resolve(manifestPath);
18769
+ const original = await readFile22(absolute, "utf8");
18335
18770
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
18336
18771
  let raw;
18337
18772
  try {
@@ -18344,12 +18779,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
18344
18779
  applyEdit(raw, edit);
18345
18780
  const next = serializeLike(original, raw);
18346
18781
  if (next === original) return unchanged(absolute, original);
18347
- const tmp = path29.join(
18348
- path29.dirname(absolute),
18349
- `.${path29.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
18782
+ const tmp = path32.join(
18783
+ path32.dirname(absolute),
18784
+ `.${path32.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
18350
18785
  );
18351
18786
  try {
18352
- await writeFile11(tmp, next);
18787
+ await writeFile12(tmp, next);
18353
18788
  let specs;
18354
18789
  try {
18355
18790
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -18367,7 +18802,7 @@ async function applyManifestEdit(manifestPath, edit) {
18367
18802
  manifestPath,
18368
18803
  edit,
18369
18804
  async ({ absolute, next, tmp }) => {
18370
- await rename7(tmp, absolute);
18805
+ await rename8(tmp, absolute);
18371
18806
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
18372
18807
  },
18373
18808
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -18375,18 +18810,18 @@ async function applyManifestEdit(manifestPath, edit) {
18375
18810
  }
18376
18811
 
18377
18812
  // src/pipeline/hand-edit.ts
18378
- import { existsSync as existsSync26 } from "fs";
18379
- import { copyFile, mkdir as mkdir9, readFile as readFile22, rename as rename8, rm as rm9, writeFile as writeFile12 } from "fs/promises";
18380
- import path30 from "path";
18813
+ import { existsSync as existsSync28 } from "fs";
18814
+ import { copyFile, mkdir as mkdir10, readFile as readFile23, rename as rename9, rm as rm9, writeFile as writeFile13 } from "fs/promises";
18815
+ import path33 from "path";
18381
18816
  import { z as z9 } from "zod";
18382
18817
  var HAND_EDIT_DIR = "edits";
18383
18818
  function handEditPath(loaded, spec) {
18384
18819
  const style = loaded.manifest.styles[spec.styleId];
18385
- const outDir = path30.resolve(loaded.root, style?.outDir ?? ".");
18386
- const relative = path30.relative(outDir, spec.outFile);
18387
- const inside = relative && !relative.startsWith("..") && !path30.isAbsolute(relative);
18388
- const file = inside ? relative : path30.basename(spec.outFile);
18389
- return path30.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
18820
+ const outDir = path33.resolve(loaded.root, style?.outDir ?? ".");
18821
+ const relative = path33.relative(outDir, spec.outFile);
18822
+ const inside = relative && !relative.startsWith("..") && !path33.isAbsolute(relative);
18823
+ const file = inside ? relative : path33.basename(spec.outFile);
18824
+ return path33.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
18390
18825
  }
18391
18826
  function handEditBases(spec, lock) {
18392
18827
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -18399,10 +18834,10 @@ function handEditBases(spec, lock) {
18399
18834
  }));
18400
18835
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
18401
18836
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
18402
- if (!members.every((member) => existsSync26(member.path))) return null;
18837
+ if (!members.every((member) => existsSync28(member.path))) return null;
18403
18838
  return members.map(({ role, path: file }) => ({ role, path: file }));
18404
18839
  }
18405
- return existsSync26(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
18840
+ return existsSync28(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
18406
18841
  }
18407
18842
  function handEditBase(spec, lock) {
18408
18843
  const bases = handEditBases(spec, lock);
@@ -18432,18 +18867,18 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
18432
18867
  `${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`
18433
18868
  );
18434
18869
  }
18435
- const existing = spec.source ? path30.resolve(loaded.root, spec.source) : null;
18870
+ const existing = spec.source ? path33.resolve(loaded.root, spec.source) : null;
18436
18871
  const editPath = existing ?? handEditPath(loaded, spec);
18437
18872
  const members = handEditMembers(loaded, spec, lock, editPath);
18438
18873
  let created = false;
18439
18874
  for (const member of members) {
18440
- if (existsSync26(member.path)) continue;
18875
+ if (existsSync28(member.path)) continue;
18441
18876
  if (!member.base) {
18442
18877
  throw new ManifestEditError(
18443
18878
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
18444
18879
  );
18445
18880
  }
18446
- await mkdir9(path30.dirname(member.path), { recursive: true });
18881
+ await mkdir10(path33.dirname(member.path), { recursive: true });
18447
18882
  await copyFile(member.base, member.path);
18448
18883
  created = true;
18449
18884
  }
@@ -18522,7 +18957,7 @@ function handEditProjectPath(editPath) {
18522
18957
  async function readHandEditCompanion(editPath) {
18523
18958
  let text;
18524
18959
  try {
18525
- text = await readFile22(handEditCompanionPath(editPath), "utf8");
18960
+ text = await readFile23(handEditCompanionPath(editPath), "utf8");
18526
18961
  } catch {
18527
18962
  return null;
18528
18963
  }
@@ -18565,7 +19000,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
18565
19000
  }
18566
19001
  });
18567
19002
  const bases = handEditBases(spec, lock);
18568
- const expectedSize = bases?.[0] ? decodePng(await readFile22(bases[0].path)) : { width: spec.width, height: spec.height };
19003
+ const expectedSize = bases?.[0] ? decodePng(await readFile23(bases[0].path)) : { width: spec.width, height: spec.height };
18569
19004
  for (const [index, image] of decoded.entries()) {
18570
19005
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
18571
19006
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -18581,7 +19016,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
18581
19016
  editor: input.editor,
18582
19017
  protocol: input.protocol,
18583
19018
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
18584
- project: projectPath ? path30.basename(projectPath) : null,
19019
+ project: projectPath ? path33.basename(projectPath) : null,
18585
19020
  outputs: incoming.map((frame, index) => ({
18586
19021
  role: frame.role,
18587
19022
  basedOn: basedOnHash(entry, index),
@@ -18611,8 +19046,8 @@ function basedOnHash(entry, index) {
18611
19046
  async function replaceFile(file, bytes) {
18612
19047
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18613
19048
  try {
18614
- await writeFile12(tmp, bytes);
18615
- await rename8(tmp, file);
19049
+ await writeFile13(tmp, bytes);
19050
+ await rename9(tmp, file);
18616
19051
  } finally {
18617
19052
  await rm9(tmp, { force: true });
18618
19053
  }
@@ -18623,9 +19058,9 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
18623
19058
  }
18624
19059
 
18625
19060
  // src/gallery/upload.ts
18626
- import { existsSync as existsSync27 } from "fs";
18627
- import { mkdir as mkdir10, writeFile as writeFile13 } from "fs/promises";
18628
- import path31 from "path";
19061
+ import { existsSync as existsSync29 } from "fs";
19062
+ import { mkdir as mkdir11, writeFile as writeFile14 } from "fs/promises";
19063
+ import path34 from "path";
18629
19064
  import { z as z10 } from "zod";
18630
19065
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
18631
19066
  var UploadImageSchema = z10.object({
@@ -18638,12 +19073,12 @@ var UploadImageSchema = z10.object({
18638
19073
  overwrite: z10.boolean().optional()
18639
19074
  }).strict();
18640
19075
  async function saveProjectImage(root, request) {
18641
- const file = path31.resolve(root, request.path);
18642
- const relative = path31.relative(root, file);
18643
- if (relative.startsWith("..") || path31.isAbsolute(relative)) {
19076
+ const file = path34.resolve(root, request.path);
19077
+ const relative = path34.relative(root, file);
19078
+ if (relative.startsWith("..") || path34.isAbsolute(relative)) {
18644
19079
  throw new ManifestEditError("an upload must stay inside the project");
18645
19080
  }
18646
- const extension = path31.extname(file).toLowerCase();
19081
+ const extension = path34.extname(file).toLowerCase();
18647
19082
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
18648
19083
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
18649
19084
  const bytes = Buffer.from(request.base64, "base64");
@@ -18655,18 +19090,18 @@ async function saveProjectImage(root, request) {
18655
19090
  if (metadata.format !== expected) {
18656
19091
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
18657
19092
  }
18658
- if (existsSync27(file) && !request.overwrite) {
18659
- throw new ManifestEditError(`${relative.split(path31.sep).join("/")} already exists; choose another name, or replace it`);
19093
+ if (existsSync29(file) && !request.overwrite) {
19094
+ throw new ManifestEditError(`${relative.split(path34.sep).join("/")} already exists; choose another name, or replace it`);
18660
19095
  }
18661
- await mkdir10(path31.dirname(file), { recursive: true });
18662
- await writeFile13(file, bytes);
18663
- return relative.split(path31.sep).join("/");
19096
+ await mkdir11(path34.dirname(file), { recursive: true });
19097
+ await writeFile14(file, bytes);
19098
+ return relative.split(path34.sep).join("/");
18664
19099
  }
18665
19100
 
18666
19101
  // src/gallery/image-revision.ts
18667
- import { existsSync as existsSync28 } from "fs";
18668
- import { readFile as readFile23, rm as rm10, writeFile as writeFile14 } from "fs/promises";
18669
- import path32 from "path";
19102
+ import { existsSync as existsSync30 } from "fs";
19103
+ import { readFile as readFile24, rm as rm10, writeFile as writeFile15 } from "fs/promises";
19104
+ import path35 from "path";
18670
19105
  import { z as z11 } from "zod";
18671
19106
  var InpaintRevisionRequestSchema = z11.object({
18672
19107
  action: z11.literal("create-inpaint-revision"),
@@ -18685,15 +19120,15 @@ var InpaintRevisionRequestSchema = z11.object({
18685
19120
  overwrite: z11.boolean().optional()
18686
19121
  }).strict();
18687
19122
  async function createInpaintRevision(manifestPath, request) {
18688
- const root = path32.dirname(path32.resolve(manifestPath));
18689
- if (path32.extname(request.maskPath).toLowerCase() !== ".png") {
19123
+ const root = path35.dirname(path35.resolve(manifestPath));
19124
+ if (path35.extname(request.maskPath).toLowerCase() !== ".png") {
18690
19125
  throw new ManifestEditError("the mask must be a .png path inside the project");
18691
19126
  }
18692
19127
  const bytes = Buffer.from(request.maskBase64, "base64");
18693
19128
  const metadata = imageMetadata(bytes);
18694
19129
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
18695
- const file = path32.resolve(root, request.maskPath);
18696
- const previous = existsSync28(file) ? await readFile23(file) : null;
19130
+ const file = path35.resolve(root, request.maskPath);
19131
+ const previous = existsSync30(file) ? await readFile24(file) : null;
18697
19132
  const mask = await saveProjectImage(root, {
18698
19133
  action: "upload-image",
18699
19134
  path: request.maskPath,
@@ -18712,7 +19147,7 @@ async function createInpaintRevision(manifestPath, request) {
18712
19147
  }
18713
19148
  });
18714
19149
  } catch (error) {
18715
- if (previous) await writeFile14(file, previous);
19150
+ if (previous) await writeFile15(file, previous);
18716
19151
  else await rm10(file, { force: true });
18717
19152
  throw error;
18718
19153
  }
@@ -18720,9 +19155,9 @@ async function createInpaintRevision(manifestPath, request) {
18720
19155
  }
18721
19156
 
18722
19157
  // src/gallery/skeleton.ts
18723
- import { existsSync as existsSync29 } from "fs";
18724
- import { mkdir as mkdir11, readFile as readFile24, rm as rm11, writeFile as writeFile15 } from "fs/promises";
18725
- import path33 from "path";
19158
+ import { existsSync as existsSync31 } from "fs";
19159
+ import { mkdir as mkdir12, readFile as readFile25, rm as rm11, writeFile as writeFile16 } from "fs/promises";
19160
+ import path36 from "path";
18726
19161
  import { z as z12 } from "zod";
18727
19162
  var SkeletonEstimateRequestSchema = z12.object({
18728
19163
  project: z12.string().min(1).optional(),
@@ -18761,21 +19196,21 @@ var SkeletonKeypointsUpdateSchema = z12.object({
18761
19196
  set: SkeletonSetSchema
18762
19197
  }).strict();
18763
19198
  async function createSkeletonAnimation(manifestPath, request) {
18764
- const root = path33.dirname(path33.resolve(manifestPath));
18765
- const file = path33.resolve(root, request.keypointsFile);
18766
- const relative = path33.relative(root, file);
18767
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path33.isAbsolute(relative)) {
19199
+ const root = path36.dirname(path36.resolve(manifestPath));
19200
+ const file = path36.resolve(root, request.keypointsFile);
19201
+ const relative = path36.relative(root, file);
19202
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path36.isAbsolute(relative)) {
18768
19203
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
18769
19204
  }
18770
- const existed = existsSync29(file);
19205
+ const existed = existsSync31(file);
18771
19206
  let previous = null;
18772
19207
  if (request.set) {
18773
19208
  if (existed && !request.overwrite) {
18774
19209
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
18775
19210
  }
18776
- if (existed) previous = await readFile24(file);
18777
- await mkdir11(path33.dirname(file), { recursive: true });
18778
- await writeFile15(file, JSON.stringify(request.set, null, 2) + "\n");
19211
+ if (existed) previous = await readFile25(file);
19212
+ await mkdir12(path36.dirname(file), { recursive: true });
19213
+ await writeFile16(file, JSON.stringify(request.set, null, 2) + "\n");
18779
19214
  } else if (!existed) {
18780
19215
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
18781
19216
  }
@@ -18790,7 +19225,7 @@ async function createSkeletonAnimation(manifestPath, request) {
18790
19225
  revision: {
18791
19226
  mode: "animate-skeleton",
18792
19227
  from: request.from,
18793
- keypointsFile: relative.split(path33.sep).join("/"),
19228
+ keypointsFile: relative.split(path36.sep).join("/"),
18794
19229
  direction: request.direction,
18795
19230
  description: request.description,
18796
19231
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -18799,31 +19234,31 @@ async function createSkeletonAnimation(manifestPath, request) {
18799
19234
  });
18800
19235
  } catch (error) {
18801
19236
  if (request.set) {
18802
- if (previous) await writeFile15(file, previous);
19237
+ if (previous) await writeFile16(file, previous);
18803
19238
  else await rm11(file, { force: true });
18804
19239
  }
18805
19240
  throw error;
18806
19241
  }
18807
19242
  }
18808
19243
  async function updateSkeletonKeypoints(ctx, request) {
18809
- const key = lockKey(request.styleId, request.assetId);
18810
- const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key);
18811
- if (!spec) throw new ManifestEditError(`"${key}" is not declared by the manifest`);
19244
+ const key2 = lockKey(request.styleId, request.assetId);
19245
+ const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key2);
19246
+ if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
18812
19247
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
18813
- if (!file) throw new ManifestEditError(`${key} is not an animate-skeleton revision`);
18814
- const relative = path33.relative(ctx.loaded.root, file);
18815
- if (relative.startsWith("..") || path33.isAbsolute(relative)) {
18816
- throw new ManifestEditError(`${key}'s keypoints file is outside the project; edit it by hand`);
19248
+ if (!file) throw new ManifestEditError(`${key2} is not an animate-skeleton revision`);
19249
+ const relative = path36.relative(ctx.loaded.root, file);
19250
+ if (relative.startsWith("..") || path36.isAbsolute(relative)) {
19251
+ throw new ManifestEditError(`${key2}'s keypoints file is outside the project; edit it by hand`);
18817
19252
  }
18818
- const current = existsSync29(file) ? sha256(await readFile24(file)) : null;
19253
+ const current = existsSync31(file) ? sha256(await readFile25(file)) : null;
18819
19254
  if (current !== request.expectedSha256) {
18820
19255
  throw Object.assign(
18821
- new Error(`${relative.split(path33.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
19256
+ new Error(`${relative.split(path36.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
18822
19257
  { status: 409 }
18823
19258
  );
18824
19259
  }
18825
- await writeFile15(file, JSON.stringify(request.set, null, 2) + "\n");
18826
- return relative.split(path33.sep).join("/");
19260
+ await writeFile16(file, JSON.stringify(request.set, null, 2) + "\n");
19261
+ return relative.split(path36.sep).join("/");
18827
19262
  }
18828
19263
 
18829
19264
  // src/gallery/edit.ts
@@ -18877,7 +19312,7 @@ function createGalleryEditHandler(opts) {
18877
19312
  const history = /* @__PURE__ */ new Map();
18878
19313
  const manifestOf = async (project) => {
18879
19314
  try {
18880
- return path34.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
19315
+ return path37.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
18881
19316
  } catch {
18882
19317
  return null;
18883
19318
  }
@@ -18887,7 +19322,7 @@ function createGalleryEditHandler(opts) {
18887
19322
  if (undo.success) {
18888
19323
  const manifestPath2 = await manifestOf(undo.data.project);
18889
19324
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
18890
- const current = await readFile25(manifestPath2, "utf8");
19325
+ const current = await readFile26(manifestPath2, "utf8");
18891
19326
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
18892
19327
  const stack = history.get(manifestPath2) ?? [];
18893
19328
  const last = stack[stack.length - 1];
@@ -18897,17 +19332,17 @@ function createGalleryEditHandler(opts) {
18897
19332
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
18898
19333
  }
18899
19334
  const tmp = manifestPath2 + ".pixelkiln-undo";
18900
- await writeFile16(tmp, last.before);
18901
- await rename9(tmp, manifestPath2);
19335
+ await writeFile17(tmp, last.before);
19336
+ await rename10(tmp, manifestPath2);
18902
19337
  stack.pop();
18903
- log(` manifest edit undone in ${path34.relative(process.cwd(), manifestPath2) || manifestPath2}`);
19338
+ log(` manifest edit undone in ${path37.relative(process.cwd(), manifestPath2) || manifestPath2}`);
18904
19339
  return opts.reload();
18905
19340
  }
18906
19341
  const manifestPath = await manifestOf(body?.project);
18907
- const before = manifestPath ? await readFile25(manifestPath, "utf8").catch(() => null) : null;
19342
+ const before = manifestPath ? await readFile26(manifestPath, "utf8").catch(() => null) : null;
18908
19343
  const build = await apply(body);
18909
19344
  if (manifestPath && before !== null) {
18910
- const after = await readFile25(manifestPath, "utf8").catch(() => null);
19345
+ const after = await readFile26(manifestPath, "utf8").catch(() => null);
18911
19346
  if (after !== null && after !== before) {
18912
19347
  const stack = history.get(manifestPath) ?? [];
18913
19348
  stack.push({ before, afterSha: sha256(after) });
@@ -18962,7 +19397,7 @@ function createEditApplier(opts, log) {
18962
19397
  } catch (error) {
18963
19398
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
18964
19399
  }
18965
- const written = await saveProjectImage(path34.dirname(path34.resolve(manifestPath2)), upload.data);
19400
+ const written = await saveProjectImage(path37.dirname(path37.resolve(manifestPath2)), upload.data);
18966
19401
  log(` image added: ${written}`);
18967
19402
  return opts.reload();
18968
19403
  }
@@ -19029,7 +19464,7 @@ function createEditApplier(opts, log) {
19029
19464
  }
19030
19465
  const result = await applyManifestEdit(manifestPath, parsed.data);
19031
19466
  if (result.changed) {
19032
- const relative = path34.relative(process.cwd(), result.manifestPath);
19467
+ const relative = path37.relative(process.cwd(), result.manifestPath);
19033
19468
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
19034
19469
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
19035
19470
  }
@@ -19057,7 +19492,7 @@ function describeEdit(edit) {
19057
19492
  // src/gallery/snapshot.ts
19058
19493
  var PROJECT_FILE_TYPE = "application/octet-stream";
19059
19494
  function galleryMediaId(absolutePath) {
19060
- return createHash5("sha256").update(path35.resolve(absolutePath)).digest("hex").slice(0, 24);
19495
+ return createHash5("sha256").update(path38.resolve(absolutePath)).digest("hex").slice(0, 24);
19061
19496
  }
19062
19497
  function galleryMediaRoute(id) {
19063
19498
  return `/media/${id}`;
@@ -19081,9 +19516,9 @@ function describeHistory(media, entry, cacheDir) {
19081
19516
  return (entry.history ?? []).map((generation, i) => {
19082
19517
  const outputs = generation.outputs.map((output) => {
19083
19518
  const mediaType = output.mediaType ?? MediaType.PNG;
19084
- const file = path35.join(cacheDir, cacheFileName(output.sha256, mediaType));
19519
+ const file = path38.join(cacheDir, cacheFileName(output.sha256, mediaType));
19085
19520
  let url = null;
19086
- if (existsSync30(file)) {
19521
+ if (existsSync32(file)) {
19087
19522
  const id = galleryMediaId(file);
19088
19523
  media.set(id, { path: file, contentType: mediaType });
19089
19524
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -19115,7 +19550,7 @@ function describeHistory(media, entry, cacheDir) {
19115
19550
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
19116
19551
  async function samePixels(a, b) {
19117
19552
  try {
19118
- const [left, right] = await Promise.all([readFile26(a), readFile26(b)]);
19553
+ const [left, right] = await Promise.all([readFile27(a), readFile27(b)]);
19119
19554
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
19120
19555
  const x = decodePng(left);
19121
19556
  const y = decodePng(right);
@@ -19213,10 +19648,10 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
19213
19648
  async function describeQuality(media, root, inspection) {
19214
19649
  const outputPaths = inspection.outputs ?? [inspection.output];
19215
19650
  const outputs = await Promise.all(
19216
- outputPaths.map((file) => describeOutput(media, root, path35.resolve(root, file)))
19651
+ outputPaths.map((file) => describeOutput(media, root, path38.resolve(root, file)))
19217
19652
  );
19218
- const recordPath = path35.resolve(root, inspection.record);
19219
- const recordExists = existsSync30(recordPath);
19653
+ const recordPath = path38.resolve(root, inspection.record);
19654
+ const recordExists = existsSync32(recordPath);
19220
19655
  let options = null;
19221
19656
  let check = null;
19222
19657
  if (recordExists) {
@@ -19235,7 +19670,7 @@ async function describeQuality(media, root, inspection) {
19235
19670
  return {
19236
19671
  state: inspection.state,
19237
19672
  reason: inspection.reason,
19238
- output: portableOutputPath(path35.resolve(root, inspection.output), root),
19673
+ output: portableOutputPath(path38.resolve(root, inspection.output), root),
19239
19674
  record: portableOutputPath(recordPath, root),
19240
19675
  recordExists,
19241
19676
  outputs,
@@ -19273,9 +19708,9 @@ async function buildGallerySnapshot(opts) {
19273
19708
  const media = /* @__PURE__ */ new Map();
19274
19709
  const plan = await buildPlan(specs, lock);
19275
19710
  const items = [];
19276
- const manifestText = await readFile26(loaded.path, "utf8");
19711
+ const manifestText = await readFile27(loaded.path, "utf8");
19277
19712
  const manifestSha256 = sha256(manifestText);
19278
- const cacheDir = path35.resolve(path35.dirname(opts.lockPath), ".pixelkiln", "cache");
19713
+ const cacheDir = path38.resolve(path38.dirname(opts.lockPath), ".pixelkiln", "cache");
19279
19714
  let rawStyles = {};
19280
19715
  try {
19281
19716
  const raw = JSON.parse(manifestText);
@@ -19283,8 +19718,8 @@ async function buildGallerySnapshot(opts) {
19283
19718
  } catch {
19284
19719
  }
19285
19720
  for (const planItem of plan.items) {
19286
- const { spec, key } = planItem;
19287
- const entry = lock.entries[key];
19721
+ const { spec, key: key2 } = planItem;
19722
+ const entry = lock.entries[key2];
19288
19723
  const asset = loaded.manifest.assets[spec.assetId] ?? null;
19289
19724
  let outputs;
19290
19725
  let edit = null;
@@ -19299,12 +19734,12 @@ async function buildGallerySnapshot(opts) {
19299
19734
  )
19300
19735
  );
19301
19736
  if (spec.source) {
19302
- const editPath = path35.resolve(root, spec.source);
19737
+ const editPath = path38.resolve(root, spec.source);
19303
19738
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
19304
19739
  const editShas = await Promise.all(
19305
19740
  Array.from({ length: memberCount }, async (_, index) => {
19306
19741
  const file = sourceOutputPath(spec.source, entry, index, root);
19307
- return { file, sha256: existsSync30(file) ? await sha256File(file) : null };
19742
+ return { file, sha256: existsSync32(file) ? await sha256File(file) : null };
19308
19743
  })
19309
19744
  );
19310
19745
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -19312,7 +19747,7 @@ async function buildGallerySnapshot(opts) {
19312
19747
  const companion = await readHandEditCompanion(editPath);
19313
19748
  if (companion) {
19314
19749
  const projectPath = handEditProjectPath(editPath);
19315
- const project = companion.project && existsSync30(projectPath) ? await fileInfo(projectPath) : null;
19750
+ const project = companion.project && existsSync32(projectPath) ? await fileInfo(projectPath) : null;
19316
19751
  let projectUrl = null;
19317
19752
  if (project) {
19318
19753
  const id = galleryMediaId(projectPath);
@@ -19348,17 +19783,17 @@ async function buildGallerySnapshot(opts) {
19348
19783
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
19349
19784
  }
19350
19785
  } else if (spec.source) {
19351
- outputs = [await describeOutput(media, root, path35.resolve(root, spec.source))];
19352
- } else if (!entry && existsSync30(spec.outFile)) {
19786
+ outputs = [await describeOutput(media, root, path38.resolve(root, spec.source))];
19787
+ } else if (!entry && existsSync32(spec.outFile)) {
19353
19788
  outputs = [await describeOutput(media, root, spec.outFile)];
19354
19789
  } else {
19355
19790
  outputs = [];
19356
19791
  }
19357
19792
  const quality = planItem.quality ? await describeQuality(media, root, planItem.quality) : null;
19358
19793
  items.push({
19359
- id: key,
19794
+ id: key2,
19360
19795
  project: null,
19361
- key,
19796
+ key: key2,
19362
19797
  styleId: spec.styleId,
19363
19798
  assetId: spec.assetId,
19364
19799
  declared: true,
@@ -19416,8 +19851,8 @@ async function buildGallerySnapshot(opts) {
19416
19851
  });
19417
19852
  }
19418
19853
  const shown = new Set(items.map((item) => item.key));
19419
- for (const [key, entry] of Object.entries(lock.entries)) {
19420
- if (shown.has(key)) continue;
19854
+ for (const [key2, entry] of Object.entries(lock.entries)) {
19855
+ if (shown.has(key2)) continue;
19421
19856
  if (isDeclared(loaded, entry.styleId, entry.assetId)) continue;
19422
19857
  if (!matchesFilter(filter, entry.styleId, entry.assetId)) continue;
19423
19858
  const outputs = await Promise.all(
@@ -19426,9 +19861,9 @@ async function buildGallerySnapshot(opts) {
19426
19861
  )
19427
19862
  );
19428
19863
  items.push({
19429
- id: key,
19864
+ id: key2,
19430
19865
  project: null,
19431
- key,
19866
+ key: key2,
19432
19867
  styleId: entry.styleId,
19433
19868
  assetId: entry.assetId,
19434
19869
  declared: false,
@@ -19529,7 +19964,7 @@ async function buildGallerySnapshot(opts) {
19529
19964
  } : null,
19530
19965
  tags: style?.tags ?? [],
19531
19966
  extends: typeof rawStyle?.extends === "string" ? rawStyle.extends : null,
19532
- ownFields: rawStyle ? Object.keys(rawStyle).filter((key) => key !== "extends") : [],
19967
+ ownFields: rawStyle ? Object.keys(rawStyle).filter((key2) => key2 !== "extends") : [],
19533
19968
  items: styleItems.length,
19534
19969
  spendByUnit: spend,
19535
19970
  regenerate: {
@@ -19553,7 +19988,7 @@ async function buildGallerySnapshot(opts) {
19553
19988
  id: loaded.manifest.name,
19554
19989
  name: loaded.manifest.name,
19555
19990
  manifest: loaded.path,
19556
- lock: path35.resolve(opts.lockPath),
19991
+ lock: path38.resolve(opts.lockPath),
19557
19992
  root,
19558
19993
  provider: loaded.manifest.provider,
19559
19994
  account: null,
@@ -19579,7 +20014,7 @@ async function buildGallerySnapshot(opts) {
19579
20014
  return { snapshot, media };
19580
20015
  }
19581
20016
  async function buildWorkspaceGallerySnapshot(opts) {
19582
- const dir = path35.dirname(path35.resolve(opts.workspacePath));
20017
+ const dir = path38.dirname(path38.resolve(opts.workspacePath));
19583
20018
  const media = /* @__PURE__ */ new Map();
19584
20019
  const projects = [];
19585
20020
  const items = [];
@@ -19622,11 +20057,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
19622
20057
  id: project.id,
19623
20058
  name: loaded.manifest.name,
19624
20059
  manifest: manifestPath,
19625
- lock: path35.resolve(lockPath),
20060
+ lock: path38.resolve(lockPath),
19626
20061
  root: loaded.root,
19627
20062
  provider: loaded.manifest.provider,
19628
20063
  account: project.account ?? null,
19629
- manifestSha256: manifestSha256 ?? sha256(await readFile26(manifestPath, "utf8")),
20064
+ manifestSha256: manifestSha256 ?? sha256(await readFile27(manifestPath, "utf8")),
19630
20065
  historyLimit: historyLimit(loaded.manifest),
19631
20066
  entries: Object.keys(lock.entries).length,
19632
20067
  items: projectItems.length,
@@ -19638,8 +20073,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
19638
20073
  id: project.id,
19639
20074
  name: project.id,
19640
20075
  manifest: manifestPath,
19641
- lock: path35.resolve(lockPath),
19642
- root: path35.dirname(manifestPath),
20076
+ lock: path38.resolve(lockPath),
20077
+ root: path38.dirname(manifestPath),
19643
20078
  provider: project.provider,
19644
20079
  account: project.account ?? null,
19645
20080
  manifestSha256: null,
@@ -19666,7 +20101,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
19666
20101
  version: 1,
19667
20102
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
19668
20103
  project: null,
19669
- workspace: { path: path35.resolve(opts.workspacePath), dir, projects },
20104
+ workspace: { path: path38.resolve(opts.workspacePath), dir, projects },
19670
20105
  filter,
19671
20106
  totals: {
19672
20107
  entries: projects.reduce((sum, project) => sum + project.entries, 0),
@@ -19683,7 +20118,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
19683
20118
  }
19684
20119
 
19685
20120
  // src/gallery/page.ts
19686
- import { existsSync as existsSync31, readFileSync as readFileSync8 } from "fs";
20121
+ import { existsSync as existsSync33, readFileSync as readFileSync8 } from "fs";
19687
20122
 
19688
20123
  // src/gallery/client-bundle.ts
19689
20124
  import { createRequire } from "module";
@@ -19724,7 +20159,7 @@ function clientAssets() {
19724
20159
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
19725
20160
  client ??= {
19726
20161
  css: readFileSync8(new URL("gallery.css", CLIENT_DIR), "utf8"),
19727
- js: existsSync31(prebuilt) ? readFileSync8(prebuilt, "utf8") : bundleGalleryClient()
20162
+ js: existsSync33(prebuilt) ? readFileSync8(prebuilt, "utf8") : bundleGalleryClient()
19728
20163
  };
19729
20164
  return client;
19730
20165
  }
@@ -19867,10 +20302,10 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
19867
20302
 
19868
20303
  // src/editor/install.ts
19869
20304
  import { createHash as createHash6 } from "crypto";
19870
- import { existsSync as existsSync32 } from "fs";
19871
- import { mkdir as mkdir12, readFile as readFile27, rename as rename10, rm as rm12, stat as stat4, writeFile as writeFile17 } from "fs/promises";
20305
+ import { existsSync as existsSync34 } from "fs";
20306
+ import { mkdir as mkdir13, readFile as readFile28, rename as rename11, rm as rm12, stat as stat4, writeFile as writeFile18 } from "fs/promises";
19872
20307
  import os3 from "os";
19873
- import path36 from "path";
20308
+ import path39 from "path";
19874
20309
  var EditorInstallError = class extends Error {
19875
20310
  constructor(message6, file) {
19876
20311
  super(message6);
@@ -19881,15 +20316,15 @@ var EditorInstallError = class extends Error {
19881
20316
  };
19882
20317
  function editorToolsRoot() {
19883
20318
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
19884
- if (override) return path36.resolve(override);
19885
- if (process.platform === "darwin") return path36.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
20319
+ if (override) return path39.resolve(override);
20320
+ if (process.platform === "darwin") return path39.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
19886
20321
  if (process.platform === "win32") {
19887
- return path36.join(process.env.LOCALAPPDATA ?? path36.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
20322
+ return path39.join(process.env.LOCALAPPDATA ?? path39.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
19888
20323
  }
19889
- return path36.join(process.env.XDG_CACHE_HOME ?? path36.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
20324
+ return path39.join(process.env.XDG_CACHE_HOME ?? path39.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
19890
20325
  }
19891
20326
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
19892
- return path36.join(root, "pixelorama", pin.release ?? "unpublished");
20327
+ return path39.join(root, "pixelorama", pin.release ?? "unpublished");
19893
20328
  }
19894
20329
  function editorBaseUrl(pin = EDITOR_PIN) {
19895
20330
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -19899,7 +20334,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
19899
20334
  }
19900
20335
  async function sha256Of(file) {
19901
20336
  try {
19902
- return createHash6("sha256").update(await readFile27(file)).digest("hex");
20337
+ return createHash6("sha256").update(await readFile28(file)).digest("hex");
19903
20338
  } catch {
19904
20339
  return null;
19905
20340
  }
@@ -19912,8 +20347,8 @@ async function editorStatus(opts = {}) {
19912
20347
  let totalBytes = 0;
19913
20348
  for (const [name, expected] of Object.entries(pin.files)) {
19914
20349
  totalBytes += expected.bytes;
19915
- const file = path36.join(dir, name);
19916
- const info = existsSync32(file) ? await stat4(file).catch(() => null) : null;
20350
+ const file = path39.join(dir, name);
20351
+ const info = existsSync34(file) ? await stat4(file).catch(() => null) : null;
19917
20352
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
19918
20353
  installedBytes += expected.bytes;
19919
20354
  } else {
@@ -19942,7 +20377,7 @@ async function installEditor(opts = {}) {
19942
20377
  );
19943
20378
  }
19944
20379
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
19945
- await mkdir12(dir, { recursive: true });
20380
+ await mkdir13(dir, { recursive: true });
19946
20381
  const downloaded = [];
19947
20382
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
19948
20383
  let fetchedBytes = before.installedBytes;
@@ -19970,11 +20405,11 @@ async function installEditor(opts = {}) {
19970
20405
  if (digest2 !== expected.sha256) {
19971
20406
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
19972
20407
  }
19973
- const final = path36.join(dir, name);
20408
+ const final = path39.join(dir, name);
19974
20409
  const tmp = `${final}.${process.pid}.part`;
19975
20410
  try {
19976
- await writeFile17(tmp, bytes);
19977
- await rename10(tmp, final);
20411
+ await writeFile18(tmp, bytes);
20412
+ await rename11(tmp, final);
19978
20413
  } finally {
19979
20414
  await rm12(tmp, { force: true });
19980
20415
  }
@@ -20016,12 +20451,12 @@ var EDITOR_CONTENT_TYPES = {
20016
20451
  ".json": "application/json; charset=utf-8"
20017
20452
  };
20018
20453
  function editorContentType(name) {
20019
- return EDITOR_CONTENT_TYPES[path36.extname(name).toLowerCase()] ?? null;
20454
+ return EDITOR_CONTENT_TYPES[path39.extname(name).toLowerCase()] ?? null;
20020
20455
  }
20021
20456
 
20022
20457
  // src/gallery/editor.ts
20023
- import { readFile as readFile28 } from "fs/promises";
20024
- import path37 from "path";
20458
+ import { readFile as readFile29 } from "fs/promises";
20459
+ import path40 from "path";
20025
20460
  function editorRoute(release, name = "index.html") {
20026
20461
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
20027
20462
  }
@@ -20094,7 +20529,7 @@ function createGalleryEditorHandlers(opts = {}) {
20094
20529
  if (!status.installed) return null;
20095
20530
  let bytes;
20096
20531
  try {
20097
- bytes = await readFile28(path37.join(dir, name));
20532
+ bytes = await readFile29(path40.join(dir, name));
20098
20533
  } catch {
20099
20534
  verified = null;
20100
20535
  return null;
@@ -20111,7 +20546,7 @@ function createGalleryEditorHandlers(opts = {}) {
20111
20546
  // src/gallery/server.ts
20112
20547
  import { randomBytes } from "crypto";
20113
20548
  import { createServer as createServer2 } from "http";
20114
- import { readFile as readFile29 } from "fs/promises";
20549
+ import { readFile as readFile30 } from "fs/promises";
20115
20550
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
20116
20551
  var EDITOR_CSP = [
20117
20552
  "default-src 'self'",
@@ -20292,7 +20727,7 @@ async function serveGallery(opts) {
20292
20727
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
20293
20728
  if (!asset) return fail(404, "no such review asset");
20294
20729
  try {
20295
- const bytes = await readFile29(asset.path);
20730
+ const bytes = await readFile30(asset.path);
20296
20731
  res.writeHead(200, {
20297
20732
  "Content-Type": asset.contentType,
20298
20733
  "Cache-Control": "no-store",
@@ -20375,7 +20810,7 @@ async function serveGallery(opts) {
20375
20810
  if (!asset) return fail(404, "no such gallery media");
20376
20811
  let bytes;
20377
20812
  try {
20378
- bytes = await readFile29(asset.path);
20813
+ bytes = await readFile30(asset.path);
20379
20814
  } catch {
20380
20815
  return fail(404, "gallery media is no longer on disk; refresh the page");
20381
20816
  }
@@ -20482,7 +20917,7 @@ function createGenerateHandlers(opts) {
20482
20917
  const busy = /* @__PURE__ */ new Map();
20483
20918
  for (const job of jobs.values()) {
20484
20919
  if (job.phase === "done" || job.phase === "failed") continue;
20485
- for (const key of job.keys) busy.set(`${job.project ?? ""}:${key}`, job.id);
20920
+ for (const key2 of job.keys) busy.set(`${job.project ?? ""}:${key2}`, job.id);
20486
20921
  }
20487
20922
  return busy;
20488
20923
  };
@@ -20525,7 +20960,7 @@ function createGenerateHandlers(opts) {
20525
20960
  });
20526
20961
  say(job, `${providerId}: ${res.completed} completed, ${res.review} awaiting review, ${res.failed} failed, ${res.stillRunning} still running`);
20527
20962
  }
20528
- job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key) => ctx.lock.entries[key]?.status === "review");
20963
+ job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key2) => ctx.lock.entries[key2]?.status === "review");
20529
20964
  job.phase = "fetching";
20530
20965
  for (const [providerId, providerSpecs] of groupByRecordedProvider(specs, ctx.lock)) {
20531
20966
  const provider = opts.providerFor(job.project ?? void 0, providerId);
@@ -20610,7 +21045,7 @@ function createGenerateHandlers(opts) {
20610
21045
  job.finishedAt = null;
20611
21046
  const next = await opts.loadProject(job.project ?? void 0);
20612
21047
  const byKey = new Map(next.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
20613
- const nextSpecs = job.keys.map((key) => byKey.get(key)).filter((spec) => Boolean(spec));
21048
+ const nextSpecs = job.keys.map((key2) => byKey.get(key2)).filter((spec) => Boolean(spec));
20614
21049
  const plan = await buildPlan(nextSpecs, next.lock);
20615
21050
  if (!plan.actionable.length) return finish();
20616
21051
  for (const group of plan.groups) {
@@ -20677,21 +21112,21 @@ function createGenerateHandlers(opts) {
20677
21112
  const ctx = await opts.loadProject(request.project);
20678
21113
  const byKey = new Map(ctx.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
20679
21114
  const specs = [];
20680
- for (const key of request.keys) {
20681
- const spec = byKey.get(key);
20682
- if (!spec) throw new GenerateRequestError(`"${key}" is not declared by the manifest`);
21115
+ for (const key2 of request.keys) {
21116
+ const spec = byKey.get(key2);
21117
+ if (!spec) throw new GenerateRequestError(`"${key2}" is not declared by the manifest`);
20683
21118
  specs.push(spec);
20684
21119
  }
20685
21120
  const busy = busyKeys();
20686
- for (const key of request.keys) {
20687
- const holder = busy.get(`${request.project ?? ""}:${key}`);
20688
- if (holder) throw new GenerateRequestError(`"${key}" is already being worked on by job ${holder}`, 409);
21121
+ for (const key2 of request.keys) {
21122
+ const holder = busy.get(`${request.project ?? ""}:${key2}`);
21123
+ if (holder) throw new GenerateRequestError(`"${key2}" is already being worked on by job ${holder}`, 409);
20689
21124
  }
20690
21125
  if (request.restore) {
20691
- for (const key of request.keys) {
20692
- const entry = ctx.lock.entries[key];
21126
+ for (const key2 of request.keys) {
21127
+ const entry = ctx.lock.entries[key2];
20693
21128
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
20694
- throw new GenerateRequestError(`"${key}" has no downloaded output recorded to restore`);
21129
+ throw new GenerateRequestError(`"${key2}" has no downloaded output recorded to restore`);
20695
21130
  }
20696
21131
  }
20697
21132
  }
@@ -20785,19 +21220,19 @@ function createGenerateHandlers(opts) {
20785
21220
  }
20786
21221
 
20787
21222
  // src/pipeline/salvage.ts
20788
- import { readFile as readFile30 } from "fs/promises";
20789
- import { existsSync as existsSync33 } from "fs";
20790
- import path38 from "path";
21223
+ import { readFile as readFile31 } from "fs/promises";
21224
+ import { existsSync as existsSync35 } from "fs";
21225
+ import path41 from "path";
20791
21226
  function providerClaimId(provider, objectId) {
20792
21227
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
20793
21228
  }
20794
21229
  async function loadClaims(lockPaths, opts = {}) {
20795
21230
  const claimed = /* @__PURE__ */ new Set();
20796
21231
  for (const p of lockPaths) {
20797
- if (!existsSync33(p)) throw new Error(`Claim lockfile not found: ${p}`);
21232
+ if (!existsSync35(p)) throw new Error(`Claim lockfile not found: ${p}`);
20798
21233
  let parsed;
20799
21234
  try {
20800
- parsed = parseLock(JSON.parse(await readFile30(p, "utf8")));
21235
+ parsed = parseLock(JSON.parse(await readFile31(p, "utf8")));
20801
21236
  } catch {
20802
21237
  throw new Error(`Claim lockfile is malformed: ${p}`);
20803
21238
  }
@@ -20901,20 +21336,20 @@ function matchOrphanStyle(prompt, manifest) {
20901
21336
  return matchStyleByPattern(prompt, manifest);
20902
21337
  }
20903
21338
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
20904
- const own = path38.resolve(ownManifestPath);
21339
+ const own = path41.resolve(ownManifestPath);
20905
21340
  const siblingManifestPaths = [
20906
21341
  .../* @__PURE__ */ new Set([
20907
21342
  ...workspaceManifestPaths,
20908
- ...claimPaths.map((c) => path38.join(path38.dirname(path38.resolve(c)), "pixelkiln.manifest.json"))
21343
+ ...claimPaths.map((c) => path41.join(path41.dirname(path41.resolve(c)), "pixelkiln.manifest.json"))
20909
21344
  ])
20910
21345
  ];
20911
21346
  const siblings = [];
20912
21347
  for (const siblingManifestPath of siblingManifestPaths) {
20913
- if (path38.resolve(siblingManifestPath) === own) continue;
20914
- if (!existsSync33(siblingManifestPath)) continue;
21348
+ if (path41.resolve(siblingManifestPath) === own) continue;
21349
+ if (!existsSync35(siblingManifestPath)) continue;
20915
21350
  try {
20916
21351
  const { manifest } = await loadManifest(siblingManifestPath);
20917
- siblings.push({ label: path38.basename(path38.dirname(siblingManifestPath)), manifest });
21352
+ siblings.push({ label: path41.basename(path41.dirname(siblingManifestPath)), manifest });
20918
21353
  } catch {
20919
21354
  }
20920
21355
  }
@@ -20934,10 +21369,10 @@ function groupOrphansByStyle(orphans, manifest, siblings = []) {
20934
21369
  }
20935
21370
  const sibling = siblings.find((s) => matchStyleByPattern(o.prompt, s.manifest));
20936
21371
  if (sibling) {
20937
- const key = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
20938
- const list = elsewhere.get(key) ?? [];
21372
+ const key2 = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
21373
+ const list = elsewhere.get(key2) ?? [];
20939
21374
  list.push(o);
20940
- elsewhere.set(key, list);
21375
+ elsewhere.set(key2, list);
20941
21376
  continue;
20942
21377
  }
20943
21378
  if (ownStyleIds.length <= 1 && ownStyleIds[0]) matched.get(ownStyleIds[0]).push(o);
@@ -21034,8 +21469,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
21034
21469
  }
21035
21470
 
21036
21471
  // src/pick/salvage-server.ts
21037
- import { mkdir as mkdir13, writeFile as writeFile18, readFile as readFile31 } from "fs/promises";
21038
- import path39 from "path";
21472
+ import { mkdir as mkdir14, writeFile as writeFile19, readFile as readFile32 } from "fs/promises";
21473
+ import path42 from "path";
21039
21474
 
21040
21475
  // src/pick/salvage-sheet.ts
21041
21476
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -21201,7 +21636,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21201
21636
  });
21202
21637
  const html = renderSalvageSheet(orphans, {
21203
21638
  styleId: ctx.styleId,
21204
- importDir: path39.relative(process.cwd(), ctx.importDir) || "."
21639
+ importDir: path42.relative(process.cwd(), ctx.importDir) || "."
21205
21640
  });
21206
21641
  const byId = new Map(orphans.map((o) => [o.id, o]));
21207
21642
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -21257,10 +21692,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21257
21692
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
21258
21693
  decodePng(buf);
21259
21694
  const assetId = idFromPrompt(orphan.prompt, taken);
21260
- const rel = path39.join("_salvaged", `${assetId}.png`);
21261
- const outFile = path39.resolve(ctx.importDir, rel);
21262
- await mkdir13(path39.dirname(outFile), { recursive: true });
21263
- await writeFile18(outFile, buf);
21695
+ const rel = path42.join("_salvaged", `${assetId}.png`);
21696
+ const outFile = path42.resolve(ctx.importDir, rel);
21697
+ await mkdir14(path42.dirname(outFile), { recursive: true });
21698
+ await writeFile19(outFile, buf);
21264
21699
  ctx.manifest.assets[assetId] = {
21265
21700
  prompt: orphan.prompt,
21266
21701
  promptByStyle: {},
@@ -21292,7 +21727,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21292
21727
  sourceUrl: durableSource,
21293
21728
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
21294
21729
  outputs: [{
21295
- path: portableOutputPath(outFile, path39.dirname(ctx.manifestPath)),
21730
+ path: portableOutputPath(outFile, path42.dirname(ctx.manifestPath)),
21296
21731
  sha256: sha256(buf)
21297
21732
  }],
21298
21733
  submittedAt: orphan.createdAt,
@@ -21316,9 +21751,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
21316
21751
  }
21317
21752
  }
21318
21753
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
21319
- const raw = JSON.parse(await readFile31(ctx.manifestPath, "utf8"));
21754
+ const raw = JSON.parse(await readFile32(ctx.manifestPath, "utf8"));
21320
21755
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
21321
- await writeFile18(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
21756
+ await writeFile19(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
21322
21757
  await saveLock(ctx.lockPath, ctx.lock);
21323
21758
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
21324
21759
  return result;
@@ -21427,6 +21862,8 @@ async function workspaceStatus(ws, dir) {
21427
21862
  }
21428
21863
  export {
21429
21864
  AssetBatchSchema,
21865
+ AssetDeriveSchema,
21866
+ AssetExternalSchema,
21430
21867
  AssetSchema,
21431
21868
  AssetVfxSchema,
21432
21869
  BudgetError,
@@ -21468,6 +21905,7 @@ export {
21468
21905
  InheritedStyleSchema,
21469
21906
  LockEntrySchema,
21470
21907
  LockHistoryEntrySchema,
21908
+ LockOriginSchema,
21471
21909
  LockSchema,
21472
21910
  LockTerrainSettingsSchema,
21473
21911
  MAX_DOWNLOAD_BYTES,