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
@@ -0,0 +1,2501 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ELEVATION_VIEW_IDS,
4
+ PANEL_KINDS,
5
+ STAIR_LIMITS,
6
+ cellKinds,
7
+ embedCircle,
8
+ getFurnitureFamily,
9
+ gridLines,
10
+ loadStairs,
11
+ parseNumberList,
12
+ parsePanels,
13
+ parseSlopeArrow,
14
+ stairCalc,
15
+ validateAnnotations,
16
+ variantIds
17
+ } from "./chunk-AYAXRYGP.js";
18
+ import {
19
+ UNIT_TO_M,
20
+ metersToProject,
21
+ projectUnits,
22
+ unitsOfMetadata
23
+ } from "./chunk-LWYIPR64.js";
24
+ import {
25
+ catalogFromRows,
26
+ effectiveRows,
27
+ layerTotal,
28
+ loadCatalog,
29
+ sameValue,
30
+ typeOfRow,
31
+ typeParamFields,
32
+ typeValues,
33
+ typeWarnings
34
+ } from "./chunk-XQU52JKB.js";
35
+ import {
36
+ mepErrors,
37
+ mepWarnings
38
+ } from "./chunk-EC5MR5ZH.js";
39
+ import {
40
+ extractLineGeometry,
41
+ featureId,
42
+ parseGeoJsonFile,
43
+ parseGeoJsonText,
44
+ stringifyFeatureCollection
45
+ } from "./chunk-4SKM4RHY.js";
46
+ import {
47
+ ANNOTATION_TABLES,
48
+ GEOJSON_FILE_NAMES,
49
+ GLOBAL_ONLY_TABLES,
50
+ ID_PREFIXES,
51
+ LAYERED_TYPE_TABLES,
52
+ LEVEL_ONLY_TABLES,
53
+ SPATIAL_3D_TABLES,
54
+ TYPE_TABLES,
55
+ VIEW_ANNOTATION_TABLES,
56
+ buildRegistry,
57
+ getSpecDir
58
+ } from "./chunk-4YHVOWS4.js";
59
+ import {
60
+ parseCsvText,
61
+ readCsv,
62
+ writeCsv
63
+ } from "./chunk-JY6KWRDB.js";
64
+ import {
65
+ ASSET_DIRS,
66
+ dirFiles,
67
+ discoverLayout,
68
+ listFiles
69
+ } from "./chunk-OBY3UYCO.js";
70
+
71
+ // src/build/index.ts
72
+ import { existsSync as existsSync11, mkdirSync, mkdtempSync, readdirSync as readdirSync2, copyFileSync, rmSync, symlinkSync } from "fs";
73
+ import { join as join13 } from "path";
74
+ import { tmpdir } from "os";
75
+
76
+ // src/validate/index.ts
77
+ import { existsSync as existsSync5 } from "fs";
78
+ import { join as join5 } from "path";
79
+
80
+ // src/validate/structure.ts
81
+ import { existsSync, readdirSync, readFileSync } from "fs";
82
+ import { join, extname } from "path";
83
+ var OPTIONAL_GEOMETRY_TABLES = /* @__PURE__ */ new Set(["opening", "space", "stair", "ramp", "railing"]);
84
+ var KNOWN_CSV_NAMES = new Set(Object.keys(ID_PREFIXES).map((t) => `${t}.csv`));
85
+ var KNOWN_GEOJSON_NAMES = new Set(Object.values(GEOJSON_FILE_NAMES).map((s) => `${s}.geojson`));
86
+ var KNOWN_GLOBAL_EXTRAS = /* @__PURE__ */ new Set(["_IdMap.csv"]);
87
+ var ROOT_NOTE_FILE = /^(LICEN[CS]E|COPYING|NOTICE|README|CREDITS)(\.(txt|md))?$/i;
88
+ var MIN_FORMAT_VERSION = 2;
89
+ var PROJECT_METADATA_FIELDS = ["format_version", "project_name", "project_number", "client", "address", "units", "source", "spatial_z", "discipline", "numbering"];
90
+ function validateStructure(dir) {
91
+ const issues = [];
92
+ const layout = discoverLayout(dir);
93
+ if (!existsSync(layout.globalDir)) {
94
+ issues.push("global/ missing global/ directory");
95
+ return issues;
96
+ }
97
+ const globalFiles = listFiles(layout.globalDir);
98
+ if (!globalFiles.includes("level.csv")) {
99
+ issues.push("global/ missing level.csv");
100
+ }
101
+ for (const f of globalFiles) {
102
+ const ext = extname(f);
103
+ if (ext === ".svg") {
104
+ issues.push(`global/${f} SVG files are not allowed (use GeoJSON; see migration script)`);
105
+ } else if (ext === ".csv") {
106
+ if (!KNOWN_CSV_NAMES.has(f) && !KNOWN_GLOBAL_EXTRAS.has(f)) {
107
+ issues.push(`global/${f} unknown file \u2014 only known table CSVs are allowed`);
108
+ } else if (ANNOTATION_TABLES.has(f.replace(".csv", "")) && !VIEW_ANNOTATION_TABLES.has(f.replace(".csv", ""))) {
109
+ issues.push(`global/${f} annotations belong to a level plan \u2014 put ${f} in a level directory`);
110
+ } else if (LEVEL_ONLY_TABLES.has(f.replace(".csv", ""))) {
111
+ issues.push(`global/${f} model groups belong to a level \u2014 put ${f} in a level directory`);
112
+ }
113
+ } else if (ext === ".geojson") {
114
+ if (!KNOWN_GEOJSON_NAMES.has(f)) {
115
+ issues.push(`global/${f} unknown GeoJSON file \u2014 not a recognized BimDown table name`);
116
+ }
117
+ } else {
118
+ issues.push(`global/${f} unexpected file \u2014 only CSV and GeoJSON files are allowed in global/`);
119
+ }
120
+ }
121
+ for (const ld of layout.levelDirs) {
122
+ if (!/^lv-.+$/.test(ld.name)) {
123
+ issues.push(`${ld.name}/ directory name does not match lv-{id} pattern`);
124
+ continue;
125
+ }
126
+ const files = listFiles(ld.path);
127
+ for (const f of files) {
128
+ const ext = extname(f);
129
+ if (ext === ".csv") {
130
+ if (!KNOWN_CSV_NAMES.has(f)) {
131
+ issues.push(`${ld.name}/${f} unknown file \u2014 not a recognized BimDown table`);
132
+ }
133
+ const tableName = f.replace(".csv", "");
134
+ if (GLOBAL_ONLY_TABLES.has(tableName)) {
135
+ issues.push(`${ld.name}/${f} ${tableName} belongs in global/ only`);
136
+ }
137
+ } else if (ext === ".svg") {
138
+ issues.push(`${ld.name}/${f} SVG files are not allowed (use GeoJSON; see migration script)`);
139
+ } else if (ext === ".geojson") {
140
+ if (!KNOWN_GEOJSON_NAMES.has(f)) {
141
+ issues.push(`${ld.name}/${f} unknown GeoJSON file \u2014 not a recognized BimDown table name`);
142
+ }
143
+ const base = f.replace(".geojson", "");
144
+ const tableName = Object.entries(GEOJSON_FILE_NAMES).find(([, v]) => v === base)?.[0];
145
+ if (tableName && !files.includes(`${tableName}.csv`)) {
146
+ issues.push(`${ld.name}/${f} orphaned GeoJSON \u2014 no matching ${tableName}.csv`);
147
+ }
148
+ } else {
149
+ issues.push(`${ld.name}/${f} unexpected file \u2014 only CSV and GeoJSON files are allowed`);
150
+ }
151
+ }
152
+ for (const f of files) {
153
+ if (extname(f) !== ".csv") continue;
154
+ const tableName = f.replace(".csv", "");
155
+ const geojsonName = GEOJSON_FILE_NAMES[tableName];
156
+ if (geojsonName && !files.includes(`${geojsonName}.geojson`) && !OPTIONAL_GEOMETRY_TABLES.has(tableName)) {
157
+ issues.push(`${ld.name}/${f} missing paired GeoJSON file "${geojsonName}.geojson"`);
158
+ }
159
+ }
160
+ }
161
+ const topEntries = readdirSync(dir);
162
+ for (const f of topEntries) {
163
+ if (f === "global" || /^lv-.+$/.test(f)) continue;
164
+ if (f === "project_metadata.json") continue;
165
+ if (f === "_IdMap.csv" || ASSET_DIRS.has(f)) continue;
166
+ if (f.startsWith(".")) continue;
167
+ if (ROOT_NOTE_FILE.test(f)) continue;
168
+ issues.push(`${f} unexpected entry in project root \u2014 only global/, lv-{n}/, mesh/, underlays/, _IdMap.csv, project_metadata.json and LICENSE/README notes are allowed`);
169
+ }
170
+ issues.push(...validateUnderlayFiles(dir));
171
+ const metadataPath = join(dir, "project_metadata.json");
172
+ if (existsSync(metadataPath)) {
173
+ try {
174
+ const raw = readFileSync(metadataPath, "utf-8");
175
+ const metadata = JSON.parse(raw);
176
+ if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) {
177
+ issues.push("project_metadata.json must be a JSON object");
178
+ } else {
179
+ const fv = metadata.format_version;
180
+ if (fv === void 0 || fv === null) {
181
+ issues.push('project_metadata.json missing "format_version"');
182
+ } else {
183
+ const n = typeof fv === "number" ? fv : parseInt(String(fv), 10);
184
+ if (!Number.isFinite(n)) {
185
+ issues.push(`project_metadata.json invalid "format_version": ${fv}`);
186
+ } else if (n < MIN_FORMAT_VERSION) {
187
+ issues.push(
188
+ `project_metadata.json format_version ${n} is no longer supported. Run: npx tsx scripts/svg-to-geojson.ts <project_dir>`
189
+ );
190
+ }
191
+ }
192
+ for (const key2 of Object.keys(metadata)) {
193
+ if (!PROJECT_METADATA_FIELDS.includes(key2)) {
194
+ issues.push(`project_metadata.json unknown field "${key2}"`);
195
+ }
196
+ }
197
+ if (metadata.spatial_z !== void 0 && metadata.spatial_z !== "absolute") {
198
+ issues.push(`project_metadata.json invalid "spatial_z": ${JSON.stringify(metadata.spatial_z)} \u2014 must be "absolute"`);
199
+ }
200
+ if (metadata.numbering !== void 0) {
201
+ const nb = metadata.numbering;
202
+ if (typeof nb !== "object" || nb === null || Array.isArray(nb) || Object.values(nb).some((v) => typeof v !== "string")) {
203
+ issues.push('project_metadata.json invalid "numbering" \u2014 must be an object of table name \u2192 prefix string');
204
+ }
205
+ }
206
+ if (metadata.units !== void 0) {
207
+ const validUnits = ["m", "ft", "in", "mm"];
208
+ if (typeof metadata.units !== "string" || !validUnits.includes(metadata.units)) {
209
+ issues.push(
210
+ `project_metadata.json invalid "units": ${JSON.stringify(metadata.units)} \u2014 must be one of ${validUnits.join(", ")}`
211
+ );
212
+ }
213
+ }
214
+ }
215
+ } catch (e) {
216
+ issues.push(`project_metadata.json failed to parse: ${e.message}`);
217
+ }
218
+ }
219
+ return issues;
220
+ }
221
+ var UNDERLAY_EXTENSIONS = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".webp", ".pdf", ".dxf"]);
222
+ function validateUnderlayFiles(dir) {
223
+ const csvPath = join(dir, "global", "underlay.csv");
224
+ if (!existsSync(csvPath)) return [];
225
+ let rows;
226
+ try {
227
+ rows = readCsv(csvPath).rows;
228
+ } catch {
229
+ return [];
230
+ }
231
+ const issues = [];
232
+ rows.forEach((row, i) => {
233
+ const file = row.file;
234
+ if (!file) return;
235
+ const where = `global/underlay.csv:${i + 2}`;
236
+ if (!file.startsWith("underlays/") || file.includes("..")) {
237
+ issues.push(`${where} file "${file}" must be a path under underlays/`);
238
+ return;
239
+ }
240
+ if (!UNDERLAY_EXTENSIONS.has(extname(file).toLowerCase())) {
241
+ issues.push(`${where} file "${file}" is not a supported underlay type (${[...UNDERLAY_EXTENSIONS].join(", ")})`);
242
+ return;
243
+ }
244
+ if (!existsSync(join(dir, file))) {
245
+ issues.push(`${where} file "${file}" not found`);
246
+ }
247
+ });
248
+ return issues;
249
+ }
250
+
251
+ // src/validate/csv.ts
252
+ function validateCsvHeaders(path, table, data, supplied) {
253
+ const issues = [];
254
+ const expected = new Set(table.csvFields.map((f) => f.name));
255
+ const actual = new Set(data.headers);
256
+ for (const h of data.duplicateHeaders ?? []) {
257
+ issues.push(`${path} duplicate column "${h}" (merged on read; rewrite the file with one "${h}" column)`);
258
+ }
259
+ for (const h of data.headers) {
260
+ if (!expected.has(h)) {
261
+ issues.push(`${path} unexpected column "${h}"`);
262
+ }
263
+ }
264
+ for (const f of table.csvFields) {
265
+ if (f.required && !actual.has(f.name)) {
266
+ if (supplied && actual.has("type_id") && data.rows.every((r) => supplied(r).has(f.name))) continue;
267
+ issues.push(`${path} missing required column "${f.name}"`);
268
+ }
269
+ }
270
+ return issues;
271
+ }
272
+ function validateCsvRequired(path, table, data, supplied) {
273
+ const issues = [];
274
+ const requiredFields = table.csvFields.filter((f) => f.required);
275
+ for (let i = 0; i < data.rows.length; i++) {
276
+ const row = data.rows[i];
277
+ const fromType = supplied && row.type_id ? supplied(row) : void 0;
278
+ for (const f of requiredFields) {
279
+ const val = row[f.name];
280
+ if ((val === void 0 || val === "") && !fromType?.has(f.name)) {
281
+ issues.push(`${path}:${i + 2} required field "${f.name}" is empty`);
282
+ }
283
+ }
284
+ }
285
+ return issues;
286
+ }
287
+ function validateCsvEnums(path, table, data) {
288
+ const issues = [];
289
+ const enumFields = table.csvFields.filter((f) => f.type === "enum" && f.values);
290
+ for (let i = 0; i < data.rows.length; i++) {
291
+ const row = data.rows[i];
292
+ for (const f of enumFields) {
293
+ const val = row[f.name];
294
+ if (val !== void 0 && val !== "" && !f.values.includes(val)) {
295
+ issues.push(
296
+ `${path}:${i + 2} field "${f.name}" value "${val}" is not a valid enum (${f.values.join(", ")})`
297
+ );
298
+ }
299
+ }
300
+ }
301
+ return issues;
302
+ }
303
+ var BOOLEAN_VALUES = /* @__PURE__ */ new Set(["true", "false"]);
304
+ function validateCsvTypes(path, table, data) {
305
+ const issues = [];
306
+ const typed = table.csvFields.filter((f) => f.type === "boolean" || f.unit === "none" && (f.type === "float" || f.type === "int"));
307
+ if (typed.length === 0) return issues;
308
+ for (let i = 0; i < data.rows.length; i++) {
309
+ const row = data.rows[i];
310
+ for (const f of typed) {
311
+ const val = row[f.name];
312
+ if (val === void 0 || val === "") continue;
313
+ if (f.type === "boolean") {
314
+ if (!BOOLEAN_VALUES.has(val.toLowerCase())) issues.push(`${path}:${i + 2} field "${f.name}" value "${val}" must be true or false`);
315
+ } else if (!Number.isFinite(Number(val)) || Number(val) < 0) {
316
+ issues.push(`${path}:${i + 2} field "${f.name}" value "${val}" must be a non-negative number`);
317
+ }
318
+ }
319
+ }
320
+ return issues;
321
+ }
322
+
323
+ // src/validate/ids.ts
324
+ function validateIdFormat(path, table, data) {
325
+ const issues = [];
326
+ const prefix = table.prefix;
327
+ for (let i = 0; i < data.rows.length; i++) {
328
+ const id = data.rows[i].id;
329
+ if (!id) continue;
330
+ const regex = new RegExp(`^${prefix}-.+$`);
331
+ if (!regex.test(id)) {
332
+ issues.push(`${path}:${i + 2} id "${id}" has wrong format, expected "${prefix}-..."`);
333
+ }
334
+ }
335
+ return issues;
336
+ }
337
+ function createIdRegistry() {
338
+ return { ids: /* @__PURE__ */ new Map(), allIds: /* @__PURE__ */ new Map(), issues: [] };
339
+ }
340
+ function registerIds(registry, path, tableName, data) {
341
+ const level = path.split("/")[0];
342
+ for (let i = 0; i < data.rows.length; i++) {
343
+ const id = data.rows[i].id;
344
+ if (!id) continue;
345
+ const scopedKey = `${level}/${id}`;
346
+ const existing = registry.ids.get(scopedKey);
347
+ if (existing) {
348
+ if (existing.table === tableName) {
349
+ registry.issues.push(
350
+ `${path}:${i + 2} duplicate id "${id}" (first seen in ${existing.path}:${existing.row})`
351
+ );
352
+ } else {
353
+ registry.issues.push(
354
+ `${path}:${i + 2} id "${id}" conflicts with ${existing.table} in ${existing.path}:${existing.row}`
355
+ );
356
+ }
357
+ } else {
358
+ registry.ids.set(scopedKey, { table: tableName, path, row: i + 2 });
359
+ }
360
+ registry.allIds.set(id, { table: tableName, path, row: i + 2 });
361
+ }
362
+ }
363
+
364
+ // src/validate/references.ts
365
+ function validateReferences(path, table, data, idRegistry) {
366
+ const issues = [];
367
+ const refFields = table.csvFields.filter((f) => f.type === "reference");
368
+ for (let i = 0; i < data.rows.length; i++) {
369
+ const row = data.rows[i];
370
+ for (const f of refFields) {
371
+ const val = row[f.name];
372
+ if (!val) continue;
373
+ const entry = idRegistry.allIds.get(val);
374
+ if (!entry) {
375
+ issues.push(`${path}:${i + 2} ${f.name} "${val}" references non-existent id`);
376
+ continue;
377
+ }
378
+ if (f.reference && f.reference !== "element") {
379
+ const expectedPrefix = ID_PREFIXES[f.reference];
380
+ if (expectedPrefix && !val.startsWith(expectedPrefix + "-")) {
381
+ issues.push(
382
+ `${path}:${i + 2} ${f.name} "${val}" should reference ${f.reference} (prefix "${expectedPrefix}-")`
383
+ );
384
+ }
385
+ }
386
+ }
387
+ }
388
+ return issues;
389
+ }
390
+
391
+ // src/build/model-checks.ts
392
+ var fmt = (v) => v.toFixed(3);
393
+ function zOverlap(a0, a1, b0, b1, tol) {
394
+ if (a0 === void 0 || a1 === void 0 || b0 === void 0 || b1 === void 0) return true;
395
+ return Math.min(a1, b1) - Math.max(a0, b0) > tol;
396
+ }
397
+ function insertOverlaps(inserts, tol, unit = "m") {
398
+ const out = [];
399
+ const byHost = /* @__PURE__ */ new Map();
400
+ for (const e of inserts) {
401
+ if (!e.hostId || !Number.isFinite(e.position) || !Number.isFinite(e.width)) continue;
402
+ const key2 = `${e.scope}\0${e.hostId}`;
403
+ const list = byHost.get(key2);
404
+ if (list) list.push(e);
405
+ else byHost.set(key2, [e]);
406
+ }
407
+ for (const group of byHost.values()) {
408
+ if (group.length < 2) continue;
409
+ group.sort((a, b) => a.position - b.position);
410
+ for (let i = 0; i < group.length; i++) {
411
+ for (let j = i + 1; j < group.length; j++) {
412
+ const a = group[i], b = group[j];
413
+ const aLo = a.position - a.width / 2, aHi = a.position + a.width / 2;
414
+ const bLo = b.position - b.width / 2, bHi = b.position + b.width / 2;
415
+ const overlap = Math.min(aHi, bHi) - Math.max(aLo, bLo);
416
+ if (overlap <= tol) continue;
417
+ const aTop = a.sill !== void 0 && a.height !== void 0 ? a.sill + a.height : void 0;
418
+ const bTop = b.sill !== void 0 && b.height !== void 0 ? b.sill + b.height : void 0;
419
+ if (!zOverlap(a.sill, aTop, b.sill, bTop, tol)) continue;
420
+ out.push({
421
+ code: "insert_overlap",
422
+ scope: a.scope,
423
+ ids: [a.id, b.id],
424
+ tables: [a.table, b.table],
425
+ hostId: a.hostId,
426
+ overlap,
427
+ message: `${a.id} and ${b.id} overlap on ${a.hostId} (${a.id}: ${fmt(aLo)}\u2013${fmt(aHi)} ${unit}, ${b.id}: ${fmt(bLo)}\u2013${fmt(bHi)} ${unit})`
428
+ });
429
+ }
430
+ }
431
+ }
432
+ return out;
433
+ }
434
+ var PARALLEL_SIN = 0.02;
435
+ function wallOverlaps(walls, tol, minOverlap = tol * 10, unit = "m") {
436
+ const out = [];
437
+ const items = walls.map((w) => {
438
+ const dx = w.b.x - w.a.x, dy = w.b.y - w.a.y;
439
+ const len = Math.hypot(dx, dy);
440
+ return { w, len, ux: dx / len, uy: dy / len, minX: Math.min(w.a.x, w.b.x) - w.thickness, maxX: Math.max(w.a.x, w.b.x) + w.thickness, minY: Math.min(w.a.y, w.b.y) - w.thickness, maxY: Math.max(w.a.y, w.b.y) + w.thickness };
441
+ }).filter((i) => i.len > tol).sort((a, b) => a.minX - b.minX);
442
+ for (let i = 0; i < items.length; i++) {
443
+ const A = items[i];
444
+ for (let j = i + 1; j < items.length; j++) {
445
+ const B = items[j];
446
+ if (B.minX > A.maxX) break;
447
+ if (A.w.scope !== B.w.scope || B.minY > A.maxY || B.maxY < A.minY) continue;
448
+ if (Math.abs(A.ux * B.uy - A.uy * B.ux) > PARALLEL_SIN) continue;
449
+ const across = (p) => -(p.x - A.w.a.x) * A.uy + (p.y - A.w.a.y) * A.ux;
450
+ const off = Math.max(Math.abs(across(B.w.a)), Math.abs(across(B.w.b)));
451
+ if (off >= Math.max(A.w.thickness, B.w.thickness) / 2 - tol) continue;
452
+ const along = (p) => (p.x - A.w.a.x) * A.ux + (p.y - A.w.a.y) * A.uy;
453
+ const b0 = along(B.w.a), b1 = along(B.w.b);
454
+ const lo = Math.max(0, Math.min(b0, b1)), hi = Math.min(A.len, Math.max(b0, b1));
455
+ if (hi - lo <= minOverlap) continue;
456
+ if (!zOverlap(A.w.z0, A.w.z1, B.w.z0, B.w.z1, tol)) continue;
457
+ const m = (lo + hi) / 2;
458
+ out.push({
459
+ code: "wall_overlap",
460
+ scope: A.w.scope,
461
+ ids: [A.w.id, B.w.id],
462
+ tables: [A.w.table, B.w.table],
463
+ overlap: hi - lo,
464
+ at: { x: A.w.a.x + A.ux * m, y: A.w.a.y + A.uy * m },
465
+ message: `${A.w.id} and ${B.w.id} overlap for ${fmt(hi - lo)} ${unit} \u2014 one wall inside the other; delete or shorten one (room boundaries and quantities count both)`
466
+ });
467
+ }
468
+ }
469
+ return out;
470
+ }
471
+ var POSITIVE_FIELDS = /* @__PURE__ */ new Set([
472
+ "thickness",
473
+ "width",
474
+ "height",
475
+ "size_x",
476
+ "size_y",
477
+ "flange",
478
+ "web",
479
+ "step_count",
480
+ "u_spacing",
481
+ "v_spacing",
482
+ "mullion_width",
483
+ "mullion_depth",
484
+ "frame_width",
485
+ "baluster_spacing",
486
+ "baluster_size",
487
+ "top_rail_size",
488
+ "conductivity"
489
+ ]);
490
+ var NON_NEGATIVE_FIELDS = /* @__PURE__ */ new Set(["position", "u_grid_count", "v_grid_count", "u_value", "shgc", "vt", "load", "rating", "voltage", "poles"]);
491
+ function numericFieldError(field, raw) {
492
+ if (raw === void 0 || raw.trim() === "") return null;
493
+ const v = Number(raw);
494
+ if (!Number.isFinite(v)) return null;
495
+ if (POSITIVE_FIELDS.has(field) && !(v > 0)) return "positive";
496
+ if (NON_NEGATIVE_FIELDS.has(field) && v < 0) return "non_negative";
497
+ return null;
498
+ }
499
+
500
+ // src/validate/ranges.ts
501
+ var FIELD_MAX = {
502
+ elevation: 500,
503
+ // tallest buildings ~500m
504
+ base_offset: 100,
505
+ top_offset: 100,
506
+ thickness: 2,
507
+ width: 30,
508
+ height: 20,
509
+ size_x: 10,
510
+ size_y: 10,
511
+ length: 100,
512
+ position: 100,
513
+ // distance in meters along host wall
514
+ start_x: 1e4,
515
+ // site coordinates can be large
516
+ start_y: 1e4,
517
+ end_x: 1e4,
518
+ end_y: 1e4,
519
+ start_z: 500,
520
+ end_z: 500,
521
+ step_count: 200
522
+ // not meters, but still bounded
523
+ };
524
+ var DEFAULT_MAX = 1e3;
525
+ var TABLE_FIELD_MAX = {
526
+ foundation: { thickness: 60 },
527
+ foundation_type: { thickness: 60 },
528
+ // A DXF underlay's origin may sit far from the plan (survey coordinates);
529
+ // scale is units per pixel / point / drawing unit, not a length.
530
+ underlay: { x: 1e7, y: 1e7, scale: 1e6 },
531
+ // Trees, cars and long counters outgrow the 10 m section limit.
532
+ furniture: { size_x: 30, size_y: 30 },
533
+ // Paper millimetres and a scale denominator, not model lengths.
534
+ sheet_viewport: { x: 1e7, y: 1e7, scale: 1e7 }
535
+ };
536
+ function validateRanges(path, table, data, units = "m") {
537
+ const toM = UNIT_TO_M[units] ?? 1;
538
+ const issues = [];
539
+ const floatFields = table.csvFields.filter(
540
+ (f) => (f.type === "float" || f.type === "int") && f.name !== "id" && f.unit !== "none"
541
+ );
542
+ const numericFields = table.csvFields.filter((f) => f.type === "float" || f.type === "int");
543
+ for (let i = 0; i < data.rows.length; i++) {
544
+ const row = data.rows[i];
545
+ const rowNum = i + 2;
546
+ for (const field of numericFields) {
547
+ const err = numericFieldError(field.name, row[field.name]);
548
+ if (err) issues.push(`${path}:${rowNum} ${field.name}=${row[field.name]} must be ${err === "positive" ? "greater than 0" : "0 or more"}`);
549
+ }
550
+ for (const field of floatFields) {
551
+ const raw = row[field.name];
552
+ if (raw === void 0 || raw === "") continue;
553
+ const val = Number(raw);
554
+ if (isNaN(val)) continue;
555
+ const max = TABLE_FIELD_MAX[table.name]?.[field.name] ?? FIELD_MAX[field.name] ?? DEFAULT_MAX;
556
+ if (field.name !== "step_count" && Math.abs(val) * toM > max) {
557
+ issues.push(
558
+ `${path}:${rowNum} ${field.name}=${raw} is out of range for project units "${units}" (max reasonable: ${+(max / toM).toPrecision(4)} ${units}) \u2014 check the unit`
559
+ );
560
+ } else if (field.name === "step_count" && Math.abs(val) > max) {
561
+ issues.push(`${path}:${rowNum} ${field.name}=${raw} is out of range (max reasonable: ${max})`);
562
+ }
563
+ }
564
+ }
565
+ return issues;
566
+ }
567
+
568
+ // src/validate/geojson.ts
569
+ var EXPECTED_GEOMETRY = {
570
+ // Line elements → LineString
571
+ wall: /* @__PURE__ */ new Set(["LineString"]),
572
+ structure_wall: /* @__PURE__ */ new Set(["LineString"]),
573
+ curtain_wall: /* @__PURE__ */ new Set(["LineString"]),
574
+ room_separator: /* @__PURE__ */ new Set(["LineString"]),
575
+ stair: /* @__PURE__ */ new Set(["LineString"]),
576
+ stair_run: /* @__PURE__ */ new Set(["LineString"]),
577
+ ramp: /* @__PURE__ */ new Set(["LineString"]),
578
+ railing: /* @__PURE__ */ new Set(["LineString"]),
579
+ beam: /* @__PURE__ */ new Set(["LineString"]),
580
+ brace: /* @__PURE__ */ new Set(["LineString"]),
581
+ duct: /* @__PURE__ */ new Set(["LineString"]),
582
+ pipe: /* @__PURE__ */ new Set(["LineString"]),
583
+ cable_tray: /* @__PURE__ */ new Set(["LineString"]),
584
+ conduit: /* @__PURE__ */ new Set(["LineString"]),
585
+ // Point elements → Point
586
+ column: /* @__PURE__ */ new Set(["Point"]),
587
+ structure_column: /* @__PURE__ */ new Set(["Point"]),
588
+ equipment: /* @__PURE__ */ new Set(["Point"]),
589
+ terminal: /* @__PURE__ */ new Set(["Point"]),
590
+ mep_node: /* @__PURE__ */ new Set(["Point"]),
591
+ furniture: /* @__PURE__ */ new Set(["Point"]),
592
+ // Polygon elements → Polygon
593
+ slab: /* @__PURE__ */ new Set(["Polygon"]),
594
+ roof: /* @__PURE__ */ new Set(["Polygon"]),
595
+ ceiling: /* @__PURE__ */ new Set(["Polygon"]),
596
+ structure_slab: /* @__PURE__ */ new Set(["Polygon"]),
597
+ space: /* @__PURE__ */ new Set(["Polygon"]),
598
+ stair_landing: /* @__PURE__ */ new Set(["Polygon"]),
599
+ // Mixed
600
+ foundation: /* @__PURE__ */ new Set(["Point", "LineString", "Polygon"]),
601
+ opening: /* @__PURE__ */ new Set(["Polygon"])
602
+ };
603
+ function validateGeoJsonFile(displayPath, fullPath, csvIds, tableName, units = "m") {
604
+ const issues = [];
605
+ let fc;
606
+ try {
607
+ fc = parseGeoJsonFile(fullPath);
608
+ } catch (e) {
609
+ issues.push(`${displayPath} failed to parse GeoJSON: ${e.message}`);
610
+ return issues;
611
+ }
612
+ const isSpatial = SPATIAL_3D_TABLES.has(tableName);
613
+ const expected = EXPECTED_GEOMETRY[tableName];
614
+ const seenIds = /* @__PURE__ */ new Set();
615
+ for (let i = 0; i < fc.features.length; i++) {
616
+ const feat = fc.features[i];
617
+ const ctx = `${displayPath}:feature[${i}]`;
618
+ if (!feat || feat.type !== "Feature") {
619
+ issues.push(`${ctx} not a Feature object`);
620
+ continue;
621
+ }
622
+ const id = featureId(feat);
623
+ if (!id || id === "<unknown>") {
624
+ issues.push(`${ctx} missing properties.id`);
625
+ continue;
626
+ }
627
+ if (seenIds.has(id)) {
628
+ issues.push(`${ctx} duplicate id "${id}"`);
629
+ }
630
+ seenIds.add(id);
631
+ if (!csvIds.has(id)) {
632
+ issues.push(`${ctx} id "${id}" has no matching CSV row`);
633
+ }
634
+ const g = feat.geometry;
635
+ if (!g || !g.type) {
636
+ issues.push(`${ctx} missing geometry`);
637
+ continue;
638
+ }
639
+ if (expected && !expected.has(g.type)) {
640
+ const allowed = [...expected].join(" or ");
641
+ issues.push(`${ctx} id "${id}" geometry type ${g.type} not allowed for ${tableName} (expected ${allowed})`);
642
+ }
643
+ issues.push(...validateGeometryCoords(ctx, id, g, isSpatial, units));
644
+ }
645
+ return issues;
646
+ }
647
+ var MAX_COORD_M = 1e3;
648
+ function validateGeometryCoords(ctx, id, g, isSpatial, units) {
649
+ const issues = [];
650
+ const max = MAX_COORD_M / (UNIT_TO_M[units] ?? 1);
651
+ const checkPosition = (p, where) => {
652
+ if (!Array.isArray(p) || p.length < 2 || p.length > 3) {
653
+ issues.push(`${ctx} id "${id}" ${where} position must be [x,y] or [x,y,z]`);
654
+ return;
655
+ }
656
+ for (let k = 0; k < p.length; k++) {
657
+ const v = p[k];
658
+ if (typeof v !== "number" || !isFinite(v)) {
659
+ issues.push(`${ctx} id "${id}" ${where} non-numeric coordinate at index ${k}`);
660
+ return;
661
+ }
662
+ if (Math.abs(v) > max) {
663
+ issues.push(`${ctx} id "${id}" ${where} coordinate ${v} is out of range for project units "${units}" (max reasonable: ${+max.toPrecision(4)} ${units}) \u2014 check the unit`);
664
+ return;
665
+ }
666
+ }
667
+ if (isSpatial && p.length !== 3) {
668
+ issues.push(`${ctx} id "${id}" ${where} spatial element requires 3D coordinates [x,y,z]`);
669
+ }
670
+ if (!isSpatial && p.length === 3) {
671
+ issues.push(`${ctx} id "${id}" ${where} level-anchored element should use 2D coordinates (Z lives in base_offset/top_offset properties)`);
672
+ }
673
+ };
674
+ if (g.type === "Point") {
675
+ checkPosition(g.coordinates, "Point");
676
+ } else if (g.type === "LineString") {
677
+ if (!Array.isArray(g.coordinates) || g.coordinates.length < 2) {
678
+ issues.push(`${ctx} id "${id}" LineString needs at least 2 coordinates`);
679
+ } else {
680
+ checkPosition(g.coordinates[0], "LineString[0]");
681
+ checkPosition(g.coordinates[g.coordinates.length - 1], "LineString[last]");
682
+ }
683
+ } else if (g.type === "Polygon") {
684
+ if (!Array.isArray(g.coordinates) || g.coordinates.length === 0) {
685
+ issues.push(`${ctx} id "${id}" Polygon needs at least one ring`);
686
+ } else {
687
+ const ring = g.coordinates[0];
688
+ if (!Array.isArray(ring) || ring.length < 4) {
689
+ issues.push(`${ctx} id "${id}" Polygon outer ring needs >= 4 positions (including closing duplicate)`);
690
+ } else {
691
+ checkPosition(ring[0], "Polygon outer[0]");
692
+ const first = ring[0], last = ring[ring.length - 1];
693
+ if (Array.isArray(first) && Array.isArray(last)) {
694
+ if (first[0] !== last[0] || first[1] !== last[1]) {
695
+ issues.push(`${ctx} id "${id}" Polygon outer ring not closed (first \u2260 last)`);
696
+ }
697
+ }
698
+ }
699
+ }
700
+ }
701
+ return issues;
702
+ }
703
+
704
+ // src/validate/types.ts
705
+ function catalogFromEntries(entries) {
706
+ const global = entries.filter((e) => e.path.startsWith("global/"));
707
+ return catalogFromRows(
708
+ global.filter((e) => TYPE_TABLES.has(e.tableName)).map((e) => ({ table: e.tableName, rows: e.data.rows })),
709
+ global.find((e) => e.tableName === "type_layer")?.data.rows ?? []
710
+ );
711
+ }
712
+ function typeSuppliedFields(table, row, catalog) {
713
+ const t = table.typeTable ? typeOfRow(table.name, row, catalog) : void 0;
714
+ if (!t) return /* @__PURE__ */ new Set();
715
+ const values = typeValues(t);
716
+ return new Set(typeParamFields(table.name).filter((f) => values[f] !== void 0));
717
+ }
718
+ var inRange01 = (v) => v >= 0 && v <= 1;
719
+ function validateTypes(entries, catalog, idRegistry) {
720
+ const issues = [];
721
+ for (const entry of entries) {
722
+ const { path, tableName, table, data } = entry;
723
+ if (tableName === "type_layer") {
724
+ const seqs = /* @__PURE__ */ new Map();
725
+ data.rows.forEach((row, i) => {
726
+ const at = `${path}:${i + 2}`;
727
+ const typeId = row.type_id ?? "";
728
+ const t = catalog.types.get(typeId);
729
+ if (typeId && idRegistry.allIds.has(typeId) && (!t || !LAYERED_TYPE_TABLES.has(t.table))) {
730
+ issues.push(`${at} type_id "${typeId}" is not a layered type (${[...LAYERED_TYPE_TABLES].join(", ")})`);
731
+ }
732
+ const seq = Number(row.seq);
733
+ if (row.seq !== void 0 && row.seq !== "") {
734
+ if (!Number.isInteger(seq) || seq < 1) {
735
+ issues.push(`${at} seq=${row.seq} must be a positive integer`);
736
+ } else {
737
+ const used = seqs.get(typeId) ?? /* @__PURE__ */ new Set();
738
+ if (used.has(seq)) issues.push(`${at} seq=${seq} repeats within type ${typeId}`);
739
+ used.add(seq);
740
+ seqs.set(typeId, used);
741
+ }
742
+ }
743
+ const th = Number(row.thickness);
744
+ if (row.thickness && (!Number.isFinite(th) || th <= 0)) {
745
+ issues.push(`${at} thickness=${row.thickness} must be > 0`);
746
+ }
747
+ const k = Number(row.conductivity);
748
+ if (row.conductivity && (!Number.isFinite(k) || k <= 0)) {
749
+ issues.push(`${at} conductivity=${row.conductivity} must be > 0 (W/(m\xB7K))`);
750
+ }
751
+ });
752
+ continue;
753
+ }
754
+ if (TYPE_TABLES.has(tableName)) {
755
+ data.rows.forEach((row, i) => {
756
+ const at = `${path}:${i + 2}`;
757
+ const t = catalog.types.get(row.id ?? "");
758
+ if (t && LAYERED_TYPE_TABLES.has(tableName)) {
759
+ const total = layerTotal(t);
760
+ const own = Number(row.thickness);
761
+ if (row.thickness && total !== void 0 && Number.isFinite(own) && Math.abs(own - total) > 5e-4) {
762
+ issues.push(`${at} ${row.id} thickness=${row.thickness} differs from its layers' total ${total} \u2014 fix it or leave thickness empty`);
763
+ }
764
+ if (!row.thickness && total === void 0) {
765
+ issues.push(`${at} ${row.id} has neither a thickness nor type_layer rows`);
766
+ }
767
+ }
768
+ for (const f of ["shgc", "vt"]) {
769
+ const v = Number(row[f]);
770
+ if (row[f] && (!Number.isFinite(v) || !inRange01(v))) issues.push(`${at} ${f}=${row[f]} must be between 0 and 1`);
771
+ }
772
+ const u = Number(row.u_value);
773
+ if (row.u_value && (!Number.isFinite(u) || u <= 0)) issues.push(`${at} u_value=${row.u_value} must be > 0 (W/(m\xB2\xB7K))`);
774
+ });
775
+ continue;
776
+ }
777
+ if (!table.typeTable || !data.headers.includes("type_id")) continue;
778
+ const params = typeParamFields(tableName);
779
+ const enumFields = table.csvFields.filter((f) => f.type === "enum" && f.values && params.includes(f.name));
780
+ data.rows.forEach((row, i) => {
781
+ const typeId = row.type_id;
782
+ if (!typeId) return;
783
+ const at = `${path}:${i + 2}`;
784
+ const target = idRegistry.allIds.get(typeId);
785
+ if (target && target.table !== table.typeTable) {
786
+ issues.push(`${at} type_id "${typeId}" is a ${target.table}; ${tableName} takes a ${table.typeTable}`);
787
+ return;
788
+ }
789
+ const t = typeOfRow(tableName, row, catalog);
790
+ if (!t) return;
791
+ const values = typeValues(t);
792
+ for (const f of enumFields) {
793
+ if ((row[f.name] ?? "") !== "") continue;
794
+ const v = values[f.name];
795
+ if (v !== void 0 && !f.values.includes(v)) {
796
+ issues.push(`${at} type ${typeId} gives ${f.name}="${v}", which ${tableName} does not accept (${f.values.join(", ")})`);
797
+ }
798
+ }
799
+ });
800
+ }
801
+ return issues;
802
+ }
803
+
804
+ // src/furniture/validate.ts
805
+ function validateFurnitureRows(path, data) {
806
+ const issues = [];
807
+ for (let i = 0; i < data.rows.length; i++) {
808
+ const row = data.rows[i];
809
+ const fam = getFurnitureFamily(row.family);
810
+ const variant = row.variant ?? "";
811
+ if (!fam || variant === "") continue;
812
+ const ids2 = variantIds(fam);
813
+ if (!ids2.includes(variant)) {
814
+ issues.push(
815
+ ids2.length > 0 ? `${path}:${i + 2} variant "${variant}" is not a variant of family "${fam.id}" (${ids2.join(", ")})` : `${path}:${i + 2} family "${fam.id}" has no variants; leave variant empty`
816
+ );
817
+ }
818
+ }
819
+ return issues;
820
+ }
821
+
822
+ // src/validate/sheets.ts
823
+ var SHEET_PAPER = {
824
+ A0: { w: 1189, h: 841 },
825
+ A1: { w: 841, h: 594 },
826
+ A2: { w: 594, h: 420 },
827
+ A3: { w: 420, h: 297 },
828
+ A4: { w: 297, h: 210 }
829
+ };
830
+ function validateSheets(sheets, viewports, registry) {
831
+ const issues = [];
832
+ const paperOf = /* @__PURE__ */ new Map();
833
+ if (sheets) {
834
+ const numbers = /* @__PURE__ */ new Map();
835
+ sheets.rows.forEach((row, i) => {
836
+ const at = `global/sheet.csv:${i + 2}`;
837
+ paperOf.set(row.id, SHEET_PAPER[row.paper || "A1"] ?? SHEET_PAPER.A1);
838
+ for (const f of ["revision_date", "issue_date"]) {
839
+ const v = row[f] ?? "";
840
+ if (v && !/^\d{4}-\d{2}-\d{2}$/.test(v)) issues.push(`${at} ${f}="${v}" is not a YYYY-MM-DD date`);
841
+ }
842
+ const n = (row.number ?? "").trim();
843
+ if (!n) return;
844
+ const prev = numbers.get(n);
845
+ if (prev) issues.push(`${at} sheet number "${n}" is already used on line ${prev}`);
846
+ else numbers.set(n, i + 2);
847
+ });
848
+ }
849
+ if (!viewports) return issues;
850
+ viewports.rows.forEach((row, i) => {
851
+ const at = `global/sheet_viewport.csv:${i + 2}`;
852
+ const type = row.view_type;
853
+ const viewId = (row.view_id ?? "").trim();
854
+ if (type === "plan" && !row.level_id) issues.push(`${at} a plan viewport needs level_id`);
855
+ if (type === "section") {
856
+ if (!viewId) issues.push(`${at} a section viewport needs view_id (a section of global/view.csv)`);
857
+ else if (registry.allIds.get(viewId)?.table !== "view") issues.push(`${at} view_id "${viewId}" is not a section of global/view.csv`);
858
+ }
859
+ if (type === "elevation" && !ELEVATION_VIEW_IDS.includes(viewId)) {
860
+ issues.push(`${at} an elevation viewport needs view_id north, south, east or west`);
861
+ }
862
+ if (type === "schedule" && !row.schedule) issues.push(`${at} a schedule viewport needs schedule`);
863
+ const scale = row.scale ?? "";
864
+ if (scale !== "" && !(Number.isInteger(Number(scale)) && Number(scale) > 0)) {
865
+ issues.push(`${at} scale="${scale}" must be a positive whole number (100 = 1:100)`);
866
+ }
867
+ for (const f of ["x", "y"]) {
868
+ const v = row[f];
869
+ if (v !== void 0 && v !== "" && !Number.isFinite(Number(v))) issues.push(`${at} ${f}="${v}" is not a number`);
870
+ }
871
+ const paper = paperOf.get(row.sheet_id);
872
+ const x = Number(row.x), y = Number(row.y);
873
+ if (paper && row.x !== "" && row.y !== "" && Number.isFinite(x) && Number.isFinite(y) && (x < 0 || y < 0 || x > paper.w || y > paper.h)) {
874
+ issues.push(`${at} centre (${x}, ${y}) mm is off its ${paper.w}\xD7${paper.h} mm sheet`);
875
+ }
876
+ });
877
+ return issues;
878
+ }
879
+
880
+ // src/validate/groups.ts
881
+ var NUMERIC = ["x", "y", "rotation"];
882
+ function validateGroups(entries, registry) {
883
+ const issues = [];
884
+ const members = /* @__PURE__ */ new Map();
885
+ for (const e of entries) {
886
+ if (e.tableName === "model_group" || !e.data.headers.includes("group_id")) continue;
887
+ const level = e.path.split("/")[0];
888
+ e.data.rows.forEach((row, i) => {
889
+ const gid = (row.group_id ?? "").trim();
890
+ if (!gid) return;
891
+ if (level === "global") {
892
+ issues.push(`${e.path}:${i + 2} group_id "${gid}": elements in global/ cannot be grouped (groups belong to one level)`);
893
+ return;
894
+ }
895
+ const g = registry.ids.get(`${level}/${gid}`);
896
+ if (registry.allIds.has(gid) && (!g || g.table !== "model_group")) {
897
+ issues.push(`${e.path}:${i + 2} group_id "${gid}" is not a model_group on ${level}`);
898
+ return;
899
+ }
900
+ members.set(`${level}/${gid}`, (members.get(`${level}/${gid}`) ?? 0) + 1);
901
+ });
902
+ }
903
+ for (const e of entries) {
904
+ if (e.tableName !== "model_group") continue;
905
+ const level = e.path.split("/")[0];
906
+ e.data.rows.forEach((row, i) => {
907
+ const at = `${e.path}:${i + 2}`;
908
+ for (const f of NUMERIC) {
909
+ const v = row[f];
910
+ if (v !== void 0 && v !== "" && !Number.isFinite(Number(v))) issues.push(`${at} ${f}="${v}" is not a number`);
911
+ }
912
+ if (row.id && !members.has(`${level}/${row.id}`)) issues.push(`${at} model group "${row.id}" has no members (no element has group_id=${row.id})`);
913
+ });
914
+ }
915
+ return issues;
916
+ }
917
+ function groupWarnings(entries) {
918
+ const nameOf = /* @__PURE__ */ new Map();
919
+ for (const e of entries) {
920
+ if (e.tableName !== "model_group") continue;
921
+ const level = e.path.split("/")[0];
922
+ for (const row of e.data.rows) if (row.id) nameOf.set(`${level}/${row.id}`, row.name ?? "");
923
+ }
924
+ if (nameOf.size === 0) return [];
925
+ const counts = /* @__PURE__ */ new Map();
926
+ for (const key2 of nameOf.keys()) counts.set(key2, /* @__PURE__ */ new Map());
927
+ for (const e of entries) {
928
+ if (e.tableName === "model_group" || !e.data.headers.includes("group_id")) continue;
929
+ const level = e.path.split("/")[0];
930
+ for (const row of e.data.rows) {
931
+ const c = counts.get(`${level}/${(row.group_id ?? "").trim()}`);
932
+ if (c) c.set(e.tableName, (c.get(e.tableName) ?? 0) + 1);
933
+ }
934
+ }
935
+ const signature = (c) => [...c].sort(([a], [b]) => a.localeCompare(b)).map(([t, n]) => `${n} ${t}`).join(", ");
936
+ const byName = /* @__PURE__ */ new Map();
937
+ for (const [key2, name] of nameOf) {
938
+ const list = byName.get(name) ?? [];
939
+ list.push({ key: key2, sig: signature(counts.get(key2)) });
940
+ byName.set(name, list);
941
+ }
942
+ const warnings = [];
943
+ for (const [name, list] of byName) {
944
+ const first = list[0];
945
+ for (const other of list.slice(1)) {
946
+ if (other.sig !== first.sig) {
947
+ warnings.push(`model group "${name}": ${other.key} (${other.sig || "empty"}) differs from ${first.key} (${first.sig || "empty"})`);
948
+ }
949
+ }
950
+ }
951
+ return warnings;
952
+ }
953
+
954
+ // src/validate/envelope.ts
955
+ import { existsSync as existsSync2 } from "fs";
956
+ import { join as join2 } from "path";
957
+ var ATTACH_TARGETS = /* @__PURE__ */ new Set(["roof", "slab", "structure_slab"]);
958
+ var BOUNDED = /* @__PURE__ */ new Set(["slab", "structure_slab", "roof", "ceiling"]);
959
+ var BOUNDING = /* @__PURE__ */ new Set(["wall", "structure_wall", "curtain_wall", "room_separator"]);
960
+ function features(dirPath, file) {
961
+ const out = /* @__PURE__ */ new Map();
962
+ const p = join2(dirPath, `${file}.geojson`);
963
+ if (!existsSync2(p)) return out;
964
+ try {
965
+ for (const f of parseGeoJsonFile(p).features) out.set(String(f.properties?.id ?? ""), f);
966
+ } catch {
967
+ }
968
+ return out;
969
+ }
970
+ function ringLength(f) {
971
+ if (!f || f.geometry.type !== "Polygon") return null;
972
+ const ring = f.geometry.coordinates[0] ?? [];
973
+ const n = ring.length;
974
+ if (n >= 2 && ring[0][0] === ring[n - 1][0] && ring[0][1] === ring[n - 1][1]) return n - 1;
975
+ return n;
976
+ }
977
+ function validateEnvelope(dir, entries, ids2, levelElevation) {
978
+ const issues = [];
979
+ for (const e of entries) {
980
+ const levelDir = e.path.split("/")[0];
981
+ const at = (i) => `${e.path}:${i + 2}`;
982
+ if (e.tableName === "roof") {
983
+ const geo = features(join2(dir, levelDir), "roof");
984
+ e.data.rows.forEach((row, i) => {
985
+ const slopes = (row.edge_slopes ?? "").trim();
986
+ if (slopes) {
987
+ const vals = slopes.split(";").map((v) => Number(v.trim()));
988
+ if (vals.some((v) => !Number.isFinite(v) || v < 0 || v >= 90)) {
989
+ issues.push(`${at(i)} edge_slopes "${slopes}" must be semicolon-separated slopes in degrees (0 \u2264 slope < 90)`);
990
+ }
991
+ const n = ringLength(geo.get(row.id));
992
+ if (n !== null && vals.length !== n) {
993
+ issues.push(`${at(i)} edge_slopes has ${vals.length} values but the roof outline has ${n} edges (one per edge, edge i from vertex i to i+1)`);
994
+ }
995
+ }
996
+ if (row.roof_type === "extrusion") {
997
+ const pts = (row.profile ?? "").split(";").filter((s) => s.trim()).map((p) => p.split(",").map((v) => Number(v.trim())));
998
+ if (pts.length < 2 || pts.some((p) => p.length !== 2 || !p.every(Number.isFinite))) {
999
+ issues.push(`${at(i)} extrusion roof needs profile "u,z;u,z;..." with at least two points`);
1000
+ }
1001
+ }
1002
+ });
1003
+ }
1004
+ if (e.tableName === "wall" || e.tableName === "structure_wall") {
1005
+ e.data.rows.forEach((row, i) => {
1006
+ const target = row.top_attach_id;
1007
+ if (!target) return;
1008
+ const t = ids2.allIds.get(target);
1009
+ if (t && !ATTACH_TARGETS.has(t.table)) {
1010
+ issues.push(`${at(i)} top_attach_id "${target}" is a ${t.table}; a wall top attaches to a roof, slab or structure_slab`);
1011
+ }
1012
+ });
1013
+ }
1014
+ if (e.tableName === "slab" || e.tableName === "structure_slab") {
1015
+ e.data.rows.forEach((row, i) => {
1016
+ const a = parseSlopeArrow(row.slope_arrow);
1017
+ if (typeof a === "string") issues.push(`${at(i)} slope_arrow "${row.slope_arrow}" ${a}`);
1018
+ });
1019
+ }
1020
+ if (BOUNDED.has(e.tableName)) {
1021
+ e.data.rows.forEach((row, i) => {
1022
+ for (const id of (row.boundary_walls ?? "").split(";").map((s) => s.trim()).filter(Boolean)) {
1023
+ const t = ids2.ids.get(`${levelDir}/${id}`) ?? ids2.ids.get(`global/${id}`);
1024
+ if (!t) issues.push(`${at(i)} boundary_walls: "${id}" is not a wall on ${levelDir} or in global/`);
1025
+ else if (!BOUNDING.has(t.table)) issues.push(`${at(i)} boundary_walls: "${id}" is a ${t.table}; list walls, curtain walls or room separators`);
1026
+ }
1027
+ });
1028
+ }
1029
+ if (e.tableName === "opening") {
1030
+ const geo = features(join2(dir, levelDir), "opening");
1031
+ e.data.rows.forEach((row, i) => {
1032
+ if (row.top_level_id) {
1033
+ if (geo.get(row.id)?.geometry.type !== "Polygon") {
1034
+ issues.push(`${at(i)} a shaft (top_level_id set) needs a Polygon in opening.geojson`);
1035
+ }
1036
+ const base = levelElevation.get(levelDir), top = levelElevation.get(row.top_level_id);
1037
+ const off = (v) => Number(v || 0) || 0;
1038
+ if (base !== void 0 && top !== void 0 && top + off(row.top_offset) <= base + off(row.base_offset)) {
1039
+ issues.push(`${at(i)} shaft top (${row.top_level_id}) must be above its base level`);
1040
+ }
1041
+ } else if (!row.host_id) {
1042
+ issues.push(`${at(i)} host_id is required (a wall, slab or roof), unless the opening is a shaft with top_level_id`);
1043
+ }
1044
+ });
1045
+ }
1046
+ }
1047
+ return issues;
1048
+ }
1049
+
1050
+ // src/validate/curtain-wall.ts
1051
+ import { existsSync as existsSync3 } from "fs";
1052
+ import { join as join3 } from "path";
1053
+ var LIST_FIELDS = ["v_grids", "u_grids"];
1054
+ function validateCurtainWallCsv(path, data) {
1055
+ const issues = [];
1056
+ data.rows.forEach((row, i) => {
1057
+ const at = `${path}:${i + 2}`;
1058
+ for (const f of LIST_FIELDS) {
1059
+ const { bad: bad2 } = parseNumberList(row[f]);
1060
+ if (bad2.length > 0) issues.push(`${at} ${f}="${row[f]}" must be semicolon-separated numbers (e.g. 1.2;2.4), bad: ${bad2.join(", ")}`);
1061
+ }
1062
+ const { rules, bad } = parsePanels(row.panels);
1063
+ if (bad.length > 0) issues.push(`${at} panels: "${bad.join("; ")}" must be col:row=kind (e.g. 1:0=door, *:0=solid)`);
1064
+ const kinds = [...new Set(rules.map((r) => r.kind).filter((k) => !PANEL_KINDS.includes(k)))];
1065
+ if (kinds.length > 0) issues.push(`${at} panels: unknown kind ${kinds.join(", ")} (use ${PANEL_KINDS.join(", ")})`);
1066
+ });
1067
+ return issues;
1068
+ }
1069
+ function curtainWallWarnings(dir) {
1070
+ const warnings = [];
1071
+ const layout = discoverLayout(dir);
1072
+ const elevations = /* @__PURE__ */ new Map();
1073
+ const levelCsv = join3(layout.globalDir, "level.csv");
1074
+ if (existsSync3(levelCsv)) {
1075
+ for (const r of readCsv(levelCsv).rows) {
1076
+ const e = parseFloat(r.elevation ?? "");
1077
+ if (r.id && Number.isFinite(e)) elevations.set(r.id, e);
1078
+ }
1079
+ }
1080
+ for (const d of layout.levelDirs) {
1081
+ const csvPath = join3(d.path, "curtain_wall.csv");
1082
+ const geoPath = join3(d.path, `${GEOJSON_FILE_NAMES.curtain_wall}.geojson`);
1083
+ if (!existsSync3(csvPath) || !existsSync3(geoPath)) continue;
1084
+ const lines = /* @__PURE__ */ new Map();
1085
+ try {
1086
+ for (const f of parseGeoJsonFile(geoPath).features) {
1087
+ if (f.geometry.type !== "LineString") continue;
1088
+ const num = (v) => typeof v === "number" ? v : parseFloat(String(v ?? "")) || 0;
1089
+ lines.set(String(f.properties.id ?? ""), {
1090
+ length: extractLineGeometry(f).length,
1091
+ baseOffset: num(f.properties.base_offset),
1092
+ topOffset: num(f.properties.top_offset)
1093
+ });
1094
+ }
1095
+ } catch {
1096
+ continue;
1097
+ }
1098
+ const rows = effectiveRows(dir, "curtain_wall", readCsv(csvPath).rows);
1099
+ rows.forEach((row, i) => {
1100
+ const g = lines.get(row.id ?? "");
1101
+ if (!g) return;
1102
+ const at = `[warn] ${d.name}/curtain_wall.csv:${i + 2}`;
1103
+ const baseEl = elevations.get(d.name);
1104
+ const topEl = row.top_level_id ? elevations.get(row.top_level_id) : void 0;
1105
+ const height = baseEl !== void 0 && topEl !== void 0 ? topEl + g.topOffset - (baseEl + g.baseOffset) : void 0;
1106
+ const outside = (field, extent, what) => {
1107
+ if (extent === void 0) return;
1108
+ const off = parseNumberList(row[field]).values.filter((v) => v <= 0 || v >= extent);
1109
+ if (off.length > 0) warnings.push(`${at} ${field} ${off.join(", ")} outside the wall ${what} ${+extent.toFixed(3)} (ignored)`);
1110
+ };
1111
+ outside("v_grids", g.length, "length");
1112
+ outside("u_grids", height, "height");
1113
+ const { rules } = parsePanels(row.panels);
1114
+ if (rules.length === 0) return;
1115
+ const cols = gridLines(row.v_grids, row.v_grid_count, row.v_spacing, g.length).length + 1;
1116
+ const spacingRows = (row.u_grids ?? "").trim() === "" && (row.u_grid_count ?? "").trim() === "" && parseFloat(row.u_spacing ?? "") > 0;
1117
+ const rowsN = height !== void 0 || !spacingRows ? gridLines(row.u_grids, row.u_grid_count, row.u_spacing, height ?? Number.MAX_VALUE).length + 1 : Infinity;
1118
+ for (const r of rules) {
1119
+ if (r.col !== "*" && r.col >= cols || r.row !== "*" && r.row >= rowsN) {
1120
+ warnings.push(`${at} panels ${r.col}:${r.row}=${r.kind} is outside the ${cols} x ${rowsN} grid (ignored)`);
1121
+ } else if ((r.kind === "door" || r.kind === "double_door") && r.row !== 0) {
1122
+ warnings.push(`${at} panels ${r.col}:${r.row}=${r.kind}: doors belong in row 0 (the bottom row)`);
1123
+ }
1124
+ }
1125
+ const marks = (row.door_numbers ?? "").split(";").filter((s) => s.trim());
1126
+ if (marks.length > 0 && Number.isFinite(rowsN)) {
1127
+ const kinds = cellKinds(rules, cols, rowsN);
1128
+ const doors = kinds.flat().filter((k) => k === "door" || k === "double_door").length;
1129
+ if (marks.length > doors) warnings.push(`${at} door_numbers lists ${marks.length} marks for ${doors} door panel(s) (extra marks ignored)`);
1130
+ }
1131
+ });
1132
+ }
1133
+ return warnings;
1134
+ }
1135
+
1136
+ // src/validate/stairs.ts
1137
+ import { join as join4 } from "path";
1138
+ import { existsSync as existsSync4 } from "fs";
1139
+ var mm = (m) => `${Math.round(m * 1e3)} mm`;
1140
+ function validateStairs(dir) {
1141
+ const issues = [];
1142
+ const warnings = [];
1143
+ const upm = 1 / UNIT_TO_M[projectUnits(dir)];
1144
+ const layout = discoverLayout(dir);
1145
+ const elevations = /* @__PURE__ */ new Map();
1146
+ const levelCsv = join4(layout.globalDir, "level.csv");
1147
+ if (existsSync4(levelCsv)) {
1148
+ try {
1149
+ for (const r of readCsv(levelCsv).rows) elevations.set(r.id, parseFloat(r.elevation) || 0);
1150
+ } catch {
1151
+ }
1152
+ }
1153
+ const L = STAIR_LIMITS;
1154
+ for (const d of loadStairs(dir)) {
1155
+ for (const o of d.orphans) {
1156
+ if (o.hostId) issues.push(`${d.dir}/${o.table}.csv:${o.line} host_id "${o.hostId}" is not a stair`);
1157
+ }
1158
+ for (const s of d.stairs) {
1159
+ const at = `${d.dir}/stair.csv:${s.line} ${s.id}`;
1160
+ const top = s.row.multistory_top_level_id;
1161
+ if (top && elevations.has(top) && d.dir !== "global" && elevations.get(top) <= (elevations.get(d.dir) ?? 0) + 1e-6) {
1162
+ issues.push(`${at} multistory_top_level_id "${top}" must be a level above the stair's base level`);
1163
+ }
1164
+ const calc = stairCalc(s.asm, upm, s.reps.map((r) => r.scale));
1165
+ if (!calc) continue;
1166
+ for (const c of calc.checks) {
1167
+ if (c.ok) continue;
1168
+ switch (c.key) {
1169
+ case "riser":
1170
+ warnings.push(`${at} riser ${mm(c.value)} outside ${mm(L.riserMin)}\u2013${mm(L.riserMax)} (${calc.risers} risers over ${mm(calc.rise)}${s.reps.length > 1 ? `, ${s.reps.length} storeys` : ""})`);
1171
+ break;
1172
+ case "going":
1173
+ warnings.push(`${at} going ${mm(c.value)} below ${mm(L.goingMin)}${c.where && c.where !== s.id ? ` (run ${c.where})` : ""}`);
1174
+ break;
1175
+ case "blondel":
1176
+ warnings.push(`${at} 2R+G ${mm(c.value)} outside ${mm(L.blondelMin)}\u2013${mm(L.blondelMax)}`);
1177
+ break;
1178
+ case "width":
1179
+ warnings.push(`${at} width ${mm(c.value)} below ${mm(L.widthMin)}${c.where && c.where !== s.id ? ` (run ${c.where})` : ""}`);
1180
+ break;
1181
+ case "landing":
1182
+ warnings.push(`${at} landing ${c.where} top is ${mm(c.value)} off the run arriving on it`);
1183
+ break;
1184
+ }
1185
+ }
1186
+ }
1187
+ for (const r of d.railings) {
1188
+ const at = `${d.dir}/railing.csv:${r.line} ${r.id}`;
1189
+ if (r.host === "missing") issues.push(`${at} host_id "${r.row.host_id}" must be a stair or a slab`);
1190
+ if (r.host === "stair" && r.row.side !== "left" && r.row.side !== "right") {
1191
+ issues.push(`${at} a railing on a stair needs side = left | right`);
1192
+ }
1193
+ if (r.host !== "stair" && r.paths.length === 0 && r.host !== "missing") {
1194
+ warnings.push(`${at} no geometry: a sketched railing needs a LineString in railing.geojson (or host_id = a stair)`);
1195
+ }
1196
+ }
1197
+ }
1198
+ return { issues, warnings };
1199
+ }
1200
+
1201
+ // src/validate/index.ts
1202
+ function validate(dir) {
1203
+ const issues = [];
1204
+ issues.push(...validateStructure(dir));
1205
+ const registry = buildRegistry(getSpecDir());
1206
+ const layout = discoverLayout(dir);
1207
+ const csvEntries = [];
1208
+ const allDirs = [
1209
+ { name: "global", path: layout.globalDir },
1210
+ ...layout.levelDirs
1211
+ ];
1212
+ for (const d of allDirs) {
1213
+ if (!existsSync5(d.path)) continue;
1214
+ const files = listFiles(d.path);
1215
+ for (const f of files) {
1216
+ if (!f.endsWith(".csv")) continue;
1217
+ const tableName = f.replace(".csv", "");
1218
+ const table = registry.get(tableName);
1219
+ if (!table) continue;
1220
+ const fullPath = join5(d.path, f);
1221
+ const relPath = `${d.name}/${f}`;
1222
+ let data;
1223
+ try {
1224
+ data = readCsv(fullPath);
1225
+ } catch (e) {
1226
+ issues.push(`${relPath} failed to read CSV: ${e.message}`);
1227
+ continue;
1228
+ }
1229
+ csvEntries.push({ path: relPath, fullPath, tableName, table, data });
1230
+ }
1231
+ }
1232
+ const catalog = catalogFromEntries(csvEntries);
1233
+ for (const entry of csvEntries) {
1234
+ const supplied = entry.table.typeTable ? (row) => typeSuppliedFields(entry.table, row, catalog) : void 0;
1235
+ issues.push(...validateCsvHeaders(entry.path, entry.table, entry.data, supplied));
1236
+ issues.push(...validateCsvRequired(entry.path, entry.table, entry.data, supplied));
1237
+ }
1238
+ for (const entry of csvEntries) {
1239
+ issues.push(...validateIdFormat(entry.path, entry.table, entry.data));
1240
+ }
1241
+ const idRegistry = createIdRegistry();
1242
+ for (const entry of csvEntries) {
1243
+ registerIds(idRegistry, entry.path, entry.tableName, entry.data);
1244
+ }
1245
+ issues.push(...idRegistry.issues);
1246
+ for (const entry of csvEntries) {
1247
+ issues.push(...validateCsvEnums(entry.path, entry.table, entry.data));
1248
+ issues.push(...validateCsvTypes(entry.path, entry.table, entry.data));
1249
+ }
1250
+ for (const entry of csvEntries) {
1251
+ if (entry.tableName === "furniture" || entry.tableName === "furniture_type") {
1252
+ const rows = entry.tableName === "furniture" ? effectiveRows(dir, "furniture", entry.data.rows) : entry.data.rows;
1253
+ issues.push(...validateFurnitureRows(entry.path, { ...entry.data, rows }));
1254
+ }
1255
+ }
1256
+ for (const entry of csvEntries) {
1257
+ issues.push(...validateReferences(entry.path, entry.table, entry.data, idRegistry));
1258
+ }
1259
+ issues.push(...validateTypes(csvEntries, catalog, idRegistry));
1260
+ for (const entry of csvEntries) {
1261
+ issues.push(...validateAnnotations(entry.path, entry.tableName, entry.data, idRegistry));
1262
+ }
1263
+ const globalCsv = (t) => csvEntries.find((e) => e.path === `global/${t}.csv`)?.data ?? null;
1264
+ issues.push(...validateSheets(globalCsv("sheet"), globalCsv("sheet_viewport"), idRegistry));
1265
+ issues.push(...validateGroups(csvEntries, idRegistry));
1266
+ const levelElevation = /* @__PURE__ */ new Map();
1267
+ for (const entry of csvEntries) {
1268
+ if (entry.tableName !== "level") continue;
1269
+ for (const row of entry.data.rows) if (row.id) levelElevation.set(row.id, Number(row.elevation) || 0);
1270
+ }
1271
+ issues.push(...validateEnvelope(dir, csvEntries, idRegistry, levelElevation));
1272
+ for (const entry of csvEntries) {
1273
+ if (entry.tableName === "curtain_wall") issues.push(...validateCurtainWallCsv(entry.path, entry.data));
1274
+ }
1275
+ issues.push(...validateStairs(dir).issues);
1276
+ const units = projectUnits(dir);
1277
+ for (const entry of csvEntries) {
1278
+ issues.push(...validateRanges(entry.path, entry.table, entry.data, units));
1279
+ }
1280
+ for (const entry of csvEntries) {
1281
+ if (!entry.table.hostType) continue;
1282
+ for (let i = 0; i < entry.data.rows.length; i++) {
1283
+ const row = entry.data.rows[i];
1284
+ const pos = row.position;
1285
+ if (pos === void 0 || pos === "") continue;
1286
+ const val = Number(pos);
1287
+ if (isNaN(val) || val < 0) {
1288
+ issues.push(
1289
+ `${entry.path}:${i + 2} position=${pos} must be a non-negative distance`
1290
+ );
1291
+ }
1292
+ }
1293
+ }
1294
+ for (const d of allDirs) {
1295
+ if (!existsSync5(d.path)) continue;
1296
+ const files = listFiles(d.path);
1297
+ for (const f of files) {
1298
+ if (!f.endsWith(".geojson")) continue;
1299
+ const base = f.replace(".geojson", "");
1300
+ const tableEntry = Object.entries(GEOJSON_FILE_NAMES).find(([, v]) => v === base);
1301
+ if (!tableEntry) continue;
1302
+ const [tableName] = tableEntry;
1303
+ const table = registry.get(tableName);
1304
+ if (!table) continue;
1305
+ const csvIds = /* @__PURE__ */ new Set();
1306
+ for (const entry of csvEntries) {
1307
+ if (entry.tableName !== tableName) continue;
1308
+ const entryDir = entry.path.split("/")[0];
1309
+ if (entryDir !== d.name) continue;
1310
+ for (const row of entry.data.rows) {
1311
+ if (row.id) csvIds.add(row.id);
1312
+ }
1313
+ }
1314
+ const fullPath = join5(d.path, f);
1315
+ const relPath = `${d.name}/${f}`;
1316
+ issues.push(...validateGeoJsonFile(relPath, fullPath, csvIds, tableName, units));
1317
+ }
1318
+ }
1319
+ return issues;
1320
+ }
1321
+
1322
+ // src/build/space-boundary.ts
1323
+ import { writeFileSync } from "fs";
1324
+ import { dirname as dirname2, join as join7 } from "path";
1325
+
1326
+ // src/build/room-area.ts
1327
+ import { existsSync as existsSync6 } from "fs";
1328
+ import { dirname, join as join6 } from "path";
1329
+
1330
+ // src/build/room-net-area.ts
1331
+ var ON_LINE_TOL_M = 0.02;
1332
+ function signedArea(v) {
1333
+ let s = 0;
1334
+ for (let i = 0; i < v.length; i++) {
1335
+ const a = v[i], b = v[(i + 1) % v.length];
1336
+ s += a.x * b.y - b.x * a.y;
1337
+ }
1338
+ return s / 2;
1339
+ }
1340
+ function cleanRing(pts, tol = 1e-6) {
1341
+ const out = [];
1342
+ for (const p of pts) {
1343
+ const last = out[out.length - 1];
1344
+ if (!last || Math.hypot(p.x - last.x, p.y - last.y) > tol) out.push(p);
1345
+ }
1346
+ while (out.length > 1 && Math.hypot(out[0].x - out[out.length - 1].x, out[0].y - out[out.length - 1].y) <= tol) out.pop();
1347
+ return out;
1348
+ }
1349
+ function distToSegment(p, a, b) {
1350
+ const dx = b.x - a.x, dy = b.y - a.y;
1351
+ const l2 = dx * dx + dy * dy;
1352
+ const t = l2 > 0 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2)) : 0;
1353
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
1354
+ }
1355
+ function netRoomOutline(polygon, lines, upm = 1) {
1356
+ const tol = ON_LINE_TOL_M * upm;
1357
+ const ring = cleanRing(polygon);
1358
+ const edges = [];
1359
+ for (let i = 0; i < ring.length; i++) {
1360
+ const a = ring[i], b = ring[(i + 1) % ring.length];
1361
+ if (Math.hypot(b.x - a.x, b.y - a.y) < 1e-6 * upm) continue;
1362
+ const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
1363
+ const wall = lines.find((w) => distToSegment(a, w.start, w.end) < tol && distToSegment(b, w.start, w.end) < tol && distToSegment(mid, w.start, w.end) < tol);
1364
+ edges.push({ a, b, half: wall ? wall.half : 0 });
1365
+ }
1366
+ const n = edges.length;
1367
+ if (n < 3) return null;
1368
+ const sign = signedArea(edges.map((e) => e.a)) >= 0 ? 1 : -1;
1369
+ const offs = edges.map((e) => {
1370
+ const dx = e.b.x - e.a.x, dy = e.b.y - e.a.y;
1371
+ const l = Math.hypot(dx, dy);
1372
+ const nx = -dy / l * sign, ny = dx / l * sign;
1373
+ return { p: { x: e.a.x + nx * e.half, y: e.a.y + ny * e.half }, u: { x: dx / l, y: dy / l } };
1374
+ });
1375
+ const out = [];
1376
+ for (let i = 0; i < n; i++) {
1377
+ const L1 = offs[(i + n - 1) % n], L2 = offs[i];
1378
+ const den = L1.u.x * L2.u.y - L1.u.y * L2.u.x;
1379
+ if (Math.abs(den) < 1e-9) {
1380
+ out.push(L2.p);
1381
+ continue;
1382
+ }
1383
+ const t = ((L2.p.x - L1.p.x) * L2.u.y - (L2.p.y - L1.p.y) * L2.u.x) / den;
1384
+ out.push({ x: L1.p.x + L1.u.x * t, y: L1.p.y + L1.u.y * t });
1385
+ }
1386
+ const gross = Math.abs(signedArea(edges.map((e) => e.a)));
1387
+ const net = Math.abs(signedArea(out));
1388
+ if (!(net > 0) || net > gross + 1e-9 * Math.max(1, gross) || Math.sign(signedArea(out)) !== sign) return null;
1389
+ return out;
1390
+ }
1391
+ function roomNetArea(polygon, lines, upm = 1) {
1392
+ const net = netRoomOutline(polygon, lines, upm);
1393
+ return Math.abs(signedArea(net ?? polygon));
1394
+ }
1395
+
1396
+ // src/build/room-area.ts
1397
+ var BOUNDARY_TABLES = ["wall", "structure_wall", "curtain_wall", "room_separator"];
1398
+ function collectBoundaryLines(dirPath) {
1399
+ const out = [];
1400
+ const projectDir = dirname(dirPath);
1401
+ for (const table of BOUNDARY_TABLES) {
1402
+ const geomPath = join6(dirPath, `${GEOJSON_FILE_NAMES[table] ?? table}.geojson`);
1403
+ if (!existsSync6(geomPath)) continue;
1404
+ const thickness = /* @__PURE__ */ new Map();
1405
+ const csvPath = join6(dirPath, `${table}.csv`);
1406
+ if (table !== "room_separator" && existsSync6(csvPath)) {
1407
+ try {
1408
+ for (const r of effectiveRows(projectDir, table, readCsv(csvPath).rows)) {
1409
+ const t = parseFloat(r.thickness ?? "");
1410
+ if (r.id && Number.isFinite(t) && t > 0) thickness.set(r.id, t);
1411
+ }
1412
+ } catch {
1413
+ }
1414
+ }
1415
+ try {
1416
+ for (const f of parseGeoJsonFile(geomPath).features) {
1417
+ if (f.geometry.type !== "LineString") continue;
1418
+ const id = String(f.properties?.id ?? "");
1419
+ const lg = extractLineGeometry(f);
1420
+ out.push({
1421
+ start: { x: lg.start_x, y: lg.start_y },
1422
+ end: { x: lg.end_x, y: lg.end_y },
1423
+ half: table === "room_separator" ? 0 : (thickness.get(id) ?? 0) / 2
1424
+ });
1425
+ }
1426
+ } catch {
1427
+ }
1428
+ }
1429
+ return out;
1430
+ }
1431
+ function unitsPerMetre(unit) {
1432
+ return 1 / (UNIT_TO_M[unit] ?? 1);
1433
+ }
1434
+
1435
+ // src/build/room-faces.ts
1436
+ var TOLERANCE = 0.01;
1437
+ var MAX_FACE_EDGES = 1e4;
1438
+ function deriveRooms(level, segments, seeds, units = "m") {
1439
+ const warnings = [];
1440
+ const roomIssues = [];
1441
+ const matched = /* @__PURE__ */ new Map();
1442
+ const splitSegments = splitAtIntersections(segments);
1443
+ const { vertices, halfEdges } = buildHalfEdgeStructure(splitSegments);
1444
+ for (const v of vertices) {
1445
+ if (v.outgoing.length === 1) {
1446
+ const he = v.outgoing[0];
1447
+ warnings.push(
1448
+ `[warn] ${level}/ ${he.sourceId} endpoint (${v.x.toFixed(3)}, ${v.y.toFixed(3)}) has no connected line element`
1449
+ );
1450
+ }
1451
+ }
1452
+ const faces = traceFaces(halfEdges);
1453
+ const seedMap = /* @__PURE__ */ new Map();
1454
+ for (const seed of seeds) {
1455
+ if (isNaN(seed.x) || isNaN(seed.y)) continue;
1456
+ let bestFace = null;
1457
+ let bestArea = Infinity;
1458
+ for (const face of faces) {
1459
+ if (face.signedArea <= 0) continue;
1460
+ if (face.signedArea < bestArea && pointInPolygon(seed.x, seed.y, face.polygon)) {
1461
+ bestFace = face;
1462
+ bestArea = face.signedArea;
1463
+ }
1464
+ }
1465
+ if (bestFace) {
1466
+ matched.set(seed.id, bestFace);
1467
+ seedMap.set(seed.id, { x: seed.x, y: seed.y });
1468
+ } else {
1469
+ roomIssues.push({ kind: "unbounded", level, spaceIds: [seed.id] });
1470
+ warnings.push(
1471
+ `[warn] ${level}/space.csv ${seed.id} at (${seed.raw?.[0] ?? seed.x}, ${seed.raw?.[1] ?? seed.y}) has no enclosing boundary \u2014 the seed is outside every closed loop of walls/room separators (wall gap or seed outside the building); no polygon generated`
1472
+ );
1473
+ }
1474
+ }
1475
+ const overlap = findRoomOverlaps(level, matched, seedMap, units);
1476
+ roomIssues.push(...overlap.roomIssues);
1477
+ warnings.push(...overlap.warnings);
1478
+ return { matched, roomIssues, warnings };
1479
+ }
1480
+ function findRoomOverlaps(level, matched, seeds, units) {
1481
+ const warnings = [];
1482
+ const roomIssues = [];
1483
+ const byFace = /* @__PURE__ */ new Map();
1484
+ for (const [id, face] of matched) {
1485
+ const ids2 = byFace.get(face);
1486
+ if (ids2) ids2.push(id);
1487
+ else byFace.set(face, [id]);
1488
+ }
1489
+ for (const [face, ids2] of byFace) {
1490
+ if (ids2.length < 2) continue;
1491
+ roomIssues.push({ kind: "shared", level, spaceIds: ids2 });
1492
+ warnings.push(
1493
+ `[warn] ${level}/space.csv ${ids2.join(", ")} share one enclosed area (${fmtArea(face.signedArea, units)}): ${ids2.slice(1).join(", ")} ${ids2.length > 2 ? "are redundant rooms" : "is a redundant room"} (area 0, the area counts once in ${ids2[0]}) \u2014 a wall gap or missing room_separator likely merges these rooms, or delete the extra room`
1494
+ );
1495
+ }
1496
+ const contained = /* @__PURE__ */ new Map();
1497
+ for (const [id, face] of matched) {
1498
+ const seed = seeds.get(id);
1499
+ let parent = null;
1500
+ for (const other of byFace.keys()) {
1501
+ if (other === face || other.signedArea <= face.signedArea) continue;
1502
+ if (parent && other.signedArea >= parent.signedArea) continue;
1503
+ if (pointInPolygon(seed.x, seed.y, other.polygon)) parent = other;
1504
+ }
1505
+ if (!parent) continue;
1506
+ const list = contained.get(parent);
1507
+ if (list) list.push(id);
1508
+ else contained.set(parent, [id]);
1509
+ }
1510
+ for (const [outer, inner] of contained) {
1511
+ const outerIds = byFace.get(outer);
1512
+ roomIssues.push({ kind: "contains", level, spaceIds: outerIds, inside: inner });
1513
+ warnings.push(
1514
+ `[warn] ${level}/space.csv ${outerIds.join(", ")} polygon (${fmtArea(outer.signedArea, units)}) contains ${inner.join(", ")} \u2014 their walls don't connect to the surrounding walls, so the outer area also counts them; join the walls or add a room_separator`
1515
+ );
1516
+ }
1517
+ return { warnings, roomIssues };
1518
+ }
1519
+ function fmtArea(a, units) {
1520
+ return `${a.toFixed(1)} ${units}\xB2`;
1521
+ }
1522
+ function splitAtIntersections(segments) {
1523
+ let result = [...segments];
1524
+ let changed = true;
1525
+ while (changed) {
1526
+ changed = false;
1527
+ const allEndpoints = [];
1528
+ for (const seg of result) {
1529
+ allEndpoints.push({ x: seg.startX, y: seg.startY });
1530
+ allEndpoints.push({ x: seg.endX, y: seg.endY });
1531
+ }
1532
+ const nextResult = [];
1533
+ for (let i = 0; i < result.length; i++) {
1534
+ const seg = result[i];
1535
+ const dx = seg.endX - seg.startX;
1536
+ const dy = seg.endY - seg.startY;
1537
+ const lenSq = dx * dx + dy * dy;
1538
+ const segLen = Math.sqrt(lenSq);
1539
+ if (lenSq < TOLERANCE * TOLERANCE) {
1540
+ nextResult.push(seg);
1541
+ continue;
1542
+ }
1543
+ const splitPoints = [];
1544
+ for (const ep of allEndpoints) {
1545
+ if (Math.abs(ep.x - seg.startX) < TOLERANCE && Math.abs(ep.y - seg.startY) < TOLERANCE) continue;
1546
+ if (Math.abs(ep.x - seg.endX) < TOLERANCE && Math.abs(ep.y - seg.endY) < TOLERANCE) continue;
1547
+ const t = ((ep.x - seg.startX) * dx + (ep.y - seg.startY) * dy) / lenSq;
1548
+ if (t * segLen <= TOLERANCE || (1 - t) * segLen <= TOLERANCE) continue;
1549
+ const closestX = seg.startX + t * dx;
1550
+ const closestY = seg.startY + t * dy;
1551
+ const distSq = (ep.x - closestX) * (ep.x - closestX) + (ep.y - closestY) * (ep.y - closestY);
1552
+ if (distSq < TOLERANCE * TOLERANCE) {
1553
+ splitPoints.push({ x: ep.x, y: ep.y, t });
1554
+ }
1555
+ }
1556
+ for (let j = 0; j < result.length; j++) {
1557
+ if (j === i) continue;
1558
+ const other = result[j];
1559
+ const ox = other.endX - other.startX;
1560
+ const oy = other.endY - other.startY;
1561
+ const det = dx * oy - dy * ox;
1562
+ if (Math.abs(det) < 1e-12) continue;
1563
+ const rx = other.startX - seg.startX;
1564
+ const ry = other.startY - seg.startY;
1565
+ const t = (rx * oy - ry * ox) / det;
1566
+ const s = (rx * dy - ry * dx) / det;
1567
+ if (t * segLen <= TOLERANCE || (1 - t) * segLen <= TOLERANCE) continue;
1568
+ const otherLen = Math.hypot(ox, oy);
1569
+ if (s * otherLen <= TOLERANCE || (1 - s) * otherLen <= TOLERANCE) continue;
1570
+ splitPoints.push({
1571
+ x: seg.startX + t * dx,
1572
+ y: seg.startY + t * dy,
1573
+ t
1574
+ });
1575
+ }
1576
+ if (splitPoints.length === 0) {
1577
+ nextResult.push(seg);
1578
+ } else {
1579
+ changed = true;
1580
+ splitPoints.sort((a, b) => a.t - b.t);
1581
+ const unique = [splitPoints[0]];
1582
+ for (let k = 1; k < splitPoints.length; k++) {
1583
+ if (Math.abs(splitPoints[k].t - unique[unique.length - 1].t) * segLen > TOLERANCE) {
1584
+ unique.push(splitPoints[k]);
1585
+ }
1586
+ }
1587
+ let prevX = seg.startX, prevY = seg.startY;
1588
+ for (const sp of unique) {
1589
+ nextResult.push({ startX: prevX, startY: prevY, endX: sp.x, endY: sp.y, id: seg.id });
1590
+ prevX = sp.x;
1591
+ prevY = sp.y;
1592
+ }
1593
+ nextResult.push({ startX: prevX, startY: prevY, endX: seg.endX, endY: seg.endY, id: seg.id });
1594
+ }
1595
+ }
1596
+ result = nextResult;
1597
+ }
1598
+ return result;
1599
+ }
1600
+ function buildHalfEdgeStructure(segments) {
1601
+ const vertices = [];
1602
+ function findOrCreateVertex(x, y) {
1603
+ for (const v2 of vertices) {
1604
+ if (Math.abs(v2.x - x) < TOLERANCE && Math.abs(v2.y - y) < TOLERANCE) {
1605
+ return v2;
1606
+ }
1607
+ }
1608
+ const v = { x, y, id: vertices.length, outgoing: [] };
1609
+ vertices.push(v);
1610
+ return v;
1611
+ }
1612
+ const halfEdges = [];
1613
+ for (const seg of segments) {
1614
+ const v1 = findOrCreateVertex(seg.startX, seg.startY);
1615
+ const v2 = findOrCreateVertex(seg.endX, seg.endY);
1616
+ if (v1 === v2) continue;
1617
+ const isDuplicate = v1.outgoing.some((he) => he.to === v2);
1618
+ if (isDuplicate) continue;
1619
+ const he1 = { from: v1, to: v2, sourceId: seg.id };
1620
+ const he2 = { from: v2, to: v1, sourceId: seg.id };
1621
+ he1.twin = he2;
1622
+ he2.twin = he1;
1623
+ he1.visited = false;
1624
+ he2.visited = false;
1625
+ v1.outgoing.push(he1);
1626
+ v2.outgoing.push(he2);
1627
+ halfEdges.push(he1, he2);
1628
+ }
1629
+ for (const v of vertices) {
1630
+ v.outgoing.sort((a, b) => {
1631
+ const angleA = Math.atan2(a.to.y - v.y, a.to.x - v.x);
1632
+ const angleB = Math.atan2(b.to.y - v.y, b.to.x - v.x);
1633
+ return angleA - angleB;
1634
+ });
1635
+ }
1636
+ for (const he of halfEdges) {
1637
+ const v = he.to;
1638
+ const twinIdx = v.outgoing.indexOf(he.twin);
1639
+ if (twinIdx === -1) {
1640
+ he.next = he.twin;
1641
+ continue;
1642
+ }
1643
+ const prevIdx = (twinIdx - 1 + v.outgoing.length) % v.outgoing.length;
1644
+ he.next = v.outgoing[prevIdx];
1645
+ }
1646
+ return { vertices, halfEdges };
1647
+ }
1648
+ function traceFaces(halfEdges) {
1649
+ const faces = [];
1650
+ for (const startHe of halfEdges) {
1651
+ if (startHe.visited) continue;
1652
+ const polygon = [];
1653
+ let current = startHe;
1654
+ let count = 0;
1655
+ do {
1656
+ current.visited = true;
1657
+ polygon.push({ x: current.from.x, y: current.from.y });
1658
+ current = current.next;
1659
+ count++;
1660
+ } while (current !== startHe && count < MAX_FACE_EDGES);
1661
+ if (count >= MAX_FACE_EDGES) continue;
1662
+ let signedArea2 = 0;
1663
+ for (let i = 0; i < polygon.length; i++) {
1664
+ const j = (i + 1) % polygon.length;
1665
+ signedArea2 += polygon[i].x * polygon[j].y;
1666
+ signedArea2 -= polygon[j].x * polygon[i].y;
1667
+ }
1668
+ signedArea2 /= 2;
1669
+ faces.push({ polygon, signedArea: signedArea2 });
1670
+ }
1671
+ return faces;
1672
+ }
1673
+ function pointInPolygon(px, py, polygon) {
1674
+ let crossings = 0;
1675
+ for (let i = 0; i < polygon.length; i++) {
1676
+ const j = (i + 1) % polygon.length;
1677
+ const yi = polygon[i].y;
1678
+ const yj = polygon[j].y;
1679
+ const xi = polygon[i].x;
1680
+ const xj = polygon[j].x;
1681
+ if (yi <= py && py < yj || yj <= py && py < yi) {
1682
+ const t = (py - yi) / (yj - yi);
1683
+ const xIntersect = xi + t * (xj - xi);
1684
+ if (px < xIntersect) crossings++;
1685
+ }
1686
+ }
1687
+ return crossings % 2 === 1;
1688
+ }
1689
+
1690
+ // src/build/project-rooms.ts
1691
+ function memoryFiles(files) {
1692
+ return {
1693
+ read: (p) => files[p],
1694
+ write: (p, t) => {
1695
+ files[p] = t;
1696
+ }
1697
+ };
1698
+ }
1699
+ var BOUNDARY_TABLES2 = ["wall", "structure_wall", "curtain_wall", "room_separator"];
1700
+ function projectUnitsOf(files) {
1701
+ return unitsOfMetadata(files.read("project_metadata.json"));
1702
+ }
1703
+ function readFc(files, path) {
1704
+ const text = files.read(path);
1705
+ if (text === void 0) return null;
1706
+ try {
1707
+ return parseGeoJsonText(text, path);
1708
+ } catch {
1709
+ return null;
1710
+ }
1711
+ }
1712
+ var SNAP_TOLERANCE_M = 0.05;
1713
+ var MAX_TURN_DEG = 2;
1714
+ function snapProjectEndpoints(files, dirs) {
1715
+ const tolerance = SNAP_TOLERANCE_M / UNIT_TO_M[projectUnitsOf(files)];
1716
+ const records = [];
1717
+ for (const dir of dirs) {
1718
+ const fcs = /* @__PURE__ */ new Map();
1719
+ const endpoints = [];
1720
+ for (const table of BOUNDARY_TABLES2) {
1721
+ const fc = readFc(files, `${dir}/${table}.geojson`);
1722
+ if (!fc) continue;
1723
+ fcs.set(table, fc);
1724
+ for (const f of fc.features) {
1725
+ if (f.geometry.type !== "LineString" || f.geometry.coordinates.length < 2) continue;
1726
+ const id = String(f.properties?.id ?? "");
1727
+ if (!id) continue;
1728
+ const a = f.geometry.coordinates[0];
1729
+ const b = f.geometry.coordinates[f.geometry.coordinates.length - 1];
1730
+ const pa = { x: a[0], y: a[1] }, pb = { x: b[0], y: b[1] };
1731
+ endpoints.push({ point: pa, other: pb, table, elementId: id, side: "start" });
1732
+ endpoints.push({ point: pb, other: pa, table, elementId: id, side: "end" });
1733
+ }
1734
+ }
1735
+ const snapMap = /* @__PURE__ */ new Map();
1736
+ for (const cluster of clusterEndpoints(endpoints, tolerance)) {
1737
+ if (cluster.length <= 1) continue;
1738
+ const canonical = pickCanonical(cluster);
1739
+ const moving = cluster.filter((ep) => !same(ep.point, canonical));
1740
+ const refused = new Set(moving.filter((ep) => turnDegrees(ep.other, ep.point, canonical) > MAX_TURN_DEG).map((ep) => key(ep.point)));
1741
+ for (const ep of moving) {
1742
+ if (refused.has(key(ep.point))) continue;
1743
+ snapMap.set(`${ep.table}:${ep.elementId}:${ep.side}`, canonical);
1744
+ records.push({ level: dir, table: ep.table, elementId: ep.elementId, side: ep.side, from: ep.point, to: canonical });
1745
+ }
1746
+ }
1747
+ if (snapMap.size === 0) continue;
1748
+ for (const [table, fc] of fcs) {
1749
+ let dirty = false;
1750
+ for (const f of fc.features) {
1751
+ if (f.geometry.type !== "LineString" || f.geometry.coordinates.length < 2) continue;
1752
+ const id = String(f.properties?.id ?? "");
1753
+ const ns = snapMap.get(`${table}:${id}:start`);
1754
+ const ne = snapMap.get(`${table}:${id}:end`);
1755
+ if (!ns && !ne) continue;
1756
+ const coords = f.geometry.coordinates;
1757
+ if (ns) coords[0] = moved(coords[0], ns);
1758
+ if (ne) coords[coords.length - 1] = moved(coords[coords.length - 1], ne);
1759
+ dirty = true;
1760
+ }
1761
+ if (dirty) files.write(`${dir}/${table}.geojson`, stringifyFeatureCollection(fc));
1762
+ }
1763
+ }
1764
+ return records;
1765
+ }
1766
+ function moved(c, to) {
1767
+ return c.length === 3 ? [to.x, to.y, c[2]] : [to.x, to.y];
1768
+ }
1769
+ function clusterEndpoints(endpoints, tolerance) {
1770
+ const visited = /* @__PURE__ */ new Set();
1771
+ const clusters = [];
1772
+ for (let i = 0; i < endpoints.length; i++) {
1773
+ if (visited.has(i)) continue;
1774
+ visited.add(i);
1775
+ const cluster = [endpoints[i]];
1776
+ for (let j = i + 1; j < endpoints.length; j++) {
1777
+ if (!visited.has(j) && dist(endpoints[i].point, endpoints[j].point) < tolerance) {
1778
+ cluster.push(endpoints[j]);
1779
+ visited.add(j);
1780
+ }
1781
+ }
1782
+ clusters.push(cluster);
1783
+ }
1784
+ return clusters;
1785
+ }
1786
+ function turnDegrees(fixed, from, to) {
1787
+ const a = Math.atan2(from.y - fixed.y, from.x - fixed.x);
1788
+ const b = Math.atan2(to.y - fixed.y, to.x - fixed.x);
1789
+ let d = Math.abs(a - b) * 180 / Math.PI;
1790
+ if (d > 180) d = 360 - d;
1791
+ return d;
1792
+ }
1793
+ var key = (p) => `${p.x.toFixed(4)},${p.y.toFixed(4)}`;
1794
+ var same = (a, b) => Math.abs(a.x - b.x) <= 1e-6 && Math.abs(a.y - b.y) <= 1e-6;
1795
+ function pickCanonical(cluster) {
1796
+ const counts = /* @__PURE__ */ new Map();
1797
+ for (const ep of cluster) {
1798
+ const k = key(ep.point);
1799
+ const entry = counts.get(k);
1800
+ if (entry) entry.count++;
1801
+ else counts.set(k, { point: ep.point, count: 1 });
1802
+ }
1803
+ let best = { point: cluster[0].point, count: 0 };
1804
+ for (const entry of counts.values()) {
1805
+ if (entry.count > best.count) best = entry;
1806
+ }
1807
+ return best.point;
1808
+ }
1809
+ function dist(a, b) {
1810
+ return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
1811
+ }
1812
+ function globalIdsOnLevel(files, level) {
1813
+ const levelCsv = files.read("global/level.csv");
1814
+ if (levelCsv === void 0) return null;
1815
+ const levels = parseCsvText(levelCsv).rows.map((r) => ({ id: r.id, elevation: parseFloat(r.elevation ?? "") })).filter((l) => !isNaN(l.elevation)).sort((a, b) => a.elevation - b.elevation);
1816
+ const here = levels.find((l) => l.id === level)?.elevation;
1817
+ if (here === void 0) return null;
1818
+ const elev = new Map(levels.map((l) => [l.id, l.elevation]));
1819
+ const ids2 = /* @__PURE__ */ new Set();
1820
+ for (const table of BOUNDARY_TABLES2) {
1821
+ const csv = files.read(`global/${table}.csv`);
1822
+ const fc = readFc(files, `global/${table}.geojson`);
1823
+ if (csv === void 0 || !fc) continue;
1824
+ const props = /* @__PURE__ */ new Map();
1825
+ for (const f of fc.features) props.set(String(f.properties?.id ?? ""), f.properties ?? {});
1826
+ for (const row of parseCsvText(csv).rows) {
1827
+ const base = elev.get(row.base_level_id ?? "");
1828
+ if (base === void 0) {
1829
+ ids2.add(row.id);
1830
+ continue;
1831
+ }
1832
+ const p = props.get(row.id) ?? {};
1833
+ const above = levels.find((l) => l.elevation > base + 1e-6);
1834
+ const topLevel = elev.get(row.top_level_id ?? "") ?? above?.elevation;
1835
+ const bottom = base + (Number(p.base_offset) || 0);
1836
+ const top = topLevel === void 0 ? Infinity : topLevel + (Number(p.top_offset) || 0);
1837
+ if (bottom <= here + TOLERANCE && top > here + TOLERANCE) ids2.add(row.id);
1838
+ }
1839
+ }
1840
+ return ids2;
1841
+ }
1842
+ function boundarySegments(files, dir, only) {
1843
+ const segments = [];
1844
+ for (const table of BOUNDARY_TABLES2) {
1845
+ const fc = readFc(files, `${dir}/${table}.geojson`);
1846
+ if (!fc) continue;
1847
+ try {
1848
+ for (const f of fc.features) {
1849
+ if (f.geometry.type !== "LineString") continue;
1850
+ const id = String(f.properties?.id ?? "");
1851
+ if (!id || only && !only.has(id)) continue;
1852
+ const lg = extractLineGeometry(f);
1853
+ if (lg.length < TOLERANCE) continue;
1854
+ segments.push({ startX: lg.start_x, startY: lg.start_y, endX: lg.end_x, endY: lg.end_y, id });
1855
+ }
1856
+ } catch {
1857
+ }
1858
+ }
1859
+ return segments;
1860
+ }
1861
+ function deriveLevelRooms(files, level) {
1862
+ const spaceCsv = files.read(`${level}/space.csv`);
1863
+ if (spaceCsv === void 0) return { warnings: [], rooms: null };
1864
+ const rows = parseCsvText(spaceCsv).rows;
1865
+ if (rows.length === 0) return { warnings: [], rooms: null };
1866
+ const segments = boundarySegments(files, level);
1867
+ segments.push(...boundarySegments(files, "global", globalIdsOnLevel(files, level)));
1868
+ if (segments.length === 0) {
1869
+ return { warnings: [`${level}/ no boundary elements found for space boundary computation`], rooms: null };
1870
+ }
1871
+ const seeds = rows.map((row) => ({
1872
+ id: row.id,
1873
+ x: parseFloat(row.x ?? ""),
1874
+ y: parseFloat(row.y ?? ""),
1875
+ raw: [row.x, row.y]
1876
+ }));
1877
+ const rooms = deriveRooms(level, segments, seeds, projectUnitsOf(files));
1878
+ return { warnings: rooms.warnings, rooms };
1879
+ }
1880
+
1881
+ // src/build/space-boundary.ts
1882
+ function computeSpaceBoundaries(levelDir, globalDir) {
1883
+ const root = dirname2(levelDir.path);
1884
+ const all = dirFiles(root);
1885
+ const files = globalDir ? all : { read: (p) => p.startsWith("global/") ? void 0 : all.read(p), write: all.write };
1886
+ const { warnings, rooms } = deriveLevelRooms(files, levelDir.name);
1887
+ const roomIssues = rooms ? [...rooms.roomIssues] : [];
1888
+ if (!rooms || rooms.matched.size === 0) return { warnings, geojsonWritten: false, roomIssues };
1889
+ const lines = collectBoundaryLines(levelDir.path);
1890
+ if (globalDir) lines.push(...collectBoundaryLines(globalDir));
1891
+ const redundant = new Set(rooms.roomIssues.filter((r) => r.kind === "shared").flatMap((r) => r.spaceIds.slice(1)));
1892
+ writeSvg(levelDir.path, rooms.matched, lines, unitsPerMetre(projectUnits(root)), redundant);
1893
+ return { warnings, geojsonWritten: true, roomIssues };
1894
+ }
1895
+ function writeSvg(levelPath, matchedSpaces, lines, upm, redundant) {
1896
+ const features2 = [];
1897
+ for (const [spaceId, face] of matchedSpaces) {
1898
+ const ring = face.polygon.map((p) => [
1899
+ Number(p.x.toFixed(3)),
1900
+ Number(p.y.toFixed(3))
1901
+ ]);
1902
+ if (ring.length === 0) continue;
1903
+ const first = ring[0], last = ring[ring.length - 1];
1904
+ if (first[0] !== last[0] || first[1] !== last[1]) ring.push([first[0], first[1]]);
1905
+ features2.push({
1906
+ type: "Feature",
1907
+ properties: redundant.has(spaceId) ? { id: spaceId, net_area: 0, redundant: true } : { id: spaceId, net_area: Number(roomNetArea(face.polygon, lines, upm).toFixed(4)) },
1908
+ geometry: { type: "Polygon", coordinates: [ring] }
1909
+ });
1910
+ }
1911
+ const fc = { type: "FeatureCollection", features: features2 };
1912
+ writeFileSync(join7(levelPath, "space.geojson"), stringifyFeatureCollection(fc), "utf-8");
1913
+ }
1914
+
1915
+ // src/build/geometry-warnings.ts
1916
+ import { existsSync as existsSync7 } from "fs";
1917
+ import { dirname as dirname3, join as join8 } from "path";
1918
+ var TOLERANCE2 = 0.01;
1919
+ var BOUNDARY_TABLES3 = ["wall", "structure_wall", "curtain_wall", "room_separator"];
1920
+ function validateGeometry(dir) {
1921
+ const warnings = [];
1922
+ const layout = discoverLayout(dir);
1923
+ const unit = projectUnits(dir);
1924
+ const allDirs = [
1925
+ { name: "global", path: layout.globalDir },
1926
+ ...layout.levelDirs
1927
+ ];
1928
+ const wallGeometries = /* @__PURE__ */ new Map();
1929
+ for (const d of allDirs) {
1930
+ if (!existsSync7(d.path)) continue;
1931
+ for (const table of ["wall", "structure_wall", "curtain_wall"]) {
1932
+ const geomName = GEOJSON_FILE_NAMES[table];
1933
+ if (!geomName) continue;
1934
+ const path = join8(d.path, `${geomName}.geojson`);
1935
+ if (!existsSync7(path)) continue;
1936
+ try {
1937
+ const fc = parseGeoJsonFile(path);
1938
+ for (const f of fc.features) {
1939
+ if (f.geometry.type !== "LineString") continue;
1940
+ const id = String(f.properties?.id ?? "");
1941
+ if (!id) continue;
1942
+ const lg = extractLineGeometry(f);
1943
+ wallGeometries.set(id, { length: lg.length });
1944
+ }
1945
+ } catch {
1946
+ }
1947
+ }
1948
+ }
1949
+ for (const d of [...layout.levelDirs]) {
1950
+ if (!existsSync7(d.path)) continue;
1951
+ warnings.push(...validateLineConnectivity(d, unit));
1952
+ warnings.push(...validateHostedBounds(d, wallGeometries, unit));
1953
+ warnings.push(...validateHostedOverlap(d, unit));
1954
+ warnings.push(...validateWallOverlap(d, unit));
1955
+ }
1956
+ return warnings;
1957
+ }
1958
+ var TOUCH_SLACK = 0.02;
1959
+ var COLUMN_TABLES = ["column", "structure_column"];
1960
+ function validateLineConnectivity(levelDir, unit) {
1961
+ const warnings = [];
1962
+ const endpoints = [];
1963
+ const segments = [];
1964
+ const columns = [];
1965
+ const csvRows = (table) => {
1966
+ const m = /* @__PURE__ */ new Map();
1967
+ const p = join8(levelDir.path, `${table}.csv`);
1968
+ if (!existsSync7(p)) return m;
1969
+ try {
1970
+ for (const r of effectiveRows(dirname3(levelDir.path), table, readCsv(p).rows)) if (r.id) m.set(r.id, r);
1971
+ } catch {
1972
+ }
1973
+ return m;
1974
+ };
1975
+ for (const table of BOUNDARY_TABLES3) {
1976
+ const geomName = GEOJSON_FILE_NAMES[table];
1977
+ if (!geomName) continue;
1978
+ const path = join8(levelDir.path, `${geomName}.geojson`);
1979
+ if (!existsSync7(path)) continue;
1980
+ const attrs = csvRows(table);
1981
+ try {
1982
+ const fc = parseGeoJsonFile(path);
1983
+ for (const f of fc.features) {
1984
+ if (f.geometry.type !== "LineString") continue;
1985
+ const id = String(f.properties?.id ?? "");
1986
+ if (!id) continue;
1987
+ const lg = extractLineGeometry(f);
1988
+ const t = parseFloat(attrs.get(id)?.thickness ?? "") || 0;
1989
+ endpoints.push({ x: lg.start_x, y: lg.start_y, side: "start", elementId: id, table });
1990
+ endpoints.push({ x: lg.end_x, y: lg.end_y, side: "end", elementId: id, table });
1991
+ const arc = f.properties?.arc ? embedCircle({ start: { x: lg.start_x, y: lg.start_y }, end: { x: lg.end_x, y: lg.end_y }, arc: f.properties.arc }) : null;
1992
+ segments.push({ ax: lg.start_x, ay: lg.start_y, bx: lg.end_x, by: lg.end_y, half: t / 2, elementId: id, table, arc });
1993
+ }
1994
+ } catch {
1995
+ }
1996
+ }
1997
+ for (const table of COLUMN_TABLES) {
1998
+ const geomName = GEOJSON_FILE_NAMES[table];
1999
+ if (!geomName) continue;
2000
+ const path = join8(levelDir.path, `${geomName}.geojson`);
2001
+ if (!existsSync7(path)) continue;
2002
+ const attrs = csvRows(table);
2003
+ try {
2004
+ const fc = parseGeoJsonFile(path);
2005
+ for (const f of fc.features) {
2006
+ if (f.geometry.type !== "Point") continue;
2007
+ const [x, y] = f.geometry.coordinates;
2008
+ const r = attrs.get(String(f.properties?.id ?? ""));
2009
+ const sx = parseFloat(r?.size_x ?? "") || 0.4;
2010
+ const sy = parseFloat(r?.size_y ?? "") || sx;
2011
+ const h = Math.max(sx, sy) / 2;
2012
+ columns.push({ x0: x - h, y0: y - h, x1: x + h, y1: y + h });
2013
+ }
2014
+ } catch {
2015
+ }
2016
+ }
2017
+ const roofOpenings = [];
2018
+ {
2019
+ const path = join8(levelDir.path, "opening.geojson");
2020
+ const roofs = csvRows("roof");
2021
+ const rows = csvRows("opening");
2022
+ if (existsSync7(path) && roofs.size > 0) {
2023
+ try {
2024
+ for (const f of parseGeoJsonFile(path).features) {
2025
+ if (f.geometry.type !== "Polygon") continue;
2026
+ const host = rows.get(String(f.properties?.id ?? ""))?.host_id ?? "";
2027
+ if (roofs.has(host)) roofOpenings.push(f.geometry.coordinates[0] ?? []);
2028
+ }
2029
+ } catch {
2030
+ }
2031
+ }
2032
+ }
2033
+ const same2 = (a, b) => a.elementId === b.elementId && a.table === b.table;
2034
+ for (const ep of endpoints) {
2035
+ const atEndpoint = endpoints.some(
2036
+ (o) => o !== ep && !same2(o, ep) && Math.abs(o.x - ep.x) < TOLERANCE2 && Math.abs(o.y - ep.y) < TOLERANCE2
2037
+ );
2038
+ if (atEndpoint) continue;
2039
+ const onWall = segments.some((seg) => !same2(seg, ep) && (seg.arc ? pointNearArc(ep.x, ep.y, seg.arc, Math.max(seg.half, TOLERANCE2) + TOUCH_SLACK) : pointNearSegment(ep.x, ep.y, seg.ax, seg.ay, seg.bx, seg.by, Math.max(seg.half, TOLERANCE2) + TOUCH_SLACK)));
2040
+ if (onWall) continue;
2041
+ const onColumn = columns.some((c) => ep.x >= c.x0 - TOUCH_SLACK && ep.x <= c.x1 + TOUCH_SLACK && ep.y >= c.y0 - TOUCH_SLACK && ep.y <= c.y1 + TOUCH_SLACK);
2042
+ if (onColumn) continue;
2043
+ const onRoofOpening = roofOpenings.some((ring) => ring.some((a, i) => {
2044
+ const b = ring[(i + 1) % ring.length];
2045
+ return pointNearSegment(ep.x, ep.y, a[0], a[1], b[0], b[1], TOLERANCE2 + TOUCH_SLACK);
2046
+ }));
2047
+ if (onRoofOpening) continue;
2048
+ let nearestDist = Infinity;
2049
+ let nearestId = "";
2050
+ let nearestSide = "";
2051
+ for (const other of endpoints) {
2052
+ if (other === ep || same2(other, ep)) continue;
2053
+ const d = Math.hypot(other.x - ep.x, other.y - ep.y);
2054
+ if (d < nearestDist) {
2055
+ nearestDist = d;
2056
+ nearestId = other.elementId;
2057
+ nearestSide = other.side;
2058
+ }
2059
+ }
2060
+ const nearestInfo = nearestDist < Infinity ? ` (nearest: ${nearestId} ${nearestSide}, distance ${nearestDist.toFixed(3)} ${unit})` : "";
2061
+ warnings.push(
2062
+ `[warn] ${levelDir.name}/${ep.table}.geojson ${ep.elementId} ${ep.side} (${ep.x.toFixed(3)}, ${ep.y.toFixed(3)}) has no connected line element${nearestInfo}`
2063
+ );
2064
+ }
2065
+ return warnings;
2066
+ }
2067
+ function pointNearArc(px, py, c, tol) {
2068
+ if (Math.abs(Math.hypot(px - c.cx, py - c.cy) - c.r) > tol) return false;
2069
+ const TAU = 2 * Math.PI;
2070
+ const t = ((Math.atan2(py - c.cy, px - c.cx) - c.a0) * Math.sign(c.sweep) % TAU + TAU) % TAU;
2071
+ const slack = tol / Math.max(c.r, 1e-9);
2072
+ return t <= Math.abs(c.sweep) + slack || t >= TAU - slack;
2073
+ }
2074
+ function pointNearSegment(px, py, ax, ay, bx, by, tol) {
2075
+ const dx = bx - ax, dy = by - ay;
2076
+ const len = Math.hypot(dx, dy);
2077
+ if (len < 1e-9) return false;
2078
+ const ux = dx / len, uy = dy / len;
2079
+ const along = (px - ax) * ux + (py - ay) * uy;
2080
+ if (along < -tol || along > len + tol) return false;
2081
+ const across = Math.abs(-(px - ax) * uy + (py - ay) * ux);
2082
+ return across <= tol;
2083
+ }
2084
+ function validateHostedBounds(levelDir, wallGeometries, unit) {
2085
+ const warnings = [];
2086
+ for (const tableName of ["door", "window"]) {
2087
+ const csvPath = join8(levelDir.path, `${tableName}.csv`);
2088
+ if (!existsSync7(csvPath)) continue;
2089
+ const rows = effectiveRows(dirname3(levelDir.path), tableName, readCsv(csvPath).rows);
2090
+ for (let i = 0; i < rows.length; i++) {
2091
+ const row = rows[i];
2092
+ const hostId = row.host_id;
2093
+ const position = parseFloat(row.position ?? "");
2094
+ const width = parseFloat(row.width ?? "");
2095
+ if (!hostId || isNaN(position) || isNaN(width)) continue;
2096
+ const wallGeo = wallGeometries.get(hostId);
2097
+ if (!wallGeo) continue;
2098
+ const halfWidth = width / 2;
2099
+ if (position - halfWidth < -TOLERANCE2) {
2100
+ warnings.push(
2101
+ `[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)} ${unit}`
2102
+ );
2103
+ }
2104
+ if (position + halfWidth > wallGeo.length + TOLERANCE2) {
2105
+ warnings.push(
2106
+ `[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)} ${unit} > wall length ${wallGeo.length.toFixed(3)} ${unit}`
2107
+ );
2108
+ }
2109
+ }
2110
+ }
2111
+ return warnings;
2112
+ }
2113
+ var INSERT_DEFAULTS = {
2114
+ door: { sill: 0, height: 2.1 },
2115
+ window: { sill: 0.9, height: 1.2 },
2116
+ opening: { sill: 0, height: 2.1 }
2117
+ };
2118
+ function validateHostedOverlap(levelDir, unit) {
2119
+ const inserts = [];
2120
+ for (const tableName of ["door", "window", "opening"]) {
2121
+ const csvPath = join8(levelDir.path, `${tableName}.csv`);
2122
+ if (!existsSync7(csvPath)) continue;
2123
+ const rows = effectiveRows(dirname3(levelDir.path), tableName, readCsv(csvPath).rows);
2124
+ const d = INSERT_DEFAULTS[tableName];
2125
+ for (const row of rows) {
2126
+ const position = parseFloat(row.position ?? "");
2127
+ const width = parseFloat(row.width ?? "");
2128
+ if (!row.host_id || isNaN(position) || isNaN(width)) continue;
2129
+ const sill = row.base_offset !== void 0 && row.base_offset !== "" ? parseFloat(row.base_offset) || 0 : d.sill;
2130
+ const height = parseFloat(row.height ?? "") || d.height;
2131
+ inserts.push({ id: row.id, scope: levelDir.name, table: tableName, hostId: row.host_id, position, width, sill, height });
2132
+ }
2133
+ }
2134
+ return insertOverlaps(inserts, TOLERANCE2, unit).map((p) => `[warn] ${levelDir.name}/ ${p.message}`);
2135
+ }
2136
+ function validateWallOverlap(levelDir, unit) {
2137
+ const walls = [];
2138
+ for (const table of ["wall", "structure_wall"]) {
2139
+ const geomName = GEOJSON_FILE_NAMES[table];
2140
+ const path = join8(levelDir.path, `${geomName}.geojson`);
2141
+ if (!geomName || !existsSync7(path)) continue;
2142
+ const thickness = /* @__PURE__ */ new Map();
2143
+ const csvPath = join8(levelDir.path, `${table}.csv`);
2144
+ if (existsSync7(csvPath)) {
2145
+ try {
2146
+ for (const r of effectiveRows(dirname3(levelDir.path), table, readCsv(csvPath).rows)) thickness.set(r.id, parseFloat(r.thickness ?? "") || 0);
2147
+ } catch {
2148
+ }
2149
+ }
2150
+ try {
2151
+ for (const f of parseGeoJsonFile(path).features) {
2152
+ if (f.geometry.type !== "LineString" || f.properties?.arc) continue;
2153
+ const id = String(f.properties?.id ?? "");
2154
+ if (!id) continue;
2155
+ const lg = extractLineGeometry(f);
2156
+ walls.push({ id, scope: levelDir.name, table, a: { x: lg.start_x, y: lg.start_y }, b: { x: lg.end_x, y: lg.end_y }, thickness: thickness.get(id) || 0.2 });
2157
+ }
2158
+ } catch {
2159
+ }
2160
+ }
2161
+ return wallOverlaps(walls, TOLERANCE2, TOLERANCE2 * 10, unit).map((p) => `[warn] ${levelDir.name}/ ${p.message}`);
2162
+ }
2163
+
2164
+ // src/build/resolve-hosted-coords.ts
2165
+ import { existsSync as existsSync8 } from "fs";
2166
+ import { join as join9 } from "path";
2167
+ var TOLERANCE_M = 0.05;
2168
+ var HOSTED_TABLES = ["door", "window", "opening"];
2169
+ function resolveHostedCoords(dir) {
2170
+ const issues = [];
2171
+ const layout = discoverLayout(dir);
2172
+ const units = projectUnits(dir);
2173
+ const tolerance = metersToProject(dir, TOLERANCE_M);
2174
+ const allDirs = [
2175
+ { name: "global", path: layout.globalDir },
2176
+ ...layout.levelDirs
2177
+ ];
2178
+ for (const d of allDirs) {
2179
+ if (!existsSync8(d.path)) continue;
2180
+ const files = listFiles(d.path);
2181
+ const walls = [];
2182
+ for (const table of ["wall", "structure_wall", "curtain_wall"]) {
2183
+ const geomName = GEOJSON_FILE_NAMES[table];
2184
+ if (!geomName) continue;
2185
+ const path = join9(d.path, `${geomName}.geojson`);
2186
+ if (!existsSync8(path)) continue;
2187
+ try {
2188
+ const fc = parseGeoJsonFile(path);
2189
+ for (const f of fc.features) {
2190
+ if (f.geometry.type !== "LineString") continue;
2191
+ const id = String(f.properties?.id ?? "");
2192
+ if (!id) continue;
2193
+ const lg = extractLineGeometry(f);
2194
+ walls.push({
2195
+ id,
2196
+ start_x: lg.start_x,
2197
+ start_y: lg.start_y,
2198
+ end_x: lg.end_x,
2199
+ end_y: lg.end_y,
2200
+ length: lg.length
2201
+ });
2202
+ }
2203
+ } catch {
2204
+ }
2205
+ }
2206
+ if (walls.length === 0) continue;
2207
+ for (const table of HOSTED_TABLES) {
2208
+ const csvPath = join9(d.path, `${table}.csv`);
2209
+ if (!files.includes(`${table}.csv`)) continue;
2210
+ const csv = readCsv(csvPath);
2211
+ const hasHostX = csv.headers.includes("host_x");
2212
+ const hasHostY = csv.headers.includes("host_y");
2213
+ if (!hasHostX || !hasHostY) continue;
2214
+ let modified = false;
2215
+ for (let i = 0; i < csv.rows.length; i++) {
2216
+ const row = csv.rows[i];
2217
+ const hostX = parseFloat(row.host_x ?? "");
2218
+ const hostY = parseFloat(row.host_y ?? "");
2219
+ if (isNaN(hostX) || isNaN(hostY)) continue;
2220
+ const existingPosition = parseFloat(row.position ?? "");
2221
+ if (!isNaN(existingPosition) && row.position !== "") continue;
2222
+ const match = findNearestWall(hostX, hostY, walls, tolerance, row.host_id);
2223
+ if (!match) {
2224
+ issues.push(
2225
+ `${d.name}/${table}.csv:${i + 2} ${row.id} host_x=${hostX}, host_y=${hostY} \u2014 no wall found within ${+tolerance.toPrecision(3)} ${units}`
2226
+ );
2227
+ continue;
2228
+ }
2229
+ row.position = match.position.toFixed(4);
2230
+ if (!row.host_id || row.host_id === "") {
2231
+ row.host_id = match.wallId;
2232
+ }
2233
+ modified = true;
2234
+ }
2235
+ if (modified) {
2236
+ const cleanHeaders = csv.headers.filter((h) => h !== "host_x" && h !== "host_y");
2237
+ if (!cleanHeaders.includes("host_id")) {
2238
+ const idIdx = cleanHeaders.indexOf("id");
2239
+ cleanHeaders.splice(idIdx + 1, 0, "host_id");
2240
+ }
2241
+ if (!cleanHeaders.includes("position")) {
2242
+ const hostIdx = cleanHeaders.indexOf("host_id");
2243
+ cleanHeaders.splice(hostIdx + 1, 0, "position");
2244
+ }
2245
+ const cleanRows = csv.rows.map((row) => {
2246
+ const clean = {};
2247
+ for (const h of cleanHeaders) {
2248
+ if (row[h] !== void 0) clean[h] = row[h];
2249
+ }
2250
+ return clean;
2251
+ });
2252
+ writeCsv(csvPath, { headers: cleanHeaders, rows: cleanRows });
2253
+ }
2254
+ }
2255
+ }
2256
+ return issues;
2257
+ }
2258
+ function findNearestWall(px, py, walls, tolerance, preferredHostId) {
2259
+ let bestWallId = "";
2260
+ let bestPosition = 0;
2261
+ let bestDist = Infinity;
2262
+ for (const wall of walls) {
2263
+ const dx = wall.end_x - wall.start_x;
2264
+ const dy = wall.end_y - wall.start_y;
2265
+ const lenSq = dx * dx + dy * dy;
2266
+ if (lenSq < 1e-10) continue;
2267
+ const t = ((px - wall.start_x) * dx + (py - wall.start_y) * dy) / lenSq;
2268
+ const clampedT = Math.max(0, Math.min(1, t));
2269
+ const closestX = wall.start_x + clampedT * dx;
2270
+ const closestY = wall.start_y + clampedT * dy;
2271
+ const dist2 = Math.sqrt((px - closestX) ** 2 + (py - closestY) ** 2);
2272
+ if (preferredHostId && preferredHostId !== "") {
2273
+ if (wall.id === preferredHostId) {
2274
+ return { wallId: wall.id, position: clampedT * wall.length };
2275
+ }
2276
+ continue;
2277
+ }
2278
+ if (dist2 < bestDist) {
2279
+ bestDist = dist2;
2280
+ bestWallId = wall.id;
2281
+ bestPosition = clampedT * wall.length;
2282
+ }
2283
+ }
2284
+ if (bestDist > tolerance && !preferredHostId) return null;
2285
+ if (!bestWallId) return null;
2286
+ return { wallId: bestWallId, position: bestPosition };
2287
+ }
2288
+
2289
+ // src/build/snap-endpoints.ts
2290
+ function snapEndpoints(dir) {
2291
+ const layout = discoverLayout(dir);
2292
+ return snapProjectEndpoints(dirFiles(dir), ["global", ...layout.levelDirs.map((d) => d.name)]);
2293
+ }
2294
+
2295
+ // src/build/group-warnings.ts
2296
+ import { join as join10 } from "path";
2297
+ function groupWarningsForDir(dir) {
2298
+ const layout = discoverLayout(dir);
2299
+ const entries = [];
2300
+ for (const d of layout.levelDirs) {
2301
+ const files = listFiles(d.path).filter((f) => f.endsWith(".csv"));
2302
+ if (!files.includes("model_group.csv")) continue;
2303
+ for (const f of files) {
2304
+ try {
2305
+ entries.push({ path: `${d.name}/${f}`, tableName: f.replace(".csv", ""), data: readCsv(join10(d.path, f)) });
2306
+ } catch {
2307
+ }
2308
+ }
2309
+ }
2310
+ return groupWarnings(entries);
2311
+ }
2312
+
2313
+ // src/build/number-warnings.ts
2314
+ import { existsSync as existsSync9 } from "fs";
2315
+ import { join as join11 } from "path";
2316
+ var GROUPS = { door: "door", curtain_wall: "door", window: "window", space: "space" };
2317
+ function numberWarnings(dir) {
2318
+ const layout = discoverLayout(dir);
2319
+ const seen = /* @__PURE__ */ new Map();
2320
+ const dirs = [{ name: "global", path: layout.globalDir }, ...layout.levelDirs];
2321
+ for (const d of dirs) {
2322
+ for (const table of Object.keys(GROUPS)) {
2323
+ const path = join11(d.path, `${table}.csv`);
2324
+ if (!existsSync9(path)) continue;
2325
+ let rows;
2326
+ try {
2327
+ rows = readCsv(path).rows;
2328
+ } catch {
2329
+ continue;
2330
+ }
2331
+ rows.forEach((row, i) => {
2332
+ const marks = table === "curtain_wall" ? (row.door_numbers ?? "").split(";") : [row.number ?? ""];
2333
+ for (const raw of marks) {
2334
+ const n = raw.trim();
2335
+ if (!n) continue;
2336
+ const k = `${GROUPS[table]}|${n}`;
2337
+ const at = `${d.name}/${table}.csv:${i + 2}`;
2338
+ const list = seen.get(k);
2339
+ if (list) list.push(at);
2340
+ else seen.set(k, [at]);
2341
+ }
2342
+ });
2343
+ }
2344
+ }
2345
+ const out = [];
2346
+ for (const [k, at] of seen) {
2347
+ if (at.length < 2) continue;
2348
+ const [group, n] = k.split("|");
2349
+ out.push(`${at[0]} ${group} number "${n}" is used ${at.length} times (${at.join(", ")})`);
2350
+ }
2351
+ return out;
2352
+ }
2353
+
2354
+ // src/build/hints.ts
2355
+ import { existsSync as existsSync10 } from "fs";
2356
+ import { join as join12 } from "path";
2357
+ var SIZE_FIELDS = ["thickness", "width", "length", "height", "size_x", "size_y"];
2358
+ var SKIP = /* @__PURE__ */ new Set(["furniture", "railing"]);
2359
+ var MARKED = ["door", "window"];
2360
+ var LIST = 3;
2361
+ function rowsOf(path) {
2362
+ if (!existsSync10(path)) return [];
2363
+ try {
2364
+ return readCsv(path).rows;
2365
+ } catch {
2366
+ return [];
2367
+ }
2368
+ }
2369
+ function matchingType(row, fields, types) {
2370
+ return types.find((t) => {
2371
+ const v = typeValues(t);
2372
+ let sized = false;
2373
+ for (const f of fields) {
2374
+ const own = (row[f] ?? "").trim();
2375
+ if (!own) continue;
2376
+ if (v[f] === void 0) return false;
2377
+ if (!sameValue(own, v[f])) return false;
2378
+ if (SIZE_FIELDS.includes(f)) sized = true;
2379
+ }
2380
+ return sized;
2381
+ });
2382
+ }
2383
+ var short = (v) => Number.isFinite(Number(v)) ? String(Math.round(Number(v) * 1e4) / 1e4) : v;
2384
+ var ids = (list) => list.slice(0, LIST).map((r) => r.at).join(", ") + (list.length > LIST ? ", \u2026" : "");
2385
+ function authoringHints(dir) {
2386
+ const registry = buildRegistry(getSpecDir());
2387
+ const layout = discoverLayout(dir);
2388
+ const dirs = [{ name: "global", path: layout.globalDir }, ...layout.levelDirs];
2389
+ const catalog = loadCatalog(dir);
2390
+ const out = [];
2391
+ for (const [table, def] of [...registry].sort(([a], [b]) => a.localeCompare(b))) {
2392
+ if (!def.typeTable || SKIP.has(table)) continue;
2393
+ const fields = typeParamFields(table);
2394
+ const sizeFields = fields.filter((f) => SIZE_FIELDS.includes(f));
2395
+ if (sizeFields.length === 0) continue;
2396
+ const raw = [];
2397
+ for (const d of dirs) {
2398
+ for (const row of rowsOf(join12(d.path, `${table}.csv`))) {
2399
+ if (row.type_id || !sizeFields.some((f) => (row[f] ?? "").trim())) continue;
2400
+ raw.push({ at: `${d.name}/${row.id}`, id: row.id, row });
2401
+ }
2402
+ }
2403
+ if (raw.length === 0) continue;
2404
+ const types = [...catalog.types.values()].filter((t) => t.table === def.typeTable);
2405
+ const byType = /* @__PURE__ */ new Map();
2406
+ const unmatched = [];
2407
+ for (const r of raw) {
2408
+ const t = matchingType(r.row, fields, types);
2409
+ if (!t) {
2410
+ unmatched.push(r);
2411
+ continue;
2412
+ }
2413
+ const list = byType.get(t.id);
2414
+ if (list) list.push(r);
2415
+ else byType.set(t.id, [r]);
2416
+ }
2417
+ const parts = [];
2418
+ if (byType.size > 0) {
2419
+ const matched = [...byType].map(([id, list]) => `${id} \u2190 ${list.length} (${ids(list)})`).join("; ");
2420
+ const set = fields.filter((f) => [...byType.values()].some((l) => l.some((r) => (r.row[f] ?? "").trim())));
2421
+ parts.push(`same size as a ${def.typeTable}: ${matched} \u2014 set type_id, clear ${set.join("/")} (check the material)`);
2422
+ }
2423
+ if (unmatched.length > 0) {
2424
+ const shown = sizeFields.filter((f) => unmatched.some((r) => (r.row[f] ?? "").trim()));
2425
+ const sizes = /* @__PURE__ */ new Map();
2426
+ for (const r of unmatched) {
2427
+ const k = shown.map((f) => r.row[f] ? short(r.row[f]) : "-").join("\xD7");
2428
+ sizes.set(k, (sizes.get(k) ?? 0) + 1);
2429
+ }
2430
+ const top = [...sizes].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([k, n]) => `${k} \xD7${n}`).join(", ");
2431
+ parts.push(`${unmatched.length} in ${sizes.size} size(s) [${shown.join("\xD7")}: ${top}${sizes.size > 4 ? ", \u2026" : ""}] \u2014 add a ${def.typeTable} row per size (or use an existing one) and set type_id`);
2432
+ }
2433
+ out.push(`[hint] ${table}: ${raw.length} row(s) without type_id; ${parts.join("; ")}`);
2434
+ }
2435
+ for (const table of MARKED) {
2436
+ const unmarked = [];
2437
+ for (const d of dirs) {
2438
+ for (const row of rowsOf(join12(d.path, `${table}.csv`))) {
2439
+ if (!(row.number ?? "").trim()) unmarked.push({ at: `${d.name}/${row.id}`, id: row.id, row });
2440
+ }
2441
+ }
2442
+ if (unmarked.length > 0) {
2443
+ out.push(`[hint] ${table}: ${unmarked.length} row(s) without a number (mark: tags and schedules show it; unique project-wide): ${ids(unmarked)}`);
2444
+ }
2445
+ }
2446
+ return out;
2447
+ }
2448
+
2449
+ // src/build/index.ts
2450
+ function build(dir) {
2451
+ const snaps = snapEndpoints(dir);
2452
+ const resolveIssues = resolveHostedCoords(dir);
2453
+ const issues = [...resolveIssues, ...validate(dir)];
2454
+ const warnings = [...validateGeometry(dir), ...typeWarnings(dir), ...groupWarningsForDir(dir), ...curtainWallWarnings(dir), ...validateStairs(dir).warnings, ...numberWarnings(dir)];
2455
+ warnings.push(...mepWarnings(dir));
2456
+ issues.push(...mepErrors(dir));
2457
+ const artifacts = [];
2458
+ const roomIssues = [];
2459
+ const layout = discoverLayout(dir);
2460
+ for (const levelDir of layout.levelDirs) {
2461
+ const spaceCsvPath = join13(levelDir.path, "space.csv");
2462
+ if (!existsSync11(spaceCsvPath)) continue;
2463
+ const result = computeSpaceBoundaries(levelDir, layout.globalDir);
2464
+ warnings.push(...result.warnings);
2465
+ roomIssues.push(...result.roomIssues);
2466
+ if (result.geojsonWritten) {
2467
+ artifacts.push(`${levelDir.name}/space.geojson`);
2468
+ }
2469
+ }
2470
+ return { issues, warnings, artifacts, snappedEndpoints: snaps.length, snaps, roomIssues, hints: authoringHints(dir) };
2471
+ }
2472
+ function validateOnly(dir) {
2473
+ const scratch = mkdtempSync(join13(tmpdir(), "bimdown-validate-"));
2474
+ try {
2475
+ copyData(dir, scratch);
2476
+ return build(scratch);
2477
+ } finally {
2478
+ rmSync(scratch, { recursive: true, force: true });
2479
+ }
2480
+ }
2481
+ function copyData(from, to) {
2482
+ for (const e of readdirSync2(from, { withFileTypes: true })) {
2483
+ const src = join13(from, e.name), dest = join13(to, e.name);
2484
+ if (e.isDirectory()) {
2485
+ mkdirSync(dest);
2486
+ copyData(src, dest);
2487
+ } else if (/\.(csv|geojson|json)$/i.test(e.name)) copyFileSync(src, dest);
2488
+ else symlinkSync(src, dest);
2489
+ }
2490
+ }
2491
+
2492
+ export {
2493
+ roomNetArea,
2494
+ deriveRooms,
2495
+ memoryFiles,
2496
+ snapProjectEndpoints,
2497
+ deriveLevelRooms,
2498
+ build,
2499
+ validateOnly
2500
+ };
2501
+ //# sourceMappingURL=chunk-KWSGJUMZ.js.map