/** * The MapRuntime's public contract: its interface, events, dependencies, options and stats. The orchestration that * implements it lives in runtime.ts; how live frames are applied in ../realtime; query planning in ../query. */ import type { MapEngineError } from '../core/errors.js'; import type { BasemapConfig, BoundingBox, Geofence, GeofenceEvent, Geometry, LayerSource, MapLayer, MapViewport, Padding, Position, ScenePatch, SceneState, SelectionContext, Size, SpatialObject, SpatialQuery, TimeSetting, TimeState, TerrainConfig, TilesetConfig, MapConfig, Unsubscribe, Annotation, Highlight, LayerStatus, Proposal, TimeRange } from '../core/types.js'; import type { CommandResult, MapCommand } from '../core/commands.js'; import type { AnnotationProvider, AuthContext, ElevationProvider, JournalEntry, JournalProvider, LinkProvider, OntologySpatialResolver, RealtimeProvider, SpatialDataProvider, TrackProvider } from '../data/contracts.js'; import type { AgeState } from '../present/present.js'; import type { Measurement } from '../spatial/measure.js'; import type { PickEvent, Renderer } from '../render/renderer.js'; import type { SpatialIndex } from '../spatial/spatial-index.js'; import type { DrawingState, DrawKind } from './drawing.js'; import type { SightResult } from '../spatial/line-of-sight.js'; export type RuntimeState = 'idle' | 'loading' | 'ready' | 'error' | 'destroyed'; export interface MapRuntimeEvents extends Record { state: RuntimeState; viewport: MapViewport; selection: SelectionContext; hover: PickEvent | null; mapClick: { position: Position; }; /** Every click: its position and what it hit (null on empty map). Fires even when selection is paused. */ click: { position: Position; hit: { objectId: string; layerId: string; } | null; }; /** Every patch sent to the renderer, for observers such as inspectors or dev tools. */ scene: ScenePatch; /** Failures the application should know about (provider, renderer). The runtime keeps the last good scene. */ error: MapEngineError; /** Recoverable problems, e.g. an object with invalid geometry that was left out. */ warning: MapEngineError; /** The map switched between live and replay, or moved to another replay time. */ time: TimeState; /** A live geofence transition (enter, exit, dwell). Replay events are read with getGeofenceEvents(). */ geofence: GeofenceEvent; /** The geofence set changed (setGeofences). */ geofences: Geofence[]; /** The camera moved a frame (pan, zoom, animation). Use it to keep overlays such as popups on their object. */ move: null; /** Auditable (doc §76): a layer was added, changed or removed; `fields` names what changed (e.g. source.filter). */ layerChanged: { action: 'added' | 'updated' | 'removed'; layerId: string; fields?: string[]; }; /** Auditable (doc §76): a spatial query ran through runtime.query(). */ spatialQuery: { query: SpatialQuery; count: number; durationMs: number; error?: string; }; /** Drawing started, gained a point, or ended (null). */ drawing: DrawingState | null; /** Auditable (doc §76): the user finished drawing. The application decides what the geometry means. */ geometryDrawn: { kind: DrawKind; geometry: Geometry; }; /** Auditable (doc §76): what a layer loads was narrowed or widened (source filter, where, spatialQuery or objectIds). */ filterChanged: { layerId: string; before: LayerFilter; after: LayerFilter; }; /** Auditable (doc §76): a geofence was created, changed or removed through setGeofences(). */ geofenceChanged: { action: 'created' | 'updated' | 'removed'; geofenceId: string; }; /** Auditable (doc §76): the application opened an object's details (inspect()). */ objectInspected: { objectId: string; source: string; layerIds: string[]; }; /** Auditable: an annotation was created, changed or removed, and by whom (`user`, `agent:`…). */ annotation: { action: 'created' | 'updated' | 'removed'; id: string; annotation?: Annotation; origin: string; }; /** Auditable: a proposal was drawn, accepted (it became an annotation), rejected or cleared. */ proposal: { action: 'proposed' | 'accepted' | 'rejected' | 'cleared'; proposal: Proposal; reason?: string; by?: string; annotationId?: string; }; /** The highlight changed (null: cleared or expired). */ highlight: Highlight | null; /** A layer's status changed (loading, ok, denied, error, missing-capability). */ layerStatus: { layerId: string; status: LayerStatus; reason?: string; }; /** Auditable (doc 28 G6): a command list ran or was refused, with its origin. */ command: { commands: MapCommand[]; origin: string; result: CommandResult; }; /** A command asked the application to open its details view for an object. */ inspectRequested: { objectId: string; origin: string; }; /** A command asked the application's timeline to play (with a speed) or pause. */ playbackRequested: { action: 'play' | 'pause'; speed?: number; origin: string; }; } /** The parts of a layer source that decide which objects it loads. */ export type LayerFilter = Pick; /** * What the engine knows about one object (doc §34): its current state (as shown, so the replayed state in replay), * the layers showing it, whether it is selected, and the map's time. The application decides how to display it. */ export interface ObjectInspection { object: SpatialObject; layerIds: string[]; selected: boolean; time: TimeState; /** Under the age thresholds of the first layer showing it that has some, at the map's time. */ age?: { state: AgeState; seconds: number; }; } /** What an id in a text (an assistant reply, an alert) points at, for the person reading it (doc 28 G8). */ export interface ResolvedReference { /** shown: on the map now; loaded: on the client but not drawn (hidden layer, outside its time); available: the * provider has it (not loaded here); unavailable: no such object, or not visible to this user. */ status: 'shown' | 'loaded' | 'available' | 'unavailable'; object?: SpatialObject; } export interface LineOfSightOptions { /** Ground samples along the path. Default 128 (8 … 1024). */ samples?: number; /** Height above the ground of an end without altitude. Defaults 2 m. */ fromHeightAboveGround?: number; toHeightAboveGround?: number; signal?: AbortSignal; } /** Where flyTo() should take the camera. */ export interface FlyToOptions { /** Zoom for a point. Default: the current zoom, at least 15. For lines and areas, the most it may zoom in (default 18). */ zoom?: number; /** Pixels kept clear at each side when framing a line or an area. Default 40. */ padding?: Padding; /** Default true. */ animate?: boolean; } export interface MapRuntimeDeps { renderer: Renderer; provider: SpatialDataProvider; /** Snapshot + stream (ADR-015): after each load, layers subscribe for incremental changes. */ realtime?: RealtimeProvider; /** Resolves each layer's ontology type to a spatial binding before it is queried (doc 12, doc 20). */ ontology?: OntologySpatialResolver; /** Historical positions: trails (track layers) and replay (doc 07). */ history?: TrackProvider; /** Ground heights for sampleElevation() (ADR-028). Without it, the renderer's terrain answers if it can. */ elevation?: ElevationProvider; /** Relations between objects, for link layers (doc 28 G4). */ links?: LinkProvider; /** The event journal: replay rebuilds whole objects at a time, not only positions (doc 29 §7–8). */ journal?: JournalProvider; /** Where annotations are kept and shared (doc 28 G10). Without it they live in this runtime only. */ annotations?: AnnotationProvider; /** Who is looking; handed to every provider that accepts it (doc 28 G13). Change it with setAuth(). */ auth?: AuthContext; spatialIndex?: SpatialIndex; } export interface MapRuntimeStats { loads: number; providerCalls: number; lastLoadMs: number; lastPlan: { calls: number; layers: number; deduplicated: number; pushedDown: boolean; } | null; realtime: { subscriptions: number; received: number; applied: number; stale: number; outOfView: number; frames: number; reconnects: number; }; temporal: { trackFetches: number; tracksLoaded: number; replayFrames: number; trailPointsAppended: number; }; geofence: { geofences: number; liveEvents: number; replayEvents: number; }; } export interface MapRuntimeOptions { /** Delay after the last viewport or layer change before querying. Default 150 ms. */ debounceMs?: number; /** Used when the renderer reports a zero size (hidden container, headless tests). */ fallbackSize?: Size; now?: () => number; /** Schedules one coalesced realtime frame. Default: requestAnimationFrame, else a 16 ms timer. */ frame?: (callback: () => void) => void; /** Wait before reloading after a realtime error (snapshot, then stream again). Default 1000 ms. */ reconnectMs?: number; /** * How far ahead of this clock an `observedAt` may be before it is treated as clock skew (doc 14). Such a time is * reported once per object (CLOCK_SKEW warning) and not trusted for ordering, so later real updates still apply. * Default 60 000 ms. */ clockSkewToleranceMs?: number; } export interface MapRuntime { /** Shows the map in a container. After unmount() it can be mounted again (same or another container). */ mount(container: HTMLElement): Promise; /** * Takes the map off screen and releases the renderer (GPU context, DOM, listeners), live subscriptions and * timers — but keeps layers, viewport, selection, time, geofences and loaded objects, so mount() shows the same * map again at once. State goes back to 'idle'. Use it when a view is hidden or moved; destroy() is the end. */ unmount(): void; /** True between a completed mount() and unmount()/destroy(). */ isMounted(): boolean; /** * Changes the basemap and keeps everything else (camera, layers, selection, time, geofence log). Renderers that * can swap styles keep their GPU context; others are remounted in the same container. */ setBasemap(basemap: BasemapConfig): Promise; /** * Switches renderer (2D ↔ 3D, ADR-027) and keeps the map: layers, camera, selection, time, geofences and loaded * objects. The old renderer is released. Capabilities are re-checked for the new one. */ setRenderer(renderer: Renderer): Promise; /** Flat map or globe (needs the renderer's `globe` capability). */ setProjection(projection: NonNullable): void; /** Terrain relief on (a config) or off (null) (needs the renderer's `terrain` capability). */ setTerrain(terrain: TerrainConfig | null): void; /** Replaces the 3D Tiles scenery (needs the renderer's `tiles3d` capability; reported otherwise). */ setTilesets(tilesets: TilesetConfig[]): void; /** * Ground heights in metres above sea level under positions (null where unknown): from `deps.elevation`, else * the renderer's terrain. Rejects with MISSING_CAPABILITY when neither can answer. */ sampleElevation(positions: Position[], signal?: AbortSignal): Promise>; /** * Line of sight over the ground (phase 3E): is `to` visible from `from`? Ends with an `altitude` use it (metres * above sea level); ends without stand on the ground plus a height (default 2 m). The ground comes from * sampleElevation (Earth curvature and refraction included); it rejects with MISSING_CAPABILITY without ground * heights. Large-area visibility (viewsheds) belongs to a server (§77). */ lineOfSight(from: Position, to: Position, options?: LineOfSightOptions): Promise; destroy(): void; readonly state: RuntimeState; getViewport(): MapViewport; /** Screen pixel (relative to the map container) of a position, or null when the renderer cannot say. */ project(position: Position): { x: number; y: number; } | null; /** Call when the container size changed; the renderer re-measures and the visible area is re-queried. */ resize(): void; setViewport(viewport: MapViewport, options?: { animate?: boolean; }): void; fitBounds(bounds: BoundingBox, options?: { padding?: Padding; animate?: boolean; }): void; /** * Moves the camera to an object (by id) or a position (doc §35: search → flyTo → select). A point is centred; * a line or area is framed. An object not loaded on the client is asked from the provider. Resolves false when * the object does not exist (or is not authorized). Does not select: call selectObject() for that. */ flyTo(to: string | Position, options?: FlyToOptions): Promise; getLayers(): MapLayer[]; addLayer(layer: MapLayer): void; updateLayer(id: string, patch: Partial>): void; removeLayer(id: string): void; setLayerVisibility(id: string, visible: boolean): void; setLayerZIndex(id: string, zIndex: number): void; selectObject(objectId: string, source?: string): void; clearSelection(source?: string): void; /** Controlled mode: the application owns selection and pushes it in. */ setSelection(selection: Pick & { primaryObjectId?: string; }): void; getSelection(): SelectionContext; /** Pause or resume click-to-select (e.g. while an application tool uses clicks). Default: enabled. */ setSelectable(enabled: boolean): void; getScene(): SceneState; /** An object currently loaded on the client (not a data query). */ getObject(objectId: string): SpatialObject | undefined; /** Details of a loaded object for an inspector (doc §34), reported as `objectInspected`; undefined when not loaded. */ inspect(objectId: string, source?: string): ObjectInspection | undefined; /** Filters objects already loaded on the client. For data beyond the viewport, use query(). */ queryLoaded(query: SpatialQuery): SpatialObject[]; /** Runs a spatial query through the provider (authorized data only), validated, and reports it (`spatialQuery`). */ query(query: SpatialQuery, signal?: AbortSignal): Promise; /** * Starts drawing (doc §37). Map clicks add points and do not select. Point, rectangle and circle finish by * themselves; lines and polygons finish with finishDrawing(). The result arrives as `geometryDrawn`. */ startDrawing(kind: DrawKind): void; /** Adds a point as if the map was clicked there (keyboard input, snapping, tests). */ addDrawingPoint(position: Position): void; undoDrawingPoint(): void; /** Finishes and returns the geometry, or null when there are too few points (drawing continues). */ finishDrawing(): Geometry | null; cancelDrawing(): void; getDrawing(): DrawingState | null; /** Re-query every visible layer now. */ refresh(): Promise; /** Resolves when no query is scheduled or in flight. */ whenIdle(): Promise; /** What the engine is doing: plans, provider calls, realtime throughput. For dev tools and observability (doc 18). */ getStats(): MapRuntimeStats; /** * Live, or the world as it was at a time (replay). The application owns time (ADR-010): it calls this from its * timeline or a Playback. Replay fetches tracks for the range once; moving `at` inside it only re-interpolates. */ setTime(time: TimeSetting): void; getTime(): TimeState; /** Replaces the geofences (doc 15). Client evaluation is for display; authoritative alerts are server-side. */ setGeofences(geofences: Geofence[]): void; getGeofences(): Geofence[]; /** Live: recent transitions. Replay: transitions over the replay range up to the replay time. Newest first. */ getGeofenceEvents(limit?: number): GeofenceEvent[]; /** Which objects are inside each geofence now (live) or at the replay time. */ getGeofenceOccupancy(): Record; /** Length, area and bearing of a geometry, on the ground (doc 28 G9). */ measure(geometry: Geometry): Measurement; /** Where an id stands for this user, for object references in text (doc 28 G8). */ resolveReference(objectId: string): Promise; /** What each layer shows right now (doc 28 G13): denied layers say so instead of failing. */ getLayerStatus(layerId: string): LayerStatus | undefined; /** Who is looking: handed to every provider that accepts it, then the map reloads with what they return. */ setAuth(auth: AuthContext | null): void; /** Emphasis on objects without changing the selection, for a while or until cleared (doc 28 G7). */ highlight(objectIds: string[], options?: { durationMs?: number; color?: string; origin?: string; }): void; clearHighlight(): void; getHighlight(): Highlight | null; /** A suggested geometry, drawn as "not confirmed" (doc 28 G7). Returns it with its id. */ propose(proposal: { geometry: Geometry; label?: string; note?: string; origin?: string; id?: string; }): Proposal; /** A person confirms a proposal: it becomes an annotation (saved through deps.annotations when there is one). */ acceptProposal(id: string, options?: { by?: string; label?: string; }): Promise; /** A person turns a proposal down: it leaves the map; the rejection is an event its origin can read. */ rejectProposal(id: string, options?: { by?: string; reason?: string; }): void; getProposals(): Proposal[]; /** Removes proposals (all, or those from one origin). */ clearProposals(origin?: string): void; /** First-class annotations (doc 29 §5): drawn by the engine, kept by deps.annotations when there is one. */ addAnnotation(annotation: Omit & { id?: string; }, origin?: string): Promise; updateAnnotation(id: string, patch: Partial>, origin?: string): Promise; removeAnnotation(id: string, origin?: string): Promise; getAnnotations(): Annotation[]; /** Shows or hides the annotations (they stay kept and selectable through the API). Default shown. */ setAnnotationsVisible(visible: boolean): void; /** * Runs map commands (doc 28 G6) as one unit: checked first, then applied in order, or refused whole. Each run is * an auditable `command` event with its origin (default 'user'). */ execute(commands: MapCommand | MapCommand[], options?: { origin?: string; }): Promise; /** The event journal for a query and range, straight from deps.journal (MISSING_CAPABILITY without one). */ getJournal(query: SpatialQuery, range: TimeRange, signal?: AbortSignal): Promise; on(event: K, listener: (payload: MapRuntimeEvents[K]) => void): Unsubscribe; }