373 lines
15 KiB
JavaScript
373 lines
15 KiB
JavaScript
'use strict';
|
|
|
|
const assert = require('assert/strict');
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
const path = require('path');
|
|
const { compileInput } = require('../src/compile/compiler');
|
|
const { compileRoadModel, loadOverrides } = require('../src/compile/native-road');
|
|
const { ensureRevisionStore } = require('../src/compile/road-revisions');
|
|
const {
|
|
editPreview,
|
|
editState,
|
|
rebaseEdits,
|
|
saveEdits,
|
|
state: browseState,
|
|
selectionFrom,
|
|
} = require('../workbench/server');
|
|
const { snapshot: outputSnapshot } = require('./fixture-baseline');
|
|
|
|
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'workbench-edit-api-'));
|
|
const input = {
|
|
areaId: 'edit-api-test',
|
|
osmFile: path.join(workspace, 'source.osm'),
|
|
outDir: path.join(workspace, 'outputs', 'native-road'),
|
|
stagingDir: path.join(workspace, 'outputs', '_pipeline'),
|
|
overridesFile: path.join(workspace, 'native-road-overrides.json'),
|
|
trafficSignalsFile: path.join(workspace, 'native-traffic-signals.json'),
|
|
options: { edgeLines: false, junctionTemplates: { enabled: false, references: [] } },
|
|
};
|
|
fs.copyFileSync(path.join(__dirname, 'fixtures', 'fengshu-er-road.osm'), input.osmFile);
|
|
fs.writeFileSync(input.overridesFile, `${JSON.stringify({ schema: 'native-road-overrides/v1', overrides: [] })}\n`);
|
|
fs.writeFileSync(
|
|
input.trafficSignalsFile,
|
|
`${JSON.stringify({ schema: 'native-traffic-signals/v1', provenance: 'empty', assemblies: { type: 'FeatureCollection', features: [] } })}\n`,
|
|
);
|
|
const initialized = ensureRevisionStore(workspace, input.options);
|
|
const area = compileInput({
|
|
...input,
|
|
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
|
|
editsFile: initialized.paths.activeEdits,
|
|
}).area;
|
|
|
|
const state = editState(area);
|
|
assert.equal(state.active, true);
|
|
assert.equal(state.documentVersion, 0);
|
|
assert.equal(state.handles.schema, 'road-edit-handles/v1');
|
|
assert.equal(state.activeRevisionId, 'rev-0001');
|
|
|
|
const trackedFiles = [
|
|
initialized.paths.activeEdits,
|
|
initialized.paths.activeState,
|
|
initialized.paths.activeAreaConfig,
|
|
].map((file) => ({
|
|
file,
|
|
bytes: fs.readFileSync(file),
|
|
mtimeMs: fs.statSync(file).mtimeMs,
|
|
}));
|
|
const preview = editPreview(area, { previewSeq: 17, document: state.document });
|
|
assert.equal(preview.ok, true);
|
|
assert.equal(preview.previewSeq, 17);
|
|
assert.equal(preview.degraded, false);
|
|
assert.equal(preview.handles.schema, 'road-edit-handles/v1');
|
|
assert.ok(preview.layers.roadSurface);
|
|
for (const tracked of trackedFiles) {
|
|
assert.deepEqual(fs.readFileSync(tracked.file), tracked.bytes, `${tracked.file} bytes unchanged by preview`);
|
|
assert.equal(fs.statSync(tracked.file).mtimeMs, tracked.mtimeMs, `${tracked.file} mtime unchanged by preview`);
|
|
}
|
|
|
|
const saved = saveEdits(area, { expectedDocumentVersion: 0, document: state.document });
|
|
assert.equal(saved.documentVersion, 1);
|
|
const beforeConflict = fs.readFileSync(initialized.paths.activeEdits);
|
|
assert.throws(
|
|
() => saveEdits(area, { expectedDocumentVersion: 0, document: state.document }),
|
|
(error) => error.statusCode === 409 && error.current.documentVersion === 1,
|
|
);
|
|
assert.deepEqual(fs.readFileSync(initialized.paths.activeEdits), beforeConflict, '409 does not write the document');
|
|
|
|
const checkpoint = require('../src/compile/road-revisions').createCheckpoint(workspace, 'Preview checkpoint');
|
|
assert.equal(checkpoint.manifest.id, 'rev-0002');
|
|
const rebased = rebaseEdits(area, checkpoint.manifest.id);
|
|
assert.equal(rebased.counts.exact, 0);
|
|
assert.deepEqual(rebased.constraints, []);
|
|
|
|
// The map saves `constraints` + `operations`, not a whole document. That merge path
|
|
// is what the client actually exercises, and leaving the operations out is exactly
|
|
// how the first wiring produced a 400.
|
|
const edgeHandle = state.handles.handles.find((handle) => handle.kind === 'road-edge-offset');
|
|
assert.ok(edgeHandle, 'the fixture must publish a road edge handle');
|
|
const clientConstraint = {
|
|
id: `constraint:${edgeHandle.handleId}`,
|
|
kind: 'road-edge-offset',
|
|
anchor: edgeHandle.anchor,
|
|
anchorSnapshot: {
|
|
coordinate: edgeHandle.position,
|
|
tangentAzimuth: 0,
|
|
roadLengthMeters: 120,
|
|
osmNodeIds: ['1'],
|
|
},
|
|
value: { offsetMeters: 0.5, transition: 'smoothstep' },
|
|
enabled: true,
|
|
status: 'exact',
|
|
provenance: { operationId: 'operation:client:1', createdAt: '2026-08-27T00:00:00.000Z' },
|
|
};
|
|
const clientOperation = {
|
|
id: clientConstraint.provenance.operationId,
|
|
createdAt: clientConstraint.provenance.createdAt,
|
|
constraintIds: [clientConstraint.id],
|
|
};
|
|
assert.throws(
|
|
() => saveEdits(area, { expectedDocumentVersion: 1, constraints: [clientConstraint], operations: [] }),
|
|
/provenance\.operationId/,
|
|
'a constraint saved without its operation must be rejected, not written',
|
|
);
|
|
const clientSaved = saveEdits(area, {
|
|
expectedDocumentVersion: 1,
|
|
constraints: [clientConstraint],
|
|
operations: [clientOperation],
|
|
});
|
|
assert.equal(clientSaved.documentVersion, 2);
|
|
|
|
// JunctionTools uses the same preview and compile solver. Exercise a real
|
|
// junction approach handle so a geometry edit cannot be preview-only: the
|
|
// published intersection layer must be byte-equivalent after a save/recompile.
|
|
const junctionHandle = state.handles.handles.find((handle) => handle.kind === 'junction-approach-width');
|
|
assert.ok(junctionHandle, 'the fixture must publish a junction approach width handle');
|
|
const junctionModel = compileRoadModel(fs.readFileSync(input.osmFile, 'utf8'), loadOverrides(input.overridesFile));
|
|
const approach = junctionModel.roads.find((road) => road.segmentId === junctionHandle.anchor.segmentId);
|
|
assert.ok(approach, 'the junction handle must resolve to a model road');
|
|
const junctionConstraint = {
|
|
id: `constraint:${junctionHandle.handleId}`,
|
|
kind: 'junction-approach-width',
|
|
anchor: junctionHandle.anchor,
|
|
anchorSnapshot: {
|
|
coordinate: junctionHandle.position,
|
|
tangentAzimuth: junctionHandle.axisAzimuth,
|
|
roadLengthMeters: 120,
|
|
osmNodeIds: approach.sourceNodeIds,
|
|
},
|
|
value: { widthMeters: junctionHandle.value.current + 0.25 },
|
|
enabled: true,
|
|
status: 'exact',
|
|
provenance: { operationId: 'operation:client:junction-1', createdAt: '2026-08-27T00:00:01.000Z' },
|
|
};
|
|
const junctionOperation = {
|
|
id: junctionConstraint.provenance.operationId,
|
|
createdAt: junctionConstraint.provenance.createdAt,
|
|
constraintIds: [junctionConstraint.id],
|
|
};
|
|
const junctionConstraints = [clientConstraint, junctionConstraint];
|
|
const junctionOperations = [clientOperation, junctionOperation];
|
|
const junctionPreview = editPreview(area, {
|
|
previewSeq: 23,
|
|
constraints: junctionConstraints,
|
|
operations: junctionOperations,
|
|
});
|
|
assert.equal(junctionPreview.ok, true);
|
|
assert.ok(junctionPreview.layers.intersectionSurface);
|
|
const junctionSaved = saveEdits(area, {
|
|
expectedDocumentVersion: 2,
|
|
constraints: junctionConstraints,
|
|
operations: junctionOperations,
|
|
});
|
|
assert.equal(junctionSaved.documentVersion, 3);
|
|
assert.throws(
|
|
() =>
|
|
saveEdits(area, {
|
|
expectedDocumentVersion: 3,
|
|
constraints: [{ ...junctionConstraint, value: { widthMeters: 1 } }],
|
|
operations: [junctionOperation],
|
|
}),
|
|
(error) => error.statusCode === 400 && /不能小于/.test(error.message),
|
|
'blocking junction geometry diagnostics must prevent saving',
|
|
);
|
|
const junctionCompiled = compileInput({
|
|
...input,
|
|
outDir: path.join(workspace, 'outputs', 'junction-with-edits'),
|
|
stagingDir: path.join(workspace, 'outputs', '_junction-with-edits'),
|
|
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
|
|
editsFile: initialized.paths.activeEdits,
|
|
});
|
|
const publishedJunction = JSON.parse(
|
|
fs.readFileSync(
|
|
path.join(junctionCompiled.area.outputs.nativeRoadDir, 'layers', 'intersection_surface.geojson'),
|
|
'utf8',
|
|
),
|
|
);
|
|
assert.deepEqual(
|
|
publishedJunction,
|
|
junctionPreview.layers.intersectionSurface,
|
|
'formal compile must publish the same junction geometry returned by preview',
|
|
);
|
|
|
|
// A save that does not survive a reload as `exact` was cosmetic.
|
|
const reloaded = editState(area);
|
|
assert.equal(reloaded.documentVersion, 3);
|
|
assert.deepEqual(
|
|
reloaded.document.constraints.map((item) => item.id),
|
|
[clientConstraint.id, junctionConstraint.id],
|
|
);
|
|
assert.equal(reloaded.constraintStates[0].status, 'exact');
|
|
assert.equal(reloaded.constraintStates[0].applied, true);
|
|
|
|
// A saved document has to reach the geometry, not just the file. `compileInput()`
|
|
// is the only caller that passes `editsFile`, and the workbench serves the outputs
|
|
// it wrote — so a stage that ignored the document would make a save look successful
|
|
// while a refresh still showed the pre-edit map. The existing identity test cannot
|
|
// catch that: an ignored document and an empty one produce the same output.
|
|
const noEdits = {
|
|
...input,
|
|
outDir: path.join(workspace, 'outputs', 'no-edits'),
|
|
stagingDir: path.join(workspace, 'outputs', '_no-edits'),
|
|
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
|
|
};
|
|
const withEdits = {
|
|
...input,
|
|
outDir: path.join(workspace, 'outputs', 'with-edits'),
|
|
stagingDir: path.join(workspace, 'outputs', '_with-edits'),
|
|
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
|
|
editsFile: initialized.paths.activeEdits,
|
|
};
|
|
compileInput(noEdits);
|
|
compileInput(withEdits);
|
|
assert.notDeepEqual(
|
|
outputSnapshot(withEdits).files,
|
|
outputSnapshot(noEdits).files,
|
|
'a saved constraint must change the compiled output, or saving cannot survive a refresh',
|
|
);
|
|
|
|
// Typed scope must survive parsing and cannot silently choose the first key.
|
|
assert.deepEqual(selectionFrom(new URLSearchParams('cluster=fixture-five-arm')), {
|
|
type: 'cluster',
|
|
id: 'fixture-five-arm',
|
|
});
|
|
assert.deepEqual(selectionFrom({ junction: '8005332807' }), { type: 'junction', id: '8005332807' });
|
|
for (const invalid of [
|
|
{ cluster: 'one', junction: 'two' },
|
|
{ cluster: '' },
|
|
{ cluster: {} },
|
|
new URLSearchParams('cluster=one&cluster=two'),
|
|
]) {
|
|
assert.throws(() => selectionFrom(invalid), /selection/);
|
|
}
|
|
assert.throws(() => editPreview(area, { selection: { cluster: 'one', segment: 'two' } }), /selection/);
|
|
|
|
const cluster = {
|
|
id: 'fixture-five-arm',
|
|
template: 'complex-junction-v1',
|
|
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
|
|
coreRadiusMeters: 24,
|
|
};
|
|
const complexInput = {
|
|
...input,
|
|
outDir: path.join(workspace, 'outputs', 'complex'),
|
|
stagingDir: path.join(workspace, 'outputs', '_complex'),
|
|
options: { edgeLines: false, junctionTemplates: { enabled: true, clusters: [cluster] } },
|
|
};
|
|
const complexArea = compileInput(complexInput).area;
|
|
const clusterState = editState(complexArea, selectionFrom({ cluster: cluster.id }));
|
|
assert.ok(
|
|
clusterState.handles.handles.every((handle) => handle.kind === 'cluster-carriageway-width'),
|
|
'cluster selection publishes only scoped complex carriageway width handles',
|
|
);
|
|
assert.ok(clusterState.handles.handles.length, 'the complex fixture must publish editable carriageways');
|
|
assert.deepEqual(clusterState.junctionStructure.junctionRef, { type: 'cluster', id: cluster.id });
|
|
assert.equal(clusterState.junctionStructure.shape.effectiveArmCount, 5);
|
|
assert.equal(
|
|
clusterState.junctionStructure.capability.editable,
|
|
false,
|
|
'structure capability opens with the frontend stage',
|
|
);
|
|
const complexTracked = trackedFiles.map(({ file }) => ({
|
|
file,
|
|
bytes: fs.readFileSync(file),
|
|
mtimeMs: fs.statSync(file).mtimeMs,
|
|
}));
|
|
const emptyDocument = { ...clusterState.document, constraints: [], operations: [] };
|
|
const clusterPreview = editPreview(complexArea, { document: emptyDocument, selection: { cluster: cluster.id } });
|
|
assert.deepEqual(clusterPreview.handles.handles, clusterState.handles.handles);
|
|
assert.deepEqual(
|
|
clusterPreview.junctionStructure,
|
|
clusterState.junctionStructure,
|
|
'preview and persisted compiler structure agree',
|
|
);
|
|
const complexWidthHandle = clusterState.handles.handles[0];
|
|
const complexWidthConstraint = {
|
|
id: 'constraint:complex-width',
|
|
kind: 'cluster-carriageway-width',
|
|
anchor: complexWidthHandle.anchor,
|
|
anchorSnapshot: {
|
|
coordinate: complexWidthHandle.position,
|
|
tangentAzimuth: complexWidthHandle.axisAzimuth,
|
|
roadLengthMeters: 120,
|
|
osmNodeIds: complexWidthHandle.anchor.sourceNodeIds,
|
|
},
|
|
value: { widthMeters: complexWidthHandle.value.current + 0.25 },
|
|
enabled: true,
|
|
status: 'exact',
|
|
provenance: { operationId: 'operation:complex-width', createdAt: '2026-09-08T00:00:00.000Z' },
|
|
};
|
|
const widenedClusterPreview = editPreview(complexArea, {
|
|
document: {
|
|
...emptyDocument,
|
|
constraints: [complexWidthConstraint],
|
|
operations: [
|
|
{
|
|
id: 'operation:complex-width',
|
|
createdAt: '2026-09-08T00:00:00.000Z',
|
|
constraintIds: [complexWidthConstraint.id],
|
|
},
|
|
],
|
|
},
|
|
selection: { cluster: cluster.id },
|
|
});
|
|
const complexSurface = (preview) =>
|
|
preview.layers.roadSurface.features.find(
|
|
(feature) => feature.properties.carriageway_key === complexWidthHandle.anchor.carriagewayKey,
|
|
);
|
|
assert.notDeepEqual(
|
|
complexSurface(widenedClusterPreview).geometry,
|
|
complexSurface(clusterPreview).geometry,
|
|
'a cluster carriageway constraint must change compiled complex geometry',
|
|
);
|
|
const browsing = browseState(complexArea);
|
|
const unavailableStructureState = browseState({
|
|
...complexArea,
|
|
nativeRoad: {
|
|
...complexArea.nativeRoad,
|
|
junctionTemplates: {
|
|
...complexArea.nativeRoad.junctionTemplates,
|
|
clusters: [
|
|
...complexArea.nativeRoad.junctionTemplates.clusters,
|
|
{ id: 'not-compiled', template: 'complex-junction-v1', nodeIds: ['missing-1', 'missing-2'] },
|
|
],
|
|
},
|
|
},
|
|
});
|
|
assert.equal(unavailableStructureState.junctionStructures['cluster:not-compiled'], undefined);
|
|
assert.ok(browsing.standardsDiagnostics.length, 'browse state retains structure diagnostics');
|
|
assert.equal(new Set(browsing.standardsDiagnostics.map((item) => item.id)).size, browsing.standardsDiagnostics.length);
|
|
assert.ok(
|
|
Object.values(browsing.junctionStructures).every(Boolean),
|
|
'the structure index contains only available structures',
|
|
);
|
|
assert.deepEqual(browsing.junctionStructures[`cluster:${cluster.id}`], clusterState.junctionStructure);
|
|
const simpleKey = Object.keys(browsing.junctionStructures).find(
|
|
(key) => key.startsWith('node:') && !cluster.nodeIds.includes(key.slice(5)),
|
|
);
|
|
assert.ok(simpleKey, 'fixture includes a simple junction outside the cluster');
|
|
const simpleState = editState(complexArea, selectionFrom({ junction: simpleKey.slice(5) }));
|
|
assert.deepEqual(simpleState.junctionStructure, browsing.junctionStructures[simpleKey]);
|
|
assert.equal(simpleState.junctionStructure.junctionRef.type, 'node');
|
|
for (const item of clusterState.standardsDiagnostics) {
|
|
assert.ok(browsing.standardsDiagnostics.some((candidate) => candidate.id === item.id));
|
|
}
|
|
assert.ok(simpleState.handles.handles.length);
|
|
for (const type of ['cluster', 'junction']) {
|
|
const missing = editState(complexArea, selectionFrom({ [type]: 'missing-junction' }));
|
|
assert.equal(missing.junctionStructure, null);
|
|
assert.deepEqual(missing.handles.handles, []);
|
|
assert.deepEqual(missing.standardsDiagnostics, []);
|
|
assert.equal(
|
|
editPreview(complexArea, { document: emptyDocument, selection: { [type]: 'missing-junction' } }).junctionStructure,
|
|
null,
|
|
);
|
|
}
|
|
for (const tracked of complexTracked) {
|
|
assert.deepEqual(fs.readFileSync(tracked.file), tracked.bytes, 'scoped reads and previews preserve active files');
|
|
assert.equal(fs.statSync(tracked.file).mtimeMs, tracked.mtimeMs);
|
|
}
|
|
|
|
fs.rmSync(workspace, { recursive: true, force: true });
|
|
console.log('workbench edit API tests passed');
|