Developer documentation
The app is plain HTML, CSS, and JavaScript with locally vendored MapLibre GL JS 5.6.1 and PMTiles 4.3.0. Static per-year tiles provide display geometry. Anonymous ArcGIS queries provide search and attributes; ArcGIS prepares download files. No application backend or runtime build step is required.
Service endpoints
Configured in js/config.js, using layer 0:
https://services2.arcgis.com/wx8u046p68e0iGuj/arcgis/rest/services/Aligned_Cliopatria_v1_2_WGS84/FeatureServer
Feature service metadata · Layer 0 metadata · Local display manifest
API requirements
This section defines the services, parameters, responses, and failure behavior required by the current website. The browser talks directly to the public ArcGIS feature service. Map display uses PMTiles; research exports use the source feature service and retain whole polygons.
Access and service capabilities
- The feature service and layer 0 must allow anonymous queries and extraction over HTTPS, with CORS permitting requests from the website. Data requests use
credentials: 'omit'and do not send an ArcGIS account token. - The app requires
QueryandExtract, distinct Name queries for suggestions, ordered and paginated attribute queries, and the nine fields below. Before each export, it checksExtractand the requested format insupportedExportFormats. - Extraction uses
syncModel=none. Editing and attachments are not required. The public Esri basemap key is a separate dependency; it is not used to authorize feature queries or downloads.
Metadata checked November 24, 2026: the service advertises Query and Extract, all four requested formats, and a 2,000-record query limit. Layer 0 supports pagination and ordering, has no attachments, and reports no timeInfo. Recheck these settings when replacing or republishing the source.
Requests and responses
Here, serviceUrl means the FeatureServer URL. ArcGIS metadata, query, and job requests include f=json. POST bodies are form-encoded with URLSearchParams; JSON-valued fields such as layerQueries are serialized inside that form body.
| Request | Purpose and required response |
|---|---|
GET data/manifest.json | Available years, tile paths, counts, and release metadata. The manifest must be complete and contain available years. |
GET data/years/{year}.pmtileswith a Range header | Tile bytes needed for the selected year and view; the entire research dataset is not loaded for map display. |
GET data/polity-display/{year}.json | One label point per named polity. The browser checks the snapshot year and source hash before displaying the points. |
GET serviceUrl?f=json | capabilities and supportedExportFormats, checked before extraction. |
POST serviceUrl/0/query | Count: {count}. IDs: {objectIds}. Search or selected record: {features: [{attributes}]}. Zoom-to-feature: {extent}. |
POST serviceUrl/createReplica | Start an export. Expect a statusUrl for an asynchronous job, or a completed file URL. |
GET returned statusUrl | Read status until Completed, then obtain resultUrl. The client also accepts URL or url for a completed response. |
GET returned file URL | The visitor follows the Download link directly to Esri. Application JavaScript does not fetch and assemble the export file in memory. |
Search uses returnGeometry=false, the nine fields, resultRecordCount=25, and a changing resultOffset. Stable ordering is Name ASC,Year ASC,AreaSqKM DESC,OBJECTID ASC. Counts and IDs use returnCountOnly=true and returnIdsOnly=true. Feature extents use returnExtentOnly=true and outSR=4326. See the Esri Query reference.
Name suggestions use the same /0/query endpoint with outFields=Name, returnGeometry=false, returnDistinctValues=true, orderByFields=Name ASC, and resultRecordCount=12. Focusing or clicking the field requests names for the selected search scope, including an empty field. Null and empty names are excluded. The default list displays at most six names alphabetically. Typing updates matches after a 300 ms pause, with no minimum length; names starting with the input are preferred among the returned candidates. Superseded requests are aborted; suggestion requests time out after ten seconds. Choosing a suggestion runs the ordinary partial-name search. See Search instructions.
Selection and time rules
| Scope | Selection rule |
|---|---|
| Map selection | Use the hosted OBJECTIDs of every record in the selected polity and snapshot. Unnamed polygons and features of other types each use one OBJECTID. The export retains each original polygon. |
| Current search results | Use the submitted Name predicate and time scope. Include all matches, beyond the loaded search page. |
| Year or year range | Use Year = 117 or inclusive bounds such as Year >= -3400 AND Year <= -1. Include available snapshots within those bounds. |
| Visible map extent | Combine the time predicate with intersection against the map rectangle captured when Prepare download is pressed. Keep each intersecting polygon whole. |
| Entire dataset | Use 1=1 for the count. Omit layerQueries and spatial filters from extraction. |
Year is a snapshot field, not a start/end validity interval. Negative values mean BCE; there is no year zero. The app rejects zero endpoints, noninteger years, reversed ranges, and ranges outside the manifest. It does not interpolate geometry or use ArcGIS's time parameter. A range crossing BCE and CE includes existing panels on both sides.
For ordinary extents, the app first queries intersecting IDs using WGS84 envelopes and spatialRel=esriSpatialRelIntersects. Extraction then uses a native Web Mercator envelope with inSR=3857, keeping replicaSR=4326 for output. Native coordinates are necessary for this service's tested KMZ route; a WGS84 export filter produced an empty KMZ during validation. The filter selects whole polygons without clipping.
Antimeridian-crossing views use two ID queries and deduplicate results. Exact ID ranges and short IN lists describe that selection; oversized filters become numbered export parts. If every feature in the period intersects the view, the time predicate alone is sufficient. Later map movement does not alter an export already submitted.
How a download is prepared
- Capture and count the selection.
prepareDownload()captures the scope, format, period, and selected record IDs or map bounds. It counts matches and reports an empty selection before starting a job. - Check the service.
exportFile()reads metadata and verifies extraction and format support. - Submit the job. POST to
/createReplicawith the parameters below. Filtered exports includelayerQueries; full-dataset exports omit it. - Wait for completion. Follow the returned
statusUrl, waiting two seconds between pending responses. The map remains usable. - Display the file link. Validate the returned URL and assign it to the Download link. Numbered parts each receive a link when splitting was necessary.
- Download the file. Prepare download creates the link; the visitor then clicks Download. Generate it again if the temporary link expires.
This example requests all BCE panels as GeoJSON. These values become a URLSearchParams form body, not a raw JSON body. f=json controls the API response; dataFormat=geojson controls the downloadable file.
const parameters = {
f: 'json',
replicaName: 'cliopatria_export',
layers: 0,
syncModel: 'none',
returnAttachments: false,
replicaSR: 4326,
dataFormat: 'geojson',
transportType: 'esriTransportTypeUrl',
async: true,
layerQueries: JSON.stringify({
'0': {
where: 'Year >= -3400 AND Year <= -1',
queryOption: 'useFilter',
useGeometry: true
}
})
};
The initial response supplies a statusUrl. A completed job supplies status: 'Completed' and a resultUrl. Use the returned URLs; do not construct job or file paths. The tested public route requires no visitor login and creates no separate permanent ArcGIS Online content item. See the Esri Create Replica reference.
| Interface option | dataFormat | Contents |
|---|---|---|
| GeoJSON | geojson | Geometry and attributes in WGS84 longitude/latitude. |
| CSV | csv | Attributes, without polygon geometry. |
| KMZ | kml | Compressed KML for Google Earth. |
| Shapefile | shapefile | ZIP containing Shapefile components. |
See the user documentation for tested format limitations, including KMZ styling and source OBJECTID preservation. The 2,000-record query limit does not define the record count allowed in an extraction file.
Errors and operational limits
- Check HTTP success and any ArcGIS
errorobject inside the JSON response. HTTP 200 alone does not mean success. - Export statuses
Failed,CompletedWithErrors,Cancelled, andCanceledstop the wait and display an error. A completed response without a URL is also an error. Status and file URLs must use HTTPS and a hostname ending in.arcgis.com. - Search and feature lookups have 30-second client timeouts; export preparation has a 15-minute client timeout. Stop waiting aborts browser requests and polling, but does not cancel the Esri job.
- Job duration varies; the polling delay is not a completion estimate. Errors require manual retry. The app does not automatically resubmit jobs or retain job history across reloads. Completed parts remain available if a later part fails.
Production checks should verify anonymous requests and CORS from the deployed origin, each format and scope, byte-range delivery, mobile behavior, and capacity under expected traffic. These requirements do not establish a high-traffic performance guarantee. A future queue, durable job history, or download-serving audit would require additional infrastructure.
Field dictionary
| Field | Type | Meaning |
|---|---|---|
| OBJECTID | OID | Release-specific record ID; may be renumbered. |
| Year | Small integer | Panel year. Negative is BCE; no zero; snapshots are not validity intervals. |
| AreaSqKM | Single precision | Publisher-calculated geodesic area in km². |
| Name | String | Entity name. Some region names are intentionally blank. |
| Color | String | Source 0xRRGGBB color, normalized to #RRGGBB in tiles; null fallback #82939A. |
| Type | String | POLITY, LEADER, GROUP, ARMY, EVENT, or missing. |
| Wikidata | String | Wikidata item ID from upstream Cliopatria v0.2.1, when available. |
| SeshatID | String | Seshat polity identifier from the same upstream release, when available. |
| Wikipedia | String | Article title; converted to an encoded Wikipedia link. |
Shape__Area and Shape__Length are service system fields, not substitutes for AreaSqKM. Dedicated alternate-name and region fields are absent. Name + Year is not a unique record key: several polygons can share both values.
Sample queries
Count the 3400 BCE panel · Get that panel as GeoJSON
For a range, use Year >= 1000 AND Year <= 1497. For search, use UPPER(Name) LIKE '%ROMAN%'. Escape apostrophes as doubled apostrophes and validate numeric IDs and years. The current Name filter retains SQL LIKE wildcards % and _. The helpers in js/lib/core.js build these predicates.
These direct query examples inspect a panel. For large downloads, use extraction. Paginate feature queries with a stable order, or query IDs; do not assume a single feature-set response contains every match.
Hosting and data releases
PMTiles hosting needs byte-range responses (206 Partial Content) with correct Content-Range. Separate tile hosting also needs CORS. Do not gzip whole PMTiles files at the HTTP layer. See PMTiles hosting documentation. For local testing, open index.html with Live Server.
The v1.2 tiles use geometry from the published GeoJSON and OBJECTIDs from the v1.2 feature service. The ZIP and service number polygons independently. The build matched records by year, attributes and area, using geometry bounds to resolve ties. For records with identical attributes and geometry, the build kept every copy and assigned each a distinct hosted ID. The manifest records the ZIP and GeoJSON SHA-256 hashes. Match the tile manifest and feature service to the same release. Rebuild after source revisions, especially OBJECTID renumbering. The selected record's year check cannot detect every source change. This folder contains the runnable website; preparation scripts and review reports are maintained separately.
Polity label placement
Within each snapshot, the label builder groups POLITY records by exact Name and chooses the highest AreaSqKM. Equal areas use the lower OBJECTID in the release GeoJSON. The point sits inside the winning polygon. For a multipart record, it sits inside the part with the largest geodesic area.
Regenerate the label points with Python 3.11 or later and the ijson, pyproj and shapely packages. Run python scripts/build_polity_display.py path/to/release.zip from the project root. The script also accepts the extracted GeoJSON and checks its SHA-256 against the map manifest.
When a different feature type shares a polity’s name in the same snapshot, the polity supplies the label. A click on a named polity or one of its search results queries the v1.2 service for the same year, exact name and POLITY type. The client checks the exact spelling and the clicked OBJECTID. The returned hosted IDs drive highlights, record counts, search selection extents and exports, including polygons outside the viewport.
Code reference
| File | Responsibility |
|---|---|
| js/config.js | Service URL, layer ID, manifest path, and display settings. |
| js/lib/api.js | jsonRequest(): fetch and response checks. DataService: counts, name suggestions, search, feature details, and extent queries. exportFile(): createReplica POST, status polling, and returned file URL. |
| js/lib/core.js | Year, Name, and ID predicates; format mapping; extent splitting and coordinate conversion. |
| js/app.js | prepareDownload(): capture the selection, count records, manage waiting and parts, call exportFile(), and set the Download link's href. |
| js/lib/map.js | PMTiles display, basemap styles, selection, and view bounds. |