@kruschdev/pascal-plugin-plumbing 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,663 @@
1
+ /**
2
+ * Pure deterministic IPC / UPC / IFGC / IRC sizing calculations:
3
+ * - DFU horizontal branch, vertical stack, and building drain sizing
4
+ * - Vent stack sizing & trap-arm distance verification
5
+ * - WSFU -> Hunter's Curve GPM, velocity, and Hazen-Williams pressure drop
6
+ * - Water heater (tank / tankless / HPWH) & expansion tank sizing
7
+ * - IFGC longest-length fuel-gas pipe sizing
8
+ * - IRC M1502.4 rigid dryer vent effective-length check
9
+ */
10
+
11
+ import { IPC_RULE_THRESHOLDS } from './rules'
12
+ import {
13
+ type CodeEdition,
14
+ HUNTERS_CURVE_WSFU_TO_GPM,
15
+ IFGC_GAS_BLACK_IRON_KBTUH,
16
+ IFGC_GAS_CSST_KBTUH,
17
+ IPC_BUILDING_DRAIN_MAX_DFU,
18
+ IPC_HORIZONTAL_BRANCH_MAX_DFU,
19
+ IPC_MAX_TRAP_ARM_FT,
20
+ IPC_VENT_SIZING_TABLE,
21
+ type OccupancyType,
22
+ PIPE_NOMINAL_INCHES,
23
+ type PipeNominalSize,
24
+ SUPPLY_ID_INCHES,
25
+ SUPPLY_MATERIAL_HYDRAULICS,
26
+ comparePipeSizes,
27
+ largerPipeSize,
28
+ round2,
29
+ } from './tables'
30
+
31
+ export type DrainSizingResult = {
32
+ dfu: number
33
+ recommendedSize: PipeNominalSize
34
+ minSlopeInPerFt: 0.125 | 0.25
35
+ maxAllowedDfuAtSize: number
36
+ codeRef: string
37
+ }
38
+
39
+ /**
40
+ * Minimum code slope (IPC Table 704.1):
41
+ * - <= 2-1/2": 1/4" per foot (0.25 in/ft = 2.08%)
42
+ * - >= 3": 1/8" per foot minimum (0.125 in/ft = 1.04%), 1/4" per foot preferred.
43
+ */
44
+ export function getMinRequiredDrainSlopeInPerFt(size: PipeNominalSize): 0.125 | 0.25 {
45
+ if (size === '3"' || size === '4"' || size === '6"') return IPC_RULE_THRESHOLDS.drainSlopeLargeInPerFt
46
+ return IPC_RULE_THRESHOLDS.drainSlopeSmallInPerFt
47
+ }
48
+
49
+ /**
50
+ * Size a horizontal fixture branch per IPC Table 710.1(2).
51
+ * Enforces >= 3" whenever a water closet is upstream and non-decreasing downstream sizing.
52
+ */
53
+ export function sizeDrainBranch(params: {
54
+ dfu: number
55
+ hasWaterCloset?: boolean
56
+ waterClosetCount?: number
57
+ minUpstreamSize?: PipeNominalSize
58
+ codeEdition?: CodeEdition
59
+ }): DrainSizingResult {
60
+ const { dfu, hasWaterCloset = false, waterClosetCount = 0, minUpstreamSize, codeEdition = 'IPC-2021' } = params
61
+ const effectiveWc = hasWaterCloset || waterClosetCount > 0
62
+ let chosen = IPC_HORIZONTAL_BRANCH_MAX_DFU[IPC_HORIZONTAL_BRANCH_MAX_DFU.length - 1]!
63
+ for (const row of IPC_HORIZONTAL_BRANCH_MAX_DFU) {
64
+ if (dfu <= row.maxBranchDfu) {
65
+ chosen = row
66
+ break
67
+ }
68
+ }
69
+
70
+ let size = chosen.size
71
+ // IPC Table 710.1(2) footnote b: max 2 water closets on a 3" horizontal branch (3+ WCs -> 4")
72
+ if (waterClosetCount > 2) {
73
+ size = largerPipeSize(size, '4"')
74
+ } else if (effectiveWc) {
75
+ size = largerPipeSize(size, '3"')
76
+ }
77
+ if (minUpstreamSize) {
78
+ size = largerPipeSize(size, minUpstreamSize)
79
+ }
80
+
81
+ const finalRow =
82
+ IPC_HORIZONTAL_BRANCH_MAX_DFU.find((r) => r.size === size) ??
83
+ IPC_HORIZONTAL_BRANCH_MAX_DFU[IPC_HORIZONTAL_BRANCH_MAX_DFU.length - 1]!
84
+
85
+ return {
86
+ dfu: round2(dfu),
87
+ recommendedSize: size,
88
+ minSlopeInPerFt: getMinRequiredDrainSlopeInPerFt(size),
89
+ maxAllowedDfuAtSize: finalRow.maxBranchDfu,
90
+ codeRef: codeEdition === 'UPC-2021' ? 'UPC Table 703.2' : 'IPC Table 710.1(2)',
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Size the main building drain / sewer per IPC Table 710.1(1).
96
+ */
97
+ export function sizeBuildingDrain(params: {
98
+ totalDfu: number
99
+ slopeInPerFt?: 0.125 | 0.25 | 0.5
100
+ hasWaterCloset?: boolean
101
+ waterClosetCount?: number
102
+ codeEdition?: CodeEdition
103
+ }): DrainSizingResult {
104
+ const {
105
+ totalDfu,
106
+ slopeInPerFt = 0.25,
107
+ hasWaterCloset = true,
108
+ waterClosetCount = hasWaterCloset ? 1 : 0,
109
+ codeEdition = 'IPC-2021',
110
+ } = params
111
+
112
+ let chosen = IPC_BUILDING_DRAIN_MAX_DFU[IPC_BUILDING_DRAIN_MAX_DFU.length - 1]!
113
+ for (const row of IPC_BUILDING_DRAIN_MAX_DFU) {
114
+ const cap =
115
+ slopeInPerFt <= 0.125
116
+ ? row.slopeEighth
117
+ : slopeInPerFt >= 0.5
118
+ ? row.slopeHalf
119
+ : row.slopeQuarter
120
+ if (cap !== null && totalDfu <= cap) {
121
+ chosen = row
122
+ break
123
+ }
124
+ }
125
+
126
+ let size = chosen.size
127
+ // IPC 710.1: building drain receiving discharge of 3+ water closets or > 20 DFU is commonly 4"; min 3" with any WC
128
+ if (waterClosetCount >= 4) {
129
+ size = largerPipeSize(size, '4"')
130
+ } else if (hasWaterCloset || waterClosetCount > 0) {
131
+ size = largerPipeSize(size, '3"')
132
+ }
133
+
134
+ const finalRow =
135
+ IPC_BUILDING_DRAIN_MAX_DFU.find((r) => r.size === size) ??
136
+ IPC_BUILDING_DRAIN_MAX_DFU[IPC_BUILDING_DRAIN_MAX_DFU.length - 1]!
137
+ const finalCap =
138
+ slopeInPerFt <= 0.125
139
+ ? (finalRow.slopeEighth ?? finalRow.slopeQuarter)
140
+ : slopeInPerFt >= 0.5
141
+ ? finalRow.slopeHalf
142
+ : finalRow.slopeQuarter
143
+
144
+ return {
145
+ dfu: round2(totalDfu),
146
+ recommendedSize: size,
147
+ minSlopeInPerFt: getMinRequiredDrainSlopeInPerFt(size),
148
+ maxAllowedDfuAtSize: finalCap,
149
+ codeRef: codeEdition === 'UPC-2021' ? 'UPC Table 703.2' : 'IPC Table 710.1(1)',
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Size the main vent stack per IPC Table 906.1 & IPC 903.1 (at least one 3" main stack in residential buildings).
155
+ */
156
+ export function sizeVentStack(params: {
157
+ totalDfu: number
158
+ isMainStack?: boolean
159
+ developedLengthFt?: number
160
+ }): { recommendedSize: PipeNominalSize; maxDevelopedFt: number; codeRef: string } {
161
+ const { totalDfu, isMainStack = true, developedLengthFt = 0 } = params
162
+ let row = IPC_VENT_SIZING_TABLE[IPC_VENT_SIZING_TABLE.length - 1]!
163
+ for (const entry of IPC_VENT_SIZING_TABLE) {
164
+ if (totalDfu <= entry.maxDfu && developedLengthFt <= entry.maxDevelopedFt) {
165
+ row = entry
166
+ break
167
+ }
168
+ }
169
+ const minRequiredSize = isMainStack ? largerPipeSize(row.minVentIn, '3"') : row.minVentIn
170
+ const finalRow =
171
+ IPC_VENT_SIZING_TABLE.find(
172
+ (entry) =>
173
+ comparePipeSizes(entry.minVentIn, minRequiredSize) >= 0 &&
174
+ totalDfu <= entry.maxDfu &&
175
+ developedLengthFt <= entry.maxDevelopedFt,
176
+ ) ??
177
+ IPC_VENT_SIZING_TABLE.find((entry) => comparePipeSizes(entry.minVentIn, minRequiredSize) >= 0) ??
178
+ IPC_VENT_SIZING_TABLE[IPC_VENT_SIZING_TABLE.length - 1]!
179
+ return {
180
+ recommendedSize: finalRow.minVentIn,
181
+ maxDevelopedFt: finalRow.maxDevelopedFt,
182
+ codeRef: isMainStack ? 'IPC 903.1 / Table 906.1' : 'IPC Table 906.1',
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Check trap-arm developed distance against IPC Table 909.1.
188
+ */
189
+ export function checkTrapArmDistance(trapSize: PipeNominalSize, distanceFt: number): {
190
+ ok: boolean
191
+ maxAllowedFt: number
192
+ distanceFt: number
193
+ codeRef: string
194
+ } {
195
+ const maxAllowedFt = IPC_MAX_TRAP_ARM_FT[trapSize] ?? 6
196
+ return {
197
+ ok: distanceFt <= maxAllowedFt + 0.05,
198
+ maxAllowedFt,
199
+ distanceFt: round2(distanceFt),
200
+ codeRef: 'IPC Table 909.1',
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Convert Water Supply Fixture Units (WSFU) to Peak Demand GPM via Modified Hunter's Curve
206
+ * (linear interpolation across IPC Table E103.3(3)).
207
+ */
208
+ export function wsfuToGpm(totalWsfu: number, flushType: 'flush-tank' | 'flushometer' = 'flush-tank'): number {
209
+ if (totalWsfu <= 0) return 0
210
+ const rows = HUNTERS_CURVE_WSFU_TO_GPM
211
+ const field = flushType === 'flushometer' ? 'gpmFlushometer' : 'gpmTank'
212
+
213
+ if (totalWsfu <= rows[0]!.wsfu) {
214
+ return round2((totalWsfu / rows[0]!.wsfu) * rows[0]![field])
215
+ }
216
+ for (let i = 1; i < rows.length; i++) {
217
+ const prev = rows[i - 1]!
218
+ const cur = rows[i]!
219
+ if (totalWsfu <= cur.wsfu) {
220
+ const t = (totalWsfu - prev.wsfu) / (cur.wsfu - prev.wsfu)
221
+ return round2(prev[field] + t * (cur[field] - prev[field]))
222
+ }
223
+ }
224
+ // Extrapolate gently above 200 WSFU
225
+ const last = rows[rows.length - 1]!
226
+ const prev = rows[rows.length - 2]!
227
+ const slope = (last[field] - prev[field]) / (last.wsfu - prev.wsfu)
228
+ return round2(last[field] + slope * (totalWsfu - last.wsfu))
229
+ }
230
+
231
+ export type SupplyHydraulicsResult = {
232
+ size: PipeNominalSize
233
+ innerDiameterIn: number
234
+ gpm: number
235
+ velocityFps: number
236
+ maxVelocityFps: number
237
+ velocityOk: boolean
238
+ frictionLossPsiPer100Ft: number
239
+ totalFrictionLossPsi: number
240
+ codeRef: string
241
+ }
242
+
243
+ /**
244
+ * Compute water velocity (ft/s) and Hazen-Williams pressure loss (psi/100 ft) for a given supply pipe.
245
+ */
246
+ export function calculateSupplyHydraulics(params: {
247
+ gpm: number
248
+ size: PipeNominalSize
249
+ material?: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc'
250
+ isHot?: boolean
251
+ lengthFt?: number
252
+ }): SupplyHydraulicsResult {
253
+ const { gpm, size, material = 'pex-a', isHot = false, lengthFt = 50 } = params
254
+ const hyd = SUPPLY_MATERIAL_HYDRAULICS[material]
255
+ const idMap = SUPPLY_ID_INCHES[material]
256
+ const idIn = idMap[size] ?? round2((PIPE_NOMINAL_INCHES[size] ?? 0.75) * 0.85)
257
+
258
+ // v (ft/s) = 0.4085 * Q (gpm) / d(in)^2
259
+ const velocityFps = gpm > 0 ? round2((0.4085 * gpm) / (idIn * idIn)) : 0
260
+ const maxVelocityFps = isHot ? hyd.maxVelocityHotFps : hyd.maxVelocityColdFps
261
+
262
+ // Hazen-Williams: hf (psi/100ft) = 452 * Q^1.852 / (C^1.852 * d^4.87)
263
+ const frictionLossPsiPer100Ft =
264
+ gpm > 0
265
+ ? round2(
266
+ (452 * Math.pow(gpm, 1.852)) / (Math.pow(hyd.cFactor, 1.852) * Math.pow(idIn, 4.87)),
267
+ )
268
+ : 0
269
+ const totalFrictionLossPsi = round2((frictionLossPsiPer100Ft * lengthFt) / 100)
270
+
271
+ return {
272
+ size,
273
+ innerDiameterIn: idIn,
274
+ gpm: round2(gpm),
275
+ velocityFps,
276
+ maxVelocityFps,
277
+ velocityOk: velocityFps <= maxVelocityFps,
278
+ frictionLossPsiPer100Ft,
279
+ totalFrictionLossPsi,
280
+ codeRef: 'IPC 604.3 / Appendix E',
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Select the smallest compliant domestic water supply pipe size that stays within velocity & friction limits.
286
+ */
287
+ export function sizeSupplyPipe(params: {
288
+ wsfu: number
289
+ material?: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc'
290
+ isHot?: boolean
291
+ lengthFt?: number
292
+ minSize?: PipeNominalSize
293
+ flushType?: 'flush-tank' | 'flushometer'
294
+ maxFrictionPsiPer100Ft?: number
295
+ }): SupplyHydraulicsResult {
296
+ const {
297
+ wsfu,
298
+ material = 'pex-a',
299
+ isHot = false,
300
+ lengthFt = 50,
301
+ minSize = '1/2"',
302
+ flushType = 'flush-tank',
303
+ maxFrictionPsiPer100Ft = 15,
304
+ } = params
305
+ const gpm = wsfuToGpm(wsfu, flushType)
306
+ const candidates: PipeNominalSize[] = ['1/2"', '3/4"', '1"', '1-1/4"', '1-1/2"', '2"', '2-1/2"', '3"', '4"', '6"']
307
+ const startIdx = Math.max(0, candidates.indexOf(minSize))
308
+
309
+ let lastResult = calculateSupplyHydraulics({
310
+ gpm,
311
+ size: candidates[candidates.length - 1]!,
312
+ material,
313
+ isHot,
314
+ lengthFt,
315
+ })
316
+ for (let i = startIdx; i < candidates.length; i++) {
317
+ const res = calculateSupplyHydraulics({
318
+ gpm,
319
+ size: candidates[i]!,
320
+ material,
321
+ isHot,
322
+ lengthFt,
323
+ })
324
+ lastResult = res
325
+ if (res.velocityOk && res.frictionLossPsiPer100Ft <= maxFrictionPsiPer100Ft) {
326
+ return res
327
+ }
328
+ }
329
+ return lastResult
330
+ }
331
+
332
+ export type WaterHeaterSizingResult = {
333
+ recommendedTankGal: number
334
+ recommendedTanklessGpm: number
335
+ recommendedTanklessBtuh: number
336
+ expansionTankGal: number
337
+ electricalLoadWatts: number
338
+ electricalBreakerAmps: number
339
+ gasBtuh: number
340
+ hpwhMinRoomCuFt: number
341
+ codeRef: string
342
+ }
343
+
344
+ /**
345
+ * Size residential or light-commercial water heating & thermal expansion tank (IPC 501 / 607.3).
346
+ */
347
+ export function sizeWaterHeater(params: {
348
+ bathrooms: number
349
+ bedrooms: number
350
+ occupancy?: OccupancyType
351
+ fuelType?: 'gas' | 'electric' | 'hpwh' | 'tankless-gas'
352
+ peakGpm?: number
353
+ }): WaterHeaterSizingResult {
354
+ const { bathrooms, bedrooms, occupancy = 'residential', fuelType = 'gas', peakGpm } = params
355
+ const effectiveBaths = Math.max(1, bathrooms)
356
+ const effectiveBeds = Math.max(1, bedrooms)
357
+
358
+ let recommendedTankGal = 40
359
+ if (occupancy === 'commercial' || effectiveBaths >= 4 || effectiveBeds >= 5) {
360
+ recommendedTankGal = 75
361
+ } else if (effectiveBaths >= 2 || effectiveBeds >= 3) {
362
+ recommendedTankGal = 50
363
+ }
364
+
365
+ const simultaneousGpm =
366
+ peakGpm !== undefined
367
+ ? occupancy === 'commercial'
368
+ ? Math.max(0, peakGpm)
369
+ : Math.min(Math.max(0, peakGpm), 11)
370
+ : Math.max(5.5, effectiveBaths * 2.5 + 1.5)
371
+ const recommendedTanklessGpm =
372
+ peakGpm !== undefined && peakGpm <= 0 ? 0 : round2(Math.max(6.5, simultaneousGpm))
373
+ // BTU/hr = GPM * 500 * deltaT (70°F typical) / 0.90 efficiency
374
+ const recommendedTanklessBtuh = Math.ceil((recommendedTanklessGpm * 500 * 70) / 0.9 / 10000) * 10000
375
+
376
+ // IPC 607.3 thermal expansion tank: 2 gal for <= 50 gal tank, 4.5 gal for 55-80 gal tank
377
+ const expansionTankGal = recommendedTankGal <= 50 ? 2.0 : 4.5
378
+
379
+ const electricalLoadWatts =
380
+ fuelType === 'electric' || fuelType === 'hpwh'
381
+ ? 4500
382
+ : fuelType === 'tankless-gas'
383
+ ? 300
384
+ : 0
385
+ const electricalBreakerAmps =
386
+ fuelType === 'electric' || fuelType === 'hpwh'
387
+ ? 30
388
+ : fuelType === 'tankless-gas'
389
+ ? 15
390
+ : 0
391
+ const gasBtuh =
392
+ fuelType === 'tankless-gas'
393
+ ? recommendedTanklessBtuh
394
+ : fuelType === 'gas'
395
+ ? recommendedTankGal >= 75
396
+ ? 75000
397
+ : 40000
398
+ : 0
399
+
400
+ return {
401
+ recommendedTankGal,
402
+ recommendedTanklessGpm,
403
+ recommendedTanklessBtuh,
404
+ expansionTankGal,
405
+ electricalLoadWatts,
406
+ electricalBreakerAmps,
407
+ gasBtuh,
408
+ hpwhMinRoomCuFt: 700,
409
+ codeRef: 'IPC 501 / 607.3',
410
+ }
411
+ }
412
+
413
+ export type FuelGasSizingResult = {
414
+ totalBtuh: number
415
+ longestRunFt: number
416
+ material: 'black-iron' | 'csst'
417
+ recommendedSize: PipeNominalSize
418
+ capacityBtuh: number
419
+ ok: boolean
420
+ codeRef: string
421
+ }
422
+
423
+ /**
424
+ * Longest-length natural gas pipe sizing per IFGC Table 402.4(2) (Black Iron) & Table 402.4(15) (CSST).
425
+ */
426
+ export function sizeFuelGasPipe(params: {
427
+ totalBtuh: number
428
+ longestRunFt: number
429
+ material?: 'black-iron' | 'csst'
430
+ }): FuelGasSizingResult {
431
+ const { totalBtuh, longestRunFt, material = 'black-iron' } = params
432
+ const kbtuh = Math.max(0, totalBtuh / 1000)
433
+ const exceedsMaxTableLength = longestRunFt > IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt
434
+
435
+ if (material === 'csst') {
436
+ const row =
437
+ IFGC_GAS_CSST_KBTUH.find((r) => longestRunFt <= r.maxLengthFt) ??
438
+ IFGC_GAS_CSST_KBTUH[IFGC_GAS_CSST_KBTUH.length - 1]!
439
+ const sizes: Array<'1/2"' | '3/4"' | '1"' | '1-1/4"'> = ['1/2"', '3/4"', '1"', '1-1/4"']
440
+ for (const sz of sizes) {
441
+ if (kbtuh <= row.capacityBySize[sz]) {
442
+ return {
443
+ totalBtuh,
444
+ longestRunFt: round2(longestRunFt),
445
+ material,
446
+ recommendedSize: sz,
447
+ capacityBtuh: row.capacityBySize[sz] * 1000,
448
+ ok: !exceedsMaxTableLength,
449
+ codeRef: 'IFGC Table 402.4(15)',
450
+ }
451
+ }
452
+ }
453
+ return {
454
+ totalBtuh,
455
+ longestRunFt: round2(longestRunFt),
456
+ material,
457
+ recommendedSize: '1-1/4"',
458
+ capacityBtuh: row.capacityBySize['1-1/4"'] * 1000,
459
+ ok: false,
460
+ codeRef: 'IFGC Table 402.4(15)',
461
+ }
462
+ }
463
+
464
+ const row =
465
+ IFGC_GAS_BLACK_IRON_KBTUH.find((r) => longestRunFt <= r.maxLengthFt) ??
466
+ IFGC_GAS_BLACK_IRON_KBTUH[IFGC_GAS_BLACK_IRON_KBTUH.length - 1]!
467
+ const sizes: Array<'1/2"' | '3/4"' | '1"' | '1-1/4"' | '1-1/2"' | '2"'> = [
468
+ '1/2"',
469
+ '3/4"',
470
+ '1"',
471
+ '1-1/4"',
472
+ '1-1/2"',
473
+ '2"',
474
+ ]
475
+ for (const sz of sizes) {
476
+ if (kbtuh <= row.capacityBySize[sz]) {
477
+ return {
478
+ totalBtuh,
479
+ longestRunFt: round2(longestRunFt),
480
+ material,
481
+ recommendedSize: sz,
482
+ capacityBtuh: row.capacityBySize[sz] * 1000,
483
+ ok: !exceedsMaxTableLength,
484
+ codeRef: 'IFGC Table 402.4(2)',
485
+ }
486
+ }
487
+ }
488
+ return {
489
+ totalBtuh,
490
+ longestRunFt: round2(longestRunFt),
491
+ material,
492
+ recommendedSize: '2"',
493
+ capacityBtuh: row.capacityBySize['2"'] * 1000,
494
+ ok: false,
495
+ codeRef: 'IFGC Table 402.4(2)',
496
+ }
497
+ }
498
+
499
+ export type FuelGasGraphSegment = {
500
+ id: string
501
+ lengthFt: number
502
+ sourceNodeId?: string
503
+ targetNodeId?: string
504
+ }
505
+
506
+ /**
507
+ * IFGC 402.4.1 (Longest Length Method): traverse connected `fuel-gas` `sourceNodeId -> targetNodeId`
508
+ * graphs (with cycle guard) to compute each connected gas network's root-to-most-remote-outlet
509
+ * developed length in feet.
510
+ */
511
+ export function computeFuelGasDevelopedLengths(
512
+ segments: ReadonlyArray<FuelGasGraphSegment>,
513
+ ): {
514
+ byRunId: Map<string, number>
515
+ maxDevelopedLengthFt: number
516
+ } {
517
+ const byRunId = new Map<string, number>()
518
+ if (segments.length === 0) return { byRunId, maxDevelopedLengthFt: 0 }
519
+
520
+ const segById = new Map<string, FuelGasGraphSegment>()
521
+ const bySourceNode = new Map<string, string[]>()
522
+ const byTargetNode = new Map<string, string[]>()
523
+ const downstream = new Map<string, Set<string>>()
524
+ const undirected = new Map<string, Set<string>>()
525
+
526
+ const linkUndirected = (a: string, b: string) => {
527
+ if (a === b) return
528
+ undirected.get(a)?.add(b)
529
+ undirected.get(b)?.add(a)
530
+ }
531
+
532
+ for (const seg of segments) {
533
+ segById.set(seg.id, seg)
534
+ downstream.set(seg.id, new Set())
535
+ undirected.set(seg.id, new Set())
536
+ if (seg.sourceNodeId) {
537
+ const list = bySourceNode.get(seg.sourceNodeId)
538
+ if (list) list.push(seg.id)
539
+ else bySourceNode.set(seg.sourceNodeId, [seg.id])
540
+ }
541
+ if (seg.targetNodeId) {
542
+ const list = byTargetNode.get(seg.targetNodeId)
543
+ if (list) list.push(seg.id)
544
+ else byTargetNode.set(seg.targetNodeId, [seg.id])
545
+ }
546
+ }
547
+
548
+ // Group runs sharing a common supply root/manifold or common junction into the same connected network
549
+ for (const ids of bySourceNode.values()) {
550
+ for (let i = 1; i < ids.length; i++) linkUndirected(ids[0]!, ids[i]!)
551
+ }
552
+ for (const ids of byTargetNode.values()) {
553
+ for (let i = 1; i < ids.length; i++) linkUndirected(ids[0]!, ids[i]!)
554
+ }
555
+
556
+ // Build directed series edges (node-mediated `a.targetNodeId === b.sourceNodeId` and direct pipe-to-pipe)
557
+ for (const a of segments) {
558
+ const out = downstream.get(a.id)!
559
+ if (a.targetNodeId) {
560
+ if (segById.has(a.targetNodeId) && a.targetNodeId !== a.id) {
561
+ out.add(a.targetNodeId)
562
+ linkUndirected(a.id, a.targetNodeId)
563
+ }
564
+ for (const nextId of bySourceNode.get(a.targetNodeId) ?? []) {
565
+ if (nextId !== a.id) {
566
+ out.add(nextId)
567
+ linkUndirected(a.id, nextId)
568
+ }
569
+ }
570
+ }
571
+ if (a.sourceNodeId && segById.has(a.sourceNodeId) && a.sourceNodeId !== a.id) {
572
+ downstream.get(a.sourceNodeId)!.add(a.id)
573
+ linkUndirected(a.sourceNodeId, a.id)
574
+ }
575
+ }
576
+
577
+ const dagMemo = new Map<string, number>()
578
+ const longestFrom = (currId: string, visited: Set<string>): { len: number; hitCycle: boolean } => {
579
+ if (visited.size === 0 && dagMemo.has(currId)) {
580
+ return { len: dagMemo.get(currId)!, hitCycle: false }
581
+ }
582
+ visited.add(currId)
583
+ const seg = segById.get(currId)!
584
+ const ownLen = Number.isFinite(seg.lengthFt) && seg.lengthFt > 0 ? seg.lengthFt : 0
585
+ let maxChild = 0
586
+ let hitCycle = false
587
+ for (const nextId of downstream.get(currId) ?? []) {
588
+ if (visited.has(nextId)) {
589
+ hitCycle = true
590
+ continue
591
+ }
592
+ if (!hitCycle && dagMemo.has(nextId)) {
593
+ const cached = dagMemo.get(nextId)!
594
+ if (cached > maxChild) maxChild = cached
595
+ continue
596
+ }
597
+ const sub = longestFrom(nextId, visited)
598
+ if (sub.hitCycle) hitCycle = true
599
+ if (sub.len > maxChild) maxChild = sub.len
600
+ }
601
+ visited.delete(currId)
602
+ const total = ownLen + maxChild
603
+ if (!hitCycle) dagMemo.set(currId, total)
604
+ return { len: total, hitCycle }
605
+ }
606
+
607
+ const seenComp = new Set<string>()
608
+ let maxDevelopedLengthFt = 0
609
+ for (const seg of segments) {
610
+ if (seenComp.has(seg.id)) continue
611
+ const comp: string[] = []
612
+ const queue: string[] = [seg.id]
613
+ seenComp.add(seg.id)
614
+ while (queue.length > 0) {
615
+ const id = queue.pop()!
616
+ comp.push(id)
617
+ for (const nb of undirected.get(id) ?? []) {
618
+ if (!seenComp.has(nb)) {
619
+ seenComp.add(nb)
620
+ queue.push(nb)
621
+ }
622
+ }
623
+ }
624
+
625
+ let compLongest = 0
626
+ for (const id of comp) {
627
+ const { len } = longestFrom(id, new Set())
628
+ if (len > compLongest) compLongest = len
629
+ }
630
+ for (const id of comp) {
631
+ byRunId.set(id, compLongest)
632
+ }
633
+ if (compLongest > maxDevelopedLengthFt) maxDevelopedLengthFt = compLongest
634
+ }
635
+
636
+ return { byRunId, maxDevelopedLengthFt }
637
+ }
638
+
639
+ /**
640
+ * IRC M1502.4.5.1 — Clothes dryer exhaust duct maximum equivalent length (35 ft; -5 ft per 90° elbow, -2.5 ft per 45°).
641
+ */
642
+ export function checkDryerVentRun(params: {
643
+ lengthFt: number
644
+ elbows90?: number
645
+ elbows45?: number
646
+ }): {
647
+ ok: boolean
648
+ lengthFt: number
649
+ effectiveLengthFt: number
650
+ maxAllowedFt: number
651
+ codeRef: string
652
+ } {
653
+ const { lengthFt, elbows90 = 2, elbows45 = 0 } = params
654
+ const effectiveLengthFt = round2(lengthFt + elbows90 * 5 + elbows45 * 2.5)
655
+ const maxAllowedFt = IPC_RULE_THRESHOLDS.dryerVentMaxEffectiveLengthFt
656
+ return {
657
+ ok: effectiveLengthFt <= maxAllowedFt,
658
+ lengthFt: round2(lengthFt),
659
+ effectiveLengthFt,
660
+ maxAllowedFt,
661
+ codeRef: 'IRC M1502.4.5.1',
662
+ }
663
+ }