@bendyline/molen-tooling 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +15 -0
  3. package/README.md +91 -0
  4. package/dist/capture/THIRD-PARTY-NOTICES.md +223 -0
  5. package/dist/capture/basis/LICENSE.txt +55 -0
  6. package/dist/capture/basis/basis_transcoder.js +19 -0
  7. package/dist/capture/basis/basis_transcoder.wasm +0 -0
  8. package/dist/capture/capture.html +15 -0
  9. package/dist/capture/harness.js +4671 -0
  10. package/dist/capture/worldgen-preview.html +15 -0
  11. package/dist/capture/worldgen-preview.js +4617 -0
  12. package/dist/cli.d.mts +1 -0
  13. package/dist/cli.mjs +1276 -0
  14. package/dist/docs-src/guide/3d-art-guidelines.md +157 -0
  15. package/dist/docs-src/guide/3d-model-assets.md +286 -0
  16. package/dist/docs-src/guide/adaptive-performance.md +89 -0
  17. package/dist/docs-src/guide/agent-loop.md +156 -0
  18. package/dist/docs-src/guide/aircraft.md +225 -0
  19. package/dist/docs-src/guide/browser-mount.md +185 -0
  20. package/dist/docs-src/guide/building-interiors.md +175 -0
  21. package/dist/docs-src/guide/capability-authoring.md +69 -0
  22. package/dist/docs-src/guide/determinism.md +285 -0
  23. package/dist/docs-src/guide/entities.md +47 -0
  24. package/dist/docs-src/guide/examples.md +58 -0
  25. package/dist/docs-src/guide/experience-playback.md +57 -0
  26. package/dist/docs-src/guide/figures.md +164 -0
  27. package/dist/docs-src/guide/game-samples.md +100 -0
  28. package/dist/docs-src/guide/graphics-performance.md +167 -0
  29. package/dist/docs-src/guide/input.md +205 -0
  30. package/dist/docs-src/guide/materials.md +125 -0
  31. package/dist/docs-src/guide/project.md +157 -0
  32. package/dist/docs-src/guide/quickstart.md +63 -0
  33. package/dist/docs-src/guide/recognizable-places.md +158 -0
  34. package/dist/docs-src/guide/rendering-backends.md +231 -0
  35. package/dist/docs-src/guide/scripting.md +330 -0
  36. package/dist/docs-src/guide/sky.md +192 -0
  37. package/dist/docs-src/guide/source-bundles.md +42 -0
  38. package/dist/docs-src/guide/structure-library.md +114 -0
  39. package/dist/docs-src/guide/surface-rendering.md +203 -0
  40. package/dist/docs-src/guide/terrain.md +389 -0
  41. package/dist/docs-src/guide/three-surface.md +70 -0
  42. package/dist/docs-src/guide/vehicle-interiors.md +126 -0
  43. package/dist/docs-src/guide/vehicles.md +110 -0
  44. package/dist/docs-src/guide/weather.md +123 -0
  45. package/dist/docs-src/guide/worldgen.md +434 -0
  46. package/dist/docs-src/llms.txt +129 -0
  47. package/dist/docs-src/schemas/README.md +36 -0
  48. package/dist/docs-src/schemas/archstyle.md +2340 -0
  49. package/dist/docs-src/schemas/assert.md +169 -0
  50. package/dist/docs-src/schemas/asset.md +543 -0
  51. package/dist/docs-src/schemas/business-catalog.md +162 -0
  52. package/dist/docs-src/schemas/cameratrack.md +132 -0
  53. package/dist/docs-src/schemas/command.md +112 -0
  54. package/dist/docs-src/schemas/components.md +5826 -0
  55. package/dist/docs-src/schemas/delta.md +204 -0
  56. package/dist/docs-src/schemas/experience-play.md +452 -0
  57. package/dist/docs-src/schemas/figure.md +290 -0
  58. package/dist/docs-src/schemas/interior-catalog.md +230 -0
  59. package/dist/docs-src/schemas/keyframe.md +314 -0
  60. package/dist/docs-src/schemas/landmark-catalog.md +56 -0
  61. package/dist/docs-src/schemas/landmark.md +293 -0
  62. package/dist/docs-src/schemas/matgraph.md +1163 -0
  63. package/dist/docs-src/schemas/pack-index.md +82 -0
  64. package/dist/docs-src/schemas/pack-source.md +139 -0
  65. package/dist/docs-src/schemas/pack.md +225 -0
  66. package/dist/docs-src/schemas/pixelgrid.md +108 -0
  67. package/dist/docs-src/schemas/prefab.md +106 -0
  68. package/dist/docs-src/schemas/project.md +271 -0
  69. package/dist/docs-src/schemas/region-atlas.md +612 -0
  70. package/dist/docs-src/schemas/replay.md +807 -0
  71. package/dist/docs-src/schemas/scatter.md +541 -0
  72. package/dist/docs-src/schemas/scene.md +1152 -0
  73. package/dist/docs-src/schemas/source-bundle.md +266 -0
  74. package/dist/docs-src/schemas/stylepack.md +420 -0
  75. package/dist/docs-src/schemas/terrain-package.md +731 -0
  76. package/dist/docs-src/schemas/terrain.md +313 -0
  77. package/dist/docs-src/schemas/types.md +218 -0
  78. package/dist/docs-src/schemas/uvpaint.md +149 -0
  79. package/dist/docs-src/schemas/worldgen-batch.md +743 -0
  80. package/dist/index.d.mts +1271 -0
  81. package/dist/index.mjs +78 -0
  82. package/dist/mcp-BFnCWrg0.mjs +796 -0
  83. package/dist/ops-BGxhSP6w.mjs +7246 -0
  84. package/package.json +96 -0
