@chanmeng666/archlang-3d 0.0.0-stage → 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.
package/dist/cli.js ADDED
@@ -0,0 +1,686 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DOOR_POSES,
4
+ adaptPlan,
5
+ buildMesh
6
+ } from "./chunk-NADV4D3M.js";
7
+ import {
8
+ SWIFTSHADER_ARGS,
9
+ checkGlb,
10
+ checkScene,
11
+ checkShells,
12
+ makeNodeWorld,
13
+ renderReplay,
14
+ replayHtml,
15
+ writeGlb
16
+ } from "./chunk-2WKSS3IA.js";
17
+ import {
18
+ ARCHLANG_3D_VERSION,
19
+ replayFacts
20
+ } from "./chunk-IQJQDQSC.js";
21
+ import "./chunk-54YVSAVZ.js";
22
+ import {
23
+ storeysOf,
24
+ timeline,
25
+ viewLabel,
26
+ viewMesh
27
+ } from "./chunk-CTFMM64C.js";
28
+
29
+ // src/cli/run.ts
30
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
31
+ import { dirname as dirname2, resolve as resolve2 } from "node:path";
32
+ import { compile } from "@chanmeng666/archlang";
33
+
34
+ // src/cli/commands.ts
35
+ import { createHash } from "node:crypto";
36
+ import { spawnSync } from "node:child_process";
37
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
38
+ import { dirname, join, resolve } from "node:path";
39
+ import { fileURLToPath } from "node:url";
40
+ import * as core from "@chanmeng666/archlang";
41
+
42
+ // src/cli/manifest.ts
43
+ var JSON_FLAG = { flag: "--json", description: "structured result on stdout, messages on stderr" };
44
+ var CURVE_TOL = {
45
+ flag: "--curve-tol",
46
+ arg: "<mm>",
47
+ description: "largest sagitta of an arc's chords, in mm (default 2)"
48
+ };
49
+ var DOORS = {
50
+ flag: "--doors",
51
+ arg: "<closed|plan>",
52
+ description: "closed (default): every leaf across its doorway; plan: each hinged or double leaf swung as the plan draws it (other kinds stay closed)"
53
+ };
54
+ var COMMANDS = [
55
+ {
56
+ name: "build",
57
+ summary: "a plan to a GLB (or its Scene3D), checked before it is written",
58
+ flags: [
59
+ {
60
+ flag: "--out",
61
+ alias: "-o",
62
+ arg: "<file|->",
63
+ description: "output file, or '-' for stdout (default: the input path with .glb, or .scene3d.json)"
64
+ },
65
+ { flag: "--format", alias: "-f", arg: "<glb|scene3d>", description: "output format (default glb)" },
66
+ CURVE_TOL,
67
+ DOORS,
68
+ { flag: "--strict", description: "refuse a build with any W3D_* warning: E3D_STRICT, exit 2, nothing written" },
69
+ JSON_FLAG
70
+ ],
71
+ input: "<plan.arch|->",
72
+ output: "a .glb (or .scene3d.json) file, or stdout with -o -",
73
+ examples: [
74
+ { cmd: "archlang3d build plan.arch -o plan.glb --json", note: "build, check and report the GLB" },
75
+ { cmd: "archlang3d build - -o - < plan.arch > plan.glb", note: "stdin to stdout" },
76
+ { cmd: "archlang3d build plan.arch -f scene3d -o plan.scene3d.json", note: "the plan-aligned Scene3D" }
77
+ ]
78
+ },
79
+ {
80
+ name: "check",
81
+ summary: "run the checks (V-SCH, V-GEO, V-GLTF) without writing a model",
82
+ flags: [CURVE_TOL, DOORS, JSON_FLAG],
83
+ input: "<plan.arch|model.glb|->",
84
+ output: "a report (stdout with --json); exit 2 when a check fails",
85
+ examples: [
86
+ { cmd: "archlang3d check plan.arch --json", note: "build in memory and check the plan's model" },
87
+ { cmd: "archlang3d check plan.glb --json", note: "glTF-Validator and the naming rules on a GLB" }
88
+ ]
89
+ },
90
+ {
91
+ name: "view",
92
+ summary: "a replay of the plan as one offline HTML file, optionally an MP4 (Chromium, ffmpeg)",
93
+ flags: [
94
+ { flag: "--replay", description: "the replay view (required; the only view so far)" },
95
+ { flag: "--out", alias: "-o", arg: "<out.html>", description: "the HTML file to write (required)" },
96
+ { flag: "--video", arg: "<out.mp4>", description: "also render an MP4 (needs Chromium and ffmpeg)" },
97
+ { flag: "--seconds", arg: "<n>", description: "replay length (default 15)" },
98
+ { flag: "--fps", arg: "<n>", description: "video frame rate (default 30)" },
99
+ { flag: "--size", arg: "<W>x<H>", description: "canvas size (default 1920x1080)" },
100
+ { flag: "--theme", arg: "<light|dark>", description: "light (default); dark for exports only" },
101
+ { flag: "--storey", arg: "<n|all>", description: "one storey (1 = the lowest) or all combined (default)" },
102
+ CURVE_TOL,
103
+ DOORS,
104
+ JSON_FLAG
105
+ ],
106
+ input: "<plan.arch|->",
107
+ output: "an HTML file (and an MP4 with --video)",
108
+ examples: [
109
+ { cmd: "archlang3d view plan.arch --replay -o plan.html --json", note: "the replay and its key-frame hashes" },
110
+ {
111
+ cmd: "archlang3d view plan.arch --replay -o plan.html --doors plan",
112
+ note: "doors swung as the plan draws them"
113
+ }
114
+ ]
115
+ },
116
+ {
117
+ name: "manifest",
118
+ summary: "this CLI as data",
119
+ flags: [JSON_FLAG],
120
+ input: "none",
121
+ output: "JSON on stdout",
122
+ examples: [{ cmd: "archlang3d manifest --json", note: "every command, flag and exit code" }]
123
+ },
124
+ {
125
+ name: "schema",
126
+ summary: "the JSON Schema of a document the package writes (scene3d)",
127
+ flags: [JSON_FLAG],
128
+ input: "[scene3d]",
129
+ output: "JSON on stdout",
130
+ examples: [{ cmd: "archlang3d schema scene3d", note: "Scene3D v0's JSON Schema" }]
131
+ },
132
+ {
133
+ name: "doctor",
134
+ summary: "check the environment: Node, the core, glTF-Validator, Chromium, ffmpeg",
135
+ flags: [JSON_FLAG],
136
+ input: "none",
137
+ output: "a report; exit 1 when something build or check needs is missing",
138
+ examples: [{ cmd: "archlang3d doctor --json", note: "what is installed and what each part is for" }]
139
+ }
140
+ ];
141
+ var CHECKS = ["V-SCH-01", "V-GEO-02", "V-GLTF-01", "V-GLTF-02"];
142
+ var DIAGNOSTIC_CODES = [
143
+ "E3D_CORE_TOO_OLD",
144
+ "E3D_PLAN_ERRORS",
145
+ "E3D_NO_WALLS",
146
+ "E3D_VERIFY_FAILED",
147
+ "E3D_STRICT",
148
+ "W3D_MIXED_HEIGHT_JOINT",
149
+ "W3D_FLOOR_OVERLAP"
150
+ ];
151
+ function buildManifest() {
152
+ return {
153
+ name: "archlang3d",
154
+ invoke: "archlang3d",
155
+ version: ARCHLANG_3D_VERSION,
156
+ description: "archlang-3d: 3D preview of an ArchLang plan, a separate package that reads the same .arch source. Builds a checked GLB and a replay from a .arch plan. ArchLang itself draws plans.",
157
+ exitCodes: {
158
+ "0": "ok",
159
+ "1": "internal / IO / environment error (a missing Chromium or ffmpeg, a file that cannot be written)",
160
+ "2": "the plan is refused, a check failed, or build --strict met a warning (E3D_STRICT); nothing is written (deterministic: fix it, don't blindly retry)",
161
+ "3": "bad usage"
162
+ },
163
+ globalFlags: [JSON_FLAG],
164
+ commands: COMMANDS,
165
+ d3: {
166
+ scene3dSchemaVersion: 0,
167
+ formats: ["glb", "scene3d"],
168
+ checks: CHECKS,
169
+ diagnosticCodes: DIAGNOSTIC_CODES
170
+ }
171
+ };
172
+ }
173
+
174
+ // src/cli/commands.ts
175
+ var HERE = dirname(fileURLToPath(import.meta.url));
176
+ var Usage = class extends Error {
177
+ };
178
+ function parseFlags(cmd, argv) {
179
+ const spec = COMMANDS.find((c) => c.name === cmd);
180
+ if (!spec) throw new Usage(`unknown command "${cmd}"`);
181
+ const flags = /* @__PURE__ */ new Map();
182
+ const positional = [];
183
+ for (let i = 0; i < argv.length; i++) {
184
+ const a = argv[i];
185
+ if (a.startsWith("-") && a !== "-") {
186
+ const f = spec.flags.find((x) => x.flag === a || x.alias === a);
187
+ if (!f) throw new Usage(`${cmd}: unknown flag "${a}"`);
188
+ if (f.arg) {
189
+ const v = argv[++i];
190
+ if (v === void 0) throw new Usage(`${cmd}: ${f.flag} takes ${f.arg}`);
191
+ flags.set(f.flag, v);
192
+ } else flags.set(f.flag, true);
193
+ } else positional.push(a);
194
+ }
195
+ return { positional, flags };
196
+ }
197
+ var say = (s) => {
198
+ process.stderr.write(`${s}
199
+ `);
200
+ };
201
+ var emit = (v) => {
202
+ process.stdout.write(`${JSON.stringify(v, null, 2)}
203
+ `);
204
+ };
205
+ var sha256 = (b) => createHash("sha256").update(b).digest("hex");
206
+ function packageDir(name, from = HERE) {
207
+ for (let d = from; ; ) {
208
+ const p = join(d, "node_modules", name);
209
+ if (existsSync(join(p, "package.json"))) return p;
210
+ const up = dirname(d);
211
+ if (up === d) return void 0;
212
+ d = up;
213
+ }
214
+ }
215
+ function coreVersion() {
216
+ const d = packageDir("@chanmeng666/archlang");
217
+ if (!d) return "unknown";
218
+ return JSON.parse(readFileSync(join(d, "package.json"), "utf8")).version;
219
+ }
220
+ function curveTol(p) {
221
+ const v = p.flags.get("--curve-tol");
222
+ if (v === void 0) return void 0;
223
+ const n = Number(v);
224
+ if (!Number.isFinite(n) || n <= 0) throw new Usage("--curve-tol takes a positive number of mm");
225
+ return n;
226
+ }
227
+ function doorPose(v) {
228
+ if (v === void 0) return "closed";
229
+ if (typeof v === "string" && DOOR_POSES.includes(v)) return v;
230
+ throw new Usage(`--doors takes ${DOOR_POSES.join(" or ")}`);
231
+ }
232
+ function onePlan(cmd, p) {
233
+ if (p.positional.length === 0) throw new Usage(`${cmd}: no input given`);
234
+ if (p.positional.length > 1) throw new Usage(`${cmd}: unexpected argument "${p.positional[1]}"`);
235
+ return p.positional[0];
236
+ }
237
+ var readInput = (input) => readFileSync(input === "-" ? 0 : input);
238
+ function buildFrom(input, source, tol, doors) {
239
+ const world = makeNodeWorld(input === "-" ? process.cwd() : dirname(resolve(input)));
240
+ const r = adaptPlan(source, {
241
+ world,
242
+ coreVersion: coreVersion(),
243
+ ...tol !== void 0 ? { curveTolMm: tol } : {}
244
+ });
245
+ if (!r.ok) return { ok: false, code: 2, refusal: r.refusal, message: `${r.refusal.code}: ${r.refusal.message}` };
246
+ return {
247
+ ok: true,
248
+ scene: r.scene,
249
+ mesh: buildMesh(r.scene, { doors }),
250
+ warnings: r.warnings.map((w) => ({ code: w.code, level: w.level, message: w.message }))
251
+ };
252
+ }
253
+ var summary = (checks) => ({
254
+ passed: checks.filter((c) => c.ok).length,
255
+ failed: checks.filter((c) => !c.ok).length,
256
+ checks: checks.map((c) => c.id),
257
+ results: checks
258
+ });
259
+ function sceneFacts(scene, mesh) {
260
+ const levels = scene.levels.map((lv) => {
261
+ const ids = (kind) => new Set(mesh.nodes.filter((n) => n.level === lv.level && n.kind === kind).map((n) => n.id)).size;
262
+ return {
263
+ level: lv.level,
264
+ elevation_mm: lv.elevation / 1e3,
265
+ storey_height_mm: lv.storeyHeight / 1e3,
266
+ counts: {
267
+ wall: ids("wall"),
268
+ floor: ids("floor"),
269
+ door: ids("door"),
270
+ window: ids("window"),
271
+ furniture: ids("furniture"),
272
+ column: ids("column"),
273
+ stair: 0
274
+ }
275
+ };
276
+ });
277
+ const min = [Infinity, Infinity, Infinity];
278
+ const max = [-Infinity, -Infinity, -Infinity];
279
+ for (const n of mesh.nodes) {
280
+ for (const s of n.shells) {
281
+ for (let i = 0; i < s.positions.length; i++) {
282
+ const k = i % 3;
283
+ const v = s.positions[i] / 1e3;
284
+ if (v < min[k]) min[k] = v;
285
+ if (v > max[k]) max[k] = v;
286
+ }
287
+ }
288
+ }
289
+ return { levels, bbox_mm: { min, max } };
290
+ }
291
+ async function cmdBuild(p) {
292
+ const input = onePlan("build", p);
293
+ const format = p.flags.get("--format") ?? "glb";
294
+ if (format !== "glb" && format !== "scene3d") throw new Usage("--format takes glb or scene3d");
295
+ const json = p.flags.has("--json");
296
+ const strict = p.flags.has("--strict");
297
+ const tol = curveTol(p);
298
+ const doors = doorPose(p.flags.get("--doors"));
299
+ let out = p.flags.get("--out");
300
+ if (out === void 0) {
301
+ if (input === "-") throw new Usage("build: reading stdin needs -o <file|->");
302
+ out = input.replace(/\.arch$/i, "") + (format === "glb" ? ".glb" : ".scene3d.json");
303
+ }
304
+ if (out === "-" && json) throw new Usage("build: -o - and --json both write stdout; pick one");
305
+ if (format === "scene3d" && doors !== "closed")
306
+ throw new Usage("build: --doors plan poses the model; a Scene3D carries no pose (use -f glb)");
307
+ let source;
308
+ try {
309
+ source = readInput(input).toString("utf8");
310
+ } catch (e) {
311
+ say(`archlang3d: cannot read ${input}: ${e.message}`);
312
+ return 1;
313
+ }
314
+ const b = buildFrom(input, source, tol, doors);
315
+ if (!b.ok) {
316
+ if (json) emit({ ok: false, refusal: b.refusal });
317
+ say(`archlang3d: ${b.message}`);
318
+ return 2;
319
+ }
320
+ const checks = [checkScene(b.scene)];
321
+ let bytes;
322
+ if (format === "glb") {
323
+ checks.push(checkShells(b.mesh));
324
+ bytes = await writeGlb(b.mesh);
325
+ checks.push(...await checkGlb(bytes, b.mesh));
326
+ } else {
327
+ bytes = new TextEncoder().encode(`${JSON.stringify(b.scene, null, 2)}
328
+ `);
329
+ }
330
+ const failed = checks.filter((c) => !c.ok);
331
+ const tool = { name: "archlang3d", version: ARCHLANG_3D_VERSION, archlang: coreVersion() };
332
+ const diagnostics = b.warnings.map((w) => ({
333
+ code: w.code,
334
+ severity: "warning",
335
+ level: w.level,
336
+ message: w.message
337
+ }));
338
+ if (failed.length > 0) {
339
+ if (json) emit({ ok: false, code: "E3D_VERIFY_FAILED", tool, diagnostics, verify: summary(checks) });
340
+ for (const c of failed) say(`archlang3d: E3D_VERIFY_FAILED ${c.id}: ${c.failures.join("; ")}`);
341
+ return 2;
342
+ }
343
+ if (strict && diagnostics.length > 0) {
344
+ if (json) emit({ ok: false, code: "E3D_STRICT", tool, diagnostics, verify: summary(checks) });
345
+ for (const d of diagnostics) say(`archlang3d: E3D_STRICT ${d.code}: ${d.message}`);
346
+ return 2;
347
+ }
348
+ try {
349
+ if (out === "-") process.stdout.write(bytes);
350
+ else writeFileSync(out, bytes);
351
+ } catch (e) {
352
+ say(`archlang3d: cannot write ${out}: ${e.message}`);
353
+ return 1;
354
+ }
355
+ const report = {
356
+ ok: true,
357
+ tool,
358
+ input: { path: input, levels: b.scene.levels.length },
359
+ doors,
360
+ outputs: [{ path: out, format, bytes: bytes.byteLength, sha256: sha256(bytes) }],
361
+ scene: sceneFacts(b.scene, b.mesh),
362
+ assumptions: b.mesh.assumptions,
363
+ diagnostics,
364
+ verify: { ...summary(checks), warnings: diagnostics.length }
365
+ };
366
+ if (json) emit(report);
367
+ else if (out !== "-") say(`archlang3d: wrote ${out} (${bytes.byteLength} bytes, ${checks.length} checks passed)`);
368
+ for (const d of diagnostics) say(`archlang3d: ${d.code}: ${d.message}`);
369
+ return 0;
370
+ }
371
+ async function cmdCheck(p) {
372
+ const input = onePlan("check", p);
373
+ const json = p.flags.has("--json");
374
+ const doorsFlag = p.flags.get("--doors");
375
+ const doors = doorPose(doorsFlag);
376
+ let raw;
377
+ try {
378
+ raw = readInput(input);
379
+ } catch (e) {
380
+ say(`archlang3d: cannot read ${input}: ${e.message}`);
381
+ return 1;
382
+ }
383
+ let checks;
384
+ let diagnostics = [];
385
+ const isGlb = raw.byteLength >= 4 && raw.readUInt32LE(0) === 1179937895;
386
+ if (isGlb && doorsFlag !== void 0)
387
+ throw new Usage("check: --doors applies to a plan; a GLB's doors were posed when it was built");
388
+ if (isGlb) {
389
+ try {
390
+ checks = await checkGlb(new Uint8Array(raw));
391
+ } catch (e) {
392
+ checks = [{ id: "V-GLTF-01", ok: false, failures: [e.message] }];
393
+ }
394
+ } else {
395
+ const b = buildFrom(input, raw.toString("utf8"), curveTol(p), doors);
396
+ if (!b.ok) {
397
+ if (json) emit({ ok: false, refusal: b.refusal });
398
+ say(`archlang3d: ${b.message}`);
399
+ return 2;
400
+ }
401
+ checks = [checkScene(b.scene), checkShells(b.mesh), ...await checkGlb(await writeGlb(b.mesh), b.mesh)];
402
+ diagnostics = b.warnings.map((w) => ({ code: w.code, severity: "warning", message: w.message }));
403
+ }
404
+ const ok = checks.every((c) => c.ok);
405
+ if (json) emit({ ok, input: { path: input }, ...isGlb ? {} : { doors }, diagnostics, verify: summary(checks) });
406
+ for (const c of checks) {
407
+ say(`archlang3d: ${c.ok ? "pass" : "FAIL"} ${c.id}${c.ok ? "" : ` E3D_VERIFY_FAILED: ${c.failures.join("; ")}`}`);
408
+ }
409
+ return ok ? 0 : 2;
410
+ }
411
+ function cmdManifest(p) {
412
+ if (p.positional.length > 0) throw new Usage(`manifest: unexpected argument "${p.positional[0]}"`);
413
+ emit(buildManifest());
414
+ return 0;
415
+ }
416
+ function cmdSchema(p) {
417
+ const name = p.positional[0] ?? "scene3d";
418
+ if (name !== "scene3d" || p.positional.length > 1) throw new Usage(`schema: the only schema is scene3d`);
419
+ const file = true ? "scene3d.schema.json" : "../scene3d/scene3d.schema.json";
420
+ process.stdout.write(readFileSync(join(HERE, file), "utf8"));
421
+ return 0;
422
+ }
423
+ async function cmdDoctor(p) {
424
+ if (p.positional.length > 0) throw new Usage(`doctor: unexpected argument "${p.positional[0]}"`);
425
+ const json = p.flags.has("--json");
426
+ const probes = [];
427
+ const major = Number(process.versions.node.split(".")[0]);
428
+ probes.push({
429
+ name: "node",
430
+ ok: major >= 20,
431
+ required: true,
432
+ for: "everything (engines: node >= 20)",
433
+ detail: process.versions.node
434
+ });
435
+ const hasSeam = typeof core.resolvePlan === "function";
436
+ probes.push({
437
+ name: "@chanmeng666/archlang",
438
+ ok: hasSeam,
439
+ required: true,
440
+ for: "reading the plan (resolvePlan, ADR 0031)",
441
+ detail: `${coreVersion()}${hasSeam ? "" : " (no resolvePlan export)"}`
442
+ });
443
+ try {
444
+ const v = await import("gltf-validator");
445
+ probes.push({ name: "gltf-validator", ok: true, required: true, for: "V-GLTF-01", detail: v.version() });
446
+ } catch (e) {
447
+ probes.push({ name: "gltf-validator", ok: false, required: true, for: "V-GLTF-01", detail: e.message });
448
+ }
449
+ if (major >= 20) {
450
+ try {
451
+ const { chromium } = await import("playwright-core");
452
+ const browser = await chromium.launch({ args: SWIFTSHADER_ARGS });
453
+ const version = browser.version();
454
+ await browser.close();
455
+ probes.push({
456
+ name: "chromium",
457
+ ok: true,
458
+ required: false,
459
+ for: "view (replay key frames, video)",
460
+ detail: version
461
+ });
462
+ } catch (e) {
463
+ const first = e.message.split("\n")[0] ?? "";
464
+ probes.push({
465
+ name: "chromium",
466
+ ok: false,
467
+ required: false,
468
+ for: "view (replay key frames, video)",
469
+ detail: `${first} (install: npx playwright-core install chromium)`
470
+ });
471
+ }
472
+ } else {
473
+ probes.push({ name: "chromium", ok: false, required: false, for: "view", detail: "needs Node >= 20" });
474
+ }
475
+ const ff = spawnSync("ffmpeg", ["-version"], { encoding: "utf8" });
476
+ probes.push({
477
+ name: "ffmpeg",
478
+ ok: ff.status === 0,
479
+ required: false,
480
+ for: "view --video",
481
+ detail: ff.status === 0 ? ff.stdout.split("\n")[0] ?? "" : "not found on PATH"
482
+ });
483
+ const ok = probes.every((x) => x.ok || !x.required);
484
+ if (json) emit({ ok, tool: { name: "archlang3d", version: ARCHLANG_3D_VERSION }, probes });
485
+ else for (const x of probes) say(`${x.ok ? "ok " : x.required ? "FAIL" : "miss"} ${x.name}: ${x.detail} (${x.for})`);
486
+ return ok ? 0 : 1;
487
+ }
488
+ var HANDLERS = {
489
+ build: cmdBuild,
490
+ check: cmdCheck,
491
+ manifest: cmdManifest,
492
+ schema: cmdSchema,
493
+ doctor: cmdDoctor
494
+ };
495
+
496
+ // src/cli/run.ts
497
+ var VIEW_USAGE = "usage: archlang3d view <plan.arch|-> --replay -o <out.html> [--video <out.mp4>] [--seconds <n>] [--fps <n>] [--size <W>x<H>] [--theme light|dark] [--storey <n>|all] [--curve-tol <mm>] [--doors closed|plan] [--json]";
498
+ var USAGE = `usage: archlang3d <build|check|view|manifest|schema|doctor> \u2026 (archlang3d manifest --json lists every flag)
499
+ ${VIEW_USAGE}`;
500
+ function parse(argv) {
501
+ const [cmd, ...rest] = argv;
502
+ if (cmd !== "view") throw new Usage(cmd ? `unknown command "${cmd}"` : "no command");
503
+ const a = {
504
+ seconds: 15,
505
+ fps: 30,
506
+ width: 1920,
507
+ height: 1080,
508
+ theme: "light",
509
+ storey: "all",
510
+ doors: "closed",
511
+ json: false
512
+ };
513
+ const num = (flag, v) => {
514
+ const n = Number(v);
515
+ if (!Number.isFinite(n) || n <= 0) throw new Usage(`${flag} takes a positive number`);
516
+ return n;
517
+ };
518
+ for (let i = 0; i < rest.length; i++) {
519
+ const f = rest[i];
520
+ const v = () => rest[++i];
521
+ if (f === "--replay") a.replay = true;
522
+ else if (f === "-o" || f === "--out") a.out = v();
523
+ else if (f === "--video") a.video = v();
524
+ else if (f === "--seconds") a.seconds = num(f, v());
525
+ else if (f === "--fps") a.fps = num(f, v());
526
+ else if (f === "--curve-tol") a.curveTol = num(f, v());
527
+ else if (f === "--json") a.json = true;
528
+ else if (f === "--doors") a.doors = doorPose(v() ?? true);
529
+ else if (f === "--storey") {
530
+ const t = v();
531
+ if (t === "all") a.storey = "all";
532
+ else if (t !== void 0 && /^[1-9]\d*$/.test(t)) a.storey = Number(t);
533
+ else throw new Usage("--storey takes a storey number (1 = the lowest) or all");
534
+ } else if (f === "--theme") {
535
+ const t = v();
536
+ if (t !== "light" && t !== "dark") throw new Usage("--theme takes light or dark");
537
+ a.theme = t;
538
+ } else if (f === "--size") {
539
+ const m = /^(\d+)x(\d+)$/.exec(v() ?? "");
540
+ if (!m) throw new Usage("--size takes <W>x<H>, e.g. 1920x1080");
541
+ a.width = Number(m[1]);
542
+ a.height = Number(m[2]);
543
+ } else if (f.startsWith("-") && f !== "-") throw new Usage(`unknown flag "${f}"`);
544
+ else if (a.input === void 0) a.input = f;
545
+ else throw new Usage(`unexpected argument "${f}"`);
546
+ }
547
+ if (!a.replay) throw new Usage("view needs --replay (the only view so far)");
548
+ if (!a.input) throw new Usage("no plan given");
549
+ if (!a.out) throw new Usage("-o <out.html> is required");
550
+ return a;
551
+ }
552
+ async function main(argv) {
553
+ const [cmd, ...rest] = argv;
554
+ const handler = cmd !== void 0 && cmd !== "view" ? HANDLERS[cmd] : void 0;
555
+ try {
556
+ if (handler) return await handler(parseFlags(cmd, rest));
557
+ return await view(parse(argv));
558
+ } catch (e) {
559
+ if (e instanceof Usage) {
560
+ process.stderr.write(`archlang3d: ${e.message}
561
+ ${USAGE}
562
+ `);
563
+ return 3;
564
+ }
565
+ throw e;
566
+ }
567
+ }
568
+ async function view(args) {
569
+ const say2 = (s) => process.stderr.write(`${s}
570
+ `);
571
+ let source;
572
+ try {
573
+ source = readFileSync2(args.input === "-" ? 0 : args.input, "utf8");
574
+ } catch (e) {
575
+ say2(`archlang3d: cannot read ${args.input}: ${e.message}`);
576
+ return 1;
577
+ }
578
+ const world = makeNodeWorld(args.input === "-" ? process.cwd() : dirname2(resolve2(args.input)));
579
+ const r = adaptPlan(source, { world, ...args.curveTol !== void 0 ? { curveTolMm: args.curveTol } : {} });
580
+ if (!r.ok) {
581
+ if (args.json) process.stdout.write(`${JSON.stringify({ ok: false, refusal: r.refusal }, null, 2)}
582
+ `);
583
+ say2(`archlang3d: ${r.refusal.code}: ${r.refusal.message}`);
584
+ return 2;
585
+ }
586
+ const mesh = buildMesh(r.scene, { doors: args.doors });
587
+ const storeys = storeysOf(mesh);
588
+ if (args.storey !== "all" && args.storey > storeys.length) {
589
+ process.stderr.write(
590
+ `archlang3d: --storey ${args.storey}: the plan has ${storeys.length} ${storeys.length === 1 ? "storey" : "storeys"}
591
+ ${VIEW_USAGE}
592
+ `
593
+ );
594
+ return 3;
595
+ }
596
+ const compiled = compile(source, { world });
597
+ const svgOf = (view2) => view2 === "all" ? compiled.svg : compiled.pages?.find((pg) => pg.level === storeys[view2 - 1])?.svg ?? compiled.svg;
598
+ const facts = (view2) => {
599
+ const f = replayFacts(source, { world, storeys, view: view2 });
600
+ return f ? { facts: f } : {};
601
+ };
602
+ const htmlOf = (view2) => replayHtml(viewMesh(mesh, view2), {
603
+ title: r.scene.meta.name,
604
+ svg: svgOf(view2),
605
+ width: args.width,
606
+ height: args.height,
607
+ seconds: args.seconds,
608
+ theme: args.theme,
609
+ ...facts(view2)
610
+ });
611
+ const html = await htmlOf(args.storey);
612
+ try {
613
+ writeFileSync2(args.out, html);
614
+ } catch (e) {
615
+ say2(`archlang3d: cannot write ${args.out}: ${e.message}`);
616
+ return 1;
617
+ }
618
+ const allViews = ["all", ...storeys.map((_, i) => i + 1)];
619
+ let video;
620
+ const views = [];
621
+ try {
622
+ video = await renderReplay({
623
+ html,
624
+ events: timeline(viewMesh(mesh, args.storey)),
625
+ width: args.width,
626
+ height: args.height,
627
+ fps: args.fps,
628
+ seconds: args.seconds,
629
+ ...args.video ? { mp4: args.video } : {}
630
+ });
631
+ const byHtml = /* @__PURE__ */ new Map([[html, video.keyFrames]]);
632
+ for (const view2 of allViews) {
633
+ const h = view2 === args.storey ? html : await htmlOf(view2);
634
+ let keys = byHtml.get(h);
635
+ if (!keys) {
636
+ keys = (await renderReplay({
637
+ html: h,
638
+ events: timeline(viewMesh(mesh, view2)),
639
+ width: args.width,
640
+ height: args.height,
641
+ fps: args.fps,
642
+ seconds: args.seconds
643
+ })).keyFrames;
644
+ byHtml.set(h, keys);
645
+ }
646
+ views.push({ view: viewLabel(view2), keyFrames: keys });
647
+ }
648
+ } catch (e) {
649
+ say2(`archlang3d: rendering failed (Chromium through Playwright, ffmpeg): ${e.message}`);
650
+ return 1;
651
+ }
652
+ const report = {
653
+ ok: true,
654
+ html: args.out,
655
+ ...video.mp4 ? { mp4: video.mp4 } : {},
656
+ frames: video.frames,
657
+ fps: video.fps,
658
+ seconds: video.seconds,
659
+ size: [video.width, video.height],
660
+ view: viewLabel(args.storey),
661
+ doors: args.doors,
662
+ storeys: storeys.length,
663
+ keyFrames: video.keyFrames,
664
+ ...video.strips ? { strips: video.strips } : {},
665
+ views,
666
+ seekRoundTrip: video.seekRoundTrip,
667
+ warnings: r.warnings.map((w) => ({ code: w.code, level: w.level, message: w.message })),
668
+ assumptions: mesh.assumptions.length
669
+ };
670
+ if (args.json) process.stdout.write(`${JSON.stringify(report, null, 2)}
671
+ `);
672
+ else say2(`archlang3d: wrote ${args.out}${video.mp4 ? ` and ${video.mp4} (${video.frames} frames)` : ""}`);
673
+ return 0;
674
+ }
675
+
676
+ // src/cli/main.ts
677
+ main(process.argv.slice(2)).then(
678
+ (code) => {
679
+ process.exitCode = code;
680
+ },
681
+ (e) => {
682
+ process.stderr.write(`archlang3d: internal error: ${e.stack ?? String(e)}
683
+ `);
684
+ process.exitCode = 1;
685
+ }
686
+ );