bimdown-cli 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +24 -3
  2. package/dist/chunk-4SKM4RHY.js +142 -0
  3. package/dist/chunk-4SKM4RHY.js.map +1 -0
  4. package/dist/chunk-4YHVOWS4.js +255 -0
  5. package/dist/chunk-4YHVOWS4.js.map +1 -0
  6. package/dist/chunk-AYAXRYGP.js +2129 -0
  7. package/dist/chunk-AYAXRYGP.js.map +1 -0
  8. package/dist/chunk-EC5MR5ZH.js +648 -0
  9. package/dist/chunk-EC5MR5ZH.js.map +1 -0
  10. package/dist/chunk-HS3PO2LB.js +487 -0
  11. package/dist/chunk-HS3PO2LB.js.map +1 -0
  12. package/dist/chunk-IQJA3EFO.js +179 -0
  13. package/dist/chunk-IQJA3EFO.js.map +1 -0
  14. package/dist/chunk-JY6KWRDB.js +80 -0
  15. package/dist/chunk-JY6KWRDB.js.map +1 -0
  16. package/dist/chunk-KWSGJUMZ.js +2501 -0
  17. package/dist/chunk-KWSGJUMZ.js.map +1 -0
  18. package/dist/chunk-LWYIPR64.js +35 -0
  19. package/dist/chunk-LWYIPR64.js.map +1 -0
  20. package/dist/chunk-OBY3UYCO.js +44 -0
  21. package/dist/chunk-OBY3UYCO.js.map +1 -0
  22. package/dist/chunk-XC6WHJRL.js +29 -0
  23. package/dist/chunk-XC6WHJRL.js.map +1 -0
  24. package/dist/chunk-XQU52JKB.js +187 -0
  25. package/dist/chunk-XQU52JKB.js.map +1 -0
  26. package/dist/clash-load-D3LNQR6G.js +941 -0
  27. package/dist/clash-load-D3LNQR6G.js.map +1 -0
  28. package/dist/cli.js +306 -3377
  29. package/dist/cli.js.map +1 -1
  30. package/dist/dehydrate-ZHAGOI7Q.js +90 -0
  31. package/dist/dehydrate-ZHAGOI7Q.js.map +1 -0
  32. package/dist/diff-T2KOK2WR.js +89 -0
  33. package/dist/diff-T2KOK2WR.js.map +1 -0
  34. package/dist/engine-2TPWJVEQ.js +12 -0
  35. package/dist/engine-2TPWJVEQ.js.map +1 -0
  36. package/dist/hydrate-V24H7IF3.js +673 -0
  37. package/dist/hydrate-V24H7IF3.js.map +1 -0
  38. package/dist/import-ifc-RCZSXDA6.js +5324 -0
  39. package/dist/import-ifc-RCZSXDA6.js.map +1 -0
  40. package/dist/info-QC7YXWNX.js +92 -0
  41. package/dist/info-QC7YXWNX.js.map +1 -0
  42. package/dist/init-VWDML3UC.js +112 -0
  43. package/dist/init-VWDML3UC.js.map +1 -0
  44. package/dist/lib.d.ts +427 -44
  45. package/dist/lib.js +6482 -225
  46. package/dist/lib.js.map +1 -1
  47. package/dist/mep-W4HJI363.js +25 -0
  48. package/dist/mep-W4HJI363.js.map +1 -0
  49. package/dist/merge-ESOPDSA5.js +413 -0
  50. package/dist/merge-ESOPDSA5.js.map +1 -0
  51. package/dist/publish-3TAXQCUV.js +80 -0
  52. package/dist/publish-3TAXQCUV.js.map +1 -0
  53. package/dist/render-UEWYHPN6.js +1807 -0
  54. package/dist/render-UEWYHPN6.js.map +1 -0
  55. package/dist/resolve-topology-AQ2RO3W3.js +338 -0
  56. package/dist/resolve-topology-AQ2RO3W3.js.map +1 -0
  57. package/dist/spec/csv-schema/annotation/dimension.yaml +77 -0
  58. package/dist/spec/csv-schema/annotation/tag.yaml +44 -0
  59. package/dist/spec/csv-schema/annotation/text_note.yaml +52 -0
  60. package/dist/spec/csv-schema/architecture/ceiling.yaml +8 -1
  61. package/dist/spec/csv-schema/architecture/column.yaml +5 -1
  62. package/dist/spec/csv-schema/architecture/curtain_wall.yaml +45 -5
  63. package/dist/spec/csv-schema/architecture/door.yaml +5 -0
  64. package/dist/spec/csv-schema/architecture/furniture.yaml +28 -0
  65. package/dist/spec/csv-schema/architecture/opening.yaml +27 -6
  66. package/dist/spec/csv-schema/architecture/railing.yaml +35 -0
  67. package/dist/spec/csv-schema/architecture/roof.yaml +34 -1
  68. package/dist/spec/csv-schema/architecture/slab.yaml +19 -0
  69. package/dist/spec/csv-schema/architecture/space.yaml +11 -1
  70. package/dist/spec/csv-schema/architecture/stair.yaml +49 -0
  71. package/dist/spec/csv-schema/architecture/stair_landing.yaml +36 -0
  72. package/dist/spec/csv-schema/architecture/stair_run.yaml +31 -0
  73. package/dist/spec/csv-schema/architecture/wall.yaml +14 -1
  74. package/dist/spec/csv-schema/architecture/window.yaml +19 -0
  75. package/dist/spec/csv-schema/base/element.yaml +20 -11
  76. package/dist/spec/csv-schema/base/furniture_params.yaml +60 -0
  77. package/dist/spec/csv-schema/base/hosted_element.yaml +10 -2
  78. package/dist/spec/csv-schema/base/mep_connectable.yaml +23 -0
  79. package/dist/spec/csv-schema/base/mep_design.yaml +24 -0
  80. package/dist/spec/csv-schema/base/mep_insulated.yaml +9 -0
  81. package/dist/spec/csv-schema/base/mep_system_tag.yaml +12 -0
  82. package/dist/spec/csv-schema/base/point_element.yaml +1 -0
  83. package/dist/spec/csv-schema/base/section_profile.yaml +5 -0
  84. package/dist/spec/csv-schema/base/spatial_line_element.yaml +4 -2
  85. package/dist/spec/csv-schema/base/structural_section_profile.yaml +50 -0
  86. package/dist/spec/csv-schema/base/vertical_span.yaml +5 -4
  87. package/dist/spec/csv-schema/base/wall_bounded.yaml +21 -0
  88. package/dist/spec/csv-schema/grid.yaml +5 -0
  89. package/dist/spec/csv-schema/mep/cable_tray.yaml +10 -3
  90. package/dist/spec/csv-schema/mep/circuit.yaml +70 -0
  91. package/dist/spec/csv-schema/mep/conduit.yaml +2 -2
  92. package/dist/spec/csv-schema/mep/connector.yaml +112 -0
  93. package/dist/spec/csv-schema/mep/duct.yaml +10 -3
  94. package/dist/spec/csv-schema/mep/equipment.yaml +18 -1
  95. package/dist/spec/csv-schema/mep/mep_node.yaml +91 -2
  96. package/dist/spec/csv-schema/mep/mep_system.yaml +21 -0
  97. package/dist/spec/csv-schema/mep/pipe.yaml +27 -3
  98. package/dist/spec/csv-schema/mep/terminal.yaml +22 -1
  99. package/dist/spec/csv-schema/model_group.yaml +40 -0
  100. package/dist/spec/csv-schema/sheet/sheet.yaml +50 -0
  101. package/dist/spec/csv-schema/sheet/sheet_viewport.yaml +86 -0
  102. package/dist/spec/csv-schema/structure/beam.yaml +29 -1
  103. package/dist/spec/csv-schema/structure/beam_system.yaml +29 -0
  104. package/dist/spec/csv-schema/structure/brace.yaml +24 -1
  105. package/dist/spec/csv-schema/structure/foundation.yaml +40 -7
  106. package/dist/spec/csv-schema/structure/structure_column.yaml +19 -1
  107. package/dist/spec/csv-schema/structure/structure_slab.yaml +32 -0
  108. package/dist/spec/csv-schema/structure/structure_wall.yaml +22 -0
  109. package/dist/spec/csv-schema/types/beam_type.yaml +11 -0
  110. package/dist/spec/csv-schema/types/ceiling_type.yaml +6 -0
  111. package/dist/spec/csv-schema/types/column_type.yaml +12 -0
  112. package/dist/spec/csv-schema/types/curtain_wall_type.yaml +32 -0
  113. package/dist/spec/csv-schema/types/door_type.yaml +27 -0
  114. package/dist/spec/csv-schema/types/element_type.yaml +21 -0
  115. package/dist/spec/csv-schema/types/fenestration.yaml +16 -0
  116. package/dist/spec/csv-schema/types/foundation_type.yaml +36 -0
  117. package/dist/spec/csv-schema/types/furniture_type.yaml +11 -0
  118. package/dist/spec/csv-schema/types/layered_type.yaml +13 -0
  119. package/dist/spec/csv-schema/types/railing_type.yaml +40 -0
  120. package/dist/spec/csv-schema/types/roof_type.yaml +7 -0
  121. package/dist/spec/csv-schema/types/slab_type.yaml +9 -0
  122. package/dist/spec/csv-schema/types/type_layer.yaml +47 -0
  123. package/dist/spec/csv-schema/types/wall_type.yaml +6 -0
  124. package/dist/spec/csv-schema/types/window_type.yaml +31 -0
  125. package/dist/spec/csv-schema/underlay.yaml +73 -0
  126. package/dist/spec/csv-schema/view.yaml +36 -0
  127. package/dist/spec/duckdb-strategy.md +4 -3
  128. package/dist/spec/geojson-schema/readme.md +380 -0
  129. package/dist/spec/mep-port-conventions.md +190 -0
  130. package/dist/spec/migration-guide.md +1 -1
  131. package/dist/spec/project_metadata.schema.yaml +52 -4
  132. package/dist/spec/readme.md +356 -97
  133. package/dist/spec/starter-types/global/beam_type.csv +5 -0
  134. package/dist/spec/starter-types/global/ceiling_type.csv +3 -0
  135. package/dist/spec/starter-types/global/column_type.csv +5 -0
  136. package/dist/spec/starter-types/global/curtain_wall_type.csv +2 -0
  137. package/dist/spec/starter-types/global/door_type.csv +6 -0
  138. package/dist/spec/starter-types/global/foundation_type.csv +7 -0
  139. package/dist/spec/starter-types/global/furniture_type.csv +11 -0
  140. package/dist/spec/starter-types/global/railing_type.csv +5 -0
  141. package/dist/spec/starter-types/global/roof_type.csv +3 -0
  142. package/dist/spec/starter-types/global/slab_type.csv +4 -0
  143. package/dist/spec/starter-types/global/type_layer.csv +40 -0
  144. package/dist/spec/starter-types/global/wall_type.csv +8 -0
  145. package/dist/spec/starter-types/global/window_type.csv +6 -0
  146. package/dist/spec/svg-schema/readme.md +47 -1
  147. package/package.json +6 -3
  148. package/dist/spec/csv-schema/base/mep_connected_segment.yaml +0 -17
  149. package/dist/spec/csv-schema/base/mep_system.yaml +0 -7
package/dist/cli.js CHANGED
@@ -1,3288 +1,174 @@
1
1
  #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __esm = (fn, res) => function __init() {
