@tangram.gl/basemap-layers 0.0.0 → 10.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +12 -7
  2. package/THIRD-PARTY-NOTICES.md +7 -5
  3. package/dist/geojson-task-worker.js +3166 -0
  4. package/dist/geojson-task-worker.js.map +6 -0
  5. package/dist/geojson-worker.js +1089 -7
  6. package/dist/geojson-worker.js.map +3 -3
  7. package/dist/index.cjs +9588 -2093
  8. package/dist/index.cjs.map +3 -3
  9. package/dist/index.js +9599 -2090
  10. package/dist/index.js.map +3 -3
  11. package/dist/map-style.cjs +456 -20
  12. package/dist/map-style.cjs.map +3 -3
  13. package/dist/map-style.js +456 -19
  14. package/dist/map-style.js.map +2 -2
  15. package/dist/types/basemap-error.d.ts +52 -0
  16. package/dist/types/basemap-layer.d.ts +378 -25
  17. package/dist/types/basemap-protocol.d.ts +91 -0
  18. package/dist/types/basemap-request.d.ts +73 -0
  19. package/dist/types/circle-layer.d.ts +65 -8
  20. package/dist/types/color-relief-layer.d.ts +184 -0
  21. package/dist/types/dem-pixels.d.ts +40 -0
  22. package/dist/types/feature-state.d.ts +55 -0
  23. package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
  24. package/dist/types/fill-outline-extension.d.ts +2 -3
  25. package/dist/types/fill-pattern.d.ts +35 -3
  26. package/dist/types/fill-style-extensions.d.ts +11 -59
  27. package/dist/types/geojson-resource.d.ts +18 -0
  28. package/dist/types/geojson-source.d.ts +13 -2
  29. package/dist/types/geojson-task-handler.d.ts +2 -0
  30. package/dist/types/geojson-task.d.ts +26 -0
  31. package/dist/types/geojson-tiler.d.ts +29 -2
  32. package/dist/types/geojson-worker.d.ts +5 -1
  33. package/dist/types/globe-horizon-extension.d.ts +2 -45
  34. package/dist/types/globe-layers.d.ts +141 -45
  35. package/dist/types/globe-line-angle-extension.d.ts +20 -17
  36. package/dist/types/glyph-store.d.ts +10 -1
  37. package/dist/types/heatmap-layer.d.ts +99 -0
  38. package/dist/types/hillshade-layer.d.ts +159 -27
  39. package/dist/types/icon-text-fit.d.ts +92 -0
  40. package/dist/types/image-source-layer.d.ts +142 -0
  41. package/dist/types/index.d.ts +25 -1
  42. package/dist/types/line-blur-extension.d.ts +3 -11
  43. package/dist/types/line-dash-extension.d.ts +53 -0
  44. package/dist/types/line-gradient-extension.d.ts +69 -0
  45. package/dist/types/line-metrics.d.ts +24 -0
  46. package/dist/types/line-pattern-extension.d.ts +50 -0
  47. package/dist/types/line-shape-extension.d.ts +76 -0
  48. package/dist/types/map-style-loader.d.ts +1 -1
  49. package/dist/types/map-style.d.ts +2 -2
  50. package/dist/types/mvt-label-layer.d.ts +111 -20
  51. package/dist/types/pmtiles-source.d.ts +38 -0
  52. package/dist/types/projected-background-layer.d.ts +63 -0
  53. package/dist/types/projected-bitmap-layer.d.ts +58 -0
  54. package/dist/types/projected-tile-data.d.ts +16 -0
  55. package/dist/types/projected-tile-selection.d.ts +72 -0
  56. package/dist/types/projected-tileset.d.ts +92 -0
  57. package/dist/types/projected-viewport.d.ts +76 -0
  58. package/dist/types/raster-color-extension.d.ts +4 -7
  59. package/dist/types/raster-fade.d.ts +155 -0
  60. package/dist/types/raster-tile-fingerprint.d.ts +11 -0
  61. package/dist/types/raster-tile-loader.d.ts +80 -0
  62. package/dist/types/shader-injection-plugin.d.ts +8 -0
  63. package/dist/types/source-features.d.ts +58 -0
  64. package/dist/types/source-tiles.d.ts +32 -0
  65. package/dist/types/sprite.d.ts +37 -3
  66. package/dist/types/stretch-icon-layer.d.ts +28 -0
  67. package/dist/types/style-accessor.d.ts +50 -12
  68. package/dist/types/style-expression.d.ts +22 -2
  69. package/dist/types/style-resolver.d.ts +47 -2
  70. package/dist/types/terrain-query.d.ts +39 -0
  71. package/dist/types/zoom-load-gate.d.ts +22 -0
  72. package/dist/types/zoom-paint-extension.d.ts +80 -11
  73. package/package.json +24 -21
  74. package/src/basemap-error.ts +82 -0
  75. package/src/basemap-layer.ts +1289 -101
  76. package/src/basemap-protocol.ts +353 -0
  77. package/src/basemap-request.ts +212 -0
  78. package/src/circle-layer.ts +430 -54
  79. package/src/color-relief-layer.ts +572 -0
  80. package/src/dem-pixels.ts +174 -0
  81. package/src/feature-state.ts +164 -0
  82. package/src/fill-extrusion-lighting-extension.ts +126 -9
  83. package/src/fill-outline-extension.ts +4 -4
  84. package/src/fill-pattern.ts +87 -9
  85. package/src/fill-style-extensions.ts +114 -44
  86. package/src/geojson-resource.ts +58 -0
  87. package/src/geojson-source.ts +106 -85
  88. package/src/geojson-task-handler.ts +11 -0
  89. package/src/geojson-task-worker.ts +8 -0
  90. package/src/geojson-task.ts +34 -0
  91. package/src/geojson-tiler.ts +270 -4
  92. package/src/geojson-worker.ts +36 -6
  93. package/src/globe-horizon-extension.ts +14 -4
  94. package/src/globe-layers.ts +1905 -406
  95. package/src/globe-line-angle-extension.ts +183 -23
  96. package/src/glyph-store.ts +28 -6
  97. package/src/heatmap-layer.ts +591 -0
  98. package/src/hillshade-layer.ts +309 -88
  99. package/src/icon-text-fit.ts +358 -0
  100. package/src/image-source-layer.ts +380 -0
  101. package/src/index.ts +58 -1
  102. package/src/line-blur-extension.ts +14 -12
  103. package/src/line-dash-extension.ts +303 -0
  104. package/src/line-gradient-extension.ts +191 -0
  105. package/src/line-metrics.ts +90 -0
  106. package/src/line-pattern-extension.ts +173 -0
  107. package/src/line-shape-extension.ts +272 -0
  108. package/src/map-style-loader.ts +5 -4
  109. package/src/map-style.ts +2 -1
  110. package/src/mvt-label-layer.ts +568 -144
  111. package/src/pmtiles-source.ts +276 -0
  112. package/src/projected-background-layer.ts +202 -0
  113. package/src/projected-bitmap-layer.ts +262 -0
  114. package/src/projected-tile-data.ts +132 -0
  115. package/src/projected-tile-selection.ts +605 -0
  116. package/src/projected-tileset.ts +183 -0
  117. package/src/projected-viewport.ts +254 -0
  118. package/src/raster-color-extension.ts +43 -18
  119. package/src/raster-fade.ts +319 -0
  120. package/src/raster-tile-fingerprint.ts +31 -0
  121. package/src/raster-tile-loader.ts +211 -0
  122. package/src/shader-injection-plugin.ts +25 -0
  123. package/src/source-features.ts +170 -0
  124. package/src/source-tiles.ts +102 -0
  125. package/src/sprite.ts +122 -15
  126. package/src/stretch-icon-layer.ts +87 -0
  127. package/src/style-accessor.ts +105 -17
  128. package/src/style-expression.ts +80 -3
  129. package/src/style-resolver.ts +200 -22
  130. package/src/terrain-query.ts +86 -0
  131. package/src/text-layout.ts +2 -3
  132. package/src/zoom-load-gate.ts +57 -0
  133. package/src/zoom-paint-extension.ts +245 -47
  134. package/dist/types/arabic-shaping.d.ts +0 -7
  135. package/dist/types/bidi.d.ts +0 -8
  136. package/dist/types/polylabel.d.ts +0 -17
  137. package/src/arabic-shaping.ts +0 -366
  138. package/src/bidi.ts +0 -199
  139. package/src/polylabel.ts +0 -312
