@tilda-geo/bicycle-infrastructure 0.1.2 → 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.
package/dist/index.js CHANGED
@@ -1,544 +1,11 @@
1
- // src/types.ts
2
- var DISALLOWED = "DISALLOWED_VALUE";
3
-
4
- // src/helpers/highway-classes.ts
5
- var TRUNK_MOTORWAY_CLASSES = ["motorway", "motorway_link", "trunk", "trunk_link"];
6
- var MAJOR_ROAD_CLASSES = [
7
- "primary",
8
- "primary_link",
9
- "secondary",
10
- "secondary_link",
11
- "tertiary",
12
- "tertiary_link"
13
- ];
14
- var MINOR_ROAD_CLASSES = [
15
- "unclassified",
16
- "residential",
17
- "road",
18
- "living_street",
19
- "pedestrian",
20
- "service"
21
- ];
22
- var PATH_CLASSES = ["track", "path", "footway", "cycleway", "steps"];
23
- var SIDEPATH_HIGHWAY_CLASSES = /* @__PURE__ */ new Set([...PATH_CLASSES, "pedestrian"]);
24
- var ALLOWED_HIGHWAYS = /* @__PURE__ */ new Set([
25
- ...TRUNK_MOTORWAY_CLASSES,
26
- ...MAJOR_ROAD_CLASSES,
27
- ...MINOR_ROAD_CLASSES,
28
- ...PATH_CLASSES
29
- ]);
30
-
31
- // src/transform/transformations.ts
32
- var SIDES = ["left", "right"];
33
- var META_PREFIXES = ["source:", "note:"];
34
- function unnestPrefixedTags(tags, prefix, infix, dest, metaPrefix) {
35
- const metaPrefixString = metaPrefix ?? "";
36
- const fullPrefix = metaPrefixString + prefix + infix;
37
- const prefixLen = fullPrefix.length;
38
- for (const key of Object.keys(tags)) {
39
- const val = tags[key];
40
- if (val === void 0) continue;
41
- if (!key.startsWith(fullPrefix)) continue;
42
- if (key === fullPrefix) {
43
- const destinationKey = metaPrefix ? metaPrefixString.slice(0, -1) : prefix;
44
- dest[destinationKey] = val;
45
- dest._infix = infix;
46
- } else {
47
- const extractedSuffix = key.slice(prefixLen + 1);
48
- const suffixKey = extractedSuffix.match(/^[^:]*/)[0];
49
- if (infix !== "" || !(suffixKey === "left" || suffixKey === "right" || suffixKey === "both")) {
50
- const destinationKey = metaPrefix ? metaPrefixString + extractedSuffix : extractedSuffix;
51
- dest[destinationKey] = val;
52
- dest._infix = infix;
53
- }
54
- }
55
- }
56
- return dest;
57
- }
58
- var DIRECTED_PARENT_TAGS = ["cycleway:lanes", "bicycle:lanes"];
59
- var DIRECTED_SELF_TAGS = ["traffic_sign"];
60
- var SIDE_TO_DIRECTION = {
61
- "": "",
62
- both: "",
63
- left: ":backward",
64
- right: ":forward"
65
- };
66
- function convertDirectedTags(cycleway, directionReference) {
67
- const parent = cycleway._parent;
68
- const side = cycleway._side ?? "";
69
- for (const key of DIRECTED_PARENT_TAGS) {
70
- const directedKey = key + SIDE_TO_DIRECTION[side];
71
- cycleway[key] = cycleway[key] ?? parent[key] ?? parent[directedKey];
72
- }
73
- for (const key of DIRECTED_SELF_TAGS) {
74
- if (directionReference === "self") {
75
- cycleway[key] = cycleway[key] ?? cycleway[`${key}:forward`];
76
- } else {
77
- const directedKey = key + SIDE_TO_DIRECTION[side];
78
- cycleway[key] = cycleway[key] ?? cycleway[directedKey];
79
- }
80
- }
81
- return cycleway;
82
- }
83
- function getTransformedObjects(tags, transformations) {
84
- const center = { ...tags, _side: "self" };
85
- if (tags.highway != null && SIDEPATH_HIGHWAY_CLASSES.has(tags.highway)) {
86
- unnestPrefixedTags(tags, "cycleway", "", center);
87
- for (const mp of META_PREFIXES) unnestPrefixedTags(tags, "cycleway", "", center, mp);
88
- if (center.oneway === "yes" && tags["oneway:bicycle"] !== "no") {
89
- center.traffic_sign = center.traffic_sign ?? center["traffic_sign:forward"];
90
- }
91
- return [center];
92
- }
93
- const results = [center];
94
- for (const transformation of transformations) {
95
- for (const side of SIDES) {
96
- if (tags.highway === transformation.highway) continue;
97
- const prefix = transformation.prefix;
98
- const newObj = {
99
- _prefix: prefix,
100
- _side: side,
101
- _parent_highway: tags.highway,
102
- highway: transformation.highway
103
- };
104
- newObj._parent = tags;
105
- unnestPrefixedTags(tags, prefix, "", newObj);
106
- unnestPrefixedTags(tags, prefix, ":both", newObj);
107
- unnestPrefixedTags(tags, prefix, `:${side}`, newObj);
108
- for (const mp of META_PREFIXES) {
109
- unnestPrefixedTags(tags, prefix, "", newObj, mp);
110
- unnestPrefixedTags(tags, prefix, ":both", newObj, mp);
111
- unnestPrefixedTags(tags, prefix, `:${side}`, newObj, mp);
112
- }
113
- if (newObj._infix !== void 0 && transformation.filter(newObj)) {
114
- convertDirectedTags(newObj, transformation.direction_reference);
115
- results.push(newObj);
116
- }
117
- }
118
- }
119
- return results;
120
- }
121
- var BIKELANE_TRANSFORMATIONS = [
122
- { highway: "cycleway", prefix: "cycleway", direction_reference: "self", filter: () => true },
123
- {
124
- highway: "footway",
125
- prefix: "sidewalk",
126
- direction_reference: "parent",
127
- filter: (t) => !(t.footway === "no" || t.footway === "separate")
128
- }
129
- ];
130
-
131
- // src/helpers/strings.ts
132
- function containsSubstring(str, subStr) {
133
- if (str == null || subStr == null) return false;
134
- return str.includes(subStr);
135
- }
136
- function hasPrefix(str, prefix) {
137
- if (str == null) return false;
138
- return str.startsWith(prefix);
139
- }
140
- function hasSuffix(str, suffix) {
141
- if (str == null) return false;
142
- if (suffix === "") return true;
143
- return str.endsWith(suffix);
144
- }
145
- function hasTagWithPrefix(tags, prefix) {
146
- if (tags == null || prefix == null) return false;
147
- for (const key of Object.keys(tags)) {
148
- if (key.startsWith(prefix)) return true;
149
- }
150
- return false;
151
- }
152
-
153
- // src/transform/prepare-tags.ts
154
- function toSemicolonList(parts) {
155
- return parts.filter((p) => p != null && p !== "").join("; ");
156
- }
157
- function restrictedAccessTags(tags) {
158
- const restricted = [];
159
- if (tags.access === "no") restricted.push("access");
160
- if (tags.highway === "cycleway" && tags.bicycle === "no") restricted.push("bicycle");
161
- if (tags.highway === "footway" && tags.foot === "no") restricted.push("foot");
162
- return restricted;
163
- }
164
- function transformLifecycleTags(tags) {
165
- if (!tags.highway) return;
166
- if (tags.construction != null && ALLOWED_HIGHWAYS.has(tags.construction)) {
167
- tags.highway = tags.construction;
168
- tags.lifecycle = "construction";
169
- tags.construction = void 0;
170
- }
171
- const constructionRestricted = restrictedAccessTags(tags);
172
- if (constructionRestricted.length > 0) {
173
- const text = `${tags["access:reason"] ?? ""} ${tags.description ?? ""} ${tags.note ?? ""}`.toLowerCase();
174
- if (containsSubstring(text, "construction") || containsSubstring(text, "baustelle")) {
175
- tags.lifecycle = "construction_no_access";
176
- tags.description = toSemicolonList([tags.description, "TILDA-Hinweis: Weg gesperrt aufgrund einer Baustelle."]);
177
- for (const t of constructionRestricted) tags[t] = void 0;
178
- }
179
- }
180
- const blockedTerms = ["sperrung", "gesperrt", "blockiert", "blocked", "closure", "closed", "blocked off"];
181
- const blockedRestricted = restrictedAccessTags(tags);
182
- if (blockedRestricted.length > 0) {
183
- const text = `${tags.description ?? ""} ${tags.note ?? ""}`.toLowerCase();
184
- if (blockedTerms.some((term) => containsSubstring(text, term))) {
185
- tags.lifecycle = "blocked";
186
- tags.description = toSemicolonList([tags.description, "TILDA-Hinweis: Weg gesperrt (Sperrung)."]);
187
- for (const t of blockedRestricted) tags[t] = void 0;
188
- }
189
- }
190
- }
191
- function transformCyclewayOppositeSchema(tags) {
192
- if (tags.oneway !== "yes") return;
193
- if (tags.cycleway === "opposite") {
194
- tags.cycleway = "no";
195
- tags["oneway:bicycle"] = "no";
196
- return;
197
- }
198
- if (tags.cycleway === "opposite_lane") {
199
- tags.cycleway = void 0;
200
- tags["cycleway:right"] = "no";
201
- tags["cycleway:left"] = "lane";
202
- tags["oneway:bicycle"] = "no";
203
- return;
204
- }
205
- if (tags.cycleway === "opposite_track") {
206
- tags.cycleway = void 0;
207
- tags["cycleway:right"] = "no";
208
- tags["cycleway:left"] = "track";
209
- tags["oneway:bicycle"] = "no";
210
- }
211
- }
212
- function transformConstructionPrefix(tags) {
213
- const constructionKeys = [];
214
- for (const key of Object.keys(tags)) {
215
- const value = tags[key];
216
- if (value !== void 0 && key.startsWith("construction:")) constructionKeys.push([key, value]);
217
- }
218
- for (const [key, value] of constructionKeys) {
219
- const baseTag = key.slice("construction:".length);
220
- tags[baseTag] = value;
221
- tags[key] = void 0;
222
- if (baseTag.startsWith("cycleway:") || baseTag.startsWith("sidewalk:")) {
223
- tags[`${baseTag}:lifecycle`] = "construction";
224
- } else {
225
- tags.lifecycle = "construction";
226
- }
227
- }
228
- }
229
- function transformCyclewayBothPostfix(tags) {
230
- if (tags.cycleway === "no" && tags["cycleway:both"] == null && tags["cycleway:left"] == null && tags["cycleway:right"] == null) {
231
- tags["cycleway:both"] = "no";
232
- tags.cycleway = void 0;
233
- }
234
- }
235
- function prepareTags(tags) {
236
- transformLifecycleTags(tags);
237
- transformCyclewayOppositeSchema(tags);
238
- transformConstructionPrefix(tags);
239
- transformCyclewayBothPostfix(tags);
240
- }
241
-
242
- // src/helpers/sanitize-for-logging.ts
243
- function sanitizeForLogging(value, allowed, ignored = []) {
244
- if (value == null) return void 0;
245
- if (allowed.includes(value)) return value;
246
- if (ignored.includes(value)) return void 0;
247
- return DISALLOWED;
248
- }
249
- function removeDisallowedValue(value) {
250
- return value === DISALLOWED ? void 0 : value;
251
- }
252
-
253
- // src/helpers/parse-length.ts
254
- function splitUnit(str) {
255
- if (str == null) return null;
256
- const m = str.match(/^(-?[0-9.]+) ?([A-Za-z]*)$/);
257
- if (!m) return null;
258
- const val = Number(m[1]);
259
- if (Number.isNaN(val)) return null;
260
- const unit = m[2] === "" ? "m" : m[2];
261
- return [val, unit];
262
- }
263
- function parseLength(length) {
264
- if (length == null) return void 0;
265
- const parsed = splitUnit(String(length));
266
- if (!parsed) return void 0;
267
- const [val, unit] = parsed;
268
- if (unit === "cm") return val / 100;
269
- if (unit === "m") return val;
270
- if (unit === "km") return val * 1e3;
271
- return void 0;
272
- }
273
-
274
- // src/sanitize/sanitize-road-tags.ts
275
- var SEPARATION_ALLOWED = [
276
- "no",
277
- "bollard",
278
- "flex_post",
279
- "vertical_panel",
280
- "studs",
281
- "bump",
282
- "planter",
283
- "kerb",
284
- "fence",
285
- "jersey_barrier",
286
- "guard_rail",
287
- "structure",
288
- "ditch",
289
- "greenery",
290
- "hedge",
291
- "tree_row",
292
- "cone",
293
- "kerb;parking_lane",
294
- "kerb;bollard",
295
- "yes"
296
- ];
297
- var MARKING_ALLOWED = [
298
- "solid_line",
299
- "dashed_line",
300
- "double_solid_line",
301
- "barred_area",
302
- "pictogram",
303
- "surface"
304
- ];
305
- var TRAFFIC_MODE_ALLOWED = ["no", "motor_vehicle", "parking", "psv", "bicycle", "foot"];
306
- var SURFACE_COLOR_ALLOWED = ["red", "green", "red;green", "no"];
307
- function sided(tags, base, side) {
308
- let value = tags[`${base}:${side}`] ?? tags[`${base}:both`];
309
- if (side === "left") value = value ?? tags[base];
310
- return value;
311
- }
312
- function surfaceColor(tags) {
313
- const raw = tags["surface:colour"] ?? tags["surface:color"];
314
- if (raw == null) return void 0;
315
- const transformations = {
316
- none: "no",
317
- grey: "no",
318
- gray: "no",
319
- "#888888": "no",
320
- silver: "no",
321
- dimgray: "no",
322
- "#b5565a": "red",
323
- orange: "red",
324
- "green;red": "red;green"
325
- };
326
- const value = transformations[raw] ?? raw;
327
- return sanitizeForLogging(value, SURFACE_COLOR_ALLOWED);
328
- }
329
- function separation(tags, side) {
330
- const raw = sided(tags, "separation", side);
331
- if (raw == null) return void 0;
332
- const transformations = {
333
- separation_kerb: "bump",
334
- lane_separator: "bump",
335
- surface: "no",
336
- "tree_row;kerb": "tree_row",
337
- "kerb;tree_row": "tree_row",
338
- "tree_row;kerb;parking_lane": "tree_row",
339
- "grass_verge;tree_row": "tree_row",
340
- "kerb;greenery": "kerb",
341
- "parking_lane;kerb": "parking_lane",
342
- "solid_line;parking_lane": "parking_lane"
343
- };
344
- const value = transformations[raw] ?? raw;
345
- return sanitizeForLogging(value, SEPARATION_ALLOWED);
346
- }
347
- function marking(tags, side) {
348
- const raw = sided(tags, "marking", side);
349
- if (raw == null) return void 0;
350
- return sanitizeForLogging(raw, MARKING_ALLOWED);
351
- }
352
- function trafficMode(tags, side) {
353
- const raw = sided(tags, "traffic_mode", side);
354
- if (raw == null) return void 0;
355
- const transformations = {
356
- "foot;bicycle": "foot",
357
- motorized: "motor_vehicle",
358
- none: "no"
359
- };
360
- const value = transformations[raw] ?? raw;
361
- return sanitizeForLogging(value, TRAFFIC_MODE_ALLOWED);
362
- }
363
- function buffer(tags, side) {
364
- const raw = sided(tags, "buffer", side);
365
- if (raw == null) return void 0;
366
- if (raw === "no" || raw === "none") return 0;
367
- return parseLength(raw);
368
- }
369
- var SIDED_SANITIZERS = {
370
- separation,
371
- marking,
372
- traffic_mode: trafficMode,
373
- buffer
374
- };
375
-
376
- // src/categories/decision-view.ts
377
- var IS_DECISION_VIEW = /* @__PURE__ */ Symbol("isDecisionView");
378
- function resolveSided(source, key) {
379
- let base;
380
- let side;
381
- if (key.endsWith("_left")) {
382
- base = key.slice(0, -"_left".length);
383
- side = "left";
384
- } else if (key.endsWith("_right")) {
385
- base = key.slice(0, -"_right".length);
386
- side = "right";
387
- }
388
- if (base === void 0 || side === void 0) return { handled: false };
389
- const sanitizer = SIDED_SANITIZERS[base];
390
- if (!sanitizer) return { handled: false };
391
- const value = sanitizer(source, side);
392
- if (value === DISALLOWED) return { handled: true, value: void 0 };
393
- return { handled: true, value };
394
- }
395
- function decisionTagsView(source) {
396
- if (source[IS_DECISION_VIEW]) return source;
397
- return new Proxy(source, {
398
- get(target, key) {
399
- if (key === IS_DECISION_VIEW) return true;
400
- if (typeof key !== "string") return target[key];
401
- const sided2 = resolveSided(target, key);
402
- if (sided2.handled) return sided2.value;
403
- const value = target[key];
404
- return value === DISALLOWED ? void 0 : value;
405
- },
406
- set(target, key, value) {
407
- if (typeof key === "string") target[key] = value;
408
- else target[key] = value;
409
- return true;
410
- }
411
- });
412
- }
413
-
414
- // src/categories/tag-predicate.ts
415
- var pred = {
416
- eq: (key, value) => ({ op: "eq", key, value }),
417
- neq: (key, value) => ({ op: "neq", key, value }),
418
- in: (key, values) => ({ op: "in", key, values }),
419
- notIn: (key, values) => ({ op: "notIn", key, values }),
420
- exists: (key) => ({ op: "exists", key }),
421
- notExists: (key) => ({ op: "notExists", key }),
422
- includes: (key, substring) => ({ op: "includes", key, substring }),
423
- hasPrefix: (key, prefix) => ({ op: "hasPrefix", key, prefix }),
424
- hasSuffix: (key, suffix) => ({ op: "hasSuffix", key, suffix }),
425
- hasTagWithPrefix: (prefix) => ({ op: "hasTagWithPrefix", prefix }),
426
- and: (...predicates) => ({ op: "and", predicates }),
427
- or: (...predicates) => ({ op: "or", predicates }),
428
- not: (predicate) => ({ op: "not", predicate }),
429
- macro: (name) => ({ op: "macro", name }),
430
- literal: (value) => ({ op: "literal", value })
431
- };
432
- function tagValue(tags, key) {
433
- return tags[key];
434
- }
435
- function evalPredicate(tags, predicate, macros) {
436
- switch (predicate.op) {
437
- case "eq":
438
- return tagValue(tags, predicate.key) === predicate.value || void 0;
439
- case "neq":
440
- return tagValue(tags, predicate.key) !== predicate.value || void 0;
441
- case "in": {
442
- const v = tagValue(tags, predicate.key);
443
- return v != null && predicate.values.includes(v) || void 0;
444
- }
445
- case "notIn": {
446
- const v = tagValue(tags, predicate.key);
447
- return v != null && !predicate.values.includes(v) || void 0;
448
- }
449
- case "exists":
450
- return tagValue(tags, predicate.key) != null || void 0;
451
- case "notExists":
452
- return tagValue(tags, predicate.key) == null || void 0;
453
- case "includes":
454
- return containsSubstring(tagValue(tags, predicate.key), predicate.substring) || void 0;
455
- case "hasPrefix":
456
- return hasPrefix(tagValue(tags, predicate.key), predicate.prefix) || void 0;
457
- case "hasSuffix":
458
- return hasSuffix(tagValue(tags, predicate.key), predicate.suffix) || void 0;
459
- case "hasTagWithPrefix":
460
- return hasTagWithPrefix(tags, predicate.prefix) || void 0;
461
- case "and": {
462
- let hasUndefined = false;
463
- for (const child of predicate.predicates) {
464
- const r = evalPredicate(tags, child, macros);
465
- if (r === false) return false;
466
- if (r !== true) hasUndefined = true;
467
- }
468
- return hasUndefined ? void 0 : true;
469
- }
470
- case "or": {
471
- let hasUndefined = false;
472
- for (const child of predicate.predicates) {
473
- const r = evalPredicate(tags, child, macros);
474
- if (r === true) return true;
475
- if (r !== false) hasUndefined = true;
476
- }
477
- return hasUndefined ? void 0 : false;
478
- }
479
- case "not": {
480
- const r = evalPredicate(tags, predicate.predicate, macros);
481
- if (r === true) return false;
482
- if (r === false) return true;
483
- return void 0;
484
- }
485
- case "macro": {
486
- const fn = macros[predicate.name];
487
- if (!fn) throw new Error(`Unknown predicate macro: ${predicate.name}`);
488
- return fn(tags);
489
- }
490
- case "literal":
491
- return predicate.value;
492
- default: {
493
- const _exhaustive = predicate;
494
- throw new Error(`Unknown predicate op: ${_exhaustive.op}`);
495
- }
496
- }
497
- }
498
- function evalPredicateStrict(tags, predicate, macros) {
499
- const r = evalPredicate(tags, predicate, macros);
500
- return r === true;
501
- }
502
-
503
- // src/helpers/extract-value-from-lanes.ts
504
- function parseLanesValue(lanesValue) {
505
- return lanesValue.split("|");
506
- }
507
- function findLaneIndex(tags) {
508
- const cyclewayLanes = tags["cycleway:lanes"];
509
- if (cyclewayLanes != null) {
510
- const i = parseLanesValue(cyclewayLanes).indexOf("lane");
511
- if (i !== -1) return i;
512
- }
513
- const bicycleLanes = tags["bicycle:lanes"];
514
- if (bicycleLanes != null) {
515
- const i = parseLanesValue(bicycleLanes).indexOf("designated");
516
- if (i !== -1) return i;
517
- }
518
- return null;
519
- }
520
- function extractValueFromLanes(lanesTag, tags) {
521
- const laneIndex = findLaneIndex(tags);
522
- if (laneIndex == null) return void 0;
523
- const raw = tags[lanesTag];
524
- if (raw != null) {
525
- const values = parseLanesValue(raw);
526
- if (values[laneIndex] != null && values[laneIndex] !== "") return values[laneIndex];
527
- }
528
- return void 0;
529
- }
530
- function extractLastValueFromLanes(lanesValue) {
531
- if (lanesValue == null) return void 0;
532
- const lanes = parseLanesValue(lanesValue);
533
- if (lanes.length > 0) return lanes[lanes.length - 1];
534
- return void 0;
535
- }
536
-
537
1
  // src/helpers/sanitize-string.ts
