@joycostudio/chopper 0.1.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.
Files changed (41) hide show
  1. package/README.md +37 -0
  2. package/THIRD_PARTY_NOTICES.md +19 -0
  3. package/codecs/avif_enc.wasm +0 -0
  4. package/codecs/basis_encoder.wasm +0 -0
  5. package/codecs/draco_decoder_gltf.js +116 -0
  6. package/codecs/draco_decoder_gltf.wasm +0 -0
  7. package/codecs/draco_encoder.wasm +0 -0
  8. package/codecs/draco_encoder_gltf.js +98 -0
  9. package/codecs/manifest.json +86 -0
  10. package/codecs/mozjpeg_dec.wasm +0 -0
  11. package/codecs/mozjpeg_enc.wasm +0 -0
  12. package/codecs/squoosh_png_bg.wasm +0 -0
  13. package/codecs/squoosh_resize_bg.wasm +0 -0
  14. package/codecs/webp_enc.wasm +0 -0
  15. package/dist/browser/chunk-5WRI5ZAA.js +29 -0
  16. package/dist/browser/chunk-5WRI5ZAA.js.map +1 -0
  17. package/dist/browser/chunk-OTTLKWP4.js +105 -0
  18. package/dist/browser/chunk-OTTLKWP4.js.map +1 -0
  19. package/dist/browser/in-process-V4NPIVZF.js +26747 -0
  20. package/dist/browser/in-process-V4NPIVZF.js.map +1 -0
  21. package/dist/browser/index.d.ts +244 -0
  22. package/dist/browser/index.js +86 -0
  23. package/dist/browser/index.js.map +1 -0
  24. package/dist/browser/node-shim-3YE6NHES.js +16 -0
  25. package/dist/browser/node-shim-3YE6NHES.js.map +1 -0
  26. package/dist/browser/worker.d.ts +2 -0
  27. package/dist/browser/worker.js +27425 -0
  28. package/dist/browser/worker.js.map +1 -0
  29. package/dist/cli/index.d.ts +2 -0
  30. package/dist/cli/index.js +1421 -0
  31. package/dist/cli/index.js.map +1 -0
  32. package/dist/config/index.d.ts +123 -0
  33. package/dist/config/index.js +9 -0
  34. package/dist/config/index.js.map +1 -0
  35. package/dist/index.d.ts +367 -0
  36. package/dist/index.js +396 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/node/index.d.ts +346 -0
  39. package/dist/node/index.js +1266 -0
  40. package/dist/node/index.js.map +1 -0
  41. package/package.json +64 -0
