'use strict'; const assert = require('assert/strict'); const { resolveDirectEditConstraints } = require('../src/compile/direct-edit-solver'); const { complexJunctionMetrics } = require('../src/compile/junction-metrics'); const { haversineMeters } = require('../src/geometry/lane-geometry'); const model = { roads: [], endpoints: [], connections: [], diagnostics: [] }; function constraint(overrides = {}) { return { id: 'constraint-1', kind: 'road-edge-offset', anchor: { type: 'road-interval', roadId: 'road:way/1:forward', startStation: 0.3, endStation: 0.7 }, anchorSnapshot: { coordinate: [113.1, 30.2], tangentAzimuth: 45, roadLengthMeters: 120, osmNodeIds: ['1', '2'], }, value: { offsetMeters: 1.5, transition: 'smoothstep' }, enabled: true, status: 'exact', provenance: { operationId: 'operation-1', createdAt: '2026-08-27T00:00:00.000Z' }, ...overrides, }; } function document(constraints) { return { schema: 'native-road-edits/v2', documentVersion: 1, base: {}, constraints, operations: [] }; } // A missing or empty document must resolve to the identity: this is what keeps // the stage insertable ahead of compileGeometry without moving any geometry. for (const empty of [null, undefined, document([])]) { const resolution = resolveDirectEditConstraints(model, empty); assert.equal(resolution.schema, 'road-edit-resolution/v1'); assert.equal(resolution.roadProfiles.size, 0); assert.equal(resolution.junctionPlans.size, 0); assert.deepEqual(resolution.constraintStates, []); assert.deepEqual(resolution.diagnostics, []); assert.equal(resolution.handles.schema, 'road-edit-handles/v1'); assert.deepEqual(resolution.handles.handles, []); assert.deepEqual(resolution.handles.reserves, []); assert.equal(resolution.handles.revisionId, null); assert.equal(resolution.handles.previewSeq, 0); } // Handle manifest context is echoed so a preview response can be matched to the // request that asked for it. const withContext = resolveDirectEditConstraints(model, null, { revisionId: 'rev-0007', previewSeq: 42 }); assert.equal(withContext.handles.revisionId, 'rev-0007'); assert.equal(withContext.handles.previewSeq, 42); // A small ordinary junction exercises the step-two manifest contract without // depending on the full OSM parser. Three approaches produce one reserve each, // all six kinds, and native feature links for the downstream map highlighter. const junctionRoads = ['a', 'b', 'c'].map((id, index) => ({ id: `road:${id}`, segmentId: `segment:${id}`, direction: 'forward', centerline: [ [113 + index * 0.001, 30], [113 + index * 0.001 + (index === 1 ? 0.001 : 0), 30 + (index === 1 ? 0.001 : 0.001)], ], sourceNodeIds: ['junction', `end-${id}`], osmWayIds: [id], widthMeters: 6, laneCount: 2, sidewalkLeft: true, sidewalkRight: true, })); const junctionModel = { roads: junctionRoads, endpoints: junctionRoads.map((road) => ({ id: `endpoint:${road.id}:start`, roadId: road.id, side: 'start', nodeId: 'junction', coordinate: road.centerline[0], })), connections: [], }; const junctionResolution = resolveDirectEditConstraints(junctionModel, document([]), { revisionId: 'rev-junction' }); assert.equal(junctionResolution.handles.reserves.length, 3); assert.ok(junctionResolution.effectiveJunctionPlans.has('node:junction')); assert.equal(junctionResolution.effectiveJunctionPlans.get('node:junction').readOnly, false); assert.equal(new Set(junctionResolution.handles.handles.map((handle) => handle.kind)).size, 9); assert.ok(junctionResolution.handles.handles.every((handle) => handle.position.every(Number.isFinite))); assert.ok(junctionResolution.handles.handles.every((handle) => Number.isFinite(handle.axisAzimuth))); assert.ok(junctionResolution.handles.handles.some((handle) => handle.affects.includes('junction:node/junction'))); // The left handle must sit on the geometry compiler's left. `offsetLine()` shifts a // positive offset counter-clockwise from the direction of travel and sidewalks use // `heading + (side === 'left' ? -90 : 90)`, so for the north-heading road:a that is // west. Drawing it east put it over the right kerb, and dragging the visually-left // handle then moved the right edge. const northEdges = junctionResolution.handles.handles.filter( (handle) => handle.kind === 'road-edge-offset' && handle.anchor.roadId === 'road:a', ); const leftEdge = northEdges.find((handle) => handle.anchor.side === 'left'); const rightEdge = northEdges.find((handle) => handle.anchor.side === 'right'); assert.ok(leftEdge && rightEdge, 'both edge handles must be published'); assert.ok(leftEdge.position[0] < 113, 'left edge handle must sit west of a north-heading centerline'); assert.ok(rightEdge.position[0] > 113, 'right edge handle must sit east of a north-heading centerline'); const northSidewalks = junctionResolution.handles.handles.filter( (handle) => handle.kind === 'road-sidewalk-width' && handle.anchor.roadId === 'road:a', ); assert.ok( northSidewalks.find((handle) => handle.anchor.side === 'left').position[0] < 113, 'the sidewalk handle must follow the same side convention as the edge handle', ); const controlHandles = junctionResolution.handles.handles.filter((handle) => handle.anchor.segmentId === 'segment:a'); const crosswalkHandle = controlHandles.find((handle) => handle.kind === 'junction-crosswalk-inset'); const stopLineHandle = controlHandles.find((handle) => handle.kind === 'junction-stop-line-offset'); assert.ok(crosswalkHandle && stopLineHandle, 'both control-marking handles must be published'); assert.notDeepEqual( crosswalkHandle.position, stopLineHandle.position, 'crosswalk and stop-line handles must not overlap at the shared cutback point', ); assert.notEqual( crosswalkHandle.axisAzimuth, stopLineHandle.axisAzimuth, 'crosswalk inset and stop-line offset use opposite positive directions along the approach', ); assert.equal( (crosswalkHandle.axisAzimuth + 180) % 360, stopLineHandle.axisAzimuth, 'increasing crosswalk inset moves toward the junction while increasing stop-line offset moves away', ); // A selection scopes the manifest to the object being edited. The whole-area // manifest is 844 KB on a 41-road workspace, 89% of it `affects` id lists, while // the map renders about six handles — so every new handle kind multiplies a // payload the client throws away. const unscoped = junctionResolution.handles.handles; const segmentScoped = resolveDirectEditConstraints(junctionModel, document([]), { selection: { type: 'segment', id: 'segment:a' }, }).handles.handles; assert.ok(segmentScoped.length > 0, 'a segment selection must still publish its road handles'); assert.ok(segmentScoped.length < unscoped.length, 'a segment selection must be smaller than the whole manifest'); // The main map owns the segment's cross-section and the control markings at its // ends. Junction *shape* — width, cutback, corner — stays with JunctionTools, so // the two editors never offer the same edit. const SHAPE_KINDS = ['junction-approach-width', 'junction-cutback', 'junction-corner-radius']; assert.ok( segmentScoped.every((handle) => !SHAPE_KINDS.includes(handle.kind)), 'junction shape kinds belong to JunctionTools and must not reach a segment selection', ); assert.ok( segmentScoped.some((handle) => handle.kind === 'junction-crosswalk-inset'), 'control markings are junction-anchored but main-map editable, so they must be included', ); assert.ok( segmentScoped.every((handle) => handle.kind.startsWith('road-') ? handle.anchor.roadId === 'road:a' : handle.kind === 'lane-maneuver' ? handle.anchor.roadId === 'road:a' : handle.anchor.segmentId === 'segment:a', ), 'a segment selection must only carry that segment’s handles', ); // Scoping must not invent or drop handles: it is a filter of the full manifest. assert.deepEqual( segmentScoped.map((handle) => handle.handleId).sort(), unscoped .filter((handle) => handle.kind.startsWith('road-') || handle.kind === 'lane-maneuver' ? handle.anchor.roadId === 'road:a' : handle.anchor.segmentId === 'segment:a', ) .filter((handle) => !SHAPE_KINDS.includes(handle.kind)) .map((handle) => handle.handleId) .sort(), ); const junctionScoped = resolveDirectEditConstraints(junctionModel, document([]), { selection: { type: 'junction', id: 'junction' }, }).handles.handles; assert.ok(junctionScoped.length > 0, 'a junction selection must publish that node’s handles'); assert.ok( junctionScoped.every((handle) => handle.kind.startsWith('junction-') && handle.anchor.nodeId === 'junction'), 'a junction selection must only carry that node’s handles', ); // Omitting the selection keeps the full manifest, which the compiler and the // existing callers rely on. assert.equal(resolveDirectEditConstraints(junctionModel, document([]), {}).handles.handles.length, unscoped.length); const anchored = constraint({ id: 'edge-on-road-a', anchor: { type: 'road-interval', roadId: 'road:a', startStation: 0.2, endStation: 0.8, side: 'left' }, }); const anchoredResolution = resolveDirectEditConstraints(junctionModel, document([anchored])); const anchoredHandle = anchoredResolution.handles.handles.find( (handle) => handle.kind === 'road-edge-offset' && handle.anchor.roadId === 'road:a' && handle.anchor.side === 'left', ); assert.equal(anchoredHandle.constraintId, 'edge-on-road-a'); // The published edge extrema are solver extrema, not the segment's combined // directional width. Submitting either endpoint must be accepted by the same // resolver that published it. for (const side of ['left', 'right']) { const handle = junctionResolution.handles.handles.find( (item) => item.kind === 'road-edge-offset' && item.anchor.roadId === 'road:a' && item.anchor.side === side, ); assert.ok(handle); const endpoint = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: `edge-endpoint-${side}`, anchor: { ...handle.anchor }, value: { offsetMeters: handle.value.min, transition: 'smoothstep' }, }), ]), ); assert.equal(endpoint.constraintStates[0].applied, true, `${side} min must be solver-accepted`); assert.deepEqual(endpoint.diagnostics, []); const maxEndpoint = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: `edge-endpoint-max-${side}`, anchor: { ...handle.anchor }, value: { offsetMeters: handle.value.max, transition: 'smoothstep' }, }), ]), ); assert.equal(maxEndpoint.constraintStates[0].applied, true, `${side} max must be solver-accepted`); assert.deepEqual(maxEndpoint.diagnostics, []); } // A value that was legal on the original road becomes stale when a reimport // narrows that road's feasible range. It must not be replayed into geometry. const savedEdge = constraint({ id: 'saved-edge', anchor: { type: 'road-interval', roadId: 'road:a', startStation: 0.2, endStation: 0.8, side: 'left' }, value: { offsetMeters: 2.5, transition: 'smoothstep' }, }); const widenedModel = { ...junctionModel, roads: junctionModel.roads.map((road) => ({ ...road, widthMeters: 6 })) }; const narrowedModel = { ...junctionModel, roads: junctionModel.roads.map((road) => ({ ...road, widthMeters: 4 })) }; assert.equal(resolveDirectEditConstraints(widenedModel, document([savedEdge])).constraintStates[0].status, 'exact'); const narrowed = resolveDirectEditConstraints(narrowedModel, document([savedEdge]), { replay: true }); assert.deepEqual(narrowed.constraintStates[0], { constraintId: 'saved-edge', kind: 'road-edge-offset', status: 'stale', applied: false, reason: 'range-out-of-bounds', }); assert.equal(narrowed.roadProfiles.size, 0); assert.deepEqual(narrowed.diagnostics, []); // A new preview draft is invalid, not stale: the server must expose a blocking // diagnostic when a client bypasses the manifest and submits an out-of-range value. const previewInvalid = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: 'preview-invalid-edge', anchor: savedEdge.anchor, value: { offsetMeters: 99, transition: 'smoothstep' }, }), ]), ); assert.equal(previewInvalid.constraintStates[0].status, 'exact'); assert.equal(previewInvalid.constraintStates[0].applied, false); assert.ok(previewInvalid.diagnostics.some((item) => item.rule === 'direct-edit-edge-offset-out-of-range')); const bothEdges = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: 'both-edges', anchor: { type: 'road-interval', roadId: 'road:a', startStation: 0.2, endStation: 0.8 }, value: { offsetMeters: 0.5, transition: 'smoothstep' }, }), ]), ); assert.equal(bothEdges.constraintStates[0].applied, true); assert.deepEqual(bothEdges.diagnostics, []); const allKinds = [ anchored, constraint({ id: 'sidewalk-on-road-a', kind: 'road-sidewalk-width', anchor: { type: 'road-interval', roadId: 'road:a', startStation: 0.2, endStation: 0.8, side: 'left' }, value: { widthMeters: 3, transition: 'linear' }, }), constraint({ id: 'divider-on-road-a', kind: 'road-lane-divider', anchor: { type: 'road-interval', roadId: 'road:a', startStation: 0.2, endStation: 0.8 }, value: { boundaryIndex: 1, offsetMeters: 0.1, transition: 'smoothstep' }, }), constraint({ id: 'approach-width', kind: 'junction-approach-width', anchor: { type: 'junction-approach', nodeId: 'junction', segmentId: 'segment:a' }, value: { widthMeters: 7 }, }), constraint({ id: 'approach-cutback', kind: 'junction-cutback', anchor: { type: 'junction-approach', nodeId: 'junction', segmentId: 'segment:a' }, value: { cutbackMeters: 2 }, }), constraint({ id: 'corner-radius', kind: 'junction-corner-radius', anchor: { type: 'junction-corner', nodeId: 'junction', incomingRoadId: 'segment:a', outgoingRoadId: 'segment:b' }, value: { radiusMeters: 4 }, }), ]; const allKindsResolution = resolveDirectEditConstraints(junctionModel, document(allKinds)); assert.deepEqual( allKindsResolution.constraintStates.map((state) => state.applied), [true, true, true, true, true, true], ); assert.equal(allKindsResolution.roadProfiles.get('road:a').sidewalkWidths.left, 3); assert.equal(allKindsResolution.roadProfiles.get('road:a').laneDividerOffsets[1], 0.1); assert.equal( allKindsResolution.handles.handles.find((handle) => handle.kind === 'road-lane-divider').constraintId, 'divider-on-road-a', ); assert.equal(allKindsResolution.junctionPlans.get('junction').approaches['segment:a'].widthMeters, 7); assert.equal(allKindsResolution.junctionPlans.get('junction').approaches['segment:a'].cutbackMeters, 2); assert.equal(allKindsResolution.junctionPlans.get('junction').corners['segment:a->segment:b'], 4); assert.equal(allKindsResolution.effectiveJunctionPlans.get('node:junction').approaches['segment:a'].widthMeters, 7); const independentCorners = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: 'corner-radius-a', kind: 'junction-corner-radius', anchor: { type: 'junction-corner', nodeId: 'junction', incomingRoadId: 'segment:a', outgoingRoadId: 'segment:b' }, value: { radiusMeters: 4 }, }), constraint({ id: 'corner-radius-b', kind: 'junction-corner-radius', anchor: { type: 'junction-corner', nodeId: 'junction', incomingRoadId: 'segment:b', outgoingRoadId: 'segment:c' }, value: { radiusMeters: 10 }, }), ]), ); assert.equal(independentCorners.junctionPlans.get('junction').corners['segment:a->segment:b'], 4); assert.equal(independentCorners.junctionPlans.get('junction').corners['segment:b->segment:c'], 10); const clusterResolution = resolveDirectEditConstraints(junctionModel, document(allKinds), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }], }); const clusterPlan = clusterResolution.effectiveJunctionPlans.get('cluster:cluster-1'); assert.ok(clusterPlan); assert.equal(clusterPlan.readOnly, false); assert.deepEqual(clusterPlan.junctionRef, { type: 'cluster', id: 'cluster-1' }); assert.equal(clusterPlan.approaches.find((item) => item.segmentId === 'segment:a').widthMeters, 7); const clusterHandleResolution = resolveDirectEditConstraints(junctionModel, document([]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }], selection: { type: 'cluster', id: 'cluster-1' }, }); const clusterWidthHandle = clusterHandleResolution.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-width', ); assert.ok(clusterWidthHandle, 'a cluster selection publishes only its external carriageway widths'); const clusterCutbackHandle = clusterHandleResolution.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-cutback', ); assert.ok(clusterCutbackHandle, 'a cluster selection publishes its carriageway cutback handles'); const clusterTransitionHandle = clusterHandleResolution.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-transition-length', ); assert.ok(clusterTransitionHandle, 'a cluster selection publishes its carriageway transition handles'); const clusterTransitionMetrics = complexJunctionMetrics({ id: 'cluster-1' }); assert.ok( clusterTransitionMetrics.approachOuterRadius - clusterCutbackHandle.value.max - clusterTransitionMetrics.approachInnerRadius >= clusterTransitionMetrics.minimumTransitionMeters - 1e-9, 'the cutback limit must retain the minimum transition between source and core sections', ); const cutbackAtLimit = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: 'cluster-carriageway-cutback', kind: 'cluster-carriageway-cutback', anchor: clusterCutbackHandle.anchor, value: { cutbackMeters: clusterCutbackHandle.value.max }, }), ]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); assert.equal(cutbackAtLimit.constraintStates[0].applied, true); const cutbackPastLimit = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: 'cluster-carriageway-cutback-invalid', kind: 'cluster-carriageway-cutback', anchor: clusterCutbackHandle.anchor, value: { cutbackMeters: clusterCutbackHandle.value.max + 0.1 }, }), ]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); assert.equal(cutbackPastLimit.constraintStates[0].applied, false); const widenedCluster = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: 'cluster-carriageway-width', kind: 'cluster-carriageway-width', anchor: clusterWidthHandle.anchor, value: { widthMeters: clusterWidthHandle.value.current + 0.5 }, }), ]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); assert.equal(widenedCluster.constraintStates[0].applied, true); assert.equal( widenedCluster.clusterPlans.get('cluster-1').get(clusterWidthHandle.anchor.carriagewayKey), clusterWidthHandle.value.current + 0.5, ); assert.equal( widenedCluster.effectiveJunctionPlans .get('cluster:cluster-1') .carriageways.find((item) => item.key === clusterWidthHandle.anchor.carriagewayKey).widthMeters, clusterWidthHandle.value.current + 0.5, ); for (const [kind, value, resultKey] of [ ['cluster-carriageway-position', { offsetMeters: 1 }, 'clusterPositions'], ['cluster-carriageway-direction', { offsetDegrees: 5 }, 'clusterDirections'], ['cluster-carriageway-edge-offset', { leftOffsetMeters: 0.4, rightOffsetMeters: -0.2 }, 'clusterEdgeOffsets'], ]) { const result = resolveDirectEditConstraints( junctionModel, document([constraint({ kind, anchor: clusterWidthHandle.anchor, value })]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); assert.equal(result.constraintStates[0].applied, true, kind); assert.deepEqual( result[resultKey].get('cluster-1').get(clusterWidthHandle.anchor.carriagewayKey), kind.endsWith('edge-offset') ? value : Object.values(value)[0], ); assert.equal(result.clusterCutbacks.size, 0); } for (const sides of [ ['left', 'right'], ['right', 'left'], ]) { const result = resolveDirectEditConstraints( junctionModel, document( sides.map((side) => constraint({ id: `edge-${side}`, kind: 'cluster-carriageway-edge-offset', anchor: { ...clusterWidthHandle.anchor, side }, value: side === 'left' ? { leftOffsetMeters: 0.4, rightOffsetMeters: 0 } : { leftOffsetMeters: 0, rightOffsetMeters: 0.7 }, }), ), ), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); assert.ok(result.constraintStates.every((state) => state.applied)); assert.deepEqual(result.clusterEdgeOffsets.get('cluster-1').get(clusterWidthHandle.anchor.carriagewayKey), { leftOffsetMeters: 0.4, rightOffsetMeters: 0.7, }); const edgePositions = {}; for (const side of sides) { const handle = result.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-edge-offset' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey && handle.anchor.side === side, ); assert.equal(handle.constraintId, `edge-${side}`); assert.equal(handle.value.current, side === 'left' ? 0.4 : 0.7); edgePositions[side] = handle.position; assert.equal( handle.axisAzimuth, clusterWidthHandle.axisAzimuth, 'both edge handles publish the rightward normal; the client reverses the left side once', ); } assert.ok( haversineMeters(edgePositions.left, edgePositions.right) > clusterWidthHandle.value.current, 'independent edge handles must be placed on opposite sides of the effective entry section', ); assert.ok( Math.abs( haversineMeters(edgePositions.left, edgePositions.right) - (clusterWidthHandle.value.current + 0.4 + 0.7), ) < 0.02, 'edge handle separation must equal the effective width plus both independent edge offsets', ); } const movedCluster = resolveDirectEditConstraints( junctionModel, document([ constraint({ kind: 'cluster-carriageway-position', anchor: clusterWidthHandle.anchor, value: { offsetMeters: 1 }, }), constraint({ kind: 'cluster-carriageway-direction', anchor: clusterWidthHandle.anchor, value: { offsetDegrees: 5 }, }), ]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); const movedEdge = movedCluster.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-edge-offset' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey && handle.anchor.side === 'right', ); assert.ok(haversineMeters(movedEdge.position, clusterWidthHandle.position) > clusterWidthHandle.value.current / 2); assert.notEqual(movedEdge.axisAzimuth, clusterWidthHandle.axisAzimuth); const movedPosition = movedCluster.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-position' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey, ); const movedWidth = movedCluster.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-width' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey, ); const movedDirection = movedCluster.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-direction' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey, ); assert.deepEqual( movedWidth.position, movedPosition.position, 'width and position controls share the effective inner section', ); assert.deepEqual(movedDirection.interaction.center, movedPosition.position); assert.equal(movedDirection.interaction.kind, 'rotation'); assert.ok( Math.abs( haversineMeters(movedDirection.interaction.center, movedDirection.position) - movedDirection.interaction.radiusMeters, ) < 0.02, 'direction control is a radial handle around the effective inner section', ); const initialEdges = clusterHandleResolution.handles.handles.filter( (handle) => handle.kind === 'cluster-carriageway-edge-offset' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey, ); for (const edge of initialEdges) { for (const [suffix, value] of [ ['min', edge.value.min], ['max', edge.value.max], ]) { const result = resolveDirectEditConstraints( junctionModel, document([ constraint({ id: `edge-bound-${edge.anchor.side}-${suffix}`, kind: edge.kind, anchor: edge.anchor, value: edge.anchor.side === 'left' ? { leftOffsetMeters: value, rightOffsetMeters: 0 } : { leftOffsetMeters: 0, rightOffsetMeters: value }, }), ]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); assert.equal(result.constraintStates[0].applied, true, `${edge.anchor.side} ${suffix} must be accepted`); } const pastMax = resolveDirectEditConstraints( junctionModel, document([ constraint({ kind: edge.kind, anchor: edge.anchor, value: edge.anchor.side === 'left' ? { leftOffsetMeters: edge.value.max + 0.01, rightOffsetMeters: 0 } : { leftOffsetMeters: 0, rightOffsetMeters: edge.value.max + 0.01 }, }), ]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); assert.equal(pastMax.constraintStates[0].applied, false, `${edge.anchor.side} beyond max must be rejected`); } const transitionedCluster = resolveDirectEditConstraints( junctionModel, document([ constraint({ kind: 'cluster-carriageway-transition-length', anchor: clusterWidthHandle.anchor, value: { transitionLengthMeters: clusterTransitionHandle.value.min }, }), ]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] }, ); const transitionedHandle = transitionedCluster.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-transition-length' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey, ); const transitionedEdges = transitionedCluster.handles.handles.filter( (handle) => handle.kind === 'cluster-carriageway-edge-offset' && handle.anchor.carriagewayKey === clusterWidthHandle.anchor.carriagewayKey, ); for (const edge of transitionedEdges) { assert.ok( Math.abs(haversineMeters(edge.position, transitionedHandle.position) - clusterWidthHandle.value.current / 2) < 0.02, 'edge handles must use the same effective inner station as the transition handle', ); } const recheckResolution = resolveDirectEditConstraints( junctionModel, { ...document([anchored]), base: { compilerGeometryVersion: 'old-geometry' } }, { compilerGeometryVersion: 'new-geometry' }, ); assert.equal(recheckResolution.constraintStates[0].status, 'recheck'); assert.equal(recheckResolution.constraintStates[0].applied, true); const pendingResolution = resolveDirectEditConstraints( junctionModel, document([ constraint({ anchor: { type: 'road-interval', roadId: 'missing-road', startStation: 0.2, endStation: 0.8, side: 'left' }, anchorSnapshot: { ...constraint().anchorSnapshot, coordinate: [113, 30], osmNodeIds: ['junction'] }, }), ]), ); assert.equal(pendingResolution.constraintStates[0].status, 'pending'); assert.equal(pendingResolution.constraintStates[0].applied, false); const invalidDivider = resolveDirectEditConstraints( junctionModel, document([ constraint({ kind: 'road-lane-divider', anchor: { type: 'road-interval', roadId: 'road:a', startStation: 0.2, endStation: 0.8 }, value: { boundaryIndex: 3, offsetMeters: 0 }, }), ]), ); assert.equal(invalidDivider.constraintStates[0].applied, false); assert.equal(invalidDivider.constraintStates[0].status, 'stale'); assert.equal(invalidDivider.constraintStates[0].reason, 'status-stale'); assert.equal(invalidDivider.roadProfiles.size, 0); // A disabled constraint is reported, never applied, and produces no diagnostic: // the user turned it off deliberately, so it is not a problem to report. const disabled = resolveDirectEditConstraints(model, document([constraint({ enabled: false })])); assert.deepEqual(disabled.constraintStates, [ { constraintId: 'constraint-1', kind: 'road-edge-offset', status: 'exact', applied: false, reason: 'disabled' }, ]); assert.deepEqual(disabled.diagnostics, []); // Only `exact` and `recheck` may reach the solver. The other three statuses mean // the anchor is not trustworthy, so they are skipped with the status as reason. for (const status of ['pending', 'conflicted', 'stale']) { const resolution = resolveDirectEditConstraints(model, document([constraint({ status })])); assert.deepEqual(resolution.constraintStates, [ { constraintId: 'constraint-1', kind: 'road-edge-offset', status, applied: false, reason: `status-${status}` }, ]); assert.deepEqual(resolution.diagnostics, []); } // An exact constraint whose anchor disappeared during reimport is stale and // must not enter the solver. for (const status of ['exact', 'recheck']) { const resolution = resolveDirectEditConstraints(model, document([constraint({ status })])); assert.deepEqual(resolution.constraintStates, [ { constraintId: 'constraint-1', kind: 'road-edge-offset', status: 'stale', applied: false, reason: 'anchor-missing', }, ]); assert.deepEqual(resolution.diagnostics, []); } // Every constraint gets exactly one state, in document order, so a caller can // report per-row status without re-deriving the mapping. const many = resolveDirectEditConstraints( model, document([ constraint({ id: 'a', enabled: false }), constraint({ id: 'b', status: 'stale' }), constraint({ id: 'c' }), ]), ); assert.deepEqual( many.constraintStates.map((state) => state.constraintId), ['a', 'b', 'c'], ); // A short road sandwiched between two junctions. `junctionReserves()` caps each // end's reserve at 0.45, so `start >= end` can never fire; what decides whether // an edit is offered is the surviving band measured in meters against the road's // own width. 0.00013 degrees of latitude is about 14.4 m, shorter than the // cutback the approaches demand at either end, so both ends hit the cap and the // band lands at ~1.4 m. function sandwichModel(shortWidthMeters, shortLaneCount) { const nodeA = [113, 30]; const nodeB = [113, 30.00013]; const road = (id, from, to, widthMeters, laneCount) => ({ id: `road:${id}`, segmentId: `segment:${id}`, direction: 'forward', centerline: [from, to], sourceNodeIds: [`node-${id}-a`, `node-${id}-b`], osmWayIds: [id], widthMeters, laneCount, sidewalkLeft: true, sidewalkRight: true, }); const endpoint = (roadId, side, nodeId, coordinate) => ({ id: `endpoint:${roadId}:${side}`, roadId, side, nodeId, coordinate, }); return { roads: [ road('short', nodeA, nodeB, shortWidthMeters, shortLaneCount), road('a1', nodeA, [112.999, 30], 6, 2), road('a2', nodeA, [113.001, 30], 6, 2), road('b1', nodeB, [112.999, 30.00013], 6, 2), road('b2', nodeB, [113.001, 30.00013], 6, 2), ], endpoints: [ endpoint('road:short', 'start', 'node-a', nodeA), endpoint('road:a1', 'start', 'node-a', nodeA), endpoint('road:a2', 'start', 'node-a', nodeA), endpoint('road:short', 'end', 'node-b', nodeB), endpoint('road:b1', 'start', 'node-b', nodeB), endpoint('road:b2', 'start', 'node-b', nodeB), ], connections: [], }; } function roadHandlesFor(resolution, roadId) { return resolution.handles.handles.filter( (handle) => handle.kind.startsWith('road-') && handle.anchor.roadId === roadId, ); } // The short road's band is ~1.4 m against a 10 m width, so every road handle on // it is read-only and says why. The long approach at the same junction keeps its // handles, which is what proves the rule is about the band and not about being // adjacent to a junction. const sandwich = resolveDirectEditConstraints(sandwichModel(10, 4), document([]), { revisionId: 'rev-sandwich' }); const shortHandles = roadHandlesFor(sandwich, 'road:short'); const longHandles = roadHandlesFor(sandwich, 'road:a1'); assert.ok(shortHandles.length > 0, 'the blocked road must still publish handles so the map can explain them'); assert.ok(longHandles.length > 0); assert.ok(shortHandles.every((handle) => handle.editable === false)); assert.ok(shortHandles.every((handle) => handle.disabledReason.includes('JunctionTools'))); assert.ok(longHandles.every((handle) => handle.editable === true)); assert.ok(longHandles.every((handle) => handle.disabledReason === undefined)); // Junction kinds are JunctionTools' territory and must stay draggable there. assert.ok( sandwich.handles.handles .filter((handle) => handle.kind.startsWith('junction-')) .every((handle) => handle.editable === true), ); // The band is compared in meters against the road's own width. The 0.45 cap keeps // the band at ~1.4 m either way, so changing only the width crosses the boundary. assert.ok( roadHandlesFor(resolveDirectEditConstraints(sandwichModel(2, 2), document([])), 'road:short').every( (h) => !h.editable, ), ); assert.ok( roadHandlesFor(resolveDirectEditConstraints(sandwichModel(1, 2), document([])), 'road:short').every( (h) => h.editable, ), ); // Greying is a UI affordance, not a retroactive veto: an edit already saved // against this road keeps being solved, or a compiler upgrade would silently drop // it and the geometry would move underneath the user. const onBlocked = resolveDirectEditConstraints( sandwichModel(10, 4), document([ constraint({ id: 'edge-on-short', anchor: { type: 'road-interval', roadId: 'road:short', startStation: 0.45, endStation: 0.55, side: 'left' }, }), ]), ); assert.equal(onBlocked.constraintStates[0].applied, true); assert.equal(onBlocked.roadProfiles.get('road:short').edgeOffsets.left, 1.5); // Control-marking offsets must reach the geometry before any handle is drawn for // them. This project already shipped a range handle for `profile.interval`, which // compileGeometry ignores, so the control dragged and changed nothing — see // 08-26-direct-edit-map-editor/research/interval-not-applied.md. The consumer is // asserted first. const controlRoads = ['a', 'b', 'c'].map((id, index) => ({ id: `road:${id}`, segmentId: `segment:${id}`, direction: 'forward', tags: {}, highway: 'residential', // Roads *arrive* at the junction: `crossingJunctionInset()` resolves the junction // from the road's last node, so a fixture whose roads leave the junction finds no // plan and silently insets by zero. centerline: [ [113 + index * 0.001 + (index === 1 ? 0.001 : 0), 30 + (index === 1 ? 0.001 : 0.001)], [113 + index * 0.001, 30], ], sourceNodeIds: [`end-${id}`, 'junction'], osmWayIds: [id], widthMeters: 6, laneCount: 2, sidewalkLeft: true, sidewalkRight: true, })); const controlModel = { roads: controlRoads, endpoints: controlRoads.map((road) => ({ id: `endpoint:${road.id}:end`, roadId: road.id, side: 'end', nodeId: 'junction', coordinate: road.centerline.at(-1), })), connections: [], diagnostics: [], crossings: [{ id: 'x1', coordinate: [113, 30.0004], tags: { highway: 'crossing' }, osmWayIds: ['a'] }], }; const controlConstraint = (kind, value) => constraint({ id: `c-${kind}`, kind, anchor: { type: 'junction-approach', nodeId: 'junction', segmentId: 'segment:a' }, value, }); // NOTE: the geometry-level proof (a crosswalk inset actually moving the zebra) was // measured on a real 41-road workspace with 8 crossings, not asserted here: this // synthetic junction resolves `junction_inset_m` to 0 because the crossing never // binds to a junction plan, and the committed OSM fixture has no crossings at all. // Closing that gap needs an OSM fixture with a crossing on a road that arrives at a // junction. What is asserted below is the wiring the handles will depend on. // Both new kinds land their value on the approach entry the compiler reads. const approachEntry = (kind, value) => resolveDirectEditConstraints(controlModel, document([controlConstraint(kind, value)]), {}).junctionPlans.get( 'junction', ).approaches['segment:a']; assert.equal(approachEntry('junction-crosswalk-inset', { insetMeters: 3 }).crosswalkInsetMeters, 3); assert.equal(approachEntry('junction-stop-line-offset', { offsetMeters: 4 }).stopLineOffsetMeters, 4); // Out of range blocks rather than clamping, and writes nothing to the plan. const absurd = resolveDirectEditConstraints( controlModel, document([controlConstraint('junction-crosswalk-inset', { insetMeters: 9999 })]), {}, ); assert.equal(absurd.constraintStates[0].applied, false); assert.ok( absurd.diagnostics.some((item) => item.rule === 'direct-edit-crosswalk-inset-invalid'), 'an out-of-range inset must produce a blocking diagnostic, not a silent clamp', ); // The kinds are distinct branches: a stop-line offset must not be validated or // written as a cutback, which the previous `else` fallthrough would have done. const stopOnly = resolveDirectEditConstraints( controlModel, document([controlConstraint('junction-stop-line-offset', { offsetMeters: 4 })]), {}, ).junctionPlans.get('junction').approaches['segment:a']; assert.equal(stopOnly.cutbackMeters !== 4, true, 'a stop-line offset must not be written as a cutback'); // Crosswalk size reaches the geometry, and bad values are refused rather than // clamped. The kind exists only because compileGeometry() reads it — the rule // design.md sets after `profile.interval` shipped a handle that did nothing. { const sized = resolveDirectEditConstraints( controlModel, document([controlConstraint('junction-crosswalk-size', { depthMeters: 4, stripeCount: 10 })]), {}, ); const plan = sized.junctionPlans.get('junction').approaches['segment:a']; assert.equal(plan.crosswalkDepthMeters, 4); assert.equal(plan.crosswalkStripeCount, 10); for (const [value, rule] of [ [{ depthMeters: 0, stripeCount: 8 }, 'direct-edit-crosswalk-depth-invalid'], [{ depthMeters: 3, stripeCount: 1 }, 'direct-edit-crosswalk-stripes-invalid'], [{ depthMeters: 3, stripeCount: 6.5 }, 'direct-edit-crosswalk-stripes-invalid'], ]) { const bad = resolveDirectEditConstraints( controlModel, document([controlConstraint('junction-crosswalk-size', value)]), {}, ); assert.equal(bad.constraintStates[0].applied, false); assert.ok( bad.diagnostics.some((item) => item.rule === rule), `${JSON.stringify(value)} must produce ${rule}`, ); } } // A crosswalk-inset handle must publish the ceiling that still moves the zebra. // // `crossingJunctionInset()` saturates once the inset reaches the cutback, and // sooner when the crossing sits far from the junction, so a flat max left 44-88% // of the declared range moving nothing and saying nothing. The ceiling is // `cutback - max(0, junctionDistance - 4)`. { const { effectiveCrosswalkInsetMax, approachForCrossing } = require('../src/compile/crossing-approach'); assert.equal(effectiveCrosswalkInsetMax(9.1, 9.89).toFixed(2), '3.21'); // Distance under the 4m cap cannot pull the ceiling below the cutback. assert.equal(effectiveCrosswalkInsetMax(9.1, 2), 9.1); assert.equal(effectiveCrosswalkInsetMax(NaN, 5), null); // Both directional roads of one segment can meet at a junction, each serving a // different crossing. Picking the first match published one road's ceiling on // the other's handle, so the road that actually ends at this node has to win. const centerline = (lon) => [ [lon, 0], [lon, 0.001], ]; const twoWay = { roads: [ { id: 'r:fwd', segmentId: 'seg', centerline: centerline(0), sourceNodeIds: ['a', 'far'], osmWayIds: ['w'] }, { id: 'r:bwd', segmentId: 'seg', centerline: centerline(0), sourceNodeIds: ['a', 'near'], osmWayIds: ['w'] }, ], endpoints: [], connections: [ { enabled: true, fromEndpointId: 'endpoint:r:fwd:end', nodeId: 'far' }, { enabled: true, fromEndpointId: 'endpoint:r:bwd:end', nodeId: 'near' }, ], crossings: [{ id: 'x', osmWayIds: ['w'], coordinate: [0, 0.0009] }], }; const paired = approachForCrossing(twoWay, twoWay.crossings[0]); assert.ok(paired, 'a crossing on a two-way segment must still pair with one road'); assert.equal(paired.road.segmentId, 'seg'); } // The solver must be free of file and network access so preview can share it. const source = require('fs').readFileSync(require.resolve('../src/compile/direct-edit-solver'), 'utf8'); for (const forbidden of ["require('fs')", "require('path')", "require('http')", "require('https')"]) assert.equal(source.includes(forbidden), false, `direct-edit-solver must not ${forbidden}`); assert.equal( source.includes("require('./complex-junction')"), false, 'direct-edit-solver must not depend on the compiler module that reads reference files', ); console.log('direct edit solver tests passed'); const transitionHandle = clusterHandleResolution.handles.handles.find( (handle) => handle.kind === 'cluster-carriageway-transition-length', ); assert.ok(transitionHandle); assert.ok( transitionHandle.value.current >= transitionHandle.value.min && transitionHandle.value.current <= transitionHandle.value.max, ); const transitionConstraint = constraint({ id: 'transition-complete', kind: 'cluster-carriageway-transition-length', anchor: transitionHandle.anchor, value: { transitionLengthMeters: (transitionHandle.value.min + transitionHandle.value.max) / 2 }, }); const resolveTransition = (value) => resolveDirectEditConstraints(junctionModel, document([value]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }], }); const appliedTransition = resolveTransition(transitionConstraint); assert.equal(appliedTransition.constraintStates[0].applied, true); assert.equal( appliedTransition.clusterTransitions.get('cluster-1').get(transitionHandle.anchor.carriagewayKey), transitionConstraint.value.transitionLengthMeters, ); assert.equal( appliedTransition.clusterCutbacks.size, 0, 'transition length must not move the outer seam through cutback', ); assert.equal( resolveTransition({ ...transitionConstraint, value: { transitionLengthMeters: transitionHandle.value.max + 1 } }) .constraintStates[0].applied, false, ); assert.equal( resolveTransition({ ...transitionConstraint, anchor: { ...transitionConstraint.anchor, sourceRoadIds: ['missing'] } }) .constraintStates[0].applied, false, ); assert.equal(resolveTransition({ ...transitionConstraint, enabled: false }).clusterTransitions.size, 0); const rejectedCutback = constraint({ id: 'transition-invalid-cutback', kind: 'cluster-carriageway-cutback', anchor: transitionHandle.anchor, value: { cutbackMeters: 999 }, }); const mixedTransition = resolveDirectEditConstraints(junctionModel, document([rejectedCutback, transitionConstraint]), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }], }); assert.equal(mixedTransition.constraintStates[0].applied, false); assert.equal(mixedTransition.constraintStates[1].applied, true); assert.equal( mixedTransition.handles.handles.find((handle) => handle.handleId === transitionHandle.handleId).value.max, transitionHandle.value.max, 'a rejected cutback must not move transition bounds away from the effective outer seam', );