A secure, type-safe utility library for OpenLayers that allows you to serialize and deserialize map objects. Easily transfer map state, layers, views, and features between frontend and backend, or save and restore map configurations.
- π Security First: Eliminated
eval()usage with safe function serialization - π‘οΈ Input Validation: Comprehensive data validation using Zod schemas
- π§ Error Recovery: Robust error handling with graceful fallbacks
- β Fully Tested: 59 unit tests with 90%+ coverage on core modules
- π TypeScript: Complete type safety and IntelliSense support
- π Serialization: Convert
ol.Map,ol.View,ol.layer.*,ol.source.*, andol.Featureinto JSON - π¦ Deserialization: Rebuild OpenLayers objects from JSON with validation
- π― Supports Map, View, Layers, Sources, and Features
- π Secure: Safe function serialization without
eval()risks - π‘οΈ Validated: Input validation and error recovery mechanisms
- πΎ Perfect for saving map configurations or data exchange
npm install openlayers-serializer
# or
yarn add openlayers-serializer
# or
pnpm add openlayers-serializerimport { serializeMap, deserializeMap } from "openlayers-serializer";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
// Create a map
const map = new Map({
view: new View({
center: [0, 0],
zoom: 2,
}),
layers: [
new TileLayer({
source: new OSM(),
}),
],
});
// Serialize map to JSON (secure, validated)
const mapData = serializeMap(map);
console.log("Serialized:", mapData);
// Save to localStorage (example)
localStorage.setItem('myMap', JSON.stringify(mapData));
// Restore map from JSON (with validation)
const savedData = JSON.parse(localStorage.getItem('myMap'));
const restoredMap = deserializeMap(savedData);
console.log("Restored:", restoredMap);import { deserializeMap, ValidationError, DeserializationError } from "openlayers-serializer";
try {
const map = deserializeMap(mapData);
} catch (error) {
if (error instanceof ValidationError) {
console.error("Invalid map data:", error.message);
} else if (error instanceof DeserializationError) {
console.error("Failed to create map:", error.message);
// Error includes context and suggestions
console.log("Context:", error.context);
console.log("Suggestions:", error.suggestions);
}
}<!DOCTYPE html>
<html>
<head>
<title>OpenLayers Serializer Demo</title>
<script type="module">
import { createDemoMap, exportMapData, importMapData } from './dist/openlayers-serializer.es.js';
// Create demo map
const map = createDemoMap();
// Export map data
window.exportMap = () => exportMapData();
// Import map data
window.importMap = () => importMapData();
</script>
</head>
<body>
<div id="map" style="width: 100%; height: 500px;"></div>
<button onclick="exportMap()">Export Map</button>
<button onclick="importMap()">Import Map</button>
</body>
</html># Install dependencies
pnpm install
# Run development server
pnpm dev
# Build for production
pnpm build
# Run tests
pnpm test
# Run tests with coverage
pnpm test:coverage
# Run tests with UI
pnpm test:ui- Total Tests: 59 tests, all passing β
- Core Modules: 90%+ test coverage
- Security: No
eval()usage, safe function serialization - Validation: Comprehensive input validation with Zod
Convert an OpenLayers Map instance into a serializable object.
Parameters:
map: Map- OpenLayers Map instance
Returns: Serialized map data object
Rebuild an OpenLayers Map instance from serialized data.
Parameters:
data: IMap- Serialized map data (validated automatically)
Returns: OpenLayers Map instance
Throws:
ValidationError- If input data is invalidDeserializationError- If map creation fails
Safely serialize functions without eval() risks.
Safely deserialize functions with validation.
| Category | Supported Types | Count |
|---|---|---|
| Map | ol/Map |
1 |
| View | ol/View |
1 |
| Layers | Tile, Vector, Image, Heatmap, Group (recursive) |
5 |
| Sources | Core (9) + Advanced (5) + Extended (7) | 21 |
| Features | ol/Feature (with geometry) |
1 |
| Styles | Style, Fill, Stroke, Circle, Icon, Text |
6+ |
- β TileLayer - Raster tile layers
- β VectorLayer - Vector feature layers with style support
- β ImageLayer - Static and dynamic image layers
- β HeatmapLayer - Heatmap visualization with gradients
- β GroupLayer - Hierarchical layer groups with recursive serialization
Core Sources (9):
- β OSM - OpenStreetMap tiles
- β XYZ - Generic XYZ tile sources
- β BingMaps - Bing Maps aerial/road tiles
- β StadiaMaps - Stadia Maps (formerly Stamen)
- β TileDebug - Debug tile boundaries
- β TileWMS - OGC WMS tile service
- β Vector - GeoJSON and other vector formats
- β ImageStatic - Static georeferenced images
- β IIIF - International Image Interoperability Framework
Advanced Sources (5):
- β Cluster - Point clustering with configurable distance
- β GeoTIFF - Cloud Optimized GeoTIFF
- β VectorTile - Mapbox Vector Tiles (MVT)
- β WMTS - OGC Web Map Tile Service
- β UTFGrid - Interactive UTF grid layers
Extended Sources (7):
- β TileJSON - TileJSON specification tiles
- β Zoomify - Zoomify image pyramids
- β OGCMapTile - OGC Map Tile API
- β ImageArcGISRest - ArcGIS REST image services
- β ImageWMS - WMS image services
- β OGCVectorTile - OGC Vector Tile API
- β TileArcGISRest - ArcGIS REST tile services
- β No
eval(): Eliminates code injection risks - β Function Registry: Pre-approved function whitelist
- β Parser-based: Safe function parsing and reconstruction
- π‘οΈ Zod Schemas: Runtime type validation
- π Data Sanitization: Automatic data cleaning and fixing
β οΈ Error Recovery: Graceful handling of invalid data
- π Structured Errors: Detailed error context and suggestions
- π Fallback Mechanisms: Automatic recovery strategies
- π Comprehensive Logging: Debug-friendly error messages
src/
βββ common/ # Core utilities
β βββ safe-functions.ts # Secure function serialization
β βββ error-handling.ts # Error recovery system
β βββ validation.ts # Zod validation schemas
β βββ registry.ts # Function registry
βββ serializer/ # Serialization logic
β βββ map.ts # Map serialization
β βββ view.ts # View serialization
β βββ layer.ts # Layer serialization
β βββ source.ts # Source serialization
βββ dto/ # Type definitions
β βββ *.ts # Interface definitions
βββ examples/ # Demo code
βββ demo.ts # Usage examples
# Run all tests
pnpm test
# Run with coverage report
pnpm test:coverage
# Run tests in watch mode
pnpm test:ui- Total: 59 tests, all passing β
- Coverage: 90%+ on core modules
- Security: No
eval()usage detected - Validation: All edge cases covered
eval()removed - functions now use safe serialization- Validation required - invalid data will throw errors
- Error handling changed - new error types with context
- Update imports: Error classes now available from main package
- Add error handling: Wrap deserialization in try-catch blocks
- Review custom functions: Ensure compatibility with safe serialization
- Test thoroughly: Validate existing serialized data
// v1.x (deprecated)
const map = deserializeMap(data); // Risky, no validation
// v2.x (recommended)
try {
const map = deserializeMap(data); // Safe, validated
} catch (error) {
if (error instanceof ValidationError) {
console.error("Data validation failed:", error.message);
}
}- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Run tests (
pnpm test) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
- π§ͺ Tests Required: All new features must include tests
- π Security First: No
eval()or unsafe practices - π Documentation: Update README for API changes
- π― TypeScript: Maintain strict type safety
MIT License Β© 2025 rgbcmy
This project uses OpenLayers which is licensed under the BSD 2-Clause License.
- OpenLayers - The amazing mapping library
- Vite - Lightning fast build tool
- Vitest - Delightful testing framework
- Zod - TypeScript-first schema validation