@joycostudio/chopper 0.8.0 → 0.9.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.
@@ -128,6 +128,9 @@ function recipeShapeIssue(recipe) {
128
128
  if (!Array.isArray(selector[valueField])) return "Texture recipe selectors are malformed";
129
129
  const encodingIssue2 = encodingShapeIssue(entry.encode);
130
130
  if (encodingIssue2) return encodingIssue2;
131
+ if (entry.encode.codec === "ktx2" && entry.encode.mode === "raw") {
132
+ return `Texture recipe "${entry.label}" uses raw RGBA8, which KHR_texture_basisu does not cover; raw mode is only supported for standalone image recipes`;
133
+ }
131
134
  }
132
135
  if (candidate.geometry !== void 0 && candidate.geometry !== false && (!candidate.geometry || typeof candidate.geometry !== "object" || !["draco", "meshopt"].includes(String(candidate.geometry.codec)))) {
133
136
  return "GLB geometry must be false, Draco, or Meshopt";
@@ -148,15 +151,18 @@ function encodingShapeIssue(encoding) {
148
151
  if (!["webp", "avif", "jpeg", "png", "ktx2"].includes(String(candidate.codec))) {
149
152
  return `Unsupported image codec: ${String(candidate.codec)}`;
150
153
  }
151
- if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s" && candidate.mode !== "uastc-hdr") {
154
+ if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s" && candidate.mode !== "raw" && candidate.mode !== "uastc-hdr") {
152
155
  return `Unsupported KTX2 mode: ${String(candidate.mode)}`;
153
156
  }
154
157
  if (candidate.codec === "ktx2" && candidate.mode === "uastc-hdr" && candidate.maxSize !== void 0) {
155
158
  return "UASTC HDR does not support maxSize; resizing requires a decoded 8-bit image. Author the source at its target resolution.";
156
159
  }
157
- const allowedFields = candidate.codec === "webp" ? ["codec", "maxSize", "quality", "effort", "lossless", "nearLossless"] : candidate.codec === "avif" ? ["codec", "maxSize", "quality", "effort", "lossless", "chromaSubsampling"] : candidate.codec === "jpeg" ? ["codec", "maxSize", "quality", "chromaSubsampling"] : candidate.codec === "png" ? ["codec", "maxSize"] : candidate.mode === "uastc" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "level", "mipmaps", "zstd", "rdo"] : candidate.mode === "etc1s" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "quality", "compression", "mipmaps"] : ["codec", "mode", "level", "mipmaps", "zstd"];
160
+ const allowedFields = candidate.codec === "webp" ? ["codec", "maxSize", "quality", "effort", "lossless", "nearLossless"] : candidate.codec === "avif" ? ["codec", "maxSize", "quality", "effort", "lossless", "chromaSubsampling"] : candidate.codec === "jpeg" ? ["codec", "maxSize", "quality", "chromaSubsampling"] : candidate.codec === "png" ? ["codec", "maxSize"] : candidate.mode === "uastc" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "level", "mipmaps", "zstd", "rdo"] : candidate.mode === "etc1s" ? ["codec", "mode", "maxSize", "colorSpace", "normalMap", "quality", "compression", "mipmaps"] : candidate.mode === "raw" ? ["codec", "mode", "colorSpace", "mipmaps", "zstd", "zstdLevel"] : ["codec", "mode", "level", "mipmaps", "zstd"];
158
161
  const unknownField = unknownFieldIssue(candidate, allowedFields, "image encoding");
159
162
  if (unknownField) return unknownField;
