From 45628f45c645bf953c1213debb4defe4648fa7bb Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Wed, 29 May 2024 08:39:43 +0200 Subject: [PATCH 01/17] fgb new layerId --- R/file.R | 4 ++-- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/R/file.R b/R/file.R index 58482df..b4177af 100644 --- a/R/file.R +++ b/R/file.R @@ -392,7 +392,7 @@ addFgb = function(map, } path_layer = tempfile() dir.create(path_layer) - path_layer = paste0(path_layer, "/", layerId, "_layer.fgb") + path_layer = paste0(path_layer, "/", group, "_layer.fgb") file.copy(file, path_layer, overwrite = TRUE) @@ -417,7 +417,7 @@ addFgb = function(map, map$dependencies = c( map$dependencies - , fileAttachment(path_layer, layerId) + , fileAttachment(path_layer, group) ) if (!is.null(minZoom)) { diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index d69399d..5503f78 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -12,7 +12,7 @@ function mouseHandler(mapId, layerId, group, eventName, extraInfo) { } let eventInfo = $.extend( { - id: layerId, + id: e.layer.feature.properties[layerId].toString(), ".nonce": Math.random() // force reactivity }, group !== null ? {group: group} : null, @@ -45,7 +45,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, pane = options.pane; } - var data_fl = document.getElementById(layerId + '-1-attachment'); + var data_fl = document.getElementById(group + '-1-attachment'); if (data_fl === null) { data_fl = url; @@ -130,6 +130,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, }, {sticky: true}); } } + lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); From a79ef17e6de53ed5c1abeeb3e5a50ba8ae99abb4 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Tue, 11 Jun 2024 14:38:31 +0200 Subject: [PATCH 02/17] fix: id can be single string or property name --- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index 5503f78..06db9e4 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -12,7 +12,7 @@ function mouseHandler(mapId, layerId, group, eventName, extraInfo) { } let eventInfo = $.extend( { - id: e.layer.feature.properties[layerId].toString(), + id: (e.layer.feature.properties[layerId]?.toString() ?? layerId.toString()), ".nonce": Math.random() // force reactivity }, group !== null ? {group: group} : null, From 475f584f8c73174acc9ea2c9c56cf29ce15fac6c Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Tue, 11 Jun 2024 14:39:08 +0200 Subject: [PATCH 03/17] stash.. not working --- R/file.R | 4 ++++ inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 25 ++++++++++++++----------- man/addRasterRGB.Rd | 2 +- man/addStarsImage.Rd | 8 ++++---- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/R/file.R b/R/file.R index b4177af..dc69530 100644 --- a/R/file.R +++ b/R/file.R @@ -424,6 +424,8 @@ addFgb = function(map, if (is.null(maxZoom)) { maxZoom = 19 } + print("!is.null(file)") + print("addFlatGeoBufFiltered") leaflet::invokeMethod( map , leaflet::getMapData(map) @@ -480,6 +482,8 @@ addFgb = function(map, if (is.null(maxZoom)) { maxZoom = 19 } + print("file = NULL") + print("addFlatGeoBufFiltered") leaflet::invokeMethod( map , leaflet::getMapData(map) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index 06db9e4..83db3b4 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -296,13 +296,15 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, var gl = false; var pane; + console.log("addFlatGeoBufFiltered") + if (options === null || options.pane === undefined) { pane = 'overlayPane'; } else { pane = options.pane; } - var data_fl = document.getElementById(layerId + '-1-attachment'); + var data_fl = document.getElementById(group + '-1-attachment'); if (data_fl === null) { data_fl = url; @@ -331,24 +333,25 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, } var previousResults = previousResults || {}; - previousResults[layerId] = L.layerGroup(); - map.layerManager.addLayer(previousResults[layerId], null, layerId, group); + previousResults[group] = L.layerGroup(); + map.layerManager.addLayer(previousResults[group], null, layerId, group); async function updateResults() { + console.log("updateResults") var nextResults = nextResults || {}; - nextResults[layerId] = L.layerGroup(); - map.layerManager.addLayer(nextResults[layerId], null, layerId, group); + nextResults[group] = L.layerGroup(); + map.layerManager.addLayer(nextResults[group], null, layerId, group); // remove the old results - map.layerManager.removeLayer(previousResults[layerId], layerId); - // previousResults[layerId].remove(); - previousResults[layerId] = nextResults[layerId]; + map.layerManager.removeLayer(previousResults[group], layerId); + // previousResults[group].remove(); + previousResults[group] = nextResults[group]; // Use flatgeobuf JavaScript API to iterate features as geojson. // Because we specify a bounding box, flatgeobuf will only fetch the resubset of data, // rather than the entire file. const iter = flatgeobuf.deserialize(data_fl, fgBoundingBox(), handleHeaderMeta); - if (map.getZoom() >= minZoom & map.getZoom() <= maxZoom & map.hasLayer(previousResults[layerId])) { + if (map.getZoom() >= minZoom & map.getZoom() <= maxZoom & map.hasLayer(previousResults[group])) { for await (const feature of iter) { if (popup) { pop = makePopup(popup, className); @@ -401,7 +404,7 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); - lyr.addTo(nextResults[layerId]); + lyr.addTo(nextResults[group]); } } } @@ -416,7 +419,7 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, updateResults(); }); map.on('layeradd', function(event) { - if(event.layer == previousResults[layerId]) { + if(event.layer == previousResults[group]) { updateResults(); } }); diff --git a/man/addRasterRGB.Rd b/man/addRasterRGB.Rd index 5b665e3..edfbb52 100644 --- a/man/addRasterRGB.Rd +++ b/man/addRasterRGB.Rd @@ -55,7 +55,7 @@ based on min-max values.} \item{method}{the method used for computing values of the new, projected raster image. \code{"bilinear"} (the default) is appropriate for continuous data, \code{"ngb"} - nearest neighbor - is appropriate for categorical data. -Ignored if \code{project = FALSE}. See \code{\link{projectRaster}} for details.} +Ignored if \code{project = FALSE}. See \code{\link[=projectRaster]{projectRaster()}} for details.} \item{...}{additional arguments passed on to \code{\link{addRasterImage}}} } diff --git a/man/addStarsImage.Rd b/man/addStarsImage.Rd index 4efe783..8c895e2 100644 --- a/man/addStarsImage.Rd +++ b/man/addStarsImage.Rd @@ -28,7 +28,7 @@ addStarsImage( \item{band}{the band number to be plotted.} -\item{colors}{the color palette (see \code{\link[leaflet]{colorNumeric}}) or function +\item{colors}{the color palette (see \code{\link[leaflet:colorNumeric]{colorNumeric()}}) or function to use to color the raster values (hint: if providing a function, set \code{na.color} to \code{"#00000000"} to make \code{NA} areas transparent). The palette is ignored if \code{x} is a SpatRaster with a color table or if @@ -41,7 +41,7 @@ it has RGB channels.} \item{layerId}{the layer id} \item{group}{the name of the group this raster image should belong to (see -the same parameter under \code{\link[leaflet]{addTiles}})} +the same parameter under \code{\link[leaflet:addTiles]{addTiles()}})} \item{project}{if \code{TRUE}, automatically project \code{x} to the map projection expected by Leaflet (\code{EPSG:3857}); if \code{FALSE}, it's @@ -52,13 +52,13 @@ coordinates} \item{method}{the method used for computing values of the new, projected raster image. \code{"bilinear"} (the default) is appropriate for continuous data, \code{"ngb"} - nearest neighbor - is appropriate for categorical data. -Ignored if \code{project = FALSE}. See \code{\link{projectRaster}} for details.} +Ignored if \code{project = FALSE}. See \code{\link[=projectRaster]{projectRaster()}} for details.} \item{maxBytes}{the maximum number of bytes to allow for the projected image (before base64 encoding); defaults to 4MB.} \item{options}{a list of additional options, intended to be provided by -a call to \code{\link[leaflet]{gridOptions}}} +a call to \code{\link[leaflet:gridOptions]{gridOptions()}}} \item{data}{the data object from which the argument values are derived; by default, it is the \code{data} object provided to \code{leaflet()} From 9d66c8fddcbc4bd6a473fcbade153e523e124a41 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Tue, 11 Jun 2024 22:39:42 +0200 Subject: [PATCH 04/17] fix: fgb filter, use group for attachments --- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 157 +++++++++++++------------ 1 file changed, 81 insertions(+), 76 deletions(-) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index 83db3b4..b9ffe02 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -292,9 +292,9 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, minZoom, maxZoom) { - var map = this; - var gl = false; - var pane; + const map = this; + let gl = false; + let pane; console.log("addFlatGeoBufFiltered") @@ -304,7 +304,7 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, pane = options.pane; } - var data_fl = document.getElementById(group + '-1-attachment'); + let data_fl = document.getElementById(group + '-1-attachment'); if (data_fl === null) { data_fl = url; @@ -312,10 +312,13 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, data_fl = data_fl.href; } - var popUp; - var colnames = []; + let popUp; + let colnames = []; function handleHeaderMeta(headerMeta) { + const header = document.getElementById('header') + const formatter = new JSONFormatter(headerMeta, 10) + header.appendChild(formatter.render()) headerMeta.columns.forEach(function(col) { colnames.push(col.name); }); @@ -332,95 +335,97 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, }; } - var previousResults = previousResults || {}; + let previousResults = previousResults || {}; previousResults[group] = L.layerGroup(); map.layerManager.addLayer(previousResults[group], null, layerId, group); async function updateResults() { - console.log("updateResults") - var nextResults = nextResults || {}; - nextResults[group] = L.layerGroup(); - map.layerManager.addLayer(nextResults[group], null, layerId, group); - // remove the old results - map.layerManager.removeLayer(previousResults[group], layerId); - // previousResults[group].remove(); - previousResults[group] = nextResults[group]; - - // Use flatgeobuf JavaScript API to iterate features as geojson. - // Because we specify a bounding box, flatgeobuf will only fetch the resubset of data, - // rather than the entire file. - const iter = flatgeobuf.deserialize(data_fl, fgBoundingBox(), handleHeaderMeta); + + // remove the old results + map.layerManager.removeLayer(previousResults[group], layerId); + previousResults[group].remove(); + + let nextResults = nextResults || {}; + nextResults[group] = L.layerGroup(); + map.layerManager.addLayer(nextResults[group], null, layerId, group); + + previousResults[group] = nextResults[group]; + + // Use flatgeobuf JavaScript API to iterate features as geojson. + // Because we specify a bounding box, flatgeobuf will only fetch the resubset of data, + // rather than the entire file. + let iter = flatgeobuf.deserialize(data_fl, fgBoundingBox(), handleHeaderMeta); if (map.getZoom() >= minZoom & map.getZoom() <= maxZoom & map.hasLayer(previousResults[group])) { - for await (const feature of iter) { - if (popup) { - pop = makePopup(popup, className); - } else { - pop = null; - } - if (scaleFields === null & - feature.properties !== undefined) { - var vls = Object.values(style); - scaleFields = []; - vls.forEach(function(name) { - //if (name in colnames) { - if (colnames.includes(name)) { - scaleFields.push(true); - } else { - scaleFields.push(false); - } - }); - } + for await (let feature of iter) { - lyr = L.geoJSON(feature, { - pointToLayer: function (feature, latlng) { - return L.circleMarker(latlng, options); - }, - style: function(feature) { - return updateStyle(style, feature, scale, scaleFields); - }, - onEachFeature: pop, - pane: pane - }); + if (popup) { + pop = makePopup(popup, className); + } else { + pop = null; + } - if (label) { - if (Object.keys(feature.properties).includes(label)) { - lyr.bindTooltip(function (layer) { - return layer.feature.properties[label].toString(); - }, {sticky: true}); - } else if (typeof(label) === Object || (typeof(label) === 'object' && label.length > 1)) { - var lb = label[cntr]; - lyr.bindTooltip(function (layer) { - return(lb); - }, {sticky: true}); - } else { - lyr.bindTooltip(function (layer) { - return(label); - }, {sticky: true}); - } + if (scaleFields === null & feature.properties !== undefined) { + let vls = Object.values(style); + scaleFields = []; + vls.forEach(function(name) { + //if (name in colnames) { + if (colnames.includes(name)) { + scaleFields.push(true); + } else { + scaleFields.push(false); } + }); + } + + lyr = L.geoJSON(feature, { + pointToLayer: function (feature, latlng) { + return L.circleMarker(latlng, options); + }, + style: function(feature) { + return updateStyle(style, feature, scale, scaleFields); + }, + onEachFeature: pop, + pane: pane + }); + + if (label) { + if (Object.keys(feature.properties).includes(label)) { + lyr.bindTooltip(function (layer) { + return layer.feature.properties[label].toString(); + }, {sticky: true}); + } else if (typeof(label) === Object || (typeof(label) === 'object' && label.length > 1)) { + let lb = label[cntr]; + lyr.bindTooltip(function (layer) { + return(lb); + }, {sticky: true}); + } else { + lyr.bindTooltip(function (layer) { + return(label); + }, {sticky: true}); + } + } - lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); - lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); - lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); - lyr.addTo(nextResults[group]); + lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); + lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); + lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); + lyr.addTo(nextResults[group]); } } } - // if the user is panning around alot, only update once per second max - // updateResults = _.throttle(updateResults, 1000); // show results based on the initial map updateResults(); + // ...and update the results whenever the map moves map.on("moveend", function(s) { - //rectangle.setBounds(getBoundForRect()); - updateResults(); + updateResults(); }); map.on('layeradd', function(event) { - if(event.layer == previousResults[group]) { - updateResults(); - } -}); + if (event.layer == previousResults[group]) { + updateResults(); + } + }); + }; From 46d62753f55f271d07e3b0cc03468f4480160a63 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Wed, 12 Jun 2024 12:15:50 +0200 Subject: [PATCH 05/17] export useWebgl, load_chunks, leafgl works with #155 merged (inserts as array) --- R/file.R | 11 +++ inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 122 +++++++++++++++++++++++-- man/addFgb.Rd | 6 ++ man/addRasterRGB.Rd | 2 +- man/addStarsImage.Rd | 8 +- 5 files changed, 135 insertions(+), 14 deletions(-) diff --git a/R/file.R b/R/file.R index dc69530..064962c 100644 --- a/R/file.R +++ b/R/file.R @@ -305,6 +305,8 @@ addTileFolder = function(map, #' opacity, fillOpacity if those are to be mapped to an attribute column. #' @param minZoom minimum zoom level at which data should be rendered. #' @param maxZoom maximum zoom level at which data should be rendered. +#' @param useWebgl use `leafgl` if TRUE. +#' @param load_chunks How many features should be drawn/updated at once. Default is 1000 #' @param ... currently not used. #' #' @examples @@ -358,6 +360,8 @@ addFgb = function(map, scale = scaleOptions(), minZoom = NULL, maxZoom = 52, + useWebgl = FALSE, + load_chunks = 1000, ...) { @@ -444,6 +448,9 @@ addFgb = function(map, , maxZoom ) } else { + print("!is.null(file)") + print("addFlatGeoBuf") + leaflet::invokeMethod( map , leaflet::getMapData(map) @@ -458,6 +465,8 @@ addFgb = function(map, , className , scale , scaleFields + , useWebgl + , load_chunks ) } } else { @@ -516,6 +525,8 @@ addFgb = function(map, , className , scale , scaleFields + , useWebgl + , load_chunks ) } } diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index b9ffe02..6e7f458 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -24,6 +24,7 @@ function mouseHandler(mapId, layerId, group, eventName, extraInfo) { }; } + LeafletWidget.methods.addFlatGeoBuf = function (layerId, group, url, @@ -33,10 +34,12 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, options, className, scale, - scaleFields) { + scaleFields, + useWebgl, + load_chunks) { var map = this; - var gl = false; + var gl = useWebgl; var pane; if (options === null || options.pane === undefined) { @@ -66,18 +69,89 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, // use fgb JavaScript API to iterate stream into results (features as geojson) // NOTE: would be more efficient with a special purpose Leaflet deserializer let it = flatgeobuf.deserialize(response.body, undefined, handleHeaderMeta); - var cntr = 0; + let cntr = 0; + let chunkSize = load_chunks; + let shapeslayer = null; + let geojson_array = []; // handle result function handleResult(result) { if (!result.done) { if (gl) { - map.layerManager.addLayer( - L.glify.shapes({ - map: map, - data: result.value, - className: group - }).glLayer, null, null, group); + geojson_array.push(result.value); + console.log("Push Data"); + if (geojson_array.length === chunkSize) { + if (!shapeslayer || !shapeslayer.layer) { + // Initialize leaflet.glify with the first chunk + console.log("Initializing leaflet.glify with the first chunk"); + let data = { + type: "FeatureCollection", + features: geojson_array + }; + + var click_event = function(e, feature, addpopup, popup) { + if (map.hasLayer(shapeslayer.layer)) { + var idx = data.features.findIndex(k => k==feature); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(map.id + "_glify_click", { + id: layerId ? (typeof layerId === 'string' && + feature.properties.hasOwnProperty(layerId) ? + feature.properties[layerId] : layerId[idx]) : idx + 1, + group: Object.values(shapeslayer.layer._eventParents)[0].groupname, + lat: e.latlng.lat, + lng: e.latlng.lng, + data: feature.properties + }); + } + if (addpopup) { + let content = popup === true ? json2table(feature.properties) : (typeof popup === 'string' && + feature.properties.hasOwnProperty(popup) ? feature.properties[popup] : popup.toString()); + + L.popup({ maxWidth: 2000 }) + .setLatLng(e.latlng) + .setContent(content) + .openOn(map); + } + } + }; + var pop = function (e, feature) { + click_event(e, feature, popup !== null, popup); + }; + let tooltip = new L.Tooltip(); + let hover_event = function(e, feature, addlabel, label) { + if (map.hasLayer(shapeslayer.layer)) { + if (addlabel && feature.properties.hasOwnProperty(label)) { + tooltip + .setLatLng(e.latlng) + .setContent(feature.properties[[label]].toString()) + .addTo(map); + } + } + } + let hvr = function(e, feature) { + hover_event(e, feature, label !== null, label); + } + + shapeslayer = L.glify.shapes({ + map: map, + //color: () => {return {r: 1,g: 0,b: 0,}}, + click: pop, + hover: hvr, + border: true, + data: data, + className: group, + pane: pane + }); + map.layerManager.addLayer(shapeslayer.layer, "glify", layerId, group); + } else { + // Insert the collected chunk into the shapeslayer + console.log("Inserting new chunk into shapeslayer"); + shapeslayer.insert(geojson_array, cntr); + } + // Reset the array for the next chunk + geojson_array = []; + } it.next().then(handleResult); + } else { if (popup) { @@ -137,6 +211,33 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, map.layerManager.addLayer(lyr, null, null, group); it.next().then(handleResult); } + + } else if (geojson_array.length > 0) { + if (gl) { + console.log("Processing remaining features, geojson_array length:", geojson_array.length); + // Insert any remaining features in geojson_array when done + if (!shapeslayer || !shapeslayer.layer) { + console.log("Draw single chunk"); + shapeslayer = L.glify.shapes({ + map: map, + data: { + type: "FeatureCollection", + features: geojson_array + }, + className: group, + pane: pane + }); + map.layerManager.addLayer(shapeslayer.layer, "glify", layerId, group); + } else { + console.log("Inserting remaining chunk into shapeslayer"); + shapeslayer.insert(geojson_array, cntr); + /* + geojson_array.forEach((feature, index) => { + shapeslayer.insert(feature, cntr + index); + }); + */ + } + } } cntr += 1; } @@ -336,10 +437,13 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, } let previousResults = previousResults || {}; + console.log("previousResults");console.log(previousResults) previousResults[group] = L.layerGroup(); + console.log("previousResults[group]");console.log(previousResults[group]) map.layerManager.addLayer(previousResults[group], null, layerId, group); async function updateResults() { + console.log("updateResults") // remove the old results map.layerManager.removeLayer(previousResults[group], layerId); diff --git a/man/addFgb.Rd b/man/addFgb.Rd index 32923ae..3a39be2 100644 --- a/man/addFgb.Rd +++ b/man/addFgb.Rd @@ -26,6 +26,8 @@ addFgb( scale = scaleOptions(), minZoom = NULL, maxZoom = 52, + useWebgl = FALSE, + load_chunks = 1000, ... ) } @@ -80,6 +82,10 @@ opacity, fillOpacity if those are to be mapped to an attribute column.} \item{maxZoom}{maximum zoom level at which data should be rendered.} +\item{useWebgl}{use `leafgl` if TRUE.} + +\item{load_chunks}{How many features should be drawn/updated at once. Default is 1000} + \item{...}{currently not used.} } \description{ diff --git a/man/addRasterRGB.Rd b/man/addRasterRGB.Rd index edfbb52..5b665e3 100644 --- a/man/addRasterRGB.Rd +++ b/man/addRasterRGB.Rd @@ -55,7 +55,7 @@ based on min-max values.} \item{method}{the method used for computing values of the new, projected raster image. \code{"bilinear"} (the default) is appropriate for continuous data, \code{"ngb"} - nearest neighbor - is appropriate for categorical data. -Ignored if \code{project = FALSE}. See \code{\link[=projectRaster]{projectRaster()}} for details.} +Ignored if \code{project = FALSE}. See \code{\link{projectRaster}} for details.} \item{...}{additional arguments passed on to \code{\link{addRasterImage}}} } diff --git a/man/addStarsImage.Rd b/man/addStarsImage.Rd index 8c895e2..4efe783 100644 --- a/man/addStarsImage.Rd +++ b/man/addStarsImage.Rd @@ -28,7 +28,7 @@ addStarsImage( \item{band}{the band number to be plotted.} -\item{colors}{the color palette (see \code{\link[leaflet:colorNumeric]{colorNumeric()}}) or function +\item{colors}{the color palette (see \code{\link[leaflet]{colorNumeric}}) or function to use to color the raster values (hint: if providing a function, set \code{na.color} to \code{"#00000000"} to make \code{NA} areas transparent). The palette is ignored if \code{x} is a SpatRaster with a color table or if @@ -41,7 +41,7 @@ it has RGB channels.} \item{layerId}{the layer id} \item{group}{the name of the group this raster image should belong to (see -the same parameter under \code{\link[leaflet:addTiles]{addTiles()}})} +the same parameter under \code{\link[leaflet]{addTiles}})} \item{project}{if \code{TRUE}, automatically project \code{x} to the map projection expected by Leaflet (\code{EPSG:3857}); if \code{FALSE}, it's @@ -52,13 +52,13 @@ coordinates} \item{method}{the method used for computing values of the new, projected raster image. \code{"bilinear"} (the default) is appropriate for continuous data, \code{"ngb"} - nearest neighbor - is appropriate for categorical data. -Ignored if \code{project = FALSE}. See \code{\link[=projectRaster]{projectRaster()}} for details.} +Ignored if \code{project = FALSE}. See \code{\link{projectRaster}} for details.} \item{maxBytes}{the maximum number of bytes to allow for the projected image (before base64 encoding); defaults to 4MB.} \item{options}{a list of additional options, intended to be provided by -a call to \code{\link[leaflet:gridOptions]{gridOptions()}}} +a call to \code{\link[leaflet]{gridOptions}}} \item{data}{the data object from which the argument values are derived; by default, it is the \code{data} object provided to \code{leaflet()} From 593c976e474d3af5327d55e5f95e4261f4990b98 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Wed, 12 Jun 2024 15:26:27 +0200 Subject: [PATCH 06/17] expose highlightOptions (fake it for leafgl), hex2rgb-JS, initializeShapesLayer for GL --- R/file.R | 12 +- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 226 +++++++++++++++---------- man/addFgb.Rd | 7 +- 3 files changed, 152 insertions(+), 93 deletions(-) diff --git a/R/file.R b/R/file.R index 064962c..9111141 100644 --- a/R/file.R +++ b/R/file.R @@ -306,7 +306,8 @@ addTileFolder = function(map, #' @param minZoom minimum zoom level at which data should be rendered. #' @param maxZoom maximum zoom level at which data should be rendered. #' @param useWebgl use `leafgl` if TRUE. -#' @param load_chunks How many features should be drawn/updated at once. Default is 1000 +#' @param chunkSize How many features should be drawn/updated at once. Default is 1000 +#' @inheritParams leaflet::highlightOptions #' @param ... currently not used. #' #' @examples @@ -361,7 +362,8 @@ addFgb = function(map, minZoom = NULL, maxZoom = 52, useWebgl = FALSE, - load_chunks = 1000, + chunkSize = 1000, + highlightOptions = NULL, ...) { @@ -466,7 +468,8 @@ addFgb = function(map, , scale , scaleFields , useWebgl - , load_chunks + , chunkSize + , highlightOptions ) } } else { @@ -526,7 +529,8 @@ addFgb = function(map, , scale , scaleFields , useWebgl - , load_chunks + , chunkSize + , highlightOptions ) } } diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index 6e7f458..0747f5a 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -24,6 +24,24 @@ function mouseHandler(mapId, layerId, group, eventName, extraInfo) { }; } +function hexToRgb(hex) { + // Remove the leading hash if present + hex = hex.startsWith('#') ? hex.slice(1) : hex; + + // If the hex value is in shorthand form, convert it to the full form + if (hex.length === 3) { + hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; + } + + // Parse the hexadecimal string into integers for red, green, and blue + const num = parseInt(hex, 16); + + return { + r: ((num >> 16) & 255) / 255, // Red + g: ((num >> 8) & 255) / 255, // Green + b: (num & 255) / 255, // Blue + }; +} LeafletWidget.methods.addFlatGeoBuf = function (layerId, group, @@ -36,11 +54,12 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, scale, scaleFields, useWebgl, - load_chunks) { + chunkSize, + highlightOptions) { - var map = this; - var gl = useWebgl; - var pane; + const map = this; + let gl = useWebgl; + let pane; if (options === null || options.pane === undefined) { pane = 'overlayPane'; @@ -48,7 +67,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, pane = options.pane; } - var data_fl = document.getElementById(group + '-1-attachment'); + let data_fl = document.getElementById(group + '-1-attachment'); if (data_fl === null) { data_fl = url; @@ -56,8 +75,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, data_fl = data_fl.href; } - var popUp; - var colnames = []; + let popUp; + let colnames = []; function handleHeaderMeta(headerMeta) { headerMeta.columns.forEach(function(col) { @@ -70,9 +89,88 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, // NOTE: would be more efficient with a special purpose Leaflet deserializer let it = flatgeobuf.deserialize(response.body, undefined, handleHeaderMeta); let cntr = 0; - let chunkSize = load_chunks; let shapeslayer = null; let geojson_array = []; + + function initializeShapesLayer(data) { + console.log("Initializing leaflet.glify with the first chunk or remaining features"); + + let click_event = function(e, feature, addpopup, popup) { + if (map.hasLayer(shapeslayer.layer)) { + var idx = data.features.findIndex(k => k == feature); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(map.id + "_glify_click", { + id: layerId ? (typeof layerId === 'string' && + feature.properties.hasOwnProperty(layerId) ? + feature.properties[layerId] : layerId[idx]) : idx + 1, + group: Object.values(shapeslayer.layer._eventParents)[0].groupname, + lat: e.latlng.lat, + lng: e.latlng.lng, + data: feature.properties + }); + } + if (addpopup) { + let content = popup === true ? json2table(feature.properties) : (typeof popup === 'string' && + feature.properties.hasOwnProperty(popup) ? feature.properties[popup] : popup.toString()); + + L.popup({ maxWidth: 2000 }) + .setLatLng(e.latlng) + .setContent(content) + .openOn(map); + } + } + }; + let pop = function(e, feature) { + click_event(e, feature, popup !== null, popup); + }; + let tooltip = new L.Tooltip(); + let hover_event = function(e, feature, addlabel, label) { + if (map.hasLayer(shapeslayer.layer)) { + console.log("map.hasLayer(shapeslayer.layer)") + console.log("feature"); console.log(feature) + console.log("e"); console.log(e) + if (highlightOptions && typeof highlightOptions === 'object' && Object.keys(highlightOptions).length > 0) { + let hoveroverLayer = L.geoJSON(feature, {style: highlightOptions}) + map.layerManager.removeLayer("fgb_hover", "fgb_hover_rndid"); + map.layerManager.addLayer(hoveroverLayer, "fgb_hover", "fgb_hover_rndid", group); + + } + + if (addlabel && feature.properties.hasOwnProperty(label)) { + tooltip + .setLatLng(e.latlng) + .setContent(feature.properties[label].toString()) + .addTo(map); + } + } + }; + let hvr = function(e, feature) { + hover_event(e, feature, label !== null, label); + }; + + // Set default values if style is not defined or properties are missing + const opacity = style && style.fillOpacity !== undefined ? style.fillOpacity : 1; + const border = style && style.stroke !== undefined ? style.stroke : true; + const color = style && style.color !== undefined ? style.color : null; + const size = style && style.weight !== undefined ? style.weight : 5; + + shapeslayer = L.glify.shapes({ + map: map, + color: hexToRgb(color), + click: pop, + hover: hvr, + border: border, + data: data, + className: group, + opacity: opacity, + size: size, + hoverWait: 10, + pane: pane + }); + + map.layerManager.addLayer(shapeslayer.layer, "glify", layerId, group); + } + // handle result function handleResult(result) { if (!result.done) { @@ -83,65 +181,10 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, if (!shapeslayer || !shapeslayer.layer) { // Initialize leaflet.glify with the first chunk console.log("Initializing leaflet.glify with the first chunk"); - let data = { + initializeShapesLayer({ type: "FeatureCollection", features: geojson_array - }; - - var click_event = function(e, feature, addpopup, popup) { - if (map.hasLayer(shapeslayer.layer)) { - var idx = data.features.findIndex(k => k==feature); - if (HTMLWidgets.shinyMode) { - Shiny.setInputValue(map.id + "_glify_click", { - id: layerId ? (typeof layerId === 'string' && - feature.properties.hasOwnProperty(layerId) ? - feature.properties[layerId] : layerId[idx]) : idx + 1, - group: Object.values(shapeslayer.layer._eventParents)[0].groupname, - lat: e.latlng.lat, - lng: e.latlng.lng, - data: feature.properties - }); - } - if (addpopup) { - let content = popup === true ? json2table(feature.properties) : (typeof popup === 'string' && - feature.properties.hasOwnProperty(popup) ? feature.properties[popup] : popup.toString()); - - L.popup({ maxWidth: 2000 }) - .setLatLng(e.latlng) - .setContent(content) - .openOn(map); - } - } - }; - var pop = function (e, feature) { - click_event(e, feature, popup !== null, popup); - }; - let tooltip = new L.Tooltip(); - let hover_event = function(e, feature, addlabel, label) { - if (map.hasLayer(shapeslayer.layer)) { - if (addlabel && feature.properties.hasOwnProperty(label)) { - tooltip - .setLatLng(e.latlng) - .setContent(feature.properties[[label]].toString()) - .addTo(map); - } - } - } - let hvr = function(e, feature) { - hover_event(e, feature, label !== null, label); - } - - shapeslayer = L.glify.shapes({ - map: map, - //color: () => {return {r: 1,g: 0,b: 0,}}, - click: pop, - hover: hvr, - border: true, - data: data, - className: group, - pane: pane - }); - map.layerManager.addLayer(shapeslayer.layer, "glify", layerId, group); + }); } else { // Insert the collected chunk into the shapeslayer console.log("Inserting new chunk into shapeslayer"); @@ -160,9 +203,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, pop = null; } - if (scaleFields === null & - result.value.properties !== undefined) { - var vls = Object.values(style); + if (scaleFields === null & result.value.properties !== undefined) { + let vls = Object.values(style); scaleFields = []; vls.forEach(function(name) { //if (name in colnames) { @@ -174,8 +216,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, }); } - lyr = L.geoJSON(result.value, Object.assign( - { + lyr = L.geoJSON(result.value, Object.assign({ pointToLayer: function (feature, latlng) { return L.circleMarker(latlng, options); }, @@ -194,7 +235,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, return layer.feature.properties[label].toString(); }, {sticky: true}); } else if (typeof(label) === Object || (typeof(label) === 'object' && label.length > 1)) { - var lb = label[cntr]; + let lb = label[cntr]; lyr.bindTooltip(function (layer) { return(lb); }, {sticky: true}); @@ -205,40 +246,51 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, } } + if (highlightOptions && typeof highlightOptions === 'object' && Object.keys(highlightOptions).length > 0) { + lyr.on({ + // highlight on hover + 'mouseover': function(e) { + const layer = e.target; + layer.setStyle(highlightOptions); + if (highlightOptions.bringToFront) { + layer.bringToFront(); + } + }, + // remove highlight when hover stops + 'mouseout': function(e) { + const layer = e.target; + layer.setStyle(style); + if (highlightOptions.sendToBack) { + layer.bringToBack(); + } + } + }) + } + lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); map.layerManager.addLayer(lyr, null, null, group); + it.next().then(handleResult); } - } else if (geojson_array.length > 0) { if (gl) { console.log("Processing remaining features, geojson_array length:", geojson_array.length); // Insert any remaining features in geojson_array when done if (!shapeslayer || !shapeslayer.layer) { console.log("Draw single chunk"); - shapeslayer = L.glify.shapes({ - map: map, - data: { - type: "FeatureCollection", - features: geojson_array - }, - className: group, - pane: pane - }); - map.layerManager.addLayer(shapeslayer.layer, "glify", layerId, group); + initializeShapesLayer({ + type: "FeatureCollection", + features: geojson_array + }); } else { console.log("Inserting remaining chunk into shapeslayer"); shapeslayer.insert(geojson_array, cntr); - /* - geojson_array.forEach((feature, index) => { - shapeslayer.insert(feature, cntr + index); - }); - */ } } } + cntr += 1; } it.next().then(handleResult); diff --git a/man/addFgb.Rd b/man/addFgb.Rd index 3a39be2..95033f5 100644 --- a/man/addFgb.Rd +++ b/man/addFgb.Rd @@ -27,7 +27,8 @@ addFgb( minZoom = NULL, maxZoom = 52, useWebgl = FALSE, - load_chunks = 1000, + chunkSize = 1000, + highlightOptions = NULL, ... ) } @@ -84,7 +85,9 @@ opacity, fillOpacity if those are to be mapped to an attribute column.} \item{useWebgl}{use `leafgl` if TRUE.} -\item{load_chunks}{How many features should be drawn/updated at once. Default is 1000} +\item{chunkSize}{How many features should be drawn/updated at once. Default is 1000} + +\item{highlightOptions}{Options for highlighting the shape on mouse over.} \item{...}{currently not used.} } From 2b12f5f126d6940e604b2a3a917cae508fe2aaaa Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Wed, 12 Jun 2024 18:05:53 +0200 Subject: [PATCH 07/17] highlight for fgbfiltered --- R/file.R | 2 ++ inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 41 +++++++++++++++++++++----- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/R/file.R b/R/file.R index 9111141..c3c284d 100644 --- a/R/file.R +++ b/R/file.R @@ -448,6 +448,7 @@ addFgb = function(map, , scaleFields , minZoom , maxZoom + , highlightOptions ) } else { print("!is.null(file)") @@ -512,6 +513,7 @@ addFgb = function(map, , scaleFields , minZoom , maxZoom + , highlightOptions ) } else { leaflet::invokeMethod( diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index 0747f5a..e485741 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -443,7 +443,8 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, scale, scaleFields, minZoom, - maxZoom) { + maxZoom, + highlightOptions) { const map = this; let gl = false; @@ -488,11 +489,13 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, }; } - let previousResults = previousResults || {}; - console.log("previousResults");console.log(previousResults) - previousResults[group] = L.layerGroup(); - console.log("previousResults[group]");console.log(previousResults[group]) - map.layerManager.addLayer(previousResults[group], null, layerId, group); + let previousResults = nextResults = {}; + + // Initialize previousResults if not already initialized + if (!previousResults[group]) { + previousResults[group] = L.layerGroup(); + map.layerManager.addLayer(previousResults[group], null, layerId, group); + } async function updateResults() { console.log("updateResults") @@ -501,7 +504,6 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, map.layerManager.removeLayer(previousResults[group], layerId); previousResults[group].remove(); - let nextResults = nextResults || {}; nextResults[group] = L.layerGroup(); map.layerManager.addLayer(nextResults[group], null, layerId, group); @@ -563,6 +565,27 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, } } + if (highlightOptions && typeof highlightOptions === 'object' && Object.keys(highlightOptions).length > 0) { + lyr.on({ + // highlight on hover + 'mouseover': function(e) { + const layer = e.target; + layer.setStyle(highlightOptions); + if (highlightOptions.bringToFront) { + layer.bringToFront(); + } + }, + // remove highlight when hover stops + 'mouseout': function(e) { + const layer = e.target; + layer.setStyle(style); + if (highlightOptions.sendToBack) { + layer.bringToBack(); + } + } + }) + } + lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); @@ -572,14 +595,18 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, } // show results based on the initial map + console.log("init updateResults") updateResults(); // ...and update the results whenever the map moves map.on("moveend", function(s) { + console.log("moveend triggers updateResults") updateResults(); }); map.on('layeradd', function(event) { + console.log("layeradd") if (event.layer == previousResults[group]) { + console.log("Trigger updateResults") updateResults(); } }); From 6cd3a5d3fcfc9032c03ed61c237b7b6e1397dd88 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Thu, 13 Jun 2024 07:28:42 +0200 Subject: [PATCH 08/17] fix: label can be a function --- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 28 +++++++++++++++++--------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index e485741..d80f2a1 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -136,11 +136,20 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, } - if (addlabel && feature.properties.hasOwnProperty(label)) { - tooltip - .setLatLng(e.latlng) - .setContent(feature.properties[label].toString()) - .addTo(map); + if (addlabel) { + let content = ""; + if (Object.keys(feature.properties).includes(label)) { + content = feature.properties[label].toString() + } else if (typeof(label) === "function") { + content = label(feature); + } else { + content = label; + } + + tooltip + .setLatLng(e.latlng) + .setContent(content) + .addTo(map); } } }; @@ -239,6 +248,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, lyr.bindTooltip(function (layer) { return(lb); }, {sticky: true}); + } else if (typeof(label) === "function") { + lyr.bindTooltip(label, {sticky: true}); } else { lyr.bindTooltip(function (layer) { return(label); @@ -553,11 +564,8 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, lyr.bindTooltip(function (layer) { return layer.feature.properties[label].toString(); }, {sticky: true}); - } else if (typeof(label) === Object || (typeof(label) === 'object' && label.length > 1)) { - let lb = label[cntr]; - lyr.bindTooltip(function (layer) { - return(lb); - }, {sticky: true}); + } else if (typeof(label) === "function") { + lyr.bindTooltip(label, {sticky: true}); } else { lyr.bindTooltip(function (layer) { return(label); From 1f4332ac69cd0f495278224e890338cca26006a7 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Thu, 13 Jun 2024 07:29:13 +0200 Subject: [PATCH 09/17] cleanup --- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 62 +++++++++----------------- 1 file changed, 21 insertions(+), 41 deletions(-) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index d80f2a1..80ef7f4 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -93,8 +93,6 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, let geojson_array = []; function initializeShapesLayer(data) { - console.log("Initializing leaflet.glify with the first chunk or remaining features"); - let click_event = function(e, feature, addpopup, popup) { if (map.hasLayer(shapeslayer.layer)) { var idx = data.features.findIndex(k => k == feature); @@ -126,9 +124,6 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, let tooltip = new L.Tooltip(); let hover_event = function(e, feature, addlabel, label) { if (map.hasLayer(shapeslayer.layer)) { - console.log("map.hasLayer(shapeslayer.layer)") - console.log("feature"); console.log(feature) - console.log("e"); console.log(e) if (highlightOptions && typeof highlightOptions === 'object' && Object.keys(highlightOptions).length > 0) { let hoveroverLayer = L.geoJSON(feature, {style: highlightOptions}) map.layerManager.removeLayer("fgb_hover", "fgb_hover_rndid"); @@ -185,18 +180,15 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, if (!result.done) { if (gl) { geojson_array.push(result.value); - console.log("Push Data"); if (geojson_array.length === chunkSize) { if (!shapeslayer || !shapeslayer.layer) { // Initialize leaflet.glify with the first chunk - console.log("Initializing leaflet.glify with the first chunk"); initializeShapesLayer({ - type: "FeatureCollection", - features: geojson_array - }); + type: "FeatureCollection", + features: geojson_array + }); } else { // Insert the collected chunk into the shapeslayer - console.log("Inserting new chunk into shapeslayer"); shapeslayer.insert(geojson_array, cntr); } // Reset the array for the next chunk @@ -285,6 +277,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, it.next().then(handleResult); } + } else if (geojson_array.length > 0) { if (gl) { console.log("Processing remaining features, geojson_array length:", geojson_array.length); @@ -292,9 +285,9 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, if (!shapeslayer || !shapeslayer.layer) { console.log("Draw single chunk"); initializeShapesLayer({ - type: "FeatureCollection", - features: geojson_array - }); + type: "FeatureCollection", + features: geojson_array + }); } else { console.log("Inserting remaining chunk into shapeslayer"); shapeslayer.insert(geojson_array, cntr); @@ -308,10 +301,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, } fetch(data_fl) //, {mode: 'no-cors'}) - .then(handleResponse); + .then(handleResponse); - //map.fitBounds(lyr.getBounds()); - //map.layerManager.addLayer(layer, null, null, group); }; function makePopup(popup, className) { @@ -444,25 +435,23 @@ function rescale(value, to_min, to_max, from_min, from_max) { LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, - group, - url, - popup, - label, - style, - options, - className, - scale, - scaleFields, - minZoom, - maxZoom, - highlightOptions) { + group, + url, + popup, + label, + style, + options, + className, + scale, + scaleFields, + minZoom, + maxZoom, + highlightOptions) { const map = this; let gl = false; let pane; - console.log("addFlatGeoBufFiltered") - if (options === null || options.pane === undefined) { pane = 'overlayPane'; } else { @@ -500,24 +489,20 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, }; } + // Initialize previousResults/nextResults if not already initialized let previousResults = nextResults = {}; - - // Initialize previousResults if not already initialized if (!previousResults[group]) { previousResults[group] = L.layerGroup(); map.layerManager.addLayer(previousResults[group], null, layerId, group); } async function updateResults() { - console.log("updateResults") // remove the old results map.layerManager.removeLayer(previousResults[group], layerId); previousResults[group].remove(); - nextResults[group] = L.layerGroup(); map.layerManager.addLayer(nextResults[group], null, layerId, group); - previousResults[group] = nextResults[group]; // Use flatgeobuf JavaScript API to iterate features as geojson. @@ -528,7 +513,6 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, if (map.getZoom() >= minZoom & map.getZoom() <= maxZoom & map.hasLayer(previousResults[group])) { for await (let feature of iter) { - if (popup) { pop = makePopup(popup, className); } else { @@ -603,18 +587,14 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, } // show results based on the initial map - console.log("init updateResults") updateResults(); // ...and update the results whenever the map moves map.on("moveend", function(s) { - console.log("moveend triggers updateResults") updateResults(); }); map.on('layeradd', function(event) { - console.log("layeradd") if (event.layer == previousResults[group]) { - console.log("Trigger updateResults") updateResults(); } }); From 954f6eeddfe1305e976bc64667fe5d12bfc87897 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Thu, 13 Jun 2024 23:36:56 +0200 Subject: [PATCH 10/17] stash (drop) --- R/file.R | 17 +- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 213 ++++-------------- .../lib/FlatGeoBuf/flatgeobuf-geojson.min.js | 29 ++- .../FlatGeoBuf/flatgeobuf-geojson.min_old.js | 17 ++ man/addFgb.Rd | 6 - 5 files changed, 74 insertions(+), 208 deletions(-) create mode 100644 inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min_old.js diff --git a/R/file.R b/R/file.R index c3c284d..31df659 100644 --- a/R/file.R +++ b/R/file.R @@ -305,8 +305,6 @@ addTileFolder = function(map, #' opacity, fillOpacity if those are to be mapped to an attribute column. #' @param minZoom minimum zoom level at which data should be rendered. #' @param maxZoom maximum zoom level at which data should be rendered. -#' @param useWebgl use `leafgl` if TRUE. -#' @param chunkSize How many features should be drawn/updated at once. Default is 1000 #' @inheritParams leaflet::highlightOptions #' @param ... currently not used. #' @@ -361,8 +359,6 @@ addFgb = function(map, scale = scaleOptions(), minZoom = NULL, maxZoom = 52, - useWebgl = FALSE, - chunkSize = 1000, highlightOptions = NULL, ...) { @@ -430,8 +426,6 @@ addFgb = function(map, if (is.null(maxZoom)) { maxZoom = 19 } - print("!is.null(file)") - print("addFlatGeoBufFiltered") leaflet::invokeMethod( map , leaflet::getMapData(map) @@ -451,9 +445,6 @@ addFgb = function(map, , highlightOptions ) } else { - print("!is.null(file)") - print("addFlatGeoBuf") - leaflet::invokeMethod( map , leaflet::getMapData(map) @@ -468,8 +459,6 @@ addFgb = function(map, , className , scale , scaleFields - , useWebgl - , chunkSize , highlightOptions ) } @@ -495,8 +484,6 @@ addFgb = function(map, if (is.null(maxZoom)) { maxZoom = 19 } - print("file = NULL") - print("addFlatGeoBufFiltered") leaflet::invokeMethod( map , leaflet::getMapData(map) @@ -530,8 +517,6 @@ addFgb = function(map, , className , scale , scaleFields - , useWebgl - , chunkSize , highlightOptions ) } @@ -556,7 +541,7 @@ fgbDependencies = function() { list( htmltools::htmlDependency( "FlatGeoBuf" - , '3.21.3' + , '3.31.1' , system.file("htmlwidgets/lib/FlatGeoBuf", package = "leafem") , script = c( 'fgb.js' diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index 80ef7f4..eb2baff 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -24,25 +24,6 @@ function mouseHandler(mapId, layerId, group, eventName, extraInfo) { }; } -function hexToRgb(hex) { - // Remove the leading hash if present - hex = hex.startsWith('#') ? hex.slice(1) : hex; - - // If the hex value is in shorthand form, convert it to the full form - if (hex.length === 3) { - hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; - } - - // Parse the hexadecimal string into integers for red, green, and blue - const num = parseInt(hex, 16); - - return { - r: ((num >> 16) & 255) / 255, // Red - g: ((num >> 8) & 255) / 255, // Green - b: (num & 255) / 255, // Blue - }; -} - LeafletWidget.methods.addFlatGeoBuf = function (layerId, group, url, @@ -53,12 +34,10 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, className, scale, scaleFields, - useWebgl, - chunkSize, highlightOptions) { const map = this; - let gl = useWebgl; + let gl = false; let pane; if (options === null || options.pane === undefined) { @@ -89,113 +68,18 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, // NOTE: would be more efficient with a special purpose Leaflet deserializer let it = flatgeobuf.deserialize(response.body, undefined, handleHeaderMeta); let cntr = 0; - let shapeslayer = null; - let geojson_array = []; - - function initializeShapesLayer(data) { - let click_event = function(e, feature, addpopup, popup) { - if (map.hasLayer(shapeslayer.layer)) { - var idx = data.features.findIndex(k => k == feature); - if (HTMLWidgets.shinyMode) { - Shiny.setInputValue(map.id + "_glify_click", { - id: layerId ? (typeof layerId === 'string' && - feature.properties.hasOwnProperty(layerId) ? - feature.properties[layerId] : layerId[idx]) : idx + 1, - group: Object.values(shapeslayer.layer._eventParents)[0].groupname, - lat: e.latlng.lat, - lng: e.latlng.lng, - data: feature.properties - }); - } - if (addpopup) { - let content = popup === true ? json2table(feature.properties) : (typeof popup === 'string' && - feature.properties.hasOwnProperty(popup) ? feature.properties[popup] : popup.toString()); - - L.popup({ maxWidth: 2000 }) - .setLatLng(e.latlng) - .setContent(content) - .openOn(map); - } - } - }; - let pop = function(e, feature) { - click_event(e, feature, popup !== null, popup); - }; - let tooltip = new L.Tooltip(); - let hover_event = function(e, feature, addlabel, label) { - if (map.hasLayer(shapeslayer.layer)) { - if (highlightOptions && typeof highlightOptions === 'object' && Object.keys(highlightOptions).length > 0) { - let hoveroverLayer = L.geoJSON(feature, {style: highlightOptions}) - map.layerManager.removeLayer("fgb_hover", "fgb_hover_rndid"); - map.layerManager.addLayer(hoveroverLayer, "fgb_hover", "fgb_hover_rndid", group); - - } - - if (addlabel) { - let content = ""; - if (Object.keys(feature.properties).includes(label)) { - content = feature.properties[label].toString() - } else if (typeof(label) === "function") { - content = label(feature); - } else { - content = label; - } - - tooltip - .setLatLng(e.latlng) - .setContent(content) - .addTo(map); - } - } - }; - let hvr = function(e, feature) { - hover_event(e, feature, label !== null, label); - }; - - // Set default values if style is not defined or properties are missing - const opacity = style && style.fillOpacity !== undefined ? style.fillOpacity : 1; - const border = style && style.stroke !== undefined ? style.stroke : true; - const color = style && style.color !== undefined ? style.color : null; - const size = style && style.weight !== undefined ? style.weight : 5; - - shapeslayer = L.glify.shapes({ - map: map, - color: hexToRgb(color), - click: pop, - hover: hvr, - border: border, - data: data, - className: group, - opacity: opacity, - size: size, - hoverWait: 10, - pane: pane - }); - - map.layerManager.addLayer(shapeslayer.layer, "glify", layerId, group); - } // handle result function handleResult(result) { if (!result.done) { if (gl) { - geojson_array.push(result.value); - if (geojson_array.length === chunkSize) { - if (!shapeslayer || !shapeslayer.layer) { - // Initialize leaflet.glify with the first chunk - initializeShapesLayer({ - type: "FeatureCollection", - features: geojson_array - }); - } else { - // Insert the collected chunk into the shapeslayer - shapeslayer.insert(geojson_array, cntr); - } - // Reset the array for the next chunk - geojson_array = []; - } + map.layerManager.addLayer( + L.glify.shapes({ + map: map, + data: result.value, + className: group + }).glLayer, null, null, group); it.next().then(handleResult); - } else { if (popup) { @@ -277,22 +161,6 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, it.next().then(handleResult); } - - } else if (geojson_array.length > 0) { - if (gl) { - console.log("Processing remaining features, geojson_array length:", geojson_array.length); - // Insert any remaining features in geojson_array when done - if (!shapeslayer || !shapeslayer.layer) { - console.log("Draw single chunk"); - initializeShapesLayer({ - type: "FeatureCollection", - features: geojson_array - }); - } else { - console.log("Inserting remaining chunk into shapeslayer"); - shapeslayer.insert(geojson_array, cntr); - } - } } cntr += 1; @@ -327,7 +195,7 @@ function makePopup(popup, className) { } else if (typeof(popup) === "object") { pop = function(feature, layer) { if (feature.properties.mvFeatureId !== undefined) { - var idx = feature.properties.mvFeatureId; + let idx = feature.properties.mvFeatureId; layer.bindPopup(popup[idx - 1], { maxWidth: 2000 }); } if (feature.properties.mvFeatureId === undefined) { @@ -349,18 +217,14 @@ function makePopup(popup, className) { function json2table(json, cls) { - var cols = Object.keys(json); - var vals = Object.values(json); - - var tab = ""; - + let cols = Object.keys(json); + let vals = Object.values(json); + let tab = ""; for (let i = 0; i < cols.length; i++) { tab += "" + cols[i] + " " + "" + vals[i] + " "; } - return "" + tab + "
"; - } @@ -375,31 +239,24 @@ function json2table(json, cls) { * @return {Object} The new object */ function pick(obj, props) { - 'use strict'; - // Make sure object and properties are provided if (!obj || !props) return; - // Create new object - var picked = {}; - + let picked = {}; // Loop through props and push to new object props.forEach(function(prop) { picked[prop] = obj[prop]; }); - - // Return new object return picked; - } function updateStyle(style_obj, feature, scale, scaleValues) { - var cols = Object.keys(style_obj); - var vals = Object.values(style_obj); + let cols = Object.keys(style_obj); + let vals = Object.values(style_obj); - var out = {}; + let out = {}; for (let i = 0; i < cols.length; i++) { if (vals[i] === null) { @@ -470,9 +327,9 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, let colnames = []; function handleHeaderMeta(headerMeta) { - const header = document.getElementById('header') - const formatter = new JSONFormatter(headerMeta, 10) - header.appendChild(formatter.render()) + //const header = document.getElementById('header') + //const formatter = new JSONFormatter(headerMeta, 10) + //header.appendChild(formatter.render()) headerMeta.columns.forEach(function(col) { colnames.push(col.name); }); @@ -490,29 +347,40 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, } // Initialize previousResults/nextResults if not already initialized - let previousResults = nextResults = {}; - if (!previousResults[group]) { - previousResults[group] = L.layerGroup(); - map.layerManager.addLayer(previousResults[group], null, layerId, group); - } + var previousResults = previousResults || {}; + previousResults[group] = L.layerGroup(); + map.layerManager.addLayer(previousResults[group], null, layerId, group); + // Async Update Function async function updateResults() { // remove the old results + console.log("1") map.layerManager.removeLayer(previousResults[group], layerId); - previousResults[group].remove(); + previousResults[group].remove() + + // add next results + console.log("2") + var nextResults = nextResults || {}; nextResults[group] = L.layerGroup(); map.layerManager.addLayer(nextResults[group], null, layerId, group); + + // Replace previous with next + console.log("3") previousResults[group] = nextResults[group]; // Use flatgeobuf JavaScript API to iterate features as geojson. - // Because we specify a bounding box, flatgeobuf will only fetch the resubset of data, + // Because we specify a bounding box, flatgeobuf will only fetch the relevant subset of data, // rather than the entire file. - let iter = flatgeobuf.deserialize(data_fl, fgBoundingBox(), handleHeaderMeta); - + console.log("4") if (map.getZoom() >= minZoom & map.getZoom() <= maxZoom & map.hasLayer(previousResults[group])) { + console.log("data_fl"); console.log(data_fl) + let iter = flatgeobuf.deserialize(data_fl, fgBoundingBox(), handleHeaderMeta); + for await (let feature of iter) { + console.log("feature") + if (popup) { pop = makePopup(popup, className); } else { @@ -589,14 +457,17 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, // show results based on the initial map updateResults(); - // ...and update the results whenever the map moves + // update the results whenever the map moves or the layer is added again map.on("moveend", function(s) { updateResults(); }); + /* map.on('layeradd', function(event) { + console.log("layeradd") if (event.layer == previousResults[group]) { updateResults(); } }); + */ }; diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js b/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js index 56b58ce..a273417 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js @@ -1,17 +1,16 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).flatgeobuf={})}(this,(function(t){"use strict";class e{constructor(t,e,r,n,s,i,o,a,h,c){this.name=t,this.type=e,this.title=r,this.description=n,this.width=s,this.precision=i,this.scale=o,this.nullable=a,this.unique=h,this.primary_key=c}}var r;!function(t){t[t.Byte=0]="Byte",t[t.UByte=1]="UByte",t[t.Bool=2]="Bool",t[t.Short=3]="Short",t[t.UShort=4]="UShort",t[t.Int=5]="Int",t[t.UInt=6]="UInt",t[t.Long=7]="Long",t[t.ULong=8]="ULong",t[t.Float=9]="Float",t[t.Double=10]="Double",t[t.String=11]="String",t[t.Json=12]="Json",t[t.DateTime=13]="DateTime",t[t.Binary=14]="Binary"}(r||(r={}));class n{constructor(t,e,r,n,s,i){this.org=t,this.code=e,this.name=r,this.description=n,this.wkt=s,this.code_string=i}}const s=new Int32Array(2),i=new Float32Array(s.buffer),o=new Float64Array(s.buffer),a=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0];class h{constructor(t,e){this.low=0|t,this.high=0|e}static create(t,e){return 0==t&&0==e?h.ZERO:new h(t,e)}toFloat64(){return(this.low>>>0)+4294967296*this.high}equals(t){return this.low==t.low&&this.high==t.high}}var c,u;h.ZERO=new h(0,0),function(t){t[t.UTF8_BYTES=1]="UTF8_BYTES",t[t.UTF16_STRING=2]="UTF16_STRING"}(c||(c={}));class l{constructor(t){this.bytes_=t,this.position_=0}static allocate(t){return new l(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return new h(this.readInt32(t),this.readInt32(t+4))}readUint64(t){return new h(this.readUint32(t),this.readUint32(t+4))}readFloat32(t){return s[0]=this.readInt32(t),i[0]}readFloat64(t){return s[a?0:1]=this.readInt32(t),s[a?1:0]=this.readInt32(t+4),o[0]}writeInt8(t,e){this.bytes_[t]=e}writeUint8(t,e){this.bytes_[t]=e}writeInt16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)}writeUint64(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)}writeFloat32(t,e){i[0]=e,this.writeInt32(t,s[0])}writeFloat64(t,e){o[0]=e,this.writeInt32(t,s[a?0:1]),this.writeInt32(t+4,s[a?1:0])}getBufferIdentifier(){if(this.bytes_.length>10),56320+(1023&e)))}return n}__union_with_string(t,e){return"string"==typeof t?this.__string(e):this.__union(t,e)}__indirect(t){return t+this.readInt32(t)}__vector(t){return t+this.readInt32(t)+4}__vector_len(t){return this.readInt32(t+this.readInt32(t))}__has_identifier(t){if(4!=t.length)throw new Error("FlatBuffers: file identifier must be length 4");for(let e=0;e<4;e++)if(t.charCodeAt(e)!=this.readInt8(this.position()+4+e))return!1;return!0}createLong(t,e){return h.create(t,e)}createScalarList(t,e){const r=[];for(let n=0;nthis.minalign&&(this.minalign=t);const r=1+~(this.bb.capacity()-this.space+e)&t-1;for(;this.space=0&&0==this.vtable[e];e--);const r=e+1;for(;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);const n=2*(r+2);this.addInt16(n);let s=0;const i=this.space;t:for(e=0;e=0;e--)this.writeInt8(t.charCodeAt(e))}this.prep(this.minalign,4+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const r=this.bb.capacity()-t,n=r-this.bb.readInt32(r);if(!(0!=this.bb.readInt16(n+e)))throw new Error("FlatBuffers: field "+e+" must be set")}startVector(t,e,r){this.notNested(),this.vector_num_elems=e,this.prep(4,t*e),this.prep(r,t*e)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(t){if(!t)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(t))return this.string_maps.get(t);const e=this.createString(t);return this.string_maps.set(t,e),e}createString(t){if(!t)return 0;let e;if(t instanceof Uint8Array)e=t;else{e=[];let r=0;for(;r=56320)n=s;else{n=(s<<10)+t.charCodeAt(r++)+-56613888}n<128?e.push(n):(n<2048?e.push(n>>6&31|192):(n<65536?e.push(n>>12&15|224):e.push(n>>18&7|240,n>>12&63|128),e.push(n>>6&63|128)),e.push(63&n|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(let t=0,r=this.space,n=this.bb.bytes();t=0;r--)t.addFloat64(e[r]);return t.endVector()}static startEnvelopeVector(t,e){t.startVector(8,e,8)}static addGeometryType(t,e){t.addFieldInt8(2,e,u.Unknown)}static addHasZ(t,e){t.addFieldInt8(3,+e,0)}static addHasM(t,e){t.addFieldInt8(4,+e,0)}static addHasT(t,e){t.addFieldInt8(5,+e,0)}static addHasTm(t,e){t.addFieldInt8(6,+e,0)}static addColumns(t,e){t.addFieldOffset(7,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static addFeaturesCount(t,e){t.addFieldInt64(8,e,t.createLong(0,0))}static addIndexNodeSize(t,e){t.addFieldInt16(9,e,16)}static addCrs(t,e){t.addFieldOffset(10,e,0)}static addTitle(t,e){t.addFieldOffset(11,e,0)}static addDescription(t,e){t.addFieldOffset(12,e,0)}static addMetadata(t,e){t.addFieldOffset(13,e,0)}static endHeader(t){return t.endObject()}static finishHeaderBuffer(t,e){t.finish(e)}static finishSizePrefixedHeaderBuffer(t,e){t.finish(e,void 0,!0)}}class p{constructor(t,e,r,n,s,i,o,a){this.geometryType=t,this.columns=e,this.featuresCount=r,this.indexNodeSize=n,this.crs=s,this.title=i,this.description=o,this.metadata=a}static fromByteBuffer(t){const r=_.getRootAsHeader(t),s=r.featuresCount().toFloat64(),i=r.indexNodeSize(),o=[];for(let t=0;t=0;r--)t.addInt32(e[r]);return t.endVector()}static startEndsVector(t,e){t.startVector(4,e,4)}static addXy(t,e){t.addFieldOffset(1,e,0)}static createXyVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startXyVector(t,e){t.startVector(8,e,8)}static addZ(t,e){t.addFieldOffset(2,e,0)}static createZVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startZVector(t,e){t.startVector(8,e,8)}static addM(t,e){t.addFieldOffset(3,e,0)}static createMVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startMVector(t,e){t.startVector(8,e,8)}static addT(t,e){t.addFieldOffset(4,e,0)}static createTVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startTVector(t,e){t.startVector(8,e,8)}static addTm(t,e){t.addFieldOffset(5,e,0)}static createTmVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startTmVector(t,e){t.startVector(8,e,8)}static addType(t,e){t.addFieldInt8(6,e,u.Unknown)}static addParts(t,e){t.addFieldOffset(7,e,0)}static createPartsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startPartsVector(t,e){t.startVector(4,e,4)}static endGeometry(t){return t.endObject()}static createGeometry(t,e,r,n,s,i,o,a,h){return y.startGeometry(t),y.addEnds(t,e),y.addXy(t,r),y.addZ(t,n),y.addM(t,s),y.addT(t,i),y.addTm(t,o),y.addType(t,a),y.addParts(t,h),y.endGeometry(t)}}function g(t,e){const{xy:r,z:n,ends:s,parts:i,type:o}=e;if(i){const e=i.map((e=>g(t,e))),r=y.createPartsVector(t,e);return y.startGeometry(t),y.addParts(t,r),y.addType(t,o),y.endGeometry(t)}const a=y.createXyVector(t,r);let h,c;return n&&(h=y.createZVector(t,n)),s&&(c=y.createEndsVector(t,s)),y.startGeometry(t),c&&y.addEnds(t,c),y.addXy(t,a),h&&y.addZ(t,h),y.addType(t,o),y.endGeometry(t)}function w(t,e,r){if(0!==t.length)if(Array.isArray(t[0]))for(const n of t)w(n,e,r);else 2===t.length?e.push(...t):(e.push(t[0],t[1]),r.push(t[2]))}function v(t,e){const r=[];for(let n=0;n>1]),r.push(s)}return r}function m(t){if(!t)return u.Unknown;return u[t]}function I(t){const e=t.coordinates,r=[],n=[];let s,i;const o=m(t.type);let a=0;switch(t.type){case"Point":case"MultiPoint":case"LineString":w(e,r,n);break;case"MultiLineString":case"Polygon":{const t=e;w(t,r,n),t.length>1&&(s=t.map((t=>a+=t.length)));break}case"MultiPolygon":i=e.map((t=>({type:"Polygon",coordinates:t}))).map(I);break;case"GeometryCollection":t.geometries&&(i=t.geometries.map(I))}return{xy:r,z:n.length>0?n:void 0,ends:s,type:o,parts:i}}function F(t,e,r){if(!r||0===r.length)return[v(t,e)];let n=0;const s=Array.from(r).map((e=>t.slice(n,n=e<<1)));let i;return e&&(n=0,i=Array.from(r).map((t=>e.slice(n,n=t)))),s.map(((t,e)=>v(t,i?i[e]:void 0)))}function x(t,e){let r=e;if(r===u.Unknown&&(r=t.type()),r===u.GeometryCollection){const e=[];for(let r=0;rt.coordinates))}}const n=function(t,e){const r=t.xyArray(),n=t.zArray();switch(e){case u.Point:{const t=Array.from(r);return n&&t.push(n[0]),t}case u.MultiPoint:case u.LineString:return v(r,n);case u.MultiLineString:case u.Polygon:return F(r,n,t.endsArray())}}(t,r);return{type:u[r],coordinates:n}}class U{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFeature(t,e){return(e||new U).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFeature(t,e){return t.setPosition(t.position()+4),(e||new U).__init(t.readInt32(t.position())+t.position(),t)}geometry(t){const e=this.bb.__offset(this.bb_pos,4);return e?(t||new y).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}properties(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}propertiesLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}propertiesArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}columns(t,e){const r=this.bb.__offset(this.bb_pos,8);return r?(e||new f).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFeature(t){t.startObject(3)}static addGeometry(t,e){t.addFieldOffset(0,e,0)}static addProperties(t,e){t.addFieldOffset(1,e,0)}static createPropertiesVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startPropertiesVector(t,e){t.startVector(1,e,1)}static addColumns(t,e){t.addFieldOffset(2,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static endFeature(t){return t.endObject()}static finishFeatureBuffer(t,e){t.finish(e)}static finishSizePrefixedFeatureBuffer(t,e){t.finish(e,void 0,!0)}static createFeature(t,e,r,n){return U.startFeature(t),U.addGeometry(t,e),U.addProperties(t,r),U.addColumns(t,n),U.endFeature(t)}}const P=new TextEncoder,O=new TextDecoder;function S(t,e,n){const s=n.columns,i=new b;let o=0,a=1024,h=new Uint8Array(a),c=new DataView(h.buffer);const u=function(t){if(o+t0&&(l=U.createPropertiesVector(i,h.slice(0,o)));const f=g(i,t);U.startFeature(i),U.addGeometry(i,f),l&&U.addProperties(i,l);const d=U.endFeature(i);return i.finishSizePrefixed(d),i.asUint8Array()}function C(t,e){const n=e.columns,s={type:"Feature",geometry:x(t.geometry(),e.geometryType)};return n&&n.length>0&&(s.properties=function(t,e){const n={};if(!e||0===e.length)return n;const s=t.propertiesArray();if(!s)return n;const i=new DataView(s.buffer,s.byteOffset),o=t.propertiesLength();let a=0;for(;a0?{done:!1,value:e}:{done:!0,value:void 0}:{done:!1,value:V(e,r.value)}}))},E.prototype.slice=function(t){if((t|=0)<0)throw new Error("invalid length");var e=this,r=this._array.length-this._index;if(this._index+t<=this._array.length)return Promise.resolve(this._array.subarray(this._index,this._index+=t));var n=new Uint8Array(t);return n.set(this._array.subarray(this._index)),function s(){return e._source.read().then((function(i){return i.done?(e._array=A,e._index=0,r>0?n.subarray(0,r):null):r+i.value.length>=t?(e._array=i.value,e._index=t-r,n.set(i.value.subarray(0,t-r),r),n):(n.set(i.value,r),r+=i.value.length,s())}))}()},E.prototype.cancel=function(){return this._source.cancel()}; -/*! ***************************************************************************** - Copyright (c) Microsoft Corporation. +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).flatgeobuf={})}(this,(function(t){"use strict";var e;!function(t){t[t.Unknown=0]="Unknown",t[t.Point=1]="Point",t[t.LineString=2]="LineString",t[t.Polygon=3]="Polygon",t[t.MultiPoint=4]="MultiPoint",t[t.MultiLineString=5]="MultiLineString",t[t.MultiPolygon=6]="MultiPolygon",t[t.GeometryCollection=7]="GeometryCollection",t[t.CircularString=8]="CircularString",t[t.CompoundCurve=9]="CompoundCurve",t[t.CurvePolygon=10]="CurvePolygon",t[t.MultiCurve=11]="MultiCurve",t[t.MultiSurface=12]="MultiSurface",t[t.Curve=13]="Curve",t[t.Surface=14]="Surface",t[t.PolyhedralSurface=15]="PolyhedralSurface",t[t.TIN=16]="TIN",t[t.Triangle=17]="Triangle"}(e||(e={}));const n=new Int32Array(2),r=new Float32Array(n.buffer),s=new Float64Array(n.buffer),i=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0];var o,a;!function(t){t[t.UTF8_BYTES=1]="UTF8_BYTES",t[t.UTF16_STRING=2]="UTF16_STRING"}(o||(o={}));class c{constructor(t){this.bytes_=t,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new c(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return BigInt.asIntN(64,BigInt(this.readUint32(t))+(BigInt(this.readUint32(t+4))<>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,Number(BigInt.asIntN(32,e))),this.writeInt32(t+4,Number(BigInt.asIntN(32,e>>BigInt(32))))}writeUint64(t,e){this.writeUint32(t,Number(BigInt.asUintN(32,e))),this.writeUint32(t+4,Number(BigInt.asUintN(32,e>>BigInt(32))))}writeFloat32(t,e){r[0]=e,this.writeInt32(t,n[0])}writeFloat64(t,e){s[0]=e,this.writeInt32(t,n[i?0:1]),this.writeInt32(t+4,n[i?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=t);const n=1+~(this.bb.capacity()-this.space+e)&t-1;for(;this.space=0&&0==this.vtable[e];e--);const n=e+1;for(;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);const r=2*(n+2);this.addInt16(r);let s=0;const i=this.space;t:for(e=0;e=0;e--)this.writeInt8(t.charCodeAt(e))}this.prep(this.minalign,4+r),this.addOffset(t),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const n=this.bb.capacity()-t,r=n-this.bb.readInt32(n);if(!(e=0;n--)t.addInt32(e[n]);return t.endVector()}static startEndsVector(t,e){t.startVector(4,e,4)}static addXy(t,e){t.addFieldOffset(1,e,0)}static createXyVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startXyVector(t,e){t.startVector(8,e,8)}static addZ(t,e){t.addFieldOffset(2,e,0)}static createZVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startZVector(t,e){t.startVector(8,e,8)}static addM(t,e){t.addFieldOffset(3,e,0)}static createMVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startMVector(t,e){t.startVector(8,e,8)}static addT(t,e){t.addFieldOffset(4,e,0)}static createTVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startTVector(t,e){t.startVector(8,e,8)}static addTm(t,e){t.addFieldOffset(5,e,0)}static createTmVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startTmVector(t,e){t.startVector(8,e,8)}static addType(t,n){t.addFieldInt8(6,n,e.Unknown)}static addParts(t,e){t.addFieldOffset(7,e,0)}static createPartsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startPartsVector(t,e){t.startVector(4,e,4)}static endGeometry(t){return t.endObject()}static createGeometry(t,e,n,r,s,i,o,a,c){return h.startGeometry(t),h.addEnds(t,e),h.addXy(t,n),h.addZ(t,r),h.addM(t,s),h.addT(t,i),h.addTm(t,o),h.addType(t,a),h.addParts(t,c),h.endGeometry(t)}}function l(t,e){const{xy:n,z:r,ends:s,parts:i,type:o}=e;if(i){const e=i.map((e=>l(t,e))),n=h.createPartsVector(t,e);return h.startGeometry(t),h.addParts(t,n),h.addType(t,o),h.endGeometry(t)}const a=h.createXyVector(t,n);let c,u;return r&&(c=h.createZVector(t,r)),s&&(u=h.createEndsVector(t,s)),h.startGeometry(t),u&&h.addEnds(t,u),h.addXy(t,a),c&&h.addZ(t,c),h.addType(t,o),h.endGeometry(t)}function b(t,e,n){if(0!==t.length)if(Array.isArray(t[0]))for(const r of t)b(r,e,n);else 2===t.length?e.push(...t):(e.push(t[0],t[1]),n.push(t[2]))}function d(t,e){const n=[];for(let r=0;r>1]),n.push(s)}return n}function f(t){if(!t)return e.Unknown;return e[t]}function p(t){const e=t.coordinates,n=[],r=[];let s,i;const o=f(t.type);let a=0;switch(t.type){case"Point":case"MultiPoint":case"LineString":b(e,n,r);break;case"MultiLineString":case"Polygon":{const t=e;b(t,n,r),t.length>1&&(s=t.map((t=>a+=t.length)));break}case"MultiPolygon":i=e.map((t=>({type:"Polygon",coordinates:t}))).map(p);break}return{xy:n,z:r.length>0?r:void 0,ends:s,type:o,parts:i}}function _(t){const e=f(t.type),n=[];for(let e=0;et.slice(r,r=e<<1)));let i;return e&&(r=0,i=Array.from(n).map((t=>e.slice(r,r=t)))),s.map(((t,e)=>d(t,i?i[e]:void 0)))}function g(t,n){let r=n;if(r===e.Unknown&&(r=t.type()),r===e.GeometryCollection){const n=[];for(let e=0;et.coordinates))}}const s=function(t,n){const r=t.xyArray(),s=t.zArray();switch(n){case e.Point:{const t=Array.from(r);return s&&t.push(s[0]),t}case e.MultiPoint:case e.LineString:return d(r,s);case e.MultiLineString:case e.Polygon:return y(r,s,t.endsArray())}}(t,r);return{type:e[r],coordinates:s}}!function(t){t[t.Byte=0]="Byte",t[t.UByte=1]="UByte",t[t.Bool=2]="Bool",t[t.Short=3]="Short",t[t.UShort=4]="UShort",t[t.Int=5]="Int",t[t.UInt=6]="UInt",t[t.Long=7]="Long",t[t.ULong=8]="ULong",t[t.Float=9]="Float",t[t.Double=10]="Double",t[t.String=11]="String",t[t.Json=12]="Json",t[t.DateTime=13]="DateTime",t[t.Binary=14]="Binary"}(a||(a={}));class w{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsColumn(t,e){return(e||new w).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsColumn(t,e){return t.setPosition(t.position()+4),(e||new w).__init(t.readInt32(t.position())+t.position(),t)}name(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}type(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):a.Byte}title(t){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}description(t){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}width(){const t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt32(this.bb_pos+t):-1}precision(){const t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt32(this.bb_pos+t):-1}scale(){const t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):-1}nullable(){const t=this.bb.__offset(this.bb_pos,18);return!t||!!this.bb.readInt8(this.bb_pos+t)}unique(){const t=this.bb.__offset(this.bb_pos,20);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}primaryKey(){const t=this.bb.__offset(this.bb_pos,22);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}metadata(t){const e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__string(this.bb_pos+e,t):null}static startColumn(t){t.startObject(11)}static addName(t,e){t.addFieldOffset(0,e,0)}static addType(t,e){t.addFieldInt8(1,e,a.Byte)}static addTitle(t,e){t.addFieldOffset(2,e,0)}static addDescription(t,e){t.addFieldOffset(3,e,0)}static addWidth(t,e){t.addFieldInt32(4,e,-1)}static addPrecision(t,e){t.addFieldInt32(5,e,-1)}static addScale(t,e){t.addFieldInt32(6,e,-1)}static addNullable(t,e){t.addFieldInt8(7,+e,1)}static addUnique(t,e){t.addFieldInt8(8,+e,0)}static addPrimaryKey(t,e){t.addFieldInt8(9,+e,0)}static addMetadata(t,e){t.addFieldOffset(10,e,0)}static endColumn(t){const e=t.endObject();return t.requiredField(e,4),e}static createColumn(t,e,n,r,s,i,o,a,c,u,h,l){return w.startColumn(t),w.addName(t,e),w.addType(t,n),w.addTitle(t,r),w.addDescription(t,s),w.addWidth(t,i),w.addPrecision(t,o),w.addScale(t,a),w.addNullable(t,c),w.addUnique(t,u),w.addPrimaryKey(t,h),w.addMetadata(t,l),w.endColumn(t)}}class m{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFeature(t,e){return(e||new m).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFeature(t,e){return t.setPosition(t.position()+4),(e||new m).__init(t.readInt32(t.position())+t.position(),t)}geometry(t){const e=this.bb.__offset(this.bb_pos,4);return e?(t||new h).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}properties(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}propertiesLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}propertiesArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}columns(t,e){const n=this.bb.__offset(this.bb_pos,8);return n?(e||new w).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFeature(t){t.startObject(3)}static addGeometry(t,e){t.addFieldOffset(0,e,0)}static addProperties(t,e){t.addFieldOffset(1,e,0)}static createPropertiesVector(t,e){t.startVector(1,e.length,1);for(let n=e.length-1;n>=0;n--)t.addInt8(e[n]);return t.endVector()}static startPropertiesVector(t,e){t.startVector(1,e,1)}static addColumns(t,e){t.addFieldOffset(2,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static endFeature(t){return t.endObject()}static finishFeatureBuffer(t,e){t.finish(e)}static finishSizePrefixedFeatureBuffer(t,e){t.finish(e,void 0,!0)}static createFeature(t,e,n,r){return m.startFeature(t),m.addGeometry(t,e),m.addProperties(t,n),m.addColumns(t,r),m.endFeature(t)}}const v=new TextEncoder,I=new TextDecoder;function F(t,e,n){const r=n.columns,s=new u;let i=0,o=1024,c=new Uint8Array(o),h=new DataView(c.buffer);const b=function(t){if(i+t0&&(d=m.createPropertiesVector(s,c.slice(0,i)));const f=l(s,t);m.startFeature(s),m.addGeometry(s,f),d&&m.addProperties(s,d);const p=m.endFeature(s);return s.finishSizePrefixed(p),s.asUint8Array()}function x(t,e){const n={};if(!e||0===e.length)return n;const r=t.propertiesArray();if(!r)return n;const s=new DataView(r.buffer,r.byteOffset),i=t.propertiesLength();let o=0;for(;o0?{done:!1,value:e}:{done:!0,value:void 0}:{done:!1,value:S(e,n.value)}}))},O.prototype.slice=function(t){if((t|=0)<0)throw new Error("invalid length");var e=this,n=this._array.length-this._index;if(this._index+t<=this._array.length)return Promise.resolve(this._array.subarray(this._index,this._index+=t));var r=new Uint8Array(t);return r.set(this._array.subarray(this._index)),function s(){return e._source.read().then((function(i){return i.done?(e._array=P,e._index=0,n>0?r.subarray(0,n):null):n+i.value.length>=t?(e._array=i.value,e._index=t-n,r.set(i.value.subarray(0,t-n),n),r):(r.set(i.value,n),n+=i.value.length,s())}))}()},O.prototype.cancel=function(){return this._source.cancel()};class C{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsCrs(t,e){return(e||new C).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsCrs(t,e){return t.setPosition(t.position()+4),(e||new C).__init(t.readInt32(t.position())+t.position(),t)}org(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}code(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt32(this.bb_pos+t):0}name(t){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}description(t){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}wkt(t){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}codeString(t){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}static startCrs(t){t.startObject(6)}static addOrg(t,e){t.addFieldOffset(0,e,0)}static addCode(t,e){t.addFieldInt32(1,e,0)}static addName(t,e){t.addFieldOffset(2,e,0)}static addDescription(t,e){t.addFieldOffset(3,e,0)}static addWkt(t,e){t.addFieldOffset(4,e,0)}static addCodeString(t,e){t.addFieldOffset(5,e,0)}static endCrs(t){return t.endObject()}static createCrs(t,e,n,r,s,i,o){return C.startCrs(t),C.addOrg(t,e),C.addCode(t,n),C.addName(t,r),C.addDescription(t,s),C.addWkt(t,i),C.addCodeString(t,o),C.endCrs(t)}}class B{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsHeader(t,e){return(e||new B).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsHeader(t,e){return t.setPosition(t.position()+4),(e||new B).__init(t.readInt32(t.position())+t.position(),t)}name(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}envelope(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readFloat64(this.bb.__vector(this.bb_pos+e)+8*t):0}envelopeLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}envelopeArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Float64Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}geometryType(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readUint8(this.bb_pos+t):e.Unknown}hasZ(){const t=this.bb.__offset(this.bb_pos,10);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}hasM(){const t=this.bb.__offset(this.bb_pos,12);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}hasT(){const t=this.bb.__offset(this.bb_pos,14);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}hasTm(){const t=this.bb.__offset(this.bb_pos,16);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}columns(t,e){const n=this.bb.__offset(this.bb_pos,18);return n?(e||new w).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}featuresCount(){const t=this.bb.__offset(this.bb_pos,20);return t?this.bb.readUint64(this.bb_pos+t):BigInt("0")}indexNodeSize(){const t=this.bb.__offset(this.bb_pos,22);return t?this.bb.readUint16(this.bb_pos+t):16}crs(t){const e=this.bb.__offset(this.bb_pos,24);return e?(t||new C).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}title(t){const e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__string(this.bb_pos+e,t):null}description(t){const e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__string(this.bb_pos+e,t):null}metadata(t){const e=this.bb.__offset(this.bb_pos,30);return e?this.bb.__string(this.bb_pos+e,t):null}static startHeader(t){t.startObject(14)}static addName(t,e){t.addFieldOffset(0,e,0)}static addEnvelope(t,e){t.addFieldOffset(1,e,0)}static createEnvelopeVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startEnvelopeVector(t,e){t.startVector(8,e,8)}static addGeometryType(t,n){t.addFieldInt8(2,n,e.Unknown)}static addHasZ(t,e){t.addFieldInt8(3,+e,0)}static addHasM(t,e){t.addFieldInt8(4,+e,0)}static addHasT(t,e){t.addFieldInt8(5,+e,0)}static addHasTm(t,e){t.addFieldInt8(6,+e,0)}static addColumns(t,e){t.addFieldOffset(7,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static addFeaturesCount(t,e){t.addFieldInt64(8,e,BigInt("0"))}static addIndexNodeSize(t,e){t.addFieldInt16(9,e,16)}static addCrs(t,e){t.addFieldOffset(10,e,0)}static addTitle(t,e){t.addFieldOffset(11,e,0)}static addDescription(t,e){t.addFieldOffset(12,e,0)}static addMetadata(t,e){t.addFieldOffset(13,e,0)}static endHeader(t){return t.endObject()}static finishHeaderBuffer(t,e){t.finish(e)}static finishSizePrefixedHeaderBuffer(t,e){t.finish(e,void 0,!0)}}function V(t){const e=B.getRootAsHeader(t),n=e.featuresCount(),r=e.indexNodeSize(),s=[];for(let t=0;t0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function k(t){return this instanceof k?(this.v=t,this):new k(t)}function L(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(t,e||[]),i=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(t){s[t]&&(r[t]=function(e){return new Promise((function(n,r){i.push([t,e,n,r])>1||a(t,e)}))})}function a(t,e){try{(n=s[t](e)).value instanceof k?Promise.resolve(n.value.v).then(c,u):h(i[0][2],n)}catch(t){h(i[0][3],t)}var n}function c(t){a("next",t)}function u(t){a("throw",t)}function h(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}var R=function(t){function e(e){var n=t.call(this,e)||this;return Object.defineProperty(n,"name",{value:"RepeaterOverflowError",enumerable:!1}),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(n,n.constructor.prototype):n.__proto__=n.constructor.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(n,n.constructor),n}return function(t,e){function n(){this.constructor=t}T(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(e,t),e}(Error);function q(t){null!=t&&"function"==typeof t.then&&t.then(G,G)}!function(){function t(t){if(t<0)throw new RangeError("Capacity may not be less than 0");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return this._q.length>=this._c},enumerable:!1,configurable:!0}),t.prototype.add=function(t){if(this.full)throw new Error("Buffer full");this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){for(;this._q.length>=this._c;)this._q.shift();this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){this._q.length=j;return Promise.resolve(e).then((function(e){return!n&&t.state>=$?D(t).then((function(t){return{value:t,done:!0}})):{value:e,done:n}}))}function W(t,e){var n,r;if(!(t.state>=M))if(t.state=M,t.onnext(),t.onstop(),null==t.err&&(t.err=e),0!==t.pushes.length||void 0!==t.buffer&&!t.buffer.empty)try{for(var s=N(t.pushes),i=s.next();!i.done;i=s.next()){i.value.resolve()}}catch(t){n={error:t}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}else X(t)}function X(t){var e,n;if(!(t.state>=j)){t.state=$||(t.state=z)throw new R("No more than "+z+" pending calls to push are allowed on a single repeater.");if(t.state>=M)return Promise.resolve(void 0);var n,r=void 0===t.pending?Promise.resolve(e):t.pending.then((function(){return e}));(r=r.catch((function(e){t.state=1)){t.state=1;var e=J.bind(null,t),n=function(t){var e=W.bind(null,t),n=new Promise((function(e){return t.onstop=e}));return e.then=n.then.bind(n),e.catch=n.catch.bind(n),e.finally=n.finally.bind(n),e}(t);t.execution=new Promise((function(r){return r(t.executor(e,n))})),t.execution.catch((function(){return W(t)}))}}var K,Q=new WeakMap,tt=function(){function t(t,e){Q.set(this,{executor:t,buffer:e,err:void 0,state:0,pushes:[],nexts:[],pending:void 0,execution:void 0,onnext:G,onstop:G})}return t.prototype.next=function(t){q(t);var e=Q.get(this);if(void 0===e)throw new Error("WeakMap error");if(e.nexts.length>=z)throw new R("No more than "+z+" pending calls to next are allowed on a single repeater.");if(e.state<=0&&Y(e),e.onnext(t),void 0!==e.buffer&&!e.buffer.empty){var n=H(e,e.buffer.remove());if(e.pushes.length){var r=e.pushes.shift();e.buffer.add(r.value),e.onnext=r.resolve}return n}if(e.pushes.length){var s=e.pushes.shift();return e.onnext=s.resolve,H(e,s.value)}return e.state>=M?(X(e),H(e,D(e))):new Promise((function(n){return e.nexts.push({resolve:n,value:t})}))},t.prototype.return=function(t){q(t);var e=Q.get(this);if(void 0===e)throw new Error("WeakMap error");return X(e),e.execution=Promise.resolve(e.execution).then((function(){return t})),H(e,D(e))},t.prototype.throw=function(t){var e=Q.get(this);if(void 0===e)throw new Error("WeakMap error");return e.state<=0||e.state>=M||void 0!==e.buffer&&!e.buffer.empty?(X(e),null==e.err&&(e.err=t),H(e,D(e))):this.next(Promise.reject(t))},t.prototype[Symbol.asyncIterator]=function(){return this},t.race=nt,t.merge=rt,t.zip=st,t.latest=it,t}();function et(t,e){var n,r,s=[],i=function(t){null!=t&&"function"==typeof t[Symbol.asyncIterator]?s.push(t[Symbol.asyncIterator]()):null!=t&&"function"==typeof t[Symbol.iterator]?s.push(t[Symbol.iterator]()):s.push(function(){return L(this,arguments,(function(){return A(this,(function(n){switch(n.label){case 0:return e.yieldValues?[4,k(t)]:[3,3];case 1:return[4,n.sent()];case 2:n.sent(),n.label=3;case 3:return e.returnValues?[4,k(t)]:[3,5];case 4:return[2,n.sent()];case 5:return[2]}}))}))}())};try{for(var o=N(t),a=o.next();!a.done;a=o.next()){i(a.value)}}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return s}function nt(t){var e=this,n=et(t,{returnValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o,a,c;return A(this,(function(u){switch(u.label){case 0:if(!n.length)return r(),[2];s=!1,r.then((function(){e(),s=!0})),u.label=1;case 1:u.trys.push([1,,5,7]),o=void 0,a=0,c=function(){var s,c,u,h,l,b;return A(this,(function(d){switch(d.label){case 0:s=a;try{for(l=void 0,c=N(n),u=c.next();!u.done;u=c.next())h=u.value,Promise.resolve(h.next()).then((function(t){t.done?(r(),void 0===i&&(i=t)):a===s&&(a++,e(t))}),(function(t){return r(t)}))}catch(t){l={error:t}}finally{try{u&&!u.done&&(b=c.return)&&b.call(c)}finally{if(l)throw l.error}}return[4,new Promise((function(t){return e=t}))];case 1:return void 0===(o=d.sent())?[3,3]:[4,t(o.value)];case 2:d.sent(),d.label=3;case 3:return[2]}}))},u.label=2;case 2:return s?[3,4]:[5,c()];case 3:return u.sent(),[3,2];case 4:return[2,i&&i.value];case 5:return r(),[4,Promise.race(n.map((function(t){return t.return&&t.return()})))];case 6:return u.sent(),[7];case 7:return[2]}}))}))}))}function rt(t){var e=this,n=et(t,{yieldValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o=this;return A(this,(function(a){switch(a.label){case 0:if(!n.length)return r(),[2];e=[],s=!1,r.then((function(){var t,n;s=!0;try{for(var r=N(e),i=r.next();!i.done;i=r.next()){(0,i.value)()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}})),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all(n.map((function(n,a){return E(o,void 0,void 0,(function(){var o;return A(this,(function(c){switch(c.label){case 0:c.trys.push([0,,6,9]),c.label=1;case 1:return s?[3,5]:(Promise.resolve(n.next()).then((function(t){return e[a](t)}),(function(t){return r(t)})),[4,new Promise((function(t){e[a]=t}))]);case 2:return void 0===(o=c.sent())?[3,4]:o.done?(i=o,[2]):[4,t(o.value)];case 3:c.sent(),c.label=4;case 4:return[3,1];case 5:return[3,9];case 6:return n.return?[4,n.return()]:[3,8];case 7:c.sent(),c.label=8;case 8:return[7];case 9:return[2]}}))}))})))];case 2:return a.sent(),[2,i&&i.value];case 3:return r(),[7];case 4:return[2]}}))}))}))}function st(t){var e=this,n=et(t,{returnValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o;return A(this,(function(a){switch(a.label){case 0:if(!n.length)return r(),[2,[]];s=!1,r.then((function(){e(),s=!0})),a.label=1;case 1:a.trys.push([1,,6,8]),a.label=2;case 2:return s?[3,5]:(Promise.all(n.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return r(t)})),[4,new Promise((function(t){return e=t}))]);case 3:return void 0===(i=a.sent())?[2]:(o=i.map((function(t){return t.value})),i.some((function(t){return t.done}))?[2,o]:[4,t(o)]);case 4:return a.sent(),[3,2];case 5:return[3,8];case 6:return r(),[4,Promise.all(n.map((function(t){return t.return&&t.return()})))];case 7:return a.sent(),[7];case 8:return[2]}}))}))}))}function it(t){var e=this,n=et(t,{yieldValues:!0,returnValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o,a,c=this;return A(this,(function(u){switch(u.label){case 0:if(!n.length)return r(),[2,[]];s=[],i=!1,r.then((function(){var t,n;e();try{for(var r=N(s),o=r.next();!o.done;o=r.next()){(0,o.value)()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}i=!0})),u.label=1;case 1:return u.trys.push([1,,5,7]),Promise.all(n.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return r(t)})),[4,new Promise((function(t){return e=t}))];case 2:return void 0===(o=u.sent())?[2]:(a=o.map((function(t){return t.value})),o.every((function(t){return t.done}))?[2,a]:[4,t(a.slice())]);case 3:return u.sent(),[4,Promise.all(n.map((function(e,n){return E(c,void 0,void 0,(function(){var c;return A(this,(function(u){switch(u.label){case 0:if(o[n].done)return[2,o[n].value];u.label=1;case 1:return i?[3,4]:(Promise.resolve(e.next()).then((function(t){return s[n](t)}),(function(t){return r(t)})),[4,new Promise((function(t){return s[n]=t}))]);case 2:return void 0===(c=u.sent())?[2,o[n].value]:c.done?[2,c.value]:(a[n]=c.value,[4,t(a.slice())]);case 3:return u.sent(),[3,1];case 4:return[2]}}))}))})))];case 4:return[2,u.sent()];case 5:return r(),[4,Promise.all(n.map((function(t){return t.return&&t.return()})))];case 6:return u.sent(),[7];case 7:return[2]}}))}))}))}class ot{constructor(){this._extraRequestThreshold=262144}extraRequestThreshold(){return this._extraRequestThreshold}setExtraRequestThreshold(t){if(t<0)throw new Error("extraRequestThreshold cannot be negative");this._extraRequestThreshold=t}}ot.global=new ot,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error"}(K||(K={}));class at{static debug(...t){this.log(K.Debug,...t)}static info(...t){this.log(K.Info,...t)}static warn(...t){this.log(K.Warn,...t)}static error(...t){this.log(K.Error,...t)}static log(t,...e){if(!(this.logLevel>t))switch(t){case K.Debug:console.debug(...e);break;case K.Info:console.info(...e);break;case K.Warn:console.warn(...e);break;case K.Error:console.error(...e)}}}at.logLevel=K.Warn;const ct=40;function ut(t,e){e=Math.min(Math.max(+e,2),65535);let n=t,r=n;do{n=Math.ceil(n/e),r+=n}while(1!==n);return r*ct}async function*ht(t,e,n,r){class s{constructor(t,e){this._level=e,this.nodes=t}level(){return this._level}startNodeIdx(){return this.nodes[0]}endNodeIdx(){return this.nodes[1]}extendEndNodeIdx(t){console.assert(t>this.nodes[1]),this.nodes[1]=t}toString(){return`[NodeRange level: ${this._level}, nodes: ${this.nodes[0]}-${this.nodes[1]}]`}}const{minX:i,minY:o,maxX:a,maxY:c}=n;at.info(`tree items: ${t}, nodeSize: ${e}`);const u=function(t,e){if(e<2)throw new Error("Node size must be at least 2");if(0===t)throw new Error("Number of items must be greater than 0");let n=t,r=n;const s=[n];do{n=Math.ceil(n/e),r+=n,s.push(n)}while(1!==n);const i=[];n=r;for(const t of s)i.push(n-t),n-=t;const o=[];for(let t=0;t{const t=u.length-1;return new s([0,1],t)})()];for(at.debug(`starting stream search with queue: ${l}, numItems: ${t}, nodeSize: ${e}, levelBounds: ${u}`);0!=l.length;){const n=l.shift();at.debug(`popped node: ${n}, queueLength: ${l.length}`);const b=n.startNodeIdx(),d=b>=h,f=(()=>{const[,t]=u[n.level()],r=Math.min(n.endNodeIdx()+e,t);return d&&ry.getFloat64(u+16,!0))continue;if(o>y.getFloat64(u+24,!0))continue;const f=y.getBigUint64(u+32,!0);if(d){const n=f,s=(()=>{if(e ${p}`),g.extendEndNodeIdx(Number(p));continue}const w=(()=>{const t=n.level()-1,e=[Number(p),Number(p)+1];return new s(e,t)})();void 0!==g&&g.level()==w.level()?at.info(`Same level, but too far away. Pushing new request for nodeIdx: ${p} rather than merging with distant ${g}`):at.info(`Pushing new level for ${w} onto queue with nearestNodeRange: ${g} since there's not already a range for this level.`),l.push(w)}}}const lt=new Uint8Array([102,103,98,3,102,103,98,0]),bt=4;class dt{constructor(t,e,n,r,s){this.headerClient=t,this.header=e,this.headerLength=n,this.indexLength=r,this.nocache=s}static async open(t,e){const n=new ft(t,e),r=(()=>{let t,e=0;for(t=0;t<3;t++){e+=16**t*ct}return e})(),s=2024+r;at.debug(`fetching header. minReqLength: ${s} (assumedHeaderLength: 2024, assumedIndexLength: ${r})`);{const t=new Uint8Array(await n.getRange(0,8,s,"header"));if(!t.subarray(0,3).every(((t,e)=>lt[e]===t)))throw at.error(`bytes: ${t} != ${lt}`),new Error("Not a FlatGeobuf file");at.debug("magic bytes look good")}let i;{const t=await n.getRange(8,4,s,"header");i=new DataView(t).getUint32(0,!0);if(i>10485760||i<8)throw new Error("Invalid header size");at.debug(`headerLength: ${i}`)}const o=await n.getRange(12,i,s,"header"),a=V(new c(new Uint8Array(o))),u=ut(a.featuresCount,a.indexNodeSize);return at.debug("completed: opening http reader"),new dt(n,a,i,u,e)}async*selectBbox(t){const e=this.lengthBeforeTree(),n=this.headerClient,r=async function(t,r){return n.getRange(e+t,r,0,"index")},s=[];let i=[];for await(const e of ht(this.header.featuresCount,this.header.indexNodeSize,t,r)){const[t,,]=e;let[,,n]=e;if(n||(at.info("final feature"),n=4),0==i.length){i.push([t,n]);continue}const r=i[i.length-1],o=t-(r[0]+r[1]);o>ot.global.extraRequestThreshold()&&(at.info(`Pushing new feature batch, since gap ${o} was too large`),s.push(i),i=[]),i.push([t,n])}this.headerClient.logUsage("header+index"),i.length>0&&s.push(i);const o=s.flatMap((t=>this.readFeatureBatch(t,this.nocache)));yield*tt.merge(o)}lengthBeforeTree(){return lt.length+bt+this.headerLength}lengthBeforeFeatures(){return this.lengthBeforeTree()+this.indexLength}buildFeatureClient(t){return new ft(this.headerClient.httpClient,t)}async*readFeatureBatch(t,e){const[n]=t[0],[r,s]=t[t.length-1],i=r+s-n,o=this.buildFeatureClient(e);let a=i;for(const[e]of t)yield await this.readFeature(o,e,a),a=0;o.logUsage("feature")}async readFeature(t,e,n){const r=e+this.lengthBeforeFeatures();let s;{const e=await t.getRange(r,4,n,"feature length");s=new DataView(e).getUint32(0,!0)}const i=await t.getRange(r+4,s,n,"feature data"),o=new Uint8Array(i),a=new Uint8Array(s+bt);a.set(o,bt);const u=new c(a);return u.setPosition(bt),m.getRootAsFeature(u)}}class ft{constructor(t,e){if(this.bytesEverUsed=0,this.bytesEverFetched=0,this.buffer=new ArrayBuffer(0),this.head=0,"string"==typeof t)this.httpClient=new pt(t,e);else{if(!(t instanceof pt))throw new Error("Unknown source ");this.httpClient=t}}async getRange(t,e,n,r){this.bytesEverUsed+=e;const s=t-this.head,i=s+e;if(s>=0&&i<=this.buffer.byteLength)return this.buffer.slice(s,i);const o=Math.max(e,n);return this.bytesEverFetched+=o,at.debug(`requesting for new Range: ${t}-${t+o-1}`),this.buffer=await this.httpClient.getRange(t,o,r),this.head=t,this.buffer.slice(0,e)}logUsage(t){const e=t.split(" ")[0],n=this.bytesEverUsed,r=this.bytesEverFetched,s=(100*n/r).toFixed(2);at.info(`${e} bytes used/requested: ${n} / ${r} = ${s}%`)}}class pt{constructor(t,e){this.requestsEverMade=0,this.bytesEverRequested=0,this.url=t,this.nocache=e}async getRange(t,e,n){this.requestsEverMade+=1,this.bytesEverRequested+=e;const r=`bytes=${t}-${t+e-1}`;at.info(`request: #${this.requestsEverMade}, purpose: ${n}), bytes: (this_request: ${e}, ever: ${this.bytesEverRequested}), Range: ${r}`);const s={Range:r};this.nocache&&(s["Cache-Control"]="no-cache, no-store");return(await fetch(this.url,{headers:s})).arrayBuffer()}}async function*_t(t,e,n){const r="function"==typeof(s=t).slice?s:new O("function"==typeof s.read?s:s.getReader());var s;const i=async t=>await r.slice(t);let o=new Uint8Array(await i(8));if(!o.subarray(0,3).every(((t,e)=>lt[e]===t)))throw new Error("Not a FlatGeobuf file");o=new Uint8Array(await i(4));let a=new c(o);const u=a.readUint32(0);o=new Uint8Array(await i(u)),a=new c(o);const h=V(a);n&&n(h);const{indexNodeSize:l,featuresCount:b}=h;if(l>0){const t=ut(b,l);await i(t)}let d;for(;d=await yt(i,h,e);)yield d}async function yt(t,e,n){let r=new Uint8Array(await t(4,"feature length"));if(0===r.byteLength)return;let s=new c(r);const i=s.readUint32(0);r=new Uint8Array(await t(i,"feature data"));const o=new Uint8Array(i+4);o.set(r,4),s=new c(o),s.setPosition(bt);return n(m.getRootAsFeature(s),e)}function gt(t,e=0){const n=new u;let r=null;t.columns&&(r=B.createColumnsVector(n,t.columns.map((t=>function(t,e){const n=t.createString(e.name);return w.startColumn(t),w.addName(t,n),w.addType(t,e.type),w.endColumn(t)}(n,t)))));const s=n.createString("L1");let i;e&&(C.startCrs(n),C.addCode(n,e),i=C.endCrs(n)),B.startHeader(n),i&&B.addCrs(n,i),B.addFeaturesCount(n,BigInt(t.featuresCount)),B.addGeometryType(n,t.geometryType),B.addIndexNodeSize(n,0),r&&B.addColumns(n,r),B.addName(n,s);const o=B.endHeader(n);return n.finishSizePrefixed(o),n.asUint8Array()}function wt(t){if("boolean"==typeof t)return a.Bool;if("number"==typeof t)return t%1==0?a.Int:a.Double;if("string"==typeof t)return a.String;if(null===t)return a.String;if("object"==typeof t)return a.Json;throw new Error(`Unknown type (value '${t}')`)}function mt(t,n=0){const r=function(t){const n=t.features[0],r=n.properties;let s=null;r&&(s=Object.keys(r).map((t=>function(t,e){return{name:e,type:wt(t[e]),title:null,description:null,width:-1,precision:-1,scale:-1,nullable:!0,unique:!1,primary_key:!1}}(r,t))));const i=function(t){let n;for(const s of t){if(n===e.Unknown)break;const t=(r=s).getGeometry?f(r.getGeometry().getType()):f(r.geometry.type);void 0===n?n=t:n!==t&&(n=e.Unknown)}var r;if(void 0===n)throw new Error("Could not infer geometry type for collection of features.");return n}(t.features),o={geometryType:i,columns:s,envelope:null,featuresCount:t.features.length,indexNodeSize:0,crs:null,title:null,description:null,metadata:null};return o}(t),s=gt(r,n),i=t.features.map((t=>F("GeometryCollection"===t.geometry.type?_(t.geometry):p(t.geometry),t.properties,r))),o=i.map((t=>t.length)).reduce(((t,e)=>t+e)),a=new Uint8Array(lt.length+s.length+o);a.set(s,lt.length);let c=lt.length+s.length;for(const t of i)a.set(t,c),c+=t.length;return a.set(lt),a}function vt(t,e){const n=function(t,e,n){if(!t.subarray(0,3).every(((t,e)=>lt[e]===t)))throw new Error("Not a FlatGeobuf file");const r=new c(t),s=r.readUint32(lt.length);r.setPosition(lt.length+bt);const i=V(r);n&&n(i);let o=lt.length+bt+s;const{indexNodeSize:a,featuresCount:u}=i;a>0&&(o+=ut(u,a));const h=[];for(;o0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(t){return this instanceof N?(this.v=t,this):new N(t)}function R(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(t,e||[]),i=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(t){s[t]&&(n[t]=function(e){return new Promise((function(r,n){i.push([t,e,r,n])>1||a(t,e)}))})}function a(t,e){try{(r=s[t](e)).value instanceof N?Promise.resolve(r.value.v).then(h,c):u(i[0][2],r)}catch(t){u(i[0][3],t)}var r}function h(t){a("next",t)}function c(t){a("throw",t)}function u(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}var q=function(t){function e(e){var r=t.call(this,e)||this;return Object.defineProperty(r,"name",{value:"RepeaterOverflowError",enumerable:!1}),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(r,r.constructor.prototype):r.__proto__=r.constructor.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,r.constructor),r}return function(t,e){function r(){this.constructor=t}T(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}(e,t),e}(Error);function M(t){null!=t&&"function"==typeof t.then&&t.then($,$)}!function(){function t(t){if(t<0)throw new RangeError("Capacity may not be less than 0");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return this._q.length>=this._c},enumerable:!1,configurable:!0}),t.prototype.add=function(t){if(this.full)throw new Error("Buffer full");this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){for(;this._q.length>=this._c;)this._q.shift();this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){this._q.length=3;return Promise.resolve(e).then((function(e){return!r&&t.state>=4?z(t).then((function(t){return{value:t,done:!0}})):{value:e,done:r}}))}function D(t,e){var r,n;if(!(t.state>=2))if(t.state=2,t.onnext(),t.onstop(),null==t.err&&(t.err=e),0!==t.pushes.length||void 0!==t.buffer&&!t.buffer.empty)try{for(var s=L(t.pushes),i=s.next();!i.done;i=s.next()){i.value.resolve()}}catch(t){r={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}else H(t)}function H(t){var e,r;if(!(t.state>=3)){t.state<2&&D(t),t.state=3,t.buffer=void 0;try{for(var n=L(t.nexts),s=n.next();!s.done;s=n.next()){var i=s.value,o=void 0===t.pending?z(t):t.pending.then((function(){return z(t)}));i.resolve(G(t,o))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}t.pushes=[],t.nexts=[]}}function W(t){t.state>=4||(t.state<3&&H(t),t.state=4)}function Z(t,e){if(M(e),t.pushes.length>=j)throw new q("No more than 1024 pending calls to push are allowed on a single repeater.");if(t.state>=2)return Promise.resolve(void 0);var r,n=void 0===t.pending?Promise.resolve(e):t.pending.then((function(){return e}));(n=n.catch((function(e){t.state<2&&(t.err=e),W(t)})),t.nexts.length)?(t.nexts.shift().resolve(G(t,n)),r=t.nexts.length?Promise.resolve(t.nexts[0].value):new Promise((function(e){return t.onnext=e}))):void 0===t.buffer||t.buffer.full?r=new Promise((function(e){return t.pushes.push({resolve:e,value:n})})):(t.buffer.add(n),r=Promise.resolve(void 0));var s=!0,i={},o=r.catch((function(t){if(s)throw t}));return i.then=function(t,e){return s=!1,Promise.prototype.then.call(r,t,e)},i.catch=function(t){return s=!1,Promise.prototype.catch.call(r,t)},i.finally=r.finally.bind(r),t.pending=n.then((function(){return o})).catch((function(e){t.err=e,W(t)})),i}function X(t){if(!(t.state>=1)){t.state=1;var e=Z.bind(null,t),r=function(t){var e=D.bind(null,t),r=new Promise((function(e){return t.onstop=e}));return e.then=r.then.bind(r),e.catch=r.catch.bind(r),e.finally=r.finally.bind(r),e}(t);t.execution=new Promise((function(n){return n(t.executor(e,r))})),t.execution.catch((function(){return D(t)}))}}var Y,K=new WeakMap,J=function(){function t(t,e){K.set(this,{executor:t,buffer:e,err:void 0,state:0,pushes:[],nexts:[],pending:void 0,execution:void 0,onnext:$,onstop:$})}return t.prototype.next=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");if(e.nexts.length>=j)throw new q("No more than 1024 pending calls to next are allowed on a single repeater.");if(e.state<=0&&X(e),e.onnext(t),void 0!==e.buffer&&!e.buffer.empty){var r=G(e,e.buffer.remove());if(e.pushes.length){var n=e.pushes.shift();e.buffer.add(n.value),e.onnext=n.resolve}return r}if(e.pushes.length){var s=e.pushes.shift();return e.onnext=s.resolve,G(e,s.value)}return e.state>=2?(H(e),G(e,z(e))):new Promise((function(r){return e.nexts.push({resolve:r,value:t})}))},t.prototype.return=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return H(e),e.execution=Promise.resolve(e.execution).then((function(){return t})),G(e,z(e))},t.prototype.throw=function(t){var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return e.state<=0||e.state>=2||void 0!==e.buffer&&!e.buffer.empty?(H(e),null==e.err&&(e.err=t),G(e,z(e))):this.next(Promise.reject(t))},t.prototype[Symbol.asyncIterator]=function(){return this},t.race=tt,t.merge=et,t.zip=rt,t.latest=nt,t}();function Q(t,e){var r,n,s=[],i=function(t){null!=t&&"function"==typeof t[Symbol.asyncIterator]?s.push(t[Symbol.asyncIterator]()):null!=t&&"function"==typeof t[Symbol.iterator]?s.push(t[Symbol.iterator]()):s.push(function(){return R(this,arguments,(function(){return k(this,(function(r){switch(r.label){case 0:return e.yieldValues?[4,N(t)]:[3,3];case 1:return[4,r.sent()];case 2:r.sent(),r.label=3;case 3:return e.returnValues?[4,N(t)]:[3,5];case 4:return[2,r.sent()];case 5:return[2]}}))}))}())};try{for(var o=L(t),a=o.next();!a.done;a=o.next()){i(a.value)}}catch(t){r={error:t}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return s}function tt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2];s=!1,n.then((function(){e(),s=!0})),c.label=1;case 1:c.trys.push([1,,5,7]),o=void 0,a=0,h=function(){var s,h,c,u,l,b;return k(this,(function(f){switch(f.label){case 0:s=a;try{for(l=void 0,h=L(r),c=h.next();!c.done;c=h.next())u=c.value,Promise.resolve(u.next()).then((function(t){t.done?(n(),void 0===i&&(i=t)):a===s&&(a++,e(t))}),(function(t){return n(t)}))}catch(t){l={error:t}}finally{try{c&&!c.done&&(b=h.return)&&b.call(h)}finally{if(l)throw l.error}}return[4,new Promise((function(t){return e=t}))];case 1:return void 0===(o=f.sent())?[3,3]:[4,t(o.value)];case 2:f.sent(),f.label=3;case 3:return[2]}}))},c.label=2;case 2:return s?[3,4]:[5,h()];case 3:return c.sent(),[3,2];case 4:return[2,i&&i.value];case 5:return n(),[4,Promise.race(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}function et(t){var e=this,r=Q(t,{yieldValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o=this;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2];e=[],s=!1,n.then((function(){var t,r;s=!0;try{for(var n=L(e),i=n.next();!i.done;i=n.next()){(0,i.value)()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all(r.map((function(r,a){return B(o,void 0,void 0,(function(){var o;return k(this,(function(h){switch(h.label){case 0:h.trys.push([0,,6,9]),h.label=1;case 1:return s?[3,5]:(Promise.resolve(r.next()).then((function(t){return e[a](t)}),(function(t){return n(t)})),[4,new Promise((function(t){e[a]=t}))]);case 2:return void 0===(o=h.sent())?[3,4]:o.done?(i=o,[2]):[4,t(o.value)];case 3:h.sent(),h.label=4;case 4:return[3,1];case 5:return[3,9];case 6:return r.return?[4,r.return()]:[3,8];case 7:h.sent(),h.label=8;case 8:return[7];case 9:return[2]}}))}))})))];case 2:return a.sent(),[2,i&&i.value];case 3:return n(),[7];case 4:return[2]}}))}))}))}function rt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2,[]];s=!1,n.then((function(){e(),s=!0})),a.label=1;case 1:a.trys.push([1,,6,8]),a.label=2;case 2:return s?[3,5]:(Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))]);case 3:return void 0===(i=a.sent())?[2]:(o=i.map((function(t){return t.value})),i.some((function(t){return t.done}))?[2,o]:[4,t(o)]);case 4:return a.sent(),[3,2];case 5:return[3,8];case 6:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 7:return a.sent(),[7];case 8:return[2]}}))}))}))}function nt(t){var e=this,r=Q(t,{yieldValues:!0,returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h=this;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2,[]];s=[],i=!1,n.then((function(){var t,r;e();try{for(var n=L(s),o=n.next();!o.done;o=n.next()){(0,o.value)()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}i=!0})),c.label=1;case 1:return c.trys.push([1,,5,7]),Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))];case 2:return void 0===(o=c.sent())?[2]:(a=o.map((function(t){return t.value})),o.every((function(t){return t.done}))?[2,a]:[4,t(a.slice())]);case 3:return c.sent(),[4,Promise.all(r.map((function(e,r){return B(h,void 0,void 0,(function(){var h;return k(this,(function(c){switch(c.label){case 0:if(o[r].done)return[2,o[r].value];c.label=1;case 1:return i?[3,4]:(Promise.resolve(e.next()).then((function(t){return s[r](t)}),(function(t){return n(t)})),[4,new Promise((function(t){return s[r]=t}))]);case 2:return void 0===(h=c.sent())?[2,o[r].value]:h.done?[2,h.value]:(a[r]=h.value,[4,t(a.slice())]);case 3:return c.sent(),[3,1];case 4:return[2]}}))}))})))];case 4:return[2,c.sent()];case 5:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}class st{constructor(){this._extraRequestThreshold=262144}extraRequestThreshold(){return this._extraRequestThreshold}setExtraRequestThreshold(t){if(t<0)throw new Error("extraRequestThreshold cannot be negative");this._extraRequestThreshold=t}}st.global=new st,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error"}(Y||(Y={}));class it{static debug(){for(var t=arguments.length,e=new Array(t),r=0;rt)){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;nthis.nodes[1]),this.nodes[1]=t}toString(){return`[NodeRange level: ${this._level}, nodes: ${this.nodes[0]}-${this.nodes[1]}]`}}const{minX:i,minY:o,maxX:a,maxY:h}=r;it.info(`tree items: ${t}, nodeSize: ${e}`);const c=function(t,e){if(e<2)throw new Error("Node size must be at least 2");if(0===t)throw new Error("Number of items must be greater than 0");let r=t,n=r;const s=[r];do{r=Math.ceil(r/e),n+=r,s.push(r)}while(1!==r);const i=[];r=n;for(const t of s)i.push(r-t),r-=t;i.reverse(),s.reverse();const o=[];for(let t=0;t{const t=c.length-1;return new s([0,1],t)})()];for(it.debug(`starting stream search with queue: ${l}, numItems: ${t}, nodeSize: ${e}, levelBounds: ${c}`);0!=l.length;){const r=l.shift();it.debug(`popped node: ${r}, queueLength: ${l.length}`);const b=r.startNode(),f=b>=u,[,d]=c[r.level()],_=Math.min(r.endNode()+e,d),p=_-b,y=await n(40*b,40*p),g=new Float64Array(y),w=new Uint32Array(y);for(let e=b;e<_;e++){const n=5*(e-b);if(ag[n+2])continue;if(o>g[n+3])continue;const c=w[8+(n<<1)],d=ht(w[9+(n<<1)],c);if(f){const r=(()=>{if(e ${d}`),p.extendEndNodeToNewOffset(d);continue}const y=(()=>{const t=r.level()-1;return new s([d,d+1],t)})();void 0!==p&&p.level()==y.level()?it.info(`Same level, but too far away. Pushing new request at offset: ${d} rather than merging with distant ${p}`):it.info(`Pushing new level for ${y} onto queue with nearestNodeRange: ${p} since there's not already a range for this level.`),l.push(y)}}}function ht(t,e){if(0!=(4293918720&t))throw Error("integer is too large to be safely represented");return e+t*2**32}const ct=new Uint8Array([102,103,98,3,102,103,98,0]);class ut{constructor(t,e,r,n){this.headerClient=t,this.header=e,this.headerLength=r,this.indexLength=n}static async open(t){const e=new lt(t),r=(()=>{let t,e=0;for(t=0;t<3;t++){e+=16**t*40}return e})(),n=2024+r;it.debug(`fetching header. minReqLength: ${n} (assumedHeaderLength: 2024, assumedIndexLength: ${r})`);{const t=new Uint8Array(await e.getRange(0,8,n,"header"));if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw it.error(`bytes: ${t} != ${ct}`),new Error("Not a FlatGeobuf file");it.debug("magic bytes look good")}let s;{const t=await e.getRange(8,4,n,"header");s=new DataView(t).getUint32(0,!0);if(s>10485760||s<8)throw new Error("Invalid header size");it.debug(`headerLength: ${s}`)}const i=await e.getRange(12,s,n,"header"),o=new l(new Uint8Array(i)),a=p.fromByteBuffer(o),h=ot(a.featuresCount,a.indexNodeSize);return it.debug("completed: opening http reader"),new ut(e,a,s,h)}async*selectBbox(t){const e=this.lengthBeforeTree(),r=this.headerClient,n=async function(t,n){return r.getRange(e+t,n,0,"index")},s=[];let i=[];for await(const e of at(this.header.featuresCount,this.header.indexNodeSize,t,n)){const[t,,]=e;let[,,r]=e;if(!r){it.info("final feature");r=st.global.extraRequestThreshold()}if(0==i.length){i.push([t,r]);continue}const n=i[i.length-1],o=t-(n[0]+n[1]);o>st.global.extraRequestThreshold()&&(it.info(`Pushing new feature batch, since gap ${o} was too large`),s.push(i),i=[]),i.push([t,r])}this.headerClient.logUsage("header+index"),i.length>0&&s.push(i);const o=s.flatMap((t=>this.readFeatureBatch(t)));yield*J.merge(o)}lengthBeforeTree(){return ct.length+4+this.headerLength}lengthBeforeFeatures(){return this.lengthBeforeTree()+this.indexLength}buildFeatureClient(){return new lt(this.headerClient.httpClient)}async*readFeatureBatch(t){const[e]=t[0],[r,n]=t[t.length-1],s=r+n-e,i=this.buildFeatureClient();for(const[e]of t)yield await this.readFeature(i,e,s);i.logUsage("feature")}async readFeature(t,e,r){const n=e+this.lengthBeforeFeatures();let s;{const e=await t.getRange(n,4,r,"feature length");s=new DataView(e).getUint32(0,!0)}const i=await t.getRange(n+4,s,r,"feature data"),o=new Uint8Array(i),a=new Uint8Array(s+4);a.set(o,4);const h=new l(a);return h.setPosition(4),U.getRootAsFeature(h)}}class lt{constructor(t){this.bytesEverUsed=0,this.bytesEverFetched=0,this.buffer=new ArrayBuffer(0),this.head=0,this.httpClient="string"==typeof t?new bt(t):t}async getRange(t,e,r,n){this.bytesEverUsed+=e;const s=t-this.head,i=s+e;if(s>=0&&i<=this.buffer.byteLength)return this.buffer.slice(s,i);const o=Math.max(e,r);return this.bytesEverFetched+=o,it.debug(`requesting for new Range: ${t}-${t+e-1}`),this.buffer=await this.httpClient.getRange(t,o,n),this.head=t,this.buffer.slice(0,e)}logUsage(t){const e=t.split(" ")[0],r=this.bytesEverUsed,n=this.bytesEverFetched,s=(100*r/n).toFixed(2);it.info(`${e} bytes used/requested: ${r} / ${n} = ${s}%`)}}class bt{constructor(t){this.requestsEverMade=0,this.bytesEverRequested=0,this.url=t}async getRange(t,e,r){this.requestsEverMade+=1,this.bytesEverRequested+=e;const n=`bytes=${t}-${t+e-1}`;it.info(`request: #${this.requestsEverMade}, purpose: ${r}), bytes: (this_request: ${e}, ever: ${this.bytesEverRequested}), Range: ${n}`);return(await fetch(this.url,{headers:{Range:n}})).arrayBuffer()}}async function*ft(t,e,r){const n="function"==typeof(s=t).slice?s:new E("function"==typeof s.read?s:s.getReader());var s;const i=async t=>await n.slice(t);let o=new Uint8Array(await i(8));if(!o.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");o=new Uint8Array(await i(4));let a=new l(o);const h=a.readUint32(0);o=new Uint8Array(await i(h)),a=new l(o);const c=p.fromByteBuffer(a);r&&r(c);const{indexNodeSize:u,featuresCount:b}=c;if(u>0){const t=ot(b,u);await i(t)}let f;for(;f=await dt(i,c,e);)yield f}async function dt(t,e,r){let n=new Uint8Array(await t(4,"feature length"));if(0===n.byteLength)return;let s=new l(n);const i=s.readUint32(0);n=new Uint8Array(await t(i,"feature data"));const o=new Uint8Array(i+4);o.set(n,4),s=new l(o),s.setPosition(4);return r(U.getRootAsFeature(s),e)}function _t(t){const e=new b;let r=null;t.columns&&(r=_.createColumnsVector(e,t.columns.map((t=>function(t,e){const r=t.createString(e.name);return f.startColumn(t),f.addName(t,r),f.addType(t,e.type),f.endColumn(t)}(e,t)))));const n=e.createString("L1");_.startHeader(e),_.addFeaturesCount(e,new h(t.featuresCount,0)),_.addGeometryType(e,t.geometryType),_.addIndexNodeSize(e,0),r&&_.addColumns(e,r),_.addName(e,n);const s=_.endHeader(e);return e.finishSizePrefixed(s),e.asUint8Array()}function pt(t){const n=function(t){const n=t.features[0].properties;let s=null;n&&(s=Object.keys(n).map((t=>new e(t,function(t){if("boolean"==typeof t)return r.Bool;if("number"==typeof t)return t%1==0?r.Int:r.Double;if("string"==typeof t)return r.String;if(null===t)return r.String;throw new Error(`Unknown type (value '${t}')`)}(n[t]),null,null,-1,-1,-1,!0,!1,!1))));const i=function(t){let e;for(const n of t){if(e===u.Unknown)break;const t=(r=n).getGeometry?m(r.getGeometry().getType()):m(r.geometry.type);void 0===e?e=t:e!==t&&(e=u.Unknown)}var r;if(void 0===e)throw new Error("Could not infer geometry type for collection of features.");return e}(t.features);return new p(i,s,t.features.length,0,null,null,null,null)}(t),s=_t(n),i=t.features.map((t=>S(I(t.geometry),t.properties,n))),o=i.map((t=>t.length)).reduce(((t,e)=>t+e)),a=new Uint8Array(ct.length+s.length+o);a.set(s,ct.length);let h=ct.length+s.length;for(const t of i)a.set(t,h),h+=t.length;return a.set(ct),a}function yt(t,e){const r=function(t,e,r){if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");const n=new l(t),s=n.readUint32(ct.length);n.setPosition(ct.length+4);const i=p.fromByteBuffer(n);r&&r(i);let o=ct.length+4+s;const{indexNodeSize:a,featuresCount:h}=i;a>0&&(o+=ot(h,a));const c=[];for(;o>>0)+4294967296*this.high}equals(t){return this.low==t.low&&this.high==t.high}}var c,u;h.ZERO=new h(0,0),function(t){t[t.UTF8_BYTES=1]="UTF8_BYTES",t[t.UTF16_STRING=2]="UTF16_STRING"}(c||(c={}));class l{constructor(t){this.bytes_=t,this.position_=0}static allocate(t){return new l(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return new h(this.readInt32(t),this.readInt32(t+4))}readUint64(t){return new h(this.readUint32(t),this.readUint32(t+4))}readFloat32(t){return s[0]=this.readInt32(t),i[0]}readFloat64(t){return s[a?0:1]=this.readInt32(t),s[a?1:0]=this.readInt32(t+4),o[0]}writeInt8(t,e){this.bytes_[t]=e}writeUint8(t,e){this.bytes_[t]=e}writeInt16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)}writeUint64(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)}writeFloat32(t,e){i[0]=e,this.writeInt32(t,s[0])}writeFloat64(t,e){o[0]=e,this.writeInt32(t,s[a?0:1]),this.writeInt32(t+4,s[a?1:0])}getBufferIdentifier(){if(this.bytes_.length>10),56320+(1023&e)))}return n}__union_with_string(t,e){return"string"==typeof t?this.__string(e):this.__union(t,e)}__indirect(t){return t+this.readInt32(t)}__vector(t){return t+this.readInt32(t)+4}__vector_len(t){return this.readInt32(t+this.readInt32(t))}__has_identifier(t){if(4!=t.length)throw new Error("FlatBuffers: file identifier must be length 4");for(let e=0;e<4;e++)if(t.charCodeAt(e)!=this.readInt8(this.position()+4+e))return!1;return!0}createLong(t,e){return h.create(t,e)}createScalarList(t,e){const r=[];for(let n=0;nthis.minalign&&(this.minalign=t);const r=1+~(this.bb.capacity()-this.space+e)&t-1;for(;this.space=0&&0==this.vtable[e];e--);const r=e+1;for(;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);const n=2*(r+2);this.addInt16(n);let s=0;const i=this.space;t:for(e=0;e=0;e--)this.writeInt8(t.charCodeAt(e))}this.prep(this.minalign,4+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const r=this.bb.capacity()-t,n=r-this.bb.readInt32(r);if(!(0!=this.bb.readInt16(n+e)))throw new Error("FlatBuffers: field "+e+" must be set")}startVector(t,e,r){this.notNested(),this.vector_num_elems=e,this.prep(4,t*e),this.prep(r,t*e)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(t){if(!t)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(t))return this.string_maps.get(t);const e=this.createString(t);return this.string_maps.set(t,e),e}createString(t){if(!t)return 0;let e;if(t instanceof Uint8Array)e=t;else{e=[];let r=0;for(;r=56320)n=s;else{n=(s<<10)+t.charCodeAt(r++)+-56613888}n<128?e.push(n):(n<2048?e.push(n>>6&31|192):(n<65536?e.push(n>>12&15|224):e.push(n>>18&7|240,n>>12&63|128),e.push(n>>6&63|128)),e.push(63&n|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(let t=0,r=this.space,n=this.bb.bytes();t=0;r--)t.addFloat64(e[r]);return t.endVector()}static startEnvelopeVector(t,e){t.startVector(8,e,8)}static addGeometryType(t,e){t.addFieldInt8(2,e,u.Unknown)}static addHasZ(t,e){t.addFieldInt8(3,+e,0)}static addHasM(t,e){t.addFieldInt8(4,+e,0)}static addHasT(t,e){t.addFieldInt8(5,+e,0)}static addHasTm(t,e){t.addFieldInt8(6,+e,0)}static addColumns(t,e){t.addFieldOffset(7,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static addFeaturesCount(t,e){t.addFieldInt64(8,e,t.createLong(0,0))}static addIndexNodeSize(t,e){t.addFieldInt16(9,e,16)}static addCrs(t,e){t.addFieldOffset(10,e,0)}static addTitle(t,e){t.addFieldOffset(11,e,0)}static addDescription(t,e){t.addFieldOffset(12,e,0)}static addMetadata(t,e){t.addFieldOffset(13,e,0)}static endHeader(t){return t.endObject()}static finishHeaderBuffer(t,e){t.finish(e)}static finishSizePrefixedHeaderBuffer(t,e){t.finish(e,void 0,!0)}}class p{constructor(t,e,r,n,s,i,o,a){this.geometryType=t,this.columns=e,this.featuresCount=r,this.indexNodeSize=n,this.crs=s,this.title=i,this.description=o,this.metadata=a}static fromByteBuffer(t){const r=_.getRootAsHeader(t),s=r.featuresCount().toFloat64(),i=r.indexNodeSize(),o=[];for(let t=0;t=0;r--)t.addInt32(e[r]);return t.endVector()}static startEndsVector(t,e){t.startVector(4,e,4)}static addXy(t,e){t.addFieldOffset(1,e,0)}static createXyVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startXyVector(t,e){t.startVector(8,e,8)}static addZ(t,e){t.addFieldOffset(2,e,0)}static createZVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startZVector(t,e){t.startVector(8,e,8)}static addM(t,e){t.addFieldOffset(3,e,0)}static createMVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startMVector(t,e){t.startVector(8,e,8)}static addT(t,e){t.addFieldOffset(4,e,0)}static createTVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startTVector(t,e){t.startVector(8,e,8)}static addTm(t,e){t.addFieldOffset(5,e,0)}static createTmVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startTmVector(t,e){t.startVector(8,e,8)}static addType(t,e){t.addFieldInt8(6,e,u.Unknown)}static addParts(t,e){t.addFieldOffset(7,e,0)}static createPartsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startPartsVector(t,e){t.startVector(4,e,4)}static endGeometry(t){return t.endObject()}static createGeometry(t,e,r,n,s,i,o,a,h){return y.startGeometry(t),y.addEnds(t,e),y.addXy(t,r),y.addZ(t,n),y.addM(t,s),y.addT(t,i),y.addTm(t,o),y.addType(t,a),y.addParts(t,h),y.endGeometry(t)}}function g(t,e){const{xy:r,z:n,ends:s,parts:i,type:o}=e;if(i){const e=i.map((e=>g(t,e))),r=y.createPartsVector(t,e);return y.startGeometry(t),y.addParts(t,r),y.addType(t,o),y.endGeometry(t)}const a=y.createXyVector(t,r);let h,c;return n&&(h=y.createZVector(t,n)),s&&(c=y.createEndsVector(t,s)),y.startGeometry(t),c&&y.addEnds(t,c),y.addXy(t,a),h&&y.addZ(t,h),y.addType(t,o),y.endGeometry(t)}function w(t,e,r){if(0!==t.length)if(Array.isArray(t[0]))for(const n of t)w(n,e,r);else 2===t.length?e.push(...t):(e.push(t[0],t[1]),r.push(t[2]))}function v(t,e){const r=[];for(let n=0;n>1]),r.push(s)}return r}function m(t){if(!t)return u.Unknown;return u[t]}function I(t){const e=t.coordinates,r=[],n=[];let s,i;const o=m(t.type);let a=0;switch(t.type){case"Point":case"MultiPoint":case"LineString":w(e,r,n);break;case"MultiLineString":case"Polygon":{const t=e;w(t,r,n),t.length>1&&(s=t.map((t=>a+=t.length)));break}case"MultiPolygon":i=e.map((t=>({type:"Polygon",coordinates:t}))).map(I);break;case"GeometryCollection":t.geometries&&(i=t.geometries.map(I))}return{xy:r,z:n.length>0?n:void 0,ends:s,type:o,parts:i}}function F(t,e,r){if(!r||0===r.length)return[v(t,e)];let n=0;const s=Array.from(r).map((e=>t.slice(n,n=e<<1)));let i;return e&&(n=0,i=Array.from(r).map((t=>e.slice(n,n=t)))),s.map(((t,e)=>v(t,i?i[e]:void 0)))}function x(t,e){let r=e;if(r===u.Unknown&&(r=t.type()),r===u.GeometryCollection){const e=[];for(let r=0;rt.coordinates))}}const n=function(t,e){const r=t.xyArray(),n=t.zArray();switch(e){case u.Point:{const t=Array.from(r);return n&&t.push(n[0]),t}case u.MultiPoint:case u.LineString:return v(r,n);case u.MultiLineString:case u.Polygon:return F(r,n,t.endsArray())}}(t,r);return{type:u[r],coordinates:n}}class U{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFeature(t,e){return(e||new U).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFeature(t,e){return t.setPosition(t.position()+4),(e||new U).__init(t.readInt32(t.position())+t.position(),t)}geometry(t){const e=this.bb.__offset(this.bb_pos,4);return e?(t||new y).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}properties(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}propertiesLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}propertiesArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}columns(t,e){const r=this.bb.__offset(this.bb_pos,8);return r?(e||new f).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFeature(t){t.startObject(3)}static addGeometry(t,e){t.addFieldOffset(0,e,0)}static addProperties(t,e){t.addFieldOffset(1,e,0)}static createPropertiesVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startPropertiesVector(t,e){t.startVector(1,e,1)}static addColumns(t,e){t.addFieldOffset(2,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static endFeature(t){return t.endObject()}static finishFeatureBuffer(t,e){t.finish(e)}static finishSizePrefixedFeatureBuffer(t,e){t.finish(e,void 0,!0)}static createFeature(t,e,r,n){return U.startFeature(t),U.addGeometry(t,e),U.addProperties(t,r),U.addColumns(t,n),U.endFeature(t)}}const P=new TextEncoder,O=new TextDecoder;function S(t,e,n){const s=n.columns,i=new b;let o=0,a=1024,h=new Uint8Array(a),c=new DataView(h.buffer);const u=function(t){if(o+t0&&(l=U.createPropertiesVector(i,h.slice(0,o)));const f=g(i,t);U.startFeature(i),U.addGeometry(i,f),l&&U.addProperties(i,l);const d=U.endFeature(i);return i.finishSizePrefixed(d),i.asUint8Array()}function C(t,e){const n=e.columns,s={type:"Feature",geometry:x(t.geometry(),e.geometryType)};return n&&n.length>0&&(s.properties=function(t,e){const n={};if(!e||0===e.length)return n;const s=t.propertiesArray();if(!s)return n;const i=new DataView(s.buffer,s.byteOffset),o=t.propertiesLength();let a=0;for(;a0?{done:!1,value:e}:{done:!0,value:void 0}:{done:!1,value:V(e,r.value)}}))},E.prototype.slice=function(t){if((t|=0)<0)throw new Error("invalid length");var e=this,r=this._array.length-this._index;if(this._index+t<=this._array.length)return Promise.resolve(this._array.subarray(this._index,this._index+=t));var n=new Uint8Array(t);return n.set(this._array.subarray(this._index)),function s(){return e._source.read().then((function(i){return i.done?(e._array=A,e._index=0,r>0?n.subarray(0,r):null):r+i.value.length>=t?(e._array=i.value,e._index=t-r,n.set(i.value.subarray(0,t-r),r),n):(n.set(i.value,r),r+=i.value.length,s())}))}()},E.prototype.cancel=function(){return this._source.cancel()}; +/*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ +var T=function(t,e){return T=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},T(t,e)};function B(t,e,r,n){return new(r||(r=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function a(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,a)}h((n=n.apply(t,e||[])).next())}))}function k(t,e){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=o.trys,(s=s.length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(t){return this instanceof N?(this.v=t,this):new N(t)}function R(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(t,e||[]),i=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(t){s[t]&&(n[t]=function(e){return new Promise((function(r,n){i.push([t,e,r,n])>1||a(t,e)}))})}function a(t,e){try{(r=s[t](e)).value instanceof N?Promise.resolve(r.value.v).then(h,c):u(i[0][2],r)}catch(t){u(i[0][3],t)}var r}function h(t){a("next",t)}function c(t){a("throw",t)}function u(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}var q=function(t){function e(e){var r=t.call(this,e)||this;return Object.defineProperty(r,"name",{value:"RepeaterOverflowError",enumerable:!1}),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(r,r.constructor.prototype):r.__proto__=r.constructor.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,r.constructor),r}return function(t,e){function r(){this.constructor=t}T(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}(e,t),e}(Error);function M(t){null!=t&&"function"==typeof t.then&&t.then($,$)}!function(){function t(t){if(t<0)throw new RangeError("Capacity may not be less than 0");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return this._q.length>=this._c},enumerable:!1,configurable:!0}),t.prototype.add=function(t){if(this.full)throw new Error("Buffer full");this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){for(;this._q.length>=this._c;)this._q.shift();this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){this._q.length=3;return Promise.resolve(e).then((function(e){return!r&&t.state>=4?z(t).then((function(t){return{value:t,done:!0}})):{value:e,done:r}}))}function D(t,e){var r,n;if(!(t.state>=2))if(t.state=2,t.onnext(),t.onstop(),null==t.err&&(t.err=e),0!==t.pushes.length||void 0!==t.buffer&&!t.buffer.empty)try{for(var s=L(t.pushes),i=s.next();!i.done;i=s.next()){i.value.resolve()}}catch(t){r={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}else H(t)}function H(t){var e,r;if(!(t.state>=3)){t.state<2&&D(t),t.state=3,t.buffer=void 0;try{for(var n=L(t.nexts),s=n.next();!s.done;s=n.next()){var i=s.value,o=void 0===t.pending?z(t):t.pending.then((function(){return z(t)}));i.resolve(G(t,o))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}t.pushes=[],t.nexts=[]}}function W(t){t.state>=4||(t.state<3&&H(t),t.state=4)}function Z(t,e){if(M(e),t.pushes.length>=j)throw new q("No more than 1024 pending calls to push are allowed on a single repeater.");if(t.state>=2)return Promise.resolve(void 0);var r,n=void 0===t.pending?Promise.resolve(e):t.pending.then((function(){return e}));(n=n.catch((function(e){t.state<2&&(t.err=e),W(t)})),t.nexts.length)?(t.nexts.shift().resolve(G(t,n)),r=t.nexts.length?Promise.resolve(t.nexts[0].value):new Promise((function(e){return t.onnext=e}))):void 0===t.buffer||t.buffer.full?r=new Promise((function(e){return t.pushes.push({resolve:e,value:n})})):(t.buffer.add(n),r=Promise.resolve(void 0));var s=!0,i={},o=r.catch((function(t){if(s)throw t}));return i.then=function(t,e){return s=!1,Promise.prototype.then.call(r,t,e)},i.catch=function(t){return s=!1,Promise.prototype.catch.call(r,t)},i.finally=r.finally.bind(r),t.pending=n.then((function(){return o})).catch((function(e){t.err=e,W(t)})),i}function X(t){if(!(t.state>=1)){t.state=1;var e=Z.bind(null,t),r=function(t){var e=D.bind(null,t),r=new Promise((function(e){return t.onstop=e}));return e.then=r.then.bind(r),e.catch=r.catch.bind(r),e.finally=r.finally.bind(r),e}(t);t.execution=new Promise((function(n){return n(t.executor(e,r))})),t.execution.catch((function(){return D(t)}))}}var Y,K=new WeakMap,J=function(){function t(t,e){K.set(this,{executor:t,buffer:e,err:void 0,state:0,pushes:[],nexts:[],pending:void 0,execution:void 0,onnext:$,onstop:$})}return t.prototype.next=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");if(e.nexts.length>=j)throw new q("No more than 1024 pending calls to next are allowed on a single repeater.");if(e.state<=0&&X(e),e.onnext(t),void 0!==e.buffer&&!e.buffer.empty){var r=G(e,e.buffer.remove());if(e.pushes.length){var n=e.pushes.shift();e.buffer.add(n.value),e.onnext=n.resolve}return r}if(e.pushes.length){var s=e.pushes.shift();return e.onnext=s.resolve,G(e,s.value)}return e.state>=2?(H(e),G(e,z(e))):new Promise((function(r){return e.nexts.push({resolve:r,value:t})}))},t.prototype.return=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return H(e),e.execution=Promise.resolve(e.execution).then((function(){return t})),G(e,z(e))},t.prototype.throw=function(t){var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return e.state<=0||e.state>=2||void 0!==e.buffer&&!e.buffer.empty?(H(e),null==e.err&&(e.err=t),G(e,z(e))):this.next(Promise.reject(t))},t.prototype[Symbol.asyncIterator]=function(){return this},t.race=tt,t.merge=et,t.zip=rt,t.latest=nt,t}();function Q(t,e){var r,n,s=[],i=function(t){null!=t&&"function"==typeof t[Symbol.asyncIterator]?s.push(t[Symbol.asyncIterator]()):null!=t&&"function"==typeof t[Symbol.iterator]?s.push(t[Symbol.iterator]()):s.push(function(){return R(this,arguments,(function(){return k(this,(function(r){switch(r.label){case 0:return e.yieldValues?[4,N(t)]:[3,3];case 1:return[4,r.sent()];case 2:r.sent(),r.label=3;case 3:return e.returnValues?[4,N(t)]:[3,5];case 4:return[2,r.sent()];case 5:return[2]}}))}))}())};try{for(var o=L(t),a=o.next();!a.done;a=o.next()){i(a.value)}}catch(t){r={error:t}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return s}function tt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2];s=!1,n.then((function(){e(),s=!0})),c.label=1;case 1:c.trys.push([1,,5,7]),o=void 0,a=0,h=function(){var s,h,c,u,l,b;return k(this,(function(f){switch(f.label){case 0:s=a;try{for(l=void 0,h=L(r),c=h.next();!c.done;c=h.next())u=c.value,Promise.resolve(u.next()).then((function(t){t.done?(n(),void 0===i&&(i=t)):a===s&&(a++,e(t))}),(function(t){return n(t)}))}catch(t){l={error:t}}finally{try{c&&!c.done&&(b=h.return)&&b.call(h)}finally{if(l)throw l.error}}return[4,new Promise((function(t){return e=t}))];case 1:return void 0===(o=f.sent())?[3,3]:[4,t(o.value)];case 2:f.sent(),f.label=3;case 3:return[2]}}))},c.label=2;case 2:return s?[3,4]:[5,h()];case 3:return c.sent(),[3,2];case 4:return[2,i&&i.value];case 5:return n(),[4,Promise.race(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}function et(t){var e=this,r=Q(t,{yieldValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o=this;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2];e=[],s=!1,n.then((function(){var t,r;s=!0;try{for(var n=L(e),i=n.next();!i.done;i=n.next()){(0,i.value)()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all(r.map((function(r,a){return B(o,void 0,void 0,(function(){var o;return k(this,(function(h){switch(h.label){case 0:h.trys.push([0,,6,9]),h.label=1;case 1:return s?[3,5]:(Promise.resolve(r.next()).then((function(t){return e[a](t)}),(function(t){return n(t)})),[4,new Promise((function(t){e[a]=t}))]);case 2:return void 0===(o=h.sent())?[3,4]:o.done?(i=o,[2]):[4,t(o.value)];case 3:h.sent(),h.label=4;case 4:return[3,1];case 5:return[3,9];case 6:return r.return?[4,r.return()]:[3,8];case 7:h.sent(),h.label=8;case 8:return[7];case 9:return[2]}}))}))})))];case 2:return a.sent(),[2,i&&i.value];case 3:return n(),[7];case 4:return[2]}}))}))}))}function rt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2,[]];s=!1,n.then((function(){e(),s=!0})),a.label=1;case 1:a.trys.push([1,,6,8]),a.label=2;case 2:return s?[3,5]:(Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))]);case 3:return void 0===(i=a.sent())?[2]:(o=i.map((function(t){return t.value})),i.some((function(t){return t.done}))?[2,o]:[4,t(o)]);case 4:return a.sent(),[3,2];case 5:return[3,8];case 6:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 7:return a.sent(),[7];case 8:return[2]}}))}))}))}function nt(t){var e=this,r=Q(t,{yieldValues:!0,returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h=this;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2,[]];s=[],i=!1,n.then((function(){var t,r;e();try{for(var n=L(s),o=n.next();!o.done;o=n.next()){(0,o.value)()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}i=!0})),c.label=1;case 1:return c.trys.push([1,,5,7]),Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))];case 2:return void 0===(o=c.sent())?[2]:(a=o.map((function(t){return t.value})),o.every((function(t){return t.done}))?[2,a]:[4,t(a.slice())]);case 3:return c.sent(),[4,Promise.all(r.map((function(e,r){return B(h,void 0,void 0,(function(){var h;return k(this,(function(c){switch(c.label){case 0:if(o[r].done)return[2,o[r].value];c.label=1;case 1:return i?[3,4]:(Promise.resolve(e.next()).then((function(t){return s[r](t)}),(function(t){return n(t)})),[4,new Promise((function(t){return s[r]=t}))]);case 2:return void 0===(h=c.sent())?[2,o[r].value]:h.done?[2,h.value]:(a[r]=h.value,[4,t(a.slice())]);case 3:return c.sent(),[3,1];case 4:return[2]}}))}))})))];case 4:return[2,c.sent()];case 5:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}class st{constructor(){this._extraRequestThreshold=262144}extraRequestThreshold(){return this._extraRequestThreshold}setExtraRequestThreshold(t){if(t<0)throw new Error("extraRequestThreshold cannot be negative");this._extraRequestThreshold=t}}st.global=new st,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error"}(Y||(Y={}));class it{static debug(){for(var t=arguments.length,e=new Array(t),r=0;rt)){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;nthis.nodes[1]),this.nodes[1]=t}toString(){return`[NodeRange level: ${this._level}, nodes: ${this.nodes[0]}-${this.nodes[1]}]`}}const{minX:i,minY:o,maxX:a,maxY:h}=r;it.info(`tree items: ${t}, nodeSize: ${e}`);const c=function(t,e){if(e<2)throw new Error("Node size must be at least 2");if(0===t)throw new Error("Number of items must be greater than 0");let r=t,n=r;const s=[r];do{r=Math.ceil(r/e),n+=r,s.push(r)}while(1!==r);const i=[];r=n;for(const t of s)i.push(r-t),r-=t;i.reverse(),s.reverse();const o=[];for(let t=0;t{const t=c.length-1;return new s([0,1],t)})()];for(it.debug(`starting stream search with queue: ${l}, numItems: ${t}, nodeSize: ${e}, levelBounds: ${c}`);0!=l.length;){const r=l.shift();it.debug(`popped node: ${r}, queueLength: ${l.length}`);const b=r.startNode(),f=b>=u,[,d]=c[r.level()],_=Math.min(r.endNode()+e,d),p=_-b,y=await n(40*b,40*p),g=new Float64Array(y),w=new Uint32Array(y);for(let e=b;e<_;e++){const n=5*(e-b);if(ag[n+2])continue;if(o>g[n+3])continue;const c=w[8+(n<<1)],d=ht(w[9+(n<<1)],c);if(f){const r=(()=>{if(e ${d}`),p.extendEndNodeToNewOffset(d);continue}const y=(()=>{const t=r.level()-1;return new s([d,d+1],t)})();void 0!==p&&p.level()==y.level()?it.info(`Same level, but too far away. Pushing new request at offset: ${d} rather than merging with distant ${p}`):it.info(`Pushing new level for ${y} onto queue with nearestNodeRange: ${p} since there's not already a range for this level.`),l.push(y)}}}function ht(t,e){if(0!=(4293918720&t))throw Error("integer is too large to be safely represented");return e+t*2**32}const ct=new Uint8Array([102,103,98,3,102,103,98,0]);class ut{constructor(t,e,r,n){this.headerClient=t,this.header=e,this.headerLength=r,this.indexLength=n}static async open(t){const e=new lt(t),r=(()=>{let t,e=0;for(t=0;t<3;t++){e+=16**t*40}return e})(),n=2024+r;it.debug(`fetching header. minReqLength: ${n} (assumedHeaderLength: 2024, assumedIndexLength: ${r})`);{const t=new Uint8Array(await e.getRange(0,8,n,"header"));if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw it.error(`bytes: ${t} != ${ct}`),new Error("Not a FlatGeobuf file");it.debug("magic bytes look good")}let s;{const t=await e.getRange(8,4,n,"header");s=new DataView(t).getUint32(0,!0);if(s>10485760||s<8)throw new Error("Invalid header size");it.debug(`headerLength: ${s}`)}const i=await e.getRange(12,s,n,"header"),o=new l(new Uint8Array(i)),a=p.fromByteBuffer(o),h=ot(a.featuresCount,a.indexNodeSize);return it.debug("completed: opening http reader"),new ut(e,a,s,h)}async*selectBbox(t){const e=this.lengthBeforeTree(),r=this.headerClient,n=async function(t,n){return r.getRange(e+t,n,0,"index")},s=[];let i=[];for await(const e of at(this.header.featuresCount,this.header.indexNodeSize,t,n)){const[t,,]=e;let[,,r]=e;if(!r){it.info("final feature");r=st.global.extraRequestThreshold()}if(0==i.length){i.push([t,r]);continue}const n=i[i.length-1],o=t-(n[0]+n[1]);o>st.global.extraRequestThreshold()&&(it.info(`Pushing new feature batch, since gap ${o} was too large`),s.push(i),i=[]),i.push([t,r])}this.headerClient.logUsage("header+index"),i.length>0&&s.push(i);const o=s.flatMap((t=>this.readFeatureBatch(t)));yield*J.merge(o)}lengthBeforeTree(){return ct.length+4+this.headerLength}lengthBeforeFeatures(){return this.lengthBeforeTree()+this.indexLength}buildFeatureClient(){return new lt(this.headerClient.httpClient)}async*readFeatureBatch(t){const[e]=t[0],[r,n]=t[t.length-1],s=r+n-e,i=this.buildFeatureClient();for(const[e]of t)yield await this.readFeature(i,e,s);i.logUsage("feature")}async readFeature(t,e,r){const n=e+this.lengthBeforeFeatures();let s;{const e=await t.getRange(n,4,r,"feature length");s=new DataView(e).getUint32(0,!0)}const i=await t.getRange(n+4,s,r,"feature data"),o=new Uint8Array(i),a=new Uint8Array(s+4);a.set(o,4);const h=new l(a);return h.setPosition(4),U.getRootAsFeature(h)}}class lt{constructor(t){this.bytesEverUsed=0,this.bytesEverFetched=0,this.buffer=new ArrayBuffer(0),this.head=0,this.httpClient="string"==typeof t?new bt(t):t}async getRange(t,e,r,n){this.bytesEverUsed+=e;const s=t-this.head,i=s+e;if(s>=0&&i<=this.buffer.byteLength)return this.buffer.slice(s,i);const o=Math.max(e,r);return this.bytesEverFetched+=o,it.debug(`requesting for new Range: ${t}-${t+e-1}`),this.buffer=await this.httpClient.getRange(t,o,n),this.head=t,this.buffer.slice(0,e)}logUsage(t){const e=t.split(" ")[0],r=this.bytesEverUsed,n=this.bytesEverFetched,s=(100*r/n).toFixed(2);it.info(`${e} bytes used/requested: ${r} / ${n} = ${s}%`)}}class bt{constructor(t){this.requestsEverMade=0,this.bytesEverRequested=0,this.url=t}async getRange(t,e,r){this.requestsEverMade+=1,this.bytesEverRequested+=e;const n=`bytes=${t}-${t+e-1}`;it.info(`request: #${this.requestsEverMade}, purpose: ${r}), bytes: (this_request: ${e}, ever: ${this.bytesEverRequested}), Range: ${n}`);return(await fetch(this.url,{headers:{Range:n}})).arrayBuffer()}}async function*ft(t,e,r){const n="function"==typeof(s=t).slice?s:new E("function"==typeof s.read?s:s.getReader());var s;const i=async t=>await n.slice(t);let o=new Uint8Array(await i(8));if(!o.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");o=new Uint8Array(await i(4));let a=new l(o);const h=a.readUint32(0);o=new Uint8Array(await i(h)),a=new l(o);const c=p.fromByteBuffer(a);r&&r(c);const{indexNodeSize:u,featuresCount:b}=c;if(u>0){const t=ot(b,u);await i(t)}let f;for(;f=await dt(i,c,e);)yield f}async function dt(t,e,r){let n=new Uint8Array(await t(4,"feature length"));if(0===n.byteLength)return;let s=new l(n);const i=s.readUint32(0);n=new Uint8Array(await t(i,"feature data"));const o=new Uint8Array(i+4);o.set(n,4),s=new l(o),s.setPosition(4);return r(U.getRootAsFeature(s),e)}function _t(t){const e=new b;let r=null;t.columns&&(r=_.createColumnsVector(e,t.columns.map((t=>function(t,e){const r=t.createString(e.name);return f.startColumn(t),f.addName(t,r),f.addType(t,e.type),f.endColumn(t)}(e,t)))));const n=e.createString("L1");_.startHeader(e),_.addFeaturesCount(e,new h(t.featuresCount,0)),_.addGeometryType(e,t.geometryType),_.addIndexNodeSize(e,0),r&&_.addColumns(e,r),_.addName(e,n);const s=_.endHeader(e);return e.finishSizePrefixed(s),e.asUint8Array()}function pt(t){const n=function(t){const n=t.features[0].properties;let s=null;n&&(s=Object.keys(n).map((t=>new e(t,function(t){if("boolean"==typeof t)return r.Bool;if("number"==typeof t)return t%1==0?r.Int:r.Double;if("string"==typeof t)return r.String;if(null===t)return r.String;throw new Error(`Unknown type (value '${t}')`)}(n[t]),null,null,-1,-1,-1,!0,!1,!1))));const i=function(t){let e;for(const n of t){if(e===u.Unknown)break;const t=(r=n).getGeometry?m(r.getGeometry().getType()):m(r.geometry.type);void 0===e?e=t:e!==t&&(e=u.Unknown)}var r;if(void 0===e)throw new Error("Could not infer geometry type for collection of features.");return e}(t.features);return new p(i,s,t.features.length,0,null,null,null,null)}(t),s=_t(n),i=t.features.map((t=>S(I(t.geometry),t.properties,n))),o=i.map((t=>t.length)).reduce(((t,e)=>t+e)),a=new Uint8Array(ct.length+s.length+o);a.set(s,ct.length);let h=ct.length+s.length;for(const t of i)a.set(t,h),h+=t.length;return a.set(ct),a}function yt(t,e){const r=function(t,e,r){if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");const n=new l(t),s=n.readUint32(ct.length);n.setPosition(ct.length+4);const i=p.fromByteBuffer(n);r&&r(i);let o=ct.length+4+s;const{indexNodeSize:a,featuresCount:h}=i;a>0&&(o+=ot(h,a));const c=[];for(;o Date: Wed, 29 May 2024 08:39:43 +0200 Subject: [PATCH 11/17] fgb attach by group fix: id can be single string or property name feat: expose highlightOptions fix: label can be a function --- R/file.R | 12 +- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 293 ++++++++++-------- .../lib/FlatGeoBuf/flatgeobuf-geojson.min.js | 29 +- .../FlatGeoBuf/flatgeobuf-geojson.min_old.js | 17 + man/addFgb.Rd | 3 + 5 files changed, 209 insertions(+), 145 deletions(-) create mode 100644 inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min_old.js diff --git a/R/file.R b/R/file.R index 58482df..31df659 100644 --- a/R/file.R +++ b/R/file.R @@ -305,6 +305,7 @@ addTileFolder = function(map, #' opacity, fillOpacity if those are to be mapped to an attribute column. #' @param minZoom minimum zoom level at which data should be rendered. #' @param maxZoom maximum zoom level at which data should be rendered. +#' @inheritParams leaflet::highlightOptions #' @param ... currently not used. #' #' @examples @@ -358,6 +359,7 @@ addFgb = function(map, scale = scaleOptions(), minZoom = NULL, maxZoom = 52, + highlightOptions = NULL, ...) { @@ -392,7 +394,7 @@ addFgb = function(map, } path_layer = tempfile() dir.create(path_layer) - path_layer = paste0(path_layer, "/", layerId, "_layer.fgb") + path_layer = paste0(path_layer, "/", group, "_layer.fgb") file.copy(file, path_layer, overwrite = TRUE) @@ -417,7 +419,7 @@ addFgb = function(map, map$dependencies = c( map$dependencies - , fileAttachment(path_layer, layerId) + , fileAttachment(path_layer, group) ) if (!is.null(minZoom)) { @@ -440,6 +442,7 @@ addFgb = function(map, , scaleFields , minZoom , maxZoom + , highlightOptions ) } else { leaflet::invokeMethod( @@ -456,6 +459,7 @@ addFgb = function(map, , className , scale , scaleFields + , highlightOptions ) } } else { @@ -496,6 +500,7 @@ addFgb = function(map, , scaleFields , minZoom , maxZoom + , highlightOptions ) } else { leaflet::invokeMethod( @@ -512,6 +517,7 @@ addFgb = function(map, , className , scale , scaleFields + , highlightOptions ) } } @@ -535,7 +541,7 @@ fgbDependencies = function() { list( htmltools::htmlDependency( "FlatGeoBuf" - , '3.21.3' + , '3.31.1' , system.file("htmlwidgets/lib/FlatGeoBuf", package = "leafem") , script = c( 'fgb.js' diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index d69399d..f082b16 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -12,7 +12,7 @@ function mouseHandler(mapId, layerId, group, eventName, extraInfo) { } let eventInfo = $.extend( { - id: layerId, + id: (e.layer.feature.properties[layerId]?.toString() ?? layerId.toString()), ".nonce": Math.random() // force reactivity }, group !== null ? {group: group} : null, @@ -33,11 +33,12 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, options, className, scale, - scaleFields) { + scaleFields, + highlightOptions) { - var map = this; - var gl = false; - var pane; + const map = this; + let gl = false; + let pane; if (options === null || options.pane === undefined) { pane = 'overlayPane'; @@ -45,7 +46,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, pane = options.pane; } - var data_fl = document.getElementById(layerId + '-1-attachment'); + let data_fl = document.getElementById(group + '-1-attachment'); if (data_fl === null) { data_fl = url; @@ -53,8 +54,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, data_fl = data_fl.href; } - var popUp; - var colnames = []; + let popUp; + let colnames = []; function handleHeaderMeta(headerMeta) { headerMeta.columns.forEach(function(col) { @@ -66,7 +67,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, // use fgb JavaScript API to iterate stream into results (features as geojson) // NOTE: would be more efficient with a special purpose Leaflet deserializer let it = flatgeobuf.deserialize(response.body, undefined, handleHeaderMeta); - var cntr = 0; + let cntr = 0; + // handle result function handleResult(result) { if (!result.done) { @@ -86,9 +88,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, pop = null; } - if (scaleFields === null & - result.value.properties !== undefined) { - var vls = Object.values(style); + if (scaleFields === null & result.value.properties !== undefined) { + let vls = Object.values(style); scaleFields = []; vls.forEach(function(name) { //if (name in colnames) { @@ -100,8 +101,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, }); } - lyr = L.geoJSON(result.value, Object.assign( - { + lyr = L.geoJSON(result.value, Object.assign({ pointToLayer: function (feature, latlng) { return L.circleMarker(latlng, options); }, @@ -120,33 +120,57 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, return layer.feature.properties[label].toString(); }, {sticky: true}); } else if (typeof(label) === Object || (typeof(label) === 'object' && label.length > 1)) { - var lb = label[cntr]; + let lb = label[cntr]; lyr.bindTooltip(function (layer) { return(lb); }, {sticky: true}); + } else if (typeof(label) === "function") { + lyr.bindTooltip(label, {sticky: true}); } else { lyr.bindTooltip(function (layer) { return(label); }, {sticky: true}); } } + + if (highlightOptions && typeof highlightOptions === 'object' && Object.keys(highlightOptions).length > 0) { + lyr.on({ + // highlight on hover + 'mouseover': function(e) { + const layer = e.target; + layer.setStyle(highlightOptions); + if (highlightOptions.bringToFront) { + layer.bringToFront(); + } + }, + // remove highlight when hover stops + 'mouseout': function(e) { + const layer = e.target; + layer.setStyle(style); + if (highlightOptions.sendToBack) { + layer.bringToBack(); + } + } + }) + } + lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); map.layerManager.addLayer(lyr, null, null, group); + it.next().then(handleResult); } } + cntr += 1; } it.next().then(handleResult); } fetch(data_fl) //, {mode: 'no-cors'}) - .then(handleResponse); + .then(handleResponse); - //map.fitBounds(lyr.getBounds()); - //map.layerManager.addLayer(layer, null, null, group); }; function makePopup(popup, className) { @@ -171,7 +195,7 @@ function makePopup(popup, className) { } else if (typeof(popup) === "object") { pop = function(feature, layer) { if (feature.properties.mvFeatureId !== undefined) { - var idx = feature.properties.mvFeatureId; + let idx = feature.properties.mvFeatureId; layer.bindPopup(popup[idx - 1], { maxWidth: 2000 }); } if (feature.properties.mvFeatureId === undefined) { @@ -193,18 +217,14 @@ function makePopup(popup, className) { function json2table(json, cls) { - var cols = Object.keys(json); - var vals = Object.values(json); - - var tab = ""; - + let cols = Object.keys(json); + let vals = Object.values(json); + let tab = ""; for (let i = 0; i < cols.length; i++) { tab += "" + cols[i] + " " + "" + vals[i] + " "; } - return "" + tab + "
"; - } @@ -219,31 +239,24 @@ function json2table(json, cls) { * @return {Object} The new object */ function pick(obj, props) { - 'use strict'; - // Make sure object and properties are provided if (!obj || !props) return; - // Create new object - var picked = {}; - + let picked = {}; // Loop through props and push to new object props.forEach(function(prop) { picked[prop] = obj[prop]; }); - - // Return new object return picked; - } function updateStyle(style_obj, feature, scale, scaleValues) { - var cols = Object.keys(style_obj); - var vals = Object.values(style_obj); + let cols = Object.keys(style_obj); + let vals = Object.values(style_obj); - var out = {}; + let out = {}; for (let i = 0; i < cols.length; i++) { if (vals[i] === null) { @@ -279,21 +292,22 @@ function rescale(value, to_min, to_max, from_min, from_max) { LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, - group, - url, - popup, - label, - style, - options, - className, - scale, - scaleFields, - minZoom, - maxZoom) { - - var map = this; - var gl = false; - var pane; + group, + url, + popup, + label, + style, + options, + className, + scale, + scaleFields, + minZoom, + maxZoom, + highlightOptions) { + + const map = this; + let gl = false; + let pane; if (options === null || options.pane === undefined) { pane = 'overlayPane'; @@ -301,7 +315,7 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, pane = options.pane; } - var data_fl = document.getElementById(layerId + '-1-attachment'); + let data_fl = document.getElementById(group + '-1-attachment'); if (data_fl === null) { data_fl = url; @@ -309,8 +323,8 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, data_fl = data_fl.href; } - var popUp; - var colnames = []; + let popUp; + let colnames = []; function handleHeaderMeta(headerMeta) { headerMeta.columns.forEach(function(col) { @@ -329,94 +343,119 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, }; } + // Initialize previousResults/nextResults if not already initialized var previousResults = previousResults || {}; - previousResults[layerId] = L.layerGroup(); - map.layerManager.addLayer(previousResults[layerId], null, layerId, group); + previousResults[group] = L.layerGroup(); + map.layerManager.addLayer(previousResults[group], null, layerId, group); + // Async Update Function async function updateResults() { - var nextResults = nextResults || {}; - nextResults[layerId] = L.layerGroup(); - map.layerManager.addLayer(nextResults[layerId], null, layerId, group); - // remove the old results - map.layerManager.removeLayer(previousResults[layerId], layerId); - // previousResults[layerId].remove(); - previousResults[layerId] = nextResults[layerId]; - - // Use flatgeobuf JavaScript API to iterate features as geojson. - // Because we specify a bounding box, flatgeobuf will only fetch the resubset of data, - // rather than the entire file. - const iter = flatgeobuf.deserialize(data_fl, fgBoundingBox(), handleHeaderMeta); - - if (map.getZoom() >= minZoom & map.getZoom() <= maxZoom & map.hasLayer(previousResults[layerId])) { - for await (const feature of iter) { - if (popup) { - pop = makePopup(popup, className); - } else { - pop = null; - } - if (scaleFields === null & - feature.properties !== undefined) { - var vls = Object.values(style); - scaleFields = []; - vls.forEach(function(name) { - //if (name in colnames) { - if (colnames.includes(name)) { - scaleFields.push(true); - } else { - scaleFields.push(false); - } - }); + // remove the old results + map.layerManager.removeLayer(previousResults[group], layerId); + previousResults[group].remove() + + // add next results + var nextResults = nextResults || {}; + nextResults[group] = L.layerGroup(); + map.layerManager.addLayer(nextResults[group], null, layerId, group); + + // Replace previous with next + previousResults[group] = nextResults[group]; + + // Use flatgeobuf JavaScript API to iterate features as geojson. + // Because we specify a bounding box, flatgeobuf will only fetch the relevant subset of data, + // rather than the entire file. + if (map.getZoom() >= minZoom & map.getZoom() <= maxZoom & map.hasLayer(previousResults[group])) { + + let iter = flatgeobuf.deserialize(data_fl, fgBoundingBox(), handleHeaderMeta); + + for await (let feature of iter) { + + if (popup) { + pop = makePopup(popup, className); + } else { + pop = null; + } + + if (scaleFields === null & feature.properties !== undefined) { + let vls = Object.values(style); + scaleFields = []; + vls.forEach(function(name) { + //if (name in colnames) { + if (colnames.includes(name)) { + scaleFields.push(true); + } else { + scaleFields.push(false); } + }); + } - lyr = L.geoJSON(feature, { - pointToLayer: function (feature, latlng) { - return L.circleMarker(latlng, options); - }, - style: function(feature) { - return updateStyle(style, feature, scale, scaleFields); - }, - onEachFeature: pop, - pane: pane - }); + lyr = L.geoJSON(feature, { + pointToLayer: function (feature, latlng) { + return L.circleMarker(latlng, options); + }, + style: function(feature) { + return updateStyle(style, feature, scale, scaleFields); + }, + onEachFeature: pop, + pane: pane + }); + + if (label) { + if (Object.keys(feature.properties).includes(label)) { + lyr.bindTooltip(function (layer) { + return layer.feature.properties[label].toString(); + }, {sticky: true}); + } else if (typeof(label) === "function") { + lyr.bindTooltip(label, {sticky: true}); + } else { + lyr.bindTooltip(function (layer) { + return(label); + }, {sticky: true}); + } + } - if (label) { - if (Object.keys(feature.properties).includes(label)) { - lyr.bindTooltip(function (layer) { - return layer.feature.properties[label].toString(); - }, {sticky: true}); - } else if (typeof(label) === Object || (typeof(label) === 'object' && label.length > 1)) { - var lb = label[cntr]; - lyr.bindTooltip(function (layer) { - return(lb); - }, {sticky: true}); - } else { - lyr.bindTooltip(function (layer) { - return(label); - }, {sticky: true}); - } + if (highlightOptions && typeof highlightOptions === 'object' && Object.keys(highlightOptions).length > 0) { + lyr.on({ + // highlight on hover + 'mouseover': function(e) { + const layer = e.target; + layer.setStyle(highlightOptions); + if (highlightOptions.bringToFront) { + layer.bringToFront(); + } + }, + // remove highlight when hover stops + 'mouseout': function(e) { + const layer = e.target; + layer.setStyle(style); + if (highlightOptions.sendToBack) { + layer.bringToBack(); + } } + }) + } - lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); - lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); - lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); - lyr.addTo(nextResults[layerId]); + lyr.on("click", mouseHandler(map.id, layerId, group, "shape_click")); + lyr.on("mouseover", mouseHandler(map.id, layerId, group, "shape_mouseover")); + lyr.on("mouseout", mouseHandler(map.id, layerId, group, "shape_mouseout")); + lyr.addTo(nextResults[group]); } } } - // if the user is panning around alot, only update once per second max - // updateResults = _.throttle(updateResults, 1000); // show results based on the initial map updateResults(); - // ...and update the results whenever the map moves + + // update the results whenever the map moves or the layer is added again map.on("moveend", function(s) { - //rectangle.setBounds(getBoundForRect()); - updateResults(); + updateResults(); }); map.on('layeradd', function(event) { - if(event.layer == previousResults[layerId]) { - updateResults(); - } -}); + if (event.layer == previousResults[group]) { + updateResults(); + } + }); + }; diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js b/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js index 56b58ce..a273417 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min.js @@ -1,17 +1,16 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).flatgeobuf={})}(this,(function(t){"use strict";class e{constructor(t,e,r,n,s,i,o,a,h,c){this.name=t,this.type=e,this.title=r,this.description=n,this.width=s,this.precision=i,this.scale=o,this.nullable=a,this.unique=h,this.primary_key=c}}var r;!function(t){t[t.Byte=0]="Byte",t[t.UByte=1]="UByte",t[t.Bool=2]="Bool",t[t.Short=3]="Short",t[t.UShort=4]="UShort",t[t.Int=5]="Int",t[t.UInt=6]="UInt",t[t.Long=7]="Long",t[t.ULong=8]="ULong",t[t.Float=9]="Float",t[t.Double=10]="Double",t[t.String=11]="String",t[t.Json=12]="Json",t[t.DateTime=13]="DateTime",t[t.Binary=14]="Binary"}(r||(r={}));class n{constructor(t,e,r,n,s,i){this.org=t,this.code=e,this.name=r,this.description=n,this.wkt=s,this.code_string=i}}const s=new Int32Array(2),i=new Float32Array(s.buffer),o=new Float64Array(s.buffer),a=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0];class h{constructor(t,e){this.low=0|t,this.high=0|e}static create(t,e){return 0==t&&0==e?h.ZERO:new h(t,e)}toFloat64(){return(this.low>>>0)+4294967296*this.high}equals(t){return this.low==t.low&&this.high==t.high}}var c,u;h.ZERO=new h(0,0),function(t){t[t.UTF8_BYTES=1]="UTF8_BYTES",t[t.UTF16_STRING=2]="UTF16_STRING"}(c||(c={}));class l{constructor(t){this.bytes_=t,this.position_=0}static allocate(t){return new l(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return new h(this.readInt32(t),this.readInt32(t+4))}readUint64(t){return new h(this.readUint32(t),this.readUint32(t+4))}readFloat32(t){return s[0]=this.readInt32(t),i[0]}readFloat64(t){return s[a?0:1]=this.readInt32(t),s[a?1:0]=this.readInt32(t+4),o[0]}writeInt8(t,e){this.bytes_[t]=e}writeUint8(t,e){this.bytes_[t]=e}writeInt16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)}writeUint64(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)}writeFloat32(t,e){i[0]=e,this.writeInt32(t,s[0])}writeFloat64(t,e){o[0]=e,this.writeInt32(t,s[a?0:1]),this.writeInt32(t+4,s[a?1:0])}getBufferIdentifier(){if(this.bytes_.length>10),56320+(1023&e)))}return n}__union_with_string(t,e){return"string"==typeof t?this.__string(e):this.__union(t,e)}__indirect(t){return t+this.readInt32(t)}__vector(t){return t+this.readInt32(t)+4}__vector_len(t){return this.readInt32(t+this.readInt32(t))}__has_identifier(t){if(4!=t.length)throw new Error("FlatBuffers: file identifier must be length 4");for(let e=0;e<4;e++)if(t.charCodeAt(e)!=this.readInt8(this.position()+4+e))return!1;return!0}createLong(t,e){return h.create(t,e)}createScalarList(t,e){const r=[];for(let n=0;nthis.minalign&&(this.minalign=t);const r=1+~(this.bb.capacity()-this.space+e)&t-1;for(;this.space=0&&0==this.vtable[e];e--);const r=e+1;for(;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);const n=2*(r+2);this.addInt16(n);let s=0;const i=this.space;t:for(e=0;e=0;e--)this.writeInt8(t.charCodeAt(e))}this.prep(this.minalign,4+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const r=this.bb.capacity()-t,n=r-this.bb.readInt32(r);if(!(0!=this.bb.readInt16(n+e)))throw new Error("FlatBuffers: field "+e+" must be set")}startVector(t,e,r){this.notNested(),this.vector_num_elems=e,this.prep(4,t*e),this.prep(r,t*e)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(t){if(!t)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(t))return this.string_maps.get(t);const e=this.createString(t);return this.string_maps.set(t,e),e}createString(t){if(!t)return 0;let e;if(t instanceof Uint8Array)e=t;else{e=[];let r=0;for(;r=56320)n=s;else{n=(s<<10)+t.charCodeAt(r++)+-56613888}n<128?e.push(n):(n<2048?e.push(n>>6&31|192):(n<65536?e.push(n>>12&15|224):e.push(n>>18&7|240,n>>12&63|128),e.push(n>>6&63|128)),e.push(63&n|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(let t=0,r=this.space,n=this.bb.bytes();t=0;r--)t.addFloat64(e[r]);return t.endVector()}static startEnvelopeVector(t,e){t.startVector(8,e,8)}static addGeometryType(t,e){t.addFieldInt8(2,e,u.Unknown)}static addHasZ(t,e){t.addFieldInt8(3,+e,0)}static addHasM(t,e){t.addFieldInt8(4,+e,0)}static addHasT(t,e){t.addFieldInt8(5,+e,0)}static addHasTm(t,e){t.addFieldInt8(6,+e,0)}static addColumns(t,e){t.addFieldOffset(7,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static addFeaturesCount(t,e){t.addFieldInt64(8,e,t.createLong(0,0))}static addIndexNodeSize(t,e){t.addFieldInt16(9,e,16)}static addCrs(t,e){t.addFieldOffset(10,e,0)}static addTitle(t,e){t.addFieldOffset(11,e,0)}static addDescription(t,e){t.addFieldOffset(12,e,0)}static addMetadata(t,e){t.addFieldOffset(13,e,0)}static endHeader(t){return t.endObject()}static finishHeaderBuffer(t,e){t.finish(e)}static finishSizePrefixedHeaderBuffer(t,e){t.finish(e,void 0,!0)}}class p{constructor(t,e,r,n,s,i,o,a){this.geometryType=t,this.columns=e,this.featuresCount=r,this.indexNodeSize=n,this.crs=s,this.title=i,this.description=o,this.metadata=a}static fromByteBuffer(t){const r=_.getRootAsHeader(t),s=r.featuresCount().toFloat64(),i=r.indexNodeSize(),o=[];for(let t=0;t=0;r--)t.addInt32(e[r]);return t.endVector()}static startEndsVector(t,e){t.startVector(4,e,4)}static addXy(t,e){t.addFieldOffset(1,e,0)}static createXyVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startXyVector(t,e){t.startVector(8,e,8)}static addZ(t,e){t.addFieldOffset(2,e,0)}static createZVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startZVector(t,e){t.startVector(8,e,8)}static addM(t,e){t.addFieldOffset(3,e,0)}static createMVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startMVector(t,e){t.startVector(8,e,8)}static addT(t,e){t.addFieldOffset(4,e,0)}static createTVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startTVector(t,e){t.startVector(8,e,8)}static addTm(t,e){t.addFieldOffset(5,e,0)}static createTmVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startTmVector(t,e){t.startVector(8,e,8)}static addType(t,e){t.addFieldInt8(6,e,u.Unknown)}static addParts(t,e){t.addFieldOffset(7,e,0)}static createPartsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startPartsVector(t,e){t.startVector(4,e,4)}static endGeometry(t){return t.endObject()}static createGeometry(t,e,r,n,s,i,o,a,h){return y.startGeometry(t),y.addEnds(t,e),y.addXy(t,r),y.addZ(t,n),y.addM(t,s),y.addT(t,i),y.addTm(t,o),y.addType(t,a),y.addParts(t,h),y.endGeometry(t)}}function g(t,e){const{xy:r,z:n,ends:s,parts:i,type:o}=e;if(i){const e=i.map((e=>g(t,e))),r=y.createPartsVector(t,e);return y.startGeometry(t),y.addParts(t,r),y.addType(t,o),y.endGeometry(t)}const a=y.createXyVector(t,r);let h,c;return n&&(h=y.createZVector(t,n)),s&&(c=y.createEndsVector(t,s)),y.startGeometry(t),c&&y.addEnds(t,c),y.addXy(t,a),h&&y.addZ(t,h),y.addType(t,o),y.endGeometry(t)}function w(t,e,r){if(0!==t.length)if(Array.isArray(t[0]))for(const n of t)w(n,e,r);else 2===t.length?e.push(...t):(e.push(t[0],t[1]),r.push(t[2]))}function v(t,e){const r=[];for(let n=0;n>1]),r.push(s)}return r}function m(t){if(!t)return u.Unknown;return u[t]}function I(t){const e=t.coordinates,r=[],n=[];let s,i;const o=m(t.type);let a=0;switch(t.type){case"Point":case"MultiPoint":case"LineString":w(e,r,n);break;case"MultiLineString":case"Polygon":{const t=e;w(t,r,n),t.length>1&&(s=t.map((t=>a+=t.length)));break}case"MultiPolygon":i=e.map((t=>({type:"Polygon",coordinates:t}))).map(I);break;case"GeometryCollection":t.geometries&&(i=t.geometries.map(I))}return{xy:r,z:n.length>0?n:void 0,ends:s,type:o,parts:i}}function F(t,e,r){if(!r||0===r.length)return[v(t,e)];let n=0;const s=Array.from(r).map((e=>t.slice(n,n=e<<1)));let i;return e&&(n=0,i=Array.from(r).map((t=>e.slice(n,n=t)))),s.map(((t,e)=>v(t,i?i[e]:void 0)))}function x(t,e){let r=e;if(r===u.Unknown&&(r=t.type()),r===u.GeometryCollection){const e=[];for(let r=0;rt.coordinates))}}const n=function(t,e){const r=t.xyArray(),n=t.zArray();switch(e){case u.Point:{const t=Array.from(r);return n&&t.push(n[0]),t}case u.MultiPoint:case u.LineString:return v(r,n);case u.MultiLineString:case u.Polygon:return F(r,n,t.endsArray())}}(t,r);return{type:u[r],coordinates:n}}class U{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFeature(t,e){return(e||new U).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFeature(t,e){return t.setPosition(t.position()+4),(e||new U).__init(t.readInt32(t.position())+t.position(),t)}geometry(t){const e=this.bb.__offset(this.bb_pos,4);return e?(t||new y).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}properties(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}propertiesLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}propertiesArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}columns(t,e){const r=this.bb.__offset(this.bb_pos,8);return r?(e||new f).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFeature(t){t.startObject(3)}static addGeometry(t,e){t.addFieldOffset(0,e,0)}static addProperties(t,e){t.addFieldOffset(1,e,0)}static createPropertiesVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startPropertiesVector(t,e){t.startVector(1,e,1)}static addColumns(t,e){t.addFieldOffset(2,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static endFeature(t){return t.endObject()}static finishFeatureBuffer(t,e){t.finish(e)}static finishSizePrefixedFeatureBuffer(t,e){t.finish(e,void 0,!0)}static createFeature(t,e,r,n){return U.startFeature(t),U.addGeometry(t,e),U.addProperties(t,r),U.addColumns(t,n),U.endFeature(t)}}const P=new TextEncoder,O=new TextDecoder;function S(t,e,n){const s=n.columns,i=new b;let o=0,a=1024,h=new Uint8Array(a),c=new DataView(h.buffer);const u=function(t){if(o+t0&&(l=U.createPropertiesVector(i,h.slice(0,o)));const f=g(i,t);U.startFeature(i),U.addGeometry(i,f),l&&U.addProperties(i,l);const d=U.endFeature(i);return i.finishSizePrefixed(d),i.asUint8Array()}function C(t,e){const n=e.columns,s={type:"Feature",geometry:x(t.geometry(),e.geometryType)};return n&&n.length>0&&(s.properties=function(t,e){const n={};if(!e||0===e.length)return n;const s=t.propertiesArray();if(!s)return n;const i=new DataView(s.buffer,s.byteOffset),o=t.propertiesLength();let a=0;for(;a0?{done:!1,value:e}:{done:!0,value:void 0}:{done:!1,value:V(e,r.value)}}))},E.prototype.slice=function(t){if((t|=0)<0)throw new Error("invalid length");var e=this,r=this._array.length-this._index;if(this._index+t<=this._array.length)return Promise.resolve(this._array.subarray(this._index,this._index+=t));var n=new Uint8Array(t);return n.set(this._array.subarray(this._index)),function s(){return e._source.read().then((function(i){return i.done?(e._array=A,e._index=0,r>0?n.subarray(0,r):null):r+i.value.length>=t?(e._array=i.value,e._index=t-r,n.set(i.value.subarray(0,t-r),r),n):(n.set(i.value,r),r+=i.value.length,s())}))}()},E.prototype.cancel=function(){return this._source.cancel()}; -/*! ***************************************************************************** - Copyright (c) Microsoft Corporation. +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).flatgeobuf={})}(this,(function(t){"use strict";var e;!function(t){t[t.Unknown=0]="Unknown",t[t.Point=1]="Point",t[t.LineString=2]="LineString",t[t.Polygon=3]="Polygon",t[t.MultiPoint=4]="MultiPoint",t[t.MultiLineString=5]="MultiLineString",t[t.MultiPolygon=6]="MultiPolygon",t[t.GeometryCollection=7]="GeometryCollection",t[t.CircularString=8]="CircularString",t[t.CompoundCurve=9]="CompoundCurve",t[t.CurvePolygon=10]="CurvePolygon",t[t.MultiCurve=11]="MultiCurve",t[t.MultiSurface=12]="MultiSurface",t[t.Curve=13]="Curve",t[t.Surface=14]="Surface",t[t.PolyhedralSurface=15]="PolyhedralSurface",t[t.TIN=16]="TIN",t[t.Triangle=17]="Triangle"}(e||(e={}));const n=new Int32Array(2),r=new Float32Array(n.buffer),s=new Float64Array(n.buffer),i=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0];var o,a;!function(t){t[t.UTF8_BYTES=1]="UTF8_BYTES",t[t.UTF16_STRING=2]="UTF16_STRING"}(o||(o={}));class c{constructor(t){this.bytes_=t,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new c(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return BigInt.asIntN(64,BigInt(this.readUint32(t))+(BigInt(this.readUint32(t+4))<>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,Number(BigInt.asIntN(32,e))),this.writeInt32(t+4,Number(BigInt.asIntN(32,e>>BigInt(32))))}writeUint64(t,e){this.writeUint32(t,Number(BigInt.asUintN(32,e))),this.writeUint32(t+4,Number(BigInt.asUintN(32,e>>BigInt(32))))}writeFloat32(t,e){r[0]=e,this.writeInt32(t,n[0])}writeFloat64(t,e){s[0]=e,this.writeInt32(t,n[i?0:1]),this.writeInt32(t+4,n[i?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=t);const n=1+~(this.bb.capacity()-this.space+e)&t-1;for(;this.space=0&&0==this.vtable[e];e--);const n=e+1;for(;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);const r=2*(n+2);this.addInt16(r);let s=0;const i=this.space;t:for(e=0;e=0;e--)this.writeInt8(t.charCodeAt(e))}this.prep(this.minalign,4+r),this.addOffset(t),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const n=this.bb.capacity()-t,r=n-this.bb.readInt32(n);if(!(e=0;n--)t.addInt32(e[n]);return t.endVector()}static startEndsVector(t,e){t.startVector(4,e,4)}static addXy(t,e){t.addFieldOffset(1,e,0)}static createXyVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startXyVector(t,e){t.startVector(8,e,8)}static addZ(t,e){t.addFieldOffset(2,e,0)}static createZVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startZVector(t,e){t.startVector(8,e,8)}static addM(t,e){t.addFieldOffset(3,e,0)}static createMVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startMVector(t,e){t.startVector(8,e,8)}static addT(t,e){t.addFieldOffset(4,e,0)}static createTVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startTVector(t,e){t.startVector(8,e,8)}static addTm(t,e){t.addFieldOffset(5,e,0)}static createTmVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startTmVector(t,e){t.startVector(8,e,8)}static addType(t,n){t.addFieldInt8(6,n,e.Unknown)}static addParts(t,e){t.addFieldOffset(7,e,0)}static createPartsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startPartsVector(t,e){t.startVector(4,e,4)}static endGeometry(t){return t.endObject()}static createGeometry(t,e,n,r,s,i,o,a,c){return h.startGeometry(t),h.addEnds(t,e),h.addXy(t,n),h.addZ(t,r),h.addM(t,s),h.addT(t,i),h.addTm(t,o),h.addType(t,a),h.addParts(t,c),h.endGeometry(t)}}function l(t,e){const{xy:n,z:r,ends:s,parts:i,type:o}=e;if(i){const e=i.map((e=>l(t,e))),n=h.createPartsVector(t,e);return h.startGeometry(t),h.addParts(t,n),h.addType(t,o),h.endGeometry(t)}const a=h.createXyVector(t,n);let c,u;return r&&(c=h.createZVector(t,r)),s&&(u=h.createEndsVector(t,s)),h.startGeometry(t),u&&h.addEnds(t,u),h.addXy(t,a),c&&h.addZ(t,c),h.addType(t,o),h.endGeometry(t)}function b(t,e,n){if(0!==t.length)if(Array.isArray(t[0]))for(const r of t)b(r,e,n);else 2===t.length?e.push(...t):(e.push(t[0],t[1]),n.push(t[2]))}function d(t,e){const n=[];for(let r=0;r>1]),n.push(s)}return n}function f(t){if(!t)return e.Unknown;return e[t]}function p(t){const e=t.coordinates,n=[],r=[];let s,i;const o=f(t.type);let a=0;switch(t.type){case"Point":case"MultiPoint":case"LineString":b(e,n,r);break;case"MultiLineString":case"Polygon":{const t=e;b(t,n,r),t.length>1&&(s=t.map((t=>a+=t.length)));break}case"MultiPolygon":i=e.map((t=>({type:"Polygon",coordinates:t}))).map(p);break}return{xy:n,z:r.length>0?r:void 0,ends:s,type:o,parts:i}}function _(t){const e=f(t.type),n=[];for(let e=0;et.slice(r,r=e<<1)));let i;return e&&(r=0,i=Array.from(n).map((t=>e.slice(r,r=t)))),s.map(((t,e)=>d(t,i?i[e]:void 0)))}function g(t,n){let r=n;if(r===e.Unknown&&(r=t.type()),r===e.GeometryCollection){const n=[];for(let e=0;et.coordinates))}}const s=function(t,n){const r=t.xyArray(),s=t.zArray();switch(n){case e.Point:{const t=Array.from(r);return s&&t.push(s[0]),t}case e.MultiPoint:case e.LineString:return d(r,s);case e.MultiLineString:case e.Polygon:return y(r,s,t.endsArray())}}(t,r);return{type:e[r],coordinates:s}}!function(t){t[t.Byte=0]="Byte",t[t.UByte=1]="UByte",t[t.Bool=2]="Bool",t[t.Short=3]="Short",t[t.UShort=4]="UShort",t[t.Int=5]="Int",t[t.UInt=6]="UInt",t[t.Long=7]="Long",t[t.ULong=8]="ULong",t[t.Float=9]="Float",t[t.Double=10]="Double",t[t.String=11]="String",t[t.Json=12]="Json",t[t.DateTime=13]="DateTime",t[t.Binary=14]="Binary"}(a||(a={}));class w{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsColumn(t,e){return(e||new w).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsColumn(t,e){return t.setPosition(t.position()+4),(e||new w).__init(t.readInt32(t.position())+t.position(),t)}name(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}type(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):a.Byte}title(t){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}description(t){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}width(){const t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt32(this.bb_pos+t):-1}precision(){const t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt32(this.bb_pos+t):-1}scale(){const t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):-1}nullable(){const t=this.bb.__offset(this.bb_pos,18);return!t||!!this.bb.readInt8(this.bb_pos+t)}unique(){const t=this.bb.__offset(this.bb_pos,20);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}primaryKey(){const t=this.bb.__offset(this.bb_pos,22);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}metadata(t){const e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__string(this.bb_pos+e,t):null}static startColumn(t){t.startObject(11)}static addName(t,e){t.addFieldOffset(0,e,0)}static addType(t,e){t.addFieldInt8(1,e,a.Byte)}static addTitle(t,e){t.addFieldOffset(2,e,0)}static addDescription(t,e){t.addFieldOffset(3,e,0)}static addWidth(t,e){t.addFieldInt32(4,e,-1)}static addPrecision(t,e){t.addFieldInt32(5,e,-1)}static addScale(t,e){t.addFieldInt32(6,e,-1)}static addNullable(t,e){t.addFieldInt8(7,+e,1)}static addUnique(t,e){t.addFieldInt8(8,+e,0)}static addPrimaryKey(t,e){t.addFieldInt8(9,+e,0)}static addMetadata(t,e){t.addFieldOffset(10,e,0)}static endColumn(t){const e=t.endObject();return t.requiredField(e,4),e}static createColumn(t,e,n,r,s,i,o,a,c,u,h,l){return w.startColumn(t),w.addName(t,e),w.addType(t,n),w.addTitle(t,r),w.addDescription(t,s),w.addWidth(t,i),w.addPrecision(t,o),w.addScale(t,a),w.addNullable(t,c),w.addUnique(t,u),w.addPrimaryKey(t,h),w.addMetadata(t,l),w.endColumn(t)}}class m{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFeature(t,e){return(e||new m).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFeature(t,e){return t.setPosition(t.position()+4),(e||new m).__init(t.readInt32(t.position())+t.position(),t)}geometry(t){const e=this.bb.__offset(this.bb_pos,4);return e?(t||new h).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}properties(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}propertiesLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}propertiesArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}columns(t,e){const n=this.bb.__offset(this.bb_pos,8);return n?(e||new w).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFeature(t){t.startObject(3)}static addGeometry(t,e){t.addFieldOffset(0,e,0)}static addProperties(t,e){t.addFieldOffset(1,e,0)}static createPropertiesVector(t,e){t.startVector(1,e.length,1);for(let n=e.length-1;n>=0;n--)t.addInt8(e[n]);return t.endVector()}static startPropertiesVector(t,e){t.startVector(1,e,1)}static addColumns(t,e){t.addFieldOffset(2,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static endFeature(t){return t.endObject()}static finishFeatureBuffer(t,e){t.finish(e)}static finishSizePrefixedFeatureBuffer(t,e){t.finish(e,void 0,!0)}static createFeature(t,e,n,r){return m.startFeature(t),m.addGeometry(t,e),m.addProperties(t,n),m.addColumns(t,r),m.endFeature(t)}}const v=new TextEncoder,I=new TextDecoder;function F(t,e,n){const r=n.columns,s=new u;let i=0,o=1024,c=new Uint8Array(o),h=new DataView(c.buffer);const b=function(t){if(i+t0&&(d=m.createPropertiesVector(s,c.slice(0,i)));const f=l(s,t);m.startFeature(s),m.addGeometry(s,f),d&&m.addProperties(s,d);const p=m.endFeature(s);return s.finishSizePrefixed(p),s.asUint8Array()}function x(t,e){const n={};if(!e||0===e.length)return n;const r=t.propertiesArray();if(!r)return n;const s=new DataView(r.buffer,r.byteOffset),i=t.propertiesLength();let o=0;for(;o0?{done:!1,value:e}:{done:!0,value:void 0}:{done:!1,value:S(e,n.value)}}))},O.prototype.slice=function(t){if((t|=0)<0)throw new Error("invalid length");var e=this,n=this._array.length-this._index;if(this._index+t<=this._array.length)return Promise.resolve(this._array.subarray(this._index,this._index+=t));var r=new Uint8Array(t);return r.set(this._array.subarray(this._index)),function s(){return e._source.read().then((function(i){return i.done?(e._array=P,e._index=0,n>0?r.subarray(0,n):null):n+i.value.length>=t?(e._array=i.value,e._index=t-n,r.set(i.value.subarray(0,t-n),n),r):(r.set(i.value,n),n+=i.value.length,s())}))}()},O.prototype.cancel=function(){return this._source.cancel()};class C{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsCrs(t,e){return(e||new C).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsCrs(t,e){return t.setPosition(t.position()+4),(e||new C).__init(t.readInt32(t.position())+t.position(),t)}org(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}code(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt32(this.bb_pos+t):0}name(t){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}description(t){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}wkt(t){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}codeString(t){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}static startCrs(t){t.startObject(6)}static addOrg(t,e){t.addFieldOffset(0,e,0)}static addCode(t,e){t.addFieldInt32(1,e,0)}static addName(t,e){t.addFieldOffset(2,e,0)}static addDescription(t,e){t.addFieldOffset(3,e,0)}static addWkt(t,e){t.addFieldOffset(4,e,0)}static addCodeString(t,e){t.addFieldOffset(5,e,0)}static endCrs(t){return t.endObject()}static createCrs(t,e,n,r,s,i,o){return C.startCrs(t),C.addOrg(t,e),C.addCode(t,n),C.addName(t,r),C.addDescription(t,s),C.addWkt(t,i),C.addCodeString(t,o),C.endCrs(t)}}class B{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsHeader(t,e){return(e||new B).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsHeader(t,e){return t.setPosition(t.position()+4),(e||new B).__init(t.readInt32(t.position())+t.position(),t)}name(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}envelope(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readFloat64(this.bb.__vector(this.bb_pos+e)+8*t):0}envelopeLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}envelopeArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Float64Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}geometryType(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readUint8(this.bb_pos+t):e.Unknown}hasZ(){const t=this.bb.__offset(this.bb_pos,10);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}hasM(){const t=this.bb.__offset(this.bb_pos,12);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}hasT(){const t=this.bb.__offset(this.bb_pos,14);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}hasTm(){const t=this.bb.__offset(this.bb_pos,16);return!!t&&!!this.bb.readInt8(this.bb_pos+t)}columns(t,e){const n=this.bb.__offset(this.bb_pos,18);return n?(e||new w).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}featuresCount(){const t=this.bb.__offset(this.bb_pos,20);return t?this.bb.readUint64(this.bb_pos+t):BigInt("0")}indexNodeSize(){const t=this.bb.__offset(this.bb_pos,22);return t?this.bb.readUint16(this.bb_pos+t):16}crs(t){const e=this.bb.__offset(this.bb_pos,24);return e?(t||new C).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}title(t){const e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__string(this.bb_pos+e,t):null}description(t){const e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__string(this.bb_pos+e,t):null}metadata(t){const e=this.bb.__offset(this.bb_pos,30);return e?this.bb.__string(this.bb_pos+e,t):null}static startHeader(t){t.startObject(14)}static addName(t,e){t.addFieldOffset(0,e,0)}static addEnvelope(t,e){t.addFieldOffset(1,e,0)}static createEnvelopeVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addFloat64(e[n]);return t.endVector()}static startEnvelopeVector(t,e){t.startVector(8,e,8)}static addGeometryType(t,n){t.addFieldInt8(2,n,e.Unknown)}static addHasZ(t,e){t.addFieldInt8(3,+e,0)}static addHasM(t,e){t.addFieldInt8(4,+e,0)}static addHasT(t,e){t.addFieldInt8(5,+e,0)}static addHasTm(t,e){t.addFieldInt8(6,+e,0)}static addColumns(t,e){t.addFieldOffset(7,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static addFeaturesCount(t,e){t.addFieldInt64(8,e,BigInt("0"))}static addIndexNodeSize(t,e){t.addFieldInt16(9,e,16)}static addCrs(t,e){t.addFieldOffset(10,e,0)}static addTitle(t,e){t.addFieldOffset(11,e,0)}static addDescription(t,e){t.addFieldOffset(12,e,0)}static addMetadata(t,e){t.addFieldOffset(13,e,0)}static endHeader(t){return t.endObject()}static finishHeaderBuffer(t,e){t.finish(e)}static finishSizePrefixedHeaderBuffer(t,e){t.finish(e,void 0,!0)}}function V(t){const e=B.getRootAsHeader(t),n=e.featuresCount(),r=e.indexNodeSize(),s=[];for(let t=0;t0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function k(t){return this instanceof k?(this.v=t,this):new k(t)}function L(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(t,e||[]),i=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(t){s[t]&&(r[t]=function(e){return new Promise((function(n,r){i.push([t,e,n,r])>1||a(t,e)}))})}function a(t,e){try{(n=s[t](e)).value instanceof k?Promise.resolve(n.value.v).then(c,u):h(i[0][2],n)}catch(t){h(i[0][3],t)}var n}function c(t){a("next",t)}function u(t){a("throw",t)}function h(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}var R=function(t){function e(e){var n=t.call(this,e)||this;return Object.defineProperty(n,"name",{value:"RepeaterOverflowError",enumerable:!1}),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(n,n.constructor.prototype):n.__proto__=n.constructor.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(n,n.constructor),n}return function(t,e){function n(){this.constructor=t}T(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(e,t),e}(Error);function q(t){null!=t&&"function"==typeof t.then&&t.then(G,G)}!function(){function t(t){if(t<0)throw new RangeError("Capacity may not be less than 0");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return this._q.length>=this._c},enumerable:!1,configurable:!0}),t.prototype.add=function(t){if(this.full)throw new Error("Buffer full");this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){for(;this._q.length>=this._c;)this._q.shift();this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){this._q.length=j;return Promise.resolve(e).then((function(e){return!n&&t.state>=$?D(t).then((function(t){return{value:t,done:!0}})):{value:e,done:n}}))}function W(t,e){var n,r;if(!(t.state>=M))if(t.state=M,t.onnext(),t.onstop(),null==t.err&&(t.err=e),0!==t.pushes.length||void 0!==t.buffer&&!t.buffer.empty)try{for(var s=N(t.pushes),i=s.next();!i.done;i=s.next()){i.value.resolve()}}catch(t){n={error:t}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}else X(t)}function X(t){var e,n;if(!(t.state>=j)){t.state=$||(t.state=z)throw new R("No more than "+z+" pending calls to push are allowed on a single repeater.");if(t.state>=M)return Promise.resolve(void 0);var n,r=void 0===t.pending?Promise.resolve(e):t.pending.then((function(){return e}));(r=r.catch((function(e){t.state=1)){t.state=1;var e=J.bind(null,t),n=function(t){var e=W.bind(null,t),n=new Promise((function(e){return t.onstop=e}));return e.then=n.then.bind(n),e.catch=n.catch.bind(n),e.finally=n.finally.bind(n),e}(t);t.execution=new Promise((function(r){return r(t.executor(e,n))})),t.execution.catch((function(){return W(t)}))}}var K,Q=new WeakMap,tt=function(){function t(t,e){Q.set(this,{executor:t,buffer:e,err:void 0,state:0,pushes:[],nexts:[],pending:void 0,execution:void 0,onnext:G,onstop:G})}return t.prototype.next=function(t){q(t);var e=Q.get(this);if(void 0===e)throw new Error("WeakMap error");if(e.nexts.length>=z)throw new R("No more than "+z+" pending calls to next are allowed on a single repeater.");if(e.state<=0&&Y(e),e.onnext(t),void 0!==e.buffer&&!e.buffer.empty){var n=H(e,e.buffer.remove());if(e.pushes.length){var r=e.pushes.shift();e.buffer.add(r.value),e.onnext=r.resolve}return n}if(e.pushes.length){var s=e.pushes.shift();return e.onnext=s.resolve,H(e,s.value)}return e.state>=M?(X(e),H(e,D(e))):new Promise((function(n){return e.nexts.push({resolve:n,value:t})}))},t.prototype.return=function(t){q(t);var e=Q.get(this);if(void 0===e)throw new Error("WeakMap error");return X(e),e.execution=Promise.resolve(e.execution).then((function(){return t})),H(e,D(e))},t.prototype.throw=function(t){var e=Q.get(this);if(void 0===e)throw new Error("WeakMap error");return e.state<=0||e.state>=M||void 0!==e.buffer&&!e.buffer.empty?(X(e),null==e.err&&(e.err=t),H(e,D(e))):this.next(Promise.reject(t))},t.prototype[Symbol.asyncIterator]=function(){return this},t.race=nt,t.merge=rt,t.zip=st,t.latest=it,t}();function et(t,e){var n,r,s=[],i=function(t){null!=t&&"function"==typeof t[Symbol.asyncIterator]?s.push(t[Symbol.asyncIterator]()):null!=t&&"function"==typeof t[Symbol.iterator]?s.push(t[Symbol.iterator]()):s.push(function(){return L(this,arguments,(function(){return A(this,(function(n){switch(n.label){case 0:return e.yieldValues?[4,k(t)]:[3,3];case 1:return[4,n.sent()];case 2:n.sent(),n.label=3;case 3:return e.returnValues?[4,k(t)]:[3,5];case 4:return[2,n.sent()];case 5:return[2]}}))}))}())};try{for(var o=N(t),a=o.next();!a.done;a=o.next()){i(a.value)}}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return s}function nt(t){var e=this,n=et(t,{returnValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o,a,c;return A(this,(function(u){switch(u.label){case 0:if(!n.length)return r(),[2];s=!1,r.then((function(){e(),s=!0})),u.label=1;case 1:u.trys.push([1,,5,7]),o=void 0,a=0,c=function(){var s,c,u,h,l,b;return A(this,(function(d){switch(d.label){case 0:s=a;try{for(l=void 0,c=N(n),u=c.next();!u.done;u=c.next())h=u.value,Promise.resolve(h.next()).then((function(t){t.done?(r(),void 0===i&&(i=t)):a===s&&(a++,e(t))}),(function(t){return r(t)}))}catch(t){l={error:t}}finally{try{u&&!u.done&&(b=c.return)&&b.call(c)}finally{if(l)throw l.error}}return[4,new Promise((function(t){return e=t}))];case 1:return void 0===(o=d.sent())?[3,3]:[4,t(o.value)];case 2:d.sent(),d.label=3;case 3:return[2]}}))},u.label=2;case 2:return s?[3,4]:[5,c()];case 3:return u.sent(),[3,2];case 4:return[2,i&&i.value];case 5:return r(),[4,Promise.race(n.map((function(t){return t.return&&t.return()})))];case 6:return u.sent(),[7];case 7:return[2]}}))}))}))}function rt(t){var e=this,n=et(t,{yieldValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o=this;return A(this,(function(a){switch(a.label){case 0:if(!n.length)return r(),[2];e=[],s=!1,r.then((function(){var t,n;s=!0;try{for(var r=N(e),i=r.next();!i.done;i=r.next()){(0,i.value)()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}})),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all(n.map((function(n,a){return E(o,void 0,void 0,(function(){var o;return A(this,(function(c){switch(c.label){case 0:c.trys.push([0,,6,9]),c.label=1;case 1:return s?[3,5]:(Promise.resolve(n.next()).then((function(t){return e[a](t)}),(function(t){return r(t)})),[4,new Promise((function(t){e[a]=t}))]);case 2:return void 0===(o=c.sent())?[3,4]:o.done?(i=o,[2]):[4,t(o.value)];case 3:c.sent(),c.label=4;case 4:return[3,1];case 5:return[3,9];case 6:return n.return?[4,n.return()]:[3,8];case 7:c.sent(),c.label=8;case 8:return[7];case 9:return[2]}}))}))})))];case 2:return a.sent(),[2,i&&i.value];case 3:return r(),[7];case 4:return[2]}}))}))}))}function st(t){var e=this,n=et(t,{returnValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o;return A(this,(function(a){switch(a.label){case 0:if(!n.length)return r(),[2,[]];s=!1,r.then((function(){e(),s=!0})),a.label=1;case 1:a.trys.push([1,,6,8]),a.label=2;case 2:return s?[3,5]:(Promise.all(n.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return r(t)})),[4,new Promise((function(t){return e=t}))]);case 3:return void 0===(i=a.sent())?[2]:(o=i.map((function(t){return t.value})),i.some((function(t){return t.done}))?[2,o]:[4,t(o)]);case 4:return a.sent(),[3,2];case 5:return[3,8];case 6:return r(),[4,Promise.all(n.map((function(t){return t.return&&t.return()})))];case 7:return a.sent(),[7];case 8:return[2]}}))}))}))}function it(t){var e=this,n=et(t,{yieldValues:!0,returnValues:!0});return new tt((function(t,r){return E(e,void 0,void 0,(function(){var e,s,i,o,a,c=this;return A(this,(function(u){switch(u.label){case 0:if(!n.length)return r(),[2,[]];s=[],i=!1,r.then((function(){var t,n;e();try{for(var r=N(s),o=r.next();!o.done;o=r.next()){(0,o.value)()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}i=!0})),u.label=1;case 1:return u.trys.push([1,,5,7]),Promise.all(n.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return r(t)})),[4,new Promise((function(t){return e=t}))];case 2:return void 0===(o=u.sent())?[2]:(a=o.map((function(t){return t.value})),o.every((function(t){return t.done}))?[2,a]:[4,t(a.slice())]);case 3:return u.sent(),[4,Promise.all(n.map((function(e,n){return E(c,void 0,void 0,(function(){var c;return A(this,(function(u){switch(u.label){case 0:if(o[n].done)return[2,o[n].value];u.label=1;case 1:return i?[3,4]:(Promise.resolve(e.next()).then((function(t){return s[n](t)}),(function(t){return r(t)})),[4,new Promise((function(t){return s[n]=t}))]);case 2:return void 0===(c=u.sent())?[2,o[n].value]:c.done?[2,c.value]:(a[n]=c.value,[4,t(a.slice())]);case 3:return u.sent(),[3,1];case 4:return[2]}}))}))})))];case 4:return[2,u.sent()];case 5:return r(),[4,Promise.all(n.map((function(t){return t.return&&t.return()})))];case 6:return u.sent(),[7];case 7:return[2]}}))}))}))}class ot{constructor(){this._extraRequestThreshold=262144}extraRequestThreshold(){return this._extraRequestThreshold}setExtraRequestThreshold(t){if(t<0)throw new Error("extraRequestThreshold cannot be negative");this._extraRequestThreshold=t}}ot.global=new ot,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error"}(K||(K={}));class at{static debug(...t){this.log(K.Debug,...t)}static info(...t){this.log(K.Info,...t)}static warn(...t){this.log(K.Warn,...t)}static error(...t){this.log(K.Error,...t)}static log(t,...e){if(!(this.logLevel>t))switch(t){case K.Debug:console.debug(...e);break;case K.Info:console.info(...e);break;case K.Warn:console.warn(...e);break;case K.Error:console.error(...e)}}}at.logLevel=K.Warn;const ct=40;function ut(t,e){e=Math.min(Math.max(+e,2),65535);let n=t,r=n;do{n=Math.ceil(n/e),r+=n}while(1!==n);return r*ct}async function*ht(t,e,n,r){class s{constructor(t,e){this._level=e,this.nodes=t}level(){return this._level}startNodeIdx(){return this.nodes[0]}endNodeIdx(){return this.nodes[1]}extendEndNodeIdx(t){console.assert(t>this.nodes[1]),this.nodes[1]=t}toString(){return`[NodeRange level: ${this._level}, nodes: ${this.nodes[0]}-${this.nodes[1]}]`}}const{minX:i,minY:o,maxX:a,maxY:c}=n;at.info(`tree items: ${t}, nodeSize: ${e}`);const u=function(t,e){if(e<2)throw new Error("Node size must be at least 2");if(0===t)throw new Error("Number of items must be greater than 0");let n=t,r=n;const s=[n];do{n=Math.ceil(n/e),r+=n,s.push(n)}while(1!==n);const i=[];n=r;for(const t of s)i.push(n-t),n-=t;const o=[];for(let t=0;t{const t=u.length-1;return new s([0,1],t)})()];for(at.debug(`starting stream search with queue: ${l}, numItems: ${t}, nodeSize: ${e}, levelBounds: ${u}`);0!=l.length;){const n=l.shift();at.debug(`popped node: ${n}, queueLength: ${l.length}`);const b=n.startNodeIdx(),d=b>=h,f=(()=>{const[,t]=u[n.level()],r=Math.min(n.endNodeIdx()+e,t);return d&&ry.getFloat64(u+16,!0))continue;if(o>y.getFloat64(u+24,!0))continue;const f=y.getBigUint64(u+32,!0);if(d){const n=f,s=(()=>{if(e ${p}`),g.extendEndNodeIdx(Number(p));continue}const w=(()=>{const t=n.level()-1,e=[Number(p),Number(p)+1];return new s(e,t)})();void 0!==g&&g.level()==w.level()?at.info(`Same level, but too far away. Pushing new request for nodeIdx: ${p} rather than merging with distant ${g}`):at.info(`Pushing new level for ${w} onto queue with nearestNodeRange: ${g} since there's not already a range for this level.`),l.push(w)}}}const lt=new Uint8Array([102,103,98,3,102,103,98,0]),bt=4;class dt{constructor(t,e,n,r,s){this.headerClient=t,this.header=e,this.headerLength=n,this.indexLength=r,this.nocache=s}static async open(t,e){const n=new ft(t,e),r=(()=>{let t,e=0;for(t=0;t<3;t++){e+=16**t*ct}return e})(),s=2024+r;at.debug(`fetching header. minReqLength: ${s} (assumedHeaderLength: 2024, assumedIndexLength: ${r})`);{const t=new Uint8Array(await n.getRange(0,8,s,"header"));if(!t.subarray(0,3).every(((t,e)=>lt[e]===t)))throw at.error(`bytes: ${t} != ${lt}`),new Error("Not a FlatGeobuf file");at.debug("magic bytes look good")}let i;{const t=await n.getRange(8,4,s,"header");i=new DataView(t).getUint32(0,!0);if(i>10485760||i<8)throw new Error("Invalid header size");at.debug(`headerLength: ${i}`)}const o=await n.getRange(12,i,s,"header"),a=V(new c(new Uint8Array(o))),u=ut(a.featuresCount,a.indexNodeSize);return at.debug("completed: opening http reader"),new dt(n,a,i,u,e)}async*selectBbox(t){const e=this.lengthBeforeTree(),n=this.headerClient,r=async function(t,r){return n.getRange(e+t,r,0,"index")},s=[];let i=[];for await(const e of ht(this.header.featuresCount,this.header.indexNodeSize,t,r)){const[t,,]=e;let[,,n]=e;if(n||(at.info("final feature"),n=4),0==i.length){i.push([t,n]);continue}const r=i[i.length-1],o=t-(r[0]+r[1]);o>ot.global.extraRequestThreshold()&&(at.info(`Pushing new feature batch, since gap ${o} was too large`),s.push(i),i=[]),i.push([t,n])}this.headerClient.logUsage("header+index"),i.length>0&&s.push(i);const o=s.flatMap((t=>this.readFeatureBatch(t,this.nocache)));yield*tt.merge(o)}lengthBeforeTree(){return lt.length+bt+this.headerLength}lengthBeforeFeatures(){return this.lengthBeforeTree()+this.indexLength}buildFeatureClient(t){return new ft(this.headerClient.httpClient,t)}async*readFeatureBatch(t,e){const[n]=t[0],[r,s]=t[t.length-1],i=r+s-n,o=this.buildFeatureClient(e);let a=i;for(const[e]of t)yield await this.readFeature(o,e,a),a=0;o.logUsage("feature")}async readFeature(t,e,n){const r=e+this.lengthBeforeFeatures();let s;{const e=await t.getRange(r,4,n,"feature length");s=new DataView(e).getUint32(0,!0)}const i=await t.getRange(r+4,s,n,"feature data"),o=new Uint8Array(i),a=new Uint8Array(s+bt);a.set(o,bt);const u=new c(a);return u.setPosition(bt),m.getRootAsFeature(u)}}class ft{constructor(t,e){if(this.bytesEverUsed=0,this.bytesEverFetched=0,this.buffer=new ArrayBuffer(0),this.head=0,"string"==typeof t)this.httpClient=new pt(t,e);else{if(!(t instanceof pt))throw new Error("Unknown source ");this.httpClient=t}}async getRange(t,e,n,r){this.bytesEverUsed+=e;const s=t-this.head,i=s+e;if(s>=0&&i<=this.buffer.byteLength)return this.buffer.slice(s,i);const o=Math.max(e,n);return this.bytesEverFetched+=o,at.debug(`requesting for new Range: ${t}-${t+o-1}`),this.buffer=await this.httpClient.getRange(t,o,r),this.head=t,this.buffer.slice(0,e)}logUsage(t){const e=t.split(" ")[0],n=this.bytesEverUsed,r=this.bytesEverFetched,s=(100*n/r).toFixed(2);at.info(`${e} bytes used/requested: ${n} / ${r} = ${s}%`)}}class pt{constructor(t,e){this.requestsEverMade=0,this.bytesEverRequested=0,this.url=t,this.nocache=e}async getRange(t,e,n){this.requestsEverMade+=1,this.bytesEverRequested+=e;const r=`bytes=${t}-${t+e-1}`;at.info(`request: #${this.requestsEverMade}, purpose: ${n}), bytes: (this_request: ${e}, ever: ${this.bytesEverRequested}), Range: ${r}`);const s={Range:r};this.nocache&&(s["Cache-Control"]="no-cache, no-store");return(await fetch(this.url,{headers:s})).arrayBuffer()}}async function*_t(t,e,n){const r="function"==typeof(s=t).slice?s:new O("function"==typeof s.read?s:s.getReader());var s;const i=async t=>await r.slice(t);let o=new Uint8Array(await i(8));if(!o.subarray(0,3).every(((t,e)=>lt[e]===t)))throw new Error("Not a FlatGeobuf file");o=new Uint8Array(await i(4));let a=new c(o);const u=a.readUint32(0);o=new Uint8Array(await i(u)),a=new c(o);const h=V(a);n&&n(h);const{indexNodeSize:l,featuresCount:b}=h;if(l>0){const t=ut(b,l);await i(t)}let d;for(;d=await yt(i,h,e);)yield d}async function yt(t,e,n){let r=new Uint8Array(await t(4,"feature length"));if(0===r.byteLength)return;let s=new c(r);const i=s.readUint32(0);r=new Uint8Array(await t(i,"feature data"));const o=new Uint8Array(i+4);o.set(r,4),s=new c(o),s.setPosition(bt);return n(m.getRootAsFeature(s),e)}function gt(t,e=0){const n=new u;let r=null;t.columns&&(r=B.createColumnsVector(n,t.columns.map((t=>function(t,e){const n=t.createString(e.name);return w.startColumn(t),w.addName(t,n),w.addType(t,e.type),w.endColumn(t)}(n,t)))));const s=n.createString("L1");let i;e&&(C.startCrs(n),C.addCode(n,e),i=C.endCrs(n)),B.startHeader(n),i&&B.addCrs(n,i),B.addFeaturesCount(n,BigInt(t.featuresCount)),B.addGeometryType(n,t.geometryType),B.addIndexNodeSize(n,0),r&&B.addColumns(n,r),B.addName(n,s);const o=B.endHeader(n);return n.finishSizePrefixed(o),n.asUint8Array()}function wt(t){if("boolean"==typeof t)return a.Bool;if("number"==typeof t)return t%1==0?a.Int:a.Double;if("string"==typeof t)return a.String;if(null===t)return a.String;if("object"==typeof t)return a.Json;throw new Error(`Unknown type (value '${t}')`)}function mt(t,n=0){const r=function(t){const n=t.features[0],r=n.properties;let s=null;r&&(s=Object.keys(r).map((t=>function(t,e){return{name:e,type:wt(t[e]),title:null,description:null,width:-1,precision:-1,scale:-1,nullable:!0,unique:!1,primary_key:!1}}(r,t))));const i=function(t){let n;for(const s of t){if(n===e.Unknown)break;const t=(r=s).getGeometry?f(r.getGeometry().getType()):f(r.geometry.type);void 0===n?n=t:n!==t&&(n=e.Unknown)}var r;if(void 0===n)throw new Error("Could not infer geometry type for collection of features.");return n}(t.features),o={geometryType:i,columns:s,envelope:null,featuresCount:t.features.length,indexNodeSize:0,crs:null,title:null,description:null,metadata:null};return o}(t),s=gt(r,n),i=t.features.map((t=>F("GeometryCollection"===t.geometry.type?_(t.geometry):p(t.geometry),t.properties,r))),o=i.map((t=>t.length)).reduce(((t,e)=>t+e)),a=new Uint8Array(lt.length+s.length+o);a.set(s,lt.length);let c=lt.length+s.length;for(const t of i)a.set(t,c),c+=t.length;return a.set(lt),a}function vt(t,e){const n=function(t,e,n){if(!t.subarray(0,3).every(((t,e)=>lt[e]===t)))throw new Error("Not a FlatGeobuf file");const r=new c(t),s=r.readUint32(lt.length);r.setPosition(lt.length+bt);const i=V(r);n&&n(i);let o=lt.length+bt+s;const{indexNodeSize:a,featuresCount:u}=i;a>0&&(o+=ut(u,a));const h=[];for(;o0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(t){return this instanceof N?(this.v=t,this):new N(t)}function R(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(t,e||[]),i=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(t){s[t]&&(n[t]=function(e){return new Promise((function(r,n){i.push([t,e,r,n])>1||a(t,e)}))})}function a(t,e){try{(r=s[t](e)).value instanceof N?Promise.resolve(r.value.v).then(h,c):u(i[0][2],r)}catch(t){u(i[0][3],t)}var r}function h(t){a("next",t)}function c(t){a("throw",t)}function u(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}var q=function(t){function e(e){var r=t.call(this,e)||this;return Object.defineProperty(r,"name",{value:"RepeaterOverflowError",enumerable:!1}),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(r,r.constructor.prototype):r.__proto__=r.constructor.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,r.constructor),r}return function(t,e){function r(){this.constructor=t}T(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}(e,t),e}(Error);function M(t){null!=t&&"function"==typeof t.then&&t.then($,$)}!function(){function t(t){if(t<0)throw new RangeError("Capacity may not be less than 0");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return this._q.length>=this._c},enumerable:!1,configurable:!0}),t.prototype.add=function(t){if(this.full)throw new Error("Buffer full");this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){for(;this._q.length>=this._c;)this._q.shift();this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){this._q.length=3;return Promise.resolve(e).then((function(e){return!r&&t.state>=4?z(t).then((function(t){return{value:t,done:!0}})):{value:e,done:r}}))}function D(t,e){var r,n;if(!(t.state>=2))if(t.state=2,t.onnext(),t.onstop(),null==t.err&&(t.err=e),0!==t.pushes.length||void 0!==t.buffer&&!t.buffer.empty)try{for(var s=L(t.pushes),i=s.next();!i.done;i=s.next()){i.value.resolve()}}catch(t){r={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}else H(t)}function H(t){var e,r;if(!(t.state>=3)){t.state<2&&D(t),t.state=3,t.buffer=void 0;try{for(var n=L(t.nexts),s=n.next();!s.done;s=n.next()){var i=s.value,o=void 0===t.pending?z(t):t.pending.then((function(){return z(t)}));i.resolve(G(t,o))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}t.pushes=[],t.nexts=[]}}function W(t){t.state>=4||(t.state<3&&H(t),t.state=4)}function Z(t,e){if(M(e),t.pushes.length>=j)throw new q("No more than 1024 pending calls to push are allowed on a single repeater.");if(t.state>=2)return Promise.resolve(void 0);var r,n=void 0===t.pending?Promise.resolve(e):t.pending.then((function(){return e}));(n=n.catch((function(e){t.state<2&&(t.err=e),W(t)})),t.nexts.length)?(t.nexts.shift().resolve(G(t,n)),r=t.nexts.length?Promise.resolve(t.nexts[0].value):new Promise((function(e){return t.onnext=e}))):void 0===t.buffer||t.buffer.full?r=new Promise((function(e){return t.pushes.push({resolve:e,value:n})})):(t.buffer.add(n),r=Promise.resolve(void 0));var s=!0,i={},o=r.catch((function(t){if(s)throw t}));return i.then=function(t,e){return s=!1,Promise.prototype.then.call(r,t,e)},i.catch=function(t){return s=!1,Promise.prototype.catch.call(r,t)},i.finally=r.finally.bind(r),t.pending=n.then((function(){return o})).catch((function(e){t.err=e,W(t)})),i}function X(t){if(!(t.state>=1)){t.state=1;var e=Z.bind(null,t),r=function(t){var e=D.bind(null,t),r=new Promise((function(e){return t.onstop=e}));return e.then=r.then.bind(r),e.catch=r.catch.bind(r),e.finally=r.finally.bind(r),e}(t);t.execution=new Promise((function(n){return n(t.executor(e,r))})),t.execution.catch((function(){return D(t)}))}}var Y,K=new WeakMap,J=function(){function t(t,e){K.set(this,{executor:t,buffer:e,err:void 0,state:0,pushes:[],nexts:[],pending:void 0,execution:void 0,onnext:$,onstop:$})}return t.prototype.next=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");if(e.nexts.length>=j)throw new q("No more than 1024 pending calls to next are allowed on a single repeater.");if(e.state<=0&&X(e),e.onnext(t),void 0!==e.buffer&&!e.buffer.empty){var r=G(e,e.buffer.remove());if(e.pushes.length){var n=e.pushes.shift();e.buffer.add(n.value),e.onnext=n.resolve}return r}if(e.pushes.length){var s=e.pushes.shift();return e.onnext=s.resolve,G(e,s.value)}return e.state>=2?(H(e),G(e,z(e))):new Promise((function(r){return e.nexts.push({resolve:r,value:t})}))},t.prototype.return=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return H(e),e.execution=Promise.resolve(e.execution).then((function(){return t})),G(e,z(e))},t.prototype.throw=function(t){var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return e.state<=0||e.state>=2||void 0!==e.buffer&&!e.buffer.empty?(H(e),null==e.err&&(e.err=t),G(e,z(e))):this.next(Promise.reject(t))},t.prototype[Symbol.asyncIterator]=function(){return this},t.race=tt,t.merge=et,t.zip=rt,t.latest=nt,t}();function Q(t,e){var r,n,s=[],i=function(t){null!=t&&"function"==typeof t[Symbol.asyncIterator]?s.push(t[Symbol.asyncIterator]()):null!=t&&"function"==typeof t[Symbol.iterator]?s.push(t[Symbol.iterator]()):s.push(function(){return R(this,arguments,(function(){return k(this,(function(r){switch(r.label){case 0:return e.yieldValues?[4,N(t)]:[3,3];case 1:return[4,r.sent()];case 2:r.sent(),r.label=3;case 3:return e.returnValues?[4,N(t)]:[3,5];case 4:return[2,r.sent()];case 5:return[2]}}))}))}())};try{for(var o=L(t),a=o.next();!a.done;a=o.next()){i(a.value)}}catch(t){r={error:t}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return s}function tt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2];s=!1,n.then((function(){e(),s=!0})),c.label=1;case 1:c.trys.push([1,,5,7]),o=void 0,a=0,h=function(){var s,h,c,u,l,b;return k(this,(function(f){switch(f.label){case 0:s=a;try{for(l=void 0,h=L(r),c=h.next();!c.done;c=h.next())u=c.value,Promise.resolve(u.next()).then((function(t){t.done?(n(),void 0===i&&(i=t)):a===s&&(a++,e(t))}),(function(t){return n(t)}))}catch(t){l={error:t}}finally{try{c&&!c.done&&(b=h.return)&&b.call(h)}finally{if(l)throw l.error}}return[4,new Promise((function(t){return e=t}))];case 1:return void 0===(o=f.sent())?[3,3]:[4,t(o.value)];case 2:f.sent(),f.label=3;case 3:return[2]}}))},c.label=2;case 2:return s?[3,4]:[5,h()];case 3:return c.sent(),[3,2];case 4:return[2,i&&i.value];case 5:return n(),[4,Promise.race(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}function et(t){var e=this,r=Q(t,{yieldValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o=this;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2];e=[],s=!1,n.then((function(){var t,r;s=!0;try{for(var n=L(e),i=n.next();!i.done;i=n.next()){(0,i.value)()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all(r.map((function(r,a){return B(o,void 0,void 0,(function(){var o;return k(this,(function(h){switch(h.label){case 0:h.trys.push([0,,6,9]),h.label=1;case 1:return s?[3,5]:(Promise.resolve(r.next()).then((function(t){return e[a](t)}),(function(t){return n(t)})),[4,new Promise((function(t){e[a]=t}))]);case 2:return void 0===(o=h.sent())?[3,4]:o.done?(i=o,[2]):[4,t(o.value)];case 3:h.sent(),h.label=4;case 4:return[3,1];case 5:return[3,9];case 6:return r.return?[4,r.return()]:[3,8];case 7:h.sent(),h.label=8;case 8:return[7];case 9:return[2]}}))}))})))];case 2:return a.sent(),[2,i&&i.value];case 3:return n(),[7];case 4:return[2]}}))}))}))}function rt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2,[]];s=!1,n.then((function(){e(),s=!0})),a.label=1;case 1:a.trys.push([1,,6,8]),a.label=2;case 2:return s?[3,5]:(Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))]);case 3:return void 0===(i=a.sent())?[2]:(o=i.map((function(t){return t.value})),i.some((function(t){return t.done}))?[2,o]:[4,t(o)]);case 4:return a.sent(),[3,2];case 5:return[3,8];case 6:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 7:return a.sent(),[7];case 8:return[2]}}))}))}))}function nt(t){var e=this,r=Q(t,{yieldValues:!0,returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h=this;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2,[]];s=[],i=!1,n.then((function(){var t,r;e();try{for(var n=L(s),o=n.next();!o.done;o=n.next()){(0,o.value)()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}i=!0})),c.label=1;case 1:return c.trys.push([1,,5,7]),Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))];case 2:return void 0===(o=c.sent())?[2]:(a=o.map((function(t){return t.value})),o.every((function(t){return t.done}))?[2,a]:[4,t(a.slice())]);case 3:return c.sent(),[4,Promise.all(r.map((function(e,r){return B(h,void 0,void 0,(function(){var h;return k(this,(function(c){switch(c.label){case 0:if(o[r].done)return[2,o[r].value];c.label=1;case 1:return i?[3,4]:(Promise.resolve(e.next()).then((function(t){return s[r](t)}),(function(t){return n(t)})),[4,new Promise((function(t){return s[r]=t}))]);case 2:return void 0===(h=c.sent())?[2,o[r].value]:h.done?[2,h.value]:(a[r]=h.value,[4,t(a.slice())]);case 3:return c.sent(),[3,1];case 4:return[2]}}))}))})))];case 4:return[2,c.sent()];case 5:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}class st{constructor(){this._extraRequestThreshold=262144}extraRequestThreshold(){return this._extraRequestThreshold}setExtraRequestThreshold(t){if(t<0)throw new Error("extraRequestThreshold cannot be negative");this._extraRequestThreshold=t}}st.global=new st,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error"}(Y||(Y={}));class it{static debug(){for(var t=arguments.length,e=new Array(t),r=0;rt)){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;nthis.nodes[1]),this.nodes[1]=t}toString(){return`[NodeRange level: ${this._level}, nodes: ${this.nodes[0]}-${this.nodes[1]}]`}}const{minX:i,minY:o,maxX:a,maxY:h}=r;it.info(`tree items: ${t}, nodeSize: ${e}`);const c=function(t,e){if(e<2)throw new Error("Node size must be at least 2");if(0===t)throw new Error("Number of items must be greater than 0");let r=t,n=r;const s=[r];do{r=Math.ceil(r/e),n+=r,s.push(r)}while(1!==r);const i=[];r=n;for(const t of s)i.push(r-t),r-=t;i.reverse(),s.reverse();const o=[];for(let t=0;t{const t=c.length-1;return new s([0,1],t)})()];for(it.debug(`starting stream search with queue: ${l}, numItems: ${t}, nodeSize: ${e}, levelBounds: ${c}`);0!=l.length;){const r=l.shift();it.debug(`popped node: ${r}, queueLength: ${l.length}`);const b=r.startNode(),f=b>=u,[,d]=c[r.level()],_=Math.min(r.endNode()+e,d),p=_-b,y=await n(40*b,40*p),g=new Float64Array(y),w=new Uint32Array(y);for(let e=b;e<_;e++){const n=5*(e-b);if(ag[n+2])continue;if(o>g[n+3])continue;const c=w[8+(n<<1)],d=ht(w[9+(n<<1)],c);if(f){const r=(()=>{if(e ${d}`),p.extendEndNodeToNewOffset(d);continue}const y=(()=>{const t=r.level()-1;return new s([d,d+1],t)})();void 0!==p&&p.level()==y.level()?it.info(`Same level, but too far away. Pushing new request at offset: ${d} rather than merging with distant ${p}`):it.info(`Pushing new level for ${y} onto queue with nearestNodeRange: ${p} since there's not already a range for this level.`),l.push(y)}}}function ht(t,e){if(0!=(4293918720&t))throw Error("integer is too large to be safely represented");return e+t*2**32}const ct=new Uint8Array([102,103,98,3,102,103,98,0]);class ut{constructor(t,e,r,n){this.headerClient=t,this.header=e,this.headerLength=r,this.indexLength=n}static async open(t){const e=new lt(t),r=(()=>{let t,e=0;for(t=0;t<3;t++){e+=16**t*40}return e})(),n=2024+r;it.debug(`fetching header. minReqLength: ${n} (assumedHeaderLength: 2024, assumedIndexLength: ${r})`);{const t=new Uint8Array(await e.getRange(0,8,n,"header"));if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw it.error(`bytes: ${t} != ${ct}`),new Error("Not a FlatGeobuf file");it.debug("magic bytes look good")}let s;{const t=await e.getRange(8,4,n,"header");s=new DataView(t).getUint32(0,!0);if(s>10485760||s<8)throw new Error("Invalid header size");it.debug(`headerLength: ${s}`)}const i=await e.getRange(12,s,n,"header"),o=new l(new Uint8Array(i)),a=p.fromByteBuffer(o),h=ot(a.featuresCount,a.indexNodeSize);return it.debug("completed: opening http reader"),new ut(e,a,s,h)}async*selectBbox(t){const e=this.lengthBeforeTree(),r=this.headerClient,n=async function(t,n){return r.getRange(e+t,n,0,"index")},s=[];let i=[];for await(const e of at(this.header.featuresCount,this.header.indexNodeSize,t,n)){const[t,,]=e;let[,,r]=e;if(!r){it.info("final feature");r=st.global.extraRequestThreshold()}if(0==i.length){i.push([t,r]);continue}const n=i[i.length-1],o=t-(n[0]+n[1]);o>st.global.extraRequestThreshold()&&(it.info(`Pushing new feature batch, since gap ${o} was too large`),s.push(i),i=[]),i.push([t,r])}this.headerClient.logUsage("header+index"),i.length>0&&s.push(i);const o=s.flatMap((t=>this.readFeatureBatch(t)));yield*J.merge(o)}lengthBeforeTree(){return ct.length+4+this.headerLength}lengthBeforeFeatures(){return this.lengthBeforeTree()+this.indexLength}buildFeatureClient(){return new lt(this.headerClient.httpClient)}async*readFeatureBatch(t){const[e]=t[0],[r,n]=t[t.length-1],s=r+n-e,i=this.buildFeatureClient();for(const[e]of t)yield await this.readFeature(i,e,s);i.logUsage("feature")}async readFeature(t,e,r){const n=e+this.lengthBeforeFeatures();let s;{const e=await t.getRange(n,4,r,"feature length");s=new DataView(e).getUint32(0,!0)}const i=await t.getRange(n+4,s,r,"feature data"),o=new Uint8Array(i),a=new Uint8Array(s+4);a.set(o,4);const h=new l(a);return h.setPosition(4),U.getRootAsFeature(h)}}class lt{constructor(t){this.bytesEverUsed=0,this.bytesEverFetched=0,this.buffer=new ArrayBuffer(0),this.head=0,this.httpClient="string"==typeof t?new bt(t):t}async getRange(t,e,r,n){this.bytesEverUsed+=e;const s=t-this.head,i=s+e;if(s>=0&&i<=this.buffer.byteLength)return this.buffer.slice(s,i);const o=Math.max(e,r);return this.bytesEverFetched+=o,it.debug(`requesting for new Range: ${t}-${t+e-1}`),this.buffer=await this.httpClient.getRange(t,o,n),this.head=t,this.buffer.slice(0,e)}logUsage(t){const e=t.split(" ")[0],r=this.bytesEverUsed,n=this.bytesEverFetched,s=(100*r/n).toFixed(2);it.info(`${e} bytes used/requested: ${r} / ${n} = ${s}%`)}}class bt{constructor(t){this.requestsEverMade=0,this.bytesEverRequested=0,this.url=t}async getRange(t,e,r){this.requestsEverMade+=1,this.bytesEverRequested+=e;const n=`bytes=${t}-${t+e-1}`;it.info(`request: #${this.requestsEverMade}, purpose: ${r}), bytes: (this_request: ${e}, ever: ${this.bytesEverRequested}), Range: ${n}`);return(await fetch(this.url,{headers:{Range:n}})).arrayBuffer()}}async function*ft(t,e,r){const n="function"==typeof(s=t).slice?s:new E("function"==typeof s.read?s:s.getReader());var s;const i=async t=>await n.slice(t);let o=new Uint8Array(await i(8));if(!o.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");o=new Uint8Array(await i(4));let a=new l(o);const h=a.readUint32(0);o=new Uint8Array(await i(h)),a=new l(o);const c=p.fromByteBuffer(a);r&&r(c);const{indexNodeSize:u,featuresCount:b}=c;if(u>0){const t=ot(b,u);await i(t)}let f;for(;f=await dt(i,c,e);)yield f}async function dt(t,e,r){let n=new Uint8Array(await t(4,"feature length"));if(0===n.byteLength)return;let s=new l(n);const i=s.readUint32(0);n=new Uint8Array(await t(i,"feature data"));const o=new Uint8Array(i+4);o.set(n,4),s=new l(o),s.setPosition(4);return r(U.getRootAsFeature(s),e)}function _t(t){const e=new b;let r=null;t.columns&&(r=_.createColumnsVector(e,t.columns.map((t=>function(t,e){const r=t.createString(e.name);return f.startColumn(t),f.addName(t,r),f.addType(t,e.type),f.endColumn(t)}(e,t)))));const n=e.createString("L1");_.startHeader(e),_.addFeaturesCount(e,new h(t.featuresCount,0)),_.addGeometryType(e,t.geometryType),_.addIndexNodeSize(e,0),r&&_.addColumns(e,r),_.addName(e,n);const s=_.endHeader(e);return e.finishSizePrefixed(s),e.asUint8Array()}function pt(t){const n=function(t){const n=t.features[0].properties;let s=null;n&&(s=Object.keys(n).map((t=>new e(t,function(t){if("boolean"==typeof t)return r.Bool;if("number"==typeof t)return t%1==0?r.Int:r.Double;if("string"==typeof t)return r.String;if(null===t)return r.String;throw new Error(`Unknown type (value '${t}')`)}(n[t]),null,null,-1,-1,-1,!0,!1,!1))));const i=function(t){let e;for(const n of t){if(e===u.Unknown)break;const t=(r=n).getGeometry?m(r.getGeometry().getType()):m(r.geometry.type);void 0===e?e=t:e!==t&&(e=u.Unknown)}var r;if(void 0===e)throw new Error("Could not infer geometry type for collection of features.");return e}(t.features);return new p(i,s,t.features.length,0,null,null,null,null)}(t),s=_t(n),i=t.features.map((t=>S(I(t.geometry),t.properties,n))),o=i.map((t=>t.length)).reduce(((t,e)=>t+e)),a=new Uint8Array(ct.length+s.length+o);a.set(s,ct.length);let h=ct.length+s.length;for(const t of i)a.set(t,h),h+=t.length;return a.set(ct),a}function yt(t,e){const r=function(t,e,r){if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");const n=new l(t),s=n.readUint32(ct.length);n.setPosition(ct.length+4);const i=p.fromByteBuffer(n);r&&r(i);let o=ct.length+4+s;const{indexNodeSize:a,featuresCount:h}=i;a>0&&(o+=ot(h,a));const c=[];for(;o>>0)+4294967296*this.high}equals(t){return this.low==t.low&&this.high==t.high}}var c,u;h.ZERO=new h(0,0),function(t){t[t.UTF8_BYTES=1]="UTF8_BYTES",t[t.UTF16_STRING=2]="UTF16_STRING"}(c||(c={}));class l{constructor(t){this.bytes_=t,this.position_=0}static allocate(t){return new l(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return new h(this.readInt32(t),this.readInt32(t+4))}readUint64(t){return new h(this.readUint32(t),this.readUint32(t+4))}readFloat32(t){return s[0]=this.readInt32(t),i[0]}readFloat64(t){return s[a?0:1]=this.readInt32(t),s[a?1:0]=this.readInt32(t+4),o[0]}writeInt8(t,e){this.bytes_[t]=e}writeUint8(t,e){this.bytes_[t]=e}writeInt16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)}writeUint64(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)}writeFloat32(t,e){i[0]=e,this.writeInt32(t,s[0])}writeFloat64(t,e){o[0]=e,this.writeInt32(t,s[a?0:1]),this.writeInt32(t+4,s[a?1:0])}getBufferIdentifier(){if(this.bytes_.length>10),56320+(1023&e)))}return n}__union_with_string(t,e){return"string"==typeof t?this.__string(e):this.__union(t,e)}__indirect(t){return t+this.readInt32(t)}__vector(t){return t+this.readInt32(t)+4}__vector_len(t){return this.readInt32(t+this.readInt32(t))}__has_identifier(t){if(4!=t.length)throw new Error("FlatBuffers: file identifier must be length 4");for(let e=0;e<4;e++)if(t.charCodeAt(e)!=this.readInt8(this.position()+4+e))return!1;return!0}createLong(t,e){return h.create(t,e)}createScalarList(t,e){const r=[];for(let n=0;nthis.minalign&&(this.minalign=t);const r=1+~(this.bb.capacity()-this.space+e)&t-1;for(;this.space=0&&0==this.vtable[e];e--);const r=e+1;for(;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);const n=2*(r+2);this.addInt16(n);let s=0;const i=this.space;t:for(e=0;e=0;e--)this.writeInt8(t.charCodeAt(e))}this.prep(this.minalign,4+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const r=this.bb.capacity()-t,n=r-this.bb.readInt32(r);if(!(0!=this.bb.readInt16(n+e)))throw new Error("FlatBuffers: field "+e+" must be set")}startVector(t,e,r){this.notNested(),this.vector_num_elems=e,this.prep(4,t*e),this.prep(r,t*e)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(t){if(!t)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(t))return this.string_maps.get(t);const e=this.createString(t);return this.string_maps.set(t,e),e}createString(t){if(!t)return 0;let e;if(t instanceof Uint8Array)e=t;else{e=[];let r=0;for(;r=56320)n=s;else{n=(s<<10)+t.charCodeAt(r++)+-56613888}n<128?e.push(n):(n<2048?e.push(n>>6&31|192):(n<65536?e.push(n>>12&15|224):e.push(n>>18&7|240,n>>12&63|128),e.push(n>>6&63|128)),e.push(63&n|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(let t=0,r=this.space,n=this.bb.bytes();t=0;r--)t.addFloat64(e[r]);return t.endVector()}static startEnvelopeVector(t,e){t.startVector(8,e,8)}static addGeometryType(t,e){t.addFieldInt8(2,e,u.Unknown)}static addHasZ(t,e){t.addFieldInt8(3,+e,0)}static addHasM(t,e){t.addFieldInt8(4,+e,0)}static addHasT(t,e){t.addFieldInt8(5,+e,0)}static addHasTm(t,e){t.addFieldInt8(6,+e,0)}static addColumns(t,e){t.addFieldOffset(7,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static addFeaturesCount(t,e){t.addFieldInt64(8,e,t.createLong(0,0))}static addIndexNodeSize(t,e){t.addFieldInt16(9,e,16)}static addCrs(t,e){t.addFieldOffset(10,e,0)}static addTitle(t,e){t.addFieldOffset(11,e,0)}static addDescription(t,e){t.addFieldOffset(12,e,0)}static addMetadata(t,e){t.addFieldOffset(13,e,0)}static endHeader(t){return t.endObject()}static finishHeaderBuffer(t,e){t.finish(e)}static finishSizePrefixedHeaderBuffer(t,e){t.finish(e,void 0,!0)}}class p{constructor(t,e,r,n,s,i,o,a){this.geometryType=t,this.columns=e,this.featuresCount=r,this.indexNodeSize=n,this.crs=s,this.title=i,this.description=o,this.metadata=a}static fromByteBuffer(t){const r=_.getRootAsHeader(t),s=r.featuresCount().toFloat64(),i=r.indexNodeSize(),o=[];for(let t=0;t=0;r--)t.addInt32(e[r]);return t.endVector()}static startEndsVector(t,e){t.startVector(4,e,4)}static addXy(t,e){t.addFieldOffset(1,e,0)}static createXyVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startXyVector(t,e){t.startVector(8,e,8)}static addZ(t,e){t.addFieldOffset(2,e,0)}static createZVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startZVector(t,e){t.startVector(8,e,8)}static addM(t,e){t.addFieldOffset(3,e,0)}static createMVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startMVector(t,e){t.startVector(8,e,8)}static addT(t,e){t.addFieldOffset(4,e,0)}static createTVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startTVector(t,e){t.startVector(8,e,8)}static addTm(t,e){t.addFieldOffset(5,e,0)}static createTmVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startTmVector(t,e){t.startVector(8,e,8)}static addType(t,e){t.addFieldInt8(6,e,u.Unknown)}static addParts(t,e){t.addFieldOffset(7,e,0)}static createPartsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startPartsVector(t,e){t.startVector(4,e,4)}static endGeometry(t){return t.endObject()}static createGeometry(t,e,r,n,s,i,o,a,h){return y.startGeometry(t),y.addEnds(t,e),y.addXy(t,r),y.addZ(t,n),y.addM(t,s),y.addT(t,i),y.addTm(t,o),y.addType(t,a),y.addParts(t,h),y.endGeometry(t)}}function g(t,e){const{xy:r,z:n,ends:s,parts:i,type:o}=e;if(i){const e=i.map((e=>g(t,e))),r=y.createPartsVector(t,e);return y.startGeometry(t),y.addParts(t,r),y.addType(t,o),y.endGeometry(t)}const a=y.createXyVector(t,r);let h,c;return n&&(h=y.createZVector(t,n)),s&&(c=y.createEndsVector(t,s)),y.startGeometry(t),c&&y.addEnds(t,c),y.addXy(t,a),h&&y.addZ(t,h),y.addType(t,o),y.endGeometry(t)}function w(t,e,r){if(0!==t.length)if(Array.isArray(t[0]))for(const n of t)w(n,e,r);else 2===t.length?e.push(...t):(e.push(t[0],t[1]),r.push(t[2]))}function v(t,e){const r=[];for(let n=0;n>1]),r.push(s)}return r}function m(t){if(!t)return u.Unknown;return u[t]}function I(t){const e=t.coordinates,r=[],n=[];let s,i;const o=m(t.type);let a=0;switch(t.type){case"Point":case"MultiPoint":case"LineString":w(e,r,n);break;case"MultiLineString":case"Polygon":{const t=e;w(t,r,n),t.length>1&&(s=t.map((t=>a+=t.length)));break}case"MultiPolygon":i=e.map((t=>({type:"Polygon",coordinates:t}))).map(I);break;case"GeometryCollection":t.geometries&&(i=t.geometries.map(I))}return{xy:r,z:n.length>0?n:void 0,ends:s,type:o,parts:i}}function F(t,e,r){if(!r||0===r.length)return[v(t,e)];let n=0;const s=Array.from(r).map((e=>t.slice(n,n=e<<1)));let i;return e&&(n=0,i=Array.from(r).map((t=>e.slice(n,n=t)))),s.map(((t,e)=>v(t,i?i[e]:void 0)))}function x(t,e){let r=e;if(r===u.Unknown&&(r=t.type()),r===u.GeometryCollection){const e=[];for(let r=0;rt.coordinates))}}const n=function(t,e){const r=t.xyArray(),n=t.zArray();switch(e){case u.Point:{const t=Array.from(r);return n&&t.push(n[0]),t}case u.MultiPoint:case u.LineString:return v(r,n);case u.MultiLineString:case u.Polygon:return F(r,n,t.endsArray())}}(t,r);return{type:u[r],coordinates:n}}class U{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFeature(t,e){return(e||new U).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFeature(t,e){return t.setPosition(t.position()+4),(e||new U).__init(t.readInt32(t.position())+t.position(),t)}geometry(t){const e=this.bb.__offset(this.bb_pos,4);return e?(t||new y).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}properties(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}propertiesLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}propertiesArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}columns(t,e){const r=this.bb.__offset(this.bb_pos,8);return r?(e||new f).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFeature(t){t.startObject(3)}static addGeometry(t,e){t.addFieldOffset(0,e,0)}static addProperties(t,e){t.addFieldOffset(1,e,0)}static createPropertiesVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startPropertiesVector(t,e){t.startVector(1,e,1)}static addColumns(t,e){t.addFieldOffset(2,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static endFeature(t){return t.endObject()}static finishFeatureBuffer(t,e){t.finish(e)}static finishSizePrefixedFeatureBuffer(t,e){t.finish(e,void 0,!0)}static createFeature(t,e,r,n){return U.startFeature(t),U.addGeometry(t,e),U.addProperties(t,r),U.addColumns(t,n),U.endFeature(t)}}const P=new TextEncoder,O=new TextDecoder;function S(t,e,n){const s=n.columns,i=new b;let o=0,a=1024,h=new Uint8Array(a),c=new DataView(h.buffer);const u=function(t){if(o+t0&&(l=U.createPropertiesVector(i,h.slice(0,o)));const f=g(i,t);U.startFeature(i),U.addGeometry(i,f),l&&U.addProperties(i,l);const d=U.endFeature(i);return i.finishSizePrefixed(d),i.asUint8Array()}function C(t,e){const n=e.columns,s={type:"Feature",geometry:x(t.geometry(),e.geometryType)};return n&&n.length>0&&(s.properties=function(t,e){const n={};if(!e||0===e.length)return n;const s=t.propertiesArray();if(!s)return n;const i=new DataView(s.buffer,s.byteOffset),o=t.propertiesLength();let a=0;for(;a0?{done:!1,value:e}:{done:!0,value:void 0}:{done:!1,value:V(e,r.value)}}))},E.prototype.slice=function(t){if((t|=0)<0)throw new Error("invalid length");var e=this,r=this._array.length-this._index;if(this._index+t<=this._array.length)return Promise.resolve(this._array.subarray(this._index,this._index+=t));var n=new Uint8Array(t);return n.set(this._array.subarray(this._index)),function s(){return e._source.read().then((function(i){return i.done?(e._array=A,e._index=0,r>0?n.subarray(0,r):null):r+i.value.length>=t?(e._array=i.value,e._index=t-r,n.set(i.value.subarray(0,t-r),r),n):(n.set(i.value,r),r+=i.value.length,s())}))}()},E.prototype.cancel=function(){return this._source.cancel()}; +/*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ +var T=function(t,e){return T=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},T(t,e)};function B(t,e,r,n){return new(r||(r=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function a(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,a)}h((n=n.apply(t,e||[])).next())}))}function k(t,e){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=o.trys,(s=s.length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(t){return this instanceof N?(this.v=t,this):new N(t)}function R(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(t,e||[]),i=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(t){s[t]&&(n[t]=function(e){return new Promise((function(r,n){i.push([t,e,r,n])>1||a(t,e)}))})}function a(t,e){try{(r=s[t](e)).value instanceof N?Promise.resolve(r.value.v).then(h,c):u(i[0][2],r)}catch(t){u(i[0][3],t)}var r}function h(t){a("next",t)}function c(t){a("throw",t)}function u(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}var q=function(t){function e(e){var r=t.call(this,e)||this;return Object.defineProperty(r,"name",{value:"RepeaterOverflowError",enumerable:!1}),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(r,r.constructor.prototype):r.__proto__=r.constructor.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,r.constructor),r}return function(t,e){function r(){this.constructor=t}T(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}(e,t),e}(Error);function M(t){null!=t&&"function"==typeof t.then&&t.then($,$)}!function(){function t(t){if(t<0)throw new RangeError("Capacity may not be less than 0");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return this._q.length>=this._c},enumerable:!1,configurable:!0}),t.prototype.add=function(t){if(this.full)throw new Error("Buffer full");this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){for(;this._q.length>=this._c;)this._q.shift();this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){this._q.length=3;return Promise.resolve(e).then((function(e){return!r&&t.state>=4?z(t).then((function(t){return{value:t,done:!0}})):{value:e,done:r}}))}function D(t,e){var r,n;if(!(t.state>=2))if(t.state=2,t.onnext(),t.onstop(),null==t.err&&(t.err=e),0!==t.pushes.length||void 0!==t.buffer&&!t.buffer.empty)try{for(var s=L(t.pushes),i=s.next();!i.done;i=s.next()){i.value.resolve()}}catch(t){r={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}else H(t)}function H(t){var e,r;if(!(t.state>=3)){t.state<2&&D(t),t.state=3,t.buffer=void 0;try{for(var n=L(t.nexts),s=n.next();!s.done;s=n.next()){var i=s.value,o=void 0===t.pending?z(t):t.pending.then((function(){return z(t)}));i.resolve(G(t,o))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}t.pushes=[],t.nexts=[]}}function W(t){t.state>=4||(t.state<3&&H(t),t.state=4)}function Z(t,e){if(M(e),t.pushes.length>=j)throw new q("No more than 1024 pending calls to push are allowed on a single repeater.");if(t.state>=2)return Promise.resolve(void 0);var r,n=void 0===t.pending?Promise.resolve(e):t.pending.then((function(){return e}));(n=n.catch((function(e){t.state<2&&(t.err=e),W(t)})),t.nexts.length)?(t.nexts.shift().resolve(G(t,n)),r=t.nexts.length?Promise.resolve(t.nexts[0].value):new Promise((function(e){return t.onnext=e}))):void 0===t.buffer||t.buffer.full?r=new Promise((function(e){return t.pushes.push({resolve:e,value:n})})):(t.buffer.add(n),r=Promise.resolve(void 0));var s=!0,i={},o=r.catch((function(t){if(s)throw t}));return i.then=function(t,e){return s=!1,Promise.prototype.then.call(r,t,e)},i.catch=function(t){return s=!1,Promise.prototype.catch.call(r,t)},i.finally=r.finally.bind(r),t.pending=n.then((function(){return o})).catch((function(e){t.err=e,W(t)})),i}function X(t){if(!(t.state>=1)){t.state=1;var e=Z.bind(null,t),r=function(t){var e=D.bind(null,t),r=new Promise((function(e){return t.onstop=e}));return e.then=r.then.bind(r),e.catch=r.catch.bind(r),e.finally=r.finally.bind(r),e}(t);t.execution=new Promise((function(n){return n(t.executor(e,r))})),t.execution.catch((function(){return D(t)}))}}var Y,K=new WeakMap,J=function(){function t(t,e){K.set(this,{executor:t,buffer:e,err:void 0,state:0,pushes:[],nexts:[],pending:void 0,execution:void 0,onnext:$,onstop:$})}return t.prototype.next=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");if(e.nexts.length>=j)throw new q("No more than 1024 pending calls to next are allowed on a single repeater.");if(e.state<=0&&X(e),e.onnext(t),void 0!==e.buffer&&!e.buffer.empty){var r=G(e,e.buffer.remove());if(e.pushes.length){var n=e.pushes.shift();e.buffer.add(n.value),e.onnext=n.resolve}return r}if(e.pushes.length){var s=e.pushes.shift();return e.onnext=s.resolve,G(e,s.value)}return e.state>=2?(H(e),G(e,z(e))):new Promise((function(r){return e.nexts.push({resolve:r,value:t})}))},t.prototype.return=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return H(e),e.execution=Promise.resolve(e.execution).then((function(){return t})),G(e,z(e))},t.prototype.throw=function(t){var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return e.state<=0||e.state>=2||void 0!==e.buffer&&!e.buffer.empty?(H(e),null==e.err&&(e.err=t),G(e,z(e))):this.next(Promise.reject(t))},t.prototype[Symbol.asyncIterator]=function(){return this},t.race=tt,t.merge=et,t.zip=rt,t.latest=nt,t}();function Q(t,e){var r,n,s=[],i=function(t){null!=t&&"function"==typeof t[Symbol.asyncIterator]?s.push(t[Symbol.asyncIterator]()):null!=t&&"function"==typeof t[Symbol.iterator]?s.push(t[Symbol.iterator]()):s.push(function(){return R(this,arguments,(function(){return k(this,(function(r){switch(r.label){case 0:return e.yieldValues?[4,N(t)]:[3,3];case 1:return[4,r.sent()];case 2:r.sent(),r.label=3;case 3:return e.returnValues?[4,N(t)]:[3,5];case 4:return[2,r.sent()];case 5:return[2]}}))}))}())};try{for(var o=L(t),a=o.next();!a.done;a=o.next()){i(a.value)}}catch(t){r={error:t}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return s}function tt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2];s=!1,n.then((function(){e(),s=!0})),c.label=1;case 1:c.trys.push([1,,5,7]),o=void 0,a=0,h=function(){var s,h,c,u,l,b;return k(this,(function(f){switch(f.label){case 0:s=a;try{for(l=void 0,h=L(r),c=h.next();!c.done;c=h.next())u=c.value,Promise.resolve(u.next()).then((function(t){t.done?(n(),void 0===i&&(i=t)):a===s&&(a++,e(t))}),(function(t){return n(t)}))}catch(t){l={error:t}}finally{try{c&&!c.done&&(b=h.return)&&b.call(h)}finally{if(l)throw l.error}}return[4,new Promise((function(t){return e=t}))];case 1:return void 0===(o=f.sent())?[3,3]:[4,t(o.value)];case 2:f.sent(),f.label=3;case 3:return[2]}}))},c.label=2;case 2:return s?[3,4]:[5,h()];case 3:return c.sent(),[3,2];case 4:return[2,i&&i.value];case 5:return n(),[4,Promise.race(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}function et(t){var e=this,r=Q(t,{yieldValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o=this;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2];e=[],s=!1,n.then((function(){var t,r;s=!0;try{for(var n=L(e),i=n.next();!i.done;i=n.next()){(0,i.value)()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all(r.map((function(r,a){return B(o,void 0,void 0,(function(){var o;return k(this,(function(h){switch(h.label){case 0:h.trys.push([0,,6,9]),h.label=1;case 1:return s?[3,5]:(Promise.resolve(r.next()).then((function(t){return e[a](t)}),(function(t){return n(t)})),[4,new Promise((function(t){e[a]=t}))]);case 2:return void 0===(o=h.sent())?[3,4]:o.done?(i=o,[2]):[4,t(o.value)];case 3:h.sent(),h.label=4;case 4:return[3,1];case 5:return[3,9];case 6:return r.return?[4,r.return()]:[3,8];case 7:h.sent(),h.label=8;case 8:return[7];case 9:return[2]}}))}))})))];case 2:return a.sent(),[2,i&&i.value];case 3:return n(),[7];case 4:return[2]}}))}))}))}function rt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2,[]];s=!1,n.then((function(){e(),s=!0})),a.label=1;case 1:a.trys.push([1,,6,8]),a.label=2;case 2:return s?[3,5]:(Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))]);case 3:return void 0===(i=a.sent())?[2]:(o=i.map((function(t){return t.value})),i.some((function(t){return t.done}))?[2,o]:[4,t(o)]);case 4:return a.sent(),[3,2];case 5:return[3,8];case 6:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 7:return a.sent(),[7];case 8:return[2]}}))}))}))}function nt(t){var e=this,r=Q(t,{yieldValues:!0,returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h=this;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2,[]];s=[],i=!1,n.then((function(){var t,r;e();try{for(var n=L(s),o=n.next();!o.done;o=n.next()){(0,o.value)()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}i=!0})),c.label=1;case 1:return c.trys.push([1,,5,7]),Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))];case 2:return void 0===(o=c.sent())?[2]:(a=o.map((function(t){return t.value})),o.every((function(t){return t.done}))?[2,a]:[4,t(a.slice())]);case 3:return c.sent(),[4,Promise.all(r.map((function(e,r){return B(h,void 0,void 0,(function(){var h;return k(this,(function(c){switch(c.label){case 0:if(o[r].done)return[2,o[r].value];c.label=1;case 1:return i?[3,4]:(Promise.resolve(e.next()).then((function(t){return s[r](t)}),(function(t){return n(t)})),[4,new Promise((function(t){return s[r]=t}))]);case 2:return void 0===(h=c.sent())?[2,o[r].value]:h.done?[2,h.value]:(a[r]=h.value,[4,t(a.slice())]);case 3:return c.sent(),[3,1];case 4:return[2]}}))}))})))];case 4:return[2,c.sent()];case 5:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}class st{constructor(){this._extraRequestThreshold=262144}extraRequestThreshold(){return this._extraRequestThreshold}setExtraRequestThreshold(t){if(t<0)throw new Error("extraRequestThreshold cannot be negative");this._extraRequestThreshold=t}}st.global=new st,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error"}(Y||(Y={}));class it{static debug(){for(var t=arguments.length,e=new Array(t),r=0;rt)){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;nthis.nodes[1]),this.nodes[1]=t}toString(){return`[NodeRange level: ${this._level}, nodes: ${this.nodes[0]}-${this.nodes[1]}]`}}const{minX:i,minY:o,maxX:a,maxY:h}=r;it.info(`tree items: ${t}, nodeSize: ${e}`);const c=function(t,e){if(e<2)throw new Error("Node size must be at least 2");if(0===t)throw new Error("Number of items must be greater than 0");let r=t,n=r;const s=[r];do{r=Math.ceil(r/e),n+=r,s.push(r)}while(1!==r);const i=[];r=n;for(const t of s)i.push(r-t),r-=t;i.reverse(),s.reverse();const o=[];for(let t=0;t{const t=c.length-1;return new s([0,1],t)})()];for(it.debug(`starting stream search with queue: ${l}, numItems: ${t}, nodeSize: ${e}, levelBounds: ${c}`);0!=l.length;){const r=l.shift();it.debug(`popped node: ${r}, queueLength: ${l.length}`);const b=r.startNode(),f=b>=u,[,d]=c[r.level()],_=Math.min(r.endNode()+e,d),p=_-b,y=await n(40*b,40*p),g=new Float64Array(y),w=new Uint32Array(y);for(let e=b;e<_;e++){const n=5*(e-b);if(ag[n+2])continue;if(o>g[n+3])continue;const c=w[8+(n<<1)],d=ht(w[9+(n<<1)],c);if(f){const r=(()=>{if(e ${d}`),p.extendEndNodeToNewOffset(d);continue}const y=(()=>{const t=r.level()-1;return new s([d,d+1],t)})();void 0!==p&&p.level()==y.level()?it.info(`Same level, but too far away. Pushing new request at offset: ${d} rather than merging with distant ${p}`):it.info(`Pushing new level for ${y} onto queue with nearestNodeRange: ${p} since there's not already a range for this level.`),l.push(y)}}}function ht(t,e){if(0!=(4293918720&t))throw Error("integer is too large to be safely represented");return e+t*2**32}const ct=new Uint8Array([102,103,98,3,102,103,98,0]);class ut{constructor(t,e,r,n){this.headerClient=t,this.header=e,this.headerLength=r,this.indexLength=n}static async open(t){const e=new lt(t),r=(()=>{let t,e=0;for(t=0;t<3;t++){e+=16**t*40}return e})(),n=2024+r;it.debug(`fetching header. minReqLength: ${n} (assumedHeaderLength: 2024, assumedIndexLength: ${r})`);{const t=new Uint8Array(await e.getRange(0,8,n,"header"));if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw it.error(`bytes: ${t} != ${ct}`),new Error("Not a FlatGeobuf file");it.debug("magic bytes look good")}let s;{const t=await e.getRange(8,4,n,"header");s=new DataView(t).getUint32(0,!0);if(s>10485760||s<8)throw new Error("Invalid header size");it.debug(`headerLength: ${s}`)}const i=await e.getRange(12,s,n,"header"),o=new l(new Uint8Array(i)),a=p.fromByteBuffer(o),h=ot(a.featuresCount,a.indexNodeSize);return it.debug("completed: opening http reader"),new ut(e,a,s,h)}async*selectBbox(t){const e=this.lengthBeforeTree(),r=this.headerClient,n=async function(t,n){return r.getRange(e+t,n,0,"index")},s=[];let i=[];for await(const e of at(this.header.featuresCount,this.header.indexNodeSize,t,n)){const[t,,]=e;let[,,r]=e;if(!r){it.info("final feature");r=st.global.extraRequestThreshold()}if(0==i.length){i.push([t,r]);continue}const n=i[i.length-1],o=t-(n[0]+n[1]);o>st.global.extraRequestThreshold()&&(it.info(`Pushing new feature batch, since gap ${o} was too large`),s.push(i),i=[]),i.push([t,r])}this.headerClient.logUsage("header+index"),i.length>0&&s.push(i);const o=s.flatMap((t=>this.readFeatureBatch(t)));yield*J.merge(o)}lengthBeforeTree(){return ct.length+4+this.headerLength}lengthBeforeFeatures(){return this.lengthBeforeTree()+this.indexLength}buildFeatureClient(){return new lt(this.headerClient.httpClient)}async*readFeatureBatch(t){const[e]=t[0],[r,n]=t[t.length-1],s=r+n-e,i=this.buildFeatureClient();for(const[e]of t)yield await this.readFeature(i,e,s);i.logUsage("feature")}async readFeature(t,e,r){const n=e+this.lengthBeforeFeatures();let s;{const e=await t.getRange(n,4,r,"feature length");s=new DataView(e).getUint32(0,!0)}const i=await t.getRange(n+4,s,r,"feature data"),o=new Uint8Array(i),a=new Uint8Array(s+4);a.set(o,4);const h=new l(a);return h.setPosition(4),U.getRootAsFeature(h)}}class lt{constructor(t){this.bytesEverUsed=0,this.bytesEverFetched=0,this.buffer=new ArrayBuffer(0),this.head=0,this.httpClient="string"==typeof t?new bt(t):t}async getRange(t,e,r,n){this.bytesEverUsed+=e;const s=t-this.head,i=s+e;if(s>=0&&i<=this.buffer.byteLength)return this.buffer.slice(s,i);const o=Math.max(e,r);return this.bytesEverFetched+=o,it.debug(`requesting for new Range: ${t}-${t+e-1}`),this.buffer=await this.httpClient.getRange(t,o,n),this.head=t,this.buffer.slice(0,e)}logUsage(t){const e=t.split(" ")[0],r=this.bytesEverUsed,n=this.bytesEverFetched,s=(100*r/n).toFixed(2);it.info(`${e} bytes used/requested: ${r} / ${n} = ${s}%`)}}class bt{constructor(t){this.requestsEverMade=0,this.bytesEverRequested=0,this.url=t}async getRange(t,e,r){this.requestsEverMade+=1,this.bytesEverRequested+=e;const n=`bytes=${t}-${t+e-1}`;it.info(`request: #${this.requestsEverMade}, purpose: ${r}), bytes: (this_request: ${e}, ever: ${this.bytesEverRequested}), Range: ${n}`);return(await fetch(this.url,{headers:{Range:n}})).arrayBuffer()}}async function*ft(t,e,r){const n="function"==typeof(s=t).slice?s:new E("function"==typeof s.read?s:s.getReader());var s;const i=async t=>await n.slice(t);let o=new Uint8Array(await i(8));if(!o.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");o=new Uint8Array(await i(4));let a=new l(o);const h=a.readUint32(0);o=new Uint8Array(await i(h)),a=new l(o);const c=p.fromByteBuffer(a);r&&r(c);const{indexNodeSize:u,featuresCount:b}=c;if(u>0){const t=ot(b,u);await i(t)}let f;for(;f=await dt(i,c,e);)yield f}async function dt(t,e,r){let n=new Uint8Array(await t(4,"feature length"));if(0===n.byteLength)return;let s=new l(n);const i=s.readUint32(0);n=new Uint8Array(await t(i,"feature data"));const o=new Uint8Array(i+4);o.set(n,4),s=new l(o),s.setPosition(4);return r(U.getRootAsFeature(s),e)}function _t(t){const e=new b;let r=null;t.columns&&(r=_.createColumnsVector(e,t.columns.map((t=>function(t,e){const r=t.createString(e.name);return f.startColumn(t),f.addName(t,r),f.addType(t,e.type),f.endColumn(t)}(e,t)))));const n=e.createString("L1");_.startHeader(e),_.addFeaturesCount(e,new h(t.featuresCount,0)),_.addGeometryType(e,t.geometryType),_.addIndexNodeSize(e,0),r&&_.addColumns(e,r),_.addName(e,n);const s=_.endHeader(e);return e.finishSizePrefixed(s),e.asUint8Array()}function pt(t){const n=function(t){const n=t.features[0].properties;let s=null;n&&(s=Object.keys(n).map((t=>new e(t,function(t){if("boolean"==typeof t)return r.Bool;if("number"==typeof t)return t%1==0?r.Int:r.Double;if("string"==typeof t)return r.String;if(null===t)return r.String;throw new Error(`Unknown type (value '${t}')`)}(n[t]),null,null,-1,-1,-1,!0,!1,!1))));const i=function(t){let e;for(const n of t){if(e===u.Unknown)break;const t=(r=n).getGeometry?m(r.getGeometry().getType()):m(r.geometry.type);void 0===e?e=t:e!==t&&(e=u.Unknown)}var r;if(void 0===e)throw new Error("Could not infer geometry type for collection of features.");return e}(t.features);return new p(i,s,t.features.length,0,null,null,null,null)}(t),s=_t(n),i=t.features.map((t=>S(I(t.geometry),t.properties,n))),o=i.map((t=>t.length)).reduce(((t,e)=>t+e)),a=new Uint8Array(ct.length+s.length+o);a.set(s,ct.length);let h=ct.length+s.length;for(const t of i)a.set(t,h),h+=t.length;return a.set(ct),a}function yt(t,e){const r=function(t,e,r){if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");const n=new l(t),s=n.readUint32(ct.length);n.setPosition(ct.length+4);const i=p.fromByteBuffer(n);r&&r(i);let o=ct.length+4+s;const{indexNodeSize:a,featuresCount:h}=i;a>0&&(o+=ot(h,a));const c=[];for(;o Date: Fri, 14 Jun 2024 00:15:08 +0200 Subject: [PATCH 12/17] rm old fgb --- .../FlatGeoBuf/flatgeobuf-geojson.min_old.js | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min_old.js diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min_old.js b/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min_old.js deleted file mode 100644 index 56b58ce..0000000 --- a/inst/htmlwidgets/lib/FlatGeoBuf/flatgeobuf-geojson.min_old.js +++ /dev/null @@ -1,17 +0,0 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).flatgeobuf={})}(this,(function(t){"use strict";class e{constructor(t,e,r,n,s,i,o,a,h,c){this.name=t,this.type=e,this.title=r,this.description=n,this.width=s,this.precision=i,this.scale=o,this.nullable=a,this.unique=h,this.primary_key=c}}var r;!function(t){t[t.Byte=0]="Byte",t[t.UByte=1]="UByte",t[t.Bool=2]="Bool",t[t.Short=3]="Short",t[t.UShort=4]="UShort",t[t.Int=5]="Int",t[t.UInt=6]="UInt",t[t.Long=7]="Long",t[t.ULong=8]="ULong",t[t.Float=9]="Float",t[t.Double=10]="Double",t[t.String=11]="String",t[t.Json=12]="Json",t[t.DateTime=13]="DateTime",t[t.Binary=14]="Binary"}(r||(r={}));class n{constructor(t,e,r,n,s,i){this.org=t,this.code=e,this.name=r,this.description=n,this.wkt=s,this.code_string=i}}const s=new Int32Array(2),i=new Float32Array(s.buffer),o=new Float64Array(s.buffer),a=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0];class h{constructor(t,e){this.low=0|t,this.high=0|e}static create(t,e){return 0==t&&0==e?h.ZERO:new h(t,e)}toFloat64(){return(this.low>>>0)+4294967296*this.high}equals(t){return this.low==t.low&&this.high==t.high}}var c,u;h.ZERO=new h(0,0),function(t){t[t.UTF8_BYTES=1]="UTF8_BYTES",t[t.UTF16_STRING=2]="UTF16_STRING"}(c||(c={}));class l{constructor(t){this.bytes_=t,this.position_=0}static allocate(t){return new l(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return new h(this.readInt32(t),this.readInt32(t+4))}readUint64(t){return new h(this.readUint32(t),this.readUint32(t+4))}readFloat32(t){return s[0]=this.readInt32(t),i[0]}readFloat64(t){return s[a?0:1]=this.readInt32(t),s[a?1:0]=this.readInt32(t+4),o[0]}writeInt8(t,e){this.bytes_[t]=e}writeUint8(t,e){this.bytes_[t]=e}writeInt16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)}writeUint64(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)}writeFloat32(t,e){i[0]=e,this.writeInt32(t,s[0])}writeFloat64(t,e){o[0]=e,this.writeInt32(t,s[a?0:1]),this.writeInt32(t+4,s[a?1:0])}getBufferIdentifier(){if(this.bytes_.length>10),56320+(1023&e)))}return n}__union_with_string(t,e){return"string"==typeof t?this.__string(e):this.__union(t,e)}__indirect(t){return t+this.readInt32(t)}__vector(t){return t+this.readInt32(t)+4}__vector_len(t){return this.readInt32(t+this.readInt32(t))}__has_identifier(t){if(4!=t.length)throw new Error("FlatBuffers: file identifier must be length 4");for(let e=0;e<4;e++)if(t.charCodeAt(e)!=this.readInt8(this.position()+4+e))return!1;return!0}createLong(t,e){return h.create(t,e)}createScalarList(t,e){const r=[];for(let n=0;nthis.minalign&&(this.minalign=t);const r=1+~(this.bb.capacity()-this.space+e)&t-1;for(;this.space=0&&0==this.vtable[e];e--);const r=e+1;for(;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);const n=2*(r+2);this.addInt16(n);let s=0;const i=this.space;t:for(e=0;e=0;e--)this.writeInt8(t.charCodeAt(e))}this.prep(this.minalign,4+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const r=this.bb.capacity()-t,n=r-this.bb.readInt32(r);if(!(0!=this.bb.readInt16(n+e)))throw new Error("FlatBuffers: field "+e+" must be set")}startVector(t,e,r){this.notNested(),this.vector_num_elems=e,this.prep(4,t*e),this.prep(r,t*e)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(t){if(!t)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(t))return this.string_maps.get(t);const e=this.createString(t);return this.string_maps.set(t,e),e}createString(t){if(!t)return 0;let e;if(t instanceof Uint8Array)e=t;else{e=[];let r=0;for(;r=56320)n=s;else{n=(s<<10)+t.charCodeAt(r++)+-56613888}n<128?e.push(n):(n<2048?e.push(n>>6&31|192):(n<65536?e.push(n>>12&15|224):e.push(n>>18&7|240,n>>12&63|128),e.push(n>>6&63|128)),e.push(63&n|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(let t=0,r=this.space,n=this.bb.bytes();t=0;r--)t.addFloat64(e[r]);return t.endVector()}static startEnvelopeVector(t,e){t.startVector(8,e,8)}static addGeometryType(t,e){t.addFieldInt8(2,e,u.Unknown)}static addHasZ(t,e){t.addFieldInt8(3,+e,0)}static addHasM(t,e){t.addFieldInt8(4,+e,0)}static addHasT(t,e){t.addFieldInt8(5,+e,0)}static addHasTm(t,e){t.addFieldInt8(6,+e,0)}static addColumns(t,e){t.addFieldOffset(7,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static addFeaturesCount(t,e){t.addFieldInt64(8,e,t.createLong(0,0))}static addIndexNodeSize(t,e){t.addFieldInt16(9,e,16)}static addCrs(t,e){t.addFieldOffset(10,e,0)}static addTitle(t,e){t.addFieldOffset(11,e,0)}static addDescription(t,e){t.addFieldOffset(12,e,0)}static addMetadata(t,e){t.addFieldOffset(13,e,0)}static endHeader(t){return t.endObject()}static finishHeaderBuffer(t,e){t.finish(e)}static finishSizePrefixedHeaderBuffer(t,e){t.finish(e,void 0,!0)}}class p{constructor(t,e,r,n,s,i,o,a){this.geometryType=t,this.columns=e,this.featuresCount=r,this.indexNodeSize=n,this.crs=s,this.title=i,this.description=o,this.metadata=a}static fromByteBuffer(t){const r=_.getRootAsHeader(t),s=r.featuresCount().toFloat64(),i=r.indexNodeSize(),o=[];for(let t=0;t=0;r--)t.addInt32(e[r]);return t.endVector()}static startEndsVector(t,e){t.startVector(4,e,4)}static addXy(t,e){t.addFieldOffset(1,e,0)}static createXyVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startXyVector(t,e){t.startVector(8,e,8)}static addZ(t,e){t.addFieldOffset(2,e,0)}static createZVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startZVector(t,e){t.startVector(8,e,8)}static addM(t,e){t.addFieldOffset(3,e,0)}static createMVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startMVector(t,e){t.startVector(8,e,8)}static addT(t,e){t.addFieldOffset(4,e,0)}static createTVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addFloat64(e[r]);return t.endVector()}static startTVector(t,e){t.startVector(8,e,8)}static addTm(t,e){t.addFieldOffset(5,e,0)}static createTmVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startTmVector(t,e){t.startVector(8,e,8)}static addType(t,e){t.addFieldInt8(6,e,u.Unknown)}static addParts(t,e){t.addFieldOffset(7,e,0)}static createPartsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startPartsVector(t,e){t.startVector(4,e,4)}static endGeometry(t){return t.endObject()}static createGeometry(t,e,r,n,s,i,o,a,h){return y.startGeometry(t),y.addEnds(t,e),y.addXy(t,r),y.addZ(t,n),y.addM(t,s),y.addT(t,i),y.addTm(t,o),y.addType(t,a),y.addParts(t,h),y.endGeometry(t)}}function g(t,e){const{xy:r,z:n,ends:s,parts:i,type:o}=e;if(i){const e=i.map((e=>g(t,e))),r=y.createPartsVector(t,e);return y.startGeometry(t),y.addParts(t,r),y.addType(t,o),y.endGeometry(t)}const a=y.createXyVector(t,r);let h,c;return n&&(h=y.createZVector(t,n)),s&&(c=y.createEndsVector(t,s)),y.startGeometry(t),c&&y.addEnds(t,c),y.addXy(t,a),h&&y.addZ(t,h),y.addType(t,o),y.endGeometry(t)}function w(t,e,r){if(0!==t.length)if(Array.isArray(t[0]))for(const n of t)w(n,e,r);else 2===t.length?e.push(...t):(e.push(t[0],t[1]),r.push(t[2]))}function v(t,e){const r=[];for(let n=0;n>1]),r.push(s)}return r}function m(t){if(!t)return u.Unknown;return u[t]}function I(t){const e=t.coordinates,r=[],n=[];let s,i;const o=m(t.type);let a=0;switch(t.type){case"Point":case"MultiPoint":case"LineString":w(e,r,n);break;case"MultiLineString":case"Polygon":{const t=e;w(t,r,n),t.length>1&&(s=t.map((t=>a+=t.length)));break}case"MultiPolygon":i=e.map((t=>({type:"Polygon",coordinates:t}))).map(I);break;case"GeometryCollection":t.geometries&&(i=t.geometries.map(I))}return{xy:r,z:n.length>0?n:void 0,ends:s,type:o,parts:i}}function F(t,e,r){if(!r||0===r.length)return[v(t,e)];let n=0;const s=Array.from(r).map((e=>t.slice(n,n=e<<1)));let i;return e&&(n=0,i=Array.from(r).map((t=>e.slice(n,n=t)))),s.map(((t,e)=>v(t,i?i[e]:void 0)))}function x(t,e){let r=e;if(r===u.Unknown&&(r=t.type()),r===u.GeometryCollection){const e=[];for(let r=0;rt.coordinates))}}const n=function(t,e){const r=t.xyArray(),n=t.zArray();switch(e){case u.Point:{const t=Array.from(r);return n&&t.push(n[0]),t}case u.MultiPoint:case u.LineString:return v(r,n);case u.MultiLineString:case u.Polygon:return F(r,n,t.endsArray())}}(t,r);return{type:u[r],coordinates:n}}class U{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFeature(t,e){return(e||new U).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFeature(t,e){return t.setPosition(t.position()+4),(e||new U).__init(t.readInt32(t.position())+t.position(),t)}geometry(t){const e=this.bb.__offset(this.bb_pos,4);return e?(t||new y).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}properties(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}propertiesLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}propertiesArray(){const t=this.bb.__offset(this.bb_pos,6);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}columns(t,e){const r=this.bb.__offset(this.bb_pos,8);return r?(e||new f).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}columnsLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFeature(t){t.startObject(3)}static addGeometry(t,e){t.addFieldOffset(0,e,0)}static addProperties(t,e){t.addFieldOffset(1,e,0)}static createPropertiesVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startPropertiesVector(t,e){t.startVector(1,e,1)}static addColumns(t,e){t.addFieldOffset(2,e,0)}static createColumnsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startColumnsVector(t,e){t.startVector(4,e,4)}static endFeature(t){return t.endObject()}static finishFeatureBuffer(t,e){t.finish(e)}static finishSizePrefixedFeatureBuffer(t,e){t.finish(e,void 0,!0)}static createFeature(t,e,r,n){return U.startFeature(t),U.addGeometry(t,e),U.addProperties(t,r),U.addColumns(t,n),U.endFeature(t)}}const P=new TextEncoder,O=new TextDecoder;function S(t,e,n){const s=n.columns,i=new b;let o=0,a=1024,h=new Uint8Array(a),c=new DataView(h.buffer);const u=function(t){if(o+t0&&(l=U.createPropertiesVector(i,h.slice(0,o)));const f=g(i,t);U.startFeature(i),U.addGeometry(i,f),l&&U.addProperties(i,l);const d=U.endFeature(i);return i.finishSizePrefixed(d),i.asUint8Array()}function C(t,e){const n=e.columns,s={type:"Feature",geometry:x(t.geometry(),e.geometryType)};return n&&n.length>0&&(s.properties=function(t,e){const n={};if(!e||0===e.length)return n;const s=t.propertiesArray();if(!s)return n;const i=new DataView(s.buffer,s.byteOffset),o=t.propertiesLength();let a=0;for(;a0?{done:!1,value:e}:{done:!0,value:void 0}:{done:!1,value:V(e,r.value)}}))},E.prototype.slice=function(t){if((t|=0)<0)throw new Error("invalid length");var e=this,r=this._array.length-this._index;if(this._index+t<=this._array.length)return Promise.resolve(this._array.subarray(this._index,this._index+=t));var n=new Uint8Array(t);return n.set(this._array.subarray(this._index)),function s(){return e._source.read().then((function(i){return i.done?(e._array=A,e._index=0,r>0?n.subarray(0,r):null):r+i.value.length>=t?(e._array=i.value,e._index=t-r,n.set(i.value.subarray(0,t-r),r),n):(n.set(i.value,r),r+=i.value.length,s())}))}()},E.prototype.cancel=function(){return this._source.cancel()}; -/*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ -var T=function(t,e){return T=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},T(t,e)};function B(t,e,r,n){return new(r||(r=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function a(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,a)}h((n=n.apply(t,e||[])).next())}))}function k(t,e){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=o.trys,(s=s.length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(t){return this instanceof N?(this.v=t,this):new N(t)}function R(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(t,e||[]),i=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(t){s[t]&&(n[t]=function(e){return new Promise((function(r,n){i.push([t,e,r,n])>1||a(t,e)}))})}function a(t,e){try{(r=s[t](e)).value instanceof N?Promise.resolve(r.value.v).then(h,c):u(i[0][2],r)}catch(t){u(i[0][3],t)}var r}function h(t){a("next",t)}function c(t){a("throw",t)}function u(t,e){t(e),i.shift(),i.length&&a(i[0][0],i[0][1])}}var q=function(t){function e(e){var r=t.call(this,e)||this;return Object.defineProperty(r,"name",{value:"RepeaterOverflowError",enumerable:!1}),"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(r,r.constructor.prototype):r.__proto__=r.constructor.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,r.constructor),r}return function(t,e){function r(){this.constructor=t}T(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}(e,t),e}(Error);function M(t){null!=t&&"function"==typeof t.then&&t.then($,$)}!function(){function t(t){if(t<0)throw new RangeError("Capacity may not be less than 0");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return this._q.length>=this._c},enumerable:!1,configurable:!0}),t.prototype.add=function(t){if(this.full)throw new Error("Buffer full");this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){for(;this._q.length>=this._c;)this._q.shift();this._q.push(t)},t.prototype.remove=function(){if(this.empty)throw new Error("Buffer empty");return this._q.shift()}}(),function(){function t(t){if(t<1)throw new RangeError("Capacity may not be less than 1");this._c=t,this._q=[]}Object.defineProperty(t.prototype,"empty",{get:function(){return 0===this._q.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"full",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.add=function(t){this._q.length=3;return Promise.resolve(e).then((function(e){return!r&&t.state>=4?z(t).then((function(t){return{value:t,done:!0}})):{value:e,done:r}}))}function D(t,e){var r,n;if(!(t.state>=2))if(t.state=2,t.onnext(),t.onstop(),null==t.err&&(t.err=e),0!==t.pushes.length||void 0!==t.buffer&&!t.buffer.empty)try{for(var s=L(t.pushes),i=s.next();!i.done;i=s.next()){i.value.resolve()}}catch(t){r={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}else H(t)}function H(t){var e,r;if(!(t.state>=3)){t.state<2&&D(t),t.state=3,t.buffer=void 0;try{for(var n=L(t.nexts),s=n.next();!s.done;s=n.next()){var i=s.value,o=void 0===t.pending?z(t):t.pending.then((function(){return z(t)}));i.resolve(G(t,o))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}t.pushes=[],t.nexts=[]}}function W(t){t.state>=4||(t.state<3&&H(t),t.state=4)}function Z(t,e){if(M(e),t.pushes.length>=j)throw new q("No more than 1024 pending calls to push are allowed on a single repeater.");if(t.state>=2)return Promise.resolve(void 0);var r,n=void 0===t.pending?Promise.resolve(e):t.pending.then((function(){return e}));(n=n.catch((function(e){t.state<2&&(t.err=e),W(t)})),t.nexts.length)?(t.nexts.shift().resolve(G(t,n)),r=t.nexts.length?Promise.resolve(t.nexts[0].value):new Promise((function(e){return t.onnext=e}))):void 0===t.buffer||t.buffer.full?r=new Promise((function(e){return t.pushes.push({resolve:e,value:n})})):(t.buffer.add(n),r=Promise.resolve(void 0));var s=!0,i={},o=r.catch((function(t){if(s)throw t}));return i.then=function(t,e){return s=!1,Promise.prototype.then.call(r,t,e)},i.catch=function(t){return s=!1,Promise.prototype.catch.call(r,t)},i.finally=r.finally.bind(r),t.pending=n.then((function(){return o})).catch((function(e){t.err=e,W(t)})),i}function X(t){if(!(t.state>=1)){t.state=1;var e=Z.bind(null,t),r=function(t){var e=D.bind(null,t),r=new Promise((function(e){return t.onstop=e}));return e.then=r.then.bind(r),e.catch=r.catch.bind(r),e.finally=r.finally.bind(r),e}(t);t.execution=new Promise((function(n){return n(t.executor(e,r))})),t.execution.catch((function(){return D(t)}))}}var Y,K=new WeakMap,J=function(){function t(t,e){K.set(this,{executor:t,buffer:e,err:void 0,state:0,pushes:[],nexts:[],pending:void 0,execution:void 0,onnext:$,onstop:$})}return t.prototype.next=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");if(e.nexts.length>=j)throw new q("No more than 1024 pending calls to next are allowed on a single repeater.");if(e.state<=0&&X(e),e.onnext(t),void 0!==e.buffer&&!e.buffer.empty){var r=G(e,e.buffer.remove());if(e.pushes.length){var n=e.pushes.shift();e.buffer.add(n.value),e.onnext=n.resolve}return r}if(e.pushes.length){var s=e.pushes.shift();return e.onnext=s.resolve,G(e,s.value)}return e.state>=2?(H(e),G(e,z(e))):new Promise((function(r){return e.nexts.push({resolve:r,value:t})}))},t.prototype.return=function(t){M(t);var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return H(e),e.execution=Promise.resolve(e.execution).then((function(){return t})),G(e,z(e))},t.prototype.throw=function(t){var e=K.get(this);if(void 0===e)throw new Error("WeakMap error");return e.state<=0||e.state>=2||void 0!==e.buffer&&!e.buffer.empty?(H(e),null==e.err&&(e.err=t),G(e,z(e))):this.next(Promise.reject(t))},t.prototype[Symbol.asyncIterator]=function(){return this},t.race=tt,t.merge=et,t.zip=rt,t.latest=nt,t}();function Q(t,e){var r,n,s=[],i=function(t){null!=t&&"function"==typeof t[Symbol.asyncIterator]?s.push(t[Symbol.asyncIterator]()):null!=t&&"function"==typeof t[Symbol.iterator]?s.push(t[Symbol.iterator]()):s.push(function(){return R(this,arguments,(function(){return k(this,(function(r){switch(r.label){case 0:return e.yieldValues?[4,N(t)]:[3,3];case 1:return[4,r.sent()];case 2:r.sent(),r.label=3;case 3:return e.returnValues?[4,N(t)]:[3,5];case 4:return[2,r.sent()];case 5:return[2]}}))}))}())};try{for(var o=L(t),a=o.next();!a.done;a=o.next()){i(a.value)}}catch(t){r={error:t}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return s}function tt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2];s=!1,n.then((function(){e(),s=!0})),c.label=1;case 1:c.trys.push([1,,5,7]),o=void 0,a=0,h=function(){var s,h,c,u,l,b;return k(this,(function(f){switch(f.label){case 0:s=a;try{for(l=void 0,h=L(r),c=h.next();!c.done;c=h.next())u=c.value,Promise.resolve(u.next()).then((function(t){t.done?(n(),void 0===i&&(i=t)):a===s&&(a++,e(t))}),(function(t){return n(t)}))}catch(t){l={error:t}}finally{try{c&&!c.done&&(b=h.return)&&b.call(h)}finally{if(l)throw l.error}}return[4,new Promise((function(t){return e=t}))];case 1:return void 0===(o=f.sent())?[3,3]:[4,t(o.value)];case 2:f.sent(),f.label=3;case 3:return[2]}}))},c.label=2;case 2:return s?[3,4]:[5,h()];case 3:return c.sent(),[3,2];case 4:return[2,i&&i.value];case 5:return n(),[4,Promise.race(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}function et(t){var e=this,r=Q(t,{yieldValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o=this;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2];e=[],s=!1,n.then((function(){var t,r;s=!0;try{for(var n=L(e),i=n.next();!i.done;i=n.next()){(0,i.value)()}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all(r.map((function(r,a){return B(o,void 0,void 0,(function(){var o;return k(this,(function(h){switch(h.label){case 0:h.trys.push([0,,6,9]),h.label=1;case 1:return s?[3,5]:(Promise.resolve(r.next()).then((function(t){return e[a](t)}),(function(t){return n(t)})),[4,new Promise((function(t){e[a]=t}))]);case 2:return void 0===(o=h.sent())?[3,4]:o.done?(i=o,[2]):[4,t(o.value)];case 3:h.sent(),h.label=4;case 4:return[3,1];case 5:return[3,9];case 6:return r.return?[4,r.return()]:[3,8];case 7:h.sent(),h.label=8;case 8:return[7];case 9:return[2]}}))}))})))];case 2:return a.sent(),[2,i&&i.value];case 3:return n(),[7];case 4:return[2]}}))}))}))}function rt(t){var e=this,r=Q(t,{returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o;return k(this,(function(a){switch(a.label){case 0:if(!r.length)return n(),[2,[]];s=!1,n.then((function(){e(),s=!0})),a.label=1;case 1:a.trys.push([1,,6,8]),a.label=2;case 2:return s?[3,5]:(Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))]);case 3:return void 0===(i=a.sent())?[2]:(o=i.map((function(t){return t.value})),i.some((function(t){return t.done}))?[2,o]:[4,t(o)]);case 4:return a.sent(),[3,2];case 5:return[3,8];case 6:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 7:return a.sent(),[7];case 8:return[2]}}))}))}))}function nt(t){var e=this,r=Q(t,{yieldValues:!0,returnValues:!0});return new J((function(t,n){return B(e,void 0,void 0,(function(){var e,s,i,o,a,h=this;return k(this,(function(c){switch(c.label){case 0:if(!r.length)return n(),[2,[]];s=[],i=!1,n.then((function(){var t,r;e();try{for(var n=L(s),o=n.next();!o.done;o=n.next()){(0,o.value)()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}i=!0})),c.label=1;case 1:return c.trys.push([1,,5,7]),Promise.all(r.map((function(t){return t.next()}))).then((function(t){return e(t)}),(function(t){return n(t)})),[4,new Promise((function(t){return e=t}))];case 2:return void 0===(o=c.sent())?[2]:(a=o.map((function(t){return t.value})),o.every((function(t){return t.done}))?[2,a]:[4,t(a.slice())]);case 3:return c.sent(),[4,Promise.all(r.map((function(e,r){return B(h,void 0,void 0,(function(){var h;return k(this,(function(c){switch(c.label){case 0:if(o[r].done)return[2,o[r].value];c.label=1;case 1:return i?[3,4]:(Promise.resolve(e.next()).then((function(t){return s[r](t)}),(function(t){return n(t)})),[4,new Promise((function(t){return s[r]=t}))]);case 2:return void 0===(h=c.sent())?[2,o[r].value]:h.done?[2,h.value]:(a[r]=h.value,[4,t(a.slice())]);case 3:return c.sent(),[3,1];case 4:return[2]}}))}))})))];case 4:return[2,c.sent()];case 5:return n(),[4,Promise.all(r.map((function(t){return t.return&&t.return()})))];case 6:return c.sent(),[7];case 7:return[2]}}))}))}))}class st{constructor(){this._extraRequestThreshold=262144}extraRequestThreshold(){return this._extraRequestThreshold}setExtraRequestThreshold(t){if(t<0)throw new Error("extraRequestThreshold cannot be negative");this._extraRequestThreshold=t}}st.global=new st,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error"}(Y||(Y={}));class it{static debug(){for(var t=arguments.length,e=new Array(t),r=0;rt)){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;nthis.nodes[1]),this.nodes[1]=t}toString(){return`[NodeRange level: ${this._level}, nodes: ${this.nodes[0]}-${this.nodes[1]}]`}}const{minX:i,minY:o,maxX:a,maxY:h}=r;it.info(`tree items: ${t}, nodeSize: ${e}`);const c=function(t,e){if(e<2)throw new Error("Node size must be at least 2");if(0===t)throw new Error("Number of items must be greater than 0");let r=t,n=r;const s=[r];do{r=Math.ceil(r/e),n+=r,s.push(r)}while(1!==r);const i=[];r=n;for(const t of s)i.push(r-t),r-=t;i.reverse(),s.reverse();const o=[];for(let t=0;t{const t=c.length-1;return new s([0,1],t)})()];for(it.debug(`starting stream search with queue: ${l}, numItems: ${t}, nodeSize: ${e}, levelBounds: ${c}`);0!=l.length;){const r=l.shift();it.debug(`popped node: ${r}, queueLength: ${l.length}`);const b=r.startNode(),f=b>=u,[,d]=c[r.level()],_=Math.min(r.endNode()+e,d),p=_-b,y=await n(40*b,40*p),g=new Float64Array(y),w=new Uint32Array(y);for(let e=b;e<_;e++){const n=5*(e-b);if(ag[n+2])continue;if(o>g[n+3])continue;const c=w[8+(n<<1)],d=ht(w[9+(n<<1)],c);if(f){const r=(()=>{if(e ${d}`),p.extendEndNodeToNewOffset(d);continue}const y=(()=>{const t=r.level()-1;return new s([d,d+1],t)})();void 0!==p&&p.level()==y.level()?it.info(`Same level, but too far away. Pushing new request at offset: ${d} rather than merging with distant ${p}`):it.info(`Pushing new level for ${y} onto queue with nearestNodeRange: ${p} since there's not already a range for this level.`),l.push(y)}}}function ht(t,e){if(0!=(4293918720&t))throw Error("integer is too large to be safely represented");return e+t*2**32}const ct=new Uint8Array([102,103,98,3,102,103,98,0]);class ut{constructor(t,e,r,n){this.headerClient=t,this.header=e,this.headerLength=r,this.indexLength=n}static async open(t){const e=new lt(t),r=(()=>{let t,e=0;for(t=0;t<3;t++){e+=16**t*40}return e})(),n=2024+r;it.debug(`fetching header. minReqLength: ${n} (assumedHeaderLength: 2024, assumedIndexLength: ${r})`);{const t=new Uint8Array(await e.getRange(0,8,n,"header"));if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw it.error(`bytes: ${t} != ${ct}`),new Error("Not a FlatGeobuf file");it.debug("magic bytes look good")}let s;{const t=await e.getRange(8,4,n,"header");s=new DataView(t).getUint32(0,!0);if(s>10485760||s<8)throw new Error("Invalid header size");it.debug(`headerLength: ${s}`)}const i=await e.getRange(12,s,n,"header"),o=new l(new Uint8Array(i)),a=p.fromByteBuffer(o),h=ot(a.featuresCount,a.indexNodeSize);return it.debug("completed: opening http reader"),new ut(e,a,s,h)}async*selectBbox(t){const e=this.lengthBeforeTree(),r=this.headerClient,n=async function(t,n){return r.getRange(e+t,n,0,"index")},s=[];let i=[];for await(const e of at(this.header.featuresCount,this.header.indexNodeSize,t,n)){const[t,,]=e;let[,,r]=e;if(!r){it.info("final feature");r=st.global.extraRequestThreshold()}if(0==i.length){i.push([t,r]);continue}const n=i[i.length-1],o=t-(n[0]+n[1]);o>st.global.extraRequestThreshold()&&(it.info(`Pushing new feature batch, since gap ${o} was too large`),s.push(i),i=[]),i.push([t,r])}this.headerClient.logUsage("header+index"),i.length>0&&s.push(i);const o=s.flatMap((t=>this.readFeatureBatch(t)));yield*J.merge(o)}lengthBeforeTree(){return ct.length+4+this.headerLength}lengthBeforeFeatures(){return this.lengthBeforeTree()+this.indexLength}buildFeatureClient(){return new lt(this.headerClient.httpClient)}async*readFeatureBatch(t){const[e]=t[0],[r,n]=t[t.length-1],s=r+n-e,i=this.buildFeatureClient();for(const[e]of t)yield await this.readFeature(i,e,s);i.logUsage("feature")}async readFeature(t,e,r){const n=e+this.lengthBeforeFeatures();let s;{const e=await t.getRange(n,4,r,"feature length");s=new DataView(e).getUint32(0,!0)}const i=await t.getRange(n+4,s,r,"feature data"),o=new Uint8Array(i),a=new Uint8Array(s+4);a.set(o,4);const h=new l(a);return h.setPosition(4),U.getRootAsFeature(h)}}class lt{constructor(t){this.bytesEverUsed=0,this.bytesEverFetched=0,this.buffer=new ArrayBuffer(0),this.head=0,this.httpClient="string"==typeof t?new bt(t):t}async getRange(t,e,r,n){this.bytesEverUsed+=e;const s=t-this.head,i=s+e;if(s>=0&&i<=this.buffer.byteLength)return this.buffer.slice(s,i);const o=Math.max(e,r);return this.bytesEverFetched+=o,it.debug(`requesting for new Range: ${t}-${t+e-1}`),this.buffer=await this.httpClient.getRange(t,o,n),this.head=t,this.buffer.slice(0,e)}logUsage(t){const e=t.split(" ")[0],r=this.bytesEverUsed,n=this.bytesEverFetched,s=(100*r/n).toFixed(2);it.info(`${e} bytes used/requested: ${r} / ${n} = ${s}%`)}}class bt{constructor(t){this.requestsEverMade=0,this.bytesEverRequested=0,this.url=t}async getRange(t,e,r){this.requestsEverMade+=1,this.bytesEverRequested+=e;const n=`bytes=${t}-${t+e-1}`;it.info(`request: #${this.requestsEverMade}, purpose: ${r}), bytes: (this_request: ${e}, ever: ${this.bytesEverRequested}), Range: ${n}`);return(await fetch(this.url,{headers:{Range:n}})).arrayBuffer()}}async function*ft(t,e,r){const n="function"==typeof(s=t).slice?s:new E("function"==typeof s.read?s:s.getReader());var s;const i=async t=>await n.slice(t);let o=new Uint8Array(await i(8));if(!o.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");o=new Uint8Array(await i(4));let a=new l(o);const h=a.readUint32(0);o=new Uint8Array(await i(h)),a=new l(o);const c=p.fromByteBuffer(a);r&&r(c);const{indexNodeSize:u,featuresCount:b}=c;if(u>0){const t=ot(b,u);await i(t)}let f;for(;f=await dt(i,c,e);)yield f}async function dt(t,e,r){let n=new Uint8Array(await t(4,"feature length"));if(0===n.byteLength)return;let s=new l(n);const i=s.readUint32(0);n=new Uint8Array(await t(i,"feature data"));const o=new Uint8Array(i+4);o.set(n,4),s=new l(o),s.setPosition(4);return r(U.getRootAsFeature(s),e)}function _t(t){const e=new b;let r=null;t.columns&&(r=_.createColumnsVector(e,t.columns.map((t=>function(t,e){const r=t.createString(e.name);return f.startColumn(t),f.addName(t,r),f.addType(t,e.type),f.endColumn(t)}(e,t)))));const n=e.createString("L1");_.startHeader(e),_.addFeaturesCount(e,new h(t.featuresCount,0)),_.addGeometryType(e,t.geometryType),_.addIndexNodeSize(e,0),r&&_.addColumns(e,r),_.addName(e,n);const s=_.endHeader(e);return e.finishSizePrefixed(s),e.asUint8Array()}function pt(t){const n=function(t){const n=t.features[0].properties;let s=null;n&&(s=Object.keys(n).map((t=>new e(t,function(t){if("boolean"==typeof t)return r.Bool;if("number"==typeof t)return t%1==0?r.Int:r.Double;if("string"==typeof t)return r.String;if(null===t)return r.String;throw new Error(`Unknown type (value '${t}')`)}(n[t]),null,null,-1,-1,-1,!0,!1,!1))));const i=function(t){let e;for(const n of t){if(e===u.Unknown)break;const t=(r=n).getGeometry?m(r.getGeometry().getType()):m(r.geometry.type);void 0===e?e=t:e!==t&&(e=u.Unknown)}var r;if(void 0===e)throw new Error("Could not infer geometry type for collection of features.");return e}(t.features);return new p(i,s,t.features.length,0,null,null,null,null)}(t),s=_t(n),i=t.features.map((t=>S(I(t.geometry),t.properties,n))),o=i.map((t=>t.length)).reduce(((t,e)=>t+e)),a=new Uint8Array(ct.length+s.length+o);a.set(s,ct.length);let h=ct.length+s.length;for(const t of i)a.set(t,h),h+=t.length;return a.set(ct),a}function yt(t,e){const r=function(t,e,r){if(!t.subarray(0,3).every(((t,e)=>ct[e]===t)))throw new Error("Not a FlatGeobuf file");const n=new l(t),s=n.readUint32(ct.length);n.setPosition(ct.length+4);const i=p.fromByteBuffer(n);r&&r(i);let o=ct.length+4+s;const{indexNodeSize:a,featuresCount:h}=i;a>0&&(o+=ot(h,a));const c=[];for(;o Date: Mon, 8 Jul 2024 11:19:35 +0200 Subject: [PATCH 13/17] dont remove bool options --- R/file.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/file.R b/R/file.R index 31df659..9146f6e 100644 --- a/R/file.R +++ b/R/file.R @@ -409,7 +409,7 @@ addFgb = function(map, scale = utils::modifyList(scaleOptions(), scale) - options = options[!(options %in% style_list)] + options = options[!(names(options) %in% names(style_list))] map$dependencies = c( map$dependencies From bde6603e6e420e22273995ba5d997d71c1ab9213 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Wed, 10 Jul 2024 00:13:54 +0200 Subject: [PATCH 14/17] expose labelOptions --- R/file.R | 13 ++++++++----- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 20 +++++++++++--------- man/addFgb.Rd | 4 ++++ 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/R/file.R b/R/file.R index 9146f6e..86eed26 100644 --- a/R/file.R +++ b/R/file.R @@ -305,7 +305,7 @@ addTileFolder = function(map, #' opacity, fillOpacity if those are to be mapped to an attribute column. #' @param minZoom minimum zoom level at which data should be rendered. #' @param maxZoom maximum zoom level at which data should be rendered. -#' @inheritParams leaflet::highlightOptions +#' @inheritParams leaflet::addPolylines #' @param ... currently not used. #' #' @examples @@ -360,6 +360,7 @@ addFgb = function(map, minZoom = NULL, maxZoom = 52, highlightOptions = NULL, + labelOptions = NULL, ...) { @@ -377,10 +378,8 @@ addFgb = function(map, if (is.null(layerId)) layerId = group layerId = gsub("[[:punct:] ]", "_", layerId) - # layerId = gsub("\\.", "_", layerId) - # layerId = gsub(" ", "", layerId) - # layerId = gsub('\\"', '', layerId) - # layerId = gsub("\\'", "", layerId) + + if (missing(labelOptions)) labelOptions <- leaflet::labelOptions() if (!is.null(file)) { if (!file.exists(file)) { @@ -443,6 +442,7 @@ addFgb = function(map, , minZoom , maxZoom , highlightOptions + , labelOptions ) } else { leaflet::invokeMethod( @@ -460,6 +460,7 @@ addFgb = function(map, , scale , scaleFields , highlightOptions + , labelOptions ) } } else { @@ -501,6 +502,7 @@ addFgb = function(map, , minZoom , maxZoom , highlightOptions + , labelOptions ) } else { leaflet::invokeMethod( @@ -518,6 +520,7 @@ addFgb = function(map, , scale , scaleFields , highlightOptions + , labelOptions ) } } diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index ef6525e..d923a3d 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -34,7 +34,8 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, className, scale, scaleFields, - highlightOptions) { + highlightOptions, + labelOptions) { const map = this; let gl = false; @@ -118,18 +119,18 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, if (Object.keys(result.value.properties).includes(label)) { lyr.bindTooltip(function (layer) { return layer.feature.properties[label].toString(); - }, {sticky: true}); + }, labelOptions); } else if (typeof(label) === Object || (typeof(label) === 'object' && label.length > 1)) { let lb = label[cntr]; lyr.bindTooltip(function (layer) { return(lb); - }, {sticky: true}); + }, labelOptions); } else if (typeof(label) === "function") { - lyr.bindTooltip(label, {sticky: true}); + lyr.bindTooltip(label, labelOptions); } else { lyr.bindTooltip(function (layer) { return(label); - }, {sticky: true}); + }, labelOptions); } } @@ -303,7 +304,8 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, scaleFields, minZoom, maxZoom, - highlightOptions) { + highlightOptions, + labelOptions) { const map = this; let gl = false; @@ -409,13 +411,13 @@ LeafletWidget.methods.addFlatGeoBufFiltered = function (layerId, if (Object.keys(feature.properties).includes(label)) { lyr.bindTooltip(function (layer) { return layer.feature.properties[label].toString(); - }, {sticky: true}); + }, labelOptions); } else if (typeof(label) === "function") { - lyr.bindTooltip(label, {sticky: true}); + lyr.bindTooltip(label, labelOptions); } else { lyr.bindTooltip(function (layer) { return(label); - }, {sticky: true}); + }, labelOptions); } } diff --git a/man/addFgb.Rd b/man/addFgb.Rd index 9de7f86..3c4d222 100644 --- a/man/addFgb.Rd +++ b/man/addFgb.Rd @@ -27,6 +27,7 @@ addFgb( minZoom = NULL, maxZoom = 52, highlightOptions = NULL, + labelOptions = NULL, ... ) } @@ -83,6 +84,9 @@ opacity, fillOpacity if those are to be mapped to an attribute column.} \item{highlightOptions}{Options for highlighting the shape on mouse over.} +\item{labelOptions}{A Vector of \code{\link[leaflet]{labelOptions}} to provide label +options for each label. Default \code{NULL}} + \item{...}{currently not used.} } \description{ From c275c5d512c90044fdd87e92aef7a8bdc0668003 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Mon, 29 Jul 2024 17:09:01 +0200 Subject: [PATCH 15/17] fix: add typeof(popup) == "function" --- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index d923a3d..db3350a 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -204,6 +204,8 @@ function makePopup(popup, className) { layer.bindPopup(""); } }; + } else if (typeof(popup) === "function") { + pop = popup } else { pop = function(feature, layer) { popUp = json2table( From ec6922c0ffd4e13c3c60f841b9ef2ebdd33e0a78 Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Tue, 6 Aug 2024 22:07:41 +0200 Subject: [PATCH 16/17] fix highlights when color = NULL and saved as data property --- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index db3350a..94db6b6 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -147,6 +147,9 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, // remove highlight when hover stops 'mouseout': function(e) { const layer = e.target; + if (style.color === null && e.layer.feature.properties.color) { + style.color = e.layer.feature.properties.color + } layer.setStyle(style); if (highlightOptions.sendToBack) { layer.bringToBack(); From b83abb8b5cac48b219cb67cb4f91c926d8588cce Mon Sep 17 00:00:00 2001 From: Sebastian Gatscha Date: Tue, 13 Aug 2024 18:31:53 +0200 Subject: [PATCH 17/17] fix: always use e.layer.feature.properties.color in highlight mouseout if it exists --- inst/htmlwidgets/lib/FlatGeoBuf/fgb.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js index 94db6b6..17a0633 100644 --- a/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js +++ b/inst/htmlwidgets/lib/FlatGeoBuf/fgb.js @@ -147,7 +147,7 @@ LeafletWidget.methods.addFlatGeoBuf = function (layerId, // remove highlight when hover stops 'mouseout': function(e) { const layer = e.target; - if (style.color === null && e.layer.feature.properties.color) { + if (e.layer.feature.properties.color) { style.color = e.layer.feature.properties.color } layer.setStyle(style);