538
2
  function sanitizeString(value) {
539
3
  if (value == null) return void 0;
540
4
  let out = value.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
541
- out = out.replace(/<\s*\/?\s*[A-Za-z][^>]*?>/g, (tag) => tag.replace(/</g, "(").replace(/>/g, ")"));
5
+ out = out.replace(
6
+ /<\s*\/?\s*[A-Za-z][^>]*?>/g,
7
+ (tag) => tag.replace(/</g, "(").replace(/>/g, ")")
8
+ );
542
9
  return out;
543
10
  }
544
11
 
@@ -577,7 +44,11 @@ function sanitizeTrafficSign(trafficSign) {
577
44
  // src/derive/derive-traffic-signs.ts
578
45
  function deriveTrafficSigns(tags) {
579
46
  if (tags == null) {
580
- return { traffic_sign: void 0, "traffic_sign:forward": void 0, "traffic_sign:backward": void 0 };
47
+ return {
48
+ traffic_sign: void 0,
49
+ "traffic_sign:forward": void 0,
50
+ "traffic_sign:backward": void 0
51
+ };
581
52
  }
582
53
  return {
583
54
  traffic_sign: sanitizeTrafficSign(tags.traffic_sign ?? tags["traffic_sign:both"]),
@@ -586,51 +57,229 @@ function deriveTrafficSigns(tags) {
586
57
  };
587
58
  }
588
59
 
589
- // src/categories/refine-predicates.ts
590
- var CATEGORY_IS_SIDEPATH_PRED = pred.or(
591
- pred.eq("is_sidepath", "yes"),
592
- pred.exists("_parent_highway"),
593
- pred.eq("footway", "sidewalk"),
594
- pred.eq("path", "sidewalk"),
595
- pred.eq("path", "sidepath"),
596
- pred.eq("cycleway", "sidepath"),
597
- pred.eq("steps", "sidewalk")
598
- );
599
- var SIDEPATH_ADJOINING_PRED = pred.and(
600
- CATEGORY_IS_SIDEPATH_PRED,
601
- pred.neq("is_sidepath", "no")
602
- );
603
- var SIDEPATH_ISOLATED_PRED = pred.or(
604
- pred.eq("is_sidepath", "no"),
605
- pred.eq("highway", "service"),
606
- pred.eq("highway", "track")
607
- );
608
- var SIDEPATH_UNKNOWN_PRED = pred.and(
609
- pred.neq("is_sidepath", "yes"),
610
- pred.notExists("_parent_highway"),
611
- pred.neq("footway", "sidewalk"),
612
- pred.neq("path", "sidewalk"),
613
- pred.neq("path", "sidepath"),
614
- pred.neq("cycleway", "sidepath"),
615
- pred.neq("steps", "sidewalk"),
616
- pred.neq("is_sidepath", "no"),
617
- pred.notIn("highway", ["service", "track"])
618
- );
619
- function advisoryOrExclusiveRefining(laneKey = "lane") {
620
- return [
621
- { idSuffix: "_advisory", match: pred.eq(laneKey, "advisory"), implicitOneWayConfidence: "high" },
622
- { idSuffix: "_exclusive", match: pred.eq(laneKey, "exclusive"), implicitOneWayConfidence: "high" },
623
- {
624
- idSuffix: "_advisoryOrExclusive",
625
- match: pred.or(pred.notExists(laneKey), pred.notIn(laneKey, ["advisory", "exclusive"]))
626
- }
627
- ];
60
+ // src/helpers/extract-value-from-lanes.ts
61
+ function parseLanesValue(lanesValue) {
62
+ return lanesValue.split("|");
628
63
  }
629
- var ADJOINING_OR_ISOLATED_REFINING = [
630
- { idSuffix: "_adjoining", match: SIDEPATH_ADJOINING_PRED },
631
- { idSuffix: "_isolated", match: SIDEPATH_ISOLATED_PRED },
632
- { idSuffix: "_adjoiningOrIsolated", match: SIDEPATH_UNKNOWN_PRED }
64
+ function findLaneIndex(tags) {
65
+ const cyclewayLanes = tags["cycleway:lanes"];
66
+ if (cyclewayLanes != null) {
67
+ const i = parseLanesValue(cyclewayLanes).indexOf("lane");
68
+ if (i !== -1) return i;
69
+ }
70
+ const bicycleLanes = tags["bicycle:lanes"];
71
+ if (bicycleLanes != null) {
72
+ const i = parseLanesValue(bicycleLanes).indexOf("designated");
73
+ if (i !== -1) return i;
74
+ }
75
+ return null;
76
+ }
77
+ function extractValueFromLanes(lanesTag, tags) {
78
+ const laneIndex = findLaneIndex(tags);
79
+ if (laneIndex == null) return void 0;
80
+ const raw = tags[lanesTag];
81
+ if (raw != null) {
82
+ const values = parseLanesValue(raw);
83
+ if (values[laneIndex] != null && values[laneIndex] !== "") return values[laneIndex];
84
+ }
85
+ return void 0;
86
+ }
87
+ function extractLastValueFromLanes(lanesValue) {
88
+ if (lanesValue == null) return void 0;
89
+ const lanes = parseLanesValue(lanesValue);
90
+ if (lanes.length > 0) return lanes[lanes.length - 1];
91
+ return void 0;
92
+ }
93
+
94
+ // src/helpers/strings.ts
95
+ function containsSubstring(str, subStr) {
96
+ if (str == null || subStr == null) return false;
97
+ return str.includes(subStr);
98
+ }
99
+ function hasPrefix(str, prefix) {
100
+ if (str == null) return false;
101
+ return str.startsWith(prefix);
102
+ }
103
+ function hasSuffix(str, suffix) {
104
+ if (str == null) return false;
105
+ if (suffix === "") return true;
106
+ return str.endsWith(suffix);
107
+ }
108
+ function hasTagWithPrefix(tags, prefix) {
109
+ if (tags == null || prefix == null) return false;
110
+ for (const key of Object.keys(tags)) {
111
+ if (key.startsWith(prefix)) return true;
112
+ }
113
+ return false;
114
+ }
115
+
116
+ // src/helpers/parse-length.ts
117
+ var DECIMAL_COMMA_VALUES = {
118
+ "0,3": "0.3",
119
+ "0,5": "0.5",
120
+ "0,6": "0.6",
121
+ "1,5": "1.5",
122
+ "2,2": "2.2",
123
+ "2,5": "2.5",
124
+ "2,50": "2.50"
125
+ };
126
+ function splitUnit(str) {
127
+ const m = str.match(/^(-?[0-9.]+) ?([A-Za-z]*)$/);
128
+ if (!m) return null;
129
+ const val = Number(m[1]);
130
+ if (Number.isNaN(val)) return null;
131
+ return [val === 0 ? 0 : val, m[2] || "m"];
132
+ }
133
+ function parseLength(length) {
134
+ if (length == null) return void 0;
135
+ const key = String(length);
136
+ const parsed = splitUnit(DECIMAL_COMMA_VALUES[key] ?? key);
137
+ if (!parsed) return void 0;
138
+ const [val, unit] = parsed;
139
+ if (val < 0) return void 0;
140
+ if (unit === "cm") return val / 100;
141
+ if (unit === "m") return val;
142
+ if (unit === "km") return val * 1e3;
143
+ return void 0;
144
+ }
145
+ function parseWidth(width) {
146
+ const value = parseLength(width);
147
+ return value !== void 0 && value > 0 ? value : void 0;
148
+ }
149
+
150
+ // src/types.ts
151
+ var DISALLOWED = "DISALLOWED_VALUE";
152
+
153
+ // src/helpers/sanitize-for-logging.ts
154
+ function sanitizeForLogging(value, allowed, ignored = []) {
155
+ if (value == null) return void 0;
156
+ if (allowed.includes(value)) return value;
157
+ if (ignored.includes(value)) return void 0;
158
+ return DISALLOWED;
159
+ }
160
+ function removeDisallowedValue(value) {
161
+ return value === DISALLOWED ? void 0 : value;
162
+ }
163
+
164
+ // src/sanitize/sanitize-road-tags.ts
165
+ var PROTECTIVE_SEPARATION = [
166
+ "bollard",
167
+ "flex_post",
168
+ "vertical_panel",
169
+ "bump",
170
+ "fence",
171
+ "guard_rail",
172
+ "planter",
173
+ "studs",
174
+ "jersey_barrier"
175
+ ];
176
+ var SEPARATION_ALLOWED = [
177
+ "no",
178
+ "bollard",
179
+ "flex_post",
180
+ "vertical_panel",
181
+ "studs",
182
+ "bump",
183
+ "planter",
184
+ "kerb",
185
+ "fence",
186
+ "jersey_barrier",
187
+ "guard_rail",
188
+ "structure",
189
+ "ditch",
190
+ "greenery",
191
+ "hedge",
192
+ "tree_row",
193
+ "cone",
194
+ "kerb;parking_lane",
195
+ "kerb;bollard",
196
+ "yes"
197
+ ];
198
+ var MARKING_ALLOWED = [
199
+ "solid_line",
200
+ "dashed_line",
201
+ "double_solid_line",
202
+ "barred_area",
203
+ "pictogram",
204
+ "surface"
205
+ ];
206
+ var TRAFFIC_MODE_ALLOWED = [
207
+ "no",
208
+ "motor_vehicle",
209
+ "parking",
210
+ "psv",
211
+ "bicycle",
212
+ "foot"
633
213
  ];
214
+ var SURFACE_COLOR_ALLOWED = ["red", "green", "red;green", "no"];
215
+ function sided(tags, base, side) {
216
+ let value = tags[`${base}:${side}`] ?? tags[`${base}:both`];
217
+ if (side === "left") value = value ?? tags[base];
218
+ return value;
219
+ }
220
+ function surfaceColor(tags) {
221
+ const raw = tags["surface:colour"] ?? tags["surface:color"];
222
+ if (raw == null) return void 0;
223
+ const transformations = {
224
+ none: "no",
225
+ grey: "no",
226
+ gray: "no",
227
+ "#888888": "no",
228
+ silver: "no",
229
+ dimgray: "no",
230
+ "#b5565a": "red",
231
+ orange: "red",
232
+ "green;red": "red;green"
233
+ };
234
+ const value = transformations[raw] ?? raw;
235
+ return sanitizeForLogging(value, SURFACE_COLOR_ALLOWED);
236
+ }
237
+ function separation(tags, side) {
238
+ const raw = sided(tags, "separation", side);
239
+ if (raw == null) return void 0;
240
+ const transformations = {
241
+ separation_kerb: "bump",
242
+ lane_separator: "bump",
243
+ surface: "no",
244
+ "tree_row;kerb": "tree_row",
245
+ "kerb;tree_row": "tree_row",
246
+ "tree_row;kerb;parking_lane": "tree_row",
247
+ "grass_verge;tree_row": "tree_row",
248
+ "kerb;greenery": "kerb",
249
+ "parking_lane;kerb": "parking_lane",
250
+ "solid_line;parking_lane": "parking_lane"
251
+ };
252
+ const value = transformations[raw] ?? raw;
253
+ return sanitizeForLogging(value, SEPARATION_ALLOWED);
254
+ }
255
+ function marking(tags, side) {
256
+ const raw = sided(tags, "marking", side);
257
+ if (raw == null) return void 0;
258
+ return sanitizeForLogging(raw, MARKING_ALLOWED);
259
+ }
260
+ function trafficMode(tags, side) {
261
+ const raw = sided(tags, "traffic_mode", side);
262
+ if (raw == null) return void 0;
263
+ const transformations = {
264
+ "foot;bicycle": "foot",
265
+ motorized: "motor_vehicle",
266
+ none: "no"
267
+ };
268
+ const value = transformations[raw] ?? raw;
269
+ return sanitizeForLogging(value, TRAFFIC_MODE_ALLOWED);
270
+ }
271
+ function buffer(tags, side) {
272
+ const raw = sided(tags, "buffer", side);
273
+ if (raw == null) return void 0;
274
+ if (raw === "no" || raw === "none") return 0;
275
+ return parseLength(raw);
276
+ }
277
+ var SIDED_SANITIZERS = {
278
+ separation,
279
+ marking,
280
+ traffic_mode: trafficMode,
281
+ buffer
282
+ };
634
283
 
635
284
  // src/categories/category-is-sidepath.ts
636
285
  function categoryIsSidepath(tags) {
@@ -644,15 +293,20 @@ function hasBetweenLanesConditions(tags) {
644
293
  if (containsSubstring(tags["cycleway:lanes"], "|lane|")) return true;
645
294
  if (containsSubstring(tags["bicycle:lanes"], "|designated|")) return true;
646
295
  if (containsSubstring(tags.lanes, "|lane|")) return true;
647
- if (tags._parent && containsSubstring(tags._parent["bicycle:lanes"], "|designated|")) return true;
296
+ if (tags._parent && containsSubstring(tags._parent["bicycle:lanes"], "|designated|"))
297
+ return true;
648
298
  }
649
299
  return false;
650
300
  }
651
301
  function isCrossingPattern(tags) {
652
- if (tags.highway === "cycleway" && tags.cycleway === "lane" && tags.lane === "crossing") return true;
653
- if (tags.highway === "cycleway" && (tags.cycleway === "crossing" || tags.cycleway === "traffic_island")) return true;
654
- if (tags.highway === "path" && (tags.path === "crossing" || tags.path === "traffic_island") && (tags.bicycle === "yes" || tags.bicycle === "designated")) return true;
655
- if (tags.highway === "footway" && (tags.footway === "crossing" || tags.footway === "traffic_island") && (tags.bicycle === "yes" || tags.bicycle === "designated")) return true;
302
+ if (tags.highway === "cycleway" && tags.cycleway === "lane" && tags.lane === "crossing")
303
+ return true;
304
+ if (tags.highway === "cycleway" && (tags.cycleway === "crossing" || tags.cycleway === "traffic_island"))
305
+ return true;
306
+ if (tags.highway === "path" && (tags.path === "crossing" || tags.path === "traffic_island") && (tags.bicycle === "yes" || tags.bicycle === "designated"))
307
+ return true;
308
+ if (tags.highway === "footway" && (tags.footway === "crossing" || tags.footway === "traffic_island") && (tags.bicycle === "yes" || tags.bicycle === "designated"))
309
+ return true;
656
310
  return false;
657
311
  }
658
312
  function bicycleRoadBase(tags) {
@@ -665,8 +319,16 @@ function bicycleRoadVehicleDestination(tags) {
665
319
  if (!bicycleRoadBase(tags)) return void 0;
666
320
  const trafficSign = sanitizeTrafficSign(tags.traffic_sign);
667
321
  if (containsSubstring(trafficSign, "1020-30")) return true;
668
- if (containsSubstring(trafficSign, "Kraftfahrzeuge-frei") || containsSubstring(trafficSign, "Kfz-Verkehr frei") || containsSubstring(trafficSign, "KFZ frei")) return true;
669
- if (tags.vehicle === "destination" || tags.motor_vehicle === "destination" || tags.vehicle === "yes" || tags.motor_vehicle === "yes") return true;
322
+ if (containsSubstring(trafficSign, "Kraftfahrzeuge-frei") || containsSubstring(trafficSign, "Kfz-Verkehr frei") || containsSubstring(trafficSign, "KFZ frei"))
323
+ return true;
324
+ if (tags.vehicle === "destination" || tags.motor_vehicle === "destination" || tags.vehicle === "yes" || tags.motor_vehicle === "yes")
325
+ return true;
326
+ return void 0;
327
+ }
328
+ function unsignedCycleway(tags) {
329
+ if (tags.highway === "cycleway" && sanitizeTrafficSign(tags.traffic_sign) === "none" && // the side object of a lane between the car lanes (tilda-geo 34fb8457d)
330
+ !hasBetweenLanesConditions(tags))
331
+ return true;
670
332
  return void 0;
671
333
  }
672
334
  function footwayBicycleYes(tags) {
@@ -689,15 +351,16 @@ function crossing(tags) {
689
351
  }
690
352
  function implicitOneWay(tags) {
691
353
  let result = tags._prefix === "cycleway" && tags._infix === "";
692
- result = result && tags._parent?.oneway === "yes" && tags._parent?.["oneway:bicycle"] !== "no";
693
- result = result && tags._side === "left";
354
+ result = result && tags._parent?.["oneway:bicycle"] !== "no";
355
+ result = result && (tags._parent?.oneway === "yes" && tags._side === "left" || tags._parent?.oneway === "-1" && tags._side === "right");
694
356
  return result || void 0;
695
357
  }
696
358
  function cyclewayOnHighwayAdvisoryOrExclusiveBase(tags) {
697
359
  if (tags.highway === "cycleway") {
698
360
  if (hasBetweenLanesConditions(tags)) {
699
361
  if (containsSubstring(tags.lanes, "|lane|") && !hasSuffix(tags.lanes, "|lane")) return false;
700
- if (tags._parent != null && containsSubstring(tags._parent["bicycle:lanes"], "|designated|") && !hasSuffix(tags._parent["bicycle:lanes"], "|designated")) return false;
362
+ if (tags._parent != null && containsSubstring(tags._parent["bicycle:lanes"], "|designated|") && !hasSuffix(tags._parent["bicycle:lanes"], "|designated"))
363
+ return false;
701
364
  const sourceWidth = tags._parent ? extractLastValueFromLanes(tags._parent["width:lanes"]) : void 0;
702
365
  tags.width = tags.width ?? sourceWidth;
703
366
  }
@@ -717,17 +380,7 @@ function cyclewayOnHighwayProtected(tags) {
717
380
  if (!categoryIsSidepath(tags)) return false;
718
381
  if (tags.lane === "advisory") return false;
719
382
  if (tags.cycleway === "share_busway" || tags.cycleway === "opposite_share_busway") return false;
720
- const allowedSeparation = /* @__PURE__ */ new Set([
721
- "bollard",
722
- "flex_post",
723
- "vertical_panel",
724
- "studs",
725
- "bump",
726
- "planter",
727
- "fence",
728
- "jersey_barrier",
729
- "guard_rail"
730
- ]);
383
+ const allowedSeparation = new Set(PROTECTIVE_SEPARATION);
731
384
  const trafficModeRight = tags.traffic_mode_right;
732
385
  const separationLeft = tags.separation_left;
733
386
  if (separationLeft != null && allowedSeparation.has(separationLeft)) {
@@ -751,7 +404,8 @@ function sharedBusLaneBusWithBike(tags) {
751
404
  if (tags.highway !== "cycleway") return void 0;
752
405
  const trafficSign = sanitizeTrafficSign(tags.traffic_sign);
753
406
  const parentTrafficSign = tags._parent ? sanitizeTrafficSign(tags._parent.traffic_sign) : void 0;
754
- if (tags.cycleway === "share_busway" || tags.cycleway === "opposite_share_busway" || hasPrefix(trafficSign, "DE:245") && (containsSubstring(trafficSign, "1022-10") || containsSubstring(trafficSign, "1022-14")) || hasPrefix(parentTrafficSign, "DE:245") && (containsSubstring(parentTrafficSign, "1022-10") || containsSubstring(parentTrafficSign, "1022-14"))) return true;
407
+ if (tags.cycleway === "share_busway" || tags.cycleway === "opposite_share_busway" || hasPrefix(trafficSign, "DE:245") && (containsSubstring(trafficSign, "1022-10") || containsSubstring(trafficSign, "1022-14")) || hasPrefix(parentTrafficSign, "DE:245") && (containsSubstring(parentTrafficSign, "1022-10") || containsSubstring(parentTrafficSign, "1022-14")))
408
+ return true;
755
409
  return void 0;
756
410
  }
757
411
  function sharedBusLaneBikeWithBus(tags) {
@@ -759,7 +413,8 @@ function sharedBusLaneBikeWithBus(tags) {
759
413
  if (tags.highway !== "cycleway") return void 0;
760
414
  const trafficSign = sanitizeTrafficSign(tags.traffic_sign);
761
415
  const parentTrafficSign = tags._parent ? sanitizeTrafficSign(tags._parent.traffic_sign) : void 0;
762
- if (tags.lane === "share_busway" || hasPrefix(trafficSign, "DE:237") && (containsSubstring(trafficSign, "1024-14") || containsSubstring(trafficSign, "1026-32")) || hasPrefix(parentTrafficSign, "DE:237") && (containsSubstring(parentTrafficSign, "1024-14") || containsSubstring(parentTrafficSign, "1026-32"))) return true;
416
+ if (tags.lane === "share_busway" || hasPrefix(trafficSign, "DE:237") && (containsSubstring(trafficSign, "1024-14") || containsSubstring(trafficSign, "1026-32")) || hasPrefix(parentTrafficSign, "DE:237") && (containsSubstring(parentTrafficSign, "1024-14") || containsSubstring(parentTrafficSign, "1026-32")))
417
+ return true;
763
418
  return void 0;
764
419
  }
765
420
  function needsClarification(tags) {
@@ -768,7 +423,14 @@ function needsClarification(tags) {
768
423
  if (tags.highway === "cycleway") return true;
769
424
  if (tags.highway === "path" && tags.bicycle === "designated") {
770
425
  if (tags.foot === "no") {
771
- const excludedSurfaces = /* @__PURE__ */ new Set(["ground", "dirt", "fine_gravel", "gravel", "pebblestone", "earth"]);
426
+ const excludedSurfaces = /* @__PURE__ */ new Set([
427
+ "ground",
428
+ "dirt",
429
+ "fine_gravel",
430
+ "gravel",
431
+ "pebblestone",
432
+ "earth"
433
+ ]);
772
434
  if (hasTagWithPrefix(tags, "mtb:") || tags.mtb === "yes" || tags.surface != null && excludedSurfaces.has(tags.surface)) {
773
435
  return false;
774
436
  }
@@ -780,15 +442,150 @@ function needsClarification(tags) {
780
442
  return void 0;
781
443
  }
782
444
 
783
- // src/categories/category-specs.ts
784
- function footAndCyclewaySharedProcess(tags) {
785
- if (tags.highway === "service") {
786
- tags.description = [tags.description, "TILDA-Hinweis: Radinfrastruktur auf einem Zufahrtsweg."].filter(Boolean).join("; ");
787
- }
788
- if (tags.highway === "track" || containsSubstring(tags.traffic_sign, "1026-36") || containsSubstring(tags.traffic_sign, "1026-37") || containsSubstring(tags.traffic_sign, "1026-38") || containsSubstring(tags.access, "agricultural") || containsSubstring(tags.motor_vehicle, "agricultural") || containsSubstring(tags.vehicle, "agricultural") || containsSubstring(tags.access, "forestry") || containsSubstring(tags.motor_vehicle, "forestry") || containsSubstring(tags.vehicle, "forestry")) {
789
- tags.description = [tags.description, "TILDA-Hinweis: Radinfrastruktur geteilt mit land- und/oder forstwirtschaftlichem Verkehr."].filter(Boolean).join("; ");
445
+ // src/categories/tag-predicate.ts
446
+ var pred = {
447
+ eq: (key, value) => ({ op: "eq", key, value }),
448
+ neq: (key, value) => ({ op: "neq", key, value }),
449
+ in: (key, values) => ({ op: "in", key, values }),
450
+ notIn: (key, values) => ({ op: "notIn", key, values }),
451
+ exists: (key) => ({ op: "exists", key }),
452
+ notExists: (key) => ({ op: "notExists", key }),
453
+ includes: (key, substring) => ({ op: "includes", key, substring }),
454
+ hasPrefix: (key, prefix) => ({ op: "hasPrefix", key, prefix }),
455
+ hasSuffix: (key, suffix) => ({ op: "hasSuffix", key, suffix }),
456
+ hasTagWithPrefix: (prefix) => ({ op: "hasTagWithPrefix", prefix }),
457
+ and: (...predicates) => ({ op: "and", predicates }),
458
+ or: (...predicates) => ({ op: "or", predicates }),
459
+ not: (predicate) => ({ op: "not", predicate }),
460
+ macro: (name) => ({ op: "macro", name }),
461
+ literal: (value) => ({ op: "literal", value })
462
+ };
463
+ function tagValue(tags, key) {
464
+ return tags[key];
465
+ }
466
+ function evalPredicate(tags, predicate, macros) {
467
+ switch (predicate.op) {
468
+ case "eq":
469
+ return tagValue(tags, predicate.key) === predicate.value || void 0;
470
+ case "neq":
471
+ return tagValue(tags, predicate.key) !== predicate.value || void 0;
472
+ case "in": {
473
+ const v = tagValue(tags, predicate.key);
474
+ return v != null && predicate.values.includes(v) || void 0;
475
+ }
476
+ case "notIn": {
477
+ const v = tagValue(tags, predicate.key);
478
+ return v != null && !predicate.values.includes(v) || void 0;
479
+ }
480
+ case "exists":
481
+ return tagValue(tags, predicate.key) != null || void 0;
482
+ case "notExists":
483
+ return tagValue(tags, predicate.key) == null || void 0;
484
+ case "includes":
485
+ return containsSubstring(tagValue(tags, predicate.key), predicate.substring) || void 0;
486
+ case "hasPrefix":
487
+ return hasPrefix(tagValue(tags, predicate.key), predicate.prefix) || void 0;
488
+ case "hasSuffix":
489
+ return hasSuffix(tagValue(tags, predicate.key), predicate.suffix) || void 0;
490
+ case "hasTagWithPrefix":
491
+ return hasTagWithPrefix(tags, predicate.prefix) || void 0;
492
+ case "and": {
493
+ let hasUndefined = false;
494
+ for (const child of predicate.predicates) {
495
+ const r = evalPredicate(tags, child, macros);
496
+ if (r === false) return false;
497
+ if (r !== true) hasUndefined = true;
498
+ }
499
+ return hasUndefined ? void 0 : true;
500
+ }
501
+ case "or": {
502
+ let hasUndefined = false;
503
+ for (const child of predicate.predicates) {
504
+ const r = evalPredicate(tags, child, macros);
505
+ if (r === true) return true;
506
+ if (r !== false) hasUndefined = true;
507
+ }
508
+ return hasUndefined ? void 0 : false;
509
+ }
510
+ case "not": {
511
+ const r = evalPredicate(tags, predicate.predicate, macros);
512
+ if (r === true) return false;
513
+ if (r === false) return true;
514
+ return void 0;
515
+ }
516
+ case "macro": {
517
+ const fn = macros[predicate.name];
518
+ if (!fn) throw new Error(`Unknown predicate macro: ${predicate.name}`);
519
+ return fn(tags);
520
+ }
521
+ case "literal":
522
+ return predicate.value;
523
+ default: {
524
+ const _exhaustive = predicate;
525
+ throw new Error(`Unknown predicate op: ${_exhaustive.op}`);
526
+ }
790
527
  }
791
528
  }
529
+ function evalPredicateStrict(tags, predicate, macros) {
530
+ const r = evalPredicate(tags, predicate, macros);
531
+ return r === true;
532
+ }
533
+
534
+ // src/categories/refine-predicates.ts
535
+ var CATEGORY_IS_SIDEPATH_PRED = pred.or(
536
+ pred.eq("is_sidepath", "yes"),
537
+ pred.exists("_parent_highway"),
538
+ pred.eq("footway", "sidewalk"),
539
+ pred.eq("path", "sidewalk"),
540
+ pred.eq("path", "sidepath"),
541
+ pred.eq("cycleway", "sidepath"),
542
+ pred.eq("steps", "sidewalk")
543
+ );
544
+ var SIDEPATH_ADJOINING_PRED = pred.and(
545
+ CATEGORY_IS_SIDEPATH_PRED,
546
+ pred.neq("is_sidepath", "no")
547
+ );
548
+ var SIDEPATH_ISOLATED_PRED = pred.or(
549
+ pred.eq("is_sidepath", "no"),
550
+ pred.eq("highway", "service"),
551
+ pred.eq("highway", "track")
552
+ );
553
+ var SIDEPATH_UNKNOWN_PRED = pred.and(
554
+ pred.neq("is_sidepath", "yes"),
555
+ pred.notExists("_parent_highway"),
556
+ pred.neq("footway", "sidewalk"),
557
+ pred.neq("path", "sidewalk"),
558
+ pred.neq("path", "sidepath"),
559
+ pred.neq("cycleway", "sidepath"),
560
+ pred.neq("steps", "sidewalk"),
561
+ pred.neq("is_sidepath", "no"),
562
+ pred.notIn("highway", ["service", "track"])
563
+ );
564
+ function advisoryOrExclusiveRefining(laneKey = "lane") {
565
+ return [
566
+ {
567
+ idSuffix: "_advisory",
568
+ match: pred.eq(laneKey, "advisory"),
569
+ implicitOneWayConfidence: "high"
570
+ },
571
+ {
572
+ idSuffix: "_exclusive",
573
+ match: pred.eq(laneKey, "exclusive"),
574
+ implicitOneWayConfidence: "high"
575
+ },
576
+ {
577
+ idSuffix: "_advisoryOrExclusive",
578
+ match: pred.or(pred.notExists(laneKey), pred.notIn(laneKey, ["advisory", "exclusive"]))
579
+ }
580
+ ];
581
+ }
582
+ var ADJOINING_OR_ISOLATED_REFINING = [
583
+ { idSuffix: "_adjoining", match: SIDEPATH_ADJOINING_PRED },
584
+ { idSuffix: "_isolated", match: SIDEPATH_ISOLATED_PRED },
585
+ { idSuffix: "_adjoiningOrIsolated", match: SIDEPATH_UNKNOWN_PRED }
586
+ ];
587
+
588
+ // src/categories/category-specs.ts
792
589
  function cyclewayOnHighwayBetweenLanesProcess(tags) {
793
590
  const width = extractValueFromLanes("width:lanes", tags);
794
591
  if (width) tags.width = width;
@@ -829,14 +626,54 @@ var LANE_GAP = [
829
626
  }
830
627
  ];
831
628
  var NEEDS_CLARIFICATION_GAP_DISCRIMINATORS = [
832
- { key: "segregated", values: ["yes"], unlocksCategory: "footAndCyclewaySegregated", reason: "Segregated foot/cycle path" },
833
- { key: "traffic_sign", values: ["DE:241"], unlocksCategory: "footAndCyclewaySegregated", reason: "German segregated foot/cycle sign" },
834
- { key: "segregated", values: ["no"], unlocksCategory: "footAndCyclewayShared", reason: "Shared foot/cycle path" },
835
- { key: "traffic_sign", values: ["DE:240"], unlocksCategory: "footAndCyclewayShared", reason: "German shared foot/cycle sign" },
836
- { key: "traffic_sign", values: ["DE:237"], unlocksCategory: "cycleway", reason: "German cycleway sign" },
837
- { key: "cycleway", values: ["track", "opposite_track"], unlocksCategory: "cycleway", reason: "Separated cycle track tagging" },
838
- { key: "cycleway", values: ["lane", "opposite_lane"], unlocksCategory: "cyclewayOnHighway_advisoryOrExclusive", reason: "On-highway cycle lane" },
839
- { key: "bicycle", values: ["yes"], unlocksCategory: "footwayBicycleYes", reason: "Bicycle allowed on footway" }
629
+ {
630
+ key: "segregated",
631
+ values: ["yes"],
632
+ unlocksCategory: "footAndCyclewaySegregated",
633
+ reason: "Segregated foot/cycle path"
634
+ },
635
+ {
636
+ key: "traffic_sign",
637
+ values: ["DE:241"],
638
+ unlocksCategory: "footAndCyclewaySegregated",
639
+ reason: "German segregated foot/cycle sign"
640
+ },
641
+ {
642
+ key: "segregated",
643
+ values: ["no"],
644
+ unlocksCategory: "footAndCyclewayShared",
645
+ reason: "Shared foot/cycle path"
646
+ },
647
+ {
648
+ key: "traffic_sign",
649
+ values: ["DE:240"],
650
+ unlocksCategory: "footAndCyclewayShared",
651
+ reason: "German shared foot/cycle sign"
652
+ },
653
+ {
654
+ key: "traffic_sign",
655
+ values: ["DE:237", "none"],
656
+ unlocksCategory: "cycleway",
657
+ reason: "German cycleway sign; on highway=cycleway also traffic_sign=none (unsigned cycleway, anderer Radweg)"
658
+ },
659
+ {
660
+ key: "cycleway",
661
+ values: ["track", "opposite_track"],
662
+ unlocksCategory: "cycleway",
663
+ reason: "Separated cycle track tagging"
664
+ },
665
+ {
666
+ key: "cycleway",
667
+ values: ["lane", "opposite_lane"],
668
+ unlocksCategory: "cyclewayOnHighway_advisoryOrExclusive",
669
+ reason: "On-highway cycle lane"
670
+ },
671
+ {
672
+ key: "bicycle",
673
+ values: ["yes"],
674
+ unlocksCategory: "footwayBicycleYes",
675
+ reason: "Bicycle allowed on footway"
676
+ }
840
677
  ];
841
678
  var FOOT_AND_CYCLEWAY_HIGHWAYS = ["cycleway", "path", "footway", "service", "track"];
842
679
  var FOOT_AND_CYCLEWAY_SHARED_MATCH = pred.or(
@@ -848,7 +685,11 @@ var FOOT_AND_CYCLEWAY_SHARED_MATCH = pred.or(
848
685
  pred.and(
849
686
  pred.in("highway", [...FOOT_AND_CYCLEWAY_HIGHWAYS]),
850
687
  pred.or(
851
- pred.and(pred.eq("segregated", "no"), pred.eq("bicycle", "designated"), pred.eq("foot", "designated")),
688
+ pred.and(
689
+ pred.eq("segregated", "no"),
690
+ pred.eq("bicycle", "designated"),
691
+ pred.eq("foot", "designated")
692
+ ),
852
693
  pred.and(pred.eq("segregated", "no"), pred.eq("bicycle", "yes"), pred.eq("foot", "yes")),
853
694
  pred.includes("traffic_sign", "240")
854
695
  )
@@ -863,7 +704,11 @@ var FOOT_AND_CYCLEWAY_SEGREGATED_MATCH = pred.or(
863
704
  pred.and(
864
705
  pred.in("highway", ["cycleway", "path", "footway"]),
865
706
  pred.or(
866
- pred.and(pred.eq("segregated", "yes"), pred.eq("bicycle", "designated"), pred.eq("foot", "designated")),
707
+ pred.and(
708
+ pred.eq("segregated", "yes"),
709
+ pred.eq("bicycle", "designated"),
710
+ pred.eq("foot", "designated")
711
+ ),
867
712
  pred.and(pred.eq("segregated", "yes"), pred.eq("bicycle", "yes"), pred.eq("foot", "yes")),
868
713
  pred.and(pred.includes("traffic_sign", "241"), pred.neq("highway", "footway"))
869
714
  )
@@ -879,6 +724,8 @@ var CYCLEWAY_SEPARATED_BASE_MATCH = pred.or(
879
724
  pred.exists("is_sidepath")
880
725
  )
881
726
  ),
727
+ // Unsigned cycleway: `highway=cycleway` + `traffic_sign=none` (tilda-geo 98e649800).
728
+ pred.macro("unsigned_cycleway"),
882
729
  pred.and(
883
730
  pred.in("highway", [
884
731
  "living_street",
@@ -951,6 +798,7 @@ var CATEGORY_SPECS = [
951
798
  implicitOneWay: false,
952
799
  implicitOneWayConfidence: "high",
953
800
  copySurfaceSmoothnessFromParent: true,
801
+ bicycleSurface: "strip",
954
802
  // Requires sanitizeTrafficSign for DE:244 prefix and German text variants.
955
803
  match: pred.macro("bicycle_road_vehicle_destination")
956
804
  },
@@ -960,6 +808,7 @@ var CATEGORY_SPECS = [
960
808
  implicitOneWay: false,
961
809
  implicitOneWayConfidence: "high",
962
810
  copySurfaceSmoothnessFromParent: true,
811
+ bicycleSurface: "strip",
963
812
  // Requires sanitizeTrafficSign for DE:244 prefix.
964
813
  match: pred.macro("bicycle_road_base")
965
814
  },
@@ -989,17 +838,19 @@ var CATEGORY_SPECS = [
989
838
  implicitOneWay: false,
990
839
  implicitOneWayConfidence: "high",
991
840
  copySurfaceSmoothnessFromParent: false,
992
- match: pred.and(
993
- pred.eq("highway", "pedestrian"),
994
- pred.in("bicycle", ["yes", "designated"])
995
- )
841
+ bicycleSurface: "strip",
842
+ match: pred.and(pred.eq("highway", "pedestrian"), pred.in("bicycle", ["yes", "designated"]))
996
843
  },
997
844
  {
998
845
  id: "sharedMotorVehicleLane",
999
846
  infrastructureExists: true,
1000
- implicitOneWay: false,
847
+ // `implicit_yes`: each row is one side of the road (`cycleway=shared_lane` without a side also gives
848
+ // a left and a right row), so it is the motor vehicle lane of that side and runs in one direction
849
+ // (tilda-geo `0927094ca`).
850
+ implicitOneWay: true,
1001
851
  implicitOneWayConfidence: "high",
1002
852
  copySurfaceSmoothnessFromParent: true,
853
+ bicycleSurface: "strip",
1003
854
  match: pred.and(pred.eq("highway", "cycleway"), pred.eq("cycleway", "shared_lane"))
1004
855
  },
1005
856
  {
@@ -1018,9 +869,9 @@ var CATEGORY_SPECS = [
1018
869
  implicitOneWay: true,
1019
870
  implicitOneWayConfidence: "low",
1020
871
  copySurfaceSmoothnessFromParent: false,
872
+ bicycleSurface: "whole_way",
1021
873
  excludes: [pred.macro("is_crossing_pattern")],
1022
874
  match: FOOT_AND_CYCLEWAY_SHARED_MATCH,
1023
- process: footAndCyclewaySharedProcess,
1024
875
  refining: [...ADJOINING_OR_ISOLATED_REFINING],
1025
876
  gapDiscriminators: SIDEpath_GAP
1026
877
  },
@@ -1030,6 +881,7 @@ var CATEGORY_SPECS = [
1030
881
  implicitOneWay: true,
1031
882
  implicitOneWayConfidence: "low",
1032
883
  copySurfaceSmoothnessFromParent: false,
884
+ bicycleSurface: "whole_way",
1033
885
  excludes: [pred.macro("is_crossing_pattern")],
1034
886
  match: FOOT_AND_CYCLEWAY_SEGREGATED_MATCH,
1035
887
  refining: [...ADJOINING_OR_ISOLATED_REFINING],
@@ -1041,6 +893,7 @@ var CATEGORY_SPECS = [
1041
893
  implicitOneWay: false,
1042
894
  implicitOneWayConfidence: "low",
1043
895
  copySurfaceSmoothnessFromParent: false,
896
+ bicycleSurface: "whole_way",
1044
897
  excludes: [pred.macro("is_crossing_pattern"), pred.eq("cycleway", "lane")],
1045
898
  match: CYCLEWAY_SEPARATED_BASE_MATCH,
1046
899
  refining: [...ADJOINING_OR_ISOLATED_REFINING],
@@ -1063,6 +916,7 @@ var CATEGORY_SPECS = [
1063
916
  implicitOneWay: true,
1064
917
  implicitOneWayConfidence: "low",
1065
918
  copySurfaceSmoothnessFromParent: false,
919
+ bicycleSurface: "whole_way",
1066
920
  // mtb:scale numeric parsing and sanitizeTrafficSign for 1022-10.
1067
921
  match: pred.macro("footway_bicycle_yes"),
1068
922
  refining: [...ADJOINING_OR_ISOLATED_REFINING],
@@ -1092,14 +946,16 @@ var CATEGORY_MACROS = {
1092
946
  shared_bus_lane_bus_with_bike: sharedBusLaneBusWithBike,
1093
947
  shared_bus_lane_bike_with_bus: sharedBusLaneBikeWithBus,
1094
948
  needs_clarification: needsClarification,
1095
- footway_bicycle_yes: footwayBicycleYes
949
+ footway_bicycle_yes: footwayBicycleYes,
950
+ unsigned_cycleway: unsignedCycleway
1096
951
  };
1097
952
  function footAndCyclewaySegregatedSeparation(tags) {
1098
- const separationRight = tags.separation_right;
1099
- let separationCondition = true;
1100
- if (separationRight != null) separationCondition = separationRight === "no";
1101
- const trafficModeCondition = tags.traffic_mode_right === "foot";
1102
- if (tags.highway === "cycleway" && trafficModeCondition && separationCondition) return true;
953
+ if (tags.highway !== "cycleway") return void 0;
954
+ const footNextToIt = (side) => {
955
+ const separation2 = tags[`separation_${side}`];
956
+ return tags[`traffic_mode_${side}`] === "foot" && (separation2 == null || separation2 === "no");
957
+ };
958
+ if (footNextToIt("right") || footNextToIt("left")) return true;
1103
959
  return void 0;
1104
960
  }
1105
961
  function specByCategoryId(id) {
@@ -1125,6 +981,44 @@ function specsWithGapDiscriminators() {
1125
981
  return CATEGORY_SPECS.filter((s) => s.gapDiscriminators != null && s.gapDiscriminators.length > 0);
1126
982
  }
1127
983
 
984
+ // src/categories/decision-view.ts
985
+ var IS_DECISION_VIEW = /* @__PURE__ */ Symbol("isDecisionView");
986
+ function resolveSided(source, key) {
987
+ let base;
988
+ let side;
989
+ if (key.endsWith("_left")) {
990
+ base = key.slice(0, -"_left".length);
991
+ side = "left";
992
+ } else if (key.endsWith("_right")) {
993
+ base = key.slice(0, -"_right".length);
994
+ side = "right";
995
+ }
996
+ if (base === void 0 || side === void 0) return { handled: false };
997
+ const sanitizer = SIDED_SANITIZERS[base];
998
+ if (!sanitizer) return { handled: false };
999
+ const value = sanitizer(source, side);
1000
+ if (value === DISALLOWED) return { handled: true, value: void 0 };
1001
+ return { handled: true, value };
1002
+ }
1003
+ function decisionTagsView(source) {
1004
+ if (source[IS_DECISION_VIEW]) return source;
1005
+ return new Proxy(source, {
1006
+ get(target, key) {
1007
+ if (key === IS_DECISION_VIEW) return true;
1008
+ if (typeof key !== "string") return target[key];
1009
+ const sided2 = resolveSided(target, key);
1010
+ if (sided2.handled) return sided2.value;
1011
+ const value = target[key];
1012
+ return value === DISALLOWED ? void 0 : value;
1013
+ },
1014
+ set(target, key, value) {
1015
+ if (typeof key === "string") target[key] = value;
1016
+ else target[key] = value;
1017
+ return true;
1018
+ }
1019
+ });
1020
+ }
1021
+
1128
1022
  // src/categories/compile-category-specs.ts
1129
1023
  var MACROS = { ...CATEGORY_MACROS };
1130
1024
  function compileMatch(spec) {
@@ -1140,13 +1034,14 @@ function compileMatch(spec) {
1140
1034
  function compileRefiningMatch(predicate) {
1141
1035
  return (tags) => evalPredicateStrict(tags, predicate, MACROS);
1142
1036
  }
1143
- function mkCategory(spec, id, condition, copyFromParent) {
1037
+ function mkCategory(spec, id, condition) {
1144
1038
  return {
1145
1039
  id,
1146
1040
  infrastructureExists: spec.infrastructureExists,
1147
1041
  implicitOneWay: spec.implicitOneWay,
1148
1042
  implicitOneWayConfidence: spec.implicitOneWayConfidence,
1149
- copySurfaceSmoothnessFromParent: copyFromParent ?? spec.copySurfaceSmoothnessFromParent,
1043
+ copySurfaceSmoothnessFromParent: spec.copySurfaceSmoothnessFromParent,
1044
+ bicycleSurface: spec.bicycleSurface,
1150
1045
  condition,
1151
1046
  process: spec.process
1152
1047
  };
@@ -1163,8 +1058,7 @@ function expandRefining(spec, baseMatch) {
1163
1058
  const refineMatch = compileRefiningMatch(child.match);
1164
1059
  const condition = (tags) => baseMatch(tags) && refineMatch(tags) || void 0;
1165
1060
  const childSpec = child.implicitOneWayConfidence ? { ...spec, implicitOneWayConfidence: child.implicitOneWayConfidence } : spec;
1166
- const copyFromParent = ["_adjoining", "_isolated", "_adjoiningOrIsolated"].includes(child.idSuffix) ? false : void 0;
1167
- return mkCategory(childSpec, resolveRefinedId2(spec, child), condition, copyFromParent);
1061
+ return mkCategory(childSpec, resolveRefinedId2(spec, child), condition);
1168
1062
  });
1169
1063
  }
1170
1064
  function expandSpec(spec) {
@@ -1172,40 +1066,297 @@ function expandSpec(spec) {
1172
1066
  if (!spec.refining?.length) {
1173
1067
  return [mkCategory(spec, spec.id, baseMatch)];
1174
1068
  }
1175
- return expandRefining(spec, baseMatch);
1176
- }
1177
- var COMPILED_CATEGORY_DEFINITIONS = CATEGORY_SPECS.flatMap(expandSpec);
1178
- function sidepathDiscriminatorKnown(tags) {
1179
- if (tags.is_sidepath === "yes" || tags.is_sidepath === "no") return true;
1180
- if (tags.highway === "service" || tags.highway === "track") return true;
1181
- return false;
1182
- }
1183
- function laneDiscriminatorKnown(tags) {
1184
- return tags.lane === "advisory" || tags.lane === "exclusive";
1185
- }
1186
-
1187
- // src/categories/bikelane-categories.ts
1188
- var CATEGORY_DEFINITIONS = COMPILED_CATEGORY_DEFINITIONS;
1189
- function categorizeBikelane(tags) {
1190
- for (const category of CATEGORY_DEFINITIONS) {
1191
- if (category.condition(decisionTagsView(tags))) {
1192
- category.process?.(tags);
1193
- return category;
1069
+ return expandRefining(spec, baseMatch);
1070
+ }
1071
+ var COMPILED_CATEGORY_DEFINITIONS = CATEGORY_SPECS.flatMap(expandSpec);
1072
+ function sidepathDiscriminatorKnown(tags) {
1073
+ if (tags.is_sidepath === "yes" || tags.is_sidepath === "no") return true;
1074
+ if (tags.highway === "service" || tags.highway === "track") return true;
1075
+ return false;
1076
+ }
1077
+ function laneDiscriminatorKnown(tags) {
1078
+ return tags.lane === "advisory" || tags.lane === "exclusive";
1079
+ }
1080
+
1081
+ // src/categories/bikelane-categories.ts
1082
+ var CATEGORY_DEFINITIONS = COMPILED_CATEGORY_DEFINITIONS;
1083
+ function categorizeBikelane(tags) {
1084
+ for (const category of CATEGORY_DEFINITIONS) {
1085
+ if (category.condition(decisionTagsView(tags))) {
1086
+ category.process?.(tags);
1087
+ return category;
1088
+ }
1089
+ }
1090
+ return null;
1091
+ }
1092
+
1093
+ // src/derive/bikelane-todos.ts
1094
+ var missingTrafficSignVehicleDestination = {
1095
+ id: "missing_traffic_sign_vehicle_destination",
1096
+ desc: "Expecting tag traffic_sign 'Anlieger frei' `traffic_sign=DE:244.1,1020-30` or similar.",
1097
+ todoTableOnly: true,
1098
+ condition: (tags) => tags.bicycle_road === "yes" && (tags.vehicle === "destination" || tags.motor_vehicle === "destination") && !containsSubstring(tags.traffic_sign, "1020-30")
1099
+ };
1100
+ var missingTrafficSign244 = {
1101
+ id: "missing_traffic_sign_244",
1102
+ desc: "Expecting tag `traffic_sign=DE:244.1` or similar.",
1103
+ todoTableOnly: true,
1104
+ condition: (tags, result) => tags.bicycle_road === "yes" && !containsSubstring(tags.traffic_sign, "244") && !missingTrafficSignVehicleDestination.condition(tags, result)
1105
+ };
1106
+ var missingAccessTagBicycleRoad = {
1107
+ id: "missing_access_tag_bicycle_road",
1108
+ desc: "Expected access tag `bicycle=designated` that is required for routing.",
1109
+ todoTableOnly: false,
1110
+ // Only check `vehicle` because `motor_vehicle` does allow `bicycle` already.
1111
+ condition: (tags) => tags.bicycle_road === "yes" && (tags.vehicle === "no" || tags.vehicle === "destination") && tags.bicycle !== "designated"
1112
+ };
1113
+ var malformedTrafficSign = {
1114
+ id: "malformed_traffic_sign",
1115
+ desc: "Traffic sign tag needs cleaning up.",
1116
+ todoTableOnly: true,
1117
+ // Compare raw with sanitized tag.
1118
+ condition: (tags) => ["traffic_sign", "traffic_sign:both", "traffic_sign:forward", "traffic_sign:backward"].some(
1119
+ (key) => tags[key] !== sanitizeTrafficSign(tags[key])
1120
+ )
1121
+ };
1122
+ var missingTrafficSign = {
1123
+ id: "missing_traffic_sign",
1124
+ desc: "Expected tag `traffic_sign=DE:*` or `traffic_sign=none`.",
1125
+ todoTableOnly: true,
1126
+ condition: (tags, result) => {
1127
+ const trafficSign = tags.traffic_sign ?? tags["traffic_sign:forward"] ?? tags["traffic_sign:backward"];
1128
+ return trafficSign === void 0 && // Add any new missing_traffic_sign_* here so we only trigger this todo when no other
1129
+ // traffic_sign todo is present.
1130
+ !(missingTrafficSign244.condition(tags, result) || missingTrafficSignVehicleDestination.condition(tags, result)) && result.category !== "cyclewayLink" && result.category !== "crossing" && result.category !== "needsClarification";
1131
+ }
1132
+ };
1133
+ var missingAccessTag240 = {
1134
+ id: "missing_access_tag_240",
1135
+ desc: "Expected tag `bicycle=designated` and `foot=designated`.",
1136
+ todoTableOnly: false,
1137
+ condition: (tags) => (containsSubstring(tags.traffic_sign, "240") || containsSubstring(tags.traffic_sign, "241")) && // either one missing (tilda-geo 61252e31f; before, only when both were missing)
1138
+ (tags.bicycle !== "designated" || tags.foot !== "designated") && tags.cycleway !== "track" && tags.cycleway !== "lane"
1139
+ };
1140
+ var SEGREGATED_VALUES = /* @__PURE__ */ new Set(["yes", "no"]);
1141
+ var missingSegregated = {
1142
+ id: "missing_segregated",
1143
+ desc: "Expected tag `segregated=yes` or `segregated=no`.",
1144
+ todoTableOnly: false,
1145
+ condition: (tags, result) => result.category === "needsClarification" && // neither `yes` nor `no` (tilda-geo ed8478350)
1146
+ !SEGREGATED_VALUES.has(tags.segregated ?? "") && (tags.bicycle === "designated" && tags.foot === "designated" || containsSubstring(tags.traffic_sign, "240") || containsSubstring(tags.traffic_sign, "241"))
1147
+ };
1148
+ var unexpectedBicycleAccessOnFootway = {
1149
+ id: "unexpected_bicycle_access_on_footway",
1150
+ desc: "Expected `highway=path+bicycle=designated` (unsigned/explicit DE:240) or `highway=footway+bicycle=yes` (unsigned/explicit DE:239,1022-10); Add traffic_sign=none to specify unsigned path.",
1151
+ todoTableOnly: true,
1152
+ condition: (tags, result) => tags.highway === "footway" && tags.bicycle === "designated" && result.category === "needsClarification"
1153
+ };
1154
+ var EXCLUDED_SURFACES = /* @__PURE__ */ new Set([
1155
+ "ground",
1156
+ "dirt",
1157
+ "fine_gravel",
1158
+ "gravel",
1159
+ "pebblestone",
1160
+ "earth"
1161
+ ]);
1162
+ var unexpectedHighwayPath = {
1163
+ id: "unexpected_highway_path",
1164
+ desc: "Expected `highway=cycleway` (unsigned/explicit DE:237)",
1165
+ todoTableOnly: true,
1166
+ // REFERENCE: See conditions in the `needsClarification` category.
1167
+ condition: (tags) => tags.highway === "path" && tags.bicycle === "designated" && tags.foot === "no" && !(hasTagWithPrefix(tags, "mtb:") || tags.mtb === "yes" || tags.surface !== void 0 && EXCLUDED_SURFACES.has(tags.surface))
1168
+ };
1169
+ var crossingTooLong = {
1170
+ id: "crossing_too_long",
1171
+ desc: "Crossing longer than 100 m, guidance form unclear. Please review and correct.",
1172
+ todoTableOnly: false,
1173
+ condition: (tags, result) => result.category === "needsClarification" && isCrossingPattern(tags) && tags._length != null && tags._length > 100
1174
+ };
1175
+ var needsClarification2 = {
1176
+ id: "needs_clarification",
1177
+ desc: "Tagging insufficient to categorize the bike infrastructure.",
1178
+ todoTableOnly: false,
1179
+ condition: (tags, result) => result.category === "needsClarification" && !(tags.cycleway === "shared" || // Handled by the road todo `deprecated_cycleway_shared`
1180
+ unexpectedBicycleAccessOnFootway.condition(tags, result) || crossingTooLong.condition(tags, result) || missingSegregated.condition(tags, result))
1181
+ };
1182
+ var adjoiningOrIsolated = {
1183
+ id: "adjoining_or_isolated",
1184
+ desc: "Only for category=cycleway_adjoiningOrIsolated for now. Expected tag `is_sidepath=yes` or `is_sidepath=no`.",
1185
+ todoTableOnly: false,
1186
+ condition: (_tags, result) => result.category === "cycleway_adjoiningOrIsolated"
1187
+ };
1188
+ var advisoryOrExclusive = {
1189
+ id: "advisory_or_exclusive",
1190
+ desc: "Expected tag `cycleway:*:lane=advisory` or `exclusive`.",
1191
+ todoTableOnly: false,
1192
+ condition: (_tags, result) => containsSubstring(result.category, "_advisoryOrExclusive")
1193
+ };
1194
+ var needsClarificationTrack = {
1195
+ id: "needs_clarification_track",
1196
+ desc: "Tagging `cycleway=track` insufficient to categorize the bike infrastructure`.",
1197
+ todoTableOnly: false,
1198
+ condition: (tags, result) => {
1199
+ if (result.category === "cyclewayOnHighwayProtected") return false;
1200
+ if (tags._parent == null) return false;
1201
+ if (tags.segregated === "yes" || tags.segregated === "no") return false;
1202
+ if (containsSubstring(tags.traffic_sign, "237")) return false;
1203
+ if (containsSubstring(tags.traffic_sign, "240")) return false;
1204
+ if (containsSubstring(tags.traffic_sign, "241")) return false;
1205
+ return tags.cycleway === "track";
1206
+ }
1207
+ };
1208
+ var mixedCyclewayBoth = {
1209
+ id: "mixed_cycleway_both",
1210
+ desc: "Mixed tagging of cycleway=* or cycleway:both=* with cycleway:SIDE",
1211
+ todoTableOnly: false,
1212
+ condition: (tags) => {
1213
+ const parent = tags._parent;
1214
+ if (parent == null) return false;
1215
+ const hasSide = parent["cycleway:left"] !== void 0 || parent["cycleway:right"] !== void 0;
1216
+ return parent["cycleway:both"] !== void 0 && hasSide || parent.cycleway !== void 0 && hasSide;
1217
+ }
1218
+ };
1219
+ var MAX_USUAL_WIDTH = 50;
1220
+ var REVIEWED_KEYS = [
1221
+ "check_date",
1222
+ "check_date:width",
1223
+ "survey:date",
1224
+ "survey:date:width",
1225
+ "survey_date"
1226
+ ];
1227
+ function hasReviewedKey(tags) {
1228
+ if (tags == null) return false;
1229
+ return REVIEWED_KEYS.some((key) => tags[key] !== void 0);
1230
+ }
1231
+ function isUnusualWidth(tags, result) {
1232
+ if (tags.width === void 0) return false;
1233
+ if (hasReviewedKey(tags) || hasReviewedKey(tags._parent)) return false;
1234
+ return result.width == null || result.width > MAX_USUAL_WIDTH;
1235
+ }
1236
+ var missingWidth = {
1237
+ id: "missing_width",
1238
+ desc: "Ways without `width`",
1239
+ todoTableOnly: true,
1240
+ condition: (_tags, result) => result.width == null && result.category !== "cyclewayLink" && result.category !== "crossing" && result.category !== "pedestrianAreaBicycleYes" && result.category !== "needsClarification" && !containsSubstring(result.category, "cyclewayOnHighway") && !containsSubstring(result.category, "sharedBusLane")
1241
+ };
1242
+ var unusualWidth = {
1243
+ id: "unusual_width",
1244
+ desc: "Width that we cannot read or that is unusually high. Fix `width`, or confirm it with `check_date=*` or `check_date:width=*`.",
1245
+ todoTableOnly: true,
1246
+ condition: (tags, result) => isUnusualWidth(tags, result)
1247
+ };
1248
+ var missingSurface = {
1249
+ id: "missing_surface",
1250
+ desc: "Ways without `surface`",
1251
+ todoTableOnly: true,
1252
+ // Either the surface is missing. But also surface values that are not derived from the osm tag
1253
+ // should be added.
1254
+ condition: (_tags, result) => (result.surface == null || result.surface_source !== "tag") && result.category !== "cyclewayLink" && result.category !== "needsClarification" && !containsSubstring(result.category, "cyclewayOnHighway") && !containsSubstring(result.category, "sharedBusLane")
1255
+ };
1256
+ var missingOneway = {
1257
+ id: "missing_oneway",
1258
+ desc: "Ways without explicit `oneway`",
1259
+ todoTableOnly: false,
1260
+ condition: (tags, result) => {
1261
+ if (needsClarificationTrack.condition(tags, result)) return false;
1262
+ if (needsClarification2.condition(tags, result)) return false;
1263
+ if (tags._parent != null) return false;
1264
+ if (result.category === "crossing") return false;
1265
+ if (result.category === "cyclewayLink") return false;
1266
+ if (!(result.oneway === "assumed_no" || result.oneway === "implicit_yes")) return false;
1267
+ return result.implicitOneWayConfidence === "low";
1268
+ }
1269
+ };
1270
+ var AGAINST_SIDE_TRAFFIC = {
1271
+ left: /* @__PURE__ */ new Set(["yes"]),
1272
+ right: /* @__PURE__ */ new Set(["-1"])
1273
+ };
1274
+ function againstSideTrafficKeys(tags) {
1275
+ const parent = tags._parent;
1276
+ const prefix = tags._prefix;
1277
+ const bothKey = `${prefix}:both:oneway`;
1278
+ const unsidedKey = `${prefix}:oneway`;
1279
+ const sharedKey = parent[bothKey] !== void 0 ? bothKey : parent[unsidedKey] !== void 0 ? unsidedKey : void 0;
1280
+ const keys = {};
1281
+ for (const side of ["left", "right"]) {
1282
+ const against = AGAINST_SIDE_TRAFFIC[side];
1283
+ const sideKey = `${prefix}:${side}:oneway`;
1284
+ const sideValue = parent[sideKey];
1285
+ if (sideValue !== void 0) {
1286
+ if (against.has(sideValue)) keys[side] = sideKey;
1287
+ } else if (sharedKey !== void 0 && against.has(parent[sharedKey])) {
1288
+ keys[side] = sharedKey;
1194
1289
  }
1195
1290
  }
1196
- return null;
1197
- }
1198
-
1199
- // src/derive/derive-oneway.ts
1200
- function deriveOneway(tags, category) {
1201
- if (tags["oneway:bicycle"] === "yes") return "yes";
1202
- if (tags["oneway:bicycle"] === "no") {
1203
- return tags.oneway === "yes" ? "car_not_bike" : "no";
1291
+ return keys;
1292
+ }
1293
+ var unexpectedOnewayDirection = {
1294
+ id: "unexpected_oneway_direction",
1295
+ desc: "Lane or track tagged to run against the traffic of its side (`cycleway:left:oneway=yes`, `cycleway:both:oneway=yes`, `cycleway:right:oneway=-1`).",
1296
+ todoTableOnly: false,
1297
+ condition: (tags) => {
1298
+ const parent = tags._parent;
1299
+ if (parent == null) return false;
1300
+ if (tags._prefix !== "cycleway") return false;
1301
+ if (parent.oneway === "yes" || parent.oneway === "-1") return false;
1302
+ if (tags["check_date:oneway"] != null || tags.check_date != null) return false;
1303
+ const keys = againstSideTrafficKeys(tags);
1304
+ for (const side of ["left", "right"]) {
1305
+ const key = keys[side];
1306
+ if (key === void 0) continue;
1307
+ if (side === tags._side || !key.includes(`:${side}:`)) return true;
1308
+ }
1309
+ return false;
1310
+ },
1311
+ // Removing the tag restores the default direction of the side. Only proposed for the left side:
1312
+ // `yes` there is the usual mix-up of "one direction" with "direction of the way".
1313
+ // The same list on both sides of a way, so MapRoulette gets one task per way.
1314
+ tagFix: (tags) => {
1315
+ const keys = againstSideTrafficKeys(tags);
1316
+ if (keys.left === void 0 || keys.right !== void 0) return void 0;
1317
+ return { unset: [keys.left] };
1204
1318
  }
1205
- if (tags.oneway === "yes" || tags.oneway === "no") return tags.oneway;
1206
- if (tags.highway === "service" || tags.highway === "track") return "assumed_no";
1207
- if (category.implicitOneWay) return "implicit_yes";
1208
- return "assumed_no";
1319
+ };
1320
+ var BIKELANE_TODOS = [
1321
+ // Infrastructure
1322
+ crossingTooLong,
1323
+ needsClarification2,
1324
+ adjoiningOrIsolated,
1325
+ advisoryOrExclusive,
1326
+ needsClarificationTrack,
1327
+ mixedCyclewayBoth,
1328
+ unexpectedHighwayPath,
1329
+ // Bicycle roads
1330
+ missingTrafficSignVehicleDestination,
1331
+ missingTrafficSign244,
1332
+ missingAccessTagBicycleRoad,
1333
+ // Traffic signs
1334
+ missingTrafficSign,
1335
+ malformedTrafficSign,
1336
+ // Bike- and foot path
1337
+ missingAccessTag240,
1338
+ missingSegregated,
1339
+ unexpectedBicycleAccessOnFootway,
1340
+ // Other
1341
+ missingWidth,
1342
+ unusualWidth,
1343
+ missingSurface,
1344
+ missingOneway,
1345
+ unexpectedOnewayDirection
1346
+ ];
1347
+ function deriveBikelaneTodos(tags, result) {
1348
+ const todos = [];
1349
+ let todoTagFixes;
1350
+ for (const todo of BIKELANE_TODOS) {
1351
+ if (!todo.condition(tags, result)) continue;
1352
+ todos.push(todo.id);
1353
+ const fix = todo.tagFix?.(tags, result);
1354
+ if (fix) {
1355
+ todoTagFixes ??= {};
1356
+ todoTagFixes[todo.id] = fix;
1357
+ }
1358
+ }
1359
+ return todoTagFixes ? { todos, todoTagFixes } : { todos };
1209
1360
  }
1210
1361
 
1211
1362
  // src/sanitize/sanitize-surface.ts
@@ -1263,27 +1414,10 @@ function sanitizeSurface(tags) {
1263
1414
  }
1264
1415
  return sanitizeForLogging(tags.surface, SURFACE_ALLOWED, SURFACE_IGNORED);
1265
1416
  }
1266
-
1267
- // src/derive/derive-surface.ts
1268
- function deriveSurface(tags) {
1269
- if (tags.surface == null) return {};
1270
- const surface = sanitizeSurface(tags);
1271
- if (surface === DISALLOWED) return {};
1272
- return { surface, surface_source: "tag", surface_confidence: "high" };
1273
- }
1274
- function deriveBikelaneSurface(tags, category) {
1275
- const own = deriveSurface(tags);
1276
- if (own.surface != null) {
1277
- return { surface: own.surface, surface_source: "tag", surface_confidence: "high" };
1278
- }
1279
- const parent = tags._parent;
1280
- if (category.copySurfaceSmoothnessFromParent && parent != null) {
1281
- const parentSurface = deriveSurface(parent);
1282
- if (parentSurface.surface != null) {
1283
- return { surface: parentSurface.surface, surface_source: "parent_highway_tag", surface_confidence: "high" };
1284
- }
1285
- }
1286
- return {};
1417
+ function allowedSurface(value, tags) {
1418
+ if (value == null) return void 0;
1419
+ const surface = sanitizeSurface({ surface: value, "sett:length": tags["sett:length"] });
1420
+ return surface === DISALLOWED ? void 0 : surface;
1287
1421
  }
1288
1422
 
1289
1423
  // src/derive/derive-smoothness.ts
@@ -1296,9 +1430,15 @@ var SMOOTHNESS_NORMALIZATION = {
1296
1430
  };
1297
1431
  function normalizeSmoothness(smoothness) {
1298
1432
  if (smoothness != null) {
1299
- if (SMOOTHNESS_DIRECT.has(smoothness)) return { smoothness, smoothness_source: "tag", smoothness_confidence: "high" };
1433
+ if (SMOOTHNESS_DIRECT.has(smoothness))
1434
+ return { smoothness, smoothness_source: "tag", smoothness_confidence: "high" };
1300
1435
  const normalized = SMOOTHNESS_NORMALIZATION[smoothness];
1301
- if (normalized) return { smoothness: normalized, smoothness_source: "tag_normalized", smoothness_confidence: "high" };
1436
+ if (normalized)
1437
+ return {
1438
+ smoothness: normalized,
1439
+ smoothness_source: "tag_normalized",
1440
+ smoothness_confidence: "high"
1441
+ };
1302
1442
  }
1303
1443
  return {};
1304
1444
  }
@@ -1380,7 +1520,12 @@ var SURFACE_TO_SMOOTHNESS_NON_STANDARD = {
1380
1520
  function deriveSmoothnessFromSurface(surface) {
1381
1521
  if (!surface) return {};
1382
1522
  const smoothness = SURFACE_TO_SMOOTHNESS[surface] ?? SURFACE_TO_SMOOTHNESS_NON_STANDARD[surface];
1383
- if (smoothness) return { smoothness, smoothness_source: "surface_to_smoothness", smoothness_confidence: "medium" };
1523
+ if (smoothness)
1524
+ return {
1525
+ smoothness,
1526
+ smoothness_source: "surface_to_smoothness",
1527
+ smoothness_confidence: "medium"
1528
+ };
1384
1529
  return {};
1385
1530
  }
1386
1531
  var TRACKTYPE_TO_SMOOTHNESS = {
@@ -1393,15 +1538,28 @@ var TRACKTYPE_TO_SMOOTHNESS = {
1393
1538
  function deriveSmoothnessFromTrackType(type) {
1394
1539
  if (!type) return {};
1395
1540
  const smoothness = TRACKTYPE_TO_SMOOTHNESS[type];
1396
- if (smoothness) return { smoothness, smoothness_source: "tracktype_to_smoothness", smoothness_confidence: "medium" };
1541
+ if (smoothness)
1542
+ return {
1543
+ smoothness,
1544
+ smoothness_source: "tracktype_to_smoothness",
1545
+ smoothness_confidence: "medium"
1546
+ };
1397
1547
  return {};
1398
1548
  }
1399
1549
  function deriveSmoothnessFromMtbScale(scale) {
1400
1550
  if (!scale) return {};
1401
1551
  if (scale === "0" || scale === "0+" || scale === "0-") {
1402
- return { smoothness: "bad", smoothness_source: "mtb:scale_to_smoothness", smoothness_confidence: "medium" };
1552
+ return {
1553
+ smoothness: "bad",
1554
+ smoothness_source: "mtb:scale_to_smoothness",
1555
+ smoothness_confidence: "medium"
1556
+ };
1403
1557
  }
1404
- return { smoothness: "very_bad", smoothness_source: "mtb:scale_to_smoothness", smoothness_confidence: "medium" };
1558
+ return {
1559
+ smoothness: "very_bad",
1560
+ smoothness_source: "mtb:scale_to_smoothness",
1561
+ smoothness_confidence: "medium"
1562
+ };
1405
1563
  }
1406
1564
  function deriveSmoothness(tags) {
1407
1565
  let result = normalizeSmoothness(tags.smoothness);
@@ -1429,47 +1587,545 @@ function deriveBikelaneSmoothness(tags, category) {
1429
1587
  smoothness_confidence = parentResult.smoothness_confidence;
1430
1588
  }
1431
1589
  }
1432
- if (smoothness != null && smoothness_source != null && smoothness_confidence != null) {
1433
- return { smoothness, smoothness_source, smoothness_confidence };
1590
+ if (smoothness != null && smoothness_source != null && smoothness_confidence != null) {
1591
+ return { smoothness, smoothness_source, smoothness_confidence };
1592
+ }
1593
+ return {};
1594
+ }
1595
+
1596
+ // src/derive/derive-directional-surface.ts
1597
+ var SURFACE_KEYS = [
1598
+ { key: "surface:bicycle", token: "surface_bicycle" },
1599
+ { key: "surface:bicycle:right", token: "surface_bicycle_right" },
1600
+ { key: "surface:bicycle:forward", token: "surface_bicycle_right" },
1601
+ { key: "surface:bicycle:left", token: "surface_bicycle_left" },
1602
+ { key: "surface:bicycle:backward", token: "surface_bicycle_left" },
1603
+ { key: "surface:right", token: "surface_right" },
1604
+ { key: "surface:forward", token: "surface_right" },
1605
+ { key: "surface:left", token: "surface_left" },
1606
+ { key: "surface:backward", token: "surface_left" }
1607
+ ];
1608
+ var SMOOTHNESS_RANK = {
1609
+ excellent: 1,
1610
+ good: 2,
1611
+ intermediate: 3,
1612
+ bad: 4,
1613
+ very_bad: 5
1614
+ };
1615
+ function badness(rawSurface) {
1616
+ const smoothness = deriveSmoothness({ surface: rawSurface }).smoothness;
1617
+ return smoothness && SMOOTHNESS_RANK[smoothness] || 0;
1618
+ }
1619
+ function worstDirectionalSurface(tags) {
1620
+ if (allowedSurface(tags.surface, tags) != null) return void 0;
1621
+ const seenTokens = /* @__PURE__ */ new Set();
1622
+ let worst;
1623
+ for (const { key, token } of SURFACE_KEYS) {
1624
+ const raw = tags[key];
1625
+ if (raw == null || seenTokens.has(token) || allowedSurface(raw, tags) == null) continue;
1626
+ seenTokens.add(token);
1627
+ if (worst == null || badness(raw) > badness(worst)) worst = raw;
1628
+ }
1629
+ return worst;
1630
+ }
1631
+
1632
+ // src/derive/derive-bikelane-surface-tags.ts
1633
+ function choose(tags) {
1634
+ const bicycle = allowedSurface(tags["surface:bicycle"], tags) ? tags["surface:bicycle"] : void 0;
1635
+ const bicycleSmoothness = tags["smoothness:bicycle"];
1636
+ if (bicycle) {
1637
+ return { surface: bicycle, smoothness: bicycleSmoothness, directional: false };
1638
+ }
1639
+ if (allowedSurface(tags.surface, tags)) {
1640
+ return {
1641
+ surface: tags.surface,
1642
+ smoothness: bicycleSmoothness ?? tags.smoothness,
1643
+ directional: false
1644
+ };
1645
+ }
1646
+ const fallback = worstDirectionalSurface(tags);
1647
+ if (fallback) {
1648
+ return {
1649
+ surface: fallback,
1650
+ smoothness: bicycleSmoothness ?? tags.smoothness,
1651
+ directional: true
1652
+ };
1653
+ }
1654
+ return {
1655
+ surface: void 0,
1656
+ smoothness: bicycleSmoothness ?? tags.smoothness,
1657
+ directional: false
1658
+ };
1659
+ }
1660
+ var SIDE_TO_DIRECTION = { right: "forward", left: "backward" };
1661
+ function chooseForSide(parent, side) {
1662
+ if (allowedSurface(parent["surface:bicycle"], parent)) return choose(parent);
1663
+ const twoWay = parent.oneway !== "yes" && parent.oneway !== "-1";
1664
+ const direction = SIDE_TO_DIRECTION[side];
1665
+ const allowed = (key) => allowedSurface(parent[key], parent) ? parent[key] : void 0;
1666
+ const surface = allowed(`surface:bicycle:${side}`) ?? (twoWay ? allowed(`surface:bicycle:${direction}`) : void 0) ?? allowed(`surface:${side}`) ?? (twoWay ? allowed(`surface:${direction}`) : void 0);
1667
+ if (surface) {
1668
+ return { surface, smoothness: parent["smoothness:bicycle"], directional: true };
1669
+ }
1670
+ return choose(parent);
1671
+ }
1672
+ function override(tags, choice, parent) {
1673
+ const result = { ...tags };
1674
+ result.surface = choice.surface;
1675
+ result.smoothness = choice.smoothness;
1676
+ result._parent = parent;
1677
+ return result;
1678
+ }
1679
+ function deriveBikelaneSurfaceTags(tags, category) {
1680
+ let parent;
1681
+ let parentDirectional = false;
1682
+ if (category.copySurfaceSmoothnessFromParent && typeof tags._parent === "object" && tags._parent) {
1683
+ const side = tags._side;
1684
+ const parentChoice = side === "left" || side === "right" ? chooseForSide(tags._parent, side) : choose(tags._parent);
1685
+ parent = override(tags._parent, parentChoice);
1686
+ parentDirectional = parentChoice.directional;
1687
+ }
1688
+ if (category.bicycleSurface == null) {
1689
+ if (parent == null) return { tags, directional: false, parentDirectional: false };
1690
+ return {
1691
+ tags: override(
1692
+ tags,
1693
+ { surface: tags.surface, smoothness: tags.smoothness},
1694
+ parent
1695
+ ),
1696
+ directional: false,
1697
+ parentDirectional
1698
+ };
1699
+ }
1700
+ const choice = choose(tags);
1701
+ return {
1702
+ tags: override(tags, choice, parent),
1703
+ directional: choice.directional,
1704
+ parentDirectional
1705
+ };
1706
+ }
1707
+ function bikelaneSurfaceSource(surfaceTags, surfaceSource) {
1708
+ if (surfaceSource === "tag" && surfaceTags.directional) return "tag_directional";
1709
+ if (surfaceSource === "parent_highway_tag" && surfaceTags.parentDirectional) {
1710
+ return "parent_highway_tag_directional";
1711
+ }
1712
+ return surfaceSource;
1713
+ }
1714
+
1715
+ // src/derive/derive-oneway.ts
1716
+ var isOneway = (value) => value === "yes" || value === "-1";
1717
+ var ONEWAY_JUNCTIONS = /* @__PURE__ */ new Set(["roundabout", "circular"]);
1718
+ function isOnewayRoad(road) {
1719
+ const oneway = road.oneway;
1720
+ if (oneway === "yes" || oneway === "1" || oneway === "true" || oneway === "-1") return true;
1721
+ return oneway === void 0 && road.junction !== void 0 && ONEWAY_JUNCTIONS.has(road.junction);
1722
+ }
1723
+ function defaultSideRunsAgainstWay(road, side) {
1724
+ if (isOnewayRoad(road)) return road.oneway === "-1";
1725
+ return side === "left";
1726
+ }
1727
+ function onewayValue(tags, category) {
1728
+ const oneway = tags.oneway;
1729
+ const onewayBicycle = tags["oneway:bicycle"];
1730
+ if (isOneway(onewayBicycle)) {
1731
+ return "yes";
1732
+ } else if (onewayBicycle === "no") {
1733
+ return isOneway(oneway) ? "car_not_bike" : "no";
1734
+ }
1735
+ if (isOneway(oneway)) return "yes";
1736
+ if (oneway === "no") return "no";
1737
+ if (tags.highway === "service" || tags.highway === "track") return "assumed_no";
1738
+ if (category.implicitOneWay) return "implicit_yes";
1739
+ return "assumed_no";
1740
+ }
1741
+ function sideLineReversed(tags) {
1742
+ const side = tags._side;
1743
+ if (side !== "left" && side !== "right") return false;
1744
+ const direction = tags["oneway:bicycle"] ?? tags.oneway;
1745
+ if (direction === "-1") return true;
1746
+ if (direction === "yes") return false;
1747
+ const parent = tags._parent ?? {};
1748
+ if (direction === void 0 && isOnewayRoad(parent)) return parent.oneway === "-1";
1749
+ return side === "left";
1750
+ }
1751
+ function deriveOnewayDirection(tags, category) {
1752
+ return { oneway: onewayValue(tags, category), lineReversed: sideLineReversed(tags) };
1753
+ }
1754
+
1755
+ // src/derive/derive-surface.ts
1756
+ function deriveSurface(tags) {
1757
+ if (tags.surface == null) return {};
1758
+ const surface = sanitizeSurface(tags);
1759
+ if (surface === DISALLOWED) return {};
1760
+ return { surface, surface_source: "tag", surface_confidence: "high" };
1761
+ }
1762
+ function deriveBikelaneSurface(tags, category) {
1763
+ const own = deriveSurface(tags);
1764
+ if (own.surface != null) {
1765
+ return { surface: own.surface, surface_source: "tag", surface_confidence: "high" };
1766
+ }
1767
+ const parent = tags._parent;
1768
+ if (category.copySurfaceSmoothnessFromParent && parent != null) {
1769
+ const parentSurface = deriveSurface(parent);
1770
+ if (parentSurface.surface != null) {
1771
+ return {
1772
+ surface: parentSurface.surface,
1773
+ surface_source: "parent_highway_tag",
1774
+ surface_confidence: "high"
1775
+ };
1776
+ }
1777
+ }
1778
+ return {};
1779
+ }
1780
+
1781
+ // src/derive/derive-traffic-mode.ts
1782
+ var DIRECTIONAL_PARKING_INFERENCE_CATEGORIES = /* @__PURE__ */ new Set([
1783
+ "cyclewayOnHighway_advisory",
1784
+ "cyclewayOnHighway_advisoryOrExclusive",
1785
+ "cyclewayOnHighway_exclusive",
1786
+ "cyclewayOnHighwayBetweenLanes",
1787
+ "cyclewayOnHighwayProtected"
1788
+ ]);
1789
+ var PARKING_ALLOWED = [
1790
+ "no",
1791
+ "yes",
1792
+ "lane",
1793
+ "street_side",
1794
+ "on_kerb",
1795
+ "half_on_kerb",
1796
+ "shoulder",
1797
+ "separate"
1798
+ ];
1799
+ function sanitizeParking(value) {
1800
+ if (value == null) return void 0;
1801
+ return sanitizeForLogging(value, PARKING_ALLOWED);
1802
+ }
1803
+ function inferTrafficModeFromParking(centerlineTags, side) {
1804
+ const raw = centerlineTags[`parking:${side}`] ?? centerlineTags["parking:both"];
1805
+ const value = sanitizeParking(raw);
1806
+ if (removeDisallowedValue(value) == null) return void 0;
1807
+ if (value === "no") return void 0;
1808
+ return "parking";
1809
+ }
1810
+ function deriveTrafficMode(bikelaneTags, centerlineTags, categoryId, side) {
1811
+ const left = removeDisallowedValue(trafficMode(bikelaneTags, "left"));
1812
+ const right = removeDisallowedValue(trafficMode(bikelaneTags, "right"));
1813
+ if (left != null || right != null) {
1814
+ return { traffic_mode_left: left, traffic_mode_right: right };
1815
+ }
1816
+ const inferredLeft = inferTrafficModeFromParking(centerlineTags, "left");
1817
+ const inferredRight = inferTrafficModeFromParking(centerlineTags, "right");
1818
+ if (categoryId === "bicycleRoad" || categoryId === "bicycleRoad_vehicleDestination") {
1819
+ return { traffic_mode_left: inferredLeft, traffic_mode_right: inferredRight };
1820
+ }
1821
+ if (DIRECTIONAL_PARKING_INFERENCE_CATEGORIES.has(categoryId)) {
1822
+ return {
1823
+ traffic_mode_left: void 0,
1824
+ traffic_mode_right: inferTrafficModeFromParking(centerlineTags, side)
1825
+ };
1826
+ }
1827
+ return { traffic_mode_left: left, traffic_mode_right: right };
1828
+ }
1829
+
1830
+ // src/helpers/road-width.ts
1831
+ var STREET_WIDTHS = {
1832
+ primary: 10,
1833
+ secondary: 8,
1834
+ tertiary: 6,
1835
+ residential: 6
1836
+ };
1837
+ function roadWidth(tags) {
1838
+ const width = parseWidth(tags.width) ?? parseWidth(tags.est_width);
1839
+ if (width !== void 0) return width;
1840
+ const byHighway = tags.highway === void 0 ? void 0 : STREET_WIDTHS[tags.highway];
1841
+ return byHighway ?? 8;
1842
+ }
1843
+
1844
+ // src/helpers/highway-classes.ts
1845
+ var TRUNK_MOTORWAY_CLASSES = ["motorway", "motorway_link", "trunk", "trunk_link"];
1846
+ var MAJOR_ROAD_CLASSES = [
1847
+ "primary",
1848
+ "primary_link",
1849
+ "secondary",
1850
+ "secondary_link",
1851
+ "tertiary",
1852
+ "tertiary_link"
1853
+ ];
1854
+ var MINOR_ROAD_CLASSES = [
1855
+ "unclassified",
1856
+ "residential",
1857
+ "road",
1858
+ "living_street",
1859
+ "pedestrian",
1860
+ "service"
1861
+ ];
1862
+ var PATH_CLASSES = ["track", "path", "footway", "cycleway", "steps"];
1863
+ var SIDEPATH_HIGHWAY_CLASSES = /* @__PURE__ */ new Set([...PATH_CLASSES, "pedestrian"]);
1864
+ var ALLOWED_HIGHWAYS = /* @__PURE__ */ new Set([
1865
+ ...TRUNK_MOTORWAY_CLASSES,
1866
+ ...MAJOR_ROAD_CLASSES,
1867
+ ...MINOR_ROAD_CLASSES,
1868
+ ...PATH_CLASSES
1869
+ ]);
1870
+
1871
+ // src/transform/prepare-tags.ts
1872
+ function restrictedAccessTags(tags) {
1873
+ const restricted = [];
1874
+ if (tags.access === "no") restricted.push("access");
1875
+ if (tags.highway === "cycleway" && tags.bicycle === "no") restricted.push("bicycle");
1876
+ if (tags.highway === "footway" && tags.foot === "no") restricted.push("foot");
1877
+ return restricted;
1878
+ }
1879
+ function transformLifecycleTags(tags) {
1880
+ if (!tags.highway) return;
1881
+ if (tags.construction != null && ALLOWED_HIGHWAYS.has(tags.construction)) {
1882
+ tags.highway = tags.construction;
1883
+ tags.lifecycle = "construction";
1884
+ tags.construction = void 0;
1885
+ }
1886
+ const constructionRestricted = restrictedAccessTags(tags);
1887
+ if (constructionRestricted.length > 0) {
1888
+ const text = `${tags["access:reason"] ?? ""} ${tags.description ?? ""} ${tags.note ?? ""}`.toLowerCase();
1889
+ if (containsSubstring(text, "construction") || containsSubstring(text, "baustelle")) {
1890
+ tags.lifecycle = "construction_no_access";
1891
+ for (const t of constructionRestricted) tags[t] = void 0;
1892
+ }
1893
+ }
1894
+ const blockedTerms = [
1895
+ "sperrung",
1896
+ "gesperrt",
1897
+ "blockiert",
1898
+ "blocked",
1899
+ "closure",
1900
+ "closed",
1901
+ "blocked off"
1902
+ ];
1903
+ const blockedRestricted = restrictedAccessTags(tags);
1904
+ if (blockedRestricted.length > 0) {
1905
+ const text = `${tags.description ?? ""} ${tags.note ?? ""}`.toLowerCase();
1906
+ if (blockedTerms.some((term) => containsSubstring(text, term))) {
1907
+ tags.lifecycle = "blocked";
1908
+ for (const t of blockedRestricted) tags[t] = void 0;
1909
+ }
1910
+ }
1911
+ transformTemporary(tags);
1912
+ }
1913
+ var TEMPORARY_SIDE_PREFIXES = ["cycleway", "sidewalk"].flatMap(
1914
+ (prefix) => ["", ":left", ":right", ":both"].map((infix) => `${prefix}${infix}`)
1915
+ );
1916
+ function transformTemporary(tags) {
1917
+ if (tags.temporary === "yes") {
1918
+ tags.temporary = void 0;
1919
+ tags.lifecycle ??= "temporary";
1920
+ }
1921
+ for (const prefix of TEMPORARY_SIDE_PREFIXES) {
1922
+ if (tags[`${prefix}:temporary`] !== "yes") continue;
1923
+ tags[`${prefix}:temporary`] = void 0;
1924
+ tags[`${prefix}:lifecycle`] ??= "temporary";
1925
+ }
1926
+ }
1927
+ var CONTRAFLOW = {
1928
+ yes: { side: "left", otherSide: "right", oneway: "-1" },
1929
+ "-1": { side: "right", otherSide: "left", oneway: "yes" }
1930
+ };
1931
+ var OPPOSITE_INFRASTRUCTURE = {
1932
+ opposite_lane: "lane",
1933
+ opposite_track: "track"
1934
+ };
1935
+ function transformCyclewayOppositeSchema(tags) {
1936
+ const direction = tags.oneway === void 0 ? void 0 : CONTRAFLOW[tags.oneway];
1937
+ if (direction === void 0) return;
1938
+ if (tags.cycleway === "opposite") {
1939
+ tags.cycleway = "no";
1940
+ tags["oneway:bicycle"] = "no";
1941
+ return;
1942
+ }
1943
+ const infrastructure = tags.cycleway === void 0 ? void 0 : OPPOSITE_INFRASTRUCTURE[tags.cycleway];
1944
+ if (infrastructure !== void 0) {
1945
+ const sideKey = `cycleway:${direction.side}`;
1946
+ const sideOnewayKey = `${sideKey}:oneway`;
1947
+ tags.cycleway = void 0;
1948
+ tags[`cycleway:${direction.otherSide}`] = "no";
1949
+ tags[sideKey] = infrastructure;
1950
+ tags[sideOnewayKey] = tags[sideOnewayKey] ?? direction.oneway;
1951
+ tags["oneway:bicycle"] = "no";
1952
+ }
1953
+ }
1954
+ function transformConstructionPrefix(tags) {
1955
+ const constructionKeys = [];
1956
+ for (const key of Object.keys(tags)) {
1957
+ const value = tags[key];
1958
+ if (value !== void 0 && key.startsWith("construction:")) constructionKeys.push([key, value]);
1959
+ }
1960
+ for (const [key, value] of constructionKeys) {
1961
+ const baseTag = key.slice("construction:".length);
1962
+ tags[baseTag] = value;
1963
+ tags[key] = void 0;
1964
+ if (/^(cycleway|sidewalk)(:|$)/.test(baseTag)) {
1965
+ tags[`${baseTag}:lifecycle`] = "construction";
1966
+ } else {
1967
+ tags.lifecycle = "construction";
1968
+ }
1969
+ }
1970
+ }
1971
+ function transformCyclewayBothPostfix(tags) {
1972
+ if (tags.cycleway === "no" && tags["cycleway:both"] == null && tags["cycleway:left"] == null && tags["cycleway:right"] == null) {
1973
+ tags["cycleway:both"] = "no";
1974
+ tags.cycleway = void 0;
1975
+ }
1976
+ }
1977
+ var ONEWAY_YES_ALIASES = /* @__PURE__ */ new Set(["1", "true"]);
1978
+ var ONEWAY_JUNCTIONS2 = /* @__PURE__ */ new Set(["roundabout", "circular"]);
1979
+ var ONEWAY_KEYS = (() => {
1980
+ const keys = ["oneway", "oneway:bicycle"];
1981
+ for (const prefix of ["cycleway", "sidewalk"]) {
1982
+ for (const infix of ["", ":left", ":right", ":both"]) keys.push(`${prefix}${infix}:oneway`);
1983
+ }
1984
+ return [...keys, ...keys.map((key) => `construction:${key}`)];
1985
+ })();
1986
+ function normalizeOnewayTags(tags) {
1987
+ for (const key of ONEWAY_KEYS) {
1988
+ const value = tags[key];
1989
+ if (value !== void 0 && ONEWAY_YES_ALIASES.has(value)) tags[key] = "yes";
1990
+ }
1991
+ if (tags.oneway === void 0 && tags.junction !== void 0 && ONEWAY_JUNCTIONS2.has(tags.junction)) {
1992
+ tags.oneway = "yes";
1434
1993
  }
1435
- return {};
1994
+ }
1995
+ function prepareTags(tags) {
1996
+ transformLifecycleTags(tags);
1997
+ normalizeOnewayTags(tags);
1998
+ transformCyclewayOppositeSchema(tags);
1999
+ transformConstructionPrefix(tags);
2000
+ transformCyclewayBothPostfix(tags);
1436
2001
  }
1437
2002
 
1438
- // src/derive/derive-traffic-mode.ts
1439
- var DIRECTIONAL_PARKING_INFERENCE_CATEGORIES = /* @__PURE__ */ new Set([
1440
- "cyclewayOnHighway_advisory",
1441
- "cyclewayOnHighway_advisoryOrExclusive",
1442
- "cyclewayOnHighway_exclusive",
1443
- "cyclewayOnHighwayBetweenLanes",
1444
- "cyclewayOnHighwayProtected"
1445
- ]);
1446
- var PARKING_ALLOWED = ["no", "yes", "lane", "street_side", "on_kerb", "half_on_kerb", "shoulder", "separate"];
1447
- function sanitizeParking(value) {
1448
- if (value == null) return void 0;
1449
- return sanitizeForLogging(value, PARKING_ALLOWED);
2003
+ // src/transform/transformations.ts
2004
+ var SIDES = ["left", "right"];
2005
+ var META_PREFIXES = ["source:", "note:"];
2006
+ function unnestPrefixedTags(tags, prefix, infix, dest, metaPrefix) {
2007
+ const metaPrefixString = metaPrefix ?? "";
2008
+ const fullPrefix = metaPrefixString + prefix + infix;
2009
+ const prefixLen = fullPrefix.length;
2010
+ for (const key of Object.keys(tags)) {
2011
+ const val = tags[key];
2012
+ if (val === void 0) continue;
2013
+ if (!key.startsWith(fullPrefix)) continue;
2014
+ if (key === fullPrefix) {
2015
+ const destinationKey = metaPrefix ? metaPrefixString.slice(0, -1) : prefix;
2016
+ dest[destinationKey] = val;
2017
+ dest._infix = infix;
2018
+ } else {
2019
+ const extractedSuffix = key.slice(prefixLen + 1);
2020
+ const suffixKey = extractedSuffix.match(/^[^:]*/)[0];
2021
+ if (infix !== "" || !(suffixKey === "left" || suffixKey === "right" || suffixKey === "both")) {
2022
+ const destinationKey = metaPrefix ? metaPrefixString + extractedSuffix : extractedSuffix;
2023
+ dest[destinationKey] = val;
2024
+ dest._infix = infix;
2025
+ }
2026
+ }
2027
+ }
2028
+ return dest;
1450
2029
  }
1451
- function inferTrafficModeFromParking(centerlineTags, side) {
1452
- const raw = centerlineTags[`parking:${side}`] ?? centerlineTags["parking:both"];
1453
- const value = sanitizeParking(raw);
1454
- if (removeDisallowedValue(value) == null) return void 0;
1455
- if (value === "no") return void 0;
1456
- return "parking";
2030
+ var DIRECTED_PARENT_TAGS = ["cycleway:lanes", "bicycle:lanes"];
2031
+ var DIRECTED_SELF_TAGS = ["traffic_sign"];
2032
+ var SIDE_TO_DIRECTION2 = {
2033
+ "": "",
2034
+ both: "",
2035
+ left: ":backward",
2036
+ right: ":forward"
2037
+ };
2038
+ function convertDirectedTags(cycleway, directionReference) {
2039
+ const parent = cycleway._parent;
2040
+ const side = cycleway._side ?? "";
2041
+ for (const key of DIRECTED_PARENT_TAGS) {
2042
+ const directedKey = key + SIDE_TO_DIRECTION2[side];
2043
+ cycleway[key] = cycleway[key] ?? parent[key] ?? parent[directedKey];
2044
+ }
2045
+ for (const key of DIRECTED_SELF_TAGS) {
2046
+ if (directionReference === "self") {
2047
+ cycleway[key] = cycleway[key] ?? cycleway[`${key}:forward`];
2048
+ } else {
2049
+ const directedKey = key + SIDE_TO_DIRECTION2[side];
2050
+ cycleway[key] = cycleway[key] ?? cycleway[directedKey];
2051
+ }
2052
+ }
2053
+ return cycleway;
1457
2054
  }
1458
- function deriveTrafficMode(bikelaneTags, centerlineTags, categoryId, side) {
1459
- const left = removeDisallowedValue(trafficMode(bikelaneTags, "left"));
1460
- const right = removeDisallowedValue(trafficMode(bikelaneTags, "right"));
1461
- if (left != null || right != null) {
1462
- return { traffic_mode_left: left, traffic_mode_right: right };
2055
+ function getTransformedObjects(tags, transformations) {
2056
+ const center = { ...tags, _side: "self" };
2057
+ if (tags.highway != null && SIDEPATH_HIGHWAY_CLASSES.has(tags.highway)) {
2058
+ unnestPrefixedTags(tags, "cycleway", "", center);
2059
+ for (const mp of META_PREFIXES) unnestPrefixedTags(tags, "cycleway", "", center, mp);
2060
+ if (center.oneway === "yes" && tags["oneway:bicycle"] !== "no") {
2061
+ center.traffic_sign = center.traffic_sign ?? center["traffic_sign:forward"];
2062
+ }
2063
+ if (center.oneway === "-1" && tags["oneway:bicycle"] !== "no") {
2064
+ center.traffic_sign = center.traffic_sign ?? center["traffic_sign:backward"];
2065
+ }
2066
+ return [center];
1463
2067
  }
1464
- const inferredLeft = inferTrafficModeFromParking(centerlineTags, "left");
1465
- const inferredRight = inferTrafficModeFromParking(centerlineTags, "right");
1466
- if (categoryId === "bicycleRoad" || categoryId === "bicycleRoad_vehicleDestination") {
1467
- return { traffic_mode_left: inferredLeft, traffic_mode_right: inferredRight };
2068
+ const results = [center];
2069
+ for (const transformation of transformations) {
2070
+ for (const side of SIDES) {
2071
+ if (tags.highway === transformation.highway) continue;
2072
+ const prefix = transformation.prefix;
2073
+ const newObj = {
2074
+ _prefix: prefix,
2075
+ _side: side,
2076
+ _parent_highway: tags.highway,
2077
+ highway: transformation.highway
2078
+ };
2079
+ newObj._parent = tags;
2080
+ unnestPrefixedTags(tags, prefix, "", newObj);
2081
+ unnestPrefixedTags(tags, prefix, ":both", newObj);
2082
+ unnestPrefixedTags(tags, prefix, `:${side}`, newObj);
2083
+ for (const mp of META_PREFIXES) {
2084
+ unnestPrefixedTags(tags, prefix, "", newObj, mp);
2085
+ unnestPrefixedTags(tags, prefix, ":both", newObj, mp);
2086
+ unnestPrefixedTags(tags, prefix, `:${side}`, newObj, mp);
2087
+ }
2088
+ if (newObj._infix !== void 0 && transformation.filter(newObj)) {
2089
+ convertDirectedTags(newObj, transformation.direction_reference);
2090
+ results.push(newObj);
2091
+ }
2092
+ }
1468
2093
  }
1469
- if (DIRECTIONAL_PARKING_INFERENCE_CATEGORIES.has(categoryId)) {
1470
- return { traffic_mode_left: void 0, traffic_mode_right: inferTrafficModeFromParking(centerlineTags, side) };
2094
+ return results;
2095
+ }
2096
+ var BIKELANE_TRANSFORMATIONS = [
2097
+ { highway: "cycleway", prefix: "cycleway", direction_reference: "self", filter: () => true },
2098
+ {
2099
+ highway: "footway",
2100
+ prefix: "sidewalk",
2101
+ direction_reference: "parent",
2102
+ filter: (t) => !(t.footway === "no" || t.footway === "separate")
1471
2103
  }
1472
- return { traffic_mode_left: left, traffic_mode_right: right };
2104
+ ];
2105
+
2106
+ // src/derive/road-todos.ts
2107
+ var SHARED_KEYS = ["cycleway", "cycleway:both", "cycleway:left", "cycleway:right"];
2108
+ var deprecatedCyclewayShared = {
2109
+ id: "deprecated_cycleway_shared",
2110
+ desc: "The tagging `cycleway=shared` (also `cycleway:both|left|right=shared`) is deprecated and should be replaced or removed.",
2111
+ todoTableOnly: false,
2112
+ condition: (tags) => SHARED_KEYS.some((key) => tags[key] === "shared")
2113
+ };
2114
+ var unusualWidth2 = {
2115
+ id: "unusual_width",
2116
+ desc: "Width that we cannot read or that is unusually high. Fix `width`, or confirm it with `check_date=*` or `check_date:width=*`.",
2117
+ todoTableOnly: true,
2118
+ // One todo per way: skip it when the self row in `bikelanes` has it already. A self row can read
2119
+ // another value (`cycleway:width`, `width:lanes`), so a self row alone is not enough.
2120
+ condition: (tags, result) => !result.selfBikelaneHasUnusualWidth && isUnusualWidth(tags, result)
2121
+ };
2122
+ var ROAD_TODOS = [deprecatedCyclewayShared, unusualWidth2];
2123
+ function deriveRoadTodos(tags, result = {}) {
2124
+ const resolved = {
2125
+ ...result,
2126
+ width: result.width !== void 0 ? result.width : parseWidth(tags.width) ?? null
2127
+ };
2128
+ return ROAD_TODOS.filter((todo) => todo.condition(tags, resolved)).map((todo) => todo.id);
1473
2129
  }
1474
2130
 
1475
2131
  // src/categories/analyze-category-gaps.ts
@@ -1536,6 +2192,41 @@ function analyzeCategoryGaps(wayTags, results) {
1536
2192
  }
1537
2193
 
1538
2194
  // src/categories/plan-tags-for-category.ts
2195
+ var TAG_REASON_CODES = [
2196
+ /** `{category}`: a tag the category needs */
2197
+ "required_for_category",
2198
+ /** `{category}`: a tag that tells the refined category apart */
2199
+ "discriminator_for_category",
2200
+ "fixed_by_mapping_target",
2201
+ "bicycle_road",
2202
+ "bicycle_road_sign",
2203
+ "vehicle_destination",
2204
+ "bicycle_road_sign_vehicle_destination",
2205
+ "unsigned_cycleway",
2206
+ "unsigned_cycleway_no_sign",
2207
+ "footway_bicycles_allowed",
2208
+ "bicycle_allowed_on_footway",
2209
+ "footway_sign_bicycles_allowed",
2210
+ "on_highway_cycle_lane",
2211
+ "bus_lane_with_bicycles",
2212
+ "cycle_lane_shared_with_buses",
2213
+ "protected_lane_separation",
2214
+ "protected_lane_parking",
2215
+ "protected_lane_sidepath",
2216
+ "cycleway_crossing",
2217
+ /** `{from}`: `cycleway:both` (or `cycleway`) split into `cycleway:left` and `cycleway:right` */
2218
+ "split_both_sides",
2219
+ /** `{key}`: the `cycleway:<side>` (or `sidewalk:<side>`) value the category needs on that side */
2220
+ "side_presence",
2221
+ /** `{lifecycle}`: the lifecycle a mapping target asks for (`temporary=yes`, `construction:*`) */
2222
+ "lifecycle",
2223
+ /** conflict, `{lifecycle}` `{result}`: the side keeps another lifecycle (an existing one wins) */
2224
+ "lifecycle_not_reached",
2225
+ /** conflict, `{target}` `{result}`: the suggested edits do not reach the target */
2226
+ "plan_not_enough",
2227
+ /** conflict, `{target}` `{result}`: nothing could be derived */
2228
+ "plan_no_edits"
2229
+ ];
1539
2230
  function isPreciseTargetCategoryId(id) {
1540
2231
  const def = CATEGORY_DEFINITIONS.find((c) => c.id === id);
1541
2232
  return def != null && def.infrastructureExists && !isIncompleteCategoryId(id);
@@ -1555,109 +2246,344 @@ function resolveRefinedIdFromSpec(spec, idSuffix) {
1555
2246
  const base = spec.id.replace(/_advisoryOrExclusive$/, "");
1556
2247
  return `${base}${idSuffix}`;
1557
2248
  }
1558
- function findTransformedTags2(wayTags, side) {
2249
+ function findTransformedTags2(wayTags, side, prefix) {
1559
2250
  const tags = { ...wayTags };
1560
2251
  prepareTags(tags);
1561
- const transformed = getTransformedObjects(tags, BIKELANE_TRANSFORMATIONS);
1562
- return transformed.find((t) => (t._side ?? "self") === side);
2252
+ const ofSide = getTransformedObjects(tags, BIKELANE_TRANSFORMATIONS).filter(
2253
+ (t) => (t._side ?? "self") === side
2254
+ );
2255
+ return ofSide.find((t) => t._prefix === prefix) ?? ofSide[0];
2256
+ }
2257
+ function categorySidePrefix(categoryId) {
2258
+ return SIDEWALK_CATEGORY.test(categoryId) ? "sidewalk" : "cycleway";
2259
+ }
2260
+ function sidePrefixFor(targetCategoryId, side) {
2261
+ return side === "self" ? void 0 : categorySidePrefix(targetCategoryId);
2262
+ }
2263
+ function lifecycleOfSide(wayTags, side, prefix) {
2264
+ const road = { ...wayTags };
2265
+ prepareTags(road);
2266
+ return findTransformedTags2(wayTags, side, prefix)?.lifecycle ?? road.lifecycle;
1563
2267
  }
1564
- function categorizeSide(wayTags, side) {
1565
- const transformed = findTransformedTags2(wayTags, side);
2268
+ function categorizeSide(wayTags, side, prefix) {
2269
+ const transformed = findTransformedTags2(wayTags, side, prefix);
1566
2270
  if (!transformed) return null;
1567
2271
  const category = categorizeBikelane(transformed);
1568
2272
  return category?.id ?? null;
1569
2273
  }
1570
2274
  function writeKeyForSide(transformedKey, side, prefix) {
1571
- if (side === "self" || prefix == null) return transformedKey;
2275
+ if (side === "self") return transformedKey;
2276
+ prefix ??= "cycleway";
1572
2277
  if (prefix === "cycleway" || prefix === "sidewalk") {
2278
+ if (transformedKey === prefix) return `${prefix}:${side}`;
1573
2279
  return `${prefix}:${side}:${transformedKey}`;
1574
2280
  }
1575
2281
  return transformedKey;
1576
2282
  }
1577
- function tagValue2(tags, key) {
1578
- return tags[key];
1579
- }
1580
- function positiveMatchScore(tags, predicate) {
1581
- switch (predicate.op) {
1582
- case "eq":
1583
- return tagValue2(tags, predicate.key) === predicate.value ? 1 : 0;
1584
- case "in": {
1585
- const v = tagValue2(tags, predicate.key);
1586
- return v != null && predicate.values.includes(v) ? 1 : 0;
2283
+ var SIDE_PRESENCE = {
2284
+ cyclewayOnHighway_advisory: "lane",
2285
+ cyclewayOnHighway_exclusive: "lane",
2286
+ cyclewayOnHighway_advisoryOrExclusive: "lane",
2287
+ cyclewayOnHighwayBetweenLanes: "lane",
2288
+ cyclewayOnHighwayProtected: ["track", "lane"],
2289
+ cycleway_adjoining: "track",
2290
+ cycleway_isolated: "track",
2291
+ cycleway_adjoiningOrIsolated: "track",
2292
+ footAndCyclewayShared_adjoining: "track",
2293
+ footAndCyclewayShared_adjoiningOrIsolated: "track",
2294
+ footAndCyclewaySegregated_adjoining: "track",
2295
+ footAndCyclewaySegregated_adjoiningOrIsolated: "track",
2296
+ sharedMotorVehicleLane: "shared_lane",
2297
+ sharedBusLaneBusWithBike: "share_busway",
2298
+ sharedBusLaneBikeWithBus: "lane"
2299
+ };
2300
+ var SIDEWALK_CATEGORY = /^footwayBicycleYes_/;
2301
+ function setUpRoadSide(wayTags, side, targetCategoryId) {
2302
+ const tags = { ...wayTags };
2303
+ const add = [];
2304
+ const change = [];
2305
+ const remove = [];
2306
+ const bothKey = SIDEWALK_CATEGORY.test(targetCategoryId) ? void 0 : ["cycleway:both", "cycleway"].find((key) => tags[key] !== void 0);
2307
+ if (bothKey) {
2308
+ const moved = Object.keys(tags).filter(
2309
+ (key) => key === bothKey || key.startsWith(`${bothKey}:`) && !/^(left|right|both)(:|$)/.test(key.slice(bothKey.length + 1))
2310
+ );
2311
+ for (const from of moved) {
2312
+ const value = tags[from];
2313
+ const suffix = from.slice(bothKey.length);
2314
+ delete tags[from];
2315
+ remove.push(from);
2316
+ for (const each of ["left", "right"]) {
2317
+ const key = `cycleway:${each}${suffix}`;
2318
+ if (tags[key] !== void 0) continue;
2319
+ tags[key] = value;
2320
+ add.push({
2321
+ key,
2322
+ value,
2323
+ reason: `Split ${from} into the two sides`,
2324
+ reasonCode: "split_both_sides",
2325
+ reasonParams: { from }
2326
+ });
2327
+ }
1587
2328
  }
1588
- case "and":
1589
- return predicate.predicates.reduce((sum, p) => sum + positiveMatchScore(tags, p), 0);
1590
- case "or":
1591
- return Math.max(0, ...predicate.predicates.map((p) => positiveMatchScore(tags, p)));
1592
- default:
1593
- return 0;
1594
2329
  }
2330
+ const setSide = (key, value, why) => {
2331
+ const reason = { reason: why, reasonCode: "side_presence", reasonParams: { key } };
2332
+ const planned = add.find((entry) => entry.key === key);
2333
+ if (planned) Object.assign(planned, { value }, reason);
2334
+ else if (tags[key] === void 0) add.push({ key, value, ...reason });
2335
+ else change.push({ key, from: tags[key], to: value, ...reason });
2336
+ tags[key] = value;
2337
+ };
2338
+ const presence = [SIDE_PRESENCE[targetCategoryId] ?? []].flat();
2339
+ const presenceKey = `cycleway:${side}`;
2340
+ const current = tags[presenceKey];
2341
+ if (presence[0] && (current === void 0 || !presence.includes(current))) {
2342
+ setSide(presenceKey, presence[0], `The category needs ${presenceKey}=${presence[0]}`);
2343
+ }
2344
+ if (SIDEWALK_CATEGORY.test(targetCategoryId)) {
2345
+ const key = `sidewalk:${side}`;
2346
+ const present = [key, "sidewalk:both", "sidewalk"].some(
2347
+ (k) => tags[k] !== void 0 && tags[k] !== "no" && tags[k] !== "separate"
2348
+ );
2349
+ if (!present) setSide(key, "yes", `The category needs a sidewalk (${key}=yes)`);
2350
+ }
2351
+ return { tags, add, change, remove };
2352
+ }
2353
+ function isNoSign(value) {
2354
+ return value === "none" || value === "no";
2355
+ }
2356
+ var eqAtom = (key, value, reason, reasonCode) => ({
2357
+ key,
2358
+ accepts: (v) => v === value,
2359
+ value,
2360
+ reason,
2361
+ reasonCode
2362
+ });
2363
+ var pblSidepath = {
2364
+ key: "is_sidepath",
2365
+ accepts: (v) => v === "yes",
2366
+ holdsOn: categoryIsSidepath,
2367
+ value: "yes",
2368
+ reason: "Protected cycle lane: runs along a road",
2369
+ reasonCode: "protected_lane_sidepath"
2370
+ };
2371
+ var footwayOrPath = {
2372
+ key: "highway",
2373
+ accepts: (v) => v === "footway" || v === "path",
2374
+ value: "footway",
2375
+ reason: "Footway with bicycles allowed",
2376
+ reasonCode: "footway_bicycles_allowed"
2377
+ };
2378
+ var MACRO_PLAN_ALTERNATIVES = {
2379
+ bicycle_road_base: [
2380
+ [eqAtom("bicycle_road", "yes", "Fahrradstra\xDFe / bicycle road", "bicycle_road")],
2381
+ [
2382
+ {
2383
+ key: "traffic_sign",
2384
+ accepts: (v) => hasPrefix(v, "DE:244"),
2385
+ value: "DE:244.1",
2386
+ reason: "Fahrradstra\xDFe sign (DE:244.1)",
2387
+ reasonCode: "bicycle_road_sign"
2388
+ }
2389
+ ]
2390
+ ],
2391
+ bicycle_road_vehicle_destination: [
2392
+ [
2393
+ eqAtom("bicycle_road", "yes", "Fahrradstra\xDFe / bicycle road", "bicycle_road"),
2394
+ eqAtom(
2395
+ "vehicle",
2396
+ "destination",
2397
+ "Motor vehicles only for destination traffic (Anlieger frei)",
2398
+ "vehicle_destination"
2399
+ )
2400
+ ],
2401
+ [
2402
+ {
2403
+ key: "traffic_sign",
2404
+ accepts: (v) => hasPrefix(v, "DE:244") && containsSubstring(v, "1020-30"),
2405
+ value: "DE:244.1,1020-30",
2406
+ reason: "Fahrradstra\xDFe sign with Anlieger frei (DE:244.1,1020-30)",
2407
+ reasonCode: "bicycle_road_sign_vehicle_destination"
2408
+ }
2409
+ ]
2410
+ ],
2411
+ unsigned_cycleway: [
2412
+ [
2413
+ eqAtom("highway", "cycleway", "Unsigned cycleway", "unsigned_cycleway"),
2414
+ {
2415
+ key: "traffic_sign",
2416
+ accepts: isNoSign,
2417
+ value: "none",
2418
+ reason: "Unsigned cycleway (traffic_sign=none)",
2419
+ reasonCode: "unsigned_cycleway_no_sign"
2420
+ }
2421
+ ]
2422
+ ],
2423
+ footway_bicycle_yes: [
2424
+ [
2425
+ footwayOrPath,
2426
+ eqAtom("bicycle", "yes", "Bicycle allowed on footway", "bicycle_allowed_on_footway")
2427
+ ],
2428
+ [
2429
+ footwayOrPath,
2430
+ {
2431
+ key: "traffic_sign",
2432
+ accepts: (v) => containsSubstring(v, "1022-10"),
2433
+ value: "DE:239,1022-10",
2434
+ reason: "Footway sign with bicycles allowed (DE:239,1022-10)",
2435
+ reasonCode: "footway_sign_bicycles_allowed"
2436
+ }
2437
+ ]
2438
+ ],
2439
+ cycleway_on_highway_advisory_or_exclusive_base: [
2440
+ [
2441
+ eqAtom("highway", "cycleway", "On-highway cycle lane", "on_highway_cycle_lane"),
2442
+ {
2443
+ key: "cycleway",
2444
+ accepts: (v) => v === "lane" || v === "opposite_lane",
2445
+ value: "lane",
2446
+ reason: "On-highway cycle lane",
2447
+ reasonCode: "on_highway_cycle_lane"
2448
+ }
2449
+ ]
2450
+ ],
2451
+ shared_bus_lane_bus_with_bike: [
2452
+ [
2453
+ eqAtom("highway", "cycleway", "Bus lane with bicycles allowed", "bus_lane_with_bicycles"),
2454
+ eqAtom(
2455
+ "cycleway",
2456
+ "share_busway",
2457
+ "Bus lane with bicycles allowed",
2458
+ "bus_lane_with_bicycles"
2459
+ )
2460
+ ]
2461
+ ],
2462
+ shared_bus_lane_bike_with_bus: [
2463
+ [
2464
+ eqAtom("highway", "cycleway", "Cycle lane shared with buses", "cycle_lane_shared_with_buses"),
2465
+ eqAtom(
2466
+ "lane",
2467
+ "share_busway",
2468
+ "Cycle lane shared with buses",
2469
+ "cycle_lane_shared_with_buses"
2470
+ )
2471
+ ]
2472
+ ],
2473
+ cycleway_on_highway_protected: [
2474
+ [
2475
+ pblSidepath,
2476
+ {
2477
+ key: "separation:left",
2478
+ accepts: (v) => v != null && PROTECTIVE_SEPARATION.includes(v),
2479
+ value: PROTECTIVE_SEPARATION[0],
2480
+ choices: PROTECTIVE_SEPARATION,
2481
+ reason: "Protected cycle lane: physical separation towards the road",
2482
+ reasonCode: "protected_lane_separation"
2483
+ }
2484
+ ],
2485
+ [
2486
+ pblSidepath,
2487
+ eqAtom(
2488
+ "traffic_mode:left",
2489
+ "parking",
2490
+ "Protected cycle lane: parking towards the road",
2491
+ "protected_lane_parking"
2492
+ )
2493
+ ]
2494
+ ],
2495
+ crossing: [
2496
+ [
2497
+ eqAtom("highway", "cycleway", "Cycleway crossing", "cycleway_crossing"),
2498
+ eqAtom("cycleway", "crossing", "Cycleway crossing", "cycleway_crossing")
2499
+ ]
2500
+ ]
2501
+ };
2502
+ function valueForSubstring(key, substring) {
2503
+ if (key === "traffic_sign" && /^\d/.test(substring)) return `DE:${substring}`;
2504
+ return substring;
1595
2505
  }
1596
- function countEqInLeaves(predicate) {
2506
+ function alternativesOf(predicate, why) {
2507
+ const { reason, reasonCode, reasonParams } = why;
1597
2508
  switch (predicate.op) {
1598
2509
  case "eq":
1599
- case "in":
1600
- return 1;
1601
- case "and":
1602
- return predicate.predicates.reduce((sum, p) => sum + countEqInLeaves(p), 0);
1603
- case "or":
1604
- return Math.max(0, ...predicate.predicates.map((p) => countEqInLeaves(p)));
1605
- default:
1606
- return 0;
1607
- }
1608
- }
1609
- function pickOrBranch(tags, predicates) {
1610
- let best;
1611
- let bestScore = -1;
1612
- let bestLeaves = -1;
1613
- for (const child of predicates) {
1614
- const score = positiveMatchScore(tags, child);
1615
- const leaves = countEqInLeaves(child);
1616
- if (score > bestScore || score === bestScore && leaves > bestLeaves) {
1617
- bestScore = score;
1618
- bestLeaves = leaves;
1619
- best = child;
2510
+ return [[{ ...eqAtom(predicate.key, predicate.value, reason, reasonCode), reasonParams }]];
2511
+ case "in": {
2512
+ const values = predicate.values;
2513
+ return [
2514
+ [
2515
+ {
2516
+ key: predicate.key,
2517
+ accepts: (v) => v != null && values.includes(v),
2518
+ value: values[0],
2519
+ reason,
2520
+ reasonCode,
2521
+ reasonParams
2522
+ }
2523
+ ]
2524
+ ];
1620
2525
  }
1621
- }
1622
- return best;
1623
- }
1624
- function collectFromPredicate(predicate, tags, reason, out) {
1625
- switch (predicate.op) {
1626
- case "eq":
1627
- out.push({ key: predicate.key, values: [predicate.value], reason });
1628
- return;
1629
- case "in":
1630
- out.push({ key: predicate.key, values: [...predicate.values], reason });
1631
- return;
1632
- case "and":
2526
+ case "includes": {
2527
+ const { key, substring } = predicate;
2528
+ return [
2529
+ [
2530
+ {
2531
+ key,
2532
+ accepts: (v) => containsSubstring(v, substring),
2533
+ value: valueForSubstring(key, substring),
2534
+ reason,
2535
+ reasonCode,
2536
+ reasonParams
2537
+ }
2538
+ ]
2539
+ ];
2540
+ }
2541
+ case "hasPrefix": {
2542
+ const { key, prefix } = predicate;
2543
+ return [
2544
+ [
2545
+ {
2546
+ key,
2547
+ accepts: (v) => hasPrefix(v, prefix),
2548
+ value: prefix,
2549
+ reason,
2550
+ reasonCode,
2551
+ reasonParams
2552
+ }
2553
+ ]
2554
+ ];
2555
+ }
2556
+ case "exists":
2557
+ return [[{ key: predicate.key, accepts: (v) => v != null, reason, reasonCode, reasonParams }]];
2558
+ case "and": {
2559
+ let result = [[]];
1633
2560
  for (const child of predicate.predicates) {
1634
- collectFromPredicate(child, tags, reason, out);
2561
+ const childAlternatives = alternativesOf(child, why);
2562
+ const next = [];
2563
+ for (const left of result) {
2564
+ for (const right of childAlternatives) next.push([...left, ...right]);
2565
+ }
2566
+ result = next;
1635
2567
  }
1636
- return;
1637
- case "or": {
1638
- const best = pickOrBranch(tags, predicate.predicates);
1639
- if (best) collectFromPredicate(best, tags, reason, out);
1640
- return;
2568
+ return result;
1641
2569
  }
2570
+ case "or":
2571
+ return predicate.predicates.flatMap((child) => alternativesOf(child, why));
1642
2572
  case "macro":
2573
+ return MACRO_PLAN_ALTERNATIVES[predicate.name] ?? [[]];
1643
2574
  case "literal":
1644
- case "exists":
1645
- case "notExists":
2575
+ return predicate.value ? [[]] : [];
1646
2576
  case "neq":
1647
2577
  case "notIn":
1648
- case "includes":
1649
- case "hasPrefix":
2578
+ case "notExists":
1650
2579
  case "hasSuffix":
1651
2580
  case "hasTagWithPrefix":
1652
2581
  case "not":
1653
- return;
2582
+ return [[]];
1654
2583
  default:
1655
- return;
2584
+ return [[]];
1656
2585
  }
1657
2586
  }
1658
- function discriminatorBaseId(targetCategoryId) {
1659
- return targetCategoryId.replace(/_adjoining$/, "").replace(/_isolated$/, "").replace(/_advisory$/, "").replace(/_exclusive$/, "");
1660
- }
1661
2587
  function findParentSpecAndRefining(targetCategoryId) {
1662
2588
  for (const parent of CATEGORY_SPECS) {
1663
2589
  if (parent.id === targetCategoryId) return { parent };
@@ -1668,66 +2594,85 @@ function findParentSpecAndRefining(targetCategoryId) {
1668
2594
  }
1669
2595
  return void 0;
1670
2596
  }
1671
- function discriminatorsForTarget(parent, targetCategoryId) {
1672
- if (!parent.gapDiscriminators?.length) return [];
1673
- const baseId = discriminatorBaseId(targetCategoryId);
1674
- return parent.gapDiscriminators.filter((d) => {
1675
- const unlocked = resolveUnlockCategory2(baseId, d.unlocksCategory);
1676
- return unlocked === targetCategoryId;
1677
- });
1678
- }
1679
- function requirementsFromSpec(targetCategoryId, tags) {
2597
+ function targetAlternatives(targetCategoryId) {
1680
2598
  const resolved = findParentSpecAndRefining(targetCategoryId);
1681
2599
  if (!resolved) return [];
1682
2600
  const { parent, refining } = resolved;
1683
- const requirements = [];
1684
- if (parent.match) {
1685
- collectFromPredicate(parent.match, tags, `Required for ${targetCategoryId}`, requirements);
1686
- }
1687
- if (refining) {
1688
- collectFromPredicate(refining.match, tags, `Discriminator for ${targetCategoryId}`, requirements);
1689
- }
1690
- for (const disc of discriminatorsForTarget(parent, targetCategoryId)) {
1691
- for (const value of disc.values) {
1692
- requirements.push({
1693
- key: disc.key,
1694
- values: [value],
1695
- reason: disc.reason
1696
- });
1697
- }
2601
+ const base = parent.match ? alternativesOf(parent.match, {
2602
+ reason: `Required for ${targetCategoryId}`,
2603
+ reasonCode: "required_for_category",
2604
+ reasonParams: { category: targetCategoryId }
2605
+ }) : [[]];
2606
+ if (!refining) return base;
2607
+ const refined = alternativesOf(refining.match, {
2608
+ reason: `Discriminator for ${targetCategoryId}`,
2609
+ reasonCode: "discriminator_for_category",
2610
+ reasonParams: { category: targetCategoryId }
2611
+ });
2612
+ return base.flatMap((left) => refined.map((right) => [...left, ...right]));
2613
+ }
2614
+ function categorySignOptions(categoryId) {
2615
+ const signs = /* @__PURE__ */ new Set();
2616
+ let unsignedPossible = false;
2617
+ for (const alternative of targetAlternatives(categoryId)) {
2618
+ const signAtoms = alternative.filter(
2619
+ (atom) => atom.key === "traffic_sign" && atom.value != null && !isNoSign(atom.value)
2620
+ );
2621
+ for (const atom of signAtoms) signs.add(atom.value);
2622
+ if (signAtoms.length === 0) unsignedPossible = true;
1698
2623
  }
1699
- const needsClarificationSpec = CATEGORY_SPECS.find((s) => s.id === "needsClarification");
1700
- const baseForTarget = discriminatorBaseId(targetCategoryId);
1701
- if (needsClarificationSpec?.gapDiscriminators) {
1702
- for (const disc of needsClarificationSpec.gapDiscriminators) {
1703
- const unlocked = resolveUnlockCategory2("", disc.unlocksCategory);
1704
- if (unlocked !== baseForTarget && unlocked !== targetCategoryId) continue;
1705
- for (const value of disc.values) {
1706
- requirements.push({
1707
- key: disc.key,
1708
- values: [value],
1709
- reason: disc.reason
1710
- });
1711
- }
1712
- }
2624
+ return { signs: [...signs], unsignedPossible };
2625
+ }
2626
+ function editCost(key, from, to, side) {
2627
+ if (key === "highway") return 10;
2628
+ if (key === "traffic_sign") {
2629
+ if (from == null) return isNoSign(to) ? 1 : 4;
2630
+ return 5;
1713
2631
  }
1714
- return requirements;
2632
+ if (from != null) return 3;
2633
+ if (key === "cycleway" && side === "self") return 3;
2634
+ return 1;
1715
2635
  }
1716
- function dedupeRequirements(requirements) {
1717
- const byKey = /* @__PURE__ */ new Map();
1718
- for (const req of requirements) {
1719
- const existing = byKey.get(req.key);
1720
- if (!existing) {
1721
- byKey.set(req.key, { ...req, values: [...req.values] });
1722
- continue;
1723
- }
1724
- const values = /* @__PURE__ */ new Set([...existing.values, ...req.values]);
1725
- byKey.set(req.key, { ...existing, values: [...values], reason: existing.reason || req.reason });
2636
+ function candidateFor(alternative, base, fixedKeys, side) {
2637
+ const edits = /* @__PURE__ */ new Map();
2638
+ const ordered = [...alternative].sort(
2639
+ (a, b) => Number(a.value === void 0) - Number(b.value === void 0)
2640
+ );
2641
+ let cost = 0;
2642
+ for (const atom of ordered) {
2643
+ const planned = edits.get(atom.key)?.value;
2644
+ const current = planned ?? base[atom.key];
2645
+ if (atom.accepts(current)) continue;
2646
+ if (planned === void 0 && atom.holdsOn?.(base)) continue;
2647
+ if (planned !== void 0) return void 0;
2648
+ if (atom.value === void 0) return void 0;
2649
+ if (atom.key.startsWith("_")) return void 0;
2650
+ if (atom.key === "highway" && side !== "self") return void 0;
2651
+ if (fixedKeys.has(atom.key)) return void 0;
2652
+ if (atom.key === "traffic_sign" && isNoSign(base.traffic_sign)) return void 0;
2653
+ edits.set(atom.key, {
2654
+ value: atom.value,
2655
+ reason: atom.reason,
2656
+ reasonCode: atom.reasonCode,
2657
+ reasonParams: atom.reasonParams,
2658
+ choices: atom.choices
2659
+ });
2660
+ cost += editCost(atom.key, base[atom.key], atom.value, side);
1726
2661
  }
1727
- return [...byKey.values()];
2662
+ return { edits, cost };
2663
+ }
2664
+ function reasonOf(why) {
2665
+ const { reason, reasonCode, reasonParams, choices } = why;
2666
+ return {
2667
+ reason,
2668
+ reasonCode,
2669
+ ...reasonParams ? { reasonParams } : {},
2670
+ ...choices ? { choices } : {}
2671
+ };
1728
2672
  }
1729
- function applyPlanToWayTags(wayTags, add, change) {
2673
+ function applyPlanToWayTags(wayTags, add, change, remove = []) {
1730
2674
  const next = { ...wayTags };
2675
+ for (const key of remove) delete next[key];
1731
2676
  for (const entry of change) {
1732
2677
  next[entry.key] = entry.to;
1733
2678
  }
@@ -1736,17 +2681,6 @@ function applyPlanToWayTags(wayTags, add, change) {
1736
2681
  }
1737
2682
  return next;
1738
2683
  }
1739
- function trafficSignSatisfied(tags, value) {
1740
- return tags.traffic_sign?.includes(value) === true;
1741
- }
1742
- function pickPreferredValue(req, tags) {
1743
- if (req.key === "traffic_sign") {
1744
- return req.values[0];
1745
- }
1746
- const current = tagValue2(tags, req.key);
1747
- if (current != null && req.values.includes(current)) return current;
1748
- return req.values[0];
1749
- }
1750
2684
  function listTargetCategories(options) {
1751
2685
  const all = CATEGORY_DEFINITIONS.map((c) => c.id).filter(isPreciseTargetCategoryId);
1752
2686
  const fromCategory = options?.fromCategory;
@@ -1777,86 +2711,210 @@ var UnknownTargetCategoryError = class extends Error {
1777
2711
  }
1778
2712
  targetCategoryId;
1779
2713
  };
2714
+ var FIXED_REASON = {
2715
+ reason: "Fixed tag of the mapping target",
2716
+ reasonCode: "fixed_by_mapping_target"
2717
+ };
1780
2718
  function planTagsForCategory(wayTags, targetCategoryId, options) {
1781
2719
  const spec = specByCategoryId(targetCategoryId);
1782
2720
  if (!spec) {
1783
2721
  throw new UnknownTargetCategoryError(targetCategoryId);
1784
2722
  }
1785
2723
  const side = options?.side ?? "self";
1786
- const transformed = findTransformedTags2(wayTags, side);
1787
- const prefix = transformed?._prefix ?? null;
1788
- const currentCategoryId = categorizeSide(wayTags, side);
1789
- const tags = transformed ?? wayTags;
1790
- if (currentCategoryId === targetCategoryId) {
2724
+ const fixed = options?.fixed ?? {};
2725
+ const sidePrefix = sidePrefixFor(targetCategoryId, side);
2726
+ const currentCategoryId = categorizeSide(wayTags, side, sidePrefix);
2727
+ const noSetup = { tags: wayTags, add: [], change: [], remove: [] };
2728
+ const setup = side === "self" ? noSetup : setUpRoadSide(wayTags, side, targetCategoryId);
2729
+ const working = setup.tags;
2730
+ const transformed = findTransformedTags2(working, side, sidePrefix);
2731
+ const prefix = transformed?._prefix ?? sidePrefix ?? null;
2732
+ const tags = transformed ?? working;
2733
+ const plan = (add2, change2, key, value, why) => {
2734
+ const writeKey = writeKeyForSide(key, side, prefix);
2735
+ const planned = add2.findIndex((entry) => entry.key === writeKey);
2736
+ if (planned >= 0) {
2737
+ add2[planned] = { key: writeKey, value, ...why };
2738
+ return;
2739
+ }
2740
+ const plannedChange = change2.findIndex((entry) => entry.key === writeKey);
2741
+ if (plannedChange >= 0) {
2742
+ const from = change2[plannedChange].from;
2743
+ change2.splice(plannedChange, 1);
2744
+ if (from !== value) change2.push({ key: writeKey, from, to: value, ...why });
2745
+ return;
2746
+ }
2747
+ const current = working[writeKey] ?? tags[key];
2748
+ if (current === value) return;
2749
+ if (current == null) add2.push({ key: writeKey, value, ...why });
2750
+ else change2.push({ key: writeKey, from: current, to: value, ...why });
2751
+ };
2752
+ const fixedAdd = [];
2753
+ const fixedChange = [];
2754
+ for (const [key, value] of Object.entries(fixed)) {
2755
+ plan(fixedAdd, fixedChange, key, value, FIXED_REASON);
2756
+ }
2757
+ const lifecycle = options?.lifecycle;
2758
+ const lifecycleHolds = (next) => lifecycle === void 0 || lifecycleOfSide(next, side, sidePrefix) === lifecycle;
2759
+ const lifecycleWhy = {
2760
+ reason: `The mapping target is ${lifecycle}`,
2761
+ reasonCode: "lifecycle",
2762
+ reasonParams: { lifecycle: lifecycle ?? "" }
2763
+ };
2764
+ const withLifecycle = (add2, change2, remove2) => {
2765
+ if (lifecycle === void 0) return;
2766
+ const next = applyPlanToWayTags(wayTags, add2, change2, remove2);
2767
+ if (lifecycleHolds(next)) return;
2768
+ if (lifecycle === "temporary") {
2769
+ plan(add2, change2, "temporary", "yes", lifecycleWhy);
2770
+ return;
2771
+ }
2772
+ if (side === "self") {
2773
+ const highway = next.highway;
2774
+ if (highway === void 0 || highway === "construction") return;
2775
+ plan(add2, change2, "highway", "construction", lifecycleWhy);
2776
+ plan(add2, change2, "construction", highway, lifecycleWhy);
2777
+ return;
2778
+ }
2779
+ const presenceKey = `${sidePrefix ?? "cycleway"}:${side}`;
2780
+ const value = next[presenceKey] ?? "yes";
2781
+ const plannedAdd = add2.findIndex((entry) => entry.key === presenceKey);
2782
+ if (plannedAdd >= 0) add2.splice(plannedAdd, 1);
2783
+ const plannedChange = change2.findIndex((entry) => entry.key === presenceKey);
2784
+ if (plannedChange >= 0) change2.splice(plannedChange, 1);
2785
+ if (wayTags[presenceKey] !== void 0 && !remove2.includes(presenceKey))
2786
+ remove2.push(presenceKey);
2787
+ add2.push({ key: `construction:${presenceKey}`, value, ...lifecycleWhy });
2788
+ };
2789
+ if (currentCategoryId === targetCategoryId && !fixedAdd.length && !fixedChange.length && lifecycleHolds(wayTags)) {
1791
2790
  return {
1792
2791
  targetCategoryId,
1793
2792
  currentCategoryId,
1794
2793
  aligned: true,
1795
2794
  add: [],
1796
2795
  change: [],
2796
+ remove: [],
1797
2797
  conflicts: []
1798
2798
  };
1799
2799
  }
1800
- const requirements = dedupeRequirements(requirementsFromSpec(targetCategoryId, tags));
1801
- const add = [];
1802
- const change = [];
1803
- const conflicts = [];
1804
- for (const req of requirements) {
1805
- const writeKey = writeKeyForSide(req.key, side, prefix);
1806
- const wayValue = wayTags[writeKey] ?? tags[req.key];
1807
- const transformedValue = tags[req.key];
1808
- if (req.key === "traffic_sign") {
1809
- const satisfied = req.values.some((v) => trafficSignSatisfied(tags, v));
1810
- if (satisfied) continue;
1811
- const preferred = pickPreferredValue(req, tags);
1812
- if (wayValue == null && transformedValue == null) {
1813
- add.push({ key: writeKey, value: preferred, reason: req.reason });
1814
- } else if (transformedValue != null && !req.values.some((v) => transformedValue.includes(v))) {
1815
- change.push({
1816
- key: writeKey,
1817
- from: wayValue ?? transformedValue,
1818
- to: preferred,
1819
- reason: req.reason
1820
- });
1821
- }
1822
- continue;
2800
+ const base = { ...tags, ...fixed };
2801
+ const fixedKeys = new Set(Object.keys(fixed));
2802
+ const candidates = [{ edits: /* @__PURE__ */ new Map(), cost: 0 }];
2803
+ for (const alternative of targetAlternatives(targetCategoryId)) {
2804
+ const candidate = candidateFor(alternative, base, fixedKeys, side);
2805
+ if (candidate) candidates.push(candidate);
2806
+ }
2807
+ candidates.sort((a, b) => a.cost - b.cost);
2808
+ const seen = /* @__PURE__ */ new Set();
2809
+ let fallback;
2810
+ for (const candidate of candidates) {
2811
+ const signature = [...candidate.edits.entries()].map(([k, v]) => `${k}=${v.value}`).sort().join(";");
2812
+ if (seen.has(signature)) continue;
2813
+ seen.add(signature);
2814
+ const add2 = [...setup.add, ...fixedAdd];
2815
+ const change2 = [...setup.change, ...fixedChange];
2816
+ const remove2 = [...setup.remove];
2817
+ for (const [key, edit] of candidate.edits) {
2818
+ plan(add2, change2, key, edit.value, reasonOf(edit));
1823
2819
  }
1824
- if (transformedValue != null && !req.values.includes(transformedValue)) {
1825
- change.push({
1826
- key: writeKey,
1827
- from: wayValue ?? transformedValue,
1828
- to: pickPreferredValue(req, tags),
1829
- reason: req.reason
1830
- });
1831
- continue;
2820
+ withLifecycle(add2, change2, remove2);
2821
+ const next = applyPlanToWayTags(wayTags, add2, change2, remove2);
2822
+ const result = categorizeSide(next, side, sidePrefix);
2823
+ if (result === targetCategoryId && lifecycleHolds(next)) {
2824
+ return {
2825
+ targetCategoryId,
2826
+ currentCategoryId,
2827
+ aligned: true,
2828
+ add: add2,
2829
+ change: change2,
2830
+ remove: remove2,
2831
+ conflicts: []
2832
+ };
1832
2833
  }
1833
- if (transformedValue == null && wayValue == null) {
1834
- add.push({
1835
- key: writeKey,
1836
- value: pickPreferredValue(req, tags),
1837
- reason: req.reason
1838
- });
2834
+ if (!fallback || !fallback.add.length && !fallback.change.length) {
2835
+ fallback = { add: add2, change: change2, remove: remove2, result, next };
1839
2836
  }
1840
2837
  }
1841
- const dryRunTags = applyPlanToWayTags(wayTags, add, change);
1842
- const resultCategory = categorizeSide(dryRunTags, side);
1843
- const aligned = resultCategory === targetCategoryId;
1844
- if (!aligned) {
1845
- conflicts.push({
1846
- key: "_category",
1847
- value: resultCategory ?? "null",
1848
- reason: "After suggested tag adds/changes, classification still does not match the target; additional tags (e.g. from macro predicates) may be required."
1849
- });
2838
+ const add = fallback?.add ?? [];
2839
+ const change = fallback?.change ?? [];
2840
+ const remove = fallback?.remove ?? setup.remove;
2841
+ const resultCategory = fallback?.result ?? currentCategoryId;
2842
+ if (resultCategory === targetCategoryId && lifecycle !== void 0) {
2843
+ const result = lifecycleOfSide(fallback?.next ?? wayTags, side, sidePrefix) ?? "none";
2844
+ return {
2845
+ targetCategoryId,
2846
+ currentCategoryId,
2847
+ aligned: false,
2848
+ add,
2849
+ change,
2850
+ remove,
2851
+ conflicts: [
2852
+ {
2853
+ key: "_lifecycle",
2854
+ value: result,
2855
+ reason: `The side keeps lifecycle=${result}; an existing lifecycle wins over ${lifecycle}.`,
2856
+ reasonCode: "lifecycle_not_reached",
2857
+ reasonParams: { lifecycle, result }
2858
+ }
2859
+ ]
2860
+ };
1850
2861
  }
2862
+ const suggested = add.length > 0 || change.length > 0 ? "Suggested tag edits are not enough to reach that classification." : "No automatic tag edits could be derived for this category (often because it matches via a complex macro).";
1851
2863
  return {
1852
2864
  targetCategoryId,
1853
2865
  currentCategoryId,
1854
- aligned,
2866
+ aligned: false,
1855
2867
  add,
1856
2868
  change,
1857
- conflicts
2869
+ remove,
2870
+ conflicts: [
2871
+ {
2872
+ key: "_category",
2873
+ value: resultCategory ?? "null",
2874
+ reason: `${suggested} Target \u201C${targetCategoryId}\u201D would still classify as ${resultCategory ?? "none"}.`,
2875
+ reasonCode: add.length > 0 || change.length > 0 ? "plan_not_enough" : "plan_no_edits",
2876
+ reasonParams: { target: targetCategoryId, result: resultCategory ?? "none" }
2877
+ }
2878
+ ]
1858
2879
  };
1859
2880
  }
2881
+ function planSignature(plan) {
2882
+ return [
2883
+ ...plan.add.map((e) => `+${e.key}=${e.value}`),
2884
+ ...plan.change.map((e) => `~${e.key}=${e.to}`),
2885
+ ...plan.remove.map((key) => `-${key}`)
2886
+ ].sort().join(";");
2887
+ }
2888
+ function planTagVariantsForCategory(wayTags, targetCategoryId, options) {
2889
+ const first = planTagsForCategory(wayTags, targetCategoryId, options);
2890
+ const variants = [{ ...first, variantId: "default" }];
2891
+ if (options?.fixed?.traffic_sign !== void 0) return variants;
2892
+ const { signs, unsignedPossible } = categorySignOptions(targetCategoryId);
2893
+ if (!signs.length) return variants;
2894
+ const seen = /* @__PURE__ */ new Set([planSignature(first)]);
2895
+ const push = (variantId, fixedSign) => {
2896
+ const plan = planTagsForCategory(wayTags, targetCategoryId, {
2897
+ ...options,
2898
+ fixed: { ...options?.fixed, traffic_sign: fixedSign }
2899
+ });
2900
+ const signature = planSignature(plan);
2901
+ if (!plan.aligned || seen.has(signature)) return;
2902
+ seen.add(signature);
2903
+ variants.push({ ...plan, variantId });
2904
+ };
2905
+ const side = options?.side ?? "self";
2906
+ const currentSign = findTransformedTags2(
2907
+ wayTags,
2908
+ side,
2909
+ sidePrefixFor(targetCategoryId, side)
2910
+ )?.traffic_sign;
2911
+ const signHolds = signs.some(
2912
+ (sign) => currentSign != null && containsSubstring(currentSign, sign)
2913
+ );
2914
+ if (!signHolds) push("with_sign", signs[0]);
2915
+ if (unsignedPossible && !isNoSign(currentSign)) push("without_sign", "none");
2916
+ return variants;
2917
+ }
1860
2918
 
1861
2919
  // src/index.ts
1862
2920
  function clean(value) {
@@ -1878,8 +2936,15 @@ function processBikelanes(objectTags) {
1878
2936
  category: category.id
1879
2937
  };
1880
2938
  if (category.infrastructureExists) {
1881
- result.oneway = deriveOneway(t, category);
1882
- result.width = parseLength(t.width) ?? null;
2939
+ const direction = deriveOnewayDirection(t, category);
2940
+ result.oneway = direction.oneway;
2941
+ result._lineReversed = direction.lineReversed;
2942
+ if (t._side === "left" || t._side === "right") {
2943
+ const laneLeftOfLine = t._side === "left" !== direction.lineReversed;
2944
+ result.offset = (laneLeftOfLine ? 1 : -1) * roadWidth(t._parent ?? tags) / 2;
2945
+ }
2946
+ result.lifecycle = t.lifecycle ?? tags.lifecycle ?? null;
2947
+ result.width = parseWidth(t.width) ?? null;
1883
2948
  result.surface_color = clean(surfaceColor(t));
1884
2949
  result.separation_left = clean(separation(t, "left"));
1885
2950
  result.separation_right = clean(separation(t, "right"));
@@ -1892,18 +2957,29 @@ function processBikelanes(objectTags) {
1892
2957
  result.traffic_mode_right = tm.traffic_mode_right ?? null;
1893
2958
  const ts = deriveTrafficSigns(t);
1894
2959
  result.traffic_sign = ts.traffic_sign ?? null;
1895
- const surf = deriveBikelaneSurface(t, category);
2960
+ const surfaceTags = deriveBikelaneSurfaceTags(t, category);
2961
+ const surf = deriveBikelaneSurface(surfaceTags.tags, category);
1896
2962
  result.surface = surf.surface ?? null;
1897
- result.surface_source = surf.surface_source ?? null;
2963
+ result.surface_source = bikelaneSurfaceSource(surfaceTags, surf.surface_source) ?? null;
1898
2964
  result.surface_confidence = surf.surface_confidence ?? null;
1899
- const smooth = deriveBikelaneSmoothness(t, category);
2965
+ const smooth = deriveBikelaneSmoothness(surfaceTags.tags, category);
1900
2966
  result.smoothness = smooth.smoothness ?? null;
1901
2967
  result.smoothness_source = smooth.smoothness_source ?? null;
1902
2968
  result.smoothness_confidence = smooth.smoothness_confidence ?? null;
2969
+ const todo = deriveBikelaneTodos(t, {
2970
+ category: category.id,
2971
+ width: result.width,
2972
+ surface: result.surface,
2973
+ surface_source: result.surface_source,
2974
+ oneway: result.oneway,
2975
+ implicitOneWayConfidence: category.implicitOneWayConfidence
2976
+ });
2977
+ result.todos = todo.todos;
2978
+ if (todo.todoTagFixes) result.todoTagFixes = todo.todoTagFixes;
1903
2979
  }
1904
2980
  results.push(result);
1905
2981
  }
1906
2982
  return results;
1907
2983
  }
1908
2984
 
1909
- export { ALLOWED_HIGHWAYS, BIKELANE_TRANSFORMATIONS, CATEGORY_DEFINITIONS, CATEGORY_SPECS, MAJOR_ROAD_CLASSES, MINOR_ROAD_CLASSES, PATH_CLASSES, SIDEPATH_HIGHWAY_CLASSES, TRUNK_MOTORWAY_CLASSES, UnknownTargetCategoryError, analyzeCategoryGaps, categorizeBikelane, getTransformedObjects, isIncompleteCategoryId, listTargetCategories, planTagsForCategory, prepareTags, processBikelanes, specsWithGapDiscriminators, writeKeyForSide };
2985
+ export { ALLOWED_HIGHWAYS, BIKELANE_TODOS, BIKELANE_TRANSFORMATIONS, CATEGORY_DEFINITIONS, CATEGORY_SPECS, DIRECTIONAL_PARKING_INFERENCE_CATEGORIES, MAJOR_ROAD_CLASSES, MARKING_ALLOWED, MINOR_ROAD_CLASSES, PARKING_ALLOWED, PATH_CLASSES, PROTECTIVE_SEPARATION, ROAD_TODOS, SEPARATION_ALLOWED, SIDEPATH_HIGHWAY_CLASSES, SURFACE_ALLOWED, SURFACE_COLOR_ALLOWED, TAG_REASON_CODES, TRAFFIC_MODE_ALLOWED, TRUNK_MOTORWAY_CLASSES, UnknownTargetCategoryError, analyzeCategoryGaps, categorizeBikelane, categorySidePrefix, categorySignOptions, defaultSideRunsAgainstWay, deriveBikelaneTodos, deriveRoadTodos, getTransformedObjects, isIncompleteCategoryId, isUnusualWidth, listTargetCategories, parseLength, parseWidth, planTagVariantsForCategory, planTagsForCategory, prepareTags, processBikelanes, specsWithGapDiscriminators, writeKeyForSide };