@@ -2,7 +2,8 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
- import {getCompiledStyleProperty, type StyleFeature} from './style-expression';
5
+ import type {FeatureStateLookup} from './feature-state';
6
+ import {type CompiledStyleProperty, getCompiledStyleProperty, type StyleFeature} from './style-expression';
6
7
 
7
8
  type StyleLayerLike = {
8
9
  paint?: Record<string, unknown>;
@@ -10,24 +11,30 @@ type StyleLayerLike = {
10
11
  };
11
12
 
12
13
  /**
13
- * Zoom step at which style values are evaluated. Paint and layout values step every
14
- * `STYLE_ZOOM_STEP` zoom levels instead of following the zoom continuously.
14
+ * Zoom step at which style values are evaluated. Layout, stepped paint and the endpoints of
15
+ * composite paint attributes step every `STYLE_ZOOM_STEP` zoom levels.
15
16
  */
16
17
  export const STYLE_ZOOM_STEP = 0.25;
17
18
 
18
19
  /**
19
- * Zoom at which paint and layout values are evaluated: the zoom rounded down to a
20
+ * Zoom at which stepped paint and layout values are evaluated: the zoom rounded down to a
20
21
  * `STYLE_ZOOM_STEP`.
21
22
  *
22
- * This is a temporary simplification, not MapLibre's behaviour. MapLibre evaluates zoom-dependent
23
- * expressions at the integer zooms on either side of the current zoom and interpolates between
24
- * them on the GPU, which remains the long-term plan here. Stepping keeps every tile on the same
25
- * evaluation zoom, so neighbouring tiles agree at their seams.
23
+ * On WebGL, supported composite paint blends attributes evaluated at the enclosing style zoom
24
+ * steps on the GPU. Stepping keeps every tile on the same evaluation zoom, so neighbouring
25
+ * tiles agree at their seams.
26
26
  */
27
27
  export function getZoomBucket(zoom: number): number {
28
28
  return Math.floor(zoom / STYLE_ZOOM_STEP) * STYLE_ZOOM_STEP;
29
29
  }
30
30
 
31
+ /** Uses the viewport zoom while it is within the style step of the generated sublayer. */
32
+ export function getZoomPaintZoom(viewportZoom: number, generationZoom?: number): number {
33
+ return generationZoom === undefined || getZoomBucket(viewportZoom) === getZoomBucket(generationZoom)
34
+ ? viewportZoom
35
+ : generationZoom;
36
+ }
37
+
31
38
  /** Zoom at which filters are evaluated: the integer zoom, as the style spec specifies. */
32
39
  export function getFilterZoom(zoom: number): number {
33
40
  return Math.floor(zoom);
@@ -46,38 +53,119 @@ export function getStyleZoomKey(zoom: number, zoomLimits: readonly (number | und
46
53
  return `${getZoomBucket(zoom)}:${crossed}`;
47
54
  }
48
55
 
56
+ /** The style inputs and conversion for one paint value. */
57
+ export type PaintProperty<T> = {
58
+ /** The style properties passed to the conversion in order. */
59
+ names: string[];
60
+ /** Combines the evaluated style properties into a width or color. */
61
+ combine: (values: any[]) => T;
62
+ };
63
+
64
+ /** A paint property that supplies a layer-wide value or the curve for blending feature values. */
65
+ type ZoomPaintProperty<T> = {
66
+ /** Evaluates the layer-wide value, or returns undefined for per-feature paint. */
67
+ evaluate: (zoom: number) => T | undefined;
68
+ /** Whether any of the inputs reads zoom. */
69
+ isZoomDependent: boolean;
70
+ /** Whether any of the inputs reads the feature or its state. */
71
+ isFeatureDependent: boolean;
72
+ /** The curve used to blend the lower and upper per-feature samples. */
73
+ interpolation: CompiledStyleProperty['zoomInterpolation'];
74
+ };
75
+
76
+ /**
77
+ * Compiles the properties that supply a layer-wide value or a composite blend factor.
78
+ * Discrete inputs are held at the lower sample's zoom. When interpolating inputs use different
79
+ * zoom curves, the composite values blend linearly between their sampled zooms.
80
+ */
81
+ export function compileZoomPaintProperty<T>(
82
+ styleLayer: StyleLayerLike,
83
+ definition: PaintProperty<T>
84
+ ): ZoomPaintProperty<T> {
85
+ const properties = definition.names.map(name => getCompiledStyleProperty(styleLayer, name));
86
+ const zoomProperties = properties.filter(property => property?.isZoomDependent);
87
+ const perFeature = properties.some(property => property?.isFeatureDependent);
88
+ const interpolated = zoomProperties.filter(property => property?.zoomInterpolation);
89
+ const curve = interpolated[0]?.zoomInterpolation ?? null;
90
+ const curveKey = JSON.stringify(curve);
91
+ const matchesCurve = interpolated.every(property => JSON.stringify(property?.zoomInterpolation) === curveKey);
92
+ const constants = perFeature
93
+ ? []
94
+ : properties.map(property => property?.isZoomDependent ? undefined : property?.evaluate(0));
95
+ const constant = !perFeature && !zoomProperties.length ? definition.combine(constants) : undefined;
96
+ const evaluate = perFeature
97
+ ? () => undefined
98
+ : zoomProperties.length
99
+ ? (zoom: number) =>
100
+ definition.combine(
101
+ properties.map((property, index) =>
102
+ property?.isZoomDependent ? property.evaluate(zoom) : constants[index]
103
+ )
104
+ )
105
+ : () => constant;
106
+ return {
107
+ evaluate,
108
+ isZoomDependent: zoomProperties.length > 0,
109
+ isFeatureDependent: perFeature,
110
+ interpolation: perFeature ? (matchesCurve ? curve : {name: 'linear'}) : null
111
+ };
112
+ }
113
+
49
114
  /** A deck.gl accessor built from one or more style properties. */
50
115
  export type StyleAccessor<T> = {
51
116
  /** A constant when no property depends on feature data, otherwise a per-feature function. */
52
117
  value: T | ((feature: StyleFeature) => T);
53
- /** Set to the evaluation zoom (`getZoomBucket`) when a per-feature value also depends on zoom. */
54
- updateTrigger?: number;
118
+ /**
119
+ * Set to the evaluation zoom (`getZoomBucket`) when a per-feature value also depends on zoom.
120
+ * A value that reads feature state takes a string instead, which also changes with the states.
121
+ */
122
+ updateTrigger?: number | string;
55
123
  };
56
124
 
57
125
  /**
58
126
  * Builds a deck.gl accessor from style properties, evaluated at the stepped zoom
59
127
  * (`getZoomBucket`). Feature-independent values become constants. Data-driven values become
60
- * per-feature functions, with an update trigger when they also depend on zoom.
128
+ * per-feature functions, with an update trigger when they also depend on zoom. With
129
+ * `featureState`, `["feature-state", ...]` reads each feature's state from it, and the update
130
+ * trigger of a value that reads it changes with the states: only that attribute is computed
131
+ * again, and the geometry is kept.
132
+ *
133
+ * With `exactZoom`, the accessor evaluates the properties at the supplied zoom. With `stepZoom`,
134
+ * discrete zoom-dependent properties are sampled at that zoom instead.
61
135
  */
62
136
  export function getStyleAccessor<T>(
63
137
  styleLayer: StyleLayerLike,
64
138
  propertyNames: string[],
65
139
  zoom: number,
66
- combine: (values: any[]) => T
140
+ combine: (values: any[]) => T,
141
+ featureState?: FeatureStateLookup,
142
+ {exactZoom = false, stepZoom}: {exactZoom?: boolean; stepZoom?: number} = {}
67
143
  ): StyleAccessor<T> {
68
144
  const properties = propertyNames.map(name => getCompiledStyleProperty(styleLayer, name));
69
145
  const isFeatureDependent = properties.some(property => property?.isFeatureDependent);
70
- const zoomBucket = getZoomBucket(zoom);
146
+ const zoomBucket = exactZoom ? zoom : getZoomBucket(zoom);
147
+ const evaluationZooms = properties.map(property =>
148
+ property?.isZoomDependent && !property.zoomInterpolation ? stepZoom ?? zoomBucket : zoomBucket
149
+ );
71
150
 
72
151
  if (!isFeatureDependent) {
73
- return {value: combine(properties.map(property => property?.evaluate(zoomBucket)))};
152
+ return {value: combine(properties.map((property, index) => property?.evaluate(evaluationZooms[index])))};
74
153
  }
75
154
 
76
155
  const isZoomDependent = properties.some(property => property?.isZoomDependent);
156
+ const state = properties.some(property => property?.isStateDependent) ? featureState : undefined;
77
157
  return {
78
- value: (feature: StyleFeature) =>
79
- combine(properties.map(property => property?.evaluate(zoomBucket, feature))),
80
- updateTrigger: isZoomDependent ? zoomBucket : undefined
158
+ value: (feature: StyleFeature) => {
159
+ const featureValues = state?.get(feature);
160
+ return combine(
161
+ properties.map((property, index) =>
162
+ property?.evaluate(evaluationZooms[index], feature, undefined, featureValues)
163
+ )
164
+ );
165
+ },
166
+ updateTrigger: state
167
+ ? `${isZoomDependent ? zoomBucket : ''}:state-${state.token}`
168
+ : isZoomDependent ? zoomBucket : undefined
81
169
  };
82
170
  }
83
171
 
@@ -8,6 +8,8 @@ import {log} from '@deck.gl/core';
8
8
  import {
9
9
  Color,
10
10
  ColorArray,
11
+ Interpolate,
12
+ type InterpolationType,
11
13
  NumberArray,
12
14
  Padding,
13
15
  VariableAnchorOffsetCollection,
@@ -30,11 +32,21 @@ export type CompiledStyleProperty = {
30
32
  isZoomDependent: boolean;
31
33
  /** True when the value depends on feature data (`["get", ...]`, `match`, ...). */
32
34
  isFeatureDependent: boolean;
35
+ /** True when the value depends on the feature's state (`["feature-state", ...]`). */
36
+ isStateDependent: boolean;
37
+ /** Interpolation of the outer zoom curve, or null for discrete or zoom-independent values. */
38
+ zoomInterpolation: InterpolationType | null;
33
39
  /**
34
40
  * Evaluates the property. Colors are returned as `[r, g, b, a]`, with `a` in 0-1.
35
41
  * `availableImages` lists the loaded sprite image names, which `["image", ...]` checks.
42
+ * `featureState` is the feature's state, which `["feature-state", ...]` reads.
36
43
  */
37
- evaluate: (zoom: number, feature?: StyleFeature, availableImages?: string[]) => unknown;
44
+ evaluate: (
45
+ zoom: number,
46
+ feature?: StyleFeature,
47
+ availableImages?: string[],
48
+ featureState?: Record<string, unknown>
49
+ ) => unknown;
38
50
  /**
39
51
  * Evaluates the property with every global input, such as `heatmapDensity` or `lineProgress`
40
52
  * as well as `zoom`. Colors are returned as in `evaluate`.
@@ -197,16 +209,25 @@ export function compileStylePropertyValue(
197
209
  return null;
198
210
  }
199
211
  const kind: string = compiled.kind;
212
+ let zoomInterpolation: InterpolationType | null = compiled.interpolationType ?? null;
213
+ if (kind === 'composite' && value && typeof value === 'object' && 'stops' in value) {
214
+ // A legacy composite function evaluates its zoom axis exponentially, even when the compiler
215
+ // reports linear interpolation. The default base of 1 gives linear interpolation.
216
+ const base = 'base' in value && typeof value.base === 'number' ? value.base : 1;
217
+ zoomInterpolation = base === 1 ? {name: 'linear'} : {name: 'exponential', base};
218
+ }
200
219
 
201
220
  return {
202
221
  isZoomDependent: kind === 'camera' || kind === 'composite',
203
222
  isFeatureDependent: kind === 'source' || kind === 'composite',
204
- evaluate: (zoom, feature, availableImages) =>
223
+ isStateDependent: Boolean(compiled.isStateDependent),
224
+ zoomInterpolation,
225
+ evaluate: (zoom, feature, availableImages, featureState) =>
205
226
  toPlainValue(
206
227
  compiled.evaluate(
207
228
  {zoom},
208
229
  toEvaluationFeature(feature) as any,
209
- undefined,
230
+ featureState as any,
210
231
  undefined,
211
232
  availableImages
212
233
  )
@@ -216,6 +237,22 @@ export function compileStylePropertyValue(
216
237
  };
217
238
  }
218
239
 
240
+ /** The clamped blend between two attribute zooms. A discrete zoom curve holds its lower value. */
241
+ export function getZoomInterpolationFactor(
242
+ interpolation: InterpolationType | null,
243
+ zoom: number,
244
+ lower: number,
245
+ upper: number
246
+ ): number {
247
+ if (!interpolation || zoom <= lower) {
248
+ return 0;
249
+ }
250
+ if (zoom >= upper) {
251
+ return 1;
252
+ }
253
+ return Math.max(0, Math.min(1, Interpolate.interpolationFactor(interpolation, zoom, lower, upper)));
254
+ }
255
+
219
256
  /**
220
257
  * Returns a compiled `paint` or `layout` property of a style layer, or `null` when the layer
221
258
  * does not set it. Compilation is cached per style layer object and property; the cached entry is
@@ -246,6 +283,46 @@ export function getCompiledStyleProperty(
246
283
  return entry.compiled;
247
284
  }
248
285
 
286
+ /** The stops of an interpolated color ramp: each stop's input, and its color. */
287
+ export type ColorRampStops = {
288
+ inputs: number[];
289
+ /** Premultiplied RGBA in 0-1, as MapLibre GL JS's `Color` stores it. */
290
+ colors: [number, number, number, number][];
291
+ };
292
+
293
+ /**
294
+ * The stops of a color ramp property, such as `color-relief-color`, as MapLibre GL JS reads them:
295
+ * the inputs of an `interpolate` (or `interpolate-hcl`, `interpolate-lab`) expression, and the
296
+ * colors it evaluates to at each. `null` for any other value, such as a `step` expression or a
297
+ * constant color, which MapLibre draws transparent. An invalid value logs a warning once.
298
+ */
299
+ export function getColorRampStops(
300
+ propertyName: string,
301
+ value: unknown,
302
+ inputName: string
303
+ ): ColorRampStops | null {
304
+ if (value === undefined) {
305
+ return null;
306
+ }
307
+ const reference = getStylePropertyReference(propertyName);
308
+ const compiled = expression.createPropertyExpression(value as any, reference as any);
309
+ if (compiled.result !== 'success') {
310
+ warnInvalidValue(propertyName, value, compiled.value.map(error => error.message).join(', '));
311
+ return null;
312
+ }
313
+ const ramp = compiled.value as any;
314
+ const interpolate = ramp.kind === 'constant' ? ramp._styleExpression?.expression : null;
315
+ if (!(interpolate instanceof Interpolate)) {
316
+ return null;
317
+ }
318
+ const inputs = [...interpolate.labels];
319
+ const colors = inputs.map(input => {
320
+ const color = ramp.evaluate({[inputName]: input}) as Color;
321
+ return [color.r, color.g, color.b, color.a] as [number, number, number, number];
322
+ });
323
+ return {inputs, colors};
324
+ }
325
+
249
326
  /**
250
327
  * Compiles a style-spec filter into a feature predicate, cached per filter array. The cached
251
328
  * predicate is reused only while the array's contents are unchanged, so a filter edited in place
@@ -3,12 +3,24 @@
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
5
  import {log} from '@deck.gl/core';
6
+ import {
7
+ BasemapFetchError,
8
+ getBasemapLoadError,
9
+ type BasemapLoadErrorHandler
10
+ } from './basemap-error';
6
11
  import {derefLayers} from '@maplibre/maplibre-gl-style-spec';
12
+ import {
13
+ getBasemapResourceFetch,
14
+ type BasemapResourceType,
15
+ type BasemapTransformRequest
16
+ } from './basemap-request';
7
17
  import {
8
18
  BasemapSourceSchema,
9
19
  BasemapStyleSchema,
10
20
  ResolvedBasemapStyleSchema
11
21
  } from './map-style-schema';
22
+ import {getPMTilesSourceFields, isPMTilesUrl, PMTILES_PROTOCOL} from './pmtiles-source';
23
+ import {isBasemapProtocolUrl} from './basemap-protocol';
12
24
 
13
25
  /**
14
26
  * A basemap source entry from a style document.
@@ -16,7 +28,10 @@ import {
16
28
  export type BasemapSource = {
17
29
  /** Source kind such as `vector` or `raster`. */
18
30
  type?: string;
19
- /** Optional TileJSON URL used to resolve the source metadata. */
31
+ /**
32
+ * Optional TileJSON URL used to resolve the source metadata, or a PMTiles archive,
33
+ * `pmtiles://<archive URL>`, whose header resolves it.
34
+ */
20
35
  url?: string;
21
36
  /** Inline tile templates for the source. */
22
37
  tiles?: string[];
@@ -101,13 +116,41 @@ export type BasemapLoadOptions = {
101
116
  fetch?: typeof fetch;
102
117
  /** Optional init object passed to the selected fetch implementation. */
103
118
  fetchOptions?: RequestInit;
119
+ /**
120
+ * Resolved sources by `getSourceKey` of their definition and base URL. A source whose key is in
121
+ * the cache is not fetched again. Each resolution replaces the entries with its own sources.
122
+ */
123
+ sourceCache?: Map<string, BasemapSource>;
124
+ /**
125
+ * Called for each source whose TileJSON or GeoJSON data cannot be loaded, in place of the
126
+ * warning that is logged without it.
127
+ */
128
+ onError?: BasemapLoadErrorHandler;
129
+ /**
130
+ * Changes each request before it is sent (see `BasemapTransformRequest`). `BasemapLayer` sets it
131
+ * from its `transformRequest` prop.
132
+ */
133
+ transformRequest?: BasemapTransformRequest | null;
104
134
  /** Additional loader options are accepted for forward compatibility. */
105
135
  [key: string]: unknown;
106
136
  } | null;
107
137
 
138
+ /**
139
+ * A key of a source's content: its JSON with sorted object keys. Two sources with the same key
140
+ * load the same tiles.
141
+ */
142
+ export function getSourceKey(value: unknown): string {
143
+ return JSON.stringify(value, (_key, item) =>
144
+ item && typeof item === 'object' && !Array.isArray(item)
145
+ ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]]))
146
+ : item
147
+ );
148
+ }
149
+
108
150
  /** Resolves a possibly relative URL against the provided base URL. */
109
151
  function normalizeUrl(url: string | undefined, baseUrl?: string) {
110
- if (!url) {
152
+ // A URL with a registered scheme is absolute, in whatever form its handler reads.
153
+ if (!url || isBasemapProtocolUrl(url)) {
111
154
  return url;
112
155
  }
113
156
 
@@ -123,13 +166,48 @@ function normalizeTiles(tiles: string[] | undefined, baseUrl?: string) {
123
166
  return Array.isArray(tiles) ? tiles.map(tile => normalizeUrl(tile, baseUrl) || tile) : tiles;
124
167
  }
125
168
 
126
- /** Fetches and parses a JSON resource. */
127
- async function fetchJson(url: string, loadOptions?: BasemapLoadOptions) {
128
- const fetchFn = loadOptions?.fetch || fetch;
169
+ /** The last path segment of an ArcGIS service root that lists relative tile templates. */
170
+ const ARCGIS_SERVICE_ROOT = /\/(VectorTileServer|MapServer)$/i;
171
+
172
+ /**
173
+ * The base URL for relative tile templates in a TileJSON. An ArcGIS service root, such as
174
+ * `.../VectorTileServer`, lists `tile/{z}/{y}/{x}.pbf` relative to the root as a directory, so a
175
+ * trailing slash is added. Every other TileJSON URL is used as it is, with standard URL resolution.
176
+ */
177
+ function getTileJsonTileBaseUrl(tileJsonUrl: string | undefined) {
178
+ if (!tileJsonUrl) {
179
+ return tileJsonUrl;
180
+ }
181
+
182
+ try {
183
+ const url = new URL(tileJsonUrl);
184
+ if (ARCGIS_SERVICE_ROOT.test(url.pathname)) {
185
+ url.pathname = `${url.pathname}/`;
186
+ }
187
+ return url.toString();
188
+ } catch {
189
+ return tileJsonUrl;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Fetches and parses a JSON resource with the `fetch`, `fetchOptions` and `transformRequest` of
195
+ * `loadOptions`.
196
+ */
197
+ export async function fetchJson(
198
+ url: string,
199
+ loadOptions: BasemapLoadOptions | undefined,
200
+ resourceType: BasemapResourceType
201
+ ) {
202
+ const fetchFn = getBasemapResourceFetch(resourceType, 'json', loadOptions || undefined);
129
203
  const response = await fetchFn(url, loadOptions?.fetchOptions);
130
204
 
131
205
  if (!response.ok) {
132
- throw new Error(`Failed to load basemap resource: ${url} (${response.status})`);
206
+ throw new BasemapFetchError(
207
+ `Failed to load basemap resource: ${url} (${response.status})`,
208
+ url,
209
+ response.status
210
+ );
133
211
  }
134
212
 
135
213
  return await response.json();
@@ -183,19 +261,31 @@ async function resolveGeoJsonSource(
183
261
  if (typeof source.data !== 'string') {
184
262
  return {...source};
185
263
  }
186
- const dataUrl = normalizeUrl(source.data, baseUrl) || source.data;
187
- const data = await fetchJson(dataUrl, loadOptions);
264
+ return {...source, data: await loadGeoJsonData(source.data, baseUrl, loadOptions)};
265
+ }
266
+
267
+ /**
268
+ * Fetches the GeoJSON of a `geojson` source's `data` URL, as MapLibre loads it. A relative URL
269
+ * resolves against `baseUrl`. Throws if the data cannot be fetched or is not a GeoJSON object.
270
+ */
271
+ export async function loadGeoJsonData(
272
+ url: string,
273
+ baseUrl: string | undefined,
274
+ loadOptions?: BasemapLoadOptions
275
+ ): Promise<object> {
276
+ const dataUrl = normalizeUrl(url, baseUrl) || url;
277
+ const data = await fetchJson(dataUrl, loadOptions, 'Source');
188
278
  if (!data || typeof data !== 'object' || Array.isArray(data)) {
189
279
  throw new Error(`Invalid GeoJSON: ${dataUrl}`);
190
280
  }
191
- return {...source, data};
281
+ return data;
192
282
  }
193
283
 
194
284
  /**
195
285
  * Resolves a single source, including optional TileJSON indirection. As in MapLibre, the style's
196
286
  * own source properties take precedence over the TileJSON's. Inline `tiles` resolve against the
197
- * style's base URL and TileJSON `tiles` against the TileJSON URL. Throws if the TileJSON cannot be
198
- * fetched or the resolved source is invalid.
287
+ * style's base URL and TileJSON `tiles` against the TileJSON URL (see `getTileJsonTileBaseUrl`).
288
+ * Throws if the TileJSON cannot be fetched or the resolved source is invalid.
199
289
  */
200
290
  async function resolveSource(
201
291
  source: BasemapSource | undefined,
@@ -210,13 +300,22 @@ async function resolveSource(
210
300
  return await resolveGeoJsonSource(source, baseUrl, loadOptions);
211
301
  }
212
302
 
303
+ // An image's url resolves against the style's base url, as tile templates do.
304
+ if (source.type === 'image' && typeof source.url === 'string') {
305
+ return {...source, url: normalizeUrl(source.url, baseUrl)};
306
+ }
307
+
213
308
  if (!source.url || !TILEJSON_SOURCE_TYPES.has(String(source.type))) {
214
309
  return source.tiles ? {...source, tiles: normalizeTiles(source.tiles, baseUrl)} : {...source};
215
310
  }
216
311
 
312
+ if (isPMTilesUrl(source.url) && !isBasemapProtocolUrl(source.url)) {
313
+ return await resolvePMTilesSource(source, baseUrl, loadOptions);
314
+ }
315
+
217
316
  const tileJsonUrl = normalizeUrl(source.url, baseUrl);
218
317
  const tileJsonFields = pickTileJsonFields(
219
- await fetchJson(tileJsonUrl || source.url, loadOptions)
318
+ await fetchJson(tileJsonUrl || source.url, loadOptions, 'Source')
220
319
  );
221
320
  const resolvedSource: BasemapSource = {
222
321
  ...tileJsonFields,
@@ -224,7 +323,10 @@ async function resolveSource(
224
323
  url: tileJsonUrl,
225
324
  tiles: source.tiles
226
325
  ? normalizeTiles(source.tiles, baseUrl)
227
- : normalizeTiles(tileJsonFields.tiles as string[] | undefined, tileJsonUrl)
326
+ : normalizeTiles(
327
+ tileJsonFields.tiles as string[] | undefined,
328
+ getTileJsonTileBaseUrl(tileJsonUrl)
329
+ )
228
330
  };
229
331
 
230
332
  const result = BasemapSourceSchema.safeParse(resolvedSource);
@@ -237,6 +339,32 @@ async function resolveSource(
237
339
  return resolvedSource;
238
340
  }
239
341
 
342
+ /**
343
+ * Resolves a source whose `url` is a PMTiles archive, `pmtiles://<archive URL>`, from the archive's
344
+ * header, as MapLibre GL JS's `pmtiles` protocol does: its tiles are read from the archive (see
345
+ * `getPMTilesSourceFields`). The archive URL resolves against the style's base URL. As with a
346
+ * TileJSON, the style's own source properties take precedence.
347
+ */
348
+ async function resolvePMTilesSource(
349
+ source: BasemapSource,
350
+ baseUrl: string | undefined,
351
+ loadOptions?: BasemapLoadOptions
352
+ ): Promise<BasemapSource> {
353
+ const archiveUrl = String(source.url).slice(PMTILES_PROTOCOL.length);
354
+ const resolvedArchiveUrl = normalizeUrl(archiveUrl, baseUrl) || archiveUrl;
355
+ const archiveFields = await getPMTilesSourceFields(
356
+ resolvedArchiveUrl,
357
+ String(source.type),
358
+ loadOptions
359
+ );
360
+ return {
361
+ ...archiveFields,
362
+ ...source,
363
+ url: `${PMTILES_PROTOCOL}${resolvedArchiveUrl}`,
364
+ tiles: source.tiles ? normalizeTiles(source.tiles, baseUrl) : archiveFields.tiles
365
+ };
366
+ }
367
+
240
368
  /**
241
369
  * Whether a source failure means the whole load was cancelled. The caller's signal decides; an
242
370
  * `AbortError` is also treated as a cancellation. A timeout raised inside a custom `fetch`
@@ -248,24 +376,62 @@ function isLoadCancelled(error: unknown, loadOptions?: BasemapLoadOptions) {
248
376
  );
249
377
  }
250
378
 
379
+ /**
380
+ * The styles that `resolveBasemapStyle` returned, with the URL that their relative `sprite` and
381
+ * `glyphs` URLs resolve against. A WeakMap, not a property: the brand adds no field to the style,
382
+ * and a copy of the style is not branded.
383
+ */
384
+ const resolvedStyleBaseUrls = new WeakMap<object, string | undefined>();
385
+
386
+ /** Brands `style` as resolved, with the URL that its relative URLs resolve against. */
387
+ export function markResolvedBasemapStyle<T extends ResolvedBasemapStyle>(
388
+ style: T,
389
+ baseUrl: string | undefined
390
+ ): T {
391
+ resolvedStyleBaseUrls.set(style, baseUrl);
392
+ return style;
393
+ }
394
+
395
+ /**
396
+ * Whether `style` is a style that `resolveBasemapStyle` or `MapStyleLoader` returned, and that
397
+ * `BasemapLayer` thus draws without resolving it again. A copy of a resolved style is not one.
398
+ */
399
+ export function isResolvedBasemapStyle(style: unknown): style is ResolvedBasemapStyle {
400
+ return typeof style === 'object' && style !== null && resolvedStyleBaseUrls.has(style);
401
+ }
402
+
403
+ /** The URL that the relative URLs of a resolved style resolve against, if it has one. */
404
+ export function getResolvedBasemapStyleBaseUrl(style: ResolvedBasemapStyle): string | undefined {
405
+ return resolvedStyleBaseUrls.get(style);
406
+ }
407
+
251
408
  /**
252
409
  * Resolves a basemap style input into a style object whose sources contain
253
- * directly consumable tile templates and source metadata.
410
+ * directly consumable tile templates and source metadata. `BasemapLayer` draws the result
411
+ * without resolving it again (see `isResolvedBasemapStyle`).
254
412
  */
255
413
  export async function resolveBasemapStyle(
256
414
  style: string | BasemapStyle,
257
415
  loadOptions?: BasemapLoadOptions
258
416
  ): Promise<ResolvedBasemapStyle> {
259
417
  const styleDefinition = BasemapStyleSchema.parse(
260
- typeof style === 'string' ? await fetchJson(style, loadOptions) : structuredClone(style)
418
+ typeof style === 'string'
419
+ ? await fetchJson(style, loadOptions, 'Style')
420
+ : structuredClone(style)
261
421
  );
262
422
  const baseUrl = typeof style === 'string' ? style : loadOptions?.baseUrl;
263
423
  const resolvedSources: Record<string, BasemapSource> = {};
424
+ const sourceCache = loadOptions?.sourceCache;
425
+ const cachedSources = new Map<string, BasemapSource>();
264
426
 
265
427
  await Promise.all(
266
428
  Object.entries(styleDefinition.sources || {}).map(async ([sourceId, source]) => {
429
+ const key = sourceCache ? getSourceKey([source, baseUrl]) : '';
267
430
  try {
268
- resolvedSources[sourceId] = (await resolveSource(source, baseUrl, loadOptions)) || {};
431
+ const resolvedSource =
432
+ sourceCache?.get(key) ?? ((await resolveSource(source, baseUrl, loadOptions)) || {});
433
+ resolvedSources[sourceId] = resolvedSource;
434
+ cachedSources.set(key, resolvedSource);
269
435
  } catch (error) {
270
436
  if (isLoadCancelled(error, loadOptions)) {
271
437
  throw loadOptions?.fetchOptions?.signal?.aborted
@@ -278,11 +444,18 @@ export async function resolveBasemapStyle(
278
444
  const inlineTiles = source?.tiles?.length
279
445
  ? normalizeTiles(source.tiles, baseUrl)
280
446
  : undefined;
281
- log.warn(
282
- `[BasemapLayer] Source "${sourceId}" could not be loaded; ${
283
- inlineTiles ? 'using its inline tiles' : 'its layers are skipped'
284
- }: ${String((error as Error)?.message ?? error)}`
285
- )();
447
+ if (loadOptions?.onError) {
448
+ const url = typeof source?.data === 'string' ? source.data : source?.url;
449
+ loadOptions.onError(
450
+ getBasemapLoadError('source', error, {sourceId, url: normalizeUrl(url, baseUrl)})
451
+ );
452
+ } else {
453
+ log.warn(
454
+ `[BasemapLayer] Source "${sourceId}" could not be loaded; ${
455
+ inlineTiles ? 'using its inline tiles' : 'its layers are skipped'
456
+ }: ${String((error as Error)?.message ?? error)}`
457
+ )();
458
+ }
286
459
  resolvedSources[sourceId] =
287
460
  source?.type === 'geojson'
288
461
  ? {...source, data: undefined}
@@ -290,12 +463,17 @@ export async function resolveBasemapStyle(
290
463
  }
291
464
  })
292
465
  );
466
+ if (sourceCache) {
467
+ sourceCache.clear();
468
+ for (const [key, source] of cachedSources) sourceCache.set(key, source);
469
+ }
293
470
 
294
- return ResolvedBasemapStyleSchema.parse({
471
+ const resolved = ResolvedBasemapStyleSchema.parse({
295
472
  ...styleDefinition,
296
473
  sources: resolvedSources,
297
474
  layers: derefLayers([...(styleDefinition.layers || [])] as Parameters<
298
475
  typeof derefLayers
299
476
  >[0]) as ResolvedBasemapStyleLayer[]
300
477
  });
478
+ return markResolvedBasemapStyle(resolved, baseUrl);
301
479
  }