@joycostudio/chopper 0.3.0 → 0.5.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/README.md +3 -5
- package/codecs/manifest.json +1 -2
- package/dist/browser/{chunk-CC6UVN2A.js → chunk-6WQPPVM2.js} +3 -4
- package/dist/browser/chunk-6WQPPVM2.js.map +1 -0
- package/dist/browser/{in-process-ELNZ7M7W.js → in-process-P6TQNY2L.js} +214 -15
- package/dist/browser/in-process-P6TQNY2L.js.map +1 -0
- package/dist/browser/index.d.ts +20 -8
- package/dist/browser/index.js +2 -2
- package/dist/browser/worker.js +222 -18
- package/dist/browser/worker.js.map +1 -1
- package/dist/cli/index.js +424 -72
- package/dist/cli/index.js.map +1 -1
- package/dist/config/index.d.ts +28 -12
- package/dist/config/index.js.map +1 -1
- package/dist/index.d.ts +36 -11
- package/dist/index.js +30 -13
- package/dist/index.js.map +1 -1
- package/dist/node/index.d.ts +34 -18
- package/dist/node/index.js +237 -32
- package/dist/node/index.js.map +1 -1
- package/package.json +3 -2
- package/dist/browser/chunk-CC6UVN2A.js.map +0 -1
- package/dist/browser/in-process-ELNZ7M7W.js.map +0 -1
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.
|
|
228
|
+
version: "0.5.0"};
|
|
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(
|
|
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({
|
|
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
|
-
|
|
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");
|
|
@@ -1148,7 +1346,7 @@ async function runConfig(options = {}) {
|
|
|
1148
1346
|
const mode = options.mode ?? "write";
|
|
1149
1347
|
const loaded = options.config ? success(options.config) : await loadConfig(resolve(cwd, options.configPath ?? "chopper.config.ts"));
|
|
1150
1348
|
if (!loaded.ok) return loaded;
|
|
1151
|
-
const planned = await planAssets(loaded.data, cwd
|
|
1349
|
+
const planned = await planAssets(loaded.data, cwd);
|
|
1152
1350
|
if (!planned.ok) return planned;
|
|
1153
1351
|
const chopper2 = options.chopper ?? createNodeChopper();
|
|
1154
1352
|
const files = await mapConcurrent(
|
|
@@ -1156,11 +1354,18 @@ async function runConfig(options = {}) {
|
|
|
1156
1354
|
loaded.data.concurrency ?? 2,
|
|
1157
1355
|
(asset) => executeAsset(asset, mode, cwd, chopper2)
|
|
1158
1356
|
);
|
|
1159
|
-
return success({ mode, files, totals: summarize(files) });
|
|
1357
|
+
return success({ mode, output: relative(cwd, resolve(cwd, loaded.data.output)), files, totals: summarize(files) });
|
|
1160
1358
|
}
|
|
1161
|
-
async function planAssets(config, cwd
|
|
1359
|
+
async function planAssets(config, cwd) {
|
|
1162
1360
|
const planned = [];
|
|
1163
|
-
|
|
1361
|
+
if (typeof config.output !== "string" || !config.output) {
|
|
1362
|
+
return failure("invalid_recipe", "Config output directory is required");
|
|
1363
|
+
}
|
|
1364
|
+
const outputRoot = resolve(cwd, config.output);
|
|
1365
|
+
const relativeRoot = relative(cwd, outputRoot);
|
|
1366
|
+
if (isAbsolute(relativeRoot) || relativeRoot === ".." || relativeRoot.startsWith(`..${sep}`)) {
|
|
1367
|
+
return failure("invalid_recipe", `Output directory must be inside the project: ${config.output}`);
|
|
1368
|
+
}
|
|
1164
1369
|
for (const rule of config.rules) {
|
|
1165
1370
|
const valid = validateRecipe(rule.recipe);
|
|
1166
1371
|
if (!valid.ok) return valid;
|
|
@@ -1170,34 +1375,34 @@ async function planAssets(config, cwd, outputDirectory) {
|
|
|
1170
1375
|
onlyFiles: true
|
|
1171
1376
|
});
|
|
1172
1377
|
for (const match of matches.sort()) {
|
|
1173
|
-
const
|
|
1174
|
-
const relativeOutput = relative(
|
|
1175
|
-
if (
|
|
1176
|
-
return failure("invalid_recipe", `
|
|
1378
|
+
const output = resolveOutput(rule, match, outputRoot);
|
|
1379
|
+
const relativeOutput = relative(outputRoot, output);
|
|
1380
|
+
if (isAbsolute(relativeOutput) || relativeOutput === ".." || relativeOutput.startsWith(`..${sep}`)) {
|
|
1381
|
+
return failure("invalid_recipe", `Output path must stay inside ${config.output}: ${rule.path}`);
|
|
1177
1382
|
}
|
|
1178
1383
|
planned.push({
|
|
1179
1384
|
input: resolve(cwd, match),
|
|
1180
|
-
output
|
|
1385
|
+
output,
|
|
1181
1386
|
rule
|
|
1182
1387
|
});
|
|
1183
1388
|
}
|
|
1184
1389
|
}
|
|
1185
|
-
const
|
|
1390
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
1186
1391
|
const inputs = new Set(planned.map(({ input }) => input));
|
|
1187
1392
|
for (const asset of planned) {
|
|
1188
|
-
const owner =
|
|
1189
|
-
if (owner && owner !== asset.input) {
|
|
1393
|
+
const owner = resolved.get(asset.output);
|
|
1394
|
+
if (owner && owner.input !== asset.input) {
|
|
1190
1395
|
return failure(
|
|
1191
1396
|
"invalid_recipe",
|
|
1192
|
-
`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)}`
|
|
1193
1398
|
);
|
|
1194
1399
|
}
|
|
1195
1400
|
if (asset.output !== asset.input && inputs.has(asset.output)) {
|
|
1196
1401
|
return failure("invalid_recipe", `Output loop: ${relative(cwd, asset.output)} is also a matched input`);
|
|
1197
1402
|
}
|
|
1198
|
-
|
|
1403
|
+
resolved.set(asset.output, asset);
|
|
1199
1404
|
}
|
|
1200
|
-
return success(
|
|
1405
|
+
return success([...resolved.values()]);
|
|
1201
1406
|
}
|
|
1202
1407
|
async function executeAsset(asset, mode, cwd, chopper2) {
|
|
1203
1408
|
try {
|
|
@@ -1240,14 +1445,13 @@ async function executeAsset(asset, mode, cwd, chopper2) {
|
|
|
1240
1445
|
};
|
|
1241
1446
|
}
|
|
1242
1447
|
}
|
|
1243
|
-
function resolveOutput(rule, input,
|
|
1244
|
-
if (rule.output.mode === "replace") return resolve(cwd, input);
|
|
1448
|
+
function resolveOutput(rule, input, outputRoot) {
|
|
1245
1449
|
const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
|
|
1246
1450
|
const inputDirectory = dirname(input) === "." ? "" : dirname(input);
|
|
1247
1451
|
const name = basename(input, extname(input));
|
|
1248
1452
|
return resolve(
|
|
1249
|
-
|
|
1250
|
-
rule.
|
|
1453
|
+
outputRoot,
|
|
1454
|
+
(rule.path ?? "{dir}/{name}.{ext}").replaceAll("{dir}", inputDirectory).replaceAll("{name}", name).replaceAll("{ext}", extension.slice(1))
|
|
1251
1455
|
);
|
|
1252
1456
|
}
|
|
1253
1457
|
async function writeAtomic(path, bytes) {
|
|
@@ -1328,28 +1532,113 @@ async function optimizeFile({
|
|
|
1328
1532
|
}
|
|
1329
1533
|
|
|
1330
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
|
+
};
|
|
1331
1618
|
async function main() {
|
|
1332
|
-
const
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
return batch("report", args);
|
|
1344
|
-
case "codecs":
|
|
1345
|
-
return codecs(args);
|
|
1346
|
-
default:
|
|
1347
|
-
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;
|
|
1348
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;
|
|
1637
|
+
}
|
|
1638
|
+
return entry.run(parseArgs(rest, command));
|
|
1349
1639
|
}
|
|
1350
1640
|
async function inspect(args) {
|
|
1351
|
-
const input = args
|
|
1352
|
-
if (!input) throw new Error("Usage: chopper inspect <asset>");
|
|
1641
|
+
const input = args.positional("asset");
|
|
1353
1642
|
const result = await createNodeChopper().inspect({
|
|
1354
1643
|
bytes: new Uint8Array(await readFile(input)),
|
|
1355
1644
|
fileName: input
|
|
@@ -1358,13 +1647,10 @@ async function inspect(args) {
|
|
|
1358
1647
|
console.log(JSON.stringify(result.data, inspectionReplacer, 2));
|
|
1359
1648
|
}
|
|
1360
1649
|
async function optimize(args) {
|
|
1361
|
-
const input = args
|
|
1362
|
-
|
|
1363
|
-
throw new Error("Usage: chopper optimize <asset> [output] [--recipe file.json]");
|
|
1364
|
-
}
|
|
1365
|
-
const recipePath = flag(args, "--recipe");
|
|
1650
|
+
const input = args.positional("asset");
|
|
1651
|
+
const recipePath = args.option("--recipe");
|
|
1366
1652
|
const recipe = recipePath ? JSON.parse(await readFile(recipePath, "utf8")) : extname(input).toLowerCase() === ".glb" ? DEFAULT_GLB_RECIPE : DEFAULT_IMAGE_RECIPE;
|
|
1367
|
-
const positionalOutput = args[1]
|
|
1653
|
+
const positionalOutput = args.positionals[1];
|
|
1368
1654
|
const parsed = parse(input);
|
|
1369
1655
|
const extension = recipe.kind === "glb" ? ".glb" : outputExtension(recipe.encode);
|
|
1370
1656
|
const output = positionalOutput ?? join(dirname(input), `${parsed.name}.optimized${extension}`);
|
|
@@ -1377,7 +1663,7 @@ async function optimize(args) {
|
|
|
1377
1663
|
async function batch(mode, args) {
|
|
1378
1664
|
const result = await runConfig({
|
|
1379
1665
|
mode,
|
|
1380
|
-
configPath:
|
|
1666
|
+
configPath: args.option("--config")
|
|
1381
1667
|
});
|
|
1382
1668
|
if (!result.ok) return fail(result.error.message);
|
|
1383
1669
|
console.log(JSON.stringify(result.data, null, 2));
|
|
@@ -1386,17 +1672,61 @@ async function batch(mode, args) {
|
|
|
1386
1672
|
}
|
|
1387
1673
|
}
|
|
1388
1674
|
async function codecs(args) {
|
|
1389
|
-
if (args[0] !== "sync") {
|
|
1390
|
-
throw new Error("
|
|
1675
|
+
if (args.positionals[0] !== "sync") {
|
|
1676
|
+
throw new Error(commandUsage("codecs"));
|
|
1391
1677
|
}
|
|
1392
|
-
const output = args[1] ?? "public/chopper-codecs";
|
|
1678
|
+
const output = args.positionals[1] ?? "public/chopper-codecs";
|
|
1393
1679
|
const result = await syncCodecs(output);
|
|
1394
1680
|
if (!result.ok) return fail(result.error.message);
|
|
1395
1681
|
console.log(`Copied ${result.data.files.length} codec files to ${result.data.directory}`);
|
|
1396
1682
|
}
|
|
1397
|
-
function
|
|
1398
|
-
|
|
1399
|
-
|
|
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
|
+
};
|
|
1400
1730
|
}
|
|
1401
1731
|
function inspectionReplacer(key, value) {
|
|
1402
1732
|
return key === "bytes" && value instanceof Uint8Array ? { byteLength: value.byteLength } : value;
|
|
@@ -1405,16 +1735,38 @@ function fail(message) {
|
|
|
1405
1735
|
console.error(message);
|
|
1406
1736
|
process.exitCode = 1;
|
|
1407
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
|
+
}
|
|
1408
1748
|
function usage() {
|
|
1409
|
-
|
|
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]
|
|
1410
1752
|
|
|
1411
1753
|
Commands:
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
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}`;
|
|
1418
1770
|
}
|
|
1419
1771
|
main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
|
|
1420
1772
|
//# sourceMappingURL=index.js.map
|