package/dist/cli.mjs ADDED
@@ -0,0 +1,1276 @@
1
+ #!/usr/bin/env node
2
+ import { $ as importAsset, A as verifyContentPack, B as describeOps, C as listTypes, D as extractContentPack, E as buildContentPack, F as exportFrames, G as stageAssets, H as checkScripts, I as driveScene, J as formatPacked, K as screenshotAsset, N as previewFigure, O as fetchContentPack, P as listFigurePresets, R as searchDocs, S as checkTypesOp, T as reserveNamespace, V as formatOp, X as inspectAsset, Y as packAsset, Z as listAssets, _ as loadComponentRegistry, b as runReplayFile, c as validateAsset, d as runSimulation, f as screenshotScene, g as listSchemasOp, h as listComponentsOp, i as bakeWorldgen, j as generateTypes, k as inspectContentPack, l as applyUvPaintOp, m as getSchemaOp, n as worldgenStats, ot as playExperience, p as getComponentOp, q as formatBytes, r as previewWorldgen, s as simWatch, t as formatWorldgenStats, u as testTypes, v as scaffoldExperience, w as projectInfo, x as rasterizeMaterial, y as diffSnapshots, z as OPS_CATALOG } from "./ops-BGxhSP6w.mjs";
3
+ import { dirname, join } from "node:path";
4
+ import { readFileSync } from "node:fs";
5
+ import { formatIssues } from "@bendyline/molen-schema";
6
+ import { fileURLToPath } from "node:url";
7
+ //#region src/cli-commands.ts
8
+ /**
9
+ * Second spellings the usage strings deliberately don't advertise. Everything else is derived
10
+ * from OPS_CATALOG, so a flag cannot exist on the CLI without being documented.
11
+ */
12
+ const EXTRA_CLI_FLAGS = {
13
+ frames: { value: ["outDir"] },
14
+ drive: { value: ["out"] },
15
+ play: { value: ["out", "actions"] },
16
+ asset: { value: ["out"] },
17
+ material: { value: ["out"] },
18
+ uvpaint: { value: ["out"] },
19
+ worldgen: { value: ["out-dir"] }
20
+ };
21
+ const FLAG_TOKEN = /^(--[A-Za-z][\w-]*|-[A-Za-z])(=.*)?$/s;
22
+ function stripUsageBrackets(token) {
23
+ return token.replace(/^[[(]+/, "").replace(/[\])]+$/, "");
24
+ }
25
+ /**
26
+ * Derive a command's flags from its documented usage forms: a `--flag` followed by anything that
27
+ * is not another flag takes a value, otherwise it is valueless. Deriving instead of duplicating
28
+ * is what keeps `molen describe`, the generated CLI reference, and the parser in step.
29
+ */
30
+ function flagsFromUsage(cliForms, verb) {
31
+ const spec = {
32
+ value: /* @__PURE__ */ new Set(),
33
+ boolean: /* @__PURE__ */ new Set()
34
+ };
35
+ for (const form of cliForms) {
36
+ const tokens = form.split(/\s+/).filter((t) => t.length > 0);
37
+ for (let i = 0; i < tokens.length; i++) {
38
+ const token = stripUsageBrackets(tokens[i]);
39
+ if (!FLAG_TOKEN.test(token)) continue;
40
+ const name = token.replace(/^--?/, "");
41
+ const next = tokens[i + 1] === void 0 ? "" : stripUsageBrackets(tokens[i + 1]);
42
+ (next.length > 0 && next !== "|" && !FLAG_TOKEN.test(next) ? spec.value : spec.boolean).add(name);
43
+ }
44
+ }
45
+ const extra = EXTRA_CLI_FLAGS[verb];
46
+ for (const name of extra?.value ?? []) spec.value.add(name);
47
+ for (const name of extra?.boolean ?? []) spec.boolean.add(name);
48
+ for (const name of spec.value) spec.boolean.delete(name);
49
+ return spec;
50
+ }
51
+ function cliVerb(op) {
52
+ return op.cli?.split(/\s+/)[1];
53
+ }
54
+ let flagSpecCache;
55
+ /** Declared flags per CLI verb, derived from the ops catalog (built once). */
56
+ function cliFlagSpecs() {
57
+ if (flagSpecCache !== void 0) return flagSpecCache;
58
+ const byVerb = /* @__PURE__ */ new Map();
59
+ for (const op of OPS_CATALOG) {
60
+ const verb = cliVerb(op);
61
+ if (verb === void 0 || op.cli === void 0) continue;
62
+ byVerb.set(verb, [...byVerb.get(verb) ?? [], op.cli]);
63
+ }
64
+ flagSpecCache = new Map([...byVerb].map(([verb, forms]) => [verb, flagsFromUsage(forms, verb)]));
65
+ return flagSpecCache;
66
+ }
67
+ function levenshtein(a, b) {
68
+ const rows = [Array.from({ length: b.length + 1 }, (_, j) => j)];
69
+ for (let i = 1; i <= a.length; i++) {
70
+ const row = [i];
71
+ for (let j = 1; j <= b.length; j++) {
72
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
73
+ row.push(Math.min(rows[i - 1]?.[j] + 1, row[j - 1] + 1, rows[i - 1]?.[j - 1] + cost));
74
+ }
75
+ rows.push(row);
76
+ }
77
+ return rows[a.length]?.[b.length];
78
+ }
79
+ /** " (did you mean --ticks?)" — empty when nothing is close enough to be worth guessing. */
80
+ function didYouMean(name, candidates, prefix = "") {
81
+ let best;
82
+ let bestScore = Number.POSITIVE_INFINITY;
83
+ for (const candidate of candidates) {
84
+ const score = levenshtein(name.toLowerCase(), candidate.toLowerCase());
85
+ if (score < bestScore) {
86
+ bestScore = score;
87
+ best = candidate;
88
+ }
89
+ }
90
+ if (best === void 0 || bestScore > Math.max(2, Math.floor(name.length / 3))) return "";
91
+ return ` (did you mean ${prefix}${best}?)`;
92
+ }
93
+ /**
94
+ * Parse `argv` for one command. With a FlagSpec: `--key=value` is understood, declared valueless
95
+ * flags never swallow the following positional, and undeclared flags are reported instead of
96
+ * silently ignored. Without one the legacy permissive behaviour is kept.
97
+ */
98
+ function parseArgs(argv, spec) {
99
+ const positionals = [];
100
+ const flags = {};
101
+ const unknownFlags = [];
102
+ const flagErrors = [];
103
+ for (let i = 0; i < argv.length; i++) {
104
+ const a = argv[i];
105
+ if (a === "--") {
106
+ positionals.push(...argv.slice(i + 1));
107
+ break;
108
+ }
109
+ if (!FLAG_TOKEN.test(a)) {
110
+ positionals.push(a);
111
+ continue;
112
+ }
113
+ const eq = a.indexOf("=");
114
+ const token = eq === -1 ? a : a.slice(0, eq);
115
+ const inlineValue = eq === -1 ? void 0 : a.slice(eq + 1);
116
+ const key = token.replace(/^--?/, "");
117
+ const isBoolean = spec?.boolean.has(key) === true;
118
+ if (spec !== void 0 && !isBoolean && !spec.value.has(key)) unknownFlags.push(token);
119
+ if (inlineValue !== void 0) {
120
+ if (isBoolean) if (inlineValue === "true" || inlineValue === "") flags[key] = true;
121
+ else if (inlineValue === "false") flags[key] = false;
122
+ else flagErrors.push(`${token} takes no value (got "${inlineValue}")`);
123
+ else flags[key] = inlineValue;
124
+ continue;
125
+ }
126
+ if (isBoolean) {
127
+ flags[key] = true;
128
+ continue;
129
+ }
130
+ const next = argv[i + 1];
131
+ const nextIsFlag = next !== void 0 && (next.startsWith("--") || spec !== void 0 && FLAG_TOKEN.test(next));
132
+ if (next !== void 0 && !nextIsFlag) {
133
+ flags[key] = next;
134
+ i++;
135
+ } else flags[key] = true;
136
+ }
137
+ return {
138
+ positionals,
139
+ flags,
140
+ ...unknownFlags.length > 0 ? { unknownFlags } : {},
141
+ ...flagErrors.length > 0 ? { flagErrors } : {}
142
+ };
143
+ }
144
+ function out(s) {
145
+ process.stdout.write(`${s}\n`);
146
+ }
147
+ function err(s) {
148
+ process.stderr.write(`${s}\n`);
149
+ }
150
+ function str(v) {
151
+ return typeof v === "string" ? v : void 0;
152
+ }
153
+ /** Parse "x,y,z"; returns undefined if absent, null if present-but-malformed (a real error). */
154
+ function parseVec3(v) {
155
+ if (v === void 0) return void 0;
156
+ if (typeof v !== "string") return null;
157
+ const parts = v.split(",").map(Number);
158
+ if (parts.length !== 3 || parts.some(Number.isNaN)) return null;
159
+ return [
160
+ parts[0],
161
+ parts[1],
162
+ parts[2]
163
+ ];
164
+ }
165
+ async function cmdValidate(args) {
166
+ const path = args.positionals[0];
167
+ if (path === void 0) {
168
+ err("usage: molen validate <path> [--kind <kind>] [--project <project.json>] [--verify-files]");
169
+ return 2;
170
+ }
171
+ const result = await validateAsset({
172
+ path,
173
+ kind: str(args.flags.kind),
174
+ verifyFiles: args.flags["verify-files"] === true,
175
+ ...str(args.flags.project) !== void 0 ? { projectPath: str(args.flags.project) } : {}
176
+ });
177
+ if (result.ok) {
178
+ out(`✓ ${path} is a valid ${result.kind}`);
179
+ if (result.verifiedFiles !== void 0) out(`✓ verified ${result.verifiedFiles} package files (size + SHA-256)`);
180
+ return 0;
181
+ }
182
+ err(result.formatted ?? "validation failed");
183
+ return 1;
184
+ }
185
+ async function cmdSim(args) {
186
+ if (args.positionals[0] === "watch" && args.positionals[1] !== void 0) {
187
+ const ticks = typeof args.flags.ticks === "string" ? Number(args.flags.ticks) : 0;
188
+ if (!Number.isInteger(ticks) || ticks <= 0) {
189
+ err("--ticks <N> is required and must be a positive integer");
190
+ return 2;
191
+ }
192
+ await simWatch({
193
+ scenePath: args.positionals[1],
194
+ ticks,
195
+ commandsPath: str(args.flags.commands),
196
+ assertPath: str(args.flags.assert),
197
+ setupModule: str(args.flags.setup),
198
+ projectPath: str(args.flags.project),
199
+ onRun: (result, diff) => {
200
+ const stamp = `— tick ${result.tick}, ${result.eventCount} events`;
201
+ if (result.error !== void 0) err(`✖ ${result.error}`);
202
+ else out(`${result.ok ? "✓" : "✖"} ${stamp} [${diff}]`);
203
+ if (result.assertionsFormatted !== void 0) out(result.assertionsFormatted);
204
+ }
205
+ });
206
+ out("watching for changes (ctrl-c to stop)…");
207
+ return await new Promise(() => {});
208
+ }
209
+ if (args.positionals[0] !== "run" || args.positionals[1] === void 0) {
210
+ err("usage: molen sim run <scene> --ticks <N> [--commands f] [--assert f] [--setup m] [--project p] [--hash]\n molen sim watch <scene> --ticks <N> [--commands f] [--assert f] [--setup m] [--project p]");
211
+ return 2;
212
+ }
213
+ const scenePath = args.positionals[1];
214
+ const ticks = typeof args.flags.ticks === "string" ? Number(args.flags.ticks) : 0;
215
+ if (!Number.isInteger(ticks) || ticks <= 0) {
216
+ err("--ticks <N> is required and must be a positive integer");
217
+ return 2;
218
+ }
219
+ const result = await runSimulation({
220
+ scenePath,
221
+ ticks,
222
+ commandsPath: str(args.flags.commands),
223
+ assertPath: str(args.flags.assert),
224
+ setupModule: str(args.flags.setup),
225
+ projectPath: str(args.flags.project)
226
+ });
227
+ if (result.error !== void 0) {
228
+ err(result.error);
229
+ return 1;
230
+ }
231
+ out(`tick: ${result.tick}`);
232
+ if (args.flags.hash === true) {
233
+ out(`hash: ${result.stateHash}`);
234
+ for (const [domain, entry] of Object.entries(result.content ?? {})) out(`content: ${domain} ${entry.hash}${entry.packs ? ` (${entry.packs.join(", ")})` : ""}`);
235
+ }
236
+ out(`events: ${result.eventCount}`);
237
+ if (result.physics !== void 0 && result.physics !== "none") out(result.physics === "rapier" ? "physics: rapier (deterministic same-build/same-platform only)" : `physics: ${result.physics} (cross-platform deterministic)`);
238
+ if (result.assertionsFormatted !== void 0) out(result.assertionsFormatted);
239
+ return result.ok ? 0 : 1;
240
+ }
241
+ async function cmdShot(args) {
242
+ const scenePath = args.positionals[0];
243
+ const outPath = str(args.flags.out);
244
+ if (scenePath === void 0 || outPath === void 0) {
245
+ err("usage: molen shot <scene> --out <png> [--ticks N] [--setup m] [--project p] [--camera x,y,z] [--look x,y,z] [--size WxH] [--clear-color css] [--terrain d.json --heightmap h.png] [--variant ktx2]");
246
+ return 2;
247
+ }
248
+ const ticksRaw = typeof args.flags.ticks === "string" ? Number(args.flags.ticks) : 0;
249
+ const position = parseVec3(args.flags.camera);
250
+ if (position === null) {
251
+ err(`--camera "${String(args.flags.camera)}" must be three numbers, e.g. --camera 0,6,16`);
252
+ return 2;
253
+ }
254
+ const lookAt = parseVec3(args.flags.look);
255
+ if (lookAt === null) {
256
+ err(`--look "${String(args.flags.look)}" must be three numbers, e.g. --look 0,0,0`);
257
+ return 2;
258
+ }
259
+ let size;
260
+ if (args.flags.size !== void 0) {
261
+ const [w, h] = (str(args.flags.size) ?? "").split("x").map(Number);
262
+ if (w === void 0 || h === void 0 || Number.isNaN(w) || Number.isNaN(h)) {
263
+ err(`--size "${String(args.flags.size)}" must be WxH, e.g. --size 1280x720`);
264
+ return 2;
265
+ }
266
+ size = [w, h];
267
+ }
268
+ const terrainPath = str(args.flags.terrain);
269
+ const heightmapPath = str(args.flags.heightmap);
270
+ if (terrainPath !== void 0 && heightmapPath === void 0) {
271
+ err("--terrain requires --heightmap <png>");
272
+ return 2;
273
+ }
274
+ const result = await screenshotScene({
275
+ scenePath,
276
+ outPath,
277
+ ticks: Number.isInteger(ticksRaw) && ticksRaw > 0 ? ticksRaw : 0,
278
+ setupModule: str(args.flags.setup),
279
+ projectPath: str(args.flags.project),
280
+ ...position !== void 0 ? { camera: {
281
+ position,
282
+ ...lookAt ? { lookAt } : {}
283
+ } } : {},
284
+ ...size !== void 0 ? { size } : {},
285
+ ...terrainPath !== void 0 && heightmapPath !== void 0 ? { terrain: {
286
+ descriptorPath: terrainPath,
287
+ heightmapPath
288
+ } } : {},
289
+ ...str(args.flags["clear-color"]) !== void 0 ? { clearColor: str(args.flags["clear-color"]) } : {},
290
+ ...str(args.flags.variant) !== void 0 ? { assetVariant: str(args.flags.variant) } : {}
291
+ });
292
+ if (!result.ok) {
293
+ err(result.error ?? "screenshot failed");
294
+ return 1;
295
+ }
296
+ out(`wrote ${result.imagePath}`);
297
+ out(`tick: ${result.tick} hash: ${result.stateHash}`);
298
+ const s = result.renderStats;
299
+ if (s !== void 0) out(`rendered: ${s.entitiesRendered} entities, ${s.drawCalls} draw calls, ${s.triangles} triangles`);
300
+ return 0;
301
+ }
302
+ async function cmdMaterial(args) {
303
+ if (args.positionals[0] !== "bake") {
304
+ err("usage: molen material bake <matgraph.json> -o <png> [or --ref palette:#rrggbb -o <png>]");
305
+ return 2;
306
+ }
307
+ const outPath = str(args.flags.o) ?? str(args.flags.out);
308
+ if (outPath === void 0) {
309
+ err("material bake requires -o <png>");
310
+ return 2;
311
+ }
312
+ const ref = str(args.flags.ref);
313
+ const path = args.positionals[1];
314
+ if (ref === void 0 && path === void 0) {
315
+ err("material bake requires a <matgraph.json> path or --ref");
316
+ return 2;
317
+ }
318
+ const result = await rasterizeMaterial({
319
+ outPath,
320
+ ...ref !== void 0 ? { ref } : {},
321
+ ...path !== void 0 ? { path } : {}
322
+ });
323
+ if (!result.ok) {
324
+ err(result.error ?? "bake failed");
325
+ return 1;
326
+ }
327
+ out(`wrote ${result.imagePath} (${result.width}x${result.height}, slots: ${result.slots?.join(", ")})`);
328
+ return 0;
329
+ }
330
+ async function cmdUvPaint(args) {
331
+ const painted = args.positionals[0] === "apply" ? args.positionals[1] : void 0;
332
+ const islands = str(args.flags.islands);
333
+ const outPath = str(args.flags.o) ?? str(args.flags.out);
334
+ if (painted === void 0 || islands === void 0 || outPath === void 0) {
335
+ err("usage: molen uvpaint apply <painted.png> --islands <map.png> -o <out.png> [--no-mask] [--dilate N]");
336
+ return 2;
337
+ }
338
+ const dilateRaw = str(args.flags.dilate);
339
+ const dilationPx = dilateRaw !== void 0 ? Number(dilateRaw) : void 0;
340
+ if (dilationPx !== void 0 && (!Number.isInteger(dilationPx) || dilationPx < 0)) {
341
+ err(`--dilate "${String(dilateRaw)}" must be a non-negative integer`);
342
+ return 2;
343
+ }
344
+ const result = await applyUvPaintOp({
345
+ paintedPath: painted,
346
+ islandMapPath: islands,
347
+ outPath,
348
+ ...args.flags["no-mask"] === true ? { maskToIslands: false } : {},
349
+ ...dilationPx !== void 0 ? { dilationPx } : {}
350
+ });
351
+ if (!result.ok) {
352
+ err(result.error ?? "uvpaint failed");
353
+ return 1;
354
+ }
355
+ out(`wrote ${result.imagePath} (${result.width}x${result.height})`);
356
+ return 0;
357
+ }
358
+ async function cmdFrames(args) {
359
+ const scenePath = args.positionals[0];
360
+ const outDir = str(args.flags["out-dir"]) ?? str(args.flags.outDir);
361
+ const from = Number(str(args.flags.from));
362
+ const to = Number(str(args.flags.to));
363
+ if (scenePath === void 0 || outDir === void 0 || Number.isNaN(from) || Number.isNaN(to)) {
364
+ err("usage: molen frames <scene> --out-dir <d> --from <N> --to <M> [--step S] [--setup m] [--project p] [--track f] [--camera x,y,z] [--look x,y,z] [--size WxH]");
365
+ return 2;
366
+ }
367
+ const position = parseVec3(args.flags.camera);
368
+ const lookAt = parseVec3(args.flags.look);
369
+ if (position === null || lookAt === null) {
370
+ err("--camera/--look must be three numbers, e.g. --camera 0,6,16");
371
+ return 2;
372
+ }
373
+ let size;
374
+ if (args.flags.size !== void 0) {
375
+ const [w, h] = (str(args.flags.size) ?? "").split("x").map(Number);
376
+ if (w === void 0 || h === void 0 || Number.isNaN(w) || Number.isNaN(h)) {
377
+ err("--size must be WxH, e.g. --size 1280x720");
378
+ return 2;
379
+ }
380
+ size = [w, h];
381
+ }
382
+ const stepRaw = str(args.flags.step);
383
+ const result = await exportFrames({
384
+ scenePath,
385
+ outDir,
386
+ from,
387
+ to,
388
+ ...stepRaw !== void 0 ? { step: Number(stepRaw) } : {},
389
+ setupModule: str(args.flags.setup),
390
+ projectPath: str(args.flags.project),
391
+ trackPath: str(args.flags.track),
392
+ ...position !== void 0 ? { camera: {
393
+ position,
394
+ ...lookAt ? { lookAt } : {}
395
+ } } : {},
396
+ ...size !== void 0 ? { size } : {}
397
+ });
398
+ if (!result.ok) {
399
+ err(result.error ?? "export failed");
400
+ return 1;
401
+ }
402
+ out(`wrote ${result.frameCount} frames to ${result.dir}`);
403
+ return 0;
404
+ }
405
+ async function cmdReplay(args) {
406
+ const path = args.positionals[0];
407
+ if (path === void 0) {
408
+ err("usage: molen replay <fixture.replay.json> [--setup <m>] [--project <p>] [--record]");
409
+ return 2;
410
+ }
411
+ const result = await runReplayFile({
412
+ path,
413
+ setupModule: str(args.flags.setup),
414
+ projectPath: str(args.flags.project),
415
+ record: args.flags.record === true
416
+ });
417
+ if (result.error !== void 0) {
418
+ err(result.error);
419
+ return 1;
420
+ }
421
+ out(result.report ?? (result.ok ? "✓ replay matches" : "✖ replay diverged"));
422
+ return result.ok ? 0 : 1;
423
+ }
424
+ async function cmdDiff(args) {
425
+ const [a, b] = args.positionals;
426
+ if (a === void 0 || b === void 0) {
427
+ err("usage: molen diff <a.keyframe.json> <b.keyframe.json>");
428
+ return 2;
429
+ }
430
+ const result = await diffSnapshots({
431
+ a,
432
+ b
433
+ });
434
+ if (!result.ok) {
435
+ err(result.error ?? "diff failed");
436
+ return 1;
437
+ }
438
+ const diffs = result.diffs ?? [];
439
+ if (diffs.length === 0) {
440
+ out("no differences");
441
+ return 0;
442
+ }
443
+ for (const d of diffs) out(`${d.kind} ${d.entity}.${d.component}` + (d.kind === "changed" ? `: ${JSON.stringify(d.before)} -> ${JSON.stringify(d.after)}` : ""));
444
+ return 0;
445
+ }
446
+ async function cmdDocs(args) {
447
+ if (args.positionals[0] !== "search" || args.positionals[1] === void 0) {
448
+ err("usage: molen docs search <query> [-k N] [--design]");
449
+ return 2;
450
+ }
451
+ const query = args.positionals.slice(1).join(" ");
452
+ const kRaw = str(args.flags.k);
453
+ out((await searchDocs({
454
+ query,
455
+ ...kRaw !== void 0 ? { k: Number(kRaw) } : {},
456
+ includeDesign: args.flags.design === true
457
+ })).formatted);
458
+ return 0;
459
+ }
460
+ function cmdSchema(args) {
461
+ const sub = args.positionals[0];
462
+ if (sub === "list" || sub === void 0) {
463
+ for (const s of listSchemasOp()) out(`${s.kind.padEnd(10)} ${s.id.padEnd(20)} ${s.title}`);
464
+ return 0;
465
+ }
466
+ if (sub === "get") {
467
+ const kind = args.positionals[1];
468
+ if (kind === void 0) {
469
+ err("usage: molen schema get <kind>");
470
+ return 2;
471
+ }
472
+ const r = getSchemaOp(kind);
473
+ if (!r.ok) {
474
+ err(r.error ?? "unknown kind");
475
+ return 1;
476
+ }
477
+ out(JSON.stringify({
478
+ id: r.id,
479
+ docsRef: r.docsRef,
480
+ examples: r.examples,
481
+ jsonSchema: r.jsonSchema
482
+ }, null, 2));
483
+ return 0;
484
+ }
485
+ err("usage: molen schema list | molen schema get <kind>");
486
+ return 2;
487
+ }
488
+ async function cmdComponents(args) {
489
+ const registry = await loadComponentRegistry({
490
+ projectPath: str(args.flags.project),
491
+ scenePath: str(args.flags.scene)
492
+ });
493
+ for (const c of listComponentsOp(registry)) out(`${c.name.padEnd(15)} ${(c.owner ?? "").padEnd(18)} ${c.description}`);
494
+ return 0;
495
+ }
496
+ async function cmdComponent(args) {
497
+ const name = args.positionals[0];
498
+ if (name === void 0) {
499
+ err("usage: molen component <name>");
500
+ return 2;
501
+ }
502
+ const r = getComponentOp(name, await loadComponentRegistry({
503
+ projectPath: str(args.flags.project),
504
+ scenePath: str(args.flags.scene)
505
+ }));
506
+ if (!r.ok) {
507
+ err(r.error ?? "unknown component");
508
+ return 1;
509
+ }
510
+ out(JSON.stringify(r, null, 2));
511
+ return 0;
512
+ }
513
+ function cmdDescribe(args) {
514
+ const ops = describeOps(args.positionals[0]);
515
+ if (ops.length === 0) {
516
+ err(`no op matching "${args.positionals[0]}". Try: molen describe`);
517
+ return 1;
518
+ }
519
+ out(ops.map(formatOp).join("\n\n"));
520
+ return 0;
521
+ }
522
+ async function cmdNew(args) {
523
+ const name = args.positionals[0];
524
+ if (name === void 0) {
525
+ err("usage: molen new <name> [--dir <path>] [--force]");
526
+ return 2;
527
+ }
528
+ const result = await scaffoldExperience({
529
+ name,
530
+ dir: str(args.flags.dir),
531
+ force: args.flags.force === true
532
+ });
533
+ if (!result.ok) {
534
+ err(result.error ?? "scaffold failed");
535
+ return 1;
536
+ }
537
+ out(`created ${result.dir}`);
538
+ for (const f of result.files ?? []) out(` ${f}`);
539
+ out("\nnext:");
540
+ for (const step of result.nextSteps ?? []) out(` ${step}`);
541
+ return 0;
542
+ }
543
+ async function cmdAsset(args) {
544
+ const sub = args.positionals[0];
545
+ if (sub === "import") {
546
+ const path = args.positionals[1];
547
+ if (path === void 0) {
548
+ err("usage: molen asset import <file.glb> [--id <asset-id>] [--trimesh] [--no-optimize] [--out-dir <d>] [--project <project.json>] [--force]");
549
+ return 2;
550
+ }
551
+ const r = await importAsset({
552
+ path,
553
+ id: str(args.flags.id),
554
+ outDir: str(args.flags["out-dir"]),
555
+ trimesh: args.flags.trimesh === true,
556
+ ...args.flags["no-optimize"] === true ? { optimize: false } : {},
557
+ projectPath: str(args.flags.project),
558
+ force: args.flags.force === true
559
+ });
560
+ if (!r.ok) {
561
+ err(r.error ?? "import failed");
562
+ return 1;
563
+ }
564
+ const s = r.sidecar;
565
+ out(`imported "${r.id}" -> ${r.dir}`);
566
+ out(` ${s.stats.triangles} tris, ${s.stats.meshes} meshes, ${s.stats.animations} clips, ${s.collision.hulls.length} hulls${s.collision.trimesh !== void 0 ? " + trimesh" : ""}`);
567
+ out(` ${r.registered === true ? `registered in ${r.projectPath}` : "NOT registered (no project.json found)"}`);
568
+ for (const w of r.warnings ?? []) out(` ! ${w}`);
569
+ return 0;
570
+ }
571
+ if (sub === "inspect") {
572
+ const ref = args.positionals[1];
573
+ if (ref === void 0) {
574
+ err("usage: molen asset inspect <sidecar.json | asset-id> [--verify]");
575
+ return 2;
576
+ }
577
+ const r = await inspectAsset({
578
+ ref,
579
+ verify: args.flags.verify === true,
580
+ projectPath: str(args.flags.project)
581
+ });
582
+ if (!r.ok) {
583
+ err(r.error ?? (r.verifyErrors ?? []).join("\n"));
584
+ return 1;
585
+ }
586
+ out(JSON.stringify(r.sidecar, null, 2));
587
+ if (r.verified === true) out("✓ file hashes verified");
588
+ return 0;
589
+ }
590
+ if (sub === "list") {
591
+ const r = await listAssets({ projectPath: str(args.flags.project) });
592
+ if (!r.ok) {
593
+ err(r.error ?? "failed");
594
+ return 1;
595
+ }
596
+ for (const a of r.assets ?? []) out(`${a.id.padEnd(24)} ${(a.kind ?? "?").padEnd(6)} ${a.triangles ?? "?"} tris ${a.sidecar}`);
597
+ if ((r.assets ?? []).length === 0) out("(no assets registered)");
598
+ return 0;
599
+ }
600
+ if (sub === "shot") {
601
+ const ref = args.positionals[1];
602
+ const outDir = str(args.flags["out-dir"]) ?? str(args.flags.out);
603
+ if (ref === void 0 || outDir === void 0) {
604
+ err("usage: molen asset shot <asset-id|sidecar> --out-dir <d> [--angles N] [--clip name --time s] [--variant ktx2]");
605
+ return 2;
606
+ }
607
+ const anglesRaw = str(args.flags.angles);
608
+ const timeRaw = str(args.flags.time);
609
+ const r = await screenshotAsset({
610
+ ref,
611
+ outDir,
612
+ projectPath: str(args.flags.project),
613
+ ...anglesRaw !== void 0 ? { angles: Number(anglesRaw) } : {},
614
+ ...str(args.flags.clip) !== void 0 ? { clip: str(args.flags.clip) } : {},
615
+ ...timeRaw !== void 0 ? { clipTime: Number(timeRaw) } : {},
616
+ ...str(args.flags.variant) !== void 0 ? { assetVariant: str(args.flags.variant) } : {}
617
+ });
618
+ if (!r.ok) {
619
+ err(r.error ?? "asset shot failed");
620
+ return 1;
621
+ }
622
+ for (const f of r.frames ?? []) out(`wrote ${f.path}`);
623
+ out(`triangles: ${r.triangles}`);
624
+ return 0;
625
+ }
626
+ if (sub === "pack") {
627
+ const ref = args.positionals[1];
628
+ const all = args.flags.all === true;
629
+ if (ref === void 0 && !all) {
630
+ err("usage: molen asset pack <asset-id|sidecar> | --all [--variant ktx2] [--mode auto|etc1s|uastc] [--max-size N] [--no-pot] [--etc1s-quality N] [--uastc-quality N]");
631
+ return 2;
632
+ }
633
+ const mode = str(args.flags.mode);
634
+ if (mode !== void 0 && mode !== "auto" && mode !== "etc1s" && mode !== "uastc") {
635
+ err(`--mode "${mode}" must be auto, etc1s, or uastc`);
636
+ return 2;
637
+ }
638
+ const num = (flag) => {
639
+ const raw = str(args.flags[flag]);
640
+ return raw === void 0 ? void 0 : Number(raw);
641
+ };
642
+ const r = await packAsset({
643
+ ...ref !== void 0 ? { ref } : {},
644
+ ...all ? { all: true } : {},
645
+ projectPath: str(args.flags.project),
646
+ ...str(args.flags.variant) !== void 0 ? { variant: str(args.flags.variant) } : {},
647
+ ...mode !== void 0 ? { mode } : {},
648
+ ...num("max-size") !== void 0 ? { maxSize: num("max-size") } : {},
649
+ ...args.flags["no-pot"] === true ? { powerOfTwo: false } : {},
650
+ ...num("etc1s-quality") !== void 0 ? { etc1sQuality: num("etc1s-quality") } : {},
651
+ ...num("uastc-quality") !== void 0 ? { uastcQuality: num("uastc-quality") } : {}
652
+ });
653
+ if (!r.ok) {
654
+ err(r.error ?? "pack failed");
655
+ return 1;
656
+ }
657
+ for (const line of formatPacked(r.assets ?? [])) out(line);
658
+ for (const w of r.warnings ?? []) out(` ! ${w}`);
659
+ return 0;
660
+ }
661
+ if (sub === "stage") {
662
+ const outDir = str(args.flags["out-dir"]) ?? str(args.flags.out);
663
+ if (outDir === void 0) {
664
+ err("usage: molen asset stage --out-dir <d> [--variant ktx2] [--require-variant] [--clean] [--project <path>]");
665
+ return 2;
666
+ }
667
+ const r = await stageAssets({
668
+ outDir,
669
+ projectPath: str(args.flags.project),
670
+ ...str(args.flags.variant) !== void 0 ? { variant: str(args.flags.variant) } : {},
671
+ ...args.flags["require-variant"] === true ? { requireVariant: true } : {},
672
+ ...args.flags.clean === true ? { clean: true } : {}
673
+ });
674
+ if (!r.ok) {
675
+ err(r.error ?? "stage failed");
676
+ return 1;
677
+ }
678
+ for (const a of r.assets ?? []) out(`${a.id.padEnd(24)} ${a.file}${a.variant !== void 0 ? ` [${a.variant}]` : ""} ${formatBytes(a.bytes)}`);
679
+ out(`wrote ${r.indexPath} (${(r.assets ?? []).length} assets)`);
680
+ for (const w of r.warnings ?? []) out(` ! ${w}`);
681
+ return 0;
682
+ }
683
+ err("usage: molen asset import <file> | inspect <ref> [--verify] | list | shot <ref> --out-dir <d> | pack <ref>|--all | stage --out-dir <d>");
684
+ return 2;
685
+ }
686
+ const PACK_USAGE = "usage: molen pack build <sourceDir> --out-dir <d> [--no-solid] | inspect <source> | verify <source> | extract <source> --out-dir <d> | fetch <url> [ids…] [--out-dir <d>] [--project <path>]";
687
+ async function cmdPack(args) {
688
+ const [sub, target, ...rest] = args.positionals;
689
+ const outDir = str(args.flags["out-dir"]);
690
+ if (sub === "build" && target !== void 0 && outDir !== void 0) {
691
+ const r = await buildContentPack({
692
+ sourceDir: target,
693
+ outDir,
694
+ ...args.flags["no-solid"] === true ? { solid: false } : {}
695
+ });
696
+ if (!r.ok) {
697
+ err(r.error ?? "pack build failed");
698
+ return 1;
699
+ }
700
+ out(`${r.id}@${r.version}: ${r.files} files -> ${r.path} (${formatBytes(r.size ?? 0)})`);
701
+ out(` contentHash ${r.contentHash}`);
702
+ out(` index ${r.indexPath}`);
703
+ return 0;
704
+ }
705
+ if (sub === "inspect" && target !== void 0) {
706
+ const r = await inspectContentPack({ source: target });
707
+ if (!r.ok) {
708
+ err(r.error ?? "pack inspect failed");
709
+ return 1;
710
+ }
711
+ const size = r.fileSize !== void 0 ? `, ${formatBytes(r.fileSize)} packed` : "";
712
+ out(`${r.id}@${r.version}${r.title !== void 0 ? ` — ${r.title}` : ""}`);
713
+ out(` ${r.files} files, ${formatBytes(r.contentSize ?? 0)} of content${size}`);
714
+ out(` contentHash ${r.contentHash}${r.license !== void 0 ? `, license ${r.license}` : ""}`);
715
+ for (const block of r.blocks ?? []) out(` block ${block.name}: ${block.files} files, ${formatBytes(block.size)}`);
716
+ for (const [role, paths] of Object.entries(r.provides ?? {})) out(` provides ${role}: ${paths.join(", ")}`);
717
+ out(` ${Object.keys(r.ids ?? {}).length} asset ids`);
718
+ for (const file of r.largest ?? []) out(` ${formatBytes(file.size).padStart(10)} ${file.path}`);
719
+ return 0;
720
+ }
721
+ if (sub === "verify" && target !== void 0) {
722
+ const r = await verifyContentPack({ source: target });
723
+ if (r.error !== void 0) {
724
+ err(r.error);
725
+ return 1;
726
+ }
727
+ for (const issue of r.issues ?? []) err(`✗ ${issue.path}: ${issue.message}`);
728
+ const summary = `${r.checked} files checked, ${r.validated} documents validated`;
729
+ if (!r.ok) {
730
+ err(`${r.id}: ${(r.issues ?? []).length} problems (${summary})`);
731
+ return 1;
732
+ }
733
+ out(`✓ ${r.id}: ${summary}`);
734
+ return 0;
735
+ }
736
+ if (sub === "extract" && target !== void 0 && outDir !== void 0) {
737
+ const r = await extractContentPack({
738
+ source: target,
739
+ outDir
740
+ });
741
+ if (!r.ok) {
742
+ err(r.error ?? "pack extract failed");
743
+ return 1;
744
+ }
745
+ out(`${r.id}: ${r.files} files -> ${r.outDir}`);
746
+ return 0;
747
+ }
748
+ if (sub === "fetch" && target !== void 0) {
749
+ const r = await fetchContentPack({
750
+ url: target,
751
+ ...rest.length > 0 ? { ids: rest } : {},
752
+ ...outDir !== void 0 ? { outDir } : {},
753
+ ...str(args.flags.project) !== void 0 ? { projectPath: str(args.flags.project) } : {}
754
+ });
755
+ if (!r.ok) {
756
+ err(r.error ?? "pack fetch failed");
757
+ return 1;
758
+ }
759
+ for (const pack of r.packs ?? []) out(`${pack.id}@${pack.version} -> ${r.outDir}/${pack.file} (${formatBytes(pack.size)})`);
760
+ out(r.projectPath !== void 0 ? `pinned in ${r.projectPath}` : "no project.json to pin in");
761
+ return 0;
762
+ }
763
+ err(PACK_USAGE);
764
+ return 2;
765
+ }
766
+ async function cmdDrive(args) {
767
+ const scenePath = args.positionals[0];
768
+ const actionsPath = str(args.flags.actions);
769
+ const outDir = str(args.flags["out-dir"]) ?? str(args.flags.out);
770
+ if (scenePath === void 0 || actionsPath === void 0 || outDir === void 0) {
771
+ err("usage: molen drive <scene|name> --actions <actions.json> --out-dir <d> [--setup m] [--until N] [--assert f]");
772
+ return 2;
773
+ }
774
+ const { readFile } = await import("node:fs/promises");
775
+ let actions;
776
+ try {
777
+ actions = JSON.parse(await readFile(actionsPath, "utf8"));
778
+ } catch (e) {
779
+ err(`${actionsPath}: ${e.message}`);
780
+ return 1;
781
+ }
782
+ if (!Array.isArray(actions)) {
783
+ err(`${actionsPath}: expected a JSON array of actions [{at, command?, screenshot?}]`);
784
+ return 1;
785
+ }
786
+ const untilRaw = str(args.flags.until);
787
+ const r = await driveScene({
788
+ scenePath,
789
+ actions,
790
+ outDir,
791
+ setupModule: str(args.flags.setup),
792
+ assertPath: str(args.flags.assert),
793
+ projectPath: str(args.flags.project),
794
+ ...untilRaw !== void 0 ? { until: Number(untilRaw) } : {}
795
+ });
796
+ if (r.error !== void 0) {
797
+ err(r.error);
798
+ return 1;
799
+ }
800
+ for (const f of r.frames ?? []) out(`frame "${f.name}" @ tick ${f.tick} -> ${f.path}`);
801
+ out(`tick: ${r.tick} hash: ${r.stateHash} events: ${r.events?.length ?? 0}`);
802
+ if (r.assertionsFormatted !== void 0) out(r.assertionsFormatted);
803
+ return r.ok ? 0 : 1;
804
+ }
805
+ async function cmdPlay(args) {
806
+ const appDir = args.positionals[0];
807
+ const scenarioPath = str(args.flags.scenario) ?? str(args.flags.actions);
808
+ const outDir = str(args.flags["out-dir"]) ?? str(args.flags.out);
809
+ if (appDir === void 0 || scenarioPath === void 0 || outDir === void 0) {
810
+ err("usage: molen play <built-app-dir> --scenario <experience-play.json> --out-dir <d> [--headed]");
811
+ return 2;
812
+ }
813
+ const { readFile } = await import("node:fs/promises");
814
+ let scenario;
815
+ try {
816
+ scenario = JSON.parse(await readFile(scenarioPath, "utf8"));
817
+ } catch (error) {
818
+ err(`${scenarioPath}: ${error.message}`);
819
+ return 1;
820
+ }
821
+ const result = await playExperience({
822
+ appDir,
823
+ scenario,
824
+ outDir,
825
+ headed: args.flags.headed === true
826
+ });
827
+ if (result.error !== void 0) {
828
+ err(result.error);
829
+ if (result.manifestPath !== void 0) out(`failed run manifest: ${result.manifestPath}`);
830
+ return 1;
831
+ }
832
+ for (const frame of result.frames ?? []) out(`frame "${frame.name}" @ action ${frame.actionIndex} -> ${frame.path}`);
833
+ for (const diagnostic of result.diagnostics ?? []) err(`${diagnostic.kind} @ action ${diagnostic.actionIndex}: ${diagnostic.text}`);
834
+ if (result.manifestPath !== void 0) out(`run manifest: ${result.manifestPath}`);
835
+ return result.ok ? 0 : 1;
836
+ }
837
+ async function cmdProject(args) {
838
+ if (args.positionals[0] !== "info" && args.positionals[0] !== void 0) {
839
+ err("usage: molen project info [--project <path>]");
840
+ return 2;
841
+ }
842
+ const r = await projectInfo({ projectPath: str(args.flags.project) });
843
+ if (r.error !== void 0) {
844
+ err(r.error);
845
+ return 1;
846
+ }
847
+ out(`project: ${r.name} (${r.path})`);
848
+ out(`scenes: ${Object.keys(r.scenes ?? {}).join(", ") || "(none)"}`);
849
+ if (r.defaultScene !== void 0) out(`default scene: ${r.defaultScene}`);
850
+ out(`types: ${(r.typeIds ?? []).join(", ") || "(none)"}`);
851
+ out(`assets: ${Object.keys(r.assets ?? {}).join(", ") || "(none)"}`);
852
+ for (const res of r.reservations ?? []) out(`reserved: ${res.namespace} -> ${res.owner}${res.note !== void 0 ? ` (${res.note})` : ""}`);
853
+ if (r.issues !== void 0 && r.issues.length > 0) {
854
+ err(formatIssues("project types", r.issues));
855
+ return 1;
856
+ }
857
+ return 0;
858
+ }
859
+ async function cmdScripts(args) {
860
+ const sub = args.positionals[0];
861
+ if (sub !== void 0 && sub !== "check") {
862
+ err("usage: molen scripts check [--project <path>]");
863
+ return 2;
864
+ }
865
+ const r = await checkScripts({ projectPath: str(args.flags.project) });
866
+ if (r.error !== void 0) {
867
+ err(r.error);
868
+ for (const path of [...r.stale ?? [], ...r.ungenerated ?? []]) err(` ${path}`);
869
+ return 1;
870
+ }
871
+ for (const d of r.diagnostics ?? []) err(`${d.file}:${d.line}:${d.column} ${d.code}: ${d.message}`);
872
+ out(r.ok ? `✓ ${r.checked ?? 0} script${r.checked === 1 ? "" : "s"} type-check clean` : `✖ ${(r.diagnostics ?? []).length} problem(s) in ${r.checked ?? 0} script(s)`);
873
+ return r.ok ? 0 : 1;
874
+ }
875
+ async function cmdTypes(args) {
876
+ const sub = args.positionals[0];
877
+ const projectPath = str(args.flags.project);
878
+ if (sub === "list" || sub === void 0) {
879
+ const r = await listTypes({ projectPath });
880
+ if (!r.ok) {
881
+ err(r.error ?? "failed");
882
+ return 1;
883
+ }
884
+ for (const t of r.types ?? []) out(`${t.id.padEnd(28)} ${(t.extends !== void 0 ? `extends ${t.extends}` : "").padEnd(30)} ${t.doc ?? ""}`);
885
+ return 0;
886
+ }
887
+ if (sub === "check") {
888
+ const r = await checkTypesOp({ projectPath });
889
+ if (r.error !== void 0) {
890
+ err(r.error);
891
+ return 1;
892
+ }
893
+ if ((r.issues ?? []).length > 0) err(formatIssues("project types", r.issues ?? []));
894
+ if (r.codegenStale === true) err("codegen is stale — run: molen types gen");
895
+ out(r.ok ? "✓ types check passed" : "✖ types check failed");
896
+ return r.ok ? 0 : 1;
897
+ }
898
+ if (sub === "reserve") {
899
+ const namespace = args.positionals[1];
900
+ const owner = str(args.flags.owner);
901
+ if (namespace === void 0 || owner === void 0) {
902
+ err("usage: molen types reserve <namespace> --owner <owner> [--note <s>]");
903
+ return 2;
904
+ }
905
+ const r = await reserveNamespace({
906
+ namespace,
907
+ owner,
908
+ note: str(args.flags.note),
909
+ projectPath
910
+ });
911
+ if (!r.ok) {
912
+ err(r.error ?? "reserve failed");
913
+ return 1;
914
+ }
915
+ out(r.alreadyReserved === true ? `✓ "${namespace}" already reserved by ${owner}` : `✓ reserved "${namespace}" for ${owner}`);
916
+ return 0;
917
+ }
918
+ if (sub === "gen") {
919
+ const r = await generateTypes({
920
+ projectPath,
921
+ out: str(args.flags.out),
922
+ check: args.flags.check === true
923
+ });
924
+ if (r.error !== void 0 && r.stale !== true) {
925
+ err(r.error);
926
+ return 1;
927
+ }
928
+ if (args.flags.check === true) {
929
+ out(r.stale === true ? `✖ ${r.outPath} is stale — run: molen types gen` : "✓ codegen up to date");
930
+ return r.ok ? 0 : 1;
931
+ }
932
+ out(`wrote ${r.outPath} (${r.componentCount} components, ${r.typeCount} types)`);
933
+ return 0;
934
+ }
935
+ if (sub === "test") {
936
+ const ticksRaw = str(args.flags.ticks);
937
+ const r = await testTypes({
938
+ projectPath,
939
+ ...ticksRaw !== void 0 ? { ticks: Number(ticksRaw) } : {},
940
+ ...args.positionals[1] !== void 0 ? { only: args.positionals.slice(1) } : {}
941
+ });
942
+ if (r.error !== void 0) {
943
+ err(r.error);
944
+ return 1;
945
+ }
946
+ for (const t of r.results ?? []) {
947
+ out(`${t.ok ? "✓" : "✖"} ${t.id}${t.error !== void 0 ? ` — ${t.error}` : ""}`);
948
+ for (const issue of t.issues ?? []) out(` ${issue.path}: ${issue.message}`);
949
+ }
950
+ return r.ok ? 0 : 1;
951
+ }
952
+ err("usage: molen types list | check | reserve <ns> --owner <o> | gen [--check] | test [ids…]");
953
+ return 2;
954
+ }
955
+ function parseSize(v) {
956
+ if (typeof v !== "string") return void 0;
957
+ const parts = v.toLowerCase().split("x").map(Number);
958
+ if (parts.length !== 2 || parts.some((n) => !Number.isFinite(n) || n <= 0)) return void 0;
959
+ return [parts[0], parts[1]];
960
+ }
961
+ async function cmdFigure(args) {
962
+ const sub = args.positionals[0];
963
+ if (sub === "presets") {
964
+ const archetype = str(args.flags.archetype);
965
+ if (archetype !== void 0 && archetype !== "biped" && archetype !== "quadruped") {
966
+ err("--archetype must be biped or quadruped");
967
+ return 2;
968
+ }
969
+ const r = listFigurePresets(archetype !== void 0 ? { archetype } : {});
970
+ if (args.flags.json === true) {
971
+ out(JSON.stringify(r.presets, null, 2));
972
+ return 0;
973
+ }
974
+ for (const preset of r.presets) out(`${preset.id.padEnd(14)} ${preset.archetype.padEnd(10)} ${preset.species.padEnd(6)} ${preset.height} m`);
975
+ return 0;
976
+ }
977
+ if (sub === "preview") {
978
+ const usage = "usage: molen figure preview [descriptor.figure.json] [--preset id[,id]] [--lineup humans|bodies|species|all] [--mode idle|walk|run|sit|jump|fall] [--tick N] [--tier 0|1|2] [--angles N|review] [--size WxH] --out <png>";
979
+ const outPath = str(args.flags.out);
980
+ if (outPath === void 0) {
981
+ err(usage);
982
+ return 2;
983
+ }
984
+ const lineup = str(args.flags.lineup);
985
+ if (lineup !== void 0 && ![
986
+ "humans",
987
+ "bodies",
988
+ "species",
989
+ "all"
990
+ ].includes(lineup)) {
991
+ err("--lineup must be humans, bodies, species or all");
992
+ return 2;
993
+ }
994
+ const mode = str(args.flags.mode);
995
+ if (mode !== void 0 && ![
996
+ "idle",
997
+ "walk",
998
+ "run",
999
+ "sit",
1000
+ "jump",
1001
+ "fall"
1002
+ ].includes(mode)) {
1003
+ err("--mode must be idle, walk, run, sit, jump or fall");
1004
+ return 2;
1005
+ }
1006
+ const anglesFlag = str(args.flags.angles);
1007
+ const angles = anglesFlag === void 0 ? void 0 : anglesFlag === "review" ? "review" : Number(anglesFlag);
1008
+ const tick = args.flags.tick !== void 0 ? Number(args.flags.tick) : void 0;
1009
+ const tierRaw = args.flags.tier !== void 0 ? Number(args.flags.tier) : void 0;
1010
+ const size = parseSize(args.flags.size);
1011
+ const presetFlag = str(args.flags.preset);
1012
+ const r = await previewFigure({
1013
+ ...presetFlag !== void 0 ? { preset: presetFlag.split(",").map((s) => s.trim()).filter((s) => s.length > 0) } : {},
1014
+ descriptorPath: args.positionals[1],
1015
+ ...lineup !== void 0 ? { lineup } : {},
1016
+ ...mode !== void 0 ? { mode } : {},
1017
+ ...tick !== void 0 && Number.isFinite(tick) ? { tick } : {},
1018
+ ...tierRaw === 0 || tierRaw === 1 || tierRaw === 2 ? { tier: tierRaw } : {},
1019
+ ...angles !== void 0 && (angles === "review" || Number.isFinite(angles)) ? { angles } : {},
1020
+ ...size !== void 0 ? { size } : {},
1021
+ outPath
1022
+ });
1023
+ if (!r.ok) {
1024
+ err(r.error ?? "figure preview failed");
1025
+ return 1;
1026
+ }
1027
+ out(`rendered ${r.stats?.figures ?? 0} figures - ${r.stats?.triangles ?? 0} triangles, ${r.stats?.joints ?? 0} joints - ${r.hash ?? ""}`);
1028
+ for (const frame of r.frames ?? []) out(` ${frame.path} (${frame.name}, yaw ${frame.yawDeg})`);
1029
+ return 0;
1030
+ }
1031
+ err("usage: molen figure preview ... --out <png> | molen figure presets [--archetype biped|quadruped] [--json]");
1032
+ return 2;
1033
+ }
1034
+ async function cmdWorldgen(args) {
1035
+ const sub = args.positionals[0];
1036
+ const ground = str(args.flags.ground);
1037
+ if (ground !== void 0 && ground !== "flat" && ground !== "slope") {
1038
+ err("--ground must be flat or slope");
1039
+ return 2;
1040
+ }
1041
+ if (sub === "preview") {
1042
+ const outPath = str(args.flags.out);
1043
+ if (outPath === void 0) {
1044
+ err("usage: molen worldgen preview [style.archstyle.json] [--pack p] [--style id] [--batch f] [--scatter id] [--ground flat|slope] [--angles N] [--size WxH] --out <png>");
1045
+ return 2;
1046
+ }
1047
+ const angles = args.flags.angles !== void 0 ? Number(args.flags.angles) : void 0;
1048
+ const size = parseSize(args.flags.size);
1049
+ const r = await previewWorldgen({
1050
+ stylePath: args.positionals[1],
1051
+ packPath: str(args.flags.pack),
1052
+ styleId: str(args.flags.style),
1053
+ batchPath: str(args.flags.batch),
1054
+ scatterId: str(args.flags.scatter),
1055
+ ...ground !== void 0 ? { ground } : {},
1056
+ ...angles !== void 0 && Number.isFinite(angles) ? { angles } : {},
1057
+ ...size !== void 0 ? { size } : {},
1058
+ outPath
1059
+ });
1060
+ if (!r.ok) {
1061
+ err(r.error ?? "worldgen preview failed");
1062
+ return 1;
1063
+ }
1064
+ const s = r.stats;
1065
+ out(`generated ${s?.buildingsRendered ?? 0} buildings (${s?.buildingsBoxed ?? 0} boxed, ${s?.buildingsSkipped ?? 0} skipped) · ${s?.triangles ?? 0} triangles · ${r.hash ?? ""}`);
1066
+ if (r.renderStats !== void 0) out(`rendered ${r.renderStats.drawCalls} draws · ${r.renderStats.triangles} triangles · ${r.renderStats.instances} instances`);
1067
+ for (const failure of r.materialFailures ?? []) out(` ! material ${failure} rendered flat`);
1068
+ for (const frame of r.frames ?? []) out(` ${frame.path} (yaw ${frame.yawDeg}°)`);
1069
+ return 0;
1070
+ }
1071
+ if (sub === "bake") {
1072
+ const outDir = str(args.flags.out) ?? str(args.flags["out-dir"]);
1073
+ const batchPath = args.positionals[1];
1074
+ const outline = str(args.flags.outline);
1075
+ if (outDir === void 0 || batchPath === void 0 && outline === void 0) {
1076
+ err("usage: molen worldgen bake [batch.json] [--outline \"x,z;x,z;...\"] [--style id] [--pack p] --out <assets-dir> [--id id] [--ground flat|slope] [--force]");
1077
+ return 2;
1078
+ }
1079
+ const r = await bakeWorldgen({
1080
+ batchPath,
1081
+ outline,
1082
+ styleId: str(args.flags.style),
1083
+ packPath: str(args.flags.pack),
1084
+ outDir,
1085
+ id: str(args.flags.id),
1086
+ ...ground !== void 0 ? { ground } : {},
1087
+ force: args.flags.force === true,
1088
+ projectPath: str(args.flags.project)
1089
+ });
1090
+ if (!r.ok) {
1091
+ err(r.error ?? "worldgen bake failed");
1092
+ return 1;
1093
+ }
1094
+ out(`baked "${r.id}" -> ${r.dir}`);
1095
+ out(` ${r.sidecar?.stats.triangles ?? 0} tris, ${r.sidecar?.stats.primitives ?? 0} material groups, ${r.glbBytes ?? 0} bytes · ${r.stats?.buildingsRendered ?? 0} buildings`);
1096
+ for (const set of r.placements ?? []) out(` not baked: ${set.count} x ${set.modelRef} (instanced placements)`);
1097
+ for (const w of r.warnings ?? []) out(` ! ${w}`);
1098
+ return 0;
1099
+ }
1100
+ if (sub === "stats") {
1101
+ const packagePath = args.positionals[1];
1102
+ if (packagePath === void 0) {
1103
+ err("usage: molen worldgen stats <terrain-package.json> [--tile z/x/y | --auto] [--pack p] [--atlas a] [--style id] [--quality q] [--dump batch.json] [--json]");
1104
+ return 2;
1105
+ }
1106
+ const quality = str(args.flags.quality);
1107
+ if (quality !== void 0 && ![
1108
+ "economy",
1109
+ "balanced",
1110
+ "high"
1111
+ ].includes(quality)) {
1112
+ err("--quality must be economy, balanced, or high");
1113
+ return 2;
1114
+ }
1115
+ const r = await worldgenStats({
1116
+ packagePath,
1117
+ tile: str(args.flags.tile),
1118
+ auto: args.flags.auto === true,
1119
+ packPath: str(args.flags.pack),
1120
+ atlasPath: str(args.flags.atlas),
1121
+ styleId: str(args.flags.style),
1122
+ ...quality !== void 0 ? { quality } : {},
1123
+ dumpPath: str(args.flags.dump)
1124
+ });
1125
+ if (!r.ok) {
1126
+ err(r.error ?? "worldgen stats failed");
1127
+ return 1;
1128
+ }
1129
+ out(args.flags.json === true ? JSON.stringify(r, null, 2) : formatWorldgenStats(r));
1130
+ return 0;
1131
+ }
1132
+ err("usage: molen worldgen preview | bake | stats");
1133
+ return 2;
1134
+ }
1135
+ async function cmdMcp() {
1136
+ const { startMcpServer } = await import("./mcp-BFnCWrg0.mjs");
1137
+ await startMcpServer();
1138
+ return 0;
1139
+ }
1140
+ /** The published package version, for `molen --version` (dist/ and src/ both walk up to it). */
1141
+ function cliVersion() {
1142
+ let dir = dirname(fileURLToPath(import.meta.url));
1143
+ for (;;) {
1144
+ try {
1145
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1146
+ if (pkg.name === "@bendyline/molen-tooling" && pkg.version !== void 0) return pkg.version;
1147
+ } catch {}
1148
+ const parent = dirname(dir);
1149
+ if (parent === dir) return "0.0.0";
1150
+ dir = parent;
1151
+ }
1152
+ }
1153
+ /** The mandatory part of a usage form: everything before the first optional `[...]` group. */
1154
+ function requiredForm(cli) {
1155
+ const withoutMolen = cli.replace(/^molen\s+/, "");
1156
+ const optional = withoutMolen.indexOf(" [");
1157
+ return (optional === -1 ? withoutMolen : withoutMolen.slice(0, optional)).trim();
1158
+ }
1159
+ function firstSentence(summary, width) {
1160
+ const sentence = /^(.*?[.!?])(\s|$)/.exec(summary)?.[1] ?? summary;
1161
+ return sentence.length <= width ? sentence : `${sentence.slice(0, width - 1).trimEnd()}…`;
1162
+ }
1163
+ const HELP_COLUMN = 44;
1164
+ const HELP_WIDTH = 98;
1165
+ /**
1166
+ * Generated from OPS_CATALOG, so a command cannot exist without appearing here — the hand-written
1167
+ * version silently omitted the whole `figure` and `scripts` groups.
1168
+ */
1169
+ function printHelp() {
1170
+ out("molen <command> [options] — headless tooling for Molen experiences");
1171
+ out("");
1172
+ for (const op of OPS_CATALOG) {
1173
+ if (op.cli === void 0) continue;
1174
+ const form = requiredForm(op.cli);
1175
+ if (form.length > HELP_COLUMN - 2) {
1176
+ out(` ${form}`);
1177
+ out(`${" ".repeat(46)}${firstSentence(op.summary, HELP_WIDTH - HELP_COLUMN - 2)}`);
1178
+ } else out(` ${form.padEnd(HELP_COLUMN)}${firstSentence(op.summary, HELP_WIDTH - HELP_COLUMN - 2)}`);
1179
+ }
1180
+ out("");
1181
+ out(" help <command> full usage + parameters for one command");
1182
+ out(" describe [op] machine-readable contracts (CLI + MCP)");
1183
+ out(" --version, -v print the molen version");
1184
+ }
1185
+ /** `molen help <command>` / `molen <command> --help`: every op of that verb, in full. */
1186
+ function printCommandHelp(verb) {
1187
+ const ops = OPS_CATALOG.filter((op) => cliVerb(op) === verb);
1188
+ if (ops.length === 0) {
1189
+ err(`unknown command "${verb}"${didYouMean(verb, Object.keys(CLI_COMMANDS))} (try: molen help)`);
1190
+ return 2;
1191
+ }
1192
+ out(ops.map(formatOp).join("\n\n"));
1193
+ return 0;
1194
+ }
1195
+ /**
1196
+ * The CLI entry point: version/help handling, command lookup with did-you-mean, then a parse
1197
+ * against the command's declared flags (an unknown or malformed flag is an error, not a shrug).
1198
+ */
1199
+ async function runCli(argv) {
1200
+ const [command, ...rest] = argv;
1201
+ if (command === void 0) {
1202
+ printHelp();
1203
+ return 2;
1204
+ }
1205
+ if (command === "--version" || command === "-v") {
1206
+ out(cliVersion());
1207
+ return 0;
1208
+ }
1209
+ if (command === "--help" || command === "-h" || command === "help") {
1210
+ const topic = rest.find((token) => !token.startsWith("-"));
1211
+ if (topic === void 0) {
1212
+ printHelp();
1213
+ return 0;
1214
+ }
1215
+ return printCommandHelp(topic);
1216
+ }
1217
+ const handler = CLI_COMMANDS[command];
1218
+ if (handler === void 0) {
1219
+ err(`unknown command "${command}"${didYouMean(command, Object.keys(CLI_COMMANDS))} (try: molen help)`);
1220
+ return 2;
1221
+ }
1222
+ if (rest.includes("--help") || rest.includes("-h")) return printCommandHelp(command);
1223
+ const spec = cliFlagSpecs().get(command);
1224
+ const args = parseArgs(rest, spec);
1225
+ for (const message of args.flagErrors ?? []) err(`molen ${command}: ${message}`);
1226
+ for (const flag of args.unknownFlags ?? []) {
1227
+ const known = spec === void 0 ? [] : [...spec.value, ...spec.boolean].sort();
1228
+ err(`molen ${command}: unknown flag ${flag}${didYouMean(flag.replace(/^--?/, ""), known, "--")}`);
1229
+ }
1230
+ if ((args.unknownFlags ?? []).length > 0 || (args.flagErrors ?? []).length > 0) {
1231
+ err(`try: molen help ${command}`);
1232
+ return 2;
1233
+ }
1234
+ return handler(args);
1235
+ }
1236
+ /**
1237
+ * Every CLI verb, keyed by its first token. The `describe` catalog (ops/describe.ts), the MCP
1238
+ * server, and this table are cross-checked by test/catalog.test.ts — a new op must land on all
1239
+ * three surfaces or that test fails.
1240
+ */
1241
+ const CLI_COMMANDS = {
1242
+ validate: cmdValidate,
1243
+ sim: cmdSim,
1244
+ shot: cmdShot,
1245
+ frames: cmdFrames,
1246
+ material: cmdMaterial,
1247
+ uvpaint: cmdUvPaint,
1248
+ replay: cmdReplay,
1249
+ diff: cmdDiff,
1250
+ docs: cmdDocs,
1251
+ schema: cmdSchema,
1252
+ components: cmdComponents,
1253
+ component: cmdComponent,
1254
+ describe: cmdDescribe,
1255
+ asset: cmdAsset,
1256
+ pack: cmdPack,
1257
+ drive: cmdDrive,
1258
+ play: cmdPlay,
1259
+ project: cmdProject,
1260
+ types: cmdTypes,
1261
+ scripts: cmdScripts,
1262
+ new: cmdNew,
1263
+ figure: cmdFigure,
1264
+ worldgen: cmdWorldgen,
1265
+ mcp: cmdMcp
1266
+ };
1267
+ //#endregion
1268
+ //#region src/cli.ts
1269
+ runCli(process.argv.slice(2)).then((code) => {
1270
+ process.exitCode = code;
1271
+ }).catch((e) => {
1272
+ process.stderr.write(`molen: ${e.message}\n`);
1273
+ process.exitCode = 1;
1274
+ });
1275
+ //#endregion
1276
+ export {};