@joycostudio/chopper 0.4.0 → 0.5.1

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/cli/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFile, readdir, mkdir, copyFile, mkdtemp, writeFile, rename, rm } from 'fs/promises';
3
3
  import { extname, parse, join, dirname, resolve, relative, isAbsolute, sep, basename } from 'path';
4
+ import { fileURLToPath } from 'url';
4
5
  import { PropertyType, NodeIO } from '@gltf-transform/core';
5
6
  import { ALL_EXTENSIONS, EXTTextureWebP, EXTTextureAVIF, KHRTextureBasisu } from '@gltf-transform/extensions';
6
7
  import draco3d from 'draco3dgltf';
@@ -23,7 +24,6 @@ import { glob } from 'tinyglobby';
23
24
  import { createJiti } from 'jiti';
24
25
 
25
26
  // src/core/recipes.ts
26
- var RECIPE_SCHEMA_VERSION = 1;
27
27
  var COLOR_TEXTURE_SLOTS = [
28
28
  "baseColorTexture",
29
29
  "emissiveTexture",
@@ -44,7 +44,6 @@ var DATA_TEXTURE_SLOTS = [
44
44
  "iridescenceThicknessTexture"
45
45
  ];
46
46
  var DEFAULT_GLB_RECIPE = {
47
- schemaVersion: RECIPE_SCHEMA_VERSION,
48
47
  kind: "glb",
49
48
  methods: [],
50
49
  textures: [
@@ -87,7 +86,6 @@ var DEFAULT_GLB_RECIPE = {
87
86
  geometry: { codec: "draco" }
88
87
  };
89
88
  var DEFAULT_IMAGE_RECIPE = {
90
- schemaVersion: RECIPE_SCHEMA_VERSION,
91
89
  kind: "image",
92
90
  encode: { codec: "webp", quality: 85, effort: 80 }
93
91
  };
@@ -101,9 +99,133 @@ function outputMimeType(encoding) {
101
99
  return `image/${encoding.codec}`;
102
100
  }
103
101
 
102
+ // src/codecs/hdr-source.ts
103
+ var HDR_SOURCE_MIME_TYPES = {
104
+ exr: "image/x-exr",
105
+ hdr: "image/vnd.radiance"
106
+ };
107
+ function isHdrSourceMimeType(mimeType) {
108
+ return mimeType === "image/x-exr" || mimeType === "image/vnd.radiance";
109
+ }
110
+ var EXR_MAGIC = [118, 47, 49, 1];
111
+ var VERSION_NUMBER_FIELD = 255;
112
+ var NON_IMAGE_FLAG = 2048;
113
+ var MULTI_PART_FILE_FLAG = 4096;
114
+ var EXR_COMPRESSION = [
115
+ { name: "NO_COMPRESSION", supported: true },
116
+ { name: "RLE", supported: true },
117
+ { name: "ZIPS", supported: true },
118
+ { name: "ZIP", supported: true },
119
+ { name: "PIZ", supported: true },
120
+ { name: "PXR24", supported: false },
121
+ { name: "B44", supported: false },
122
+ { name: "B44A", supported: false },
123
+ { name: "DWAA", supported: false },
124
+ { name: "DWAB", supported: false }
125
+ ];
126
+ var RADIANCE_MAGIC = [35, 63];
127
+ var RADIANCE_HEADER_LIMIT = 8192;
128
+ var MAX_HDR_SOURCE_TEXELS = 12 * 1024 * 1024;
129
+ function detectHdrContainer(bytes) {
130
+ if (bytes.length >= 8 && EXR_MAGIC.every((byte, index) => bytes[index] === byte)) return "exr";
131
+ if (bytes.length >= 8 && RADIANCE_MAGIC.every((byte, index) => bytes[index] === byte)) return "hdr";
132
+ return void 0;
133
+ }
134
+ function readHdrSource(bytes) {
135
+ const container = detectHdrContainer(bytes);
136
+ if (!container) return { error: "Not an OpenEXR or Radiance HDR file" };
137
+ return container === "exr" ? readExr(bytes) : readRadiance(bytes);
138
+ }
139
+ function readExr(bytes) {
140
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
141
+ const version = view.getInt32(4, true);
142
+ if ((version & VERSION_NUMBER_FIELD) !== 2) {
143
+ return { error: `Unsupported EXR version: ${version & VERSION_NUMBER_FIELD}` };
144
+ }
145
+ if (version & MULTI_PART_FILE_FLAG) return { error: "Multi-part EXR files are not supported" };
146
+ if (version & NON_IMAGE_FLAG) return { error: "Deep EXR files are not supported" };
147
+ let size;
148
+ let compressionIssue;
149
+ let offset = 8;
150
+ while (offset < bytes.length) {
151
+ const name = readNullTerminated(bytes, offset);
152
+ if (name === void 0) return { error: "Malformed EXR header" };
153
+ if (name.value === "") break;
154
+ offset = name.next;
155
+ const type = readNullTerminated(bytes, offset);
156
+ if (type === void 0) return { error: "Malformed EXR header" };
157
+ offset = type.next;
158
+ if (offset + 4 > bytes.length) return { error: "Malformed EXR header" };
159
+ const length = view.getInt32(offset, true);
160
+ offset += 4;
161
+ if (length < 0 || offset + length > bytes.length) return { error: "Malformed EXR header" };
162
+ if (name.value === "dataWindow") {
163
+ if (type.value !== "box2i" || length !== 16) return { error: "Malformed EXR dataWindow" };
164
+ const xMin = view.getInt32(offset, true);
165
+ const yMin = view.getInt32(offset + 4, true);
166
+ const xMax = view.getInt32(offset + 8, true);
167
+ const yMax = view.getInt32(offset + 12, true);
168
+ const width = xMax - xMin + 1;
169
+ const height = yMax - yMin + 1;
170
+ if (width < 1 || height < 1) return { error: "EXR dataWindow is empty" };
171
+ size = { container: "exr", width, height };
172
+ }
173
+ if (name.value === "compression") {
174
+ if (length !== 1) return { error: "Malformed EXR compression attribute" };
175
+ compressionIssue = exrCompressionIssue(bytes[offset]);
176
+ }
177
+ offset += length;
178
+ }
179
+ if (compressionIssue) return { error: compressionIssue };
180
+ return size ?? { error: "EXR header has no dataWindow attribute" };
181
+ }
182
+ function exrCompressionIssue(code) {
183
+ const codec = EXR_COMPRESSION[code];
184
+ if (!codec) return `Unsupported EXR compression: unknown codec ${code}`;
185
+ if (codec.supported) return void 0;
186
+ const readable = EXR_COMPRESSION.filter((entry) => entry.supported).map((entry) => entry.name).join(", ");
187
+ return `EXR uses ${codec.name} compression, which the HDR encoder cannot read. Re-export with one of: ${readable}. EXR compression only affects the file on disk \u2014 it does not change the encoded KTX2.`;
188
+ }
189
+ function readRadiance(bytes) {
190
+ const text = latin1(bytes.subarray(0, RADIANCE_HEADER_LIMIT));
191
+ const lines = text.split("\n");
192
+ let index = 0;
193
+ while (index < lines.length && lines[index] !== "" && lines[index] !== "\r") index++;
194
+ index++;
195
+ while (index < lines.length && (lines[index] === "" || lines[index] === "\r")) index++;
196
+ if (index >= lines.length) return { error: "Radiance file has no resolution line" };
197
+ const resolution = /^([+-][XY])\s+(\d+)\s+([+-][XY])\s+(\d+)\s*$/.exec(lines[index].replace(/\r$/, ""));
198
+ if (!resolution) return { error: `Malformed Radiance resolution line: ${lines[index].slice(0, 40)}` };
199
+ const extents = /* @__PURE__ */ new Map([
200
+ [resolution[1][1], Number(resolution[2])],
201
+ [resolution[3][1], Number(resolution[4])]
202
+ ]);
203
+ const width = extents.get("X");
204
+ const height = extents.get("Y");
205
+ if (width === void 0 || height === void 0) {
206
+ return { error: "Radiance resolution line must pair an X and a Y axis" };
207
+ }
208
+ if (width < 1 || height < 1) return { error: "Radiance image is empty" };
209
+ return { container: "hdr", width, height };
210
+ }
211
+ function readNullTerminated(bytes, start) {
212
+ const limit = Math.min(bytes.length, start + 256);
213
+ for (let index = start; index < limit; index++) {
214
+ if (bytes[index] === 0) {
215
+ return { value: latin1(bytes.subarray(start, index)), next: index + 1 };
216
+ }
217
+ }
218
+ return void 0;
219
+ }
220
+ function latin1(bytes) {
221
+ let value = "";
222
+ for (const byte of bytes) value += String.fromCharCode(byte);
223
+ return value;
224
+ }
225
+
104
226
  // package.json
105
227
  var package_default = {
106
- version: "0.4.0"};
228
+ version: "0.5.1"};
107
229
 
108
230
  // src/codecs/manifest.ts
109
231
  var CODEC_MANIFEST_HASH = "2046d60deb0f9f224743f4404f3c6e8ba5399f81b2811fa50466e93fce3bd322";
@@ -215,13 +337,11 @@ function normalizeRecipe(value) {
215
337
  const recipe = validated.data;
216
338
  if (recipe.kind === "image") {
217
339
  return success({
218
- schemaVersion: RECIPE_SCHEMA_VERSION,
219
340
  kind: "image",
220
341
  encode: normalizeEncoding(recipe.encode)
221
342
  });
222
343
  }
223
344
  return success({
224
- schemaVersion: RECIPE_SCHEMA_VERSION,
225
345
  kind: "glb",
226
346
  methods: recipe.methods ?? [],
227
347
  textures: (recipe.textures ?? []).map((texture) => ({
@@ -275,15 +395,15 @@ function encodingShapeIssue(encoding) {
275
395
  if (!["webp", "avif", "jpeg", "png", "ktx2"].includes(String(candidate.codec))) {
276
396
  return `Unsupported image codec: ${String(candidate.codec)}`;
277
397
  }
278
- if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s") {
398
+ if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s" && candidate.mode !== "uastc-hdr") {
279
399
  return `Unsupported KTX2 mode: ${String(candidate.mode)}`;
280
400
  }
401
+ if (candidate.codec === "ktx2" && candidate.mode === "uastc-hdr" && candidate.maxSize !== void 0) {
402
+ return "UASTC HDR does not support maxSize; resizing requires a decoded 8-bit image. Author the source at its target resolution.";
403
+ }
281
404
  return void 0;
282
405
  }
283
406
  function recipeIssue(recipe) {
284
- if (recipe.schemaVersion !== RECIPE_SCHEMA_VERSION) {
285
- return `Unsupported recipe schema version: ${String(recipe.schemaVersion)}`;
286
- }
287
407
  if (recipe.kind === "image") return encodingIssue(recipe.encode);
288
408
  const labels = /* @__PURE__ */ new Set();
289
409
  const selectors = /* @__PURE__ */ new Set();
@@ -305,6 +425,9 @@ function recipeIssue(recipe) {
305
425
  }
306
426
  selectors.add(key);
307
427
  }
428
+ if (texture.encode.codec === "ktx2" && texture.encode.mode === "uastc-hdr") {
429
+ return `Texture recipe "${texture.label}" uses UASTC HDR, which KHR_texture_basisu does not cover; HDR is only supported for standalone image recipes`;
430
+ }
308
431
  const issue = encodingIssue(texture.encode);
309
432
  if (issue) return issue;
310
433
  }
@@ -326,7 +449,7 @@ function selectorValues(selector) {
326
449
  return success(selector.indices);
327
450
  }
328
451
  function encodingIssue(encoding) {
329
- if (encoding.maxSize) {
452
+ if ("maxSize" in encoding && encoding.maxSize) {
330
453
  const [width, height] = encoding.maxSize;
331
454
  if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
332
455
  return "Texture maxSize must contain positive integers";
@@ -355,6 +478,9 @@ function encodingIssue(encoding) {
355
478
  return "UASTC RDO lambda must be between 0.001 and 10";
356
479
  }
357
480
  }
481
+ if (encoding.codec === "ktx2" && encoding.mode === "uastc-hdr" && encoding.level !== void 0 && (!Number.isInteger(encoding.level) || encoding.level < 0 || encoding.level > 4)) {
482
+ return "UASTC HDR level must be an integer between 0 and 4";
483
+ }
358
484
  if (encoding.codec === "ktx2" && encoding.mode === "etc1s" && encoding.compression !== void 0 && (!Number.isInteger(encoding.compression) || encoding.compression < 0 || encoding.compression > 6)) {
359
485
  return "ETC1S compression must be an integer between 0 and 6";
360
486
  }
@@ -387,6 +513,14 @@ function normalizeEncoding(encoding) {
387
513
  case "png":
388
514
  return { ...encoding };
389
515
  case "ktx2":
516
+ if (encoding.mode === "uastc-hdr") {
517
+ return {
518
+ ...encoding,
519
+ level: encoding.level ?? 1,
520
+ mipmaps: encoding.mipmaps ?? true,
521
+ zstd: encoding.zstd ?? true
522
+ };
523
+ }
390
524
  if (encoding.mode === "uastc") {
391
525
  return {
392
526
  ...encoding,
@@ -507,8 +641,11 @@ function detectAsset(input) {
507
641
  if (input.bytes.length >= 4 && input.bytes[0] === 103 && input.bytes[1] === 108 && input.bytes[2] === 84 && input.bytes[3] === 70) {
508
642
  return success("glb");
509
643
  }
510
- if (isPng(input.bytes) || isJpeg(input.bytes)) return success("image");
511
- return failure("unsupported_asset", `Unsupported asset: ${input.fileName}; expected GLB, PNG, or JPEG`);
644
+ if (isPng(input.bytes) || isJpeg(input.bytes) || detectHdrContainer(input.bytes)) return success("image");
645
+ return failure(
646
+ "unsupported_asset",
647
+ `Unsupported asset: ${input.fileName}; expected GLB, PNG, JPEG, EXR, or Radiance HDR`
648
+ );
512
649
  }
513
650
  async function inspectImage(input, mimeType, engine) {
514
651
  const dimensions = await engine.inspect({ bytes: input.bytes, mimeType });
@@ -522,6 +659,8 @@ async function inspectImage(input, mimeType, engine) {
522
659
  });
523
660
  }
524
661
  function imageMimeType(input) {
662
+ const hdr = detectHdrContainer(input.bytes);
663
+ if (hdr) return HDR_SOURCE_MIME_TYPES[hdr];
525
664
  return isPng(input.bytes) ? "image/png" : "image/jpeg";
526
665
  }
527
666
  function isPng(bytes) {
@@ -819,12 +958,23 @@ function inspectDocument(document, byteLength) {
819
958
  }
820
959
  var CodecLoadError = class extends Error {
821
960
  };
961
+ var SourceError = class extends Error {
962
+ constructor(code, message) {
963
+ super(message);
964
+ this.code = code;
965
+ }
966
+ };
822
967
  function createWasmImageEngine(loader) {
823
968
  const adapters = createAdapterCache(loader);
824
969
  return {
825
970
  id: ENGINE_ID,
826
971
  manifestHash: CODEC_MANIFEST_HASH,
827
972
  async inspect(source) {
973
+ if (isHdrSourceMimeType(source.mimeType)) {
974
+ const header = readHdrSource(source.bytes);
975
+ if ("error" in header) return failure("decode_failed", header.error);
976
+ return success({ width: header.width, height: header.height });
977
+ }
828
978
  try {
829
979
  const image = await decodeSource(source, adapters);
830
980
  return success({ width: image.width, height: image.height });
@@ -833,10 +983,17 @@ function createWasmImageEngine(loader) {
833
983
  }
834
984
  },
835
985
  async encode(source, encoding, signal) {
836
- const valid = validateRecipe({ schemaVersion: 1, kind: "image", encode: encoding });
986
+ const valid = validateRecipe({ kind: "image", encode: encoding });
837
987
  if (!valid.ok) return valid;
988
+ const mismatch = sourcePairingIssue(source, encoding);
989
+ if (mismatch) return mismatch;
838
990
  try {
839
991
  assertNotAborted2(signal);
992
+ if (isHdrEncoding(encoding)) {
993
+ const encoded2 = await encodeKtx2Hdr(source, encoding, await loader.basisEncoderUrl());
994
+ assertNotAborted2(signal);
995
+ return success(encoded2);
996
+ }
840
997
  let image = await decodeSource(source, adapters);
841
998
  assertNotAborted2(signal);
842
999
  if (encoding.maxSize) {
@@ -991,6 +1148,45 @@ async function encodeRaster(image, encoding, adapters) {
991
1148
  }
992
1149
  return { bytes: toUint8Array(bytes), mimeType: outputMimeType(encoding) };
993
1150
  }
1151
+ var megapixels = (texels) => (texels / 1e6).toFixed(1);
1152
+ function isHdrEncoding(encoding) {
1153
+ return encoding.codec === "ktx2" && encoding.mode === "uastc-hdr";
1154
+ }
1155
+ function sourcePairingIssue(source, encoding) {
1156
+ const isHdrSource = isHdrSourceMimeType(source.mimeType);
1157
+ if (isHdrEncoding(encoding) && !isHdrSource) {
1158
+ return failure("invalid_recipe", `UASTC HDR requires an EXR or Radiance HDR source; received ${source.mimeType}`);
1159
+ }
1160
+ if (isHdrSource && !isHdrEncoding(encoding)) {
1161
+ return failure(
1162
+ "invalid_recipe",
1163
+ "HDR sources can only be encoded as KTX2 with mode 'uastc-hdr'; chopper does not decode HDR pixels"
1164
+ );
1165
+ }
1166
+ return void 0;
1167
+ }
1168
+ async function encodeKtx2Hdr(source, encoding, wasmUrl) {
1169
+ const header = readHdrSource(source.bytes);
1170
+ if ("error" in header) throw new SourceError("decode_failed", header.error);
1171
+ const texels = header.width * header.height;
1172
+ if (texels > MAX_HDR_SOURCE_TEXELS) {
1173
+ throw new SourceError(
1174
+ "unsupported_asset",
1175
+ `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.`
1176
+ );
1177
+ }
1178
+ const bytes = await encodeToKTX2(source.bytes, {
1179
+ isHDR: true,
1180
+ imageType: header.container,
1181
+ isUASTC: true,
1182
+ hdrQualityLevel: encoding.level ?? 1,
1183
+ needSupercompression: encoding.zstd ?? true,
1184
+ generateMipmap: encoding.mipmaps ?? true,
1185
+ isKTX2File: true,
1186
+ wasmUrl
1187
+ });
1188
+ return { bytes, mimeType: outputMimeType(encoding), width: header.width, height: header.height };
1189
+ }
994
1190
  async function encodeKtx2(source, image, encoding, wasmUrl) {
995
1191
  const srgb = encoding.colorSpace !== "linear";
996
1192
  const bytes = await encodeToKTX2(source.bytes, {
@@ -1016,7 +1212,9 @@ async function encodeKtx2(source, image, encoding, wasmUrl) {
1016
1212
  return { bytes, mimeType: outputMimeType(encoding) };
1017
1213
  }
1018
1214
  function operationFailure(code, message, cause) {
1019
- return cause instanceof CodecLoadError ? failure("codec_load_failed", cause.message, cause.cause) : failure(code, message, cause);
1215
+ if (cause instanceof CodecLoadError) return failure("codec_load_failed", cause.message, cause.cause);
1216
+ if (cause instanceof SourceError) return failure(cause.code, cause.message);
1217
+ return failure(code, message, cause);
1020
1218
  }
1021
1219
  function assertNotAborted2(signal) {
1022
1220
  if (signal?.aborted) throw new DOMException("Optimization was aborted", "AbortError");
@@ -1189,22 +1387,22 @@ async function planAssets(config, cwd) {
1189
1387
  });
1190
1388
  }
1191
1389
  }
1192
- const outputs = /* @__PURE__ */ new Map();
1390
+ const resolved = /* @__PURE__ */ new Map();
1193
1391
  const inputs = new Set(planned.map(({ input }) => input));
1194
1392
  for (const asset of planned) {
1195
- const owner = outputs.get(asset.output);
1196
- if (owner && owner !== asset.input) {
1393
+ const owner = resolved.get(asset.output);
1394
+ if (owner && owner.input !== asset.input) {
1197
1395
  return failure(
1198
1396
  "invalid_recipe",
1199
- `Output collision: ${relative(cwd, owner)} and ${relative(cwd, asset.input)} both write ${relative(cwd, asset.output)}`
1397
+ `Output collision: ${relative(cwd, owner.input)} and ${relative(cwd, asset.input)} both write ${relative(cwd, asset.output)}`
1200
1398
  );
1201
1399
  }
1202
1400
  if (asset.output !== asset.input && inputs.has(asset.output)) {
1203
1401
  return failure("invalid_recipe", `Output loop: ${relative(cwd, asset.output)} is also a matched input`);
1204
1402
  }
1205
- outputs.set(asset.output, asset.input);
1403
+ resolved.set(asset.output, asset);
1206
1404
  }
1207
- return success(planned);
1405
+ return success([...resolved.values()]);
1208
1406
  }
1209
1407
  async function executeAsset(asset, mode, cwd, chopper2) {
1210
1408
  try {
@@ -1334,28 +1532,113 @@ async function optimizeFile({
1334
1532
  }
1335
1533
 
1336
1534
  // src/cli/index.ts
1535
+ var CONFIG_OPTION = " --config <file> Config file to load. Defaults to chopper.config.ts.";
1536
+ var COMMANDS = {
1537
+ inspect: {
1538
+ summary: "Print an asset's inspection report as JSON",
1539
+ usage: "chopper inspect <asset>",
1540
+ options: [],
1541
+ positionals: 1,
1542
+ help: "Reads <asset> and prints what Chopper detects about it as JSON on stdout.",
1543
+ run: inspect
1544
+ },
1545
+ optimize: {
1546
+ summary: "Optimize a single asset with a recipe",
1547
+ usage: "chopper optimize <asset> [output] [--recipe <file>]",
1548
+ options: ["--recipe"],
1549
+ positionals: 2,
1550
+ help: [
1551
+ "Options:",
1552
+ " --recipe <file> JSON recipe to apply. Defaults to the built-in GLB recipe",
1553
+ " for .glb inputs and the built-in image recipe otherwise.",
1554
+ "",
1555
+ "Omitting [output] writes <name>.optimized<ext> beside the input, where <ext>",
1556
+ "comes from the recipe's encode target."
1557
+ ].join("\n"),
1558
+ run: optimize
1559
+ },
1560
+ run: {
1561
+ summary: "Optimize every asset the config matches and write the results",
1562
+ usage: "chopper run [--config <file>]",
1563
+ options: ["--config"],
1564
+ positionals: 0,
1565
+ help: [
1566
+ "Options:",
1567
+ CONFIG_OPTION,
1568
+ "",
1569
+ "Optimizes each matched asset and writes it into the config output directory",
1570
+ "through a temporary sibling and an atomic rename. Prints the batch report as",
1571
+ "JSON and exits 1 when any asset fails."
1572
+ ].join("\n"),
1573
+ run: (args) => batch("write", args)
1574
+ },
1575
+ check: {
1576
+ summary: "Verify optimized outputs are up to date without writing",
1577
+ usage: "chopper check [--config <file>]",
1578
+ options: ["--config"],
1579
+ positionals: 0,
1580
+ help: [
1581
+ "Options:",
1582
+ CONFIG_OPTION,
1583
+ "",
1584
+ "Optimizes each matched asset in memory and compares the bytes against the",
1585
+ "existing output, marking it current or stale. Writes nothing. Prints the batch",
1586
+ "report as JSON and exits 1 when any asset is stale or fails, which makes it",
1587
+ "suitable as a CI gate."
1588
+ ].join("\n"),
1589
+ run: (args) => batch("check", args)
1590
+ },
1591
+ report: {
1592
+ summary: "Summarize what the config matches without writing or comparing",
1593
+ usage: "chopper report [--config <file>]",
1594
+ options: ["--config"],
1595
+ positionals: 0,
1596
+ help: [
1597
+ "Options:",
1598
+ CONFIG_OPTION,
1599
+ "",
1600
+ "Optimizes each matched asset in memory and reports its before and after sizes",
1601
+ "and the engine used. Writes nothing and compares nothing. Prints the batch",
1602
+ "report as JSON and exits 1 when any asset fails."
1603
+ ].join("\n"),
1604
+ run: (args) => batch("report", args)
1605
+ },
1606
+ codecs: {
1607
+ summary: "Copy the package-owned codec files into a public directory",
1608
+ usage: "chopper codecs sync [directory]",
1609
+ options: [],
1610
+ positionals: 2,
1611
+ help: [
1612
+ "Copies the codec files this package pins into [directory] so the browser host",
1613
+ "can load them. Defaults to public/chopper-codecs."
1614
+ ].join("\n"),
1615
+ run: codecs
1616
+ }
1617
+ };
1337
1618
  async function main() {
1338
- const [command, ...args] = process.argv.slice(2);
1339
- switch (command) {
1340
- case "inspect":
1341
- return inspect(args);
1342
- case "optimize":
1343
- return optimize(args);
1344
- case "run":
1345
- return batch("write", args);
1346
- case "check":
1347
- return batch("check", args);
1348
- case "report":
1349
- return batch("report", args);
1350
- case "codecs":
1351
- return codecs(args);
1352
- default:
1353
- throw new Error(usage());
1619
+ const argv = process.argv.slice(2);
1620
+ const [command, ...rest] = argv;
1621
+ if (command === void 0 || command === "help" || command === "--help" || command === "-h") {
1622
+ const topic = command === "help" && !isHelpFlag(rest[0]) ? rest[0] : void 0;
1623
+ if (topic !== void 0 && !(topic in COMMANDS)) throw new Error(unknownCommand(topic));
1624
+ console.log(topic === void 0 ? usage() : commandUsage(topic));
1625
+ return;
1626
+ }
1627
+ if (command === "--version" || command === "-v") {
1628
+ console.log(await packageVersion());
1629
+ return;
1630
+ }
1631
+ const entry = COMMANDS[command];
1632
+ if (!entry) throw new Error(unknownCommand(command));
1633
+ const separator = rest.indexOf("--");
1634
+ if ((separator === -1 ? rest : rest.slice(0, separator)).some(isHelpFlag)) {
1635
+ console.log(commandUsage(command));
1636
+ return;
1354
1637
  }
1638
+ return entry.run(parseArgs(rest, command));
1355
1639
  }
1356
1640
  async function inspect(args) {
1357
- const input = args[0];
1358
- if (!input) throw new Error("Usage: chopper inspect <asset>");
1641
+ const input = args.positional("asset");
1359
1642
  const result = await createNodeChopper().inspect({
1360
1643
  bytes: new Uint8Array(await readFile(input)),
1361
1644
  fileName: input
@@ -1364,13 +1647,10 @@ async function inspect(args) {
1364
1647
  console.log(JSON.stringify(result.data, inspectionReplacer, 2));
1365
1648
  }
1366
1649
  async function optimize(args) {
1367
- const input = args[0];
1368
- if (!input) {
1369
- throw new Error("Usage: chopper optimize <asset> [output] [--recipe file.json]");
1370
- }
1371
- const recipePath = flag(args, "--recipe");
1650
+ const input = args.positional("asset");
1651
+ const recipePath = args.option("--recipe");
1372
1652
  const recipe = recipePath ? JSON.parse(await readFile(recipePath, "utf8")) : extname(input).toLowerCase() === ".glb" ? DEFAULT_GLB_RECIPE : DEFAULT_IMAGE_RECIPE;
1373
- const positionalOutput = args[1]?.startsWith("--") ? void 0 : args[1];
1653
+ const positionalOutput = args.positionals[1];
1374
1654
  const parsed = parse(input);
1375
1655
  const extension = recipe.kind === "glb" ? ".glb" : outputExtension(recipe.encode);
1376
1656
  const output = positionalOutput ?? join(dirname(input), `${parsed.name}.optimized${extension}`);
@@ -1383,7 +1663,7 @@ async function optimize(args) {
1383
1663
  async function batch(mode, args) {
1384
1664
  const result = await runConfig({
1385
1665
  mode,
1386
- configPath: flag(args, "--config")
1666
+ configPath: args.option("--config")
1387
1667
  });
1388
1668
  if (!result.ok) return fail(result.error.message);
1389
1669
  console.log(JSON.stringify(result.data, null, 2));
@@ -1392,17 +1672,61 @@ async function batch(mode, args) {
1392
1672
  }
1393
1673
  }
1394
1674
  async function codecs(args) {
1395
- if (args[0] !== "sync") {
1396
- throw new Error("Usage: chopper codecs sync <directory>");
1675
+ if (args.positionals[0] !== "sync") {
1676
+ throw new Error(commandUsage("codecs"));
1397
1677
  }
1398
- const output = args[1] ?? "public/chopper-codecs";
1678
+ const output = args.positionals[1] ?? "public/chopper-codecs";
1399
1679
  const result = await syncCodecs(output);
1400
1680
  if (!result.ok) return fail(result.error.message);
1401
1681
  console.log(`Copied ${result.data.files.length} codec files to ${result.data.directory}`);
1402
1682
  }
1403
- function flag(args, name) {
1404
- const index = args.indexOf(name);
1405
- return index === -1 ? void 0 : args[index + 1];
1683
+ function isHelpFlag(arg) {
1684
+ return arg === "--help" || arg === "-h";
1685
+ }
1686
+ function parseArgs(args, command) {
1687
+ const { options, positionals: budget } = COMMANDS[command];
1688
+ const positionals = [];
1689
+ const values = /* @__PURE__ */ new Map();
1690
+ for (let index = 0; index < args.length; index += 1) {
1691
+ const arg = args[index];
1692
+ if (arg === "--") {
1693
+ positionals.push(...args.slice(index + 1));
1694
+ break;
1695
+ }
1696
+ if (!arg.startsWith("-") || arg === "-") {
1697
+ positionals.push(arg);
1698
+ continue;
1699
+ }
1700
+ if (!options.includes(arg)) {
1701
+ throw new Error(`Unknown option ${arg}
1702
+
1703
+ ${commandUsage(command)}`);
1704
+ }
1705
+ const value = args[index + 1];
1706
+ if (value === void 0 || value.startsWith("-")) {
1707
+ throw new Error(`Option ${arg} requires a value
1708
+
1709
+ ${commandUsage(command)}`);
1710
+ }
1711
+ values.set(arg, value);
1712
+ index += 1;
1713
+ }
1714
+ if (positionals.length > budget) {
1715
+ throw new Error(`Unexpected argument ${positionals[budget]}
1716
+
1717
+ ${commandUsage(command)}`);
1718
+ }
1719
+ return {
1720
+ positionals,
1721
+ option: (name) => values.get(name),
1722
+ positional: (name) => {
1723
+ const value = positionals[0];
1724
+ if (value === void 0) throw new Error(`Missing <${name}>
1725
+
1726
+ ${commandUsage(command)}`);
1727
+ return value;
1728
+ }
1729
+ };
1406
1730
  }
1407
1731
  function inspectionReplacer(key, value) {
1408
1732
  return key === "bytes" && value instanceof Uint8Array ? { byteLength: value.byteLength } : value;
@@ -1411,16 +1735,38 @@ function fail(message) {
1411
1735
  console.error(message);
1412
1736
  process.exitCode = 1;
1413
1737
  }
1738
+ async function packageVersion() {
1739
+ const manifest = fileURLToPath(new URL("../../package.json", import.meta.url));
1740
+ const parsed = JSON.parse(await readFile(manifest, "utf8"));
1741
+ return parsed.version ?? "unknown";
1742
+ }
1743
+ function unknownCommand(command) {
1744
+ return `Unknown command ${command}
1745
+
1746
+ ${usage()}`;
1747
+ }
1414
1748
  function usage() {
1415
- return `Usage: chopper <command>
1749
+ const width = Math.max(...Object.keys(COMMANDS).map((name) => name.length));
1750
+ const commands = Object.entries(COMMANDS).map(([name, command]) => ` ${name.padEnd(width)} ${command.summary}`).join("\n");
1751
+ return `Usage: chopper <command> [options]
1416
1752
 
1417
1753
  Commands:
1418
- inspect <asset>
1419
- optimize <asset> [output] [--recipe recipe.json]
1420
- run [--config chopper.config.ts]
1421
- check [--config chopper.config.ts]
1422
- report [--config chopper.config.ts]
1423
- codecs sync [directory]`;
1754
+ ${commands}
1755
+
1756
+ Options:
1757
+ -h, --help Show help for chopper or for a command
1758
+ -v, --version Print the installed Chopper version
1759
+
1760
+ Pass \`--\` to end option parsing when a path starts with a dash.
1761
+ Run \`chopper <command> --help\` for details on a command.`;
1762
+ }
1763
+ function commandUsage(name) {
1764
+ const command = COMMANDS[name];
1765
+ return `Usage: ${command.usage}
1766
+
1767
+ ${command.summary}.
1768
+
1769
+ ${command.help}`;
1424
1770
  }
1425
1771
  main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
1426
1772
  //# sourceMappingURL=index.js.map