5
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
- };
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
-
12
- // src/schema/loader.ts
13
- import { readFileSync, readdirSync, statSync } from "fs";
14
- import { join } from "path";
15
- import { parse as parseYaml } from "yaml";
16
- function loadAllSchemas(specDir) {
17
- const schemas = /* @__PURE__ */ new Map();
18
- walkYaml(specDir, schemas);
19
- return schemas;
20
- }
21
- function walkYaml(dir, schemas) {
22
- for (const entry of readdirSync(dir)) {
23
- const full = join(dir, entry);
24
- if (statSync(full).isDirectory()) {
25
- walkYaml(full, schemas);
26
- } else if (entry.endsWith(".yaml") || entry.endsWith(".yml")) {
27
- const raw = parseYaml(readFileSync(full, "utf-8"));
28
- if (raw?.name) schemas.set(raw.name, raw);
29
- }
30
- }
31
- }
32
- function resolveFields(name, schemas, resolved = /* @__PURE__ */ new Map()) {
33
- if (resolved.has(name)) return resolved.get(name);
34
- const schema = schemas.get(name);
35
- if (!schema) throw new Error(`Unknown schema: ${name}`);
36
- const fields = [];
37
- const seen = /* @__PURE__ */ new Set();
38
- for (const baseName of schema.bases ?? []) {
39
- for (const f of resolveFields(baseName, schemas, resolved)) {
40
- if (!seen.has(f.name)) {
41
- seen.add(f.name);
42
- fields.push(f);
43
- }
44
- }
45
- }
46
- for (const raw of schema.fields ?? []) {
47
- const rf = normalizeField(raw);
48
- const idx = fields.findIndex((f) => f.name === rf.name);
49
- if (idx >= 0) {
50
- fields[idx] = rf;
51
- } else {
52
- fields.push(rf);
53
- }
54
- }
55
- resolved.set(name, fields);
56
- return fields;
57
- }
58
- function normalizeField(raw) {
59
- return {
60
- name: raw.name,
61
- type: raw.type,
62
- required: raw.required ?? false,
63
- computed: raw.computed ?? false,
64
- reference: raw.reference,
65
- values: raw.values,
66
- description: raw.description
67
- };
68
- }
69
- var init_loader = __esm({
70
- "src/schema/loader.ts"() {
71
- "use strict";
72
- }
73
- });
74
-
75
- // src/schema/registry.ts
76
- import { join as join2, dirname } from "path";
77
- import { existsSync } from "fs";
78
- import { fileURLToPath } from "url";
79
- function buildRegistry(specDir) {
80
- if (_registry && _specDir === specDir) return _registry;
81
- const schemas = loadAllSchemas(join2(specDir, "csv-schema"));
82
- const resolved = /* @__PURE__ */ new Map();
83
- const registry = /* @__PURE__ */ new Map();
84
- for (const [name, schema] of schemas) {
85
- if (schema.abstract) continue;
86
- const prefix = ID_PREFIXES[name];
87
- if (!prefix) continue;
88
- const allFields = resolveFields(name, schemas, resolved);
89
- const csvFields = allFields.filter((f) => !f.computed);
90
- const computedFields = allFields.filter((f) => f.computed);
91
- registry.set(name, {
92
- name,
93
- prefix,
94
- description: schema.description,
95
- hostType: schema.host_type,
96
- allFields,
97
- csvFields,
98
- computedFields
99
- });
100
- }
101
- _registry = registry;
102
- _specDir = specDir;
103
- return registry;
104
- }
105
- function getSpecDir() {
106
- if (process.env.SPEC_DIR) return process.env.SPEC_DIR;
107
- const thisDir = dirname(fileURLToPath(import.meta.url));
108
- const bundledPath = join2(thisDir, "spec");
109
- if (existsSync(bundledPath)) return bundledPath;
110
- let current = thisDir;
111
- for (let i = 0; i < 5; i++) {
112
- const candidate = join2(current, "spec");
113
- if (existsSync(candidate)) return candidate;
114
- const parent = dirname(current);
115
- if (parent === current) break;
116
- current = parent;
117
- }
118
- return join2(process.cwd(), "spec");
119
- }
120
- var ID_PREFIXES, GLOBAL_ONLY_TABLES, TABLES_WITHOUT_SVG, SVG_FILE_NAMES, TABLES_WITH_SVG, _registry, _specDir;
121
- var init_registry = __esm({
122
- "src/schema/registry.ts"() {
123
- "use strict";
124
- init_loader();
125
- ID_PREFIXES = {
126
- level: "lv",
127
- grid: "gr",
128
- wall: "w",
129
- column: "c",
130
- slab: "sl",
131
- space: "sp",
132
- door: "d",
133
- window: "wn",
134
- stair: "st",
135
- ramp: "rp",
136
- railing: "rl",
137
- room_separator: "rs",
138
- curtain_wall: "cw",
139
- roof: "ro",
140
- ceiling: "cl",
141
- opening: "op",
142
- structure_wall: "sw",
143
- structure_column: "sc",
144
- structure_slab: "ss",
145
- beam: "bm",
146
- brace: "br",
147
- foundation: "f",
148
- duct: "du",
149
- pipe: "pi",
150
- cable_tray: "ct",
151
- conduit: "co",
152
- equipment: "eq",
153
- terminal: "tm",
154
- mep_node: "mn",
155
- mesh: "ms"
156
- };
157
- GLOBAL_ONLY_TABLES = /* @__PURE__ */ new Set(["level", "grid", "mesh"]);
158
- TABLES_WITHOUT_SVG = /* @__PURE__ */ new Set(["level", "grid", "door", "window", "mesh"]);
159
- SVG_FILE_NAMES = Object.fromEntries(
160
- Object.keys(ID_PREFIXES).filter((k) => !TABLES_WITHOUT_SVG.has(k)).map((k) => [k, k])
161
- );
162
- TABLES_WITH_SVG = new Set(Object.keys(SVG_FILE_NAMES));
163
- _registry = null;
164
- _specDir = null;
165
- }
166
- });
167
-
168
- // src/utils/fs.ts
169
- import { readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync2 } from "fs";
170
- import { join as join3 } from "path";
171
- function discoverLayout(dir) {
172
- const globalDir = join3(dir, "global");
173
- const levelDirs = [];
174
- if (existsSync2(dir) && statSync2(dir).isDirectory()) {
175
- for (const entry of readdirSync2(dir)) {
176
- if (entry === "global" || entry.startsWith(".")) continue;
177
- const full = join3(dir, entry);
178
- if (statSync2(full).isDirectory()) {
179
- levelDirs.push({ name: entry, path: full });
180
- }
181
- }
182
- }
183
- return { root: dir, globalDir, levelDirs };
184
- }
185
- function listFiles(dir) {
186
- if (!existsSync2(dir)) return [];
187
- return readdirSync2(dir).filter((f) => {
188
- const full = join3(dir, f);
189
- return statSync2(full).isFile();
190
- });
191
- }
192
- var init_fs = __esm({
193
- "src/utils/fs.ts"() {
194
- "use strict";
195
- }
196
- });
197
-
198
- // src/utils/csv.ts
199
- import { readFileSync as readFileSync2, writeFileSync } from "fs";
200
- function readCsv(filePath) {
201
- let text = readFileSync2(filePath, "utf-8");
202
- if (text.charCodeAt(0) === 65279) text = text.slice(1);
203
- const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");
204
- if (lines.length === 0) return { headers: [], rows: [] };
205
- const headers = parseCsvLine(lines[0]);
206
- const rows = lines.slice(1).map((line) => {
207
- const values = parseCsvLine(line);
208
- const row = {};
209
- for (let i = 0; i < headers.length; i++) {
210
- row[headers[i]] = values[i] ?? "";
211
- }
212
- return row;
213
- });
214
- return { headers, rows };
215
- }
216
- function parseCsvLine(line) {
217
- const result = [];
218
- let current = "";
219
- let inQuotes = false;
220
- for (let i = 0; i < line.length; i++) {
221
- const ch = line[i];
222
- if (inQuotes) {
223
- if (ch === '"') {
224
- if (i + 1 < line.length && line[i + 1] === '"') {
225
- current += '"';
226
- i++;
227
- } else {
228
- inQuotes = false;
229
- }
230
- } else {
231
- current += ch;
232
- }
233
- } else {
234
- if (ch === '"') {
235
- inQuotes = true;
236
- } else if (ch === ",") {
237
- result.push(current);
238
- current = "";
239
- } else {
240
- current += ch;
241
- }
242
- }
243
- }
244
- result.push(current);
245
- return result;
246
- }
247
- function writeCsv(filePath, data) {
248
- const lines = [data.headers.join(",")];
249
- for (const row of data.rows) {
250
- const values = data.headers.map((h) => escapeCsvValue(row[h] ?? ""));
251
- lines.push(values.join(","));
252
- }
253
- writeFileSync(filePath, lines.join("\n") + "\n", "utf-8");
254
- }
255
- function escapeCsvValue(val) {
256
- if (val.includes(",") || val.includes('"') || val.includes("\n")) {
257
- return '"' + val.replace(/"/g, '""') + '"';
258
- }
259
- return val;
260
- }
261
- var init_csv = __esm({
262
- "src/utils/csv.ts"() {
263
- "use strict";
264
- }
265
- });
266
-
267
- // src/utils/svg.ts
268
- import { readFileSync as readFileSync4 } from "fs";
269
- import { XMLParser } from "fast-xml-parser";
270
- function parseSvgFile(filePath) {
271
- let text = readFileSync4(filePath, "utf-8");
272
- if (text.charCodeAt(0) === 65279) text = text.slice(1);
273
- const parsed = parser.parse(text);
274
- const elements = [];
275
- const allTags = [];
276
- let hasYFlip = false;
277
- function walk(node, tag) {
278
- if (!node || typeof node !== "object") return;
279
- if (tag) allTags.push(tag);
280
- if (tag === "g") {
281
- const transform = node["@_transform"] ?? "";
282
- if (typeof transform === "string" && transform.includes("scale(1,-1)")) {
283
- hasYFlip = true;
284
- }
285
- }
286
- const geoTags = ["path", "line", "rect", "polygon", "circle", "text"];
287
- if (tag && geoTags.includes(tag)) {
288
- const attrs = {};
289
- for (const [k, v] of Object.entries(node)) {
290
- if (k.startsWith("@_")) {
291
- attrs[k.slice(2)] = String(v);
292
- }
293
- }
294
- if (attrs.id) {
295
- elements.push({ tag, id: attrs.id, attrs });
296
- }
297
- }
298
- for (const [key, value] of Object.entries(node)) {
299
- if (key.startsWith("@_") || key.startsWith("?")) continue;
300
- if (Array.isArray(value)) {
301
- for (const item of value) walk(item, key);
302
- } else if (typeof value === "object" && value !== null) {
303
- walk(value, key);
304
- }
305
- }
306
- }
307
- walk(parsed);
308
- return { elements, allTags, hasYFlip, raw: parsed };
309
- }
310
- function extractLineGeometry(el) {
311
- let x1, y1, x2, y2;
312
- if (el.tag === "path") {
313
- const d = el.attrs.d ?? "";
314
- const m = d.match(/M\s*(-?[\d.]+)[,\s]+(-?[\d.]+)\s*L\s*(-?[\d.]+)[,\s]+(-?[\d.]+)/);
315
- if (m) {
316
- x1 = parseFloat(m[1]);
317
- y1 = parseFloat(m[2]);
318
- x2 = parseFloat(m[3]);
319
- y2 = parseFloat(m[4]);
320
- } else {
321
- x1 = y1 = x2 = y2 = 0;
322
- }
323
- } else {
324
- x1 = parseFloat(el.attrs.x1 ?? "0");
325
- y1 = parseFloat(el.attrs.y1 ?? "0");
326
- x2 = parseFloat(el.attrs.x2 ?? "0");
327
- y2 = parseFloat(el.attrs.y2 ?? "0");
328
- }
329
- const dx = x2 - x1;
330
- const dy = y2 - y1;
331
- return {
332
- start_x: x1,
333
- start_y: y1,
334
- end_x: x2,
335
- end_y: y2,
336
- length: Math.sqrt(dx * dx + dy * dy),
337
- thickness: 0
338
- };
339
- }
340
- function extractRectGeometry(el) {
341
- const x = parseFloat(el.attrs.x ?? "0");
342
- const y = parseFloat(el.attrs.y ?? "0");
343
- const w = parseFloat(el.attrs.width ?? "0");
344
- const h = parseFloat(el.attrs.height ?? "0");
345
- let rotation = 0;
346
- const transform = el.attrs.transform;
347
- if (transform) {
348
- const m = transform.match(/rotate\(([^,)]+)/);
349
- if (m) rotation = parseFloat(m[1]);
350
- }
351
- return {
352
- x: x + w / 2,
353
- y: y + h / 2,
354
- rotation,
355
- size_x: w,
356
- size_y: h
357
- };
358
- }
359
- function extractPolygonGeometry(el) {
360
- const pointsStr = el.attrs.points ?? "";
361
- const coords = pointsStr.trim().split(/\s+/).map((p) => {
362
- const [x, y] = p.split(",").map(Number);
363
- return { x: x ?? 0, y: y ?? 0 };
364
- });
365
- let area = 0;
366
- for (let i = 0; i < coords.length; i++) {
367
- const j = (i + 1) % coords.length;
368
- area += coords[i].x * coords[j].y;
369
- area -= coords[j].x * coords[i].y;
370
- }
371
- return { points: pointsStr, area: Math.abs(area) / 2 };
372
- }
373
- function extractCircleGeometry(el) {
374
- const cx = parseFloat(el.attrs.cx ?? "0");
375
- const cy = parseFloat(el.attrs.cy ?? "0");
376
- const r = parseFloat(el.attrs.r ?? "0");
377
- return { x: cx, y: cy, size_x: r * 2, size_y: r * 2 };
378
- }
379
- function formatSvgAttrs(attrs, idOverride) {
380
- const parts = [];
381
- for (const [k, v] of Object.entries(attrs)) {
382
- const val = k === "id" && idOverride ? idOverride : v;
383
- parts.push(`${k}="${val}"`);
384
- }
385
- return parts.join(" ");
386
- }
387
- function elementBounds(el) {
388
- switch (el.tag) {
389
- case "path": {
390
- const geo = extractLineGeometry(el);
391
- return {
392
- minX: Math.min(geo.start_x, geo.end_x),
393
- minY: Math.min(geo.start_y, geo.end_y),
394
- maxX: Math.max(geo.start_x, geo.end_x),
395
- maxY: Math.max(geo.start_y, geo.end_y)
396
- };
397
- }
398
- case "line": {
399
- const x1 = parseFloat(el.attrs.x1 ?? "0"), y1 = parseFloat(el.attrs.y1 ?? "0");
400
- const x2 = parseFloat(el.attrs.x2 ?? "0"), y2 = parseFloat(el.attrs.y2 ?? "0");
401
- return { minX: Math.min(x1, x2), minY: Math.min(y1, y2), maxX: Math.max(x1, x2), maxY: Math.max(y1, y2) };
402
- }
403
- case "rect": {
404
- const x = parseFloat(el.attrs.x ?? "0"), y = parseFloat(el.attrs.y ?? "0");
405
- const w = parseFloat(el.attrs.width ?? "0"), h = parseFloat(el.attrs.height ?? "0");
406
- return { minX: x, minY: y, maxX: x + w, maxY: y + h };
407
- }
408
- case "circle": {
409
- const cx = parseFloat(el.attrs.cx ?? "0"), cy = parseFloat(el.attrs.cy ?? "0");
410
- const r = parseFloat(el.attrs.r ?? "0");
411
- return { minX: cx - r, minY: cy - r, maxX: cx + r, maxY: cy + r };
412
- }
413
- case "polygon": {
414
- const pts = (el.attrs.points ?? "").trim().split(/\s+/).map((p) => {
415
- const [x, y] = p.split(",").map(Number);
416
- return { x: x ?? 0, y: y ?? 0 };
417
- });
418
- if (pts.length === 0) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
419
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
420
- for (const p of pts) {
421
- minX = Math.min(minX, p.x);
422
- minY = Math.min(minY, p.y);
423
- maxX = Math.max(maxX, p.x);
424
- maxY = Math.max(maxY, p.y);
425
- }
426
- return { minX, minY, maxX, maxY };
427
- }
428
- default:
429
- return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
430
- }
431
- }
432
- function writeMergedSvg(inputs) {
433
- const allElements = [];
434
- for (const input of inputs) {
435
- for (const el of input.elements) {
436
- const newId = input.idRemap.get(el.id) ?? el.id;
437
- allElements.push({ el, newId });
438
- }
439
- }
440
- if (allElements.length === 0) {
441
- return '<?xml version="1.0" encoding="utf-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0">\n <g transform="scale(1,-1)">\n </g>\n</svg>';
442
- }
443
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
444
- for (const { el } of allElements) {
445
- const b = elementBounds(el);
446
- minX = Math.min(minX, b.minX);
447
- minY = Math.min(minY, b.minY);
448
- maxX = Math.max(maxX, b.maxX);
449
- maxY = Math.max(maxY, b.maxY);
450
- }
451
- const vbX = minX;
452
- const vbY = -maxY;
453
- const vbW = maxX - minX;
454
- const vbH = maxY - minY;
455
- const pad = Math.max(vbW, vbH) * 0.02;
456
- const viewBox = `${(vbX - pad).toFixed(3)} ${(vbY - pad).toFixed(3)} ${(vbW + pad * 2).toFixed(3)} ${(vbH + pad * 2).toFixed(3)}`;
457
- const lines = [
458
- '<?xml version="1.0" encoding="utf-8"?>',
459
- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`,
460
- ' <g transform="scale(1,-1)">'
461
- ];
462
- for (const { el, newId } of allElements) {
463
- lines.push(` <${el.tag} ${formatSvgAttrs(el.attrs, newId)} />`);
464
- }
465
- lines.push(" </g>");
466
- lines.push("</svg>");
467
- return lines.join("\n");
468
- }
469
- var parser;
470
- var init_svg = __esm({
471
- "src/utils/svg.ts"() {
472
- "use strict";
473
- parser = new XMLParser({
474
- ignoreAttributes: false,
475
- attributeNamePrefix: "@_",
476
- allowBooleanAttributes: true,
477
- parseAttributeValue: false,
478
- trimValues: true
479
- });
480
- }
481
- });
482
-
483
- // src/duckdb/engine.ts
484
- var engine_exports = {};
485
- __export(engine_exports, {
486
- closeConnection: () => closeConnection,
487
- getConnection: () => getConnection,
488
- runQuery: () => runQuery
489
- });
490
- import { DuckDBInstance } from "@duckdb/node-api";
491
- async function getConnection() {
492
- if (connection) return connection;
493
- instance = await DuckDBInstance.create(":memory:");
494
- connection = await instance.connect();
495
- return connection;
496
- }
497
- async function closeConnection() {
498
- connection = null;
499
- instance = null;
500
- }
501
- async function runQuery(conn, sql) {
502
- const reader = await conn.runAndReadAll(sql);
503
- const columns = reader.columnNames();
504
- const rows = reader.getRowObjects();
505
- return { columns, rows };
506
- }
507
- var instance, connection;
508
- var init_engine = __esm({
509
- "src/duckdb/engine.ts"() {
510
- "use strict";
511
- instance = null;
512
- connection = null;
513
- }
514
- });
515
-
516
- // src/duckdb/hydrate.ts
517
- var hydrate_exports = {};
518
- __export(hydrate_exports, {
519
- hydrate: () => hydrate
520
- });
521
- import { existsSync as existsSync10 } from "fs";
522
- import { join as join11 } from "path";
523
- async function hydrate(conn, dir) {
524
- const registry = buildRegistry(getSpecDir());
525
- const layout = discoverLayout(dir);
526
- const tables = [];
527
- const allDirs = [
528
- { name: "global", path: layout.globalDir },
529
- ...layout.levelDirs
530
- ];
531
- const hydrated = [];
532
- for (const [tableName, table] of registry) {
533
- const csvFiles = [];
534
- for (const d of allDirs) {
535
- const csvPath = join11(d.path, `${tableName}.csv`);
536
- if (existsSync10(csvPath)) {
537
- csvFiles.push({ dir: d.name, fullPath: csvPath });
538
- }
539
- }
540
- if (csvFiles.length === 0) continue;
541
- const allRows = [];
542
- let headers = [];
543
- for (const { dir: dirName, fullPath } of csvFiles) {
544
- const data = readCsv(fullPath);
545
- if (headers.length === 0) headers = data.headers;
546
- for (const row of data.rows) {
547
- allRows.push({ ...row, _partition: dirName });
548
- }
549
- }
550
- if (allRows.length === 0) continue;
551
- const cols = [...headers, "_partition"];
552
- const colDefs = cols.map((c) => `"${c}" VARCHAR`).join(", ");
553
- await runQuery(conn, `CREATE TABLE "${tableName}" (${colDefs})`);
554
- for (let i = 0; i < allRows.length; i += INSERT_BATCH_SIZE) {
555
- const batch = allRows.slice(i, i + INSERT_BATCH_SIZE);
556
- const valuesSql = batch.map((row) => `(${cols.map((c) => escapeSql(row[c] ?? "")).join(", ")})`).join(", ");
557
- await runQuery(conn, `INSERT INTO "${tableName}" VALUES ${valuesSql}`);
558
- }
559
- tables.push(tableName);
560
- hydrated.push({ name: tableName, table });
561
- }
562
- const levelsReady = await tryCreateLevelsTemp(conn);
563
- for (const { name, table } of hydrated) {
564
- await injectGeometry(conn, name, allDirs);
565
- if (levelsReady && table.computedFields.some((f) => f.name === "height")) {
566
- await injectHeight(conn, name);
567
- }
568
- }
569
- return tables;
570
- }
571
- async function tryCreateLevelsTemp(conn) {
572
- const check = await runQuery(
573
- conn,
574
- `SELECT table_name FROM information_schema.tables WHERE table_name = 'level'`
575
- );
576
- if (check.rows.length === 0) return false;
577
- await runQuery(
578
- conn,
579
- `CREATE TEMP TABLE _levels AS
580
- SELECT
581
- id,
582
- CAST(elevation AS DOUBLE) AS elevation,
583
- ROW_NUMBER() OVER (ORDER BY CAST(elevation AS DOUBLE)) AS rank
584
- FROM level
585
- WHERE elevation IS NOT NULL AND elevation <> ''`
586
- );
587
- return true;
588
- }
589
- async function injectHeight(conn, tableName) {
590
- const colsResult = await runQuery(
591
- conn,
592
- `SELECT column_name FROM information_schema.columns WHERE table_name = '${tableName}'`
593
- );
594
- const existing = new Set(colsResult.rows.map((r) => String(r.column_name)));
595
- const ensureVarchar = async (col) => {
596
- if (!existing.has(col)) {
597
- await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "${col}" VARCHAR`);
598
- }
599
- };
600
- await ensureVarchar("base_level_id");
601
- await ensureVarchar("top_level_id");
602
- await ensureVarchar("base_offset");
603
- await ensureVarchar("top_offset");
604
- if (!existing.has("height")) {
605
- await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "height" DOUBLE`);
606
- }
607
- await runQuery(
608
- conn,
609
- `UPDATE "${tableName}" AS t
610
- SET height = (lv_top.elevation + COALESCE(CAST(NULLIF(t.top_offset, '') AS DOUBLE), 0))
611
- - (lv_base.elevation + COALESCE(CAST(NULLIF(t.base_offset, '') AS DOUBLE), 0))
612
- FROM _levels AS lv_base, _levels AS lv_top
613
- WHERE lv_base.id = COALESCE(
614
- NULLIF(t.base_level_id, ''),
615
- CASE WHEN t._partition <> 'global'
616
- THEN t._partition
617
- ELSE (SELECT id FROM _levels ORDER BY rank LIMIT 1)
618
- END
619
- )
620
- AND lv_top.id = COALESCE(
621
- NULLIF(t.top_level_id, ''),
622
- (SELECT id FROM _levels WHERE rank = lv_base.rank + 1)
623
- )`
624
- );
625
- }
626
- async function injectGeometry(conn, tableName, dirs) {
627
- const svgName = SVG_FILE_NAMES[tableName];
628
- if (!svgName) return;
629
- const geometries = /* @__PURE__ */ new Map();
630
- for (const d of dirs) {
631
- const svgPath = join11(d.path, `${svgName}.svg`);
632
- if (!existsSync10(svgPath)) continue;
633
- try {
634
- const svg = parseSvgFile(svgPath);
635
- for (const el of svg.elements) {
636
- if (el.tag === "path") {
637
- geometries.set(el.id, extractLineGeometry(el));
638
- } else if (el.tag === "rect") {
639
- geometries.set(el.id, extractRectGeometry(el));
640
- } else if (el.tag === "polygon") {
641
- geometries.set(el.id, extractPolygonGeometry(el));
642
- } else if (el.tag === "circle") {
643
- geometries.set(el.id, extractCircleGeometry(el));
644
- }
645
- }
646
- } catch {
647
- }
648
- }
649
- if (geometries.size === 0) return;
650
- const allKeys = /* @__PURE__ */ new Set();
651
- for (const geo of geometries.values()) {
652
- for (const k of Object.keys(geo)) allKeys.add(k);
653
- }
654
- const geoCols = Array.from(allKeys);
655
- const typeOf = (col) => col === "points" ? "VARCHAR" : "DOUBLE";
656
- const existingCols = await runQuery(
657
- conn,
658
- `SELECT column_name FROM information_schema.columns WHERE table_name = '${tableName}'`
659
- );
660
- const existingSet = new Set(existingCols.rows.map((r) => String(r.column_name)));
661
- for (const col of geoCols) {
662
- if (existingSet.has(col)) continue;
663
- await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "${col}" ${typeOf(col)}`);
664
- }
665
- const stagingName = `_geo_${tableName}`;
666
- const stagingColDefs = ['"id" VARCHAR', ...geoCols.map((c) => `"${c}" ${typeOf(c)}`)].join(", ");
667
- await runQuery(conn, `CREATE TEMP TABLE "${stagingName}" (${stagingColDefs})`);
668
- const entries = Array.from(geometries.entries());
669
- for (let i = 0; i < entries.length; i += INSERT_BATCH_SIZE) {
670
- const batch = entries.slice(i, i + INSERT_BATCH_SIZE);
671
- const valuesSql = batch.map(([id, geo]) => {
672
- const vals = [escapeSql(id)];
673
- for (const col of geoCols) {
674
- const v = geo[col];
675
- if (v === void 0 || v === null) {
676
- vals.push("NULL");
677
- } else if (typeof v === "string") {
678
- vals.push(escapeSql(v));
679
- } else {
680
- vals.push(String(v));
681
- }
682
- }
683
- return `(${vals.join(", ")})`;
684
- }).join(", ");
685
- await runQuery(conn, `INSERT INTO "${stagingName}" VALUES ${valuesSql}`);
686
- }
687
- const setClause = geoCols.map((c) => `"${c}" = g."${c}"`).join(", ");
688
- await runQuery(
689
- conn,
690
- `UPDATE "${tableName}" SET ${setClause} FROM "${stagingName}" g WHERE "${tableName}".id = g.id`
691
- );
692
- await runQuery(conn, `DROP TABLE "${stagingName}"`);
693
- }
694
- function escapeSql(val) {
695
- return "'" + val.replace(/'/g, "''") + "'";
696
- }
697
- var INSERT_BATCH_SIZE;
698
- var init_hydrate = __esm({
699
- "src/duckdb/hydrate.ts"() {
700
- "use strict";
701
- init_registry();
702
- init_fs();
703
- init_csv();
704
- init_svg();
705
- init_engine();
706
- INSERT_BATCH_SIZE = 500;
707
- }
708
- });
709
-
710
- // src/duckdb/dehydrate.ts
711
- var dehydrate_exports = {};
712
- __export(dehydrate_exports, {
713
- dehydrate: () => dehydrate
714
- });
715
- import { existsSync as existsSync11, mkdirSync } from "fs";
716
- import { join as join12 } from "path";
717
- async function dehydrate(conn, dir) {
718
- const registry = buildRegistry(getSpecDir());
719
- for (const [tableName, table] of registry) {
720
- const check = await runQuery(
721
- conn,
722
- `SELECT count(*) as cnt FROM information_schema.tables WHERE table_name = '${tableName}'`
723
- );
724
- if (!check.rows.length || check.rows[0].cnt === 0n) continue;
725
- const csvHeaders = table.csvFields.map((f) => f.name);
726
- const partResult = await runQuery(
727
- conn,
728
- `SELECT DISTINCT _partition FROM "${tableName}"`
729
- );
730
- for (const partRow of partResult.rows) {
731
- const partition = String(partRow._partition);
732
- const outDir = join12(dir, partition);
733
- if (!existsSync11(outDir)) mkdirSync(outDir, { recursive: true });
734
- const selectCols = csvHeaders.map((h) => `"${h}"`).join(", ");
735
- const dataResult = await runQuery(
736
- conn,
737
- `SELECT ${selectCols} FROM "${tableName}" WHERE _partition = '${partition}'`
738
- );
739
- const data = {
740
- headers: csvHeaders,
741
- rows: dataResult.rows.map((r) => {
742
- const row = {};
743
- for (const h of csvHeaders) {
744
- const val = r[h];
745
- row[h] = val == null ? "" : String(val);
746
- }
747
- return row;
748
- })
749
- };
750
- writeCsv(join12(outDir, `${tableName}.csv`), data);
751
- }
752
- }
753
- }
754
- var init_dehydrate = __esm({
755
- "src/duckdb/dehydrate.ts"() {
756
- "use strict";
757
- init_registry();
758
- init_csv();
759
- init_engine();
760
- }
761
- });
762
-
763
- // src/render.ts
764
- var render_exports = {};
765
- __export(render_exports, {
766
- renderLevel: () => renderLevel
767
- });
768
- import { existsSync as existsSync12 } from "fs";
769
- import { join as join13 } from "path";
770
- function elementBounds2(el) {
771
- switch (el.tag) {
772
- case "path": {
773
- const d = el.attrs.d ?? "";
774
- const m = d.match(/M\s*(-?[\d.]+)[,\s]+(-?[\d.]+)\s*L\s*(-?[\d.]+)[,\s]+(-?[\d.]+)/);
775
- if (!m) return null;
776
- const x1 = parseFloat(m[1]), y1 = parseFloat(m[2]);
777
- const x2 = parseFloat(m[3]), y2 = parseFloat(m[4]);
778
- const sw = parseFloat(el.attrs["stroke-width"] ?? "0.2") / 2;
779
- return { minX: Math.min(x1, x2) - sw, minY: Math.min(y1, y2) - sw, maxX: Math.max(x1, x2) + sw, maxY: Math.max(y1, y2) + sw };
780
- }
781
- case "line": {
782
- const x1 = parseFloat(el.attrs.x1 ?? "0"), y1 = parseFloat(el.attrs.y1 ?? "0");
783
- const x2 = parseFloat(el.attrs.x2 ?? "0"), y2 = parseFloat(el.attrs.y2 ?? "0");
784
- const sw = parseFloat(el.attrs["stroke-width"] ?? "0") / 2;
785
- return { minX: Math.min(x1, x2) - sw, minY: Math.min(y1, y2) - sw, maxX: Math.max(x1, x2) + sw, maxY: Math.max(y1, y2) + sw };
786
- }
787
- case "rect": {
788
- const x = parseFloat(el.attrs.x ?? "0"), y = parseFloat(el.attrs.y ?? "0");
789
- const w = parseFloat(el.attrs.width ?? "0"), h = parseFloat(el.attrs.height ?? "0");
790
- return { minX: x, minY: y, maxX: x + w, maxY: y + h };
791
- }
792
- case "circle": {
793
- const cx = parseFloat(el.attrs.cx ?? "0"), cy = parseFloat(el.attrs.cy ?? "0");
794
- const r = parseFloat(el.attrs.r ?? "0");
795
- return { minX: cx - r, minY: cy - r, maxX: cx + r, maxY: cy + r };
796
- }
797
- case "polygon": {
798
- const pts = (el.attrs.points ?? "").trim().split(/\s+/).map((p) => {
799
- const [x, y] = p.split(",").map(Number);
800
- return { x: x ?? 0, y: y ?? 0 };
801
- });
802
- if (pts.length === 0) return null;
803
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
804
- for (const p of pts) {
805
- minX = Math.min(minX, p.x);
806
- minY = Math.min(minY, p.y);
807
- maxX = Math.max(maxX, p.x);
808
- maxY = Math.max(maxY, p.y);
809
- }
810
- return { minX, minY, maxX, maxY };
811
- }
812
- default:
813
- return null;
814
- }
815
- }
816
- function renderElement(el, tableName) {
817
- const color = COLORS[tableName] ?? DEFAULT_COLOR;
818
- const isDashed = tableName === "room_separator";
819
- switch (el.tag) {
820
- case "path": {
821
- const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
822
- const sw = el.attrs["stroke-width"] ?? "0.2";
823
- const dash = isDashed ? ' stroke-dasharray="0.2,0.1"' : "";
824
- return ` <path ${attrs} stroke="${color.stroke}" stroke-width="${sw}" stroke-linecap="square"${dash} />`;
825
- }
826
- case "line": {
827
- const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
828
- const sw = el.attrs["stroke-width"] ?? "0.2";
829
- const dash = isDashed ? ' stroke-dasharray="0.2,0.1"' : "";
830
- return ` <line ${attrs} stroke="${color.stroke}" stroke-width="${sw}" stroke-linecap="square"${dash} />`;
831
- }
832
- case "polygon": {
833
- const fill = color.fill ?? "none";
834
- const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
835
- return ` <polygon ${attrs} fill="${fill}" stroke="${color.stroke}" stroke-width="0.05" />`;
836
- }
837
- case "rect": {
838
- const fill = color.fill ?? "none";
839
- const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
840
- return ` <rect ${attrs} fill="${fill}" stroke="${color.stroke}" stroke-width="0.05" />`;
841
- }
842
- case "circle": {
843
- const fill = color.fill ?? "none";
844
- const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
845
- return ` <circle ${attrs} fill="${fill}" stroke="${color.stroke}" stroke-width="0.05" />`;
846
- }
847
- default:
848
- return "";
849
- }
850
- }
851
- function escapeXml(s) {
852
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
853
- }
854
- function renderHostedElements(levelDir, tableName, wallElements) {
855
- const csvPath = join13(levelDir.path, `${tableName}.csv`);
856
- if (!existsSync12(csvPath)) return [];
857
- const csv = readCsv(csvPath);
858
- const color = COLORS[tableName] ?? DEFAULT_COLOR;
859
- const results = [];
860
- for (const row of csv.rows) {
861
- const hostId = row.host_id;
862
- const position = parseFloat(row.position ?? "");
863
- const width = parseFloat(row.width ?? "0");
864
- if (!hostId || isNaN(position)) continue;
865
- const wall = wallElements.get(hostId);
866
- if (!wall) continue;
867
- let wx1, wy1, wx2, wy2;
868
- if (wall.tag === "path") {
869
- const d = wall.attrs.d ?? "";
870
- const m = d.match(/M\s*(-?[\d.]+)[,\s]+(-?[\d.]+)\s*L\s*(-?[\d.]+)[,\s]+(-?[\d.]+)/);
871
- if (!m) continue;
872
- wx1 = parseFloat(m[1]);
873
- wy1 = parseFloat(m[2]);
874
- wx2 = parseFloat(m[3]);
875
- wy2 = parseFloat(m[4]);
876
- } else {
877
- wx1 = parseFloat(wall.attrs.x1 ?? "0");
878
- wy1 = parseFloat(wall.attrs.y1 ?? "0");
879
- wx2 = parseFloat(wall.attrs.x2 ?? "0");
880
- wy2 = parseFloat(wall.attrs.y2 ?? "0");
881
- }
882
- const dx = wx2 - wx1;
883
- const dy = wy2 - wy1;
884
- const len = Math.sqrt(dx * dx + dy * dy);
885
- if (len === 0) continue;
886
- const ux = dx / len;
887
- const uy = dy / len;
888
- const cx = wx1 + ux * position;
889
- const cy = wy1 + uy * position;
890
- const halfW = width / 2;
891
- const x1 = cx - ux * halfW;
892
- const y1 = cy - uy * halfW;
893
- const x2 = cx + ux * halfW;
894
- const y2 = cy + uy * halfW;
895
- const sw = tableName === "door" ? "0.22" : "0.18";
896
- const markup = ` <line id="${row.id}" x1="${x1.toFixed(3)}" y1="${y1.toFixed(3)}" x2="${x2.toFixed(3)}" y2="${y2.toFixed(3)}" stroke="${color.stroke}" stroke-width="${sw}" />`;
897
- results.push({
898
- tableName,
899
- svgMarkup: markup,
900
- bounds: {
901
- minX: Math.min(x1, x2),
902
- minY: Math.min(y1, y2),
903
- maxX: Math.max(x1, x2),
904
- maxY: Math.max(y1, y2)
905
- }
906
- });
907
- }
908
- return results;
909
- }
910
- function renderSpaces(levelDir) {
911
- const csvPath = join13(levelDir.path, "space.csv");
912
- if (!existsSync12(csvPath)) return [];
913
- const csv = readCsv(csvPath);
914
- const color = COLORS.space ?? DEFAULT_COLOR;
915
- const results = [];
916
- const nameMap = /* @__PURE__ */ new Map();
917
- for (const row of csv.rows) {
918
- nameMap.set(row.id, row.name ?? row.id ?? "");
919
- }
920
- const svgPath = join13(levelDir.path, "space.svg");
921
- if (existsSync12(svgPath)) {
922
- try {
923
- const svg = parseSvgFile(svgPath);
924
- for (const el of svg.elements) {
925
- if (el.tag !== "polygon") continue;
926
- const points = (el.attrs.points ?? "").trim().split(/\s+/).map((p) => {
927
- const [x, y] = p.split(",").map(Number);
928
- return { x: x ?? 0, y: y ?? 0 };
929
- });
930
- if (points.length < 3) continue;
931
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
932
- let cx = 0, cy = 0;
933
- for (const p of points) {
934
- minX = Math.min(minX, p.x);
935
- minY = Math.min(minY, p.y);
936
- maxX = Math.max(maxX, p.x);
937
- maxY = Math.max(maxY, p.y);
938
- cx += p.x;
939
- cy += p.y;
940
- }
941
- cx /= points.length;
942
- cy /= points.length;
943
- const name = nameMap.get(el.id) ?? el.id;
944
- let markup = ` <polygon id="${el.id}" points="${el.attrs.points}" fill="${color.fill ?? "none"}" stroke="${color.stroke}" stroke-width="0.03" />`;
945
- markup += `
946
- <text x="${cx.toFixed(3)}" y="${cy.toFixed(3)}" font-size="0.4" fill="${color.stroke}" text-anchor="middle" dominant-baseline="central" transform="scale(1,-1) translate(0,${(-2 * cy).toFixed(3)})">${escapeXml(name)}</text>`;
947
- results.push({
948
- tableName: "space",
949
- svgMarkup: markup,
950
- bounds: { minX, minY, maxX, maxY }
951
- });
952
- }
953
- if (results.length > 0) return results;
954
- } catch {
955
- }
956
- }
957
- for (const row of csv.rows) {
958
- const x = parseFloat(row.x ?? "");
959
- const y = parseFloat(row.y ?? "");
960
- if (isNaN(x) || isNaN(y)) continue;
961
- const name = row.name ?? row.id ?? "";
962
- const r = 0.15;
963
- let markup = ` <circle id="${row.id}" cx="${x.toFixed(3)}" cy="${y.toFixed(3)}" r="${r}" fill="${color.fill ?? "none"}" stroke="${color.stroke}" stroke-width="0.03" />`;
964
- markup += `
965
- <text x="${x.toFixed(3)}" y="${y.toFixed(3)}" font-size="0.4" fill="${color.stroke}" text-anchor="middle" dominant-baseline="central" transform="scale(1,-1) translate(0,${(-2 * y).toFixed(3)})">${escapeXml(name)}</text>`;
966
- results.push({
967
- tableName: "space",
968
- svgMarkup: markup,
969
- bounds: { minX: x - 1, minY: y - 1, maxX: x + 1, maxY: y + 1 }
970
- });
971
- }
972
- return results;
973
- }
974
- function renderLevel(projectDir, levelId) {
975
- const layout = discoverLayout(projectDir);
976
- const levelDir = layout.levelDirs.find((d) => d.name === levelId);
977
- if (!levelDir) {
978
- throw new Error(`Level "${levelId}" not found. Available: ${layout.levelDirs.map((d) => d.name).join(", ")}`);
979
- }
980
- const allElements = [];
981
- const csvOnlyElements = [];
982
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
983
- const wallElements = /* @__PURE__ */ new Map();
984
- const renderSources = [
985
- { path: layout.globalDir },
986
- { path: levelDir.path }
987
- ];
988
- for (const tableName of RENDER_ORDER) {
989
- if (CSV_ONLY_TABLES.has(tableName)) continue;
990
- const svgName = SVG_FILE_NAMES[tableName];
991
- if (!svgName) continue;
992
- for (const src of renderSources) {
993
- const svgPath = join13(src.path, svgName + ".svg");
994
- if (!existsSync12(svgPath)) continue;
995
- const svg = parseSvgFile(svgPath);
996
- for (const el of svg.elements) {
997
- allElements.push({ tableName, el });
998
- if (tableName === "wall") wallElements.set(el.id, el);
999
- const b = elementBounds2(el);
1000
- if (b) {
1001
- minX = Math.min(minX, b.minX);
1002
- minY = Math.min(minY, b.minY);
1003
- maxX = Math.max(maxX, b.maxX);
1004
- maxY = Math.max(maxY, b.maxY);
1005
- }
1006
- }
1007
- }
1008
- }
1009
- for (const tableName of ["door", "window"]) {
1010
- csvOnlyElements.push(...renderHostedElements(levelDir, tableName, wallElements));
1011
- }
1012
- csvOnlyElements.push(...renderSpaces(levelDir));
1013
- for (const el of csvOnlyElements) {
1014
- minX = Math.min(minX, el.bounds.minX);
1015
- minY = Math.min(minY, el.bounds.minY);
1016
- maxX = Math.max(maxX, el.bounds.maxX);
1017
- maxY = Math.max(maxY, el.bounds.maxY);
1018
- }
1019
- if (allElements.length === 0 && csvOnlyElements.length === 0) {
1020
- return '<?xml version="1.0" encoding="utf-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">\n <text x="5" y="5" text-anchor="middle" font-size="1">No geometry found</text>\n</svg>';
1021
- }
1022
- const pad = Math.max(maxX - minX, maxY - minY) * 0.05;
1023
- const vbX = minX - pad;
1024
- const vbY = -(maxY + pad);
1025
- const vbW = maxX - minX + 2 * pad;
1026
- const vbH = maxY - minY + 2 * pad;
1027
- const parts = [
1028
- '<?xml version="1.0" encoding="utf-8"?>',
1029
- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vbX.toFixed(3)} ${vbY.toFixed(3)} ${vbW.toFixed(3)} ${vbH.toFixed(3)}">`,
1030
- ` <rect x="${vbX.toFixed(3)}" y="${vbY.toFixed(3)}" width="${vbW.toFixed(3)}" height="${vbH.toFixed(3)}" fill="white" />`,
1031
- ' <g transform="scale(1,-1)">'
1032
- ];
1033
- for (const { tableName, el } of allElements) {
1034
- const line = renderElement(el, tableName);
1035
- if (line) parts.push(line);
1036
- }
1037
- for (const el of csvOnlyElements) {
1038
- parts.push(el.svgMarkup);
1039
- }
1040
- parts.push(" </g>");
1041
- parts.push("</svg>");
1042
- return parts.join("\n");
1043
- }
1044
- var COLORS, DEFAULT_COLOR, OVERRIDE_ATTRS, RENDER_ORDER, CSV_ONLY_TABLES;
1045
- var init_render = __esm({
1046
- "src/render.ts"() {
1047
- "use strict";
1048
- init_fs();
1049
- init_csv();
1050
- init_svg();
1051
- init_registry();
1052
- COLORS = {
1053
- wall: { stroke: "#1a1a2e" },
1054
- structure_wall: { stroke: "#4a4e69" },
1055
- column: { stroke: "#2b2d42", fill: "#2b2d42" },
1056
- structure_column: { stroke: "#6c757d", fill: "#6c757d" },
1057
- slab: { stroke: "#adb5bd", fill: "rgba(173,181,189,0.2)" },
1058
- structure_slab: { stroke: "#868e96", fill: "rgba(134,142,150,0.2)" },
1059
- space: { stroke: "#3a86ff", fill: "rgba(58,134,255,0.15)" },
1060
- room_separator: { stroke: "#adb5bd" },
1061
- door: { stroke: "#e63946" },
1062
- window: { stroke: "#2a9d8f" },
1063
- stair: { stroke: "#f4a261", fill: "rgba(244,162,97,0.2)" },
1064
- beam: { stroke: "#9b5de5" },
1065
- duct: { stroke: "#00b4d8" },
1066
- pipe: { stroke: "#48bfe3" },
1067
- cable_tray: { stroke: "#90be6d" },
1068
- conduit: { stroke: "#43aa8b" },
1069
- equipment: { stroke: "#f94144", fill: "rgba(249,65,68,0.15)" },
1070
- terminal: { stroke: "#f3722c", fill: "rgba(243,114,44,0.15)" }
1071
- };
1072
- DEFAULT_COLOR = { stroke: "#666" };
1073
- OVERRIDE_ATTRS = /* @__PURE__ */ new Set(["stroke", "fill", "stroke-width", "stroke-linecap"]);
1074
- RENDER_ORDER = [
1075
- "slab",
1076
- "structure_slab",
1077
- "wall",
1078
- "structure_wall",
1079
- "room_separator",
1080
- "column",
1081
- "structure_column",
1082
- "beam",
1083
- "brace",
1084
- "stair",
1085
- "duct",
1086
- "pipe",
1087
- "cable_tray",
1088
- "conduit",
1089
- "equipment",
1090
- "terminal",
1091
- "door",
1092
- "window",
1093
- "space"
1094
- ];
1095
- CSV_ONLY_TABLES = /* @__PURE__ */ new Set(["door", "window", "space"]);
1096
- }
1097
- });
1098
-
1099
- // src/commands/resolve-topology.ts
1100
- var resolve_topology_exports = {};
1101
- __export(resolve_topology_exports, {
1102
- resolveTopology: () => resolveTopology
1103
- });
1104
- import { existsSync as existsSync13, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
1105
- import { join as join14 } from "path";
1106
- function dist3d(a, b) {
1107
- const dx = a.x - b.x;
1108
- const dy = a.y - b.y;
1109
- const dz = a.z - b.z;
1110
- return Math.sqrt(dx * dx + dy * dy + dz * dz);
1111
- }
1112
- function insideBBox(point, node) {
1113
- const dz = Math.abs(point.z - node.pos.z);
1114
- if (dz > TOLERANCE4) return false;
1115
- const dx = Math.abs(point.x - node.pos.x);
1116
- const dy = Math.abs(point.y - node.pos.y);
1117
- return dx <= node.halfW + TOLERANCE4 && dy <= node.halfH + TOLERANCE4;
1118
- }
1119
- function resolveTopology(dir) {
1120
- buildRegistry(getSpecDir());
1121
- const layout = discoverLayout(dir);
1122
- const allDirs = [
1123
- { name: "global", path: layout.globalDir },
1124
- ...layout.levelDirs
1125
- ];
1126
- const freeEndpoints = [];
1127
- const curveData = /* @__PURE__ */ new Map();
1128
- let totalCurves = 0;
1129
- let skippedStart = 0;
1130
- let skippedEnd = 0;
1131
- for (const d of allDirs) {
1132
- if (!existsSync13(d.path)) continue;
1133
- const files = listFiles(d.path);
1134
- for (const tableName of CURVE_TABLES) {
1135
- if (!files.includes(`${tableName}.csv`)) continue;
1136
- const svgName = SVG_FILE_NAMES[tableName];
1137
- if (!svgName || !files.includes(`${svgName}.svg`)) continue;
1138
- const csvPath = join14(d.path, `${tableName}.csv`);
1139
- const svgPath = join14(d.path, `${svgName}.svg`);
1140
- const csv = readCsv(csvPath);
1141
- const key = `${d.name}/${tableName}`;
1142
- curveData.set(key, { csv, path: csvPath });
1143
- let svgElements;
1144
- try {
1145
- svgElements = parseSvgFile(svgPath).elements;
1146
- } catch {
1147
- continue;
1148
- }
1149
- const geoMap = /* @__PURE__ */ new Map();
1150
- for (const el of svgElements) {
1151
- if (el.tag === "path") {
1152
- const geo = extractLineGeometry(el);
1153
- geoMap.set(el.id, geo);
1154
- }
1155
- }
1156
- for (const row of csv.rows) {
1157
- const geo = geoMap.get(row.id);
1158
- if (!geo) continue;
1159
- totalCurves++;
1160
- const startZ = parseFloat(row.start_z ?? "0");
1161
- const endZ = parseFloat(row.end_z ?? "0");
1162
- if (row.start_node_id) {
1163
- skippedStart++;
1164
- } else {
1165
- freeEndpoints.push({
1166
- curveId: row.id,
1167
- side: "start",
1168
- point: { x: geo.start_x, y: geo.start_y, z: startZ },
1169
- levelDir: d.name,
1170
- systemType: row.system_type ?? ""
1171
- });
1172
- }
1173
- if (row.end_node_id) {
1174
- skippedEnd++;
1175
- } else {
1176
- freeEndpoints.push({
1177
- curveId: row.id,
1178
- side: "end",
1179
- point: { x: geo.end_x, y: geo.end_y, z: endZ },
1180
- levelDir: d.name,
1181
- systemType: row.system_type ?? ""
1182
- });
1183
- }
1184
- }
1185
- }
1186
- }
1187
- const nodes = [];
1188
- for (const d of allDirs) {
1189
- if (!existsSync13(d.path)) continue;
1190
- const files = listFiles(d.path);
1191
- for (const tableName of NODE_TABLES) {
1192
- if (!files.includes(`${tableName}.csv`)) continue;
1193
- const svgName = SVG_FILE_NAMES[tableName];
1194
- if (!svgName || !files.includes(`${svgName}.svg`)) continue;
1195
- const csvPath = join14(d.path, `${tableName}.csv`);
1196
- const svgPath = join14(d.path, `${svgName}.svg`);
1197
- const csv = readCsv(csvPath);
1198
- let svgElements;
1199
- try {
1200
- svgElements = parseSvgFile(svgPath).elements;
1201
- } catch {
1202
- continue;
1203
- }
1204
- const posMap = /* @__PURE__ */ new Map();
1205
- for (const el of svgElements) {
1206
- if (el.tag === "rect") {
1207
- const geo = extractRectGeometry(el);
1208
- posMap.set(el.id, { x: geo.x, y: geo.y, halfW: geo.size_x / 2, halfH: geo.size_y / 2 });
1209
- } else if (el.tag === "circle") {
1210
- const geo = extractCircleGeometry(el);
1211
- const r = geo.size_x / 2;
1212
- posMap.set(el.id, { x: geo.x, y: geo.y, halfW: r, halfH: r });
1213
- }
1214
- }
1215
- for (const row of csv.rows) {
1216
- const p = posMap.get(row.id);
1217
- if (!p) continue;
1218
- const z = parseFloat(row.base_offset ?? "0");
1219
- nodes.push({
1220
- levelDir: d.name,
1221
- tableName,
1222
- id: row.id,
1223
- pos: { x: p.x, y: p.y, z },
1224
- halfW: p.halfW,
1225
- halfH: p.halfH
1226
- });
1227
- }
1228
- }
1229
- }
1230
- const resolvedIds = /* @__PURE__ */ new Map();
1231
- const stillFree = [];
1232
- for (const ep of freeEndpoints) {
1233
- let matched = null;
1234
- for (const node of nodes) {
1235
- if (insideBBox(ep.point, node)) {
1236
- matched = node;
1237
- break;
1238
- }
1239
- }
1240
- if (matched) {
1241
- resolvedIds.set(`${ep.curveId}:${ep.side}`, matched.id);
1242
- } else {
1243
- stillFree.push(ep);
1244
- }
1245
- }
1246
- const fittingMatches = resolvedIds.size;
1247
- const junctions = [];
1248
- for (const ep of stillFree) {
1249
- let found = false;
1250
- for (const j of junctions) {
1251
- if (dist3d(ep.point, j.point) < TOLERANCE4) {
1252
- j.endpoints.push(ep);
1253
- found = true;
1254
- break;
1255
- }
1256
- }
1257
- if (!found) {
1258
- junctions.push({
1259
- point: ep.point,
1260
- endpoints: [ep],
1261
- levelDir: ep.levelDir,
1262
- systemType: ep.systemType,
1263
- nodeId: ""
1264
- });
1265
- }
1266
- }
1267
- const maxMnId = /* @__PURE__ */ new Map();
1268
- for (const n of nodes) {
1269
- if (n.tableName === "mep_node") {
1270
- const num = parseInt(n.id.replace("mn-", ""), 10);
1271
- const current = maxMnId.get(n.levelDir) ?? 0;
1272
- if (num > current) maxMnId.set(n.levelDir, num);
1273
- }
1274
- }
1275
- for (const j of junctions) {
1276
- const current = maxMnId.get(j.levelDir) ?? 0;
1277
- const nextId = current + 1;
1278
- maxMnId.set(j.levelDir, nextId);
1279
- j.nodeId = `mn-${nextId}`;
1280
- for (const ep of j.endpoints) {
1281
- resolvedIds.set(`${ep.curveId}:${ep.side}`, j.nodeId);
1282
- }
1283
- }
1284
- const newNodesByLevel = /* @__PURE__ */ new Map();
1285
- for (const j of junctions) {
1286
- const arr = newNodesByLevel.get(j.levelDir) ?? [];
1287
- arr.push(j);
1288
- newNodesByLevel.set(j.levelDir, arr);
1289
- }
1290
- for (const [levelDir, levelJunctions] of newNodesByLevel) {
1291
- const dirPath = levelDir === "global" ? layout.globalDir : join14(dir, levelDir);
1292
- if (!existsSync13(dirPath)) mkdirSync2(dirPath, { recursive: true });
1293
- const csvPath = join14(dirPath, "mep_node.csv");
1294
- const svgPath = join14(dirPath, "mep_node.svg");
1295
- let csv;
1296
- if (existsSync13(csvPath)) {
1297
- csv = readCsv(csvPath);
1298
- } else {
1299
- csv = { headers: ["id", "number", "base_offset", "system_type"], rows: [] };
1300
- }
1301
- for (const h of ["id", "number", "base_offset", "system_type"]) {
1302
- if (!csv.headers.includes(h)) csv.headers.push(h);
1303
- }
1304
- let existingSvgElements = [];
1305
- if (existsSync13(svgPath)) {
1306
- try {
1307
- existingSvgElements = parseSvgFile(svgPath).elements;
1308
- } catch {
1309
- }
1310
- }
1311
- const newSvgLines = [];
1312
- const NODE_RADIUS = 0.025;
1313
- for (const j of levelJunctions) {
1314
- csv.rows.push({
1315
- id: j.nodeId,
1316
- number: "",
1317
- base_offset: String(j.point.z),
1318
- system_type: j.systemType
1319
- });
1320
- newSvgLines.push(
1321
- ` <circle id="${j.nodeId}" cx="${j.point.x.toFixed(3)}" cy="${j.point.y.toFixed(3)}" r="${NODE_RADIUS}" />`
1322
- );
1323
- }
1324
- writeCsv(csvPath, csv);
1325
- const existingLines = [];
1326
- for (const el of existingSvgElements) {
1327
- const attrs = Object.entries(el.attrs).map(([k, v]) => `${k}="${v}"`).join(" ");
1328
- existingLines.push(` <${el.tag} ${attrs} />`);
1329
- }
1330
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1331
- for (const el of existingSvgElements) {
1332
- if (el.tag === "rect") {
1333
- const g = extractRectGeometry(el);
1334
- minX = Math.min(minX, g.x - g.size_x / 2);
1335
- minY = Math.min(minY, g.y - g.size_y / 2);
1336
- maxX = Math.max(maxX, g.x + g.size_x / 2);
1337
- maxY = Math.max(maxY, g.y + g.size_y / 2);
1338
- } else if (el.tag === "circle") {
1339
- const g = extractCircleGeometry(el);
1340
- const r = g.size_x / 2;
1341
- minX = Math.min(minX, g.x - r);
1342
- minY = Math.min(minY, g.y - r);
1343
- maxX = Math.max(maxX, g.x + r);
1344
- maxY = Math.max(maxY, g.y + r);
1345
- }
1346
- }
1347
- for (const j of levelJunctions) {
1348
- minX = Math.min(minX, j.point.x - NODE_RADIUS);
1349
- minY = Math.min(minY, j.point.y - NODE_RADIUS);
1350
- maxX = Math.max(maxX, j.point.x + NODE_RADIUS);
1351
- maxY = Math.max(maxY, j.point.y + NODE_RADIUS);
1352
- }
1353
- let viewBox = "0 0 1 1";
1354
- if (minX !== Infinity) {
1355
- const pad = Math.max(maxX - minX, maxY - minY) * 0.02;
1356
- viewBox = `${(minX - pad).toFixed(3)} ${(-(maxY + pad)).toFixed(3)} ${(maxX - minX + pad * 2).toFixed(3)} ${(maxY - minY + pad * 2).toFixed(3)}`;
1357
- }
1358
- writeFileSync4(svgPath, [
1359
- '<?xml version="1.0" encoding="utf-8"?>',
1360
- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`,
1361
- ' <g transform="scale(1,-1)">',
1362
- ...existingLines,
1363
- ...newSvgLines,
1364
- " </g>",
1365
- "</svg>"
1366
- ].join("\n"), "utf-8");
1367
- }
1368
- let updatedRows = 0;
1369
- for (const [, entry] of curveData) {
1370
- let modified = false;
1371
- const csv = entry.csv;
1372
- if (!csv.headers.includes("start_node_id")) csv.headers.push("start_node_id");
1373
- if (!csv.headers.includes("end_node_id")) csv.headers.push("end_node_id");
1374
- for (const row of csv.rows) {
1375
- if (!row.start_node_id) {
1376
- const id = resolvedIds.get(`${row.id}:start`);
1377
- if (id) {
1378
- row.start_node_id = id;
1379
- modified = true;
1380
- updatedRows++;
1381
- }
1382
- }
1383
- if (!row.end_node_id) {
1384
- const id = resolvedIds.get(`${row.id}:end`);
1385
- if (id) {
1386
- row.end_node_id = id;
1387
- modified = true;
1388
- }
1389
- }
1390
- }
1391
- if (modified) {
1392
- writeCsv(entry.path, csv);
1393
- }
1394
- }
1395
- const totalEndpoints = totalCurves * 2;
1396
- const alreadyResolved = skippedStart + skippedEnd;
1397
- console.log(`Scanned ${totalCurves} MEP curves (${totalEndpoints} endpoints)`);
1398
- console.log(` Already connected: ${alreadyResolved} (from Revit export)`);
1399
- console.log(` Free endpoints: ${freeEndpoints.length}`);
1400
- console.log(` Matched to existing fittings (bbox): ${fittingMatches}`);
1401
- console.log(` New mep_nodes created: ${junctions.length}`);
1402
- console.log(` Unresolved: ${stillFree.length - junctions.reduce((s, j) => s + j.endpoints.length, 0)}`);
1403
- if (updatedRows > 0) {
1404
- console.log(`Updated ${updatedRows} curve rows`);
1405
- }
1406
- }
1407
- var TOLERANCE4, CURVE_TABLES, NODE_TABLES;
1408
- var init_resolve_topology = __esm({
1409
- "src/commands/resolve-topology.ts"() {
1410
- "use strict";
1411
- init_csv();
1412
- init_svg();
1413
- init_fs();
1414
- init_registry();
1415
- TOLERANCE4 = 0.01;
1416
- CURVE_TABLES = ["duct", "pipe", "cable_tray", "conduit"];
1417
- NODE_TABLES = ["equipment", "terminal", "mep_node"];
1418
- }
1419
- });
1420
-
1421
- // src/commands/merge.ts
1422
- var merge_exports = {};
1423
- __export(merge_exports, {
1424
- merge: () => merge
1425
- });
1426
- import { existsSync as existsSync14, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
1427
- import { join as join15, basename as basename2 } from "path";
1428
- async function merge(dirs, outputDir) {
1429
- const registry = buildRegistry(getSpecDir());
1430
- console.log(`Scanning ${dirs.length} sources...`);
1431
- const sources = dirs.map((dir) => scanSource(dir, registry));
1432
- const { canonicalLevels, levelRemaps } = deduplicateLevels(sources);
1433
- console.log(`Merged levels: ${canonicalLevels.rows.length} unique levels`);
1434
- const { canonicalGrids, gridRemaps } = deduplicateGrids(sources);
1435
- console.log(`Merged grids: ${canonicalGrids.rows.length} unique grids`);
1436
- const fullRemaps = buildFullRemaps(sources, levelRemaps, gridRemaps, registry);
1437
- mkdirSync3(join15(outputDir, "global"), { recursive: true });
1438
- writeCsv(join15(outputDir, "global", "level.csv"), canonicalLevels);
1439
- if (canonicalGrids.rows.length > 0) {
1440
- writeCsv(join15(outputDir, "global", "grid.csv"), canonicalGrids);
1441
- }
1442
- writeIdMap(outputDir, sources, fullRemaps);
1443
- const levelDirMap = buildLevelDirMap(sources, fullRemaps);
1444
- writeGlobalTables(outputDir, sources, fullRemaps, registry);
1445
- writeLevelTables(outputDir, sources, fullRemaps, levelDirMap, registry);
1446
- console.log(`Merge complete \u2192 ${outputDir}`);
1447
- }
1448
- function scanSource(dir, registry) {
1449
- const layout = discoverLayout(dir);
1450
- const name = basename2(dir);
1451
- const levelPath = join15(layout.globalDir, "level.csv");
1452
- if (!existsSync14(levelPath)) {
1453
- throw new Error(`Missing level.csv in ${dir}/global/`);
1454
- }
1455
- const levels = readCsv(levelPath);
1456
- const gridPath = join15(layout.globalDir, "grid.csv");
1457
- const grids = existsSync14(gridPath) ? readCsv(gridPath) : null;
1458
- const idMapPath = join15(layout.globalDir, "_IdMap.csv");
1459
- const idMap = existsSync14(idMapPath) ? readCsv(idMapPath) : null;
1460
- const globalData = /* @__PURE__ */ new Map();
1461
- if (existsSync14(layout.globalDir)) {
1462
- for (const f of listFiles(layout.globalDir)) {
1463
- if (!f.endsWith(".csv")) continue;
1464
- const tableName = f.replace(".csv", "");
1465
- if (tableName === "level" || tableName === "grid" || tableName === "_IdMap") continue;
1466
- if (!registry.has(tableName)) continue;
1467
- const csv = readCsv(join15(layout.globalDir, f));
1468
- const svgName = SVG_FILE_NAMES[tableName];
1469
- const svgFile = svgName ? join15(layout.globalDir, svgName + ".svg") : null;
1470
- globalData.set(tableName, { csv, svgFile: svgFile && existsSync14(svgFile) ? svgFile : null });
1471
- }
1472
- }
1473
- const levelData = /* @__PURE__ */ new Map();
1474
- for (const ld of layout.levelDirs) {
1475
- const tables = /* @__PURE__ */ new Map();
1476
- for (const f of listFiles(ld.path)) {
1477
- if (!f.endsWith(".csv")) continue;
1478
- const tableName = f.replace(".csv", "");
1479
- if (!registry.has(tableName)) continue;
1480
- const csv = readCsv(join15(ld.path, f));
1481
- const svgName = SVG_FILE_NAMES[tableName];
1482
- const svgFile = svgName ? join15(ld.path, svgName + ".svg") : null;
1483
- tables.set(tableName, { csv, svgFile: svgFile && existsSync14(svgFile) ? svgFile : null });
1484
- }
1485
- if (tables.size > 0) {
1486
- levelData.set(ld.name, tables);
1487
- }
1488
- }
1489
- return { name, layout, levels, grids, idMap, levelData, globalData };
1490
- }
1491
- function deduplicateLevels(sources) {
1492
- const allLevels = [];
1493
- for (let si = 0; si < sources.length; si++) {
1494
- for (const row of sources[si].levels.rows) {
1495
- allLevels.push({
1496
- sourceIdx: si,
1497
- id: row.id,
1498
- name: row.name ?? "",
1499
- number: row.number ?? "",
1500
- elevation: parseFloat(row.elevation ?? "0")
1501
- });
1502
- }
1503
- }
1504
- allLevels.sort((a, b) => a.elevation - b.elevation);
1505
- const groups = [];
1506
- for (const lv of allLevels) {
1507
- const last = groups[groups.length - 1];
1508
- if (last && Math.abs(last[0].elevation - lv.elevation) <= ELEVATION_TOLERANCE) {
1509
- last.push(lv);
1510
- } else {
1511
- groups.push([lv]);
1512
- }
1513
- }
1514
- const canonicalRows = [];
1515
- const remaps = sources.map(() => /* @__PURE__ */ new Map());
1516
- for (let gi = 0; gi < groups.length; gi++) {
1517
- const canonId = `lv-${gi + 1}`;
1518
- const rep = groups[gi][0];
1519
- canonicalRows.push({
1520
- id: canonId,
1521
- number: rep.number,
1522
- name: rep.name,
1523
- elevation: String(rep.elevation)
1524
- });
1525
- for (const entry of groups[gi]) {
1526
- remaps[entry.sourceIdx].set(entry.id, canonId);
1527
- }
1528
- }
1529
- return {
1530
- canonicalLevels: { headers: ["id", "number", "name", "elevation"], rows: canonicalRows },
1531
- levelRemaps: remaps
1532
- };
1533
- }
1534
- function deduplicateGrids(sources) {
1535
- const allGrids = [];
1536
- for (let si = 0; si < sources.length; si++) {
1537
- if (!sources[si].grids) continue;
1538
- for (const row of sources[si].grids.rows) {
1539
- allGrids.push({
1540
- sourceIdx: si,
1541
- id: row.id,
1542
- number: row.number ?? "",
1543
- start_x: parseFloat(row.start_x ?? "0"),
1544
- start_y: parseFloat(row.start_y ?? "0"),
1545
- end_x: parseFloat(row.end_x ?? "0"),
1546
- end_y: parseFloat(row.end_y ?? "0")
1547
- });
1548
- }
1549
- }
1550
- const remaps = sources.map(() => /* @__PURE__ */ new Map());
1551
- if (allGrids.length === 0) {
1552
- return { canonicalGrids: { headers: ["id", "number", "start_x", "start_y", "end_x", "end_y"], rows: [] }, gridRemaps: remaps };
1553
- }
1554
- const matched = [];
1555
- for (const g of allGrids) {
1556
- let found = false;
1557
- for (const group of matched) {
1558
- const rep = group[0];
1559
- if (Math.abs(rep.start_x - g.start_x) <= GRID_COORD_TOLERANCE && Math.abs(rep.start_y - g.start_y) <= GRID_COORD_TOLERANCE && Math.abs(rep.end_x - g.end_x) <= GRID_COORD_TOLERANCE && Math.abs(rep.end_y - g.end_y) <= GRID_COORD_TOLERANCE) {
1560
- group.push(g);
1561
- found = true;
1562
- break;
1563
- }
1564
- }
1565
- if (!found) {
1566
- matched.push([g]);
1567
- }
1568
- }
1569
- const canonicalRows = [];
1570
- for (let gi = 0; gi < matched.length; gi++) {
1571
- const canonId = `gr-${gi + 1}`;
1572
- const rep = matched[gi][0];
1573
- canonicalRows.push({
1574
- id: canonId,
1575
- number: rep.number,
1576
- start_x: String(rep.start_x),
1577
- start_y: String(rep.start_y),
1578
- end_x: String(rep.end_x),
1579
- end_y: String(rep.end_y)
1580
- });
1581
- for (const entry of matched[gi]) {
1582
- remaps[entry.sourceIdx].set(entry.id, canonId);
1583
- }
1584
- }
1585
- return {
1586
- canonicalGrids: { headers: ["id", "number", "start_x", "start_y", "end_x", "end_y"], rows: canonicalRows },
1587
- gridRemaps: remaps
1588
- };
1589
- }
1590
- function buildFullRemaps(sources, levelRemaps, gridRemaps, registry) {
1591
- const remaps = sources.map((_, i) => {
1592
- const m = /* @__PURE__ */ new Map();
1593
- for (const [old, nw] of levelRemaps[i]) m.set(old, nw);
1594
- for (const [old, nw] of gridRemaps[i]) m.set(old, nw);
1595
- return m;
1596
- });
1597
- const prefixCounters = /* @__PURE__ */ new Map();
1598
- const prefixGroups = /* @__PURE__ */ new Map();
1599
- for (let si = 0; si < sources.length; si++) {
1600
- const collectIds = (csv) => {
1601
- for (const row of csv.rows) {
1602
- if (!row.id) continue;
1603
- const dash = row.id.indexOf("-");
1604
- if (dash < 0) continue;
1605
- const prefix = row.id.substring(0, dash);
1606
- if (prefix === "lv" || prefix === "gr") continue;
1607
- let group = prefixGroups.get(prefix);
1608
- if (!group) {
1609
- group = [];
1610
- prefixGroups.set(prefix, group);
1611
- }
1612
- group.push({ sourceIdx: si, oldId: row.id });
1613
- }
1614
- };
1615
- for (const [, data] of sources[si].globalData) {
1616
- collectIds(data.csv);
1617
- }
1618
- for (const [, tables] of sources[si].levelData) {
1619
- for (const [, data] of tables) {
1620
- collectIds(data.csv);
1621
- }
1622
- }
1623
- }
1624
- for (const [prefix, group] of prefixGroups) {
1625
- let counter = 1;
1626
- for (const { sourceIdx, oldId } of group) {
1627
- const newId = `${prefix}-${counter}`;
1628
- remaps[sourceIdx].set(oldId, newId);
1629
- counter++;
1630
- }
1631
- }
1632
- return remaps;
1633
- }
1634
- function remapRow(row, remap, refFieldNames) {
1635
- const out = {};
1636
- for (const [key, val] of Object.entries(row)) {
1637
- if (val && (refFieldNames.has(key) || KNOWN_ID_FIELDS.has(key))) {
1638
- out[key] = remap.get(val) ?? val;
1639
- } else {
1640
- out[key] = val;
1641
- }
1642
- }
1643
- return out;
1644
- }
1645
- function getRefFieldNames(registry) {
1646
- const names = /* @__PURE__ */ new Set();
1647
- for (const [, table] of registry) {
1648
- for (const f of table.csvFields) {
1649
- if (f.type === "reference") names.add(f.name);
1650
- }
1651
- }
1652
- for (const f of KNOWN_ID_FIELDS) names.add(f);
1653
- return names;
1654
- }
1655
- function writeIdMap(outputDir, sources, remaps) {
1656
- const seenUuid = /* @__PURE__ */ new Map();
1657
- const rows = [];
1658
- for (let si = 0; si < sources.length; si++) {
1659
- if (!sources[si].idMap) continue;
1660
- for (const row of sources[si].idMap.rows) {
1661
- const oldId = row.id;
1662
- const uuid = row.uuid;
1663
- const newId = remaps[si].get(oldId) ?? oldId;
1664
- if (seenUuid.has(uuid)) continue;
1665
- seenUuid.set(uuid, newId);
1666
- rows.push({ id: newId, uuid });
1667
- }
1668
- }
1669
- if (rows.length > 0) {
1670
- writeCsv(join15(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
1671
- }
1672
- }
1673
- function buildLevelDirMap(sources, remaps) {
1674
- const result = /* @__PURE__ */ new Map();
1675
- for (let si = 0; si < sources.length; si++) {
1676
- const dirMap = /* @__PURE__ */ new Map();
1677
- const src = sources[si];
1678
- for (const ld of src.layout.levelDirs) {
1679
- const oldLevelId = ld.name;
1680
- const newLevelId = remaps[si].get(oldLevelId);
1681
- if (newLevelId) {
1682
- dirMap.set(ld.name, newLevelId);
1683
- } else {
1684
- dirMap.set(ld.name, ld.name);
1685
- }
1686
- }
1687
- result.set(String(si), dirMap);
1688
- }
1689
- return result;
1690
- }
1691
- function writeGlobalTables(outputDir, sources, remaps, registry) {
1692
- const refFields = getRefFieldNames(registry);
1693
- const merged = /* @__PURE__ */ new Map();
1694
- for (let si = 0; si < sources.length; si++) {
1695
- for (const [tableName, data] of sources[si].globalData) {
1696
- if (!merged.has(tableName)) {
1697
- merged.set(tableName, { rows: [], headers: data.csv.headers, svgInputs: [] });
1698
- }
1699
- const entry = merged.get(tableName);
1700
- for (const row of data.csv.rows) {
1701
- entry.rows.push(remapRow(row, remaps[si], refFields));
1702
- }
1703
- if (data.svgFile) {
1704
- const svg = parseSvgFile(data.svgFile);
1705
- entry.svgInputs.push({ elements: svg.elements, idRemap: remaps[si] });
1706
- }
1707
- }
1708
- }
1709
- for (const [tableName, entry] of merged) {
1710
- if (entry.rows.length > 0) {
1711
- writeCsv(join15(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1712
- }
1713
- if (entry.svgInputs.length > 0) {
1714
- const svgName = SVG_FILE_NAMES[tableName];
1715
- if (svgName) {
1716
- const content = writeMergedSvg(entry.svgInputs);
1717
- writeFileSync5(join15(outputDir, "global", svgName + ".svg"), content, "utf-8");
1718
- }
1719
- }
1720
- }
1721
- }
1722
- function writeLevelTables(outputDir, sources, remaps, levelDirMap, registry) {
1723
- const refFields = getRefFieldNames(registry);
1724
- const merged = /* @__PURE__ */ new Map();
1725
- for (let si = 0; si < sources.length; si++) {
1726
- const dirMap = levelDirMap.get(String(si));
1727
- for (const [srcDirName, tables] of sources[si].levelData) {
1728
- const outDirName = dirMap.get(srcDirName) ?? srcDirName;
1729
- if (!merged.has(outDirName)) {
1730
- merged.set(outDirName, /* @__PURE__ */ new Map());
1731
- }
1732
- const levelMerged = merged.get(outDirName);
1733
- for (const [tableName, data] of tables) {
1734
- if (!levelMerged.has(tableName)) {
1735
- levelMerged.set(tableName, { rows: [], headers: data.csv.headers, svgInputs: [] });
1736
- }
1737
- const entry = levelMerged.get(tableName);
1738
- for (const row of data.csv.rows) {
1739
- entry.rows.push(remapRow(row, remaps[si], refFields));
1740
- }
1741
- if (data.svgFile) {
1742
- const svg = parseSvgFile(data.svgFile);
1743
- entry.svgInputs.push({ elements: svg.elements, idRemap: remaps[si] });
1744
- }
1745
- }
1746
- }
1747
- }
1748
- for (const [outDirName, tables] of merged) {
1749
- const dirPath = join15(outputDir, outDirName);
1750
- mkdirSync3(dirPath, { recursive: true });
1751
- for (const [tableName, entry] of tables) {
1752
- if (entry.rows.length > 0) {
1753
- writeCsv(join15(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1754
- }
1755
- if (entry.svgInputs.length > 0) {
1756
- const svgName = SVG_FILE_NAMES[tableName];
1757
- if (svgName) {
1758
- const content = writeMergedSvg(entry.svgInputs);
1759
- writeFileSync5(join15(dirPath, svgName + ".svg"), content, "utf-8");
1760
- }
1761
- }
1762
- }
1763
- }
1764
- }
1765
- var ELEVATION_TOLERANCE, GRID_COORD_TOLERANCE, KNOWN_ID_FIELDS;
1766
- var init_merge = __esm({
1767
- "src/commands/merge.ts"() {
1768
- "use strict";
1769
- init_csv();
1770
- init_svg();
1771
- init_fs();
1772
- init_registry();
1773
- ELEVATION_TOLERANCE = 1e-3;
1774
- GRID_COORD_TOLERANCE = 0.01;
1775
- KNOWN_ID_FIELDS = /* @__PURE__ */ new Set([
1776
- "id",
1777
- "host_id",
1778
- "top_level_id",
1779
- "level_id",
1780
- "start_node_id",
1781
- "end_node_id"
1782
- ]);
1783
- }
1784
- });
1785
-
1786
- // src/commands/init.ts
1787
- var init_exports = {};
1788
- __export(init_exports, {
1789
- initProject: () => initProject
1790
- });
1791
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync6, existsSync as existsSync15 } from "fs";
1792
- import { join as join16 } from "path";
1793
- function initProject(absDir) {
1794
- if (!existsSync15(absDir)) {
1795
- mkdirSync4(absDir, { recursive: true });
1796
- }
1797
- writeFileSync6(join16(absDir, ".bimdown"), "", "utf-8");
1798
- const globalDir = join16(absDir, "global");
1799
- if (!existsSync15(globalDir)) {
1800
- mkdirSync4(globalDir, { recursive: true });
1801
- }
1802
- const levelCsvPath = join16(globalDir, "level.csv");
1803
- if (!existsSync15(levelCsvPath)) {
1804
- writeFileSync6(levelCsvPath, "id,name,elevation\nlv-1,Level 1,0.0\n", "utf-8");
1805
- }
1806
- const gridCsvPath = join16(globalDir, "grid.csv");
1807
- if (!existsSync15(gridCsvPath)) {
1808
- const gridContent = [
1809
- "id,name,role,start_x,start_y,end_x,end_y",
1810
- "gr-1,A,primary,-10000,0,10000,0",
1811
- "gr-2,1,primary,0,-10000,0,10000"
1812
- ].join("\n") + "\n";
1813
- writeFileSync6(gridCsvPath, gridContent, "utf-8");
1814
- }
1815
- console.log(`Initialized empty BimDown project at ${absDir}`);
1816
- console.log("Created:");
1817
- console.log(" - global/level.csv (lv-1)");
1818
- console.log(" - global/grid.csv (A, 1)");
1819
- }
1820
- var init_init = __esm({
1821
- "src/commands/init.ts"() {
1822
- "use strict";
1823
- }
1824
- });
1825
-
1826
- // src/commands/diff.ts
1827
- var diff_exports = {};
1828
- __export(diff_exports, {
1829
- diffProjects: () => diffProjects
1830
- });
1831
- import { existsSync as existsSync16 } from "fs";
1832
- import { join as join17 } from "path";
1833
- function diffProjects(dirA, dirB) {
1834
- if (!existsSync16(dirA)) {
1835
- console.error(`Directory not found: ${dirA}`);
1836
- process.exitCode = 1;
1837
- return;
1838
- }
1839
- if (!existsSync16(dirB)) {
1840
- console.error(`Directory not found: ${dirB}`);
1841
- process.exitCode = 1;
1842
- return;
1843
- }
1844
- const layoutA = discoverLayout(dirA);
1845
- const layoutB = discoverLayout(dirB);
1846
- const pathsA = [
1847
- { name: "global", abs: layoutA.globalDir },
1848
- ...layoutA.levelDirs.map((d) => ({ name: d.name, abs: d.path }))
1849
- ];
1850
- const pathsB = [
1851
- { name: "global", abs: layoutB.globalDir },
1852
- ...layoutB.levelDirs.map((d) => ({ name: d.name, abs: d.path }))
1853
- ];
1854
- const allPathNames = /* @__PURE__ */ new Set([...pathsA.map((p) => p.name), ...pathsB.map((p) => p.name)]);
1855
- for (const pathName of allPathNames) {
1856
- const dirAAbs = pathsA.find((p) => p.name === pathName)?.abs;
1857
- const dirBAbs = pathsB.find((p) => p.name === pathName)?.abs;
1858
- const filesA = new Set(dirAAbs && existsSync16(dirAAbs) ? listFiles(dirAAbs).filter((f) => f.endsWith(".csv")) : []);
1859
- const filesB = new Set(dirBAbs && existsSync16(dirBAbs) ? listFiles(dirBAbs).filter((f) => f.endsWith(".csv")) : []);
1860
- const allFiles = /* @__PURE__ */ new Set([...filesA, ...filesB]);
1861
- let printedPathHeader = false;
1862
- for (const f of allFiles) {
1863
- const tableName = f.replace(".csv", "");
1864
- const pathFileA = dirAAbs ? join17(dirAAbs, f) : null;
1865
- const pathFileB = dirBAbs ? join17(dirBAbs, f) : null;
1866
- const rowsA = {};
1867
- const rowsB = {};
1868
- if (pathFileA && existsSync16(pathFileA)) {
1869
- for (const row of readCsv(pathFileA).rows) {
1870
- if (row.id) rowsA[String(row.id)] = row;
1871
- }
1872
- }
1873
- if (pathFileB && existsSync16(pathFileB)) {
1874
- for (const row of readCsv(pathFileB).rows) {
1875
- if (row.id) rowsB[String(row.id)] = row;
1876
- }
1877
- }
1878
- const allIds = /* @__PURE__ */ new Set([...Object.keys(rowsA), ...Object.keys(rowsB)]);
1879
- const diffs = [];
1880
- for (const id of allIds) {
1881
- if (!rowsA[id] && rowsB[id]) {
1882
- diffs.push({ sign: "+", id });
1883
- } else if (rowsA[id] && !rowsB[id]) {
1884
- diffs.push({ sign: "-", id });
1885
- } else {
1886
- if (JSON.stringify(rowsA[id]) !== JSON.stringify(rowsB[id])) {
1887
- diffs.push({ sign: "~", id });
1888
- }
1889
- }
1890
- }
1891
- if (diffs.length > 0) {
1892
- if (!printedPathHeader) {
1893
- console.log(`
1894
- \u{1F4C1} ${pathName}`);
1895
- printedPathHeader = true;
1896
- }
1897
- console.log(` == ${tableName} ==`);
1898
- for (const d of diffs) {
1899
- console.log(` ${d.sign} ${d.id}`);
1900
- }
1901
- }
1902
- }
1903
- }
1904
- console.log();
1905
- }
1906
- var init_diff = __esm({
1907
- "src/commands/diff.ts"() {
1908
- "use strict";
1909
- init_fs();
1910
- init_csv();
1911
- }
1912
- });
1913
-
1914
- // src/commands/publish.ts
1915
- var publish_exports = {};
1916
- __export(publish_exports, {
1917
- publish: () => publish
1918
- });
1919
- import { resolve } from "path";
1920
- import { readFileSync as readFileSync6, existsSync as existsSync17 } from "fs";
1921
- import { zipSync } from "fflate";
1922
- async function publish(dir, opts) {
1923
- const absDir = resolve(dir);
1924
- if (!existsSync17(absDir)) {
1925
- console.error(`Directory not found: ${absDir}`);
1926
- process.exitCode = 1;
1927
- return;
1928
- }
1929
- const apiBase = (opts.api || process.env.BIMCLAW_API || DEFAULT_API).replace(/\/$/, "");
1930
- const expires = opts.expires || DEFAULT_EXPIRES;
1931
- const layout = discoverLayout(absDir);
1932
- const allDirs = [
1933
- { prefix: "global", path: layout.globalDir },
1934
- ...layout.levelDirs.map((d) => ({ prefix: d.name, path: d.path }))
1935
- ];
1936
- const files = {};
1937
- for (const d of allDirs) {
1938
- if (!existsSync17(d.path)) continue;
1939
- for (const f of listFiles(d.path)) {
1940
- const filePath = `${d.prefix}/${f}`;
1941
- const content = readFileSync6(resolve(d.path, f));
1942
- files[filePath] = new Uint8Array(content);
1943
- }
1944
- }
1945
- const metadataPath = resolve(absDir, "project_metadata.json");
1946
- if (existsSync17(metadataPath)) {
1947
- files["project_metadata.json"] = new Uint8Array(readFileSync6(metadataPath));
1948
- }
1949
- const fileCount = Object.keys(files).length;
1950
- if (fileCount === 0) {
1951
- console.error("No files found in project directory.");
1952
- process.exitCode = 1;
1953
- return;
1954
- }
1955
- const zipData = zipSync(files);
1956
- const sizeMB = (zipData.byteLength / 1024 / 1024).toFixed(1);
1957
- console.log(`Packed ${fileCount} files (${sizeMB} MB)`);
1958
- const projectName = opts.name || absDir.split("/").pop() || "Untitled";
1959
- const url = `${apiBase}/api/shares/publish`;
1960
- const formData = new FormData();
1961
- formData.append("file", new Blob([zipData], { type: "application/zip" }), `${projectName}.zip`);
1962
- formData.append("name", projectName);
1963
- formData.append("expires", expires);
1964
- try {
1965
- const resp = await fetch(url, {
1966
- method: "POST",
1967
- body: formData
1968
- });
1969
- if (!resp.ok) {
1970
- const body = await resp.text();
1971
- console.error(`Publish failed (${resp.status}): ${body}`);
1972
- process.exitCode = 1;
1973
- return;
1974
- }
1975
- const result = await resp.json();
1976
- console.log(`
1977
- \u2705 Published: ${result.url}`);
1978
- if (result.expiresAt) {
1979
- console.log(` Expires: ${new Date(result.expiresAt).toLocaleString()}`);
1980
- }
1981
- } catch (err) {
1982
- console.error(`Publish failed: ${err.message}`);
1983
- process.exitCode = 1;
1984
- }
1985
- }
1986
- var DEFAULT_API, DEFAULT_EXPIRES;
1987
- var init_publish = __esm({
1988
- "src/commands/publish.ts"() {
1989
- "use strict";
1990
- init_fs();
1991
- DEFAULT_API = "https://bim-claw.com";
1992
- DEFAULT_EXPIRES = "7d";
1993
- }
1994
- });
2
+ import {
3
+ build,
4
+ validateOnly
5
+ } from "./chunk-KWSGJUMZ.js";
6
+ import {
7
+ CATEGORY_LABELS,
8
+ CATEGORY_ORDER,
9
+ furnitureFamilies
10
+ } from "./chunk-AYAXRYGP.js";
11
+ import "./chunk-LWYIPR64.js";
12
+ import {
13
+ typeParamFields
14
+ } from "./chunk-XQU52JKB.js";
15
+ import "./chunk-EC5MR5ZH.js";
16
+ import "./chunk-IQJA3EFO.js";
17
+ import "./chunk-4SKM4RHY.js";
18
+ import {
19
+ buildRegistry,
20
+ getSpecDir
21
+ } from "./chunk-4YHVOWS4.js";
22
+ import "./chunk-JY6KWRDB.js";
23
+ import {
24
+ discoverLayout
25
+ } from "./chunk-OBY3UYCO.js";
1995
26
 
1996
27
  // src/index.ts
1997
28
  import { Command } from "commander";
1998
- import { resolve as resolve2 } from "path";
1999
-
2000
- // src/build/index.ts
2001
- import { existsSync as existsSync9 } from "fs";
2002
- import { join as join10 } from "path";
2003
-
2004
- // src/validate/index.ts
2005
- init_registry();
2006
- init_fs();
2007
- init_csv();
2008
- import { existsSync as existsSync4 } from "fs";
2009
- import { join as join5 } from "path";
2010
-
2011
- // src/validate/structure.ts
2012
- init_fs();
2013
- init_registry();
2014
- import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
2015
- import { join as join4, extname } from "path";
2016
- var OPTIONAL_SVG_TABLES = /* @__PURE__ */ new Set(["opening", "space"]);
2017
- var KNOWN_CSV_NAMES = new Set(Object.keys(ID_PREFIXES).map((t) => `${t}.csv`));
2018
- var KNOWN_SVG_NAMES = new Set(Object.values(SVG_FILE_NAMES).map((s) => `${s}.svg`));
2019
- var KNOWN_GLOBAL_EXTRAS = /* @__PURE__ */ new Set(["_IdMap.csv"]);
2020
- function validateStructure(dir) {
2021
- const issues = [];
2022
- const layout = discoverLayout(dir);
2023
- if (!existsSync3(layout.globalDir)) {
2024
- issues.push("global/ missing global/ directory");
2025
- return issues;
2026
- }
2027
- const globalFiles = listFiles(layout.globalDir);
2028
- if (!globalFiles.includes("level.csv")) {
2029
- issues.push("global/ missing level.csv");
2030
- }
2031
- if (!globalFiles.includes("grid.csv")) {
2032
- issues.push("global/ missing grid.csv");
2033
- }
2034
- for (const f of globalFiles) {
2035
- const ext = extname(f);
2036
- if (ext === ".svg") {
2037
- issues.push(`global/${f} SVG files are not allowed in global/`);
2038
- } else if (ext === ".csv") {
2039
- if (!KNOWN_CSV_NAMES.has(f) && !KNOWN_GLOBAL_EXTRAS.has(f)) {
2040
- issues.push(`global/${f} unknown file \u2014 only known table CSVs are allowed`);
2041
- }
2042
- } else {
2043
- issues.push(`global/${f} unexpected file \u2014 only CSV files are allowed in global/`);
2044
- }
2045
- }
2046
- for (const ld of layout.levelDirs) {
2047
- if (!/^lv-.+$/.test(ld.name)) {
2048
- issues.push(`${ld.name}/ directory name does not match lv-{id} pattern`);
2049
- continue;
2050
- }
2051
- const files = listFiles(ld.path);
2052
- for (const f of files) {
2053
- const ext = extname(f);
2054
- if (ext === ".csv") {
2055
- if (!KNOWN_CSV_NAMES.has(f)) {
2056
- issues.push(`${ld.name}/${f} unknown file \u2014 not a recognized BimDown table`);
2057
- }
2058
- const tableName = f.replace(".csv", "");
2059
- if (GLOBAL_ONLY_TABLES.has(tableName)) {
2060
- issues.push(`${ld.name}/${f} ${tableName} belongs in global/ only`);
2061
- }
2062
- } else if (ext === ".svg") {
2063
- if (!KNOWN_SVG_NAMES.has(f)) {
2064
- issues.push(`${ld.name}/${f} unknown SVG file \u2014 not a recognized BimDown table name`);
2065
- }
2066
- const svgBase = f.replace(".svg", "");
2067
- const tableName = Object.entries(SVG_FILE_NAMES).find(
2068
- ([, v]) => v === svgBase
2069
- )?.[0];
2070
- if (tableName && !files.includes(`${tableName}.csv`)) {
2071
- issues.push(`${ld.name}/${f} orphaned SVG \u2014 no matching ${tableName}.csv`);
2072
- }
2073
- } else {
2074
- issues.push(`${ld.name}/${f} unexpected file \u2014 only CSV and SVG files are allowed`);
2075
- }
2076
- }
2077
- for (const f of files) {
2078
- if (extname(f) !== ".csv") continue;
2079
- const tableName = f.replace(".csv", "");
2080
- const svgName = SVG_FILE_NAMES[tableName];
2081
- if (svgName && !files.includes(`${svgName}.svg`) && !OPTIONAL_SVG_TABLES.has(tableName)) {
2082
- issues.push(`${ld.name}/${f} missing paired SVG file "${svgName}.svg"`);
2083
- }
2084
- }
2085
- }
2086
- const topEntries = readdirSync3(dir);
2087
- for (const f of topEntries) {
2088
- if (f === "global" || /^lv-.+$/.test(f)) continue;
2089
- if (f === "project_metadata.json") continue;
2090
- if (f.startsWith(".")) continue;
2091
- issues.push(`${f} unexpected entry in project root \u2014 only global/ and lv-{n}/ directories are allowed`);
2092
- }
2093
- const metadataPath = join4(dir, "project_metadata.json");
2094
- if (existsSync3(metadataPath)) {
2095
- try {
2096
- const raw = readFileSync3(metadataPath, "utf-8");
2097
- const metadata = JSON.parse(raw);
2098
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) {
2099
- issues.push("project_metadata.json must be a JSON object");
2100
- } else {
2101
- if (!metadata.format_version || typeof metadata.format_version !== "string") {
2102
- issues.push('project_metadata.json missing or invalid "format_version" (required string)');
2103
- }
2104
- for (const key of Object.keys(metadata)) {
2105
- if (!["format_version", "project_name", "units", "source"].includes(key)) {
2106
- issues.push(`project_metadata.json unknown field "${key}"`);
2107
- }
2108
- }
2109
- }
2110
- } catch (e) {
2111
- issues.push(`project_metadata.json failed to parse: ${e.message}`);
2112
- }
2113
- }
2114
- return issues;
2115
- }
2116
-
2117
- // src/validate/csv.ts
2118
- function validateCsvHeaders(path, table, data) {
2119
- const issues = [];
2120
- const expected = new Set(table.csvFields.map((f) => f.name));
2121
- const actual = new Set(data.headers);
2122
- for (const h of data.headers) {
2123
- if (!expected.has(h)) {
2124
- issues.push(`${path} unexpected column "${h}"`);
2125
- }
2126
- }
2127
- for (const f of table.csvFields) {
2128
- if (f.required && !actual.has(f.name)) {
2129
- issues.push(`${path} missing required column "${f.name}"`);
2130
- }
2131
- }
2132
- return issues;
2133
- }
2134
- function validateCsvRequired(path, table, data) {
2135
- const issues = [];
2136
- const requiredFields = table.csvFields.filter((f) => f.required);
2137
- for (let i = 0; i < data.rows.length; i++) {
2138
- const row = data.rows[i];
2139
- for (const f of requiredFields) {
2140
- const val = row[f.name];
2141
- if (val === void 0 || val === "") {
2142
- issues.push(`${path}:${i + 2} required field "${f.name}" is empty`);
2143
- }
2144
- }
2145
- }
2146
- return issues;
2147
- }
2148
- function validateCsvEnums(path, table, data) {
2149
- const issues = [];
2150
- const enumFields = table.csvFields.filter((f) => f.type === "enum" && f.values);
2151
- for (let i = 0; i < data.rows.length; i++) {
2152
- const row = data.rows[i];
2153
- for (const f of enumFields) {
2154
- const val = row[f.name];
2155
- if (val !== void 0 && val !== "" && !f.values.includes(val)) {
2156
- issues.push(
2157
- `${path}:${i + 2} field "${f.name}" value "${val}" is not a valid enum (${f.values.join(", ")})`
2158
- );
2159
- }
2160
- }
2161
- }
2162
- return issues;
2163
- }
2164
-
2165
- // src/validate/ids.ts
2166
- function validateIdFormat(path, table, data) {
2167
- const issues = [];
2168
- const prefix = table.prefix;
2169
- for (let i = 0; i < data.rows.length; i++) {
2170
- const id = data.rows[i].id;
2171
- if (!id) continue;
2172
- const freeformTables = /* @__PURE__ */ new Set(["grid", "level"]);
2173
- const pattern = freeformTables.has(table.name) ? `^${prefix}-.+$` : `^${prefix}-\\d+$`;
2174
- const regex = new RegExp(pattern);
2175
- if (!regex.test(id)) {
2176
- const expected = freeformTables.has(table.name) ? `"${prefix}-{name}"` : `"${prefix}-{n}"`;
2177
- issues.push(`${path}:${i + 2} id "${id}" has wrong format, expected ${expected}`);
2178
- }
2179
- }
2180
- return issues;
2181
- }
2182
- function createIdRegistry() {
2183
- return { ids: /* @__PURE__ */ new Map(), allIds: /* @__PURE__ */ new Map(), issues: [] };
2184
- }
2185
- function registerIds(registry, path, tableName, data) {
2186
- const level = path.split("/")[0];
2187
- for (let i = 0; i < data.rows.length; i++) {
2188
- const id = data.rows[i].id;
2189
- if (!id) continue;
2190
- const scopedKey = `${level}/${id}`;
2191
- const existing = registry.ids.get(scopedKey);
2192
- if (existing) {
2193
- if (existing.table === tableName) {
2194
- registry.issues.push(
2195
- `${path}:${i + 2} duplicate id "${id}" (first seen in ${existing.path}:${existing.row})`
2196
- );
2197
- } else {
2198
- registry.issues.push(
2199
- `${path}:${i + 2} id "${id}" conflicts with ${existing.table} in ${existing.path}:${existing.row}`
2200
- );
2201
- }
2202
- } else {
2203
- registry.ids.set(scopedKey, { table: tableName, path, row: i + 2 });
2204
- }
2205
- registry.allIds.set(id, { table: tableName, path, row: i + 2 });
2206
- }
2207
- }
2208
-
2209
- // src/validate/references.ts
2210
- init_registry();
2211
- function validateReferences(path, table, data, idRegistry) {
2212
- const issues = [];
2213
- const refFields = table.csvFields.filter((f) => f.type === "reference");
2214
- for (let i = 0; i < data.rows.length; i++) {
2215
- const row = data.rows[i];
2216
- for (const f of refFields) {
2217
- const val = row[f.name];
2218
- if (!val) continue;
2219
- const entry = idRegistry.allIds.get(val);
2220
- if (!entry) {
2221
- issues.push(`${path}:${i + 2} ${f.name} "${val}" references non-existent id`);
2222
- continue;
2223
- }
2224
- if (f.reference && f.reference !== "element") {
2225
- const expectedPrefix = ID_PREFIXES[f.reference];
2226
- if (expectedPrefix && !val.startsWith(expectedPrefix + "-")) {
2227
- issues.push(
2228
- `${path}:${i + 2} ${f.name} "${val}" should reference ${f.reference} (prefix "${expectedPrefix}-")`
2229
- );
2230
- }
2231
- }
2232
- }
2233
- }
2234
- return issues;
2235
- }
2236
-
2237
- // src/validate/ranges.ts
2238
- var FIELD_MAX = {
2239
- elevation: 500,
2240
- // tallest buildings ~500m
2241
- base_offset: 100,
2242
- top_offset: 100,
2243
- thickness: 2,
2244
- width: 30,
2245
- height: 20,
2246
- size_x: 10,
2247
- size_y: 10,
2248
- length: 100,
2249
- position: 100,
2250
- // distance in meters along host wall
2251
- start_x: 1e4,
2252
- // site coordinates can be large
2253
- start_y: 1e4,
2254
- end_x: 1e4,
2255
- end_y: 1e4,
2256
- start_z: 500,
2257
- end_z: 500,
2258
- step_count: 200
2259
- // not meters, but still bounded
2260
- };
2261
- var DEFAULT_MAX = 1e3;
2262
- function validateRanges(path, table, data) {
2263
- const issues = [];
2264
- const floatFields = table.csvFields.filter(
2265
- (f) => (f.type === "float" || f.type === "int") && f.name !== "id"
2266
- );
2267
- for (let i = 0; i < data.rows.length; i++) {
2268
- const row = data.rows[i];
2269
- const rowNum = i + 2;
2270
- for (const field of floatFields) {
2271
- const raw = row[field.name];
2272
- if (raw === void 0 || raw === "") continue;
2273
- const val = Number(raw);
2274
- if (isNaN(val)) continue;
2275
- const max = FIELD_MAX[field.name] ?? DEFAULT_MAX;
2276
- if (Math.abs(val) > max) {
2277
- issues.push(
2278
- `${path}:${rowNum} ${field.name}=${raw} looks like millimeters \u2014 all values must be in meters (max reasonable: ${max})`
2279
- );
2280
- }
2281
- }
2282
- }
2283
- return issues;
2284
- }
2285
-
2286
- // src/validate/svg.ts
2287
- init_svg();
2288
- var ALLOWED_TAGS = /* @__PURE__ */ new Set(["svg", "g", "path", "rect", "polygon", "circle", "text"]);
2289
- var FORBIDDEN_TAGS = /* @__PURE__ */ new Set(["line", "defs", "use", "script", "linearGradient", "radialGradient", "filter"]);
2290
- var EXPECTED_TAGS = {
2291
- // Line elements → <path>
2292
- wall: /* @__PURE__ */ new Set(["path"]),
2293
- structure_wall: /* @__PURE__ */ new Set(["path"]),
2294
- curtain_wall: /* @__PURE__ */ new Set(["path"]),
2295
- room_separator: /* @__PURE__ */ new Set(["path"]),
2296
- stair: /* @__PURE__ */ new Set(["path"]),
2297
- ramp: /* @__PURE__ */ new Set(["path"]),
2298
- railing: /* @__PURE__ */ new Set(["path"]),
2299
- beam: /* @__PURE__ */ new Set(["path"]),
2300
- brace: /* @__PURE__ */ new Set(["path"]),
2301
- duct: /* @__PURE__ */ new Set(["path"]),
2302
- pipe: /* @__PURE__ */ new Set(["path"]),
2303
- cable_tray: /* @__PURE__ */ new Set(["path"]),
2304
- conduit: /* @__PURE__ */ new Set(["path"]),
2305
- // Point elements → <rect> | <circle>
2306
- column: /* @__PURE__ */ new Set(["rect", "circle"]),
2307
- structure_column: /* @__PURE__ */ new Set(["rect", "circle"]),
2308
- equipment: /* @__PURE__ */ new Set(["rect", "circle"]),
2309
- terminal: /* @__PURE__ */ new Set(["rect", "circle"]),
2310
- mep_node: /* @__PURE__ */ new Set(["rect", "circle"]),
2311
- // Polygon elements → <polygon>
2312
- slab: /* @__PURE__ */ new Set(["polygon"]),
2313
- roof: /* @__PURE__ */ new Set(["polygon"]),
2314
- ceiling: /* @__PURE__ */ new Set(["polygon"]),
2315
- structure_slab: /* @__PURE__ */ new Set(["polygon"]),
2316
- space: /* @__PURE__ */ new Set(["polygon"]),
2317
- // Mixed geometry
2318
- foundation: /* @__PURE__ */ new Set(["rect", "circle", "path", "polygon"]),
2319
- opening: /* @__PURE__ */ new Set(["rect", "polygon"])
2320
- };
2321
- function extractPathCoords(d) {
2322
- const coords = [];
2323
- const nums = d.match(/-?[\d.]+/g);
2324
- if (nums) {
2325
- for (const n of nums) {
2326
- const val = parseFloat(n);
2327
- if (!isNaN(val)) coords.push(val);
2328
- }
2329
- }
2330
- return coords;
2331
- }
2332
- function validateSvgFile(displayPath, fullPath, csvIds, isHosted, tableName) {
2333
- const issues = [];
2334
- let svg;
2335
- try {
2336
- svg = parseSvgFile(fullPath);
2337
- } catch (e) {
2338
- issues.push(`${displayPath} failed to parse SVG: ${e.message}`);
2339
- return issues;
2340
- }
2341
- if (!svg.hasYFlip) {
2342
- issues.push(`${displayPath} missing required <g transform="scale(1,-1)"> for Y-axis flip`);
2343
- }
2344
- for (const tag of svg.allTags) {
2345
- if (FORBIDDEN_TAGS.has(tag)) {
2346
- issues.push(`${displayPath} forbidden tag <${tag}> found`);
2347
- }
2348
- if (!ALLOWED_TAGS.has(tag) && !FORBIDDEN_TAGS.has(tag) && !tag.startsWith("?")) {
2349
- issues.push(`${displayPath} unknown tag <${tag}>`);
2350
- }
2351
- }
2352
- const svgIds = /* @__PURE__ */ new Set();
2353
- for (const el of svg.elements) {
2354
- if (svgIds.has(el.id)) {
2355
- issues.push(`${displayPath} duplicate SVG element id "${el.id}"`);
2356
- }
2357
- svgIds.add(el.id);
2358
- if (!csvIds.has(el.id)) {
2359
- issues.push(`${displayPath} SVG element "${el.id}" has no matching CSV row`);
2360
- }
2361
- if (tableName && EXPECTED_TAGS[tableName] && !EXPECTED_TAGS[tableName].has(el.tag)) {
2362
- const expected = [...EXPECTED_TAGS[tableName]].join(" or ");
2363
- issues.push(`${displayPath} element "${el.id}" uses <${el.tag}> but ${tableName} requires <${expected}>`);
2364
- }
2365
- if (isHosted && !el.attrs["data-host"]) {
2366
- issues.push(`${displayPath} hosted element "${el.id}" missing data-host attribute`);
2367
- }
2368
- if (el.tag === "path" && el.attrs.d) {
2369
- const coords = extractPathCoords(el.attrs.d);
2370
- for (const val of coords) {
2371
- if (Math.abs(val) > 1e3) {
2372
- issues.push(
2373
- `${displayPath} element "${el.id}" path coordinates look like millimeters \u2014 SVG coordinates must be in meters`
2374
- );
2375
- break;
2376
- }
2377
- }
2378
- }
2379
- const coordAttrs = ["x", "y", "cx", "cy", "r", "width", "height"];
2380
- for (const attr of coordAttrs) {
2381
- const raw = el.attrs[attr];
2382
- if (raw === void 0) continue;
2383
- const val = Number(raw);
2384
- if (!isNaN(val) && Math.abs(val) > 1e3) {
2385
- issues.push(
2386
- `${displayPath} element "${el.id}" ${attr}=${raw} looks like millimeters \u2014 SVG coordinates must be in meters`
2387
- );
2388
- }
2389
- }
2390
- if (el.attrs["points"]) {
2391
- const points = el.attrs["points"].trim().split(/\s+/);
2392
- for (const pt of points) {
2393
- const [px, py] = pt.split(",").map(Number);
2394
- if (!isNaN(px) && Math.abs(px) > 1e3 || !isNaN(py) && Math.abs(py) > 1e3) {
2395
- issues.push(
2396
- `${displayPath} element "${el.id}" polygon point ${pt} looks like millimeters \u2014 coordinates must be in meters`
2397
- );
2398
- break;
2399
- }
2400
- }
2401
- }
2402
- }
2403
- return issues;
2404
- }
2405
-
2406
- // src/validate/index.ts
2407
- function validate(dir) {
2408
- const issues = [];
2409
- issues.push(...validateStructure(dir));
2410
- const registry = buildRegistry(getSpecDir());
2411
- const layout = discoverLayout(dir);
2412
- const csvEntries = [];
2413
- const allDirs = [
2414
- { name: "global", path: layout.globalDir },
2415
- ...layout.levelDirs
2416
- ];
2417
- for (const d of allDirs) {
2418
- if (!existsSync4(d.path)) continue;
2419
- const files = listFiles(d.path);
2420
- for (const f of files) {
2421
- if (!f.endsWith(".csv")) continue;
2422
- const tableName = f.replace(".csv", "");
2423
- const table = registry.get(tableName);
2424
- if (!table) continue;
2425
- const fullPath = join5(d.path, f);
2426
- const relPath = `${d.name}/${f}`;
2427
- let data;
2428
- try {
2429
- data = readCsv(fullPath);
2430
- } catch (e) {
2431
- issues.push(`${relPath} failed to read CSV: ${e.message}`);
2432
- continue;
2433
- }
2434
- csvEntries.push({ path: relPath, fullPath, tableName, table, data });
2435
- }
2436
- }
2437
- for (const entry of csvEntries) {
2438
- issues.push(...validateCsvHeaders(entry.path, entry.table, entry.data));
2439
- issues.push(...validateCsvRequired(entry.path, entry.table, entry.data));
2440
- }
2441
- for (const entry of csvEntries) {
2442
- issues.push(...validateIdFormat(entry.path, entry.table, entry.data));
2443
- }
2444
- const idRegistry = createIdRegistry();
2445
- for (const entry of csvEntries) {
2446
- registerIds(idRegistry, entry.path, entry.tableName, entry.data);
2447
- }
2448
- issues.push(...idRegistry.issues);
2449
- for (const entry of csvEntries) {
2450
- issues.push(...validateCsvEnums(entry.path, entry.table, entry.data));
2451
- }
2452
- for (const entry of csvEntries) {
2453
- issues.push(...validateReferences(entry.path, entry.table, entry.data, idRegistry));
2454
- }
2455
- for (const entry of csvEntries) {
2456
- issues.push(...validateRanges(entry.path, entry.table, entry.data));
2457
- }
2458
- for (const entry of csvEntries) {
2459
- if (!entry.table.hostType) continue;
2460
- for (let i = 0; i < entry.data.rows.length; i++) {
2461
- const row = entry.data.rows[i];
2462
- const pos = row.position;
2463
- if (pos === void 0 || pos === "") continue;
2464
- const val = Number(pos);
2465
- if (isNaN(val) || val < 0) {
2466
- issues.push(
2467
- `${entry.path}:${i + 2} position=${pos} must be a non-negative distance in meters`
2468
- );
2469
- }
2470
- }
2471
- }
2472
- for (const d of allDirs) {
2473
- if (!existsSync4(d.path) || d.name === "global") continue;
2474
- const files = listFiles(d.path);
2475
- for (const f of files) {
2476
- if (!f.endsWith(".svg")) continue;
2477
- const svgBase = f.replace(".svg", "");
2478
- const tableEntry = Object.entries(SVG_FILE_NAMES).find(([, v]) => v === svgBase);
2479
- if (!tableEntry) continue;
2480
- const [tableName] = tableEntry;
2481
- const table = registry.get(tableName);
2482
- if (!table) continue;
2483
- const csvIds = /* @__PURE__ */ new Set();
2484
- for (const entry of csvEntries) {
2485
- if (entry.tableName === tableName) {
2486
- const entryDir = entry.path.split("/")[0];
2487
- if (entryDir === d.name) {
2488
- for (const row of entry.data.rows) {
2489
- if (row.id) csvIds.add(row.id);
2490
- }
2491
- }
2492
- }
2493
- }
2494
- const svgFullPath = join5(d.path, f);
2495
- const relPath = `${d.name}/${f}`;
2496
- const isHosted = !!table.hostType;
2497
- issues.push(...validateSvgFile(relPath, svgFullPath, csvIds, isHosted, tableName));
2498
- }
2499
- }
2500
- return issues;
2501
- }
2502
-
2503
- // src/build/index.ts
2504
- init_fs();
2505
-
2506
- // src/build/space-boundary.ts
2507
- init_svg();
2508
- init_csv();
2509
- import { existsSync as existsSync5, writeFileSync as writeFileSync2 } from "fs";
2510
- import { join as join6 } from "path";
2511
- var TOLERANCE = 0.01;
2512
- var MAX_FACE_EDGES = 1e4;
2513
- var BOUNDARY_TABLES = ["wall", "structure_wall", "curtain_wall", "room_separator"];
2514
- function computeSpaceBoundaries(levelDir, globalDir) {
2515
- const warnings = [];
2516
- const spaceCsvPath = join6(levelDir.path, "space.csv");
2517
- if (!existsSync5(spaceCsvPath)) return { warnings, svgWritten: false };
2518
- const spaceCsv = readCsv(spaceCsvPath);
2519
- if (spaceCsv.rows.length === 0) return { warnings, svgWritten: false };
2520
- const segments = collectBoundarySegments(levelDir.path);
2521
- if (globalDir) {
2522
- segments.push(...collectBoundarySegments(globalDir));
2523
- }
2524
- if (segments.length === 0) {
2525
- warnings.push(`${levelDir.name}/ no boundary elements found for space boundary computation`);
2526
- return { warnings, svgWritten: false };
2527
- }
2528
- const splitSegments = splitAtIntersections(segments);
2529
- const { vertices, halfEdges } = buildHalfEdgeStructure(splitSegments);
2530
- for (const v of vertices) {
2531
- if (v.outgoing.length === 1) {
2532
- const he = v.outgoing[0];
2533
- warnings.push(
2534
- `[warn] ${levelDir.name}/ ${he.sourceId} endpoint (${v.x.toFixed(3)}, ${v.y.toFixed(3)}) has no connected line element`
2535
- );
2536
- }
2537
- }
2538
- const faces = traceFaces(halfEdges);
2539
- const matchedSpaces = /* @__PURE__ */ new Map();
2540
- for (const row of spaceCsv.rows) {
2541
- const seedX = parseFloat(row.x ?? "");
2542
- const seedY = parseFloat(row.y ?? "");
2543
- if (isNaN(seedX) || isNaN(seedY)) continue;
2544
- let bestFace = null;
2545
- let bestArea = Infinity;
2546
- for (const face of faces) {
2547
- if (face.signedArea <= 0) continue;
2548
- if (face.signedArea < bestArea && pointInPolygon(seedX, seedY, face.polygon)) {
2549
- bestFace = face;
2550
- bestArea = face.signedArea;
2551
- }
2552
- }
2553
- if (bestFace) {
2554
- matchedSpaces.set(row.id, bestFace);
2555
- } else {
2556
- warnings.push(
2557
- `[warn] ${levelDir.name}/space.csv ${row.id} at (${row.x}, ${row.y}) has no enclosing boundary`
2558
- );
2559
- }
2560
- }
2561
- if (matchedSpaces.size === 0) return { warnings, svgWritten: false };
2562
- writeSvg(levelDir.path, matchedSpaces);
2563
- return { warnings, svgWritten: true };
2564
- }
2565
- function collectBoundarySegments(levelPath) {
2566
- const segments = [];
2567
- for (const table of BOUNDARY_TABLES) {
2568
- const svgPath = join6(levelPath, `${table}.svg`);
2569
- if (!existsSync5(svgPath)) continue;
2570
- try {
2571
- const svg = parseSvgFile(svgPath);
2572
- for (const el of svg.elements) {
2573
- if (el.tag !== "path") continue;
2574
- const geo = extractLineGeometry(el);
2575
- if (geo.length < TOLERANCE) continue;
2576
- segments.push({
2577
- startX: geo.start_x,
2578
- startY: geo.start_y,
2579
- endX: geo.end_x,
2580
- endY: geo.end_y,
2581
- id: el.id
2582
- });
2583
- }
2584
- } catch {
2585
- }
2586
- }
2587
- return segments;
2588
- }
2589
- function splitAtIntersections(segments) {
2590
- let result = [...segments];
2591
- let changed = true;
2592
- while (changed) {
2593
- changed = false;
2594
- const allEndpoints = [];
2595
- for (const seg of result) {
2596
- allEndpoints.push({ x: seg.startX, y: seg.startY });
2597
- allEndpoints.push({ x: seg.endX, y: seg.endY });
2598
- }
2599
- const nextResult = [];
2600
- for (let i = 0; i < result.length; i++) {
2601
- const seg = result[i];
2602
- const dx = seg.endX - seg.startX;
2603
- const dy = seg.endY - seg.startY;
2604
- const lenSq = dx * dx + dy * dy;
2605
- if (lenSq < TOLERANCE * TOLERANCE) {
2606
- nextResult.push(seg);
2607
- continue;
2608
- }
2609
- const splitPoints = [];
2610
- for (const ep of allEndpoints) {
2611
- if (Math.abs(ep.x - seg.startX) < TOLERANCE && Math.abs(ep.y - seg.startY) < TOLERANCE) continue;
2612
- if (Math.abs(ep.x - seg.endX) < TOLERANCE && Math.abs(ep.y - seg.endY) < TOLERANCE) continue;
2613
- const t = ((ep.x - seg.startX) * dx + (ep.y - seg.startY) * dy) / lenSq;
2614
- if (t <= TOLERANCE || t >= 1 - TOLERANCE) continue;
2615
- const closestX = seg.startX + t * dx;
2616
- const closestY = seg.startY + t * dy;
2617
- const distSq = (ep.x - closestX) * (ep.x - closestX) + (ep.y - closestY) * (ep.y - closestY);
2618
- if (distSq < TOLERANCE * TOLERANCE) {
2619
- splitPoints.push({ x: ep.x, y: ep.y, t });
2620
- }
2621
- }
2622
- for (let j = 0; j < result.length; j++) {
2623
- if (j === i) continue;
2624
- const other = result[j];
2625
- const ox = other.endX - other.startX;
2626
- const oy = other.endY - other.startY;
2627
- const det = dx * oy - dy * ox;
2628
- if (Math.abs(det) < 1e-12) continue;
2629
- const rx = other.startX - seg.startX;
2630
- const ry = other.startY - seg.startY;
2631
- const t = (rx * oy - ry * ox) / det;
2632
- const s = (rx * dy - ry * dx) / det;
2633
- if (t <= TOLERANCE || t >= 1 - TOLERANCE) continue;
2634
- if (s <= TOLERANCE || s >= 1 - TOLERANCE) continue;
2635
- splitPoints.push({
2636
- x: seg.startX + t * dx,
2637
- y: seg.startY + t * dy,
2638
- t
2639
- });
2640
- }
2641
- if (splitPoints.length === 0) {
2642
- nextResult.push(seg);
2643
- } else {
2644
- changed = true;
2645
- splitPoints.sort((a, b) => a.t - b.t);
2646
- const unique = [splitPoints[0]];
2647
- for (let k = 1; k < splitPoints.length; k++) {
2648
- if (Math.abs(splitPoints[k].t - unique[unique.length - 1].t) > TOLERANCE) {
2649
- unique.push(splitPoints[k]);
2650
- }
2651
- }
2652
- let prevX = seg.startX, prevY = seg.startY;
2653
- for (const sp of unique) {
2654
- nextResult.push({ startX: prevX, startY: prevY, endX: sp.x, endY: sp.y, id: seg.id });
2655
- prevX = sp.x;
2656
- prevY = sp.y;
2657
- }
2658
- nextResult.push({ startX: prevX, startY: prevY, endX: seg.endX, endY: seg.endY, id: seg.id });
2659
- }
2660
- }
2661
- result = nextResult;
2662
- }
2663
- return result;
2664
- }
2665
- function buildHalfEdgeStructure(segments) {
2666
- const vertices = [];
2667
- function findOrCreateVertex(x, y) {
2668
- for (const v2 of vertices) {
2669
- if (Math.abs(v2.x - x) < TOLERANCE && Math.abs(v2.y - y) < TOLERANCE) {
2670
- return v2;
2671
- }
2672
- }
2673
- const v = { x, y, id: vertices.length, outgoing: [] };
2674
- vertices.push(v);
2675
- return v;
2676
- }
2677
- const halfEdges = [];
2678
- for (const seg of segments) {
2679
- const v1 = findOrCreateVertex(seg.startX, seg.startY);
2680
- const v2 = findOrCreateVertex(seg.endX, seg.endY);
2681
- if (v1 === v2) continue;
2682
- const isDuplicate = v1.outgoing.some((he) => he.to === v2);
2683
- if (isDuplicate) continue;
2684
- const he1 = { from: v1, to: v2, sourceId: seg.id };
2685
- const he2 = { from: v2, to: v1, sourceId: seg.id };
2686
- he1.twin = he2;
2687
- he2.twin = he1;
2688
- he1.visited = false;
2689
- he2.visited = false;
2690
- v1.outgoing.push(he1);
2691
- v2.outgoing.push(he2);
2692
- halfEdges.push(he1, he2);
2693
- }
2694
- for (const v of vertices) {
2695
- v.outgoing.sort((a, b) => {
2696
- const angleA = Math.atan2(a.to.y - v.y, a.to.x - v.x);
2697
- const angleB = Math.atan2(b.to.y - v.y, b.to.x - v.x);
2698
- return angleA - angleB;
2699
- });
2700
- }
2701
- for (const he of halfEdges) {
2702
- const v = he.to;
2703
- const twinIdx = v.outgoing.indexOf(he.twin);
2704
- if (twinIdx === -1) {
2705
- he.next = he.twin;
2706
- continue;
2707
- }
2708
- const prevIdx = (twinIdx - 1 + v.outgoing.length) % v.outgoing.length;
2709
- he.next = v.outgoing[prevIdx];
2710
- }
2711
- return { vertices, halfEdges };
2712
- }
2713
- function traceFaces(halfEdges) {
2714
- const faces = [];
2715
- for (const startHe of halfEdges) {
2716
- if (startHe.visited) continue;
2717
- const polygon = [];
2718
- let current = startHe;
2719
- let count = 0;
2720
- do {
2721
- current.visited = true;
2722
- polygon.push({ x: current.from.x, y: current.from.y });
2723
- current = current.next;
2724
- count++;
2725
- } while (current !== startHe && count < MAX_FACE_EDGES);
2726
- if (count >= MAX_FACE_EDGES) continue;
2727
- let signedArea = 0;
2728
- for (let i = 0; i < polygon.length; i++) {
2729
- const j = (i + 1) % polygon.length;
2730
- signedArea += polygon[i].x * polygon[j].y;
2731
- signedArea -= polygon[j].x * polygon[i].y;
2732
- }
2733
- signedArea /= 2;
2734
- faces.push({ polygon, signedArea });
2735
- }
2736
- return faces;
2737
- }
2738
- function pointInPolygon(px, py, polygon) {
2739
- let crossings = 0;
2740
- for (let i = 0; i < polygon.length; i++) {
2741
- const j = (i + 1) % polygon.length;
2742
- const yi = polygon[i].y;
2743
- const yj = polygon[j].y;
2744
- const xi = polygon[i].x;
2745
- const xj = polygon[j].x;
2746
- if (yi <= py && py < yj || yj <= py && py < yi) {
2747
- const t = (py - yi) / (yj - yi);
2748
- const xIntersect = xi + t * (xj - xi);
2749
- if (px < xIntersect) crossings++;
2750
- }
2751
- }
2752
- return crossings % 2 === 1;
2753
- }
2754
- function writeSvg(levelPath, matchedSpaces) {
2755
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2756
- for (const face of matchedSpaces.values()) {
2757
- for (const p of face.polygon) {
2758
- minX = Math.min(minX, p.x);
2759
- minY = Math.min(minY, p.y);
2760
- maxX = Math.max(maxX, p.x);
2761
- maxY = Math.max(maxY, p.y);
2762
- }
2763
- }
2764
- const pad = Math.max(maxX - minX, maxY - minY) * 0.02;
2765
- const vbX = (minX - pad).toFixed(3);
2766
- const vbY = (-(maxY + pad)).toFixed(3);
2767
- const vbW = (maxX - minX + pad * 2).toFixed(3);
2768
- const vbH = (maxY - minY + pad * 2).toFixed(3);
2769
- const lines = [
2770
- '<?xml version="1.0" encoding="utf-8"?>',
2771
- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vbX} ${vbY} ${vbW} ${vbH}">`,
2772
- ' <g transform="scale(1,-1)">'
2773
- ];
2774
- for (const [spaceId, face] of matchedSpaces) {
2775
- const pointsStr = face.polygon.map((p) => `${p.x.toFixed(3)},${p.y.toFixed(3)}`).join(" ");
2776
- lines.push(` <polygon id="${spaceId}" points="${pointsStr}" />`);
2777
- }
2778
- lines.push(" </g>");
2779
- lines.push("</svg>");
2780
- writeFileSync2(join6(levelPath, "space.svg"), lines.join("\n"));
2781
- }
2782
-
2783
- // src/build/geometry-warnings.ts
2784
- init_registry();
2785
- init_fs();
2786
- init_csv();
2787
- init_svg();
2788
- import { existsSync as existsSync6 } from "fs";
2789
- import { join as join7 } from "path";
2790
- var TOLERANCE2 = 0.01;
2791
- var BOUNDARY_TABLES2 = ["wall", "structure_wall", "curtain_wall", "room_separator"];
2792
- function validateGeometry(dir) {
2793
- const warnings = [];
2794
- const registry = buildRegistry(getSpecDir());
2795
- const layout = discoverLayout(dir);
2796
- const allDirs = [
2797
- { name: "global", path: layout.globalDir },
2798
- ...layout.levelDirs
2799
- ];
2800
- const wallGeometries = /* @__PURE__ */ new Map();
2801
- for (const d of allDirs) {
2802
- if (!existsSync6(d.path)) continue;
2803
- for (const table of ["wall", "structure_wall", "curtain_wall"]) {
2804
- const svgPath = join7(d.path, `${table}.svg`);
2805
- if (!existsSync6(svgPath)) continue;
2806
- try {
2807
- const svg = parseSvgFile(svgPath);
2808
- for (const el of svg.elements) {
2809
- if (el.tag !== "path") continue;
2810
- const geo = extractLineGeometry(el);
2811
- wallGeometries.set(el.id, { length: geo.length });
2812
- }
2813
- } catch {
2814
- }
2815
- }
2816
- }
2817
- for (const d of [...layout.levelDirs]) {
2818
- if (!existsSync6(d.path)) continue;
2819
- warnings.push(...validateLineConnectivity(d));
2820
- warnings.push(...validateHostedBounds(d, wallGeometries));
2821
- warnings.push(...validateHostedOverlap(d));
2822
- }
2823
- return warnings;
2824
- }
2825
- function validateLineConnectivity(levelDir) {
2826
- const warnings = [];
2827
- const endpoints = [];
2828
- const segments = [];
2829
- for (const table of BOUNDARY_TABLES2) {
2830
- const svgPath = join7(levelDir.path, `${table}.svg`);
2831
- if (!existsSync6(svgPath)) continue;
2832
- try {
2833
- const svg = parseSvgFile(svgPath);
2834
- for (const el of svg.elements) {
2835
- if (el.tag !== "path") continue;
2836
- const geo = extractLineGeometry(el);
2837
- endpoints.push({ x: geo.start_x, y: geo.start_y, side: "start", elementId: el.id, table });
2838
- endpoints.push({ x: geo.end_x, y: geo.end_y, side: "end", elementId: el.id, table });
2839
- segments.push({ start_x: geo.start_x, start_y: geo.start_y, end_x: geo.end_x, end_y: geo.end_y, elementId: el.id, table });
2840
- }
2841
- } catch {
2842
- }
2843
- }
2844
- for (const ep of endpoints) {
2845
- const hasEndpointNeighbor = endpoints.some(
2846
- (other) => other !== ep && !(other.elementId === ep.elementId && other.table === ep.table) && Math.abs(other.x - ep.x) < TOLERANCE2 && Math.abs(other.y - ep.y) < TOLERANCE2
2847
- );
2848
- if (hasEndpointNeighbor) continue;
2849
- const hasTJunction = segments.some((seg) => {
2850
- if (seg.elementId === ep.elementId && seg.table === ep.table) return false;
2851
- return pointOnSegment(ep.x, ep.y, seg.start_x, seg.start_y, seg.end_x, seg.end_y, TOLERANCE2);
2852
- });
2853
- if (hasTJunction) continue;
2854
- let nearestDist = Infinity;
2855
- let nearestId = "";
2856
- let nearestSide = "";
2857
- for (const other of endpoints) {
2858
- if (other === ep || other.elementId === ep.elementId && other.table === ep.table) continue;
2859
- const dx = other.x - ep.x;
2860
- const dy = other.y - ep.y;
2861
- const dist2 = Math.sqrt(dx * dx + dy * dy);
2862
- if (dist2 < nearestDist) {
2863
- nearestDist = dist2;
2864
- nearestId = other.elementId;
2865
- nearestSide = other.side;
2866
- }
2867
- }
2868
- const nearestInfo = nearestDist < Infinity ? ` (nearest: ${nearestId} ${nearestSide}, distance ${nearestDist.toFixed(3)}m)` : "";
2869
- warnings.push(
2870
- `[warn] ${levelDir.name}/${ep.table}.svg ${ep.elementId} ${ep.side} (${ep.x.toFixed(3)}, ${ep.y.toFixed(3)}) has no connected line element${nearestInfo}`
2871
- );
2872
- }
2873
- return warnings;
2874
- }
2875
- function pointOnSegment(px, py, ax, ay, bx, by, tol) {
2876
- const dx = bx - ax;
2877
- const dy = by - ay;
2878
- const lenSq = dx * dx + dy * dy;
2879
- if (lenSq < tol * tol) return false;
2880
- const t = ((px - ax) * dx + (py - ay) * dy) / lenSq;
2881
- if (t < -tol || t > 1 + tol) return false;
2882
- const clampedT = Math.max(0, Math.min(1, t));
2883
- const closestX = ax + clampedT * dx;
2884
- const closestY = ay + clampedT * dy;
2885
- const distSq = (px - closestX) * (px - closestX) + (py - closestY) * (py - closestY);
2886
- return distSq < tol * tol;
2887
- }
2888
- function validateHostedBounds(levelDir, wallGeometries) {
2889
- const warnings = [];
2890
- for (const tableName of ["door", "window"]) {
2891
- const csvPath = join7(levelDir.path, `${tableName}.csv`);
2892
- if (!existsSync6(csvPath)) continue;
2893
- const csv = readCsv(csvPath);
2894
- for (let i = 0; i < csv.rows.length; i++) {
2895
- const row = csv.rows[i];
2896
- const hostId = row.host_id;
2897
- const position = parseFloat(row.position ?? "");
2898
- const width = parseFloat(row.width ?? "");
2899
- if (!hostId || isNaN(position) || isNaN(width)) continue;
2900
- const wallGeo = wallGeometries.get(hostId);
2901
- if (!wallGeo) continue;
2902
- const halfWidth = width / 2;
2903
- if (position - halfWidth < -TOLERANCE2) {
2904
- warnings.push(
2905
- `[warn] ${levelDir.name}/${tableName}.csv:${i + 2} ${row.id} extends before host ${hostId} start: position(${position}) - width/2(${halfWidth.toFixed(3)}) = ${(position - halfWidth).toFixed(3)}m`
2906
- );
2907
- }
2908
- if (position + halfWidth > wallGeo.length + TOLERANCE2) {
2909
- warnings.push(
2910
- `[warn] ${levelDir.name}/${tableName}.csv:${i + 2} ${row.id} extends past host ${hostId} end: position(${position}) + width/2(${halfWidth.toFixed(3)}) = ${(position + halfWidth).toFixed(3)}m > wall length ${wallGeo.length.toFixed(3)}m`
2911
- );
2912
- }
2913
- }
2914
- }
2915
- return warnings;
2916
- }
2917
- function validateHostedOverlap(levelDir) {
2918
- const warnings = [];
2919
- const entries = [];
2920
- for (const tableName of ["door", "window", "opening"]) {
2921
- const csvPath = join7(levelDir.path, `${tableName}.csv`);
2922
- if (!existsSync6(csvPath)) continue;
2923
- const csv = readCsv(csvPath);
2924
- for (let i = 0; i < csv.rows.length; i++) {
2925
- const row = csv.rows[i];
2926
- const hostId = row.host_id;
2927
- const position = parseFloat(row.position ?? "");
2928
- const width = parseFloat(row.width ?? "");
2929
- if (!hostId || isNaN(position) || isNaN(width)) continue;
2930
- entries.push({ id: row.id, hostId, position, width, tableName, row: i + 2 });
2931
- }
2932
- }
2933
- const byHost = /* @__PURE__ */ new Map();
2934
- for (const entry of entries) {
2935
- const list = byHost.get(entry.hostId) ?? [];
2936
- list.push(entry);
2937
- byHost.set(entry.hostId, list);
2938
- }
2939
- for (const [hostId, group] of byHost) {
2940
- if (group.length < 2) continue;
2941
- group.sort((a, b) => a.position - b.position);
2942
- for (let i = 0; i < group.length; i++) {
2943
- for (let j = i + 1; j < group.length; j++) {
2944
- const a = group[i];
2945
- const b = group[j];
2946
- const aEnd = a.position + a.width / 2;
2947
- const bStart = b.position - b.width / 2;
2948
- if (aEnd > bStart + TOLERANCE2) {
2949
- warnings.push(
2950
- `[warn] ${levelDir.name}/ ${a.id} and ${b.id} overlap on ${hostId} (${a.id}: ${(a.position - a.width / 2).toFixed(3)}\u2013${aEnd.toFixed(3)}m, ${b.id}: ${bStart.toFixed(3)}\u2013${(b.position + b.width / 2).toFixed(3)}m)`
2951
- );
2952
- }
2953
- }
2954
- }
2955
- }
2956
- return warnings;
2957
- }
2958
-
2959
- // src/build/resolve-hosted-coords.ts
2960
- init_svg();
2961
- init_csv();
2962
- init_fs();
2963
- import { existsSync as existsSync7 } from "fs";
2964
- import { join as join8 } from "path";
2965
- var TOLERANCE3 = 0.05;
2966
- var HOSTED_TABLES = ["door", "window", "opening"];
2967
- function resolveHostedCoords(dir) {
2968
- const issues = [];
2969
- const layout = discoverLayout(dir);
2970
- const allDirs = [
2971
- { name: "global", path: layout.globalDir },
2972
- ...layout.levelDirs
2973
- ];
2974
- for (const d of allDirs) {
2975
- if (!existsSync7(d.path)) continue;
2976
- const files = listFiles(d.path);
2977
- const walls = [];
2978
- for (const table of ["wall", "structure_wall", "curtain_wall"]) {
2979
- const svgPath = join8(d.path, `${table}.svg`);
2980
- if (!existsSync7(svgPath)) continue;
2981
- try {
2982
- const svg = parseSvgFile(svgPath);
2983
- for (const el of svg.elements) {
2984
- if (el.tag !== "path") continue;
2985
- const geo = extractLineGeometry(el);
2986
- walls.push({
2987
- id: el.id,
2988
- start_x: geo.start_x,
2989
- start_y: geo.start_y,
2990
- end_x: geo.end_x,
2991
- end_y: geo.end_y,
2992
- length: geo.length
2993
- });
2994
- }
2995
- } catch {
2996
- }
2997
- }
2998
- if (walls.length === 0) continue;
2999
- for (const table of HOSTED_TABLES) {
3000
- const csvPath = join8(d.path, `${table}.csv`);
3001
- if (!files.includes(`${table}.csv`)) continue;
3002
- const csv = readCsv(csvPath);
3003
- const hasHostX = csv.headers.includes("host_x");
3004
- const hasHostY = csv.headers.includes("host_y");
3005
- if (!hasHostX || !hasHostY) continue;
3006
- let modified = false;
3007
- for (let i = 0; i < csv.rows.length; i++) {
3008
- const row = csv.rows[i];
3009
- const hostX = parseFloat(row.host_x ?? "");
3010
- const hostY = parseFloat(row.host_y ?? "");
3011
- if (isNaN(hostX) || isNaN(hostY)) continue;
3012
- const existingPosition = parseFloat(row.position ?? "");
3013
- if (!isNaN(existingPosition) && row.position !== "") continue;
3014
- const match = findNearestWall(hostX, hostY, walls, row.host_id);
3015
- if (!match) {
3016
- issues.push(
3017
- `${d.name}/${table}.csv:${i + 2} ${row.id} host_x=${hostX}, host_y=${hostY} \u2014 no wall found within ${TOLERANCE3}m`
3018
- );
3019
- continue;
3020
- }
3021
- row.position = match.position.toFixed(4);
3022
- if (!row.host_id || row.host_id === "") {
3023
- row.host_id = match.wallId;
3024
- }
3025
- modified = true;
3026
- }
3027
- if (modified) {
3028
- const cleanHeaders = csv.headers.filter((h) => h !== "host_x" && h !== "host_y");
3029
- if (!cleanHeaders.includes("host_id")) {
3030
- const idIdx = cleanHeaders.indexOf("id");
3031
- cleanHeaders.splice(idIdx + 1, 0, "host_id");
3032
- }
3033
- if (!cleanHeaders.includes("position")) {
3034
- const hostIdx = cleanHeaders.indexOf("host_id");
3035
- cleanHeaders.splice(hostIdx + 1, 0, "position");
3036
- }
3037
- const cleanRows = csv.rows.map((row) => {
3038
- const clean = {};
3039
- for (const h of cleanHeaders) {
3040
- if (row[h] !== void 0) clean[h] = row[h];
3041
- }
3042
- return clean;
3043
- });
3044
- writeCsv(csvPath, { headers: cleanHeaders, rows: cleanRows });
3045
- }
3046
- }
3047
- }
3048
- return issues;
3049
- }
3050
- function findNearestWall(px, py, walls, preferredHostId) {
3051
- let bestWallId = "";
3052
- let bestPosition = 0;
3053
- let bestDist = Infinity;
3054
- for (const wall of walls) {
3055
- const dx = wall.end_x - wall.start_x;
3056
- const dy = wall.end_y - wall.start_y;
3057
- const lenSq = dx * dx + dy * dy;
3058
- if (lenSq < 1e-10) continue;
3059
- const t = ((px - wall.start_x) * dx + (py - wall.start_y) * dy) / lenSq;
3060
- const clampedT = Math.max(0, Math.min(1, t));
3061
- const closestX = wall.start_x + clampedT * dx;
3062
- const closestY = wall.start_y + clampedT * dy;
3063
- const dist2 = Math.sqrt((px - closestX) ** 2 + (py - closestY) ** 2);
3064
- if (preferredHostId && preferredHostId !== "") {
3065
- if (wall.id === preferredHostId) {
3066
- return { wallId: wall.id, position: clampedT * wall.length };
3067
- }
3068
- continue;
3069
- }
3070
- if (dist2 < bestDist) {
3071
- bestDist = dist2;
3072
- bestWallId = wall.id;
3073
- bestPosition = clampedT * wall.length;
3074
- }
3075
- }
3076
- if (bestDist > TOLERANCE3 && !preferredHostId) return null;
3077
- if (!bestWallId) return null;
3078
- return { wallId: bestWallId, position: bestPosition };
3079
- }
29
+ import { resolve } from "path";
3080
30
 
3081
- // src/build/snap-endpoints.ts
3082
- init_svg();
3083
- init_csv();
3084
- init_fs();
3085
- import { existsSync as existsSync8, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
3086
- import { join as join9 } from "path";
3087
- var MIN_SNAP_TOLERANCE = 0.1;
3088
- var BOUNDARY_TABLES3 = ["wall", "structure_wall", "curtain_wall", "room_separator"];
3089
- var WALL_TABLES_WITH_THICKNESS = ["wall", "structure_wall", "curtain_wall"];
3090
- function snapEndpoints(dir) {
3091
- const layout = discoverLayout(dir);
3092
- const allDirs = [
3093
- { name: "global", path: layout.globalDir },
3094
- ...layout.levelDirs
3095
- ];
3096
- let totalSnapped = 0;
3097
- const snapTolerance = computeSnapTolerance(allDirs);
3098
- const allEndpoints = [];
3099
- for (const d of allDirs) {
3100
- if (!existsSync8(d.path)) continue;
3101
- for (const table of BOUNDARY_TABLES3) {
3102
- const svgPath = join9(d.path, `${table}.svg`);
3103
- if (!existsSync8(svgPath)) continue;
3104
- try {
3105
- const svg = parseSvgFile(svgPath);
3106
- for (const el of svg.elements) {
3107
- if (el.tag !== "path") continue;
3108
- const geo = extractLineGeometry(el);
3109
- allEndpoints.push({ point: { x: geo.start_x, y: geo.start_y }, table, elementId: el.id, side: "start", levelDir: d.name, levelPath: d.path });
3110
- allEndpoints.push({ point: { x: geo.end_x, y: geo.end_y }, table, elementId: el.id, side: "end", levelDir: d.name, levelPath: d.path });
3111
- }
3112
- } catch {
3113
- }
3114
- }
3115
- }
3116
- if (allEndpoints.length === 0) return 0;
3117
- const clusters = clusterEndpoints(allEndpoints, snapTolerance);
3118
- const snapMap = /* @__PURE__ */ new Map();
3119
- for (const cluster of clusters) {
3120
- if (cluster.length <= 1) continue;
3121
- const canonical = pickCanonical(cluster);
3122
- for (const ep of cluster) {
3123
- const dx = Math.abs(ep.point.x - canonical.x);
3124
- const dy = Math.abs(ep.point.y - canonical.y);
3125
- if (dx > 1e-6 || dy > 1e-6) {
3126
- const key = `${ep.levelPath}:${ep.table}:${ep.elementId}:${ep.side}`;
3127
- snapMap.set(key, canonical);
3128
- totalSnapped++;
3129
- }
3130
- }
3131
- }
3132
- if (snapMap.size === 0) return 0;
3133
- for (const d of allDirs) {
3134
- if (!existsSync8(d.path)) continue;
3135
- for (const table of BOUNDARY_TABLES3) {
3136
- const svgPath = join9(d.path, `${table}.svg`);
3137
- if (!existsSync8(svgPath)) continue;
3138
- let svgText = readFileSync5(svgPath, "utf-8");
3139
- let modified = false;
3140
- try {
3141
- const svg = parseSvgFile(svgPath);
3142
- for (const el of svg.elements) {
3143
- if (el.tag !== "path") continue;
3144
- const geo = extractLineGeometry(el);
3145
- const startKey = `${d.path}:${table}:${el.id}:start`;
3146
- const endKey = `${d.path}:${table}:${el.id}:end`;
3147
- const newStart = snapMap.get(startKey);
3148
- const newEnd = snapMap.get(endKey);
3149
- if (!newStart && !newEnd) continue;
3150
- const sx = newStart?.x ?? geo.start_x;
3151
- const sy = newStart?.y ?? geo.start_y;
3152
- const ex = newEnd?.x ?? geo.end_x;
3153
- const ey = newEnd?.y ?? geo.end_y;
3154
- const oldD = el.attrs.d;
3155
- const newD = `M ${fmtNum(sx)} ${fmtNum(sy)} L ${fmtNum(ex)} ${fmtNum(ey)}`;
3156
- if (oldD && oldD !== newD) {
3157
- svgText = replacePathD(svgText, el.id, oldD, newD);
3158
- modified = true;
3159
- }
3160
- }
3161
- } catch {
3162
- continue;
3163
- }
3164
- if (modified) {
3165
- writeFileSync3(svgPath, svgText, "utf-8");
3166
- }
3167
- }
3168
- }
3169
- return totalSnapped;
3170
- }
3171
- function computeSnapTolerance(dirs) {
3172
- let maxThickness = 0;
3173
- for (const d of dirs) {
3174
- if (!existsSync8(d.path)) continue;
3175
- for (const table of WALL_TABLES_WITH_THICKNESS) {
3176
- const csvPath = join9(d.path, `${table}.csv`);
3177
- if (!existsSync8(csvPath)) continue;
3178
- try {
3179
- const csv = readCsv(csvPath);
3180
- for (const row of csv.rows) {
3181
- const t = parseFloat(row.thickness ?? "0");
3182
- if (t > maxThickness) maxThickness = t;
3183
- }
3184
- } catch {
3185
- }
3186
- }
3187
- }
3188
- const tolerance = Math.max(MIN_SNAP_TOLERANCE, maxThickness);
3189
- return tolerance;
3190
- }
3191
- function clusterEndpoints(endpoints, tolerance) {
3192
- const visited = /* @__PURE__ */ new Set();
3193
- const clusters = [];
3194
- for (let i = 0; i < endpoints.length; i++) {
3195
- if (visited.has(i)) continue;
3196
- const cluster = [endpoints[i]];
3197
- visited.add(i);
3198
- let expanded = true;
3199
- while (expanded) {
3200
- expanded = false;
3201
- for (let j = 0; j < endpoints.length; j++) {
3202
- if (visited.has(j)) continue;
3203
- for (const member of cluster) {
3204
- if (dist(member.point, endpoints[j].point) < tolerance) {
3205
- cluster.push(endpoints[j]);
3206
- visited.add(j);
3207
- expanded = true;
3208
- break;
3209
- }
3210
- }
3211
- }
3212
- }
3213
- clusters.push(cluster);
3214
- }
3215
- return clusters;
3216
- }
3217
- function pickCanonical(cluster) {
3218
- const counts = /* @__PURE__ */ new Map();
3219
- for (const ep of cluster) {
3220
- const key = `${fmtNum(ep.point.x)},${fmtNum(ep.point.y)}`;
3221
- const entry = counts.get(key);
3222
- if (entry) {
3223
- entry.count++;
3224
- } else {
3225
- counts.set(key, { point: ep.point, count: 1 });
31
+ // src/furniture/catalog-text.ts
32
+ var size = (s) => s.map((v) => +v.toFixed(3)).join("\xD7");
33
+ function furnitureCatalogLines() {
34
+ const lines = [" Families (default size_x\xD7size_y\xD7height m; variants with their own default size):"];
35
+ for (const cat of CATEGORY_ORDER) {
36
+ const fams = furnitureFamilies().filter((f) => f.category === cat);
37
+ if (fams.length === 0) continue;
38
+ lines.push(` ${CATEGORY_LABELS[cat].en}:`);
39
+ for (const f of fams) {
40
+ const tags = [];
41
+ if (f.wallBacked) tags.push("back to wall");
42
+ if (f.baseOffset) tags.push(`base_offset ${f.baseOffset}`);
43
+ const variants = (f.variants ?? []).map((v, i) => `${v.id}${v.size ? ` ${size(v.size)}` : ""}${i === 0 ? " (default)" : ""}`);
44
+ lines.push(` ${f.id} ${size(f.size)}${tags.length ? ` [${tags.join(", ")}]` : ""}${variants.length ? ` variants: ${variants.join(", ")}` : ""}`);
3226
45
  }
3227
46
  }
3228
- let best = { point: cluster[0].point, count: 0 };
3229
- for (const entry of counts.values()) {
3230
- if (entry.count > best.count) best = entry;
3231
- }
3232
- return best.point;
3233
- }
3234
- function dist(a, b) {
3235
- return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
3236
- }
3237
- function fmtNum(n) {
3238
- const s = n.toFixed(4);
3239
- return s.replace(/\.?0+$/, "") || "0";
3240
- }
3241
- function replacePathD(svgText, id, oldD, newD) {
3242
- const escaped = oldD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3243
- const idEscaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3244
- const pathRegex = new RegExp(`(<path[^>]*\\bid="${idEscaped}"[^>]*\\bd=")${escaped}(")`);
3245
- if (pathRegex.test(svgText)) {
3246
- return svgText.replace(pathRegex, `$1${newD}$2`);
3247
- }
3248
- const pathRegex2 = new RegExp(`(<path[^>]*\\bd=")${escaped}("[^>]*\\bid="${idEscaped}")`);
3249
- if (pathRegex2.test(svgText)) {
3250
- return svgText.replace(pathRegex2, `$1${newD}$2`);
3251
- }
3252
- return svgText;
47
+ return lines;
3253
48
  }
3254
49
 
3255
- // src/build/index.ts
3256
- function build(dir) {
3257
- const snapped = snapEndpoints(dir);
3258
- const resolveIssues = resolveHostedCoords(dir);
3259
- const issues = [...resolveIssues, ...validate(dir)];
3260
- const warnings = validateGeometry(dir);
3261
- const artifacts = [];
3262
- const layout = discoverLayout(dir);
3263
- for (const levelDir of layout.levelDirs) {
3264
- const spaceCsvPath = join10(levelDir.path, "space.csv");
3265
- if (!existsSync9(spaceCsvPath)) continue;
3266
- const result = computeSpaceBoundaries(levelDir, layout.globalDir);
3267
- warnings.push(...result.warnings);
3268
- if (result.svgWritten) {
3269
- artifacts.push(`${levelDir.name}/space.svg`);
3270
- }
3271
- }
3272
- return { issues, warnings, artifacts, snappedEndpoints: snapped };
50
+ // src/schema/schema-text.ts
51
+ var INDEX = [
52
+ ["Project (global/)", [
53
+ ["level", "storey: number, elevation (absolute)"],
54
+ ["grid", "axis line: number, start/end x y"],
55
+ ["view", "section / elevation / 3D view: view_type, cut line"],
56
+ ["underlay", "tracing image / PDF under a level: level_id, file"],
57
+ ["mesh", "imported GLB: category, mesh_file"],
58
+ ["sheet", "drawing sheet: number, paper"],
59
+ ["sheet_viewport", "view placed on a sheet: sheet_id, view_type, x y"]
60
+ ]],
61
+ ["Architecture", [
62
+ ["wall", "line: thickness, type_id, base_offset/top_level_id/top_offset"],
63
+ ["curtain_wall", "line: u/v grids, panels, mullions"],
64
+ ["column", "point: shape, size_x/size_y"],
65
+ ["slab", "polygon floor, top = level + base_offset: thickness"],
66
+ ["roof", "polygon: roof_type (flat/gable/hip...), slope"],
67
+ ["ceiling", "polygon: height_offset"],
68
+ ["space", "room seed point: x y, name; boundary computed"],
69
+ ["room_separator", "line splitting rooms without a wall"],
70
+ ["door", "hosted on a wall: host_id, position, width, height"],
71
+ ["window", "hosted on a wall: host_id, position, width, height, base_offset (sill)"],
72
+ ["opening", "void in a wall / slab / roof"],
73
+ ["stair", "stair container (3D); parts below"],
74
+ ["stair_run", "flight of steps: host_id (stair)"],
75
+ ["stair_landing", "landing: host_id (stair)"],
76
+ ["ramp", "3D line (start_z/end_z): width"],
77
+ ["railing", "3D path or hosted on stair / slab edge"],
78
+ ["furniture", "library component (point): family, variant, rotation"]
79
+ ]],
80
+ ["Structure", [
81
+ ["structure_wall", "line: thickness"],
82
+ ["structure_column", "point: shape, size_x/size_y or designation"],
83
+ ["structure_slab", "polygon, top = level + base_offset: thickness"],
84
+ ["beam", "3D line (absolute z = top): shape, size_x, size_y"],
85
+ ["beam_system", "parallel infill beams in a bay: spacing"],
86
+ ["brace", "3D line: shape"],
87
+ ["foundation", "pad / pile / strip / raft / pile cap: kind, thickness"]
88
+ ]],
89
+ ["MEP", [
90
+ ["duct", "3D line: shape, size_x/size_y, system_type, from/to"],
91
+ ["pipe", "3D line: shape, size_x (diameter), system_type"],
92
+ ["cable_tray", "3D line: size_x/size_y, system_type"],
93
+ ["conduit", "3D line: size_x (diameter)"],
94
+ ["equipment", "point: equipment_type (AHU, pump, panel...); ports in connector"],
95
+ ["terminal", "point: terminal_type (diffuser, sink, WC, light...)"],
96
+ ["mep_node", "elbow / tee / fitting joining runs: kind"],
97
+ ["connector", "port on equipment / terminal / mep_node: host_id, name"],
98
+ ["mep_system", "system lookup: system_type"],
99
+ ["circuit", "electrical circuit from a panel: host_id"]
100
+ ]],
101
+ ["Types (global/; instances use type_id)", [
102
+ ["wall_type", "layers in type_layer"],
103
+ ["slab_type", "layered"],
104
+ ["roof_type", "layered"],
105
+ ["ceiling_type", "layered"],
106
+ ["type_layer", "one layer: type_id, seq, function, thickness"],
107
+ ["door_type", "width, height, operation"],
108
+ ["window_type", "width, height, operation, u_value"],
109
+ ["curtain_wall_type", "u/v spacing, mullions"],
110
+ ["column_type", "shape, sizes"],
111
+ ["beam_type", "shape, sizes"],
112
+ ["foundation_type", "kind, sizes"],
113
+ ["furniture_type", "family, variant, sizes"],
114
+ ["railing_type", "height, rails, infill"]
115
+ ]],
116
+ ["Annotation (level dirs)", [
117
+ ["dimension", "linear dimension: start/end x y"],
118
+ ["text_note", "text at x y"],
119
+ ["tag", "label of an element: host_id"],
120
+ ["model_group", "group instance: name, x y"]
121
+ ]]
122
+ ];
123
+ function schemaIndexLines(registry) {
124
+ const lines = ["Tables. Run `schema <table>` for exact columns, types, enums, references."];
125
+ const seen = /* @__PURE__ */ new Set();
126
+ for (const [group, tables] of INDEX) {
127
+ const present = tables.filter(([t]) => registry.has(t));
128
+ if (present.length === 0) continue;
129
+ lines.push(`${group}:`);
130
+ for (const [t, purpose] of present) {
131
+ seen.add(t);
132
+ lines.push(` ${t}: ${purpose}`);
133
+ }
134
+ }
135
+ const other = [...registry.keys()].filter((t) => !seen.has(t)).sort();
136
+ if (other.length > 0) lines.push(`Other: ${other.join(", ")}`);
137
+ return lines;
138
+ }
139
+ function schemaTableLines(resolved) {
140
+ const t = resolved.name;
141
+ const lines = [`\u2500\u2500 ${t} (prefix: ${resolved.prefix}) \u2500\u2500`];
142
+ if (resolved.hostType) lines.push(` host_type: ${resolved.hostType}`);
143
+ if (resolved.typeOf) {
144
+ lines.push(` type of: ${resolved.typeOf.join(", ")} (global/ only; instances inherit shared fields they leave empty)`);
145
+ }
146
+ if (resolved.typeTable) lines.push(` type_id \u2192 ${resolved.typeTable}: empty shared fields inherit the type's values`);
147
+ const typeParams = new Set(resolved.typeTable ? typeParamFields(t) : []);
148
+ lines.push(" CSV fields:");
149
+ for (const f of resolved.csvFields) {
150
+ const tags = [];
151
+ if (f.required) tags.push(typeParams.has(f.name) ? "required unless type_id gives it" : "required");
152
+ if (f.type === "reference") tags.push(`ref:${f.reference}`);
153
+ if (f.type === "enum") tags.push(`enum:[${f.values?.join("|")}]`);
154
+ lines.push(` ${f.name}: ${f.type}${tags.length > 0 ? ` (${tags.join(", ")})` : ""}`);
155
+ }
156
+ if (resolved.computedFields.length > 0) {
157
+ lines.push(" Computed fields (derived from geometry; queryable, never written to CSV):");
158
+ for (const f of resolved.computedFields) lines.push(` ${f.name}: ${f.type}`);
159
+ }
160
+ if (t === "furniture") lines.push(...furnitureCatalogLines());
161
+ return lines;
3273
162
  }
3274
163
 
3275
164
  // src/index.ts
3276
- init_registry();
3277
- init_fs();
3278
- init_csv();
3279
- import { existsSync as existsSync18, writeFileSync as writeFileSync7 } from "fs";
3280
- import { join as join18 } from "path";
165
+ import { existsSync, writeFileSync } from "fs";
3281
166
  var program = new Command();
3282
- program.name("bimdown").description("BimDown CLI \u2014 build, query, and manage BimDown projects").version(true ? "0.4.0" : "0.0.0");
3283
- function runBuild(dir) {
3284
- const absDir = resolve2(dir);
3285
- const result = build(absDir);
167
+ program.name("bimdown").description("BimDown CLI \u2014 build, query, and manage BimDown projects").version(true ? "0.5.1" : "0.0.0");
168
+ var WARN_LIST_LIMIT = 20;
169
+ function runBuild(dir, opts = {}, readOnly = false) {
170
+ const absDir = resolve(dir);
171
+ const result = readOnly ? validateOnly(absDir) : build(absDir);
3286
172
  if (result.issues.length > 0) {
3287
173
  for (const issue of result.issues) {
3288
174
  console.log(issue);
@@ -3292,16 +178,42 @@ ${result.issues.length} issue(s) found.`);
3292
178
  process.exitCode = 1;
3293
179
  }
3294
180
  if (result.warnings.length > 0) {
3295
- for (const w of result.warnings) {
181
+ const shown = opts.verbose ? result.warnings : result.warnings.slice(0, WARN_LIST_LIMIT);
182
+ for (const w of shown) {
3296
183
  console.log(w);
3297
184
  }
185
+ if (shown.length < result.warnings.length) {
186
+ console.log(`... ${result.warnings.length - shown.length} more (use --verbose to list all)`);
187
+ }
188
+ console.log(`
189
+ ${result.warnings.length} warning(s). Warnings are advisory; issues are errors.`);
190
+ }
191
+ if (result.roomIssues.length > 0) {
192
+ const label = { shared: "share one enclosed area", contains: "encloses", unbounded: "has no enclosing boundary" };
3298
193
  console.log(`
3299
- ${result.warnings.length} warning(s).`);
194
+ Room problems (${result.roomIssues.length}): derived room areas are wrong until fixed`);
195
+ const shown = opts.verbose ? result.roomIssues : result.roomIssues.slice(0, WARN_LIST_LIMIT);
196
+ for (const r of shown) {
197
+ const text = r.kind === "contains" ? `${r.spaceIds.join(", ")} ${label.contains} ${(r.inside ?? []).join(", ")}` : `${r.spaceIds.join(", ")} ${label[r.kind]}`;
198
+ console.log(` ${r.level}: ${text}`);
199
+ }
200
+ if (shown.length < result.roomIssues.length) {
201
+ console.log(` ... ${result.roomIssues.length - shown.length} more (use --verbose to list all)`);
202
+ }
203
+ }
204
+ if (result.snaps.length > 0) {
205
+ console.log(readOnly ? `${result.snaps.length} endpoint(s) closer than 5 cm (build snaps them):` : `Snapped ${result.snaps.length} endpoint(s) closer than 5 cm:`);
206
+ const shown = opts.verbose ? result.snaps : result.snaps.slice(0, WARN_LIST_LIMIT);
207
+ for (const s of shown) {
208
+ console.log(` ${s.level}/${s.table} ${s.elementId} ${s.side} (${s.from.x.toFixed(3)}, ${s.from.y.toFixed(3)}) -> (${s.to.x.toFixed(3)}, ${s.to.y.toFixed(3)})`);
209
+ }
210
+ if (shown.length < result.snaps.length) console.log(` ... ${result.snaps.length - shown.length} more`);
3300
211
  }
3301
- if (result.snappedEndpoints > 0) {
3302
- console.log(`Snapped ${result.snappedEndpoints} endpoint(s).`);
212
+ if (result.hints.length > 0) {
213
+ console.log();
214
+ for (const h of result.hints) console.log(h);
3303
215
  }
3304
- if (result.artifacts.length > 0) {
216
+ if (result.artifacts.length > 0 && !readOnly) {
3305
217
  console.log(`
3306
218
  Generated: ${result.artifacts.join(", ")}`);
3307
219
  }
@@ -3309,47 +221,47 @@ Generated: ${result.artifacts.join(", ")}`);
3309
221
  console.log("Build successful. No issues found.");
3310
222
  }
3311
223
  }
3312
- program.command("build").argument("<dir>", "BimDown project directory").description("Build a BimDown project (validate + compute space boundaries)").action((dir) => runBuild(dir));
3313
- program.command("validate").argument("<dir>", "BimDown project directory").description("Alias for build").action((dir) => runBuild(dir));
224
+ program.command("build").argument("<dir>", "BimDown project directory").option("--verbose", "List every warning and snapped endpoint").description("Build a BimDown project (validate + compute space boundaries)").action((dir, opts) => runBuild(dir, opts));
225
+ program.command("validate").argument("<dir>", "BimDown project directory").option("--verbose", "List every warning and snapped endpoint").description("Check a BimDown project like build, without writing anything").action((dir, opts) => runBuild(dir, opts, true));
3314
226
  program.command("query").argument("<dir>", "BimDown project directory").argument("<sql>", "SQL query to execute").option("--json", "Output results as JSON").description("Hydrate into DuckDB and execute a SQL query").action(async (dir, sql, opts) => {
3315
- const absDir = resolve2(dir);
3316
- const { getConnection: getConnection2, runQuery: runQuery2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
3317
- const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
3318
- const conn = await getConnection2();
227
+ const absDir = resolve(dir);
228
+ const { getConnection, runQuery, closeConnection } = await import("./engine-2TPWJVEQ.js");
229
+ const { hydrate } = await import("./hydrate-V24H7IF3.js");
230
+ const conn = await getConnection();
3319
231
  try {
3320
- await hydrate2(conn, absDir);
3321
- const result = await runQuery2(conn, sql);
232
+ await hydrate(conn, absDir);
233
+ const result = await runQuery(conn, sql);
3322
234
  if (opts.json) {
3323
235
  console.log(JSON.stringify(result.rows, jsonReplacer, 2));
3324
236
  } else {
3325
237
  printTable(result.columns, result.rows);
3326
238
  }
3327
239
  } finally {
3328
- await closeConnection2();
240
+ await closeConnection();
3329
241
  }
3330
242
  });
3331
243
  program.command("sync").argument("<dir>", "BimDown project directory").description("Hydrate, then dehydrate back (sync DuckDB changes to files)").action(async (dir) => {
3332
- const absDir = resolve2(dir);
3333
- const { getConnection: getConnection2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
3334
- const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
3335
- const { dehydrate: dehydrate2 } = await Promise.resolve().then(() => (init_dehydrate(), dehydrate_exports));
3336
- const conn = await getConnection2();
244
+ const absDir = resolve(dir);
245
+ const { getConnection, closeConnection } = await import("./engine-2TPWJVEQ.js");
246
+ const { hydrate } = await import("./hydrate-V24H7IF3.js");
247
+ const { dehydrate } = await import("./dehydrate-ZHAGOI7Q.js");
248
+ const conn = await getConnection();
3337
249
  try {
3338
- const tables = await hydrate2(conn, absDir);
250
+ const tables = await hydrate(conn, absDir);
3339
251
  console.log(`Hydrated ${tables.length} tables: ${tables.join(", ")}`);
3340
- await dehydrate2(conn, absDir);
252
+ await dehydrate(conn, absDir);
3341
253
  console.log("Sync complete \u2014 files updated.");
3342
254
  } finally {
3343
- await closeConnection2();
255
+ await closeConnection();
3344
256
  }
3345
257
  });
3346
- program.command("render").argument("<dir>", "BimDown project directory").option("-l, --level <id>", "Level to render (defaults to lv-1)", "lv-1").option("-o, --output <file>", "Output file path (defaults to render.png)", "render.png").option("-w, --width <px>", "Image width in pixels", "2048").description("Renders the BimDown project into a visual blueprint (PNG). Color legend: walls=dark navy, structural walls=slate, columns=dark filled, slabs=light grey translucent, spaces=blue translucent, stairs=orange, beams=purple. DOORS render as BOLD RED (#e63946) lines and WINDOWS as BOLD TEAL (#2a9d8f) lines cutting across their host walls. MEP: ducts=cyan, pipes=light blue, cable tray=green, conduit=teal, equipment=red fill, terminals=orange fill.").action(async (dir, opts) => {
3347
- const absDir = resolve2(dir);
3348
- const { renderLevel: renderLevel2 } = await Promise.resolve().then(() => (init_render(), render_exports));
258
+ program.command("render").argument("<dir>", "BimDown project directory").option("-l, --level <id>", "Level to render (defaults to lv-1)", "lv-1").option("-o, --output <file>", "Output file path (defaults to render.png)", "render.png").option("-w, --width <px>", "Image width in pixels", "2048").description("Renders the BimDown project into a visual blueprint (PNG). Color legend: walls=dark navy, structural walls=slate, columns=dark filled, slabs=light grey translucent (sloped floors with their slope arrow, tail dot \u2192 head), spaces=blue translucent, stairs=orange runs with treads (dashed beyond the 1.2 m plan cut), landings and an UP walking line (multi-storey stairs also on the storeys they repeat on), railings=slate lines (stair railings follow the derived path), beams/braces=thin purple dashed centerlines (overhead, drawn under walls), columns at their real section size, foundations=brown dashed outlines (pads width\xD7length, piles as circles, strips at their width, rafts/pile caps), grids=red dash-dot axes with numbered bubbles, roofs=brown outline with ridges and hips (valleys dashed) and down-slope arrows labelled with the slope, slab holes and slab openings (white with a cross; shafts also on every level they cross), wall openings=orange lines, curtain walls=light blue strips with a tick per vertical grid line (door panels open, with red swings). DOORS render as BOLD RED (#e63946) lines and WINDOWS as BOLD TEAL (#2a9d8f) lines cutting across their host walls. MEP: runs at their real width in system colours (SA blue, RA light blue, CHWS cyan, SAN brown, FP red, \u2026) with elbow / tee / reducer bodies, system + size tags, rise / drop boxes, slope arrows; terminals, equipment and valves as plan symbols. Furniture and library components draw their grey plan symbols (back edge = local +Y). Annotations (dimension/text_note/tag tables) in dark blue: dimension lines with values in mm (ft-in for imperial), text, boxed door/window tags, room tags with name/number/area.").action(async (dir, opts) => {
259
+ const absDir = resolve(dir);
260
+ const { renderLevel } = await import("./render-UEWYHPN6.js");
3349
261
  try {
3350
- const svg = renderLevel2(absDir, opts.level);
262
+ const svg = renderLevel(absDir, opts.level);
3351
263
  if (opts.output.endsWith(".svg")) {
3352
- writeFileSync7(opts.output, svg);
264
+ writeFileSync(opts.output, svg);
3353
265
  } else {
3354
266
  const sharp = (await import("sharp")).default;
3355
267
  const width = parseInt(opts.width, 10) || 2048;
@@ -3361,53 +273,68 @@ program.command("render").argument("<dir>", "BimDown project directory").option(
3361
273
  process.exitCode = 1;
3362
274
  }
3363
275
  });
3364
- program.command("info").argument("<dir>", "BimDown project directory").description("Print project summary").action((dir) => {
3365
- const absDir = resolve2(dir);
3366
- const registry = buildRegistry(getSpecDir());
3367
- const layout = discoverLayout(absDir);
3368
- const levelCsv = join18(layout.globalDir, "level.csv");
3369
- if (existsSync18(levelCsv)) {
3370
- const levels = readCsv(levelCsv);
3371
- console.log("Levels:");
3372
- for (const row of levels.rows) {
3373
- console.log(` ${row.id} ${row.name || row.number || ""} elevation=${row.elevation}`);
276
+ program.command("info").argument("<dir>", "BimDown project directory").description("Print project summary: units, levels, element counts, element types").action(async (dir) => {
277
+ const { projectInfoLines } = await import("./info-QC7YXWNX.js");
278
+ for (const l of projectInfoLines(resolve(dir))) console.log(l);
279
+ });
280
+ program.command("resolve-topology").argument("<dir>", "BimDown project directory").description("Auto-resolve MEP topology: detect coincident endpoints, generate mep_nodes, fill connectivity").action(async (dir) => {
281
+ const absDir = resolve(dir);
282
+ const { resolveTopology } = await import("./resolve-topology-AQ2RO3W3.js");
283
+ resolveTopology(absDir);
284
+ });
285
+ program.command("mep-check").argument("<dir>", "BimDown project directory").option("--json", "Print the report as JSON").option("--all", "Also list info-level findings (unused equipment ports, devices without a circuit)").description("MEP connectivity check: systems (curves, length, devices) and problems \u2014 open ends, port refs that do not resolve or whose curve end is not on the port, system / domain mismatches, disconnected devices, orphan fittings, overloaded circuits. Exit code 1 when there are warnings.").action(async (dir, opts) => {
286
+ const { mepReport, formatProblem } = await import("./mep-W4HJI363.js");
287
+ const report = mepReport(resolve(dir));
288
+ const shown = opts.all ? report.problems : report.problems.filter((p) => p.severity === "warning");
289
+ if (opts.json) {
290
+ console.log(JSON.stringify({ systems: report.systems, problems: shown }, null, 2));
291
+ } else {
292
+ console.log("Systems:");
293
+ if (report.systems.length === 0) console.log(" (no MEP curves)");
294
+ for (const s of report.systems) {
295
+ console.log(` ${s.system.padEnd(8)} ${String(s.curves).padStart(4)} curve(s) ${s.length.toFixed(1).padStart(7)} long ${s.devices} device(s) [${s.tables.join(", ")}]`);
3374
296
  }
3375
297
  console.log();
298
+ for (const p of shown) console.log(`${p.severity === "info" ? "info " : ""}${formatProblem(p)}`);
299
+ const warnings = report.problems.filter((p) => p.severity === "warning").length;
300
+ console.log(warnings === 0 ? "MEP connectivity: no problems." : `
301
+ ${warnings} connectivity problem(s).`);
3376
302
  }
3377
- const allDirs = [
3378
- { name: "global", path: layout.globalDir },
3379
- ...layout.levelDirs
3380
- ];
3381
- const totals = {};
3382
- for (const d of allDirs) {
3383
- if (!existsSync18(d.path)) continue;
3384
- const files = listFiles(d.path);
3385
- const counts = [];
3386
- for (const f of files) {
3387
- if (!f.endsWith(".csv")) continue;
3388
- const tableName = f.replace(".csv", "");
3389
- if (!registry.has(tableName)) continue;
3390
- const data = readCsv(join18(d.path, f));
3391
- counts.push(`${tableName}: ${data.rows.length}`);
3392
- totals[tableName] = (totals[tableName] ?? 0) + data.rows.length;
3393
- }
3394
- if (counts.length > 0) {
3395
- console.log(`${d.name}/ ${counts.join(", ")}`);
3396
- }
303
+ if (report.problems.some((p) => p.severity === "warning")) process.exitCode = 1;
304
+ });
305
+ function parseLengthM(s, bareM) {
306
+ const m = /^\s*([0-9]*\.?[0-9]+(?:e[-+]?\d+)?)\s*(mm|cm|m)?\s*$/i.exec(s);
307
+ if (!m) return null;
308
+ const v = Number(m[1]) * (m[2] ? { mm: 1e-3, cm: 0.01, m: 1 }[m[2].toLowerCase()] : bareM);
309
+ return Number.isFinite(v) && v >= 0 ? v : null;
310
+ }
311
+ program.command("clash").argument("<dir>", "BimDown project directory").option("--tolerance <m>", "Overlaps no deeper than this are within tolerance, not clashes: metres, or with a unit (50mm, 5cm); 0 = every overlap", "0.05").option("--clearance <mm>", "Also report MEP closer than this to MEP / structure without touching: mm, or with a unit (0 = off)", "0").option("--minor", "Also list the overlaps within tolerance").option("--level <id>", "Only MEP on this level (obstacles from every level)").option("--json", "Print the report as JSON").option("--mep-only", "Only MEP vs MEP").description("MEP clash detection: ducts / pipes / conduits / cable trays and devices against structure (high), against other MEP they do not connect to (medium), through slabs / roofs / non-structural walls with no opening (low penetration), and closer than --clearance (low). Overlaps up to --tolerance (5 cm) are modelling slack, not clashes. Exit code 0 unless the project cannot be read.").action(async (dir, opts) => {
312
+ const absDir = resolve(dir);
313
+ const tolerance = parseLengthM(opts.tolerance, 1), clearance = parseLengthM(opts.clearance, 1e-3);
314
+ if (!existsSync(absDir)) {
315
+ console.error(`No such directory: ${dir}`);
316
+ process.exitCode = 1;
317
+ return;
318
+ }
319
+ if (tolerance === null || clearance === null) {
320
+ console.error("--tolerance takes a length in metres, --clearance in mm (>= 0; or with a unit: 50mm, 5cm, 0.05m)");
321
+ process.exitCode = 1;
322
+ return;
3397
323
  }
3398
- console.log();
3399
- console.log("Totals:");
3400
- let grand = 0;
3401
- for (const [table, count] of Object.entries(totals).sort(([a], [b]) => a.localeCompare(b))) {
3402
- console.log(` ${table}: ${count}`);
3403
- grand += count;
324
+ if (tolerance > 1 && !/[a-z]$/i.test(opts.tolerance.trim())) {
325
+ console.error(`--tolerance is in metres (0.05 = 5 cm); for millimetres write ${opts.tolerance}mm`);
326
+ process.exitCode = 1;
327
+ return;
3404
328
  }
3405
- console.log(` TOTAL: ${grand}`);
3406
- });
3407
- program.command("resolve-topology").argument("<dir>", "BimDown project directory").description("Auto-resolve MEP topology: detect coincident endpoints, generate mep_nodes, fill connectivity").action(async (dir) => {
3408
- const absDir = resolve2(dir);
3409
- const { resolveTopology: resolveTopology2 } = await Promise.resolve().then(() => (init_resolve_topology(), resolve_topology_exports));
3410
- resolveTopology2(absDir);
329
+ if (opts.level && !discoverLayout(absDir).levelDirs.some((d) => d.name === opts.level) && opts.level !== "global") {
330
+ console.error(`No level directory ${opts.level} in ${dir}`);
331
+ process.exitCode = 1;
332
+ return;
333
+ }
334
+ const { clashReport, formatClashReport } = await import("./clash-load-D3LNQR6G.js");
335
+ const report = clashReport(absDir, { toleranceM: tolerance, clearanceMm: clearance * 1e3, level: opts.level, mepOnly: opts.mepOnly, minor: opts.minor });
336
+ if (opts.json) console.log(JSON.stringify(report, null, 2));
337
+ else for (const line of formatClashReport(report)) console.log(line);
3411
338
  });
3412
339
  program.command("merge").argument("<dirs...>", "Two or more BimDown project directories to merge").requiredOption("-o, --output <dir>", "Output directory for merged project").description("Merge multiple BimDown project directories into one, resolving ID conflicts").action(async (dirs, opts) => {
3413
340
  if (dirs.length < 2) {
@@ -3415,57 +342,59 @@ program.command("merge").argument("<dirs...>", "Two or more BimDown project dire
3415
342
  process.exitCode = 1;
3416
343
  return;
3417
344
  }
3418
- const absDirs = dirs.map((d) => resolve2(d));
3419
- const absOut = resolve2(opts.output);
3420
- const { merge: merge2 } = await Promise.resolve().then(() => (init_merge(), merge_exports));
3421
- await merge2(absDirs, absOut);
345
+ const absDirs = dirs.map((d) => resolve(d));
346
+ const absOut = resolve(opts.output);
347
+ const { merge } = await import("./merge-ESOPDSA5.js");
348
+ await merge(absDirs, absOut);
3422
349
  });
3423
- program.command("schema").argument("[table]", "Table name (omit for all tables)").description("Print resolved schema for a table or all tables").action((table) => {
350
+ program.command("schema").argument("[table]", "Table name (omit for a compact index of all tables)").option("--all", "Print the full schema of every table (long)").description("Print the full schema of a table, or an index of all tables").action((table, opts) => {
3424
351
  const registry = buildRegistry(getSpecDir());
352
+ if (!table && !opts.all) {
353
+ for (const l of schemaIndexLines(registry)) console.log(l);
354
+ return;
355
+ }
3425
356
  const tables = table ? [table] : [...registry.keys()].sort();
3426
357
  for (const t of tables) {
3427
358
  const resolved = registry.get(t);
3428
359
  if (!resolved) {
3429
- console.error(`Unknown table: ${t}`);
360
+ console.error(`Unknown table: ${t}. Run \`bimdown schema\` for the list of tables.`);
3430
361
  process.exitCode = 1;
3431
362
  return;
3432
363
  }
3433
- console.log(`\u2500\u2500 ${resolved.name} (prefix: ${resolved.prefix}) \u2500\u2500`);
3434
- if (resolved.hostType) {
3435
- console.log(` host_type: ${resolved.hostType}`);
3436
- }
3437
- console.log(" CSV fields:");
3438
- for (const f of resolved.csvFields) {
3439
- const tags = [];
3440
- if (f.required) tags.push("required");
3441
- if (f.type === "reference") tags.push(`ref:${f.reference}`);
3442
- if (f.type === "enum") tags.push(`enum:[${f.values?.join("|")}]`);
3443
- const tagStr = tags.length > 0 ? ` (${tags.join(", ")})` : "";
3444
- console.log(` ${f.name}: ${f.type}${tagStr}`);
3445
- }
3446
- if (resolved.computedFields.length > 0) {
3447
- console.log(" Computed fields:");
3448
- for (const f of resolved.computedFields) {
3449
- console.log(` ${f.name}: ${f.type}`);
3450
- }
3451
- }
364
+ for (const l of schemaTableLines(resolved)) console.log(l);
3452
365
  console.log();
3453
366
  }
3454
367
  });
3455
- program.command("init").argument("<dir>", "BimDown project directory").description("Initialize a new BimDown project structure").action(async (dir) => {
3456
- const absDir = resolve2(dir);
3457
- const { initProject: initProject2 } = await Promise.resolve().then(() => (init_init(), init_exports));
3458
- initProject2(absDir);
368
+ program.command("init").argument("<dir>", "BimDown project directory").option("--units <units>", "Project units: m, mm, ft or in (starter types are scaled to them)", "m").description("Initialize a new BimDown project structure").action(async (dir, opts) => {
369
+ const absDir = resolve(dir);
370
+ const { initProject, PROJECT_UNITS } = await import("./init-VWDML3UC.js");
371
+ if (!PROJECT_UNITS.includes(opts.units)) {
372
+ console.error(`Unknown units "${opts.units}" (use ${PROJECT_UNITS.join(", ")})`);
373
+ process.exitCode = 1;
374
+ return;
375
+ }
376
+ initProject(absDir, { units: opts.units });
3459
377
  });
3460
378
  program.command("diff").argument("<dirA>", "First BimDown project directory").argument("<dirB>", "Second BimDown project directory").description("Show differences between two BimDown projects").action(async (dirA, dirB) => {
3461
- const absA = resolve2(dirA);
3462
- const absB = resolve2(dirB);
3463
- const { diffProjects: diffProjects2 } = await Promise.resolve().then(() => (init_diff(), diff_exports));
3464
- diffProjects2(absA, absB);
379
+ const absA = resolve(dirA);
380
+ const absB = resolve(dirB);
381
+ const { diffProjects } = await import("./diff-T2KOK2WR.js");
382
+ diffProjects(absA, absB);
383
+ });
384
+ program.command("import-ifc").argument("<file>", "IFC file (IFC2x3 / IFC4 / IFC4x3, .ifc)").argument("<outdir>", "Directory for the new BimDown project").option("--force", "Write into a non-empty directory").option("--json <path>", "Also write the import report as JSON").description("Convert an IFC model into a BimDown project, then build it and report room problems").action(async (file, outdir, opts) => {
385
+ const { runImportIfc, printImportResult } = await import("./import-ifc-RCZSXDA6.js");
386
+ try {
387
+ const r = await runImportIfc(file, outdir, opts);
388
+ printImportResult(r, outdir);
389
+ if (r.build.issues.length > 0) process.exitCode = 1;
390
+ } catch (e) {
391
+ console.error(`import-ifc: ${e.message}`);
392
+ process.exitCode = 1;
393
+ }
3465
394
  });
3466
- program.command("publish").argument("<dir>", "BimDown project directory").option("--expires <duration>", "Expiration time (e.g. 7d, 24h, 30m)", "7d").option("--api <url>", "BimClaw API base URL").option("--name <name>", "Project name").description("Publish a BimDown project to BimClaw for sharing").action(async (dir, opts) => {
3467
- const { publish: publish2 } = await Promise.resolve().then(() => (init_publish(), publish_exports));
3468
- await publish2(dir, opts);
395
+ program.command("publish").argument("<dir>", "BimDown project directory").option("--expires <duration>", "Expiration time (e.g. 7d, 24h, 30m)", "7d").option("--api <url>", "API base URL (default https://bim.jouledown.com, or $BIMDOWN_API)").option("--name <name>", "Project name").description("Publish a BimDown project to bim.jouledown.com and get a share link").action(async (dir, opts) => {
396
+ const { publish } = await import("./publish-3TAXQCUV.js");
397
+ await publish(dir, opts);
3469
398
  });
3470
399
  program.parse();
3471
400
  function printTable(columns, rows) {