163
+ if (candidate.codec === "ktx2" && candidate.mode === "raw" && candidate.zstd === false && candidate.zstdLevel !== void 0) {
164
+ return "Raw KTX2 zstdLevel requires Zstandard supercompression";
165
+ }
160
166
  if (candidate.codec === "ktx2" && candidate.mode === "uastc" && candidate.rdo !== void 0) {
161
167
  if (!candidate.rdo || typeof candidate.rdo !== "object" || Array.isArray(candidate.rdo)) {
162
168
  return "UASTC RDO must be an object";
@@ -212,6 +218,18 @@ function selectorValues(selector) {
212
218
  return success(selector.indices);
213
219
  }
214
220
  function encodingIssue(encoding) {
221
+ if (encoding.codec === "ktx2" && encoding.mode === "raw") {
222
+ if (encoding.colorSpace !== void 0 && encoding.colorSpace !== "linear" && encoding.colorSpace !== "srgb") {
223
+ return "Raw KTX2 colorSpace must be linear or srgb";
224
+ }
225
+ if (encoding.mipmaps !== void 0 && encoding.mipmaps !== false) return "Raw KTX2 mipmaps must be false";
226
+ if (encoding.zstd !== void 0 && typeof encoding.zstd !== "boolean") return "Raw KTX2 zstd must be a boolean";
227
+ if (encoding.zstdLevel !== void 0) {
228
+ if (!Number.isInteger(encoding.zstdLevel) || encoding.zstdLevel < 1 || encoding.zstdLevel > 19) {
229
+ return "Raw KTX2 zstdLevel must be an integer between 1 and 19";
230
+ }
231
+ }
232
+ }
215
233
  if ("maxSize" in encoding && encoding.maxSize) {
216
234
  const [width, height] = encoding.maxSize;
217
235
  if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
@@ -276,6 +294,15 @@ function normalizeEncoding(encoding) {
276
294
  case "png":
277
295
  return { ...encoding };
278
296
  case "ktx2":
297
+ if (encoding.mode === "raw") {
298
+ return {
299
+ codec: "ktx2",
300
+ mode: "raw",
301
+ colorSpace: encoding.colorSpace ?? "linear",
302
+ mipmaps: false,
303
+ ...encoding.zstd === false ? { zstd: false } : { zstd: true, zstdLevel: encoding.zstdLevel ?? 19 }
304
+ };
305
+ }
279
306
  if (encoding.mode === "uastc-hdr") {
280
307
  return {
281
308
  ...encoding,
@@ -431,11 +458,18 @@ function latin1(bytes) {
431
458
 
432
459
  // package.json
433
460
  var package_default = {
434
- version: "0.8.0"};
461
+ version: "0.9.0"};
435
462
 
436
463
  // src/codecs/manifest.ts
437
- var CODEC_MANIFEST_HASH = "2046d60deb0f9f224743f4404f3c6e8ba5399f81b2811fa50466e93fce3bd322";
464
+ var CODEC_MANIFEST_HASH = "1a43d902a113a7dcfa7801bcbd90998e401898dbad555f913e1e7f4352d9c63c";
438
465
  var CODEC_ARTIFACTS = {
466
+ zstdEncoder: {
467
+ packageName: "@bokuweb/zstd-wasm",
468
+ packageVersion: "0.0.27",
469
+ packagePath: "dist/common/zstd.wasm",
470
+ publicFile: "zstd.wasm",
471
+ sha256: "80260eee5795ee8072bb5821e203730c74dca3909938f5ac1128da67f96223df"
472
+ },
439
473
  avifEncoder: {
440
474
  packageName: "@jsquash/avif",
441
475
  packageVersion: "2.1.1",
@@ -518,6 +552,172 @@ var CODEC_MANIFEST = {
518
552
  chopperVersion: package_default.version};
519
553
  var ENGINE_ID = `chopper@${package_default.version}:${CODEC_MANIFEST_HASH}`;
520
554
 
555
+ // src/codecs/raw-ktx2.ts
556
+ var IDENTIFIER = new Uint8Array([171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10]);
557
+ var HEADER_SIZE = 104;
558
+ var DFD_SIZE = 92;
559
+ function rawSourceIssue(source) {
560
+ if (source.mimeType !== "image/png" && source.mimeType !== "image/jpeg") {
561
+ return failure(
562
+ "unsupported_asset",
563
+ "Raw KTX2 requires an 8-bit PNG or JPEG source; HDR/float sources are unsupported"
564
+ );
565
+ }
566
+ if (source.mimeType === "image/png" && source.bytes.length > 24 && source.bytes[24] === 16) {
567
+ return failure("unsupported_asset", "Raw KTX2 does not support 16-bit PNG; author an RGBA8 source");
568
+ }
569
+ return void 0;
570
+ }
571
+ function rgbaDescriptor(srgb) {
572
+ const bytes = new Uint8Array(DFD_SIZE);
573
+ const view = new DataView(bytes.buffer);
574
+ view.setUint32(0, DFD_SIZE, true);
575
+ view.setUint16(8, 2, true);
576
+ view.setUint16(10, DFD_SIZE - 4, true);
577
+ bytes[12] = 1;
578
+ bytes[13] = srgb ? 1 : 0;
579
+ bytes[14] = srgb ? 2 : 1;
580
+ bytes[20] = 4;
581
+ for (let channel = 0; channel < 4; channel++) {
582
+ const offset = 28 + channel * 16;
583
+ view.setUint16(offset, channel * 8, true);
584
+ bytes[offset + 2] = 7;
585
+ bytes[offset + 3] = channel === 3 ? 15 | (srgb ? 16 : 0) : channel;
586
+ view.setUint32(offset + 12, 255, true);
587
+ }
588
+ return bytes;
589
+ }
590
+ function writeRawKtx2(width, height, payload, encoding) {
591
+ const srgb = encoding.colorSpace === "srgb";
592
+ const descriptor = rgbaDescriptor(srgb);
593
+ const orientation = new TextEncoder().encode("KTXorientation\0rd\0");
594
+ const kvdOffset = HEADER_SIZE + descriptor.length;
595
+ const kvdLength = 4 + Math.ceil(orientation.length / 4) * 4;
596
+ const levelOffset = kvdOffset + kvdLength;
597
+ const bytes = new Uint8Array(levelOffset + payload.length);
598
+ const view = new DataView(bytes.buffer);
599
+ bytes.set(IDENTIFIER);
600
+ [
601
+ srgb ? 43 : 37,
602
+ 1,
603
+ width,
604
+ height,
605
+ 0,
606
+ 0,
607
+ 1,
608
+ 1,
609
+ encoding.zstd === false ? 0 : 2,
610
+ HEADER_SIZE,
611
+ descriptor.length,
612
+ kvdOffset,
613
+ kvdLength
614
+ ].forEach((value, index) => {
615
+ view.setUint32(12 + index * 4, value, true);
616
+ });
617
+ view.setBigUint64(80, BigInt(levelOffset), true);
618
+ view.setBigUint64(88, BigInt(payload.length), true);
619
+ view.setBigUint64(96, BigInt(width * height * 4), true);
620
+ bytes.set(descriptor, HEADER_SIZE);
621
+ view.setUint32(kvdOffset, orientation.length, true);
622
+ bytes.set(orientation, kvdOffset + 4);
623
+ bytes.set(payload, levelOffset);
624
+ return bytes;
625
+ }
626
+ function validateRawKtx2(bytes, width, height, encoding) {
627
+ if (bytes.length < HEADER_SIZE || !IDENTIFIER.every((byte, i) => bytes[i] === byte)) return false;
628
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
629
+ const u32 = (offset) => view.getUint32(offset, true);
630
+ const u64 = (offset) => Number(view.getBigUint64(offset, true));
631
+ const expected = [
632
+ encoding.colorSpace === "srgb" ? 43 : 37,
633
+ 1,
634
+ width,
635
+ height,
636
+ 0,
637
+ 0,
638
+ 1,
639
+ 1,
640
+ encoding.zstd === false ? 0 : 2
641
+ ];
642
+ if (!expected.every((value, i) => u32(12 + i * 4) === value)) return false;
643
+ if (width < 1 || height < 1 || !Number.isSafeInteger(width * height * 4)) return false;
644
+ if (u64(64) !== 0 || u64(72) !== 0 || u64(96) !== width * height * 4) return false;
645
+ const dfdOffset = u32(48);
646
+ const dfdLength = u32(52);
647
+ const kvdOffset = u32(56);
648
+ const kvdLength = u32(60);
649
+ const levelOffset = u64(80);
650
+ const levelLength = u64(88);
651
+ if (dfdOffset < HEADER_SIZE || dfdOffset % 4 !== 0 || dfdLength !== DFD_SIZE || kvdOffset < dfdOffset + dfdLength || kvdOffset % 4 !== 0 || kvdLength % 4 !== 0 || levelOffset < kvdOffset + kvdLength || !Number.isSafeInteger(levelOffset) || !Number.isSafeInteger(levelLength) || levelLength < 1 || levelOffset + levelLength !== bytes.length)
652
+ return false;
653
+ if (encoding.zstd === false && (levelOffset % 4 !== 0 || levelLength !== width * height * 4)) return false;
654
+ if (!rgbaDescriptor(encoding.colorSpace === "srgb").every((byte, i) => bytes[dfdOffset + i] === byte)) return false;
655
+ let orientation;
656
+ for (let offset = kvdOffset; offset < kvdOffset + kvdLength; ) {
657
+ const length = u32(offset);
658
+ const end = offset + 4 + length;
659
+ if (length < 2 || end > kvdOffset + kvdLength) return false;
660
+ const entry = bytes.subarray(offset + 4, end);
661
+ const separator = entry.indexOf(0);
662
+ if (separator < 1) return false;
663
+ if (new TextDecoder().decode(entry.subarray(0, separator)) === "KTXorientation") {
664
+ if (orientation !== void 0) return false;
665
+ orientation = new TextDecoder().decode(entry.subarray(separator + 1));
666
+ }
667
+ offset += 4 + Math.ceil(length / 4) * 4;
668
+ }
669
+ return orientation === "rd\0";
670
+ }
671
+
672
+ // src/codecs/zstd.ts
673
+ async function createZstdEncoder(module) {
674
+ let memory;
675
+ const abort = () => {
676
+ throw new Error("Zstandard WASM aborted");
677
+ };
678
+ const instance = await WebAssembly.instantiate(module, {
679
+ a: {
680
+ a: abort,
681
+ // proc_exit
682
+ b: () => {
683
+ },
684
+ // emscripten_runtime_keepalive_clear
685
+ c: abort,
686
+ // abort_js
687
+ d: abort,
688
+ // setitimer_js (unused by the synchronous compressor)
689
+ e: (requestedSize) => {
690
+ try {
691
+ memory.grow(Math.ceil((requestedSize - memory.buffer.byteLength) / 65536));
692
+ return 1;
693
+ } catch {
694
+ return 0;
695
+ }
696
+ }
697
+ }
698
+ });
699
+ const api = instance.exports;
700
+ memory = api.f;
701
+ api.g();
702
+ return (data, level) => {
703
+ let source = 0;
704
+ let destination = 0;
705
+ try {
706
+ const capacity = api.i(data.length);
707
+ source = api.s(data.length);
708
+ destination = api.s(capacity);
709
+ if (!source || !destination) throw new Error("Could not allocate Zstandard buffers");
710
+ new Uint8Array(memory.buffer, source, data.length).set(data);
711
+ const size = api.m(destination, capacity, source, data.length, level);
712
+ if (api.h(size)) throw new Error(`Zstandard compression failed: ${size}`);
713
+ return new Uint8Array(memory.buffer, destination, size).slice();
714
+ } finally {
715
+ if (source) api.t(source);
716
+ if (destination) api.t(destination);
717
+ }
718
+ };
719
+ }
720
+
521
721
  // src/codecs/image-engine.ts
522
722
  var CodecLoadError = class extends Error {
523
723
  };
@@ -533,12 +733,11 @@ function createWasmImageEngine(loader) {
533
733
  id: ENGINE_ID,
534
734
  manifestHash: CODEC_MANIFEST_HASH,
535
735
  async inspect(source) {
536
- if (isHdrSourceMimeType(source.mimeType)) {
537
- const header = readHdrSource(source.bytes);
538
- if ("error" in header) return failure("decode_failed", header.error);
539
- return success({ width: header.width, height: header.height });
540
- }
541
736
  try {
737
+ if (isHdrSourceMimeType(source.mimeType)) {
738
+ const header = readSupportedHdrSource(source.bytes);
739
+ return success({ width: header.width, height: header.height });
740
+ }
542
741
  const image = await decodeSource(source, adapters);
543
742
  return success({ width: image.width, height: image.height });
544
743
  } catch (cause) {
@@ -548,6 +747,10 @@ function createWasmImageEngine(loader) {
548
747
  async encode(source, encoding, signal) {
549
748
  const valid = validateRecipe({ kind: "image", encode: encoding });
550
749
  if (!valid.ok) return valid;
750
+ if (encoding.codec === "ktx2" && encoding.mode === "raw") {
751
+ const issue = rawSourceIssue(source);
752
+ if (issue) return issue;
753
+ }
551
754
  const mismatch = sourcePairingIssue(source, encoding);
552
755
  if (mismatch) return mismatch;
553
756
  try {
@@ -557,8 +760,30 @@ function createWasmImageEngine(loader) {
557
760
  assertNotAborted(signal);
558
761
  return success(encoded2);
559
762
  }
560
- let image = await decodeSource(source, adapters);
763
+ let image;
764
+ try {
765
+ image = await decodeSource(source, adapters);
766
+ } catch (cause) {
767
+ if (encoding.codec === "ktx2" && encoding.mode === "raw") {
768
+ return operationFailure("decode_failed", "Could not decode image", cause);
769
+ }
770
+ throw cause;
771
+ }
561
772
  assertNotAborted(signal);
773
+ if (encoding.codec === "ktx2" && encoding.mode === "raw") {
774
+ const rgba = new Uint8Array(image.data.buffer, image.data.byteOffset, image.data.byteLength);
775
+ if (rgba.length !== image.width * image.height * 4) throw new Error("Decoder did not return RGBA8 pixels");
776
+ const compress = encoding.zstd === false ? void 0 : await adapters.zstd();
777
+ assertNotAborted(signal);
778
+ const payload = compress ? compress(rgba, encoding.zstdLevel ?? 19) : rgba;
779
+ assertNotAborted(signal);
780
+ return success({
781
+ bytes: writeRawKtx2(image.width, image.height, payload, encoding),
782
+ mimeType: outputMimeType(encoding),
783
+ width: image.width,
784
+ height: image.height
785
+ });
786
+ }
562
787
  if (encoding.maxSize) {
563
788
  image = await resizeWithin(image, encoding.maxSize, adapters);
564
789
  }
@@ -586,6 +811,7 @@ function createAdapterCache(loader) {
586
811
  let png;
587
812
  let resizeModule;
588
813
  let webp;
814
+ let zstd;
589
815
  const load = async (name) => {
590
816
  try {
591
817
  return await loader.load(name);
@@ -594,6 +820,9 @@ function createAdapterCache(loader) {
594
820
  }
595
821
  };
596
822
  return {
823
+ zstd: () => zstd ??= load("zstdEncoder").then(createZstdEncoder).catch((cause) => {
824
+ throw new CodecLoadError("Could not initialize zstdEncoder", { cause });
825
+ }),
597
826
  avif: () => avif ??= load("avifEncoder").then(
598
827
  (module) => initEmscriptenModule(avifEncoderFactory, module)
599
828
  ),
@@ -728,16 +957,20 @@ function sourcePairingIssue(source, encoding) {
728
957
  }
729
958
  return void 0;
730
959
  }
731
- async function encodeKtx2Hdr(source, encoding, wasmUrl) {
732
- const header = readHdrSource(source.bytes);
960
+ function readSupportedHdrSource(bytes) {
961
+ const header = readHdrSource(bytes);
733
962
  if ("error" in header) throw new SourceError("decode_failed", header.error);
734
963
  const texels = header.width * header.height;
735
964
  if (texels > MAX_HDR_SOURCE_TEXELS) {
736
965
  throw new SourceError(
737
966
  "unsupported_asset",
738
- `Source is ${header.width}x${header.height} (${megapixels(texels)} Mpix), over the ${megapixels(MAX_HDR_SOURCE_TEXELS)} Mpix HDR encoder limit. Reduce the total pixel count (3072x3072 and 4096x3072 both fit) or split the source into tiles.`
967
+ `Source is ${header.width}x${header.height} (${megapixels(texels)} Mpix), over the ${megapixels(MAX_HDR_SOURCE_TEXELS)} Mpix HDR source limit. Reduce the total pixel count (3072x3072 and 4096x3072 both fit) or split the source into tiles.`
739
968
  );
740
969
  }
970
+ return header;
971
+ }
972
+ async function encodeKtx2Hdr(source, encoding, wasmUrl) {
973
+ const header = readSupportedHdrSource(source.bytes);
741
974
  const bytes = await encodeToKTX2(source.bytes, {
742
975
  isHDR: true,
743
976
  imageType: header.container,
@@ -1183,6 +1416,11 @@ function createChopper(runtime) {
1183
1416
  if (kind.data !== "image" || recipe.kind !== "image") {
1184
1417
  return failure("invalid_recipe", "Recipe and input type do not match");
1185
1418
  }
1419
+ const rawEncoding = recipe.encode.codec === "ktx2" && recipe.encode.mode === "raw" ? recipe.encode : void 0;
1420
+ if (rawEncoding) {
1421
+ const issue = rawSourceIssue({ bytes: input.bytes, mimeType: imageMimeType(input) });
1422
+ if (issue) return issue;
1423
+ }
1186
1424
  const inspection = await inspectImage(input, imageMimeType(input), runtime.image);
1187
1425
  if (!inspection.ok) return inspection;
1188
1426
  const encoded = await runtime.image.encode(
@@ -1195,6 +1433,12 @@ function createChopper(runtime) {
1195
1433
  if (!hasExpectedSignature(encoded.data.bytes, encoded.data.mimeType)) {
1196
1434
  return failure("validation_failed", `Encoded bytes do not match ${encoded.data.mimeType}`);
1197
1435
  }
1436
+ if (rawEncoding && (encoded.data.mimeType !== "image/ktx2" || !validateRawKtx2(encoded.data.bytes, inspection.data.width, inspection.data.height, rawEncoding))) {
1437
+ return failure(
1438
+ "validation_failed",
1439
+ "Raw KTX2 output does not match the source dimensions or RGBA8 container contract"
1440
+ );
1441
+ }
1198
1442
  const report = createReport({
1199
1443
  recipe: normalized.data,
1200
1444
  beforeBytes: input.bytes.byteLength,
@@ -1365,7 +1609,11 @@ function validateConfig(config) {
1365
1609
  return failure("invalid_recipe", `Config rule ${index} must be an object`);
1366
1610
  }
1367
1611
  const entry = rule;
1368
- const ruleUnknownField = unknownFieldIssue(entry, ["include", "exclude", "recipe"], `config rule ${index}`);
1612
+ const ruleUnknownField = unknownFieldIssue(
1613
+ entry,
1614
+ ["include", "exclude", "recipe", "filename"],
1615
+ `config rule ${index}`
1616
+ );
1369
1617
  if (ruleUnknownField) return failure("invalid_recipe", ruleUnknownField);
1370
1618
  if (!isStringArray(entry.include)) {
1371
1619
  return failure("invalid_recipe", `Config rule ${index} include must be an array of glob patterns`);
@@ -1379,6 +1627,9 @@ function validateConfig(config) {
1379
1627
  if (invalidGlob) {
1380
1628
  return failure("invalid_recipe", `Config rule ${index} glob must be project-relative: ${invalidGlob}`);
1381
1629
  }
1630
+ if (entry.filename !== void 0 && typeof entry.filename !== "function") {
1631
+ return failure("invalid_recipe", `Config rule ${index} filename must be a function`);
1632
+ }
1382
1633
  const recipe = validateRecipe(entry.recipe);
1383
1634
  if (!recipe.ok) return recipe;
1384
1635
  }
@@ -1476,7 +1727,8 @@ function createConfigAssetPlanner(config) {
1476
1727
  for (const { rule, matches } of prepared.data.rules) {
1477
1728
  if (!matches(normalizedInput)) continue;
1478
1729
  const output = resolveOutput(rule, normalizedInput, prepared.data.outputDirectory);
1479
- planned.set(output, { input: normalizedInput, output, rule });
1730
+ if (!output.ok) return output;
1731
+ planned.set(output.data, { input: normalizedInput, output: output.data, rule });
1480
1732
  }
1481
1733
  const outputs = [...planned.values()];
1482
1734
  return outputs.length ? success({ kind: "source", input: normalizedInput, outputs }) : success({ kind: "unmatched", input: normalizedInput });
@@ -1526,24 +1778,26 @@ function resolveOutput(rule, input, outputDirectory) {
1526
1778
  const dot = base.lastIndexOf(".");
1527
1779
  const name = dot <= 0 ? base : base.slice(0, dot);
1528
1780
  const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
1529
- return `${directory ? `${directory}/` : ""}${outputDirectory}/${name}${extension}`;
1781
+ let filename = name;
1782
+ if (rule.filename) {
1783
+ try {
1784
+ filename = rule.filename({ input, directory, name, recipe: rule.recipe });
1785
+ } catch (cause) {
1786
+ return failure("invalid_recipe", `Config rule filename threw for ${input}`, cause);
1787
+ }
1788
+ if (!isSafePathSegment(filename)) {
1789
+ return failure(
1790
+ "invalid_recipe",
1791
+ `Config rule filename must return exactly one safe path segment for ${input}: ${String(filename)}`
1792
+ );
1793
+ }
1794
+ }
1795
+ return success(`${directory ? `${directory}/` : ""}${outputDirectory}/${filename}${extension}`);
1530
1796
  }
1531
1797
  function isGeneratedOutput(input, outputDirectory) {
1532
1798
  return input.split("/").slice(0, -1).includes(outputDirectory);
1533
1799
  }
1534
1800
 
1535
- // src/config/index.ts
1536
- function createChopper2(config) {
1537
- const { buildDirectory = DEFAULT_BUILD_DIRECTORY, outputDirectory = DEFAULT_OUTPUT_DIRECTORY, ...rest } = config;
1538
- const defined = { buildDirectory, outputDirectory, ...rest };
1539
- const planner = createConfigAssetPlanner(defined);
1540
- Object.defineProperties(defined, {
1541
- route: { enumerable: false, value: planner.route },
1542
- resolve: { enumerable: false, value: planner.resolve }
1543
- });
1544
- return defined;
1545
- }
1546
-
1547
1801
  // src/node/batch.ts
1548
1802
  async function runConfig(options = {}) {
1549
1803
  const cwd = resolve(options.cwd ?? process.cwd());
@@ -1578,7 +1832,7 @@ async function planAssets(config, cwd) {
1578
1832
  if (isAbsolute(relativeRoot) || relativeRoot === ".." || relativeRoot.startsWith(`..${sep}`)) {
1579
1833
  return failure("invalid_recipe", `Build directory must be inside the project: ${configured.buildDirectory}`);
1580
1834
  }
1581
- const planner = createChopper2(configured);
1835
+ const planner = createConfigAssetPlanner(configured);
1582
1836
  const discoveryPatterns = configured.rules.flatMap(
1583
1837
  ({ include }) => include.filter((pattern) => !pattern.startsWith("!") || pattern.startsWith("!("))
1584
1838
  );