@@ -0,0 +1,1421 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, readdir, mkdir, copyFile, mkdtemp, writeFile, rename, rm } from 'fs/promises';
3
+ import { extname, parse, join, dirname, resolve, relative, basename } from 'path';
4
+ import { PropertyType, NodeIO } from '@gltf-transform/core';
5
+ import { ALL_EXTENSIONS, EXTTextureWebP, EXTTextureAVIF, KHRTextureBasisu } from '@gltf-transform/extensions';
6
+ import draco3d from 'draco3dgltf';
7
+ import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
8
+ import { draco, meshopt, resample, prune, dedup, listTextureSlots } from '@gltf-transform/functions';
9
+ import { createHash } from 'crypto';
10
+ import avifEncoderFactory from '@jsquash/avif/codec/enc/avif_enc.js';
11
+ import { defaultOptions as defaultOptions$1 } from '@jsquash/avif/meta.js';
12
+ import jpegDecoderFactory from '@jsquash/jpeg/codec/dec/mozjpeg_dec.js';
13
+ import jpegEncoderFactory from '@jsquash/jpeg/codec/enc/mozjpeg_enc.js';
14
+ import { defaultOptions } from '@jsquash/jpeg/meta.js';
15
+ import decodePng, { init } from '@jsquash/png/decode.js';
16
+ import encodePng, { init as init$1 } from '@jsquash/png/encode.js';
17
+ import resize, { initResize } from '@jsquash/resize';
18
+ import { initEmscriptenModule } from '@jsquash/webp/utils.js';
19
+ import webpEncoderFactory from '@jsquash/webp/codec/enc/webp_enc.js';
20
+ import { defaultOptions as defaultOptions$2 } from '@jsquash/webp/meta.js';
21
+ import { encodeToKTX2 } from 'ktx2-encoder';
22
+ import { glob } from 'tinyglobby';
23
+ import { createJiti } from 'jiti';
24
+
25
+ // src/core/recipes.ts
26
+ var RECIPE_SCHEMA_VERSION = 1;
27
+ var COLOR_TEXTURE_SLOTS = [
28
+ "baseColorTexture",
29
+ "emissiveTexture",
30
+ "specularColorTexture",
31
+ "sheenColorTexture"
32
+ ];
33
+ var DIRECTIONAL_TEXTURE_SLOTS = ["normalTexture", "clearcoatNormalTexture", "anisotropyTexture"];
34
+ var DATA_TEXTURE_SLOTS = [
35
+ "occlusionTexture",
36
+ "metallicRoughnessTexture",
37
+ "specularTexture",
38
+ "clearcoatTexture",
39
+ "clearcoatRoughnessTexture",
40
+ "sheenRoughnessTexture",
41
+ "transmissionTexture",
42
+ "thicknessTexture",
43
+ "iridescenceTexture",
44
+ "iridescenceThicknessTexture"
45
+ ];
46
+ var DEFAULT_GLB_RECIPE = {
47
+ schemaVersion: RECIPE_SCHEMA_VERSION,
48
+ kind: "glb",
49
+ methods: [],
50
+ textures: [
51
+ {
52
+ label: "color",
53
+ select: { by: "slot", slots: COLOR_TEXTURE_SLOTS },
54
+ encode: {
55
+ codec: "ktx2",
56
+ mode: "uastc",
57
+ colorSpace: "srgb",
58
+ level: 3,
59
+ zstd: true
60
+ }
61
+ },
62
+ {
63
+ label: "directional",
64
+ select: { by: "slot", slots: DIRECTIONAL_TEXTURE_SLOTS },
65
+ encode: {
66
+ codec: "ktx2",
67
+ mode: "uastc",
68
+ colorSpace: "linear",
69
+ normalMap: true,
70
+ level: 3,
71
+ zstd: true
72
+ }
73
+ },
74
+ {
75
+ label: "data",
76
+ select: { by: "slot", slots: DATA_TEXTURE_SLOTS },
77
+ encode: {
78
+ codec: "ktx2",
79
+ mode: "uastc",
80
+ colorSpace: "linear",
81
+ level: 3,
82
+ zstd: true,
83
+ rdo: { lambda: 1 }
84
+ }
85
+ }
86
+ ],
87
+ geometry: { codec: "draco" }
88
+ };
89
+ var DEFAULT_IMAGE_RECIPE = {
90
+ schemaVersion: RECIPE_SCHEMA_VERSION,
91
+ kind: "image",
92
+ encode: { codec: "webp", quality: 85, effort: 80 }
93
+ };
94
+ function outputExtension(encoding) {
95
+ if (encoding.codec === "ktx2") return ".ktx2";
96
+ if (encoding.codec === "jpeg") return ".jpg";
97
+ return `.${encoding.codec}`;
98
+ }
99
+ function outputMimeType(encoding) {
100
+ if (encoding.codec === "ktx2") return "image/ktx2";
101
+ return `image/${encoding.codec}`;
102
+ }
103
+
104
+ // package.json
105
+ var package_default = {
106
+ version: "0.1.0"};
107
+
108
+ // src/codecs/manifest.ts
109
+ var CODEC_MANIFEST_HASH = "2046d60deb0f9f224743f4404f3c6e8ba5399f81b2811fa50466e93fce3bd322";
110
+ var CODEC_ARTIFACTS = {
111
+ avifEncoder: {
112
+ packageName: "@jsquash/avif",
113
+ packageVersion: "2.1.1",
114
+ packagePath: "codec/enc/avif_enc.wasm",
115
+ publicFile: "avif_enc.wasm",
116
+ sha256: "d9f2a95164362af48558d176e619becfd49dd97b50b86c679b47100860522b3d"
117
+ },
118
+ jpegDecoder: {
119
+ packageName: "@jsquash/jpeg",
120
+ packageVersion: "1.6.0",
121
+ packagePath: "codec/dec/mozjpeg_dec.wasm",
122
+ publicFile: "mozjpeg_dec.wasm",
123
+ sha256: "a7c4b12169817e779ff4af137981393ae924944e167ad1bd95747c9199162d3e"
124
+ },
125
+ jpegEncoder: {
126
+ packageName: "@jsquash/jpeg",
127
+ packageVersion: "1.6.0",
128
+ packagePath: "codec/enc/mozjpeg_enc.wasm",
129
+ publicFile: "mozjpeg_enc.wasm",
130
+ sha256: "24d4177f1c4963e2058b107189249651c61fdef125570e79b1dfb63c8bb49326"
131
+ },
132
+ ktx2Encoder: {
133
+ packageName: "ktx2-encoder",
134
+ packageVersion: "0.6.0",
135
+ packagePath: "dist/basis/basis_encoder.wasm",
136
+ publicFile: "basis_encoder.wasm",
137
+ sha256: "9807719e87cf3d979b0d69ae7112eb88aec6a0e0206c0b2d00dc0bed0d581b80"
138
+ },
139
+ png: {
140
+ packageName: "@jsquash/png",
141
+ packageVersion: "3.1.1",
142
+ packagePath: "codec/pkg/squoosh_png_bg.wasm",
143
+ publicFile: "squoosh_png_bg.wasm",
144
+ sha256: "263d6e658808a74b72a1a99c5cc1d619237e70c150db6e41d5d84d3d117ab9be"
145
+ },
146
+ resize: {
147
+ packageName: "@jsquash/resize",
148
+ packageVersion: "2.1.1",
149
+ packagePath: "lib/resize/pkg/squoosh_resize_bg.wasm",
150
+ publicFile: "squoosh_resize_bg.wasm",
151
+ sha256: "5b1f702d502c4d0a70b99f78691bd554d566ba95859e4c57af5435955a1d74a5"
152
+ },
153
+ webpEncoder: {
154
+ packageName: "@jsquash/webp",
155
+ packageVersion: "1.5.0",
156
+ packagePath: "codec/enc/webp_enc.wasm",
157
+ publicFile: "webp_enc.wasm",
158
+ sha256: "b6085bb6702f144e9dc6016d58d230b34a84976bf0d080b7390b4b4b137d6ab7"
159
+ },
160
+ dracoDecoderScript: {
161
+ packageName: "draco3dgltf",
162
+ packageVersion: "1.5.7",
163
+ packagePath: "draco_decoder_gltf_nodejs.js",
164
+ publicFile: "draco_decoder_gltf.js",
165
+ sha256: "8bb2952d2ba7d67e1414f8df819410cb0434a666be53f671fff75f68843d76f6"
166
+ },
167
+ dracoDecoderWasm: {
168
+ packageName: "draco3dgltf",
169
+ packageVersion: "1.5.7",
170
+ packagePath: "draco_decoder_gltf.wasm",
171
+ publicFile: "draco_decoder_gltf.wasm",
172
+ sha256: "712db3449ae2041d6e8a224c395bda6cedb49e51322fae38b7db9beb8b381889"
173
+ },
174
+ dracoEncoderScript: {
175
+ packageName: "draco3dgltf",
176
+ packageVersion: "1.5.7",
177
+ packagePath: "draco_encoder_gltf_nodejs.js",
178
+ publicFile: "draco_encoder_gltf.js",
179
+ sha256: "8434adecd1446459601763e499be3697546056bca90b286a538ae0483a00845a"
180
+ },
181
+ dracoEncoderWasm: {
182
+ packageName: "draco3dgltf",
183
+ packageVersion: "1.5.7",
184
+ packagePath: "draco_encoder.wasm",
185
+ publicFile: "draco_encoder.wasm",
186
+ sha256: "d2a3ac80c91980d5d321c116454834ff36264825c6d1794cc84e42288f158958"
187
+ }
188
+ };
189
+ var CODEC_MANIFEST = {
190
+ chopperVersion: package_default.version};
191
+ var ENGINE_ID = `chopper@${package_default.version}:${CODEC_MANIFEST_HASH}`;
192
+
193
+ // src/core/result.ts
194
+ var success = (data) => ({ ok: true, data });
195
+ var failure = (code, message, cause) => ({
196
+ ok: false,
197
+ error: cause === void 0 ? { code, message } : { code, message, cause }
198
+ });
199
+
200
+ // src/core/validation.ts
201
+ function validateRecipe(recipe) {
202
+ const shapeIssue = recipeShapeIssue(recipe);
203
+ if (shapeIssue) return failure("invalid_recipe", shapeIssue);
204
+ try {
205
+ const typedRecipe = recipe;
206
+ const issue = recipeIssue(typedRecipe);
207
+ return issue ? failure("invalid_recipe", issue) : success(typedRecipe);
208
+ } catch {
209
+ return failure("invalid_recipe", "Recipe contains malformed fields");
210
+ }
211
+ }
212
+ function normalizeRecipe(value) {
213
+ const validated = validateRecipe(value);
214
+ if (!validated.ok) return validated;
215
+ const recipe = validated.data;
216
+ if (recipe.kind === "image") {
217
+ return success({
218
+ schemaVersion: RECIPE_SCHEMA_VERSION,
219
+ kind: "image",
220
+ encode: normalizeEncoding(recipe.encode)
221
+ });
222
+ }
223
+ return success({
224
+ schemaVersion: RECIPE_SCHEMA_VERSION,
225
+ kind: "glb",
226
+ methods: recipe.methods ?? [],
227
+ textures: (recipe.textures ?? []).map((texture) => ({
228
+ ...texture,
229
+ encode: normalizeEncoding(texture.encode)
230
+ })),
231
+ geometry: recipe.geometry ?? false
232
+ });
233
+ }
234
+ function recipeShapeIssue(recipe) {
235
+ if (!recipe || typeof recipe !== "object") return "Recipe must be an object";
236
+ const candidate = recipe;
237
+ if (candidate.kind !== "image" && candidate.kind !== "glb") {
238
+ return `Unsupported recipe kind: ${String(candidate.kind)}`;
239
+ }
240
+ if (candidate.kind === "image") {
241
+ return encodingShapeIssue(candidate.encode);
242
+ }
243
+ if (candidate.methods !== void 0 && !Array.isArray(candidate.methods)) {
244
+ return "GLB methods must be an array";
245
+ }
246
+ for (const method of candidate.methods ?? []) {
247
+ if (!method || typeof method !== "object" || !["dedup", "prune", "resample"].includes(String(method.method))) {
248
+ return "GLB methods contain an unsupported transform";
249
+ }
250
+ }
251
+ if (candidate.textures !== void 0 && !Array.isArray(candidate.textures)) {
252
+ return "GLB textures must be an array";
253
+ }
254
+ for (const texture of candidate.textures ?? []) {
255
+ if (!texture || typeof texture !== "object") return "Texture recipes must be objects";
256
+ const entry = texture;
257
+ if (typeof entry.label !== "string") return "Texture recipe labels must be strings";
258
+ if (!entry.select || typeof entry.select !== "object") return "Texture recipes require a selector";
259
+ const selector = entry.select;
260
+ const values = selector[selector.by === "slot" ? "slots" : selector.by === "name" ? "names" : "indices"];
261
+ if (!["slot", "name", "index"].includes(String(selector.by)) || !Array.isArray(values)) {
262
+ return "Texture recipe selectors are malformed";
263
+ }
264
+ const encodingIssue2 = encodingShapeIssue(entry.encode);
265
+ if (encodingIssue2) return encodingIssue2;
266
+ }
267
+ if (candidate.geometry !== void 0 && candidate.geometry !== false && (!candidate.geometry || typeof candidate.geometry !== "object" || !["draco", "meshopt"].includes(String(candidate.geometry.codec)))) {
268
+ return "GLB geometry must be false, Draco, or Meshopt";
269
+ }
270
+ return void 0;
271
+ }
272
+ function encodingShapeIssue(encoding) {
273
+ if (!encoding || typeof encoding !== "object") return "Image encoding must be an object";
274
+ const candidate = encoding;
275
+ if (!["webp", "avif", "jpeg", "png", "ktx2"].includes(String(candidate.codec))) {
276
+ return `Unsupported image codec: ${String(candidate.codec)}`;
277
+ }
278
+ if (candidate.codec === "ktx2" && candidate.mode !== "uastc" && candidate.mode !== "etc1s") {
279
+ return `Unsupported KTX2 mode: ${String(candidate.mode)}`;
280
+ }
281
+ return void 0;
282
+ }
283
+ function recipeIssue(recipe) {
284
+ if (recipe.schemaVersion !== RECIPE_SCHEMA_VERSION) {
285
+ return `Unsupported recipe schema version: ${String(recipe.schemaVersion)}`;
286
+ }
287
+ if (recipe.kind === "image") return encodingIssue(recipe.encode);
288
+ const labels = /* @__PURE__ */ new Set();
289
+ const selectors = /* @__PURE__ */ new Set();
290
+ for (const texture of recipe.textures ?? []) {
291
+ if (!texture.label) return "Texture recipe labels cannot be empty";
292
+ if (labels.has(texture.label)) {
293
+ return `Duplicate texture recipe label: ${texture.label}`;
294
+ }
295
+ labels.add(texture.label);
296
+ const values = selectorValues(texture.select);
297
+ if (!values.ok) return values.error.message;
298
+ if (!values.data.length) {
299
+ return `Texture recipe "${texture.label}" has an empty selector`;
300
+ }
301
+ for (const value of values.data) {
302
+ const key = `${texture.select.by}:${value}`;
303
+ if (selectors.has(key)) {
304
+ return `Texture selector appears in more than one recipe: ${key}`;
305
+ }
306
+ selectors.add(key);
307
+ }
308
+ const issue = encodingIssue(texture.encode);
309
+ if (issue) return issue;
310
+ }
311
+ for (const method of recipe.methods ?? []) {
312
+ if (method.method === "resample" && (method.tolerance ?? 1e-4) <= 0) {
313
+ return "Resample tolerance must be greater than zero";
314
+ }
315
+ }
316
+ return void 0;
317
+ }
318
+ function selectorValues(selector) {
319
+ if (selector.by === "slot") return success(selector.slots);
320
+ if (selector.by === "name") return success(selector.names);
321
+ for (const index of selector.indices) {
322
+ if (!Number.isInteger(index) || index < 0) {
323
+ return failure("invalid_recipe", "Texture indices must be non-negative integers");
324
+ }
325
+ }
326
+ return success(selector.indices);
327
+ }
328
+ function encodingIssue(encoding) {
329
+ if (encoding.maxSize) {
330
+ const [width, height] = encoding.maxSize;
331
+ if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
332
+ return "Texture maxSize must contain positive integers";
333
+ }
334
+ }
335
+ if ("quality" in encoding && encoding.quality !== void 0) {
336
+ const max = encoding.codec === "ktx2" ? 255 : 100;
337
+ if (encoding.quality < 1 || encoding.quality > max) {
338
+ return `${encoding.codec} quality must be between 1 and ${max}`;
339
+ }
340
+ }
341
+ if ("effort" in encoding && encoding.effort !== void 0) {
342
+ if (encoding.effort < 0 || encoding.effort > 100) {
343
+ return `${encoding.codec} effort must be between 0 and 100`;
344
+ }
345
+ }
346
+ if (encoding.codec === "webp" && encoding.nearLossless !== void 0 && (encoding.nearLossless < 0 || encoding.nearLossless > 100)) {
347
+ return "WebP nearLossless must be between 0 and 100";
348
+ }
349
+ if (encoding.codec === "ktx2" && encoding.mode === "uastc") {
350
+ if (encoding.level !== void 0 && (!Number.isInteger(encoding.level) || encoding.level < 0 || encoding.level > 4)) {
351
+ return "UASTC level must be an integer between 0 and 4";
352
+ }
353
+ const lambda = encoding.rdo?.lambda;
354
+ if (lambda !== void 0 && (lambda < 1e-3 || lambda > 10)) {
355
+ return "UASTC RDO lambda must be between 0.001 and 10";
356
+ }
357
+ }
358
+ if (encoding.codec === "ktx2" && encoding.mode === "etc1s" && encoding.compression !== void 0 && (!Number.isInteger(encoding.compression) || encoding.compression < 0 || encoding.compression > 6)) {
359
+ return "ETC1S compression must be an integer between 0 and 6";
360
+ }
361
+ return void 0;
362
+ }
363
+ function normalizeEncoding(encoding) {
364
+ switch (encoding.codec) {
365
+ case "webp":
366
+ return {
367
+ ...encoding,
368
+ quality: encoding.quality ?? 75,
369
+ effort: encoding.effort ?? 50,
370
+ lossless: encoding.lossless ?? false,
371
+ nearLossless: encoding.nearLossless ?? 100
372
+ };
373
+ case "avif":
374
+ return {
375
+ ...encoding,
376
+ quality: encoding.quality ?? 50,
377
+ effort: encoding.effort ?? 40,
378
+ lossless: encoding.lossless ?? false,
379
+ chromaSubsampling: encoding.chromaSubsampling ?? "4:2:0"
380
+ };
381
+ case "jpeg":
382
+ return {
383
+ ...encoding,
384
+ quality: encoding.quality ?? 75,
385
+ chromaSubsampling: encoding.chromaSubsampling ?? "4:2:0"
386
+ };
387
+ case "png":
388
+ return { ...encoding };
389
+ case "ktx2":
390
+ if (encoding.mode === "uastc") {
391
+ return {
392
+ ...encoding,
393
+ colorSpace: encoding.colorSpace ?? "srgb",
394
+ normalMap: encoding.normalMap ?? false,
395
+ level: encoding.level ?? 2,
396
+ mipmaps: encoding.mipmaps ?? true,
397
+ zstd: encoding.zstd ?? true
398
+ };
399
+ }
400
+ return {
401
+ ...encoding,
402
+ colorSpace: encoding.colorSpace ?? "srgb",
403
+ normalMap: encoding.normalMap ?? false,
404
+ quality: encoding.quality ?? 128,
405
+ compression: encoding.compression ?? 1,
406
+ mipmaps: encoding.mipmaps ?? true
407
+ };
408
+ }
409
+ }
410
+
411
+ // src/core/chopper.ts
412
+ function createChopper(runtime) {
413
+ return {
414
+ engine: {
415
+ id: ENGINE_ID,
416
+ version: CODEC_MANIFEST.chopperVersion,
417
+ manifestHash: CODEC_MANIFEST_HASH
418
+ },
419
+ async inspect(input) {
420
+ const kind = detectAsset(input);
421
+ if (!kind.ok) return kind;
422
+ if (kind.data === "glb") {
423
+ try {
424
+ return await (await runtime.glb()).inspect(input.bytes);
425
+ } catch (cause) {
426
+ return runtimeLoadFailure("GLB", cause);
427
+ }
428
+ }
429
+ return inspectImage(input, imageMimeType(input), runtime.image);
430
+ },
431
+ async optimize(input, recipe, options = {}) {
432
+ const normalized = normalizeRecipe(recipe);
433
+ if (!normalized.ok) return normalized;
434
+ const kind = detectAsset(input);
435
+ if (!kind.ok) return kind;
436
+ if (kind.data !== recipe.kind) {
437
+ return failure("invalid_recipe", `A ${recipe.kind} recipe cannot process a ${kind.data} asset`);
438
+ }
439
+ options.onProgress?.({ phase: "inspect" });
440
+ const startedAt = performance.now();
441
+ if (kind.data === "glb" && recipe.kind === "glb") {
442
+ let glb;
443
+ try {
444
+ glb = await runtime.glb();
445
+ } catch (cause) {
446
+ return runtimeLoadFailure("GLB", cause);
447
+ }
448
+ const optimized = await glb.optimize(input.bytes, recipe, options);
449
+ if (!optimized.ok) return optimized;
450
+ options.onProgress?.({ phase: "validate" });
451
+ const report2 = createReport({
452
+ recipe: normalized.data,
453
+ beforeBytes: input.bytes.byteLength,
454
+ afterBytes: optimized.data.bytes.byteLength,
455
+ durationMs: performance.now() - startedAt,
456
+ textures: optimized.data.textures
457
+ });
458
+ options.onProgress?.({ phase: "complete" });
459
+ return success({
460
+ bytes: optimized.data.bytes,
461
+ fileName: outputFileName(input.fileName, ".glb"),
462
+ mimeType: "model/gltf-binary",
463
+ inspection: optimized.data.inspection,
464
+ report: report2
465
+ });
466
+ }
467
+ if (kind.data !== "image" || recipe.kind !== "image") {
468
+ return failure("invalid_recipe", "Recipe and input type do not match");
469
+ }
470
+ const inspection = await inspectImage(input, imageMimeType(input), runtime.image);
471
+ if (!inspection.ok) return inspection;
472
+ const encoded = await runtime.image.encode(
473
+ { bytes: input.bytes, mimeType: imageMimeType(input) },
474
+ recipe.encode,
475
+ options.signal
476
+ );
477
+ if (!encoded.ok) return encoded;
478
+ options.onProgress?.({ phase: "validate" });
479
+ if (!hasExpectedSignature(encoded.data.bytes, encoded.data.mimeType)) {
480
+ return failure("validation_failed", `Encoded bytes do not match ${encoded.data.mimeType}`);
481
+ }
482
+ const report = createReport({
483
+ recipe: normalized.data,
484
+ beforeBytes: input.bytes.byteLength,
485
+ afterBytes: encoded.data.bytes.byteLength,
486
+ durationMs: performance.now() - startedAt
487
+ });
488
+ options.onProgress?.({ phase: "complete" });
489
+ return success({
490
+ bytes: encoded.data.bytes,
491
+ fileName: outputFileName(input.fileName, outputExtension(recipe.encode)),
492
+ mimeType: encoded.data.mimeType,
493
+ inspection: inspection.data,
494
+ report
495
+ });
496
+ }
497
+ };
498
+ }
499
+ function runtimeLoadFailure(runtime, cause) {
500
+ return failure(
501
+ "codec_load_failed",
502
+ `Could not initialize ${runtime} runtime: ${cause instanceof Error ? cause.message : String(cause)}`,
503
+ cause
504
+ );
505
+ }
506
+ function detectAsset(input) {
507
+ if (input.bytes.length >= 4 && input.bytes[0] === 103 && input.bytes[1] === 108 && input.bytes[2] === 84 && input.bytes[3] === 70) {
508
+ return success("glb");
509
+ }
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`);
512
+ }
513
+ async function inspectImage(input, mimeType, engine) {
514
+ const dimensions = await engine.inspect({ bytes: input.bytes, mimeType });
515
+ if (!dimensions.ok) return dimensions;
516
+ return success({
517
+ kind: "image",
518
+ mimeType,
519
+ width: dimensions.data.width,
520
+ height: dimensions.data.height,
521
+ byteLength: input.bytes.byteLength
522
+ });
523
+ }
524
+ function imageMimeType(input) {
525
+ return isPng(input.bytes) ? "image/png" : "image/jpeg";
526
+ }
527
+ function isPng(bytes) {
528
+ return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71;
529
+ }
530
+ function isJpeg(bytes) {
531
+ return bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 216;
532
+ }
533
+ function hasExpectedSignature(bytes, mimeType) {
534
+ if (mimeType === "image/png") return isPng(bytes);
535
+ if (mimeType === "image/jpeg") return isJpeg(bytes);
536
+ if (mimeType === "image/webp") {
537
+ return ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP";
538
+ }
539
+ if (mimeType === "image/avif") return ascii(bytes, 4, 12) === "ftypavif";
540
+ if (mimeType === "image/ktx2") {
541
+ return bytes.length >= 12 && bytes[0] === 171 && ascii(bytes, 1, 7) === "KTX 20";
542
+ }
543
+ return false;
544
+ }
545
+ function ascii(bytes, start, end) {
546
+ return String.fromCharCode(...bytes.subarray(start, end));
547
+ }
548
+ function outputFileName(fileName, extension) {
549
+ const lastSlash = Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\\"));
550
+ const lastDot = fileName.lastIndexOf(".");
551
+ const end = lastDot > lastSlash ? lastDot : fileName.length;
552
+ return `${fileName.slice(0, end)}${extension}`;
553
+ }
554
+ function createReport(values) {
555
+ return {
556
+ engineId: ENGINE_ID,
557
+ manifestHash: CODEC_MANIFEST_HASH,
558
+ recipe: values.recipe,
559
+ beforeBytes: values.beforeBytes,
560
+ afterBytes: values.afterBytes,
561
+ durationMs: values.durationMs,
562
+ textures: values.textures ?? [],
563
+ warnings: [],
564
+ validation: { valid: true, messages: [] }
565
+ };
566
+ }
567
+ var PROPERTY_TYPES = {
568
+ accessor: PropertyType.ACCESSOR,
569
+ animation: PropertyType.ANIMATION,
570
+ buffer: PropertyType.BUFFER,
571
+ camera: PropertyType.CAMERA,
572
+ material: PropertyType.MATERIAL,
573
+ mesh: PropertyType.MESH,
574
+ node: PropertyType.NODE,
575
+ primitive: PropertyType.PRIMITIVE,
576
+ primitiveTarget: PropertyType.PRIMITIVE_TARGET,
577
+ skin: PropertyType.SKIN,
578
+ texture: PropertyType.TEXTURE
579
+ };
580
+ function compileGlbMethods(recipes, options = {}) {
581
+ return recipes.map((recipe) => {
582
+ switch (recipe.method) {
583
+ case "dedup":
584
+ return dedup({
585
+ keepUniqueNames: recipe.keepUniqueNames,
586
+ propertyTypes: dedupPropertyTypes(recipe, options).map(toPropertyType)
587
+ });
588
+ case "prune":
589
+ return prune({
590
+ keepAttributes: recipe.keepAttributes,
591
+ keepExtras: recipe.keepExtras,
592
+ keepLeaves: recipe.keepLeaves,
593
+ keepSolidTextures: recipe.keepSolidTextures,
594
+ propertyTypes: recipe.propertyTypes?.map(toPropertyType)
595
+ });
596
+ case "resample":
597
+ return resample({
598
+ cleanup: recipe.cleanup,
599
+ tolerance: recipe.tolerance
600
+ });
601
+ }
602
+ });
603
+ }
604
+ function dedupPropertyTypes(recipe, options) {
605
+ const propertyTypes = recipe.propertyTypes ?? ["accessor", "material", "mesh", "skin", "texture"];
606
+ return options.preserveTextureIdentity ? propertyTypes.filter((type) => type !== "texture") : propertyTypes;
607
+ }
608
+ function toPropertyType(property) {
609
+ return PROPERTY_TYPES[property];
610
+ }
611
+ function inspectGlbTextures(document) {
612
+ const textures = document.getRoot().listTextures();
613
+ const nameCounts = /* @__PURE__ */ new Map();
614
+ for (const texture of textures) {
615
+ const name = texture.getName();
616
+ if (name) nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);
617
+ }
618
+ return textures.flatMap((texture, index) => {
619
+ const image = texture.getImage();
620
+ if (!image) return [];
621
+ const name = texture.getName();
622
+ return [
623
+ {
624
+ index,
625
+ name,
626
+ uri: texture.getURI(),
627
+ mimeType: texture.getMimeType(),
628
+ size: texture.getSize() ?? null,
629
+ slots: listTextureSlots(texture),
630
+ bytes: new Uint8Array(image),
631
+ authoringSelector: name && nameCounts.get(name) === 1 ? { by: "name", names: [name] } : { by: "index", indices: [index] }
632
+ }
633
+ ];
634
+ });
635
+ }
636
+ function textureMatchesRecipe(texture, index, recipe) {
637
+ const selector = recipe.select;
638
+ if (selector.by === "index") return selector.indices.includes(index);
639
+ if (selector.by === "name") return selector.names.includes(texture.getName());
640
+ const slots = listTextureSlots(texture);
641
+ return selector.slots.some((slot) => slots.includes(slot));
642
+ }
643
+
644
+ // src/gltf/optimizer.ts
645
+ var GlbPipelineFailure = class extends Error {
646
+ constructor(code, message, originalCause) {
647
+ super(message, originalCause === void 0 ? void 0 : { cause: originalCause });
648
+ this.code = code;
649
+ this.originalCause = originalCause;
650
+ }
651
+ };
652
+ async function optimizeGlbDocument(document, recipe, imageEngine, options = {}) {
653
+ const texturePlans = planTextureEncodings(document, recipe.textures);
654
+ assertNotAborted(options.signal);
655
+ for (const extension of ["KHR_draco_mesh_compression", "EXT_meshopt_compression"]) {
656
+ if (document.hasExtension(extension)) document.disposeExtension(extension);
657
+ }
658
+ for (const [index, method] of recipe.methods.entries()) {
659
+ options.onProgress?.({
660
+ phase: "transform",
661
+ method: method.method,
662
+ index,
663
+ total: recipe.methods.length
664
+ });
665
+ await document.transform(...compileGlbMethods([method], { preserveTextureIdentity: texturePlans.length > 0 }));
666
+ assertNotAborted(options.signal);
667
+ }
668
+ const reports = await encodeTextures(document, texturePlans, imageEngine, options);
669
+ if (recipe.geometry) {
670
+ options.onProgress?.({ phase: "geometry", codec: recipe.geometry.codec });
671
+ if (recipe.geometry.codec === "draco") {
672
+ await document.transform(draco());
673
+ } else {
674
+ await MeshoptEncoder.ready;
675
+ await document.transform(meshopt({ encoder: MeshoptEncoder }));
676
+ }
677
+ assertNotAborted(options.signal);
678
+ }
679
+ return reports;
680
+ }
681
+ async function encodeTextures(document, plans, engine, options) {
682
+ const reports = [];
683
+ const textures = document.getRoot().listTextures();
684
+ const outputIndices = new Map(textures.map((texture, index) => [texture, index]));
685
+ for (const { texture, recipe, sourceIndex } of plans) {
686
+ const outputIndex = outputIndices.get(texture);
687
+ if (outputIndex === void 0) continue;
688
+ const image = texture.getImage();
689
+ if (!image) continue;
690
+ const mimeType = sourceMimeType(texture);
691
+ options.onProgress?.({
692
+ phase: "texture",
693
+ label: recipe.label,
694
+ index: outputIndex,
695
+ total: textures.length
696
+ });
697
+ const encoded = await engine.encode({ bytes: image, mimeType }, recipe.encode, options.signal);
698
+ if (!encoded.ok) {
699
+ throw new GlbPipelineFailure(
700
+ encoded.error.code === "validation_failed" || encoded.error.code === "unsupported_asset" || encoded.error.code === "io_failed" ? "encode_failed" : encoded.error.code,
701
+ encoded.error.message,
702
+ encoded.error.cause
703
+ );
704
+ }
705
+ texture.setImage(encoded.data.bytes).setMimeType(encoded.data.mimeType);
706
+ updateTextureUri(texture, outputExtension(recipe.encode));
707
+ reports.push({
708
+ label: recipe.label,
709
+ sourceIndex,
710
+ outputIndex,
711
+ beforeBytes: image.byteLength,
712
+ afterBytes: encoded.data.bytes.byteLength,
713
+ beforeMimeType: mimeType,
714
+ afterMimeType: encoded.data.mimeType
715
+ });
716
+ assertNotAborted(options.signal);
717
+ }
718
+ const mimeTypes = new Set(
719
+ document.getRoot().listTextures().map((texture) => texture.getMimeType())
720
+ );
721
+ syncTextureExtension(document, "image/webp", EXTTextureWebP, mimeTypes);
722
+ syncTextureExtension(document, "image/avif", EXTTextureAVIF, mimeTypes);
723
+ syncTextureExtension(document, "image/ktx2", KHRTextureBasisu, mimeTypes);
724
+ return reports;
725
+ }
726
+ function planTextureEncodings(document, recipes) {
727
+ const plans = [];
728
+ for (const [sourceIndex, texture] of document.getRoot().listTextures().entries()) {
729
+ const matches = recipes.filter((recipe) => textureMatchesRecipe(texture, sourceIndex, recipe));
730
+ if (matches.length > 1) {
731
+ const label = texture.getName() || texture.getURI() || "unnamed texture";
732
+ throw new GlbPipelineFailure(
733
+ "invalid_recipe",
734
+ `Texture "${label}" matches multiple encoders: ${matches.map(({ label: match }) => match).join(", ")}`
735
+ );
736
+ }
737
+ if (matches[0]) plans.push({ texture, recipe: matches[0], sourceIndex });
738
+ }
739
+ return plans;
740
+ }
741
+ function syncTextureExtension(document, mimeType, extension, mimeTypes) {
742
+ if (mimeTypes.has(mimeType)) {
743
+ document.createExtension(extension).setRequired(true);
744
+ } else if (document.hasExtension(extension.EXTENSION_NAME)) {
745
+ document.disposeExtension(extension.EXTENSION_NAME);
746
+ }
747
+ }
748
+ function sourceMimeType(texture) {
749
+ const mimeType = texture.getMimeType();
750
+ if (mimeType === "image/png" || mimeType === "image/jpeg") return mimeType;
751
+ const label = texture.getName() || texture.getURI() || "unnamed texture";
752
+ throw new GlbPipelineFailure(
753
+ "decode_failed",
754
+ `Texture "${label}" uses unsupported source type ${mimeType || "unknown"}; expected PNG or JPEG`
755
+ );
756
+ }
757
+ function updateTextureUri(texture, extension) {
758
+ const uri = texture.getURI();
759
+ if (!uri) return;
760
+ texture.setURI(uri.replace(/\.[^./]+$/, "") + extension);
761
+ }
762
+ function assertNotAborted(signal) {
763
+ if (signal?.aborted) {
764
+ throw new GlbPipelineFailure("aborted", "Optimization was aborted");
765
+ }
766
+ }
767
+
768
+ // src/gltf/engine.ts
769
+ function createGlbEngine(imageEngine, io) {
770
+ return {
771
+ id: imageEngine.id,
772
+ async inspect(source) {
773
+ try {
774
+ const document = await io.readBinary(source);
775
+ return success(inspectDocument(document, source.byteLength));
776
+ } catch (cause) {
777
+ return failure("decode_failed", "Could not decode GLB", cause);
778
+ }
779
+ },
780
+ async optimize(source, recipe, options = {}) {
781
+ const normalized = normalizeRecipe(recipe);
782
+ if (!normalized.ok) return normalized;
783
+ if (normalized.data.kind !== "glb") {
784
+ return failure("invalid_recipe", "Expected a GLB recipe");
785
+ }
786
+ try {
787
+ options.onProgress?.({ phase: "decode" });
788
+ const document = await io.readBinary(source);
789
+ const textures = await optimizeGlbDocument(document, normalized.data, imageEngine, options);
790
+ const bytes = await io.writeBinary(document);
791
+ const verifiedDocument = await io.readBinary(bytes);
792
+ return success({
793
+ bytes,
794
+ inspection: inspectDocument(verifiedDocument, bytes.byteLength),
795
+ textures
796
+ });
797
+ } catch (cause) {
798
+ if (cause instanceof GlbPipelineFailure) {
799
+ return failure(cause.code, cause.message, cause.originalCause);
800
+ }
801
+ return failure("encode_failed", "Could not optimize GLB", cause);
802
+ }
803
+ }
804
+ };
805
+ }
806
+ function inspectDocument(document, byteLength) {
807
+ const root = document.getRoot();
808
+ const meshes = root.listMeshes();
809
+ return {
810
+ kind: "glb",
811
+ byteLength,
812
+ textures: inspectGlbTextures(document),
813
+ geometry: {
814
+ compression: document.hasExtension("KHR_draco_mesh_compression") ? "draco" : document.hasExtension("EXT_meshopt_compression") ? "meshopt" : false,
815
+ meshCount: meshes.length,
816
+ primitiveCount: meshes.reduce((total, mesh) => total + mesh.listPrimitives().length, 0)
817
+ }
818
+ };
819
+ }
820
+ var CodecLoadError = class extends Error {
821
+ };
822
+ function createWasmImageEngine(loader) {
823
+ const adapters = createAdapterCache(loader);
824
+ return {
825
+ id: ENGINE_ID,
826
+ manifestHash: CODEC_MANIFEST_HASH,
827
+ async inspect(source) {
828
+ try {
829
+ const image = await decodeSource(source, adapters);
830
+ return success({ width: image.width, height: image.height });
831
+ } catch (cause) {
832
+ return operationFailure("decode_failed", "Could not decode image", cause);
833
+ }
834
+ },
835
+ async encode(source, encoding, signal) {
836
+ const valid = validateRecipe({ schemaVersion: 1, kind: "image", encode: encoding });
837
+ if (!valid.ok) return valid;
838
+ try {
839
+ assertNotAborted2(signal);
840
+ let image = await decodeSource(source, adapters);
841
+ assertNotAborted2(signal);
842
+ if (encoding.maxSize) {
843
+ image = await resizeWithin(image, encoding.maxSize, adapters);
844
+ }
845
+ assertNotAborted2(signal);
846
+ const encoded = encoding.codec === "ktx2" ? await encodeKtx2(source, image, encoding, await loader.basisEncoderUrl()) : await encodeRaster(image, encoding, adapters);
847
+ assertNotAborted2(signal);
848
+ return success({
849
+ ...encoded,
850
+ width: image.width,
851
+ height: image.height
852
+ });
853
+ } catch (cause) {
854
+ if (cause instanceof DOMException && cause.name === "AbortError") {
855
+ return failure("aborted", "Optimization was aborted", cause);
856
+ }
857
+ return operationFailure("encode_failed", "Could not encode image", cause);
858
+ }
859
+ }
860
+ };
861
+ }
862
+ function createAdapterCache(loader) {
863
+ let avif;
864
+ let jpegDecoder;
865
+ let jpegEncoder;
866
+ let png;
867
+ let resizeModule;
868
+ let webp;
869
+ const load = async (name) => {
870
+ try {
871
+ return await loader.load(name);
872
+ } catch (cause) {
873
+ throw new CodecLoadError(`Could not load ${name}`, { cause });
874
+ }
875
+ };
876
+ return {
877
+ avif: () => avif ??= load("avifEncoder").then(
878
+ (module) => initEmscriptenModule(avifEncoderFactory, module)
879
+ ),
880
+ jpegDecoder: () => jpegDecoder ??= load("jpegDecoder").then(
881
+ (module) => initEmscriptenModule(jpegDecoderFactory, module)
882
+ ),
883
+ jpegEncoder: () => jpegEncoder ??= load("jpegEncoder").then(
884
+ (module) => initEmscriptenModule(jpegEncoderFactory, module)
885
+ ),
886
+ png: () => png ??= load("png").then(async (module) => {
887
+ await Promise.all([init(module), init$1(module)]);
888
+ }),
889
+ resize: () => resizeModule ??= load("resize").then(async (module) => {
890
+ await initResize(module);
891
+ }),
892
+ webp: () => webp ??= load("webpEncoder").then(
893
+ (module) => initEmscriptenModule(webpEncoderFactory, module)
894
+ )
895
+ };
896
+ }
897
+ async function decodeSource(source, adapters) {
898
+ if (source.mimeType === "image/png") {
899
+ await adapters.png();
900
+ return decodePng(toArrayBuffer(source.bytes));
901
+ }
902
+ const decoder = await adapters.jpegDecoder();
903
+ const image = decoder.decode(source.bytes, false);
904
+ if (!image) throw new Error("JPEG decoding failed");
905
+ return image;
906
+ }
907
+ async function resizeWithin(image, [maxWidth, maxHeight], adapters) {
908
+ const scale = Math.min(maxWidth / image.width, maxHeight / image.height, 1);
909
+ if (scale === 1) return image;
910
+ await adapters.resize();
911
+ return resize(image, {
912
+ width: Math.max(1, Math.round(image.width * scale)),
913
+ height: Math.max(1, Math.round(image.height * scale)),
914
+ method: "lanczos3",
915
+ fitMethod: "stretch",
916
+ premultiply: true,
917
+ linearRGB: true
918
+ });
919
+ }
920
+ async function encodeRaster(image, encoding, adapters) {
921
+ let bytes;
922
+ switch (encoding.codec) {
923
+ case "webp": {
924
+ const encoder = await adapters.webp();
925
+ bytes = requireEncoded(
926
+ encoder.encode(image.data, image.width, image.height, {
927
+ ...defaultOptions$2,
928
+ quality: encoding.quality ?? 75,
929
+ method: encoding.effort === void 0 ? defaultOptions$2.method : remapEffort(encoding.effort, 6),
930
+ lossless: encoding.lossless ? 1 : 0,
931
+ near_lossless: encoding.nearLossless ?? 100,
932
+ thread_level: 0
933
+ }),
934
+ "WebP"
935
+ );
936
+ break;
937
+ }
938
+ case "avif": {
939
+ const encoder = await adapters.avif();
940
+ bytes = requireEncoded(
941
+ encoder.encode(image.data, image.width, image.height, {
942
+ ...defaultOptions$1,
943
+ quality: encoding.lossless ? 100 : encoding.quality ?? 50,
944
+ qualityAlpha: -1,
945
+ denoiseLevel: 0,
946
+ tileRowsLog2: 0,
947
+ tileColsLog2: 0,
948
+ speed: encoding.effort === void 0 ? defaultOptions$1.speed : 10 - remapEffort(encoding.effort, 10),
949
+ subsample: encoding.lossless || encoding.chromaSubsampling === "4:4:4" ? 3 : 1,
950
+ chromaDeltaQ: false,
951
+ sharpness: 0,
952
+ enableSharpYUV: false,
953
+ tune: 0,
954
+ bitDepth: 8,
955
+ lossless: encoding.lossless ?? false
956
+ }),
957
+ "AVIF"
958
+ );
959
+ break;
960
+ }
961
+ case "jpeg": {
962
+ const encoder = await adapters.jpegEncoder();
963
+ bytes = requireEncoded(
964
+ encoder.encode(image.data, image.width, image.height, {
965
+ ...defaultOptions,
966
+ quality: encoding.quality ?? 75,
967
+ baseline: false,
968
+ arithmetic: false,
969
+ progressive: true,
970
+ optimize_coding: true,
971
+ smoothing: 0,
972
+ color_space: 3,
973
+ quant_table: 3,
974
+ trellis_multipass: false,
975
+ trellis_opt_zero: false,
976
+ trellis_opt_table: false,
977
+ trellis_loops: 1,
978
+ auto_subsample: encoding.chromaSubsampling === void 0,
979
+ chroma_subsample: encoding.chromaSubsampling === "4:4:4" ? 1 : 2,
980
+ separate_chroma_quality: false,
981
+ chroma_quality: encoding.quality ?? 75
982
+ }),
983
+ "JPEG"
984
+ );
985
+ break;
986
+ }
987
+ case "png":
988
+ await adapters.png();
989
+ bytes = await encodePng(image);
990
+ break;
991
+ }
992
+ return { bytes: toUint8Array(bytes), mimeType: outputMimeType(encoding) };
993
+ }
994
+ async function encodeKtx2(source, image, encoding, wasmUrl) {
995
+ const srgb = encoding.colorSpace !== "linear";
996
+ const bytes = await encodeToKTX2(source.bytes, {
997
+ isUASTC: encoding.mode === "uastc",
998
+ qualityLevel: encoding.mode === "etc1s" ? encoding.quality : void 0,
999
+ compressionLevel: encoding.mode === "etc1s" ? encoding.compression : void 0,
1000
+ needSupercompression: encoding.mode === "uastc" ? encoding.zstd ?? true : false,
1001
+ uastcLDRQualityLevel: encoding.mode === "uastc" ? encoding.level : void 0,
1002
+ enableRDO: encoding.mode === "uastc" && encoding.rdo !== void 0,
1003
+ rdoQualityLevel: encoding.mode === "uastc" ? encoding.rdo?.lambda : void 0,
1004
+ isNormalMap: encoding.normalMap,
1005
+ isPerceptual: srgb,
1006
+ isSetKTX2SRGBTransferFunc: srgb,
1007
+ generateMipmap: encoding.mipmaps ?? true,
1008
+ isKTX2File: true,
1009
+ imageDecoder: async () => ({
1010
+ data: new Uint8Array(image.data.buffer, image.data.byteOffset, image.data.byteLength),
1011
+ width: image.width,
1012
+ height: image.height
1013
+ }),
1014
+ wasmUrl
1015
+ });
1016
+ return { bytes, mimeType: outputMimeType(encoding) };
1017
+ }
1018
+ function operationFailure(code, message, cause) {
1019
+ return cause instanceof CodecLoadError ? failure("codec_load_failed", cause.message, cause.cause) : failure(code, message, cause);
1020
+ }
1021
+ function assertNotAborted2(signal) {
1022
+ if (signal?.aborted) throw new DOMException("Optimization was aborted", "AbortError");
1023
+ }
1024
+ function requireEncoded(bytes, codec) {
1025
+ if (!bytes) throw new Error(`${codec} encoding failed`);
1026
+ return bytes;
1027
+ }
1028
+ function toUint8Array(bytes) {
1029
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
1030
+ }
1031
+ function toArrayBuffer(bytes) {
1032
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1033
+ }
1034
+ function remapEffort(effort, max) {
1035
+ return Math.round(effort / 100 * max);
1036
+ }
1037
+
1038
+ // src/node/image-engine.ts
1039
+ var defaultEngine;
1040
+ function createNodeImageEngine(options = {}) {
1041
+ installImageData();
1042
+ if (options.codecDirectory) {
1043
+ return createWasmImageEngine(createNodeCodecLoader(options.codecDirectory));
1044
+ }
1045
+ return defaultEngine ??= createWasmImageEngine(createNodeCodecLoader());
1046
+ }
1047
+ function createNodeCodecLoader(codecDirectory = new URL("../../codecs/", import.meta.url)) {
1048
+ const modules = /* @__PURE__ */ new Map();
1049
+ return {
1050
+ load(name) {
1051
+ const existing = modules.get(name);
1052
+ if (existing) return existing;
1053
+ const pending = loadModule(name, codecDirectory);
1054
+ modules.set(name, pending);
1055
+ return pending;
1056
+ },
1057
+ async basisEncoderUrl() {
1058
+ return void 0;
1059
+ }
1060
+ };
1061
+ }
1062
+ async function loadModule(name, codecDirectory) {
1063
+ const artifact = CODEC_ARTIFACTS[name];
1064
+ const location = typeof codecDirectory === "string" ? join(codecDirectory, artifact.publicFile) : new URL(artifact.publicFile, codecDirectory);
1065
+ const bytes = await readFile(location);
1066
+ const hash = createHash("sha256").update(bytes).digest("hex");
1067
+ if (hash !== artifact.sha256) {
1068
+ throw new Error(`${name} failed integrity validation`);
1069
+ }
1070
+ return WebAssembly.compile(bytes);
1071
+ }
1072
+ function installImageData() {
1073
+ if (globalThis.ImageData) return;
1074
+ globalThis.ImageData = class ImageData {
1075
+ constructor(dataOrWidth, widthOrHeight, heightOrSettings) {
1076
+ this.colorSpace = "srgb";
1077
+ if (typeof dataOrWidth === "number") {
1078
+ this.width = dataOrWidth;
1079
+ this.height = widthOrHeight;
1080
+ this.data = new Uint8ClampedArray(this.width * this.height * 4);
1081
+ return;
1082
+ }
1083
+ this.data = dataOrWidth;
1084
+ this.width = widthOrHeight;
1085
+ if (typeof heightOrSettings !== "number") {
1086
+ throw new Error("ImageData height is required in Node");
1087
+ }
1088
+ this.height = heightOrSettings;
1089
+ }
1090
+ };
1091
+ }
1092
+
1093
+ // src/node/glb-engine.ts
1094
+ var dependencies;
1095
+ async function createNodeGlbEngine(imageEngine = createNodeImageEngine()) {
1096
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies(await loadDependencies());
1097
+ return createGlbEngine(imageEngine, io);
1098
+ }
1099
+ function loadDependencies() {
1100
+ return dependencies ??= Promise.all([
1101
+ draco3d.createDecoderModule(),
1102
+ draco3d.createEncoderModule(),
1103
+ MeshoptDecoder.ready,
1104
+ MeshoptEncoder.ready
1105
+ ]).then(([dracoDecoder, dracoEncoder]) => ({
1106
+ "draco3d.decoder": dracoDecoder,
1107
+ "draco3d.encoder": dracoEncoder,
1108
+ "meshopt.decoder": MeshoptDecoder,
1109
+ "meshopt.encoder": MeshoptEncoder
1110
+ }));
1111
+ }
1112
+
1113
+ // src/node/chopper.ts
1114
+ var chopper;
1115
+ function createNodeChopper(options = {}) {
1116
+ if (!options.codecDirectory && chopper) return chopper;
1117
+ const image = createNodeImageEngine(options);
1118
+ const created = createChopper({
1119
+ image,
1120
+ glb: () => createNodeGlbEngine(image)
1121
+ });
1122
+ if (!options.codecDirectory) chopper = created;
1123
+ return created;
1124
+ }
1125
+ async function loadConfig(path = "chopper.config.ts") {
1126
+ const absolutePath = resolve(path);
1127
+ try {
1128
+ await readFile(absolutePath);
1129
+ const jiti = createJiti(import.meta.url);
1130
+ const config = await jiti.import(absolutePath, {
1131
+ default: true
1132
+ });
1133
+ if (!config || !Array.isArray(config.rules)) {
1134
+ return failure("invalid_recipe", `${path} must export a Chopper config`);
1135
+ }
1136
+ if (config.concurrency !== void 0 && (!Number.isInteger(config.concurrency) || config.concurrency < 1)) {
1137
+ return failure("invalid_recipe", "Config concurrency must be a positive integer");
1138
+ }
1139
+ return success(config);
1140
+ } catch (cause) {
1141
+ return failure("io_failed", `Could not load ${path}`, cause);
1142
+ }
1143
+ }
1144
+
1145
+ // src/node/batch.ts
1146
+ async function runConfig(options = {}) {
1147
+ const cwd = resolve(options.cwd ?? process.cwd());
1148
+ const mode = options.mode ?? "write";
1149
+ const loaded = options.config ? success(options.config) : await loadConfig(resolve(cwd, options.configPath ?? "chopper.config.ts"));
1150
+ if (!loaded.ok) return loaded;
1151
+ const planned = await planAssets(loaded.data, cwd, options.changedPaths);
1152
+ if (!planned.ok) return planned;
1153
+ const chopper2 = options.chopper ?? createNodeChopper();
1154
+ const files = await mapConcurrent(
1155
+ planned.data,
1156
+ loaded.data.concurrency ?? 2,
1157
+ (asset) => executeAsset(asset, mode, cwd, chopper2)
1158
+ );
1159
+ return success({ mode, files, totals: summarize(files) });
1160
+ }
1161
+ async function planAssets(config, cwd, changedPaths) {
1162
+ const changed = changedPaths ? new Set(changedPaths.map((path) => normalizePath(path))) : void 0;
1163
+ const planned = [];
1164
+ for (const rule of config.rules) {
1165
+ const valid = validateRecipe(rule.recipe);
1166
+ if (!valid.ok) return valid;
1167
+ const matches = await glob(rule.include, {
1168
+ cwd,
1169
+ ignore: rule.exclude,
1170
+ onlyFiles: true
1171
+ });
1172
+ for (const match of matches.sort()) {
1173
+ const normalized = normalizePath(match);
1174
+ if (changed && !changed.has(normalized)) continue;
1175
+ planned.push({
1176
+ input: resolve(cwd, match),
1177
+ output: resolveOutput(rule, match, cwd),
1178
+ rule
1179
+ });
1180
+ }
1181
+ }
1182
+ const outputs = /* @__PURE__ */ new Map();
1183
+ const inputs = new Set(planned.map(({ input }) => input));
1184
+ for (const asset of planned) {
1185
+ const owner = outputs.get(asset.output);
1186
+ if (owner && owner !== asset.input) {
1187
+ return failure(
1188
+ "invalid_recipe",
1189
+ `Output collision: ${relative(cwd, owner)} and ${relative(cwd, asset.input)} both write ${relative(cwd, asset.output)}`
1190
+ );
1191
+ }
1192
+ if (asset.output !== asset.input && inputs.has(asset.output)) {
1193
+ return failure("invalid_recipe", `Output loop: ${relative(cwd, asset.output)} is also a matched input`);
1194
+ }
1195
+ outputs.set(asset.output, asset.input);
1196
+ }
1197
+ return success(planned);
1198
+ }
1199
+ async function executeAsset(asset, mode, cwd, chopper2) {
1200
+ try {
1201
+ const source = new Uint8Array(await readFile(asset.input));
1202
+ const optimized = await chopper2.optimize({ bytes: source, fileName: relative(cwd, asset.input) }, asset.rule.recipe);
1203
+ if (!optimized.ok) {
1204
+ return {
1205
+ input: relative(cwd, asset.input),
1206
+ output: relative(cwd, asset.output),
1207
+ status: "failed",
1208
+ error: optimized.error
1209
+ };
1210
+ }
1211
+ const base = {
1212
+ input: relative(cwd, asset.input),
1213
+ output: relative(cwd, asset.output),
1214
+ beforeBytes: source.byteLength,
1215
+ afterBytes: optimized.data.bytes.byteLength,
1216
+ engineId: optimized.data.report.engineId
1217
+ };
1218
+ if (mode === "report") return { ...base, status: "reported" };
1219
+ if (mode === "check") {
1220
+ const current = await readFile(asset.output).catch(() => void 0);
1221
+ return {
1222
+ ...base,
1223
+ status: current && bytesEqual(current, optimized.data.bytes) ? "current" : "stale"
1224
+ };
1225
+ }
1226
+ await writeAtomic(asset.output, optimized.data.bytes);
1227
+ return { ...base, status: "written" };
1228
+ } catch (cause) {
1229
+ return {
1230
+ input: relative(cwd, asset.input),
1231
+ output: relative(cwd, asset.output),
1232
+ status: "failed",
1233
+ error: {
1234
+ code: "io_failed",
1235
+ message: cause instanceof Error ? cause.message : String(cause)
1236
+ }
1237
+ };
1238
+ }
1239
+ }
1240
+ function resolveOutput(rule, input, cwd) {
1241
+ if (rule.output.mode === "replace") return resolve(cwd, input);
1242
+ const extension = rule.recipe.kind === "glb" ? ".glb" : outputExtension(rule.recipe.encode);
1243
+ const inputDirectory = dirname(input) === "." ? "" : dirname(input);
1244
+ const name = basename(input, extname(input));
1245
+ return resolve(
1246
+ cwd,
1247
+ rule.output.path.replaceAll("{dir}", inputDirectory).replaceAll("{name}", name).replaceAll("{ext}", extension.slice(1))
1248
+ );
1249
+ }
1250
+ async function writeAtomic(path, bytes) {
1251
+ await mkdir(dirname(path), { recursive: true });
1252
+ const temporaryDirectory = await mkdtemp(join(dirname(path), ".chopper-"));
1253
+ const pending = join(temporaryDirectory, "output");
1254
+ try {
1255
+ await writeFile(pending, bytes);
1256
+ await rename(pending, path);
1257
+ } finally {
1258
+ await rm(temporaryDirectory, { recursive: true, force: true });
1259
+ }
1260
+ }
1261
+ function bytesEqual(left, right) {
1262
+ if (left.byteLength !== right.byteLength) return false;
1263
+ return left.every((value, index) => value === right[index]);
1264
+ }
1265
+ function normalizePath(path) {
1266
+ return path.replaceAll("\\", "/");
1267
+ }
1268
+ async function mapConcurrent(values, concurrency, operation) {
1269
+ const results = new Array(values.length);
1270
+ let next = 0;
1271
+ await Promise.all(
1272
+ Array.from({ length: Math.min(concurrency, values.length) }, async () => {
1273
+ while (next < values.length) {
1274
+ const index = next++;
1275
+ results[index] = await operation(values[index]);
1276
+ }
1277
+ })
1278
+ );
1279
+ return results;
1280
+ }
1281
+ function summarize(files) {
1282
+ return {
1283
+ matched: files.length,
1284
+ written: files.filter(({ status }) => status === "written").length,
1285
+ current: files.filter(({ status }) => status === "current").length,
1286
+ stale: files.filter(({ status }) => status === "stale").length,
1287
+ reported: files.filter(({ status }) => status === "reported").length,
1288
+ failed: files.filter(({ status }) => status === "failed").length
1289
+ };
1290
+ }
1291
+ async function syncCodecs(output) {
1292
+ const destination = resolve(output);
1293
+ const source = new URL("../../codecs/", import.meta.url);
1294
+ try {
1295
+ const files = (await readdir(source)).sort();
1296
+ await mkdir(destination, { recursive: true });
1297
+ await Promise.all(files.map((file) => copyFile(new URL(file, source), join(destination, file))));
1298
+ return success({ directory: destination, files });
1299
+ } catch (cause) {
1300
+ return failure("io_failed", `Could not sync codecs to ${output}`, cause);
1301
+ }
1302
+ }
1303
+ async function optimizeFile({
1304
+ input,
1305
+ output,
1306
+ recipe,
1307
+ ...options
1308
+ }) {
1309
+ const source = resolve(input);
1310
+ const destination = resolve(output);
1311
+ try {
1312
+ const bytes = new Uint8Array(await readFile(source));
1313
+ const result = await createNodeChopper().optimize({ bytes, fileName: input }, recipe, options);
1314
+ if (!result.ok) return result;
1315
+ await mkdir(dirname(destination), { recursive: true });
1316
+ const temporaryDirectory = await mkdtemp(join(dirname(destination), ".chopper-"));
1317
+ const pending = join(temporaryDirectory, "output");
1318
+ try {
1319
+ await writeFile(pending, result.data.bytes);
1320
+ await rename(pending, destination);
1321
+ } finally {
1322
+ await rm(temporaryDirectory, { recursive: true, force: true });
1323
+ }
1324
+ return result;
1325
+ } catch (cause) {
1326
+ return failure("io_failed", `Could not optimize ${input}`, cause);
1327
+ }
1328
+ }
1329
+
1330
+ // src/cli/index.ts
1331
+ async function main() {
1332
+ const [command, ...args] = process.argv.slice(2);
1333
+ switch (command) {
1334
+ case "inspect":
1335
+ return inspect(args);
1336
+ case "optimize":
1337
+ return optimize(args);
1338
+ case "run":
1339
+ return batch("write", args);
1340
+ case "check":
1341
+ return batch("check", args);
1342
+ case "report":
1343
+ return batch("report", args);
1344
+ case "codecs":
1345
+ return codecs(args);
1346
+ default:
1347
+ throw new Error(usage());
1348
+ }
1349
+ }
1350
+ async function inspect(args) {
1351
+ const input = args[0];
1352
+ if (!input) throw new Error("Usage: chopper inspect <asset>");
1353
+ const result = await createNodeChopper().inspect({
1354
+ bytes: new Uint8Array(await readFile(input)),
1355
+ fileName: input
1356
+ });
1357
+ if (!result.ok) return fail(result.error.message);
1358
+ console.log(JSON.stringify(result.data, inspectionReplacer, 2));
1359
+ }
1360
+ async function optimize(args) {
1361
+ const input = args[0];
1362
+ if (!input) {
1363
+ throw new Error("Usage: chopper optimize <asset> [output] [--recipe file.json]");
1364
+ }
1365
+ const recipePath = flag(args, "--recipe");
1366
+ const recipe = recipePath ? JSON.parse(await readFile(recipePath, "utf8")) : extname(input).toLowerCase() === ".glb" ? DEFAULT_GLB_RECIPE : DEFAULT_IMAGE_RECIPE;
1367
+ const positionalOutput = args[1]?.startsWith("--") ? void 0 : args[1];
1368
+ const parsed = parse(input);
1369
+ const extension = recipe.kind === "glb" ? ".glb" : outputExtension(recipe.encode);
1370
+ const output = positionalOutput ?? join(dirname(input), `${parsed.name}.optimized${extension}`);
1371
+ const result = await optimizeFile({ input, output, recipe });
1372
+ if (!result.ok) return fail(result.error.message);
1373
+ console.log(
1374
+ `${input} -> ${output} (${result.data.report.beforeBytes} -> ${result.data.report.afterBytes} bytes, ${result.data.report.engineId})`
1375
+ );
1376
+ }
1377
+ async function batch(mode, args) {
1378
+ const result = await runConfig({
1379
+ mode,
1380
+ configPath: flag(args, "--config")
1381
+ });
1382
+ if (!result.ok) return fail(result.error.message);
1383
+ console.log(JSON.stringify(result.data, null, 2));
1384
+ if (result.data.totals.failed || result.data.totals.stale) {
1385
+ process.exitCode = 1;
1386
+ }
1387
+ }
1388
+ async function codecs(args) {
1389
+ if (args[0] !== "sync") {
1390
+ throw new Error("Usage: chopper codecs sync <directory>");
1391
+ }
1392
+ const output = args[1] ?? "public/chopper-codecs";
1393
+ const result = await syncCodecs(output);
1394
+ if (!result.ok) return fail(result.error.message);
1395
+ console.log(`Copied ${result.data.files.length} codec files to ${result.data.directory}`);
1396
+ }
1397
+ function flag(args, name) {
1398
+ const index = args.indexOf(name);
1399
+ return index === -1 ? void 0 : args[index + 1];
1400
+ }
1401
+ function inspectionReplacer(key, value) {
1402
+ return key === "bytes" && value instanceof Uint8Array ? { byteLength: value.byteLength } : value;
1403
+ }
1404
+ function fail(message) {
1405
+ console.error(message);
1406
+ process.exitCode = 1;
1407
+ }
1408
+ function usage() {
1409
+ return `Usage: chopper <command>
1410
+
1411
+ Commands:
1412
+ inspect <asset>
1413
+ optimize <asset> [output] [--recipe recipe.json]
1414
+ run [--config chopper.config.ts]
1415
+ check [--config chopper.config.ts]
1416
+ report [--config chopper.config.ts]
1417
+ codecs sync [directory]`;
1418
+ }
1419
+ main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
1420
+ //# sourceMappingURL=index.js.map
1421
+ //# sourceMappingURL=index.js.map