@spacexr/tiles 0.0.0-stage → 0.1.0

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 (119) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +57 -2
  3. package/dist/addressing/index.d.ts +16 -0
  4. package/dist/addressing/index.js +4 -0
  5. package/dist/addressing/index.js.map +1 -0
  6. package/dist/bake/index.d.ts +91 -0
  7. package/dist/bake/index.js +3 -0
  8. package/dist/bake/index.js.map +1 -0
  9. package/dist/celestial-dataset-CUIsplKO.d.ts +99 -0
  10. package/dist/chunk-2HLQXRDD.js +246 -0
  11. package/dist/chunk-2HLQXRDD.js.map +1 -0
  12. package/dist/chunk-6YNCRDEE.js +170 -0
  13. package/dist/chunk-6YNCRDEE.js.map +1 -0
  14. package/dist/chunk-7AWV2IEK.js +79 -0
  15. package/dist/chunk-7AWV2IEK.js.map +1 -0
  16. package/dist/chunk-ESLGXWQR.js +219 -0
  17. package/dist/chunk-ESLGXWQR.js.map +1 -0
  18. package/dist/chunk-FB57CZDK.js +312 -0
  19. package/dist/chunk-FB57CZDK.js.map +1 -0
  20. package/dist/chunk-GRTG4WNA.js +44 -0
  21. package/dist/chunk-GRTG4WNA.js.map +1 -0
  22. package/dist/chunk-HVYN4AIT.js +45 -0
  23. package/dist/chunk-HVYN4AIT.js.map +1 -0
  24. package/dist/chunk-IGNRXAW3.js +77 -0
  25. package/dist/chunk-IGNRXAW3.js.map +1 -0
  26. package/dist/chunk-QGTREKHS.js +145 -0
  27. package/dist/chunk-QGTREKHS.js.map +1 -0
  28. package/dist/chunk-SPDRAY37.js +56 -0
  29. package/dist/chunk-SPDRAY37.js.map +1 -0
  30. package/dist/chunk-TA4BEVHL.js +81 -0
  31. package/dist/chunk-TA4BEVHL.js.map +1 -0
  32. package/dist/chunk-TGOB5HT5.js +149 -0
  33. package/dist/chunk-TGOB5HT5.js.map +1 -0
  34. package/dist/chunk-X6ZJ2PDY.js +104 -0
  35. package/dist/chunk-X6ZJ2PDY.js.map +1 -0
  36. package/dist/chunk-XTY4HCPY.js +22 -0
  37. package/dist/chunk-XTY4HCPY.js.map +1 -0
  38. package/dist/chunk-Y66PNDG2.js +107 -0
  39. package/dist/chunk-Y66PNDG2.js.map +1 -0
  40. package/dist/chunk-YEACOJOC.js +51 -0
  41. package/dist/chunk-YEACOJOC.js.map +1 -0
  42. package/dist/cube/index.d.ts +160 -0
  43. package/dist/cube/index.js +9 -0
  44. package/dist/cube/index.js.map +1 -0
  45. package/dist/datasets/index.d.ts +75 -0
  46. package/dist/datasets/index.js +11 -0
  47. package/dist/datasets/index.js.map +1 -0
  48. package/dist/index.d.ts +22 -0
  49. package/dist/index.js +18 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/mercator/index.d.ts +24 -0
  52. package/dist/mercator/index.js +8 -0
  53. package/dist/mercator/index.js.map +1 -0
  54. package/dist/metrics-HGbzqj6L.d.ts +45 -0
  55. package/dist/pyramid/index.d.ts +156 -0
  56. package/dist/pyramid/index.js +4 -0
  57. package/dist/pyramid/index.js.map +1 -0
  58. package/dist/raster-registration-CgBxrhDB.d.ts +19 -0
  59. package/dist/reference-surface-CsTtrNsc.d.ts +49 -0
  60. package/dist/reprojection/index.d.ts +255 -0
  61. package/dist/reprojection/index.js +6 -0
  62. package/dist/reprojection/index.js.map +1 -0
  63. package/dist/sources/index.d.ts +55 -0
  64. package/dist/sources/index.js +7 -0
  65. package/dist/sources/index.js.map +1 -0
  66. package/dist/surface/index.d.ts +15 -0
  67. package/dist/surface/index.js +4 -0
  68. package/dist/surface/index.js.map +1 -0
  69. package/dist/tile-D-jjIRRA.d.ts +53 -0
  70. package/dist/tile-address-BkfSftp6.d.ts +66 -0
  71. package/dist/tile-http-client-BHZOtGX7.d.ts +73 -0
  72. package/dist/tile-neighbors-LfvV7oiX.d.ts +48 -0
  73. package/dist/tile-surface-s9Zi6X9_.d.ts +40 -0
  74. package/dist/tile-topology-B6xHYqPb.d.ts +51 -0
  75. package/dist/web-mercator-dataset-Dmou8byO.d.ts +125 -0
  76. package/dist/web-tile-source-DrZDBIm6.d.ts +92 -0
  77. package/package.json +122 -5
  78. package/src/addressing/index.ts +8 -0
  79. package/src/addressing/metrics.ts +48 -0
  80. package/src/addressing/raster-registration.ts +22 -0
  81. package/src/addressing/tile-address.ts +130 -0
  82. package/src/addressing/tile-edge-rotation.ts +13 -0
  83. package/src/addressing/tile-neighbors.ts +73 -0
  84. package/src/addressing/tile-surface.ts +44 -0
  85. package/src/addressing/tile-topology.ts +86 -0
  86. package/src/addressing/tile.ts +73 -0
  87. package/src/bake/bake-pyramid.ts +106 -0
  88. package/src/bake/index.ts +2 -0
  89. package/src/bake/pyramid-levels.ts +63 -0
  90. package/src/cube/celestial-dataset.ts +182 -0
  91. package/src/cube/cube-face.ts +51 -0
  92. package/src/cube/cube-geometric-error.ts +30 -0
  93. package/src/cube/cube-mapping.ts +101 -0
  94. package/src/cube/cube-neighbors.ts +198 -0
  95. package/src/cube/cube-tile-surface.ts +30 -0
  96. package/src/cube/index.ts +6 -0
  97. package/src/datasets/index.ts +1 -0
  98. package/src/datasets/tile-dataset.ts +121 -0
  99. package/src/index.ts +9 -0
  100. package/src/mercator/index.ts +3 -0
  101. package/src/mercator/web-mercator-dataset.ts +215 -0
  102. package/src/mercator/web-mercator-tile-metrics.ts +119 -0
  103. package/src/mercator/web-mercator-tile-surface.ts +52 -0
  104. package/src/pyramid/index.ts +2 -0
  105. package/src/pyramid/resident-tiles.ts +81 -0
  106. package/src/pyramid/tile-pyramid.ts +285 -0
  107. package/src/reprojection/cube-resampling.ts +159 -0
  108. package/src/reprojection/index.ts +4 -0
  109. package/src/reprojection/source-projection.ts +196 -0
  110. package/src/reprojection/source-tile-matrix.ts +100 -0
  111. package/src/reprojection/wmts-capabilities.ts +112 -0
  112. package/src/sources/index.ts +4 -0
  113. package/src/sources/tile-http-client.ts +154 -0
  114. package/src/sources/tile-layer-changes.ts +88 -0
  115. package/src/sources/url-template.ts +96 -0
  116. package/src/sources/web-tile-source.ts +73 -0
  117. package/src/surface/directions.ts +27 -0
  118. package/src/surface/index.ts +2 -0
  119. package/src/surface/reference-surface.ts +88 -0
@@ -0,0 +1,100 @@
1
+ import { assertRasterRegistration, type RasterRegistration } from "../addressing";
2
+
3
+ import type { IMapPosition } from "./source-projection";
4
+
5
+ /**
6
+ * One level of the tiles of a raster source. The pixel size is explicit: it cannot always be read from a WMTS
7
+ * `ScaleDenominator`, and the matrix may be larger than the map: a A provider polar matrix of 2 x 1 tiles has its whole map
8
+ * in the first column.
9
+ */
10
+ export interface ISourceTileMatrix {
11
+ identifier: string;
12
+ /** Where the pixels lie, required: a WMTS or XYZ tile is `area`; a GeoTIFF declares it in its `GTRasterTypeGeoKey`. */
13
+ registration: RasterRegistration;
14
+ /** Map position of the outer corner of the first pixel in `area` registration, of its centre in `point` registration. */
15
+ originX: number;
16
+ originY: number;
17
+ /** Map units per pixel. Rows run toward decreasing `y`. */
18
+ pixelSize: number;
19
+ tileWidth: number;
20
+ tileHeight: number;
21
+ matrixWidth: number;
22
+ matrixHeight: number;
23
+ }
24
+
25
+ /** A pixel of a source tile. */
26
+ export interface ISourcePixel {
27
+ column: number;
28
+ row: number;
29
+ /** Pixel in the tile, 0 at its west and north. */
30
+ x: number;
31
+ y: number;
32
+ }
33
+
34
+ /** Tile of a source. */
35
+ export interface ISourceTile {
36
+ column: number;
37
+ row: number;
38
+ }
39
+
40
+ /**
41
+ * Fractional pixel of a map position, over the whole matrix: pixel `n` has its centre at `n`.
42
+ *
43
+ * @throws TypeError When the matrix does not declare its registration.
44
+ */
45
+ export function sourcePixelCoordinates(matrix: ISourceTileMatrix, position: Readonly<IMapPosition>, target: IMapPosition = { x: 0, y: 0 }): IMapPosition {
46
+ assertRasterRegistration(matrix.registration);
47
+ const offset = matrix.registration === "area" ? 0.5 : 0;
48
+ target.x = (position.x - matrix.originX) / matrix.pixelSize - offset;
49
+ target.y = (matrix.originY - position.y) / matrix.pixelSize - offset;
50
+ return target;
51
+ }
52
+
53
+ /**
54
+ * The tile and the pixel holding a pixel of the matrix.
55
+ *
56
+ * @param periodPixels - Width of the map in pixels when it wraps around the body; columns then wrap.
57
+ * @returns `undefined` beyond the matrix.
58
+ */
59
+ export function sourcePixelAt(matrix: ISourceTileMatrix, pixelX: number, pixelY: number, periodPixels?: number): ISourcePixel | undefined {
60
+ let x = pixelX;
61
+ if (periodPixels !== undefined) x = ((x % periodPixels) + periodPixels) % periodPixels;
62
+ if (x < 0 || pixelY < 0) return undefined;
63
+ const column = Math.floor(x / matrix.tileWidth);
64
+ const row = Math.floor(pixelY / matrix.tileHeight);
65
+ if (column >= matrix.matrixWidth || row >= matrix.matrixHeight) return undefined;
66
+ return { column, row, x: x - column * matrix.tileWidth, y: pixelY - row * matrix.tileHeight };
67
+ }
68
+
69
+ /** The tile matrix of a level of an XYZ Web Mercator pyramid, EPSG:3857: rows from the north, 2^level tiles per side. */
70
+ export function webMercatorTileMatrix(level: number, tileSize = 256, semiMajorAxis: number): ISourceTileMatrix {
71
+ const half = Math.PI * semiMajorAxis;
72
+ const tiles = 2 ** level;
73
+ return {
74
+ identifier: String(level),
75
+ registration: "area",
76
+ originX: -half,
77
+ originY: half,
78
+ pixelSize: (2 * half) / (tiles * tileSize),
79
+ tileWidth: tileSize,
80
+ tileHeight: tileSize,
81
+ matrixWidth: tiles,
82
+ matrixHeight: tiles,
83
+ };
84
+ }
85
+
86
+ /** The tile matrix of a level of a global geographic pyramid, such as A provider: 2 x 1 tiles at level 0, from -180 and 90. */
87
+ export function geographicTileMatrix(level: number, tileSize = 256): ISourceTileMatrix {
88
+ const tiles = 2 ** level;
89
+ return {
90
+ identifier: String(level),
91
+ registration: "area",
92
+ originX: -180,
93
+ originY: 90,
94
+ pixelSize: 180 / (tiles * tileSize),
95
+ tileWidth: tileSize,
96
+ tileHeight: tileSize,
97
+ matrixWidth: 2 * tiles,
98
+ matrixHeight: tiles,
99
+ };
100
+ }
@@ -0,0 +1,112 @@
1
+ import type { ISourceTileMatrix } from "./source-tile-matrix";
2
+
3
+ /** A layer read from a WMTS capabilities document. */
4
+ export interface IWmtsLayer {
5
+ identifier: string;
6
+ /** `SupportedCRS` as written: A provider polar layers write `EPSG::0`, so the projection must come from elsewhere. */
7
+ crs: string | undefined;
8
+ /** Media type of the tiles. An 8-bit format is for display: it holds no elevation. */
9
+ format: string | undefined;
10
+ style: string;
11
+ tileMatrixSet: string;
12
+ /** Coverage of the layer in map units, `[minX, minY, maxX, maxY]`. */
13
+ boundingBox: readonly [number, number, number, number] | undefined;
14
+ /** REST template, with `{Style}`, `{TileMatrixSet}`, `{TileMatrix}`, `{TileRow}` and `{TileCol}`. */
15
+ resourceUrl: string | undefined;
16
+ /** Levels from the coarsest. */
17
+ matrices: readonly ISourceTileMatrix[];
18
+ }
19
+
20
+ /** Metres per pixel of a WMTS scale denominator: 0.28 mm per pixel on the sheet. */
21
+ const METRES_PER_SCALE = 0.00028;
22
+
23
+ function block(source: string, tag: string): string[] {
24
+ return [...source.matchAll(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "g"))].map((match) => match[1]!);
25
+ }
26
+
27
+ function text(source: string, tag: string): string | undefined {
28
+ return new RegExp(`<${tag}(?:\\s[^>]*)?>\\s*([^<]*?)\\s*</${tag}>`).exec(source)?.[1];
29
+ }
30
+
31
+ function numbers(value: string | undefined): number[] {
32
+ return (value ?? "").trim().split(/\s+/).filter(Boolean).map(Number);
33
+ }
34
+
35
+ function required(value: string | undefined, name: string): string {
36
+ if (value === undefined || value === "") throw new RangeError(`The WMTS capabilities miss ${name}.`);
37
+ return value;
38
+ }
39
+
40
+ /**
41
+ * Reads a WMTS capabilities document, whose tiles are images, so in `area` registration, without any XML library, so that it also runs in a Cloudflare Worker, which has no
42
+ * `DOMParser`. Comments are ignored: A provider leaves old tile matrices in them.
43
+ *
44
+ * Pixel sizes come from the geometry of the matrix: the rows of a level span the origin symmetrically, so a pixel is
45
+ * `2 * originY / (MatrixHeight * TileHeight)`, in degrees or in metres. `ScaleDenominator` is not reliable: it assumes
46
+ * source-specific unit assumptions on geographic layers. Geometry-derived pixel size is preferred; the scale is used only when the origin is 0.
47
+ *
48
+ * @param xml - The document.
49
+ * @param layerIdentifier - Layer to read. Defaults to the first one.
50
+ * @throws RangeError When the document, the layer or a value it needs is missing or invalid.
51
+ */
52
+ export function parseWmtsCapabilities(xml: string, layerIdentifier?: string): IWmtsLayer {
53
+ const source = xml.replace(/<!--[\s\S]*?-->/g, "");
54
+ const layers = block(source, "Layer");
55
+ const layer = layerIdentifier === undefined ? layers[0] : layers.find((candidate) => text(candidate, "ows:Identifier") === layerIdentifier);
56
+ if (layer === undefined) throw new RangeError(`The WMTS capabilities have no layer ${layerIdentifier ?? ""}.`.trim());
57
+ const set = required(text(required(block(layer, "TileMatrixSetLink")[0], "TileMatrixSetLink"), "TileMatrixSet"), "TileMatrixSet");
58
+ const definition = block(source, "TileMatrixSet").find((candidate) => text(candidate, "ows:Identifier") === set);
59
+ if (definition === undefined) throw new RangeError(`The WMTS capabilities do not define the tile matrix set ${set}.`);
60
+
61
+ const matrices = block(definition, "TileMatrix").map((matrix): ISourceTileMatrix => {
62
+ const identifier = required(text(matrix, "ows:Identifier"), "a TileMatrix identifier");
63
+ let corner = numbers(text(matrix, "TopLeftCorner"));
64
+ // WMTS may write geographic corners latitude first.
65
+ if (corner.length === 2 && Math.abs(corner[1]!) > 90 && Math.abs(corner[1]!) <= 180 && Math.abs(corner[0]!) <= 90) corner = [corner[1]!, corner[0]!];
66
+ const [originX, originY] = corner;
67
+ const scale = Number(text(matrix, "ScaleDenominator"));
68
+ const tileWidth = Number(text(matrix, "TileWidth"));
69
+ const tileHeight = Number(text(matrix, "TileHeight"));
70
+ const matrixWidth = Number(text(matrix, "MatrixWidth"));
71
+ const matrixHeight = Number(text(matrix, "MatrixHeight"));
72
+ if (![originX, originY, tileWidth, tileHeight, matrixWidth, matrixHeight].every((value) => Number.isFinite(value)) || !(tileWidth > 0)) {
73
+ throw new RangeError(`The tile matrix ${identifier} is invalid.`);
74
+ }
75
+ const pixelSize = originY !== 0 ? (2 * Math.abs(originY!)) / (matrixHeight * tileHeight) : scale * METRES_PER_SCALE;
76
+ if (!(pixelSize > 0)) throw new RangeError(`The tile matrix ${identifier} has no pixel size.`);
77
+ return { identifier, registration: "area", originX: originX!, originY: originY!, pixelSize, tileWidth, tileHeight, matrixWidth, matrixHeight };
78
+ });
79
+ if (matrices.length === 0) throw new RangeError(`The tile matrix set ${set} has no tile matrix.`);
80
+
81
+ const box = block(layer, "ows:BoundingBox")[0];
82
+ const lower = numbers(box && text(box, "ows:LowerCorner"));
83
+ const upper = numbers(box && text(box, "ows:UpperCorner"));
84
+ const style = block(layer, "Style")[0];
85
+ return {
86
+ identifier: required(text(layer, "ows:Identifier"), "a layer identifier"),
87
+ crs: text(definition, "ows:SupportedCRS"),
88
+ format: text(layer, "Format"),
89
+ style: (style && text(style, "ows:Identifier")) ?? "default",
90
+ tileMatrixSet: set,
91
+ boundingBox: lower.length === 2 && upper.length === 2 ? [lower[0]!, lower[1]!, upper[0]!, upper[1]!] : undefined,
92
+ resourceUrl: /<ResourceURL[^>]*\stemplate="([^"]+)"/.exec(layer)?.[1],
93
+ matrices,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * URL of a tile of a WMTS layer. Empty path segments are removed: A provider templates hold `1.0.0//{Style}`.
99
+ *
100
+ * @throws RangeError When the layer has no REST template.
101
+ */
102
+ export function wmtsTileUrl(layer: IWmtsLayer, matrix: ISourceTileMatrix, row: number, column: number): string {
103
+ if (layer.resourceUrl === undefined) throw new RangeError(`The layer ${layer.identifier} has no REST template.`);
104
+ const url = layer.resourceUrl
105
+ .replaceAll("{Style}", layer.style)
106
+ .replaceAll("{style}", layer.style)
107
+ .replaceAll("{TileMatrixSet}", layer.tileMatrixSet)
108
+ .replaceAll("{TileMatrix}", matrix.identifier)
109
+ .replaceAll("{TileRow}", String(row))
110
+ .replaceAll("{TileCol}", String(column));
111
+ return url.replace(/([^:/])\/{2,}/g, "$1/");
112
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./tile-http-client";
2
+ export * from "./url-template";
3
+ export * from "./web-tile-source";
4
+ export * from "./tile-layer-changes";
@@ -0,0 +1,154 @@
1
+ /** Fetch function compatible with `globalThis.fetch`. */
2
+ export type FetchFunction = (input: string, init?: RequestInit) => Promise<Response>;
3
+
4
+ /** Options of {@link TileHttpClient}. */
5
+ export interface ITileHttpClientOptions {
6
+ /** Defaults to `globalThis.fetch`. */
7
+ fetch?: FetchFunction;
8
+ /** Headers sent with every request, for example an `Authorization` header. */
9
+ headers?: Readonly<Record<string, string>>;
10
+ /** Total number of attempts, including the first one. Defaults to 4. */
11
+ maxAttempts?: number;
12
+ /** Base delay of the exponential backoff in milliseconds. Defaults to 500. */
13
+ initialDelayMs?: number;
14
+ /** Upper bound of a single delay in milliseconds, including `Retry-After`. Defaults to 30,000. */
15
+ maxDelayMs?: number;
16
+ /** HTTP statuses retried with backoff. Defaults to 408, 425, 429, 500, 502, 503 and 504. */
17
+ retryStatuses?: readonly number[];
18
+ /** HTTP statuses meaning that the tile does not exist. Defaults to 204 and 404. */
19
+ absentStatuses?: readonly number[];
20
+ /** Random source in `[0, 1)` for the jitter. Defaults to `Math.random`. */
21
+ random?: () => number;
22
+ /** Waits for a delay, rejecting when the signal aborts. Replaceable for tests. */
23
+ sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
24
+ }
25
+
26
+ /** Outcome of a tile request. A tile known to be missing is a result, not an error. */
27
+ export type TileFetchResult = { status: "ok"; url: string; bytes: Uint8Array; contentType: string | undefined } | { status: "absent"; url: string; httpStatus: number };
28
+
29
+ /** Raised when a tile request fails permanently or exhausts its attempts. */
30
+ export class TileHttpError extends Error {
31
+ public constructor(
32
+ message: string,
33
+ public readonly url: string,
34
+ public readonly attempts: number,
35
+ public readonly httpStatus?: number,
36
+ options?: ErrorOptions
37
+ ) {
38
+ super(message, options);
39
+ this.name = "TileHttpError";
40
+ }
41
+ }
42
+
43
+ function abortReason(signal: AbortSignal): unknown {
44
+ return signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
45
+ }
46
+
47
+ function defaultSleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
48
+ return new Promise((resolve, reject) => {
49
+ if (signal?.aborted) {
50
+ reject(abortReason(signal));
51
+ return;
52
+ }
53
+ const timer = setTimeout(() => {
54
+ signal?.removeEventListener("abort", onAbort);
55
+ resolve();
56
+ }, milliseconds);
57
+ const onAbort = (): void => {
58
+ clearTimeout(timer);
59
+ reject(abortReason(signal!));
60
+ };
61
+ signal?.addEventListener("abort", onAbort, { once: true });
62
+ });
63
+ }
64
+
65
+ /** Parses a `Retry-After` header expressed in seconds or as an HTTP date. */
66
+ function retryAfterMs(response: Response): number | undefined {
67
+ const value = response.headers.get("retry-after");
68
+ if (value === null) return undefined;
69
+ const seconds = Number(value);
70
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
71
+ const date = Date.parse(value);
72
+ return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
73
+ }
74
+
75
+ /**
76
+ * HTTP client for tile requests.
77
+ *
78
+ * - Statuses listed in `absentStatuses` resolve to `{ status: "absent" }`, so sparse pyramids need no error handling.
79
+ * - Network errors and statuses listed in `retryStatuses` are retried with exponential backoff and jitter:
80
+ * `min(maxDelayMs, initialDelayMs * 2^(attempt - 1)) + random() * initialDelayMs`, or `Retry-After` when present.
81
+ * - Any other status fails immediately with a {@link TileHttpError}.
82
+ * - Aborting the signal rejects with the abort reason, including during a backoff delay.
83
+ */
84
+ export class TileHttpClient {
85
+ private readonly fetchFunction: FetchFunction;
86
+ private readonly headers: Readonly<Record<string, string>>;
87
+ private readonly maxAttempts: number;
88
+ private readonly initialDelayMs: number;
89
+ private readonly maxDelayMs: number;
90
+ private readonly retryStatuses: ReadonlySet<number>;
91
+ private readonly absentStatuses: ReadonlySet<number>;
92
+ private readonly random: () => number;
93
+ private readonly sleep: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
94
+
95
+ public constructor(options: ITileHttpClientOptions = {}) {
96
+ if (!options.fetch && typeof globalThis.fetch !== "function") throw new TypeError("No fetch implementation is available; supply options.fetch.");
97
+ // Browsers require fetch to be called on the global object, so the default is bound to it.
98
+ this.fetchFunction = options.fetch ?? globalThis.fetch.bind(globalThis);
99
+ this.headers = { ...(options.headers ?? {}) };
100
+ this.maxAttempts = options.maxAttempts ?? 4;
101
+ this.initialDelayMs = options.initialDelayMs ?? 500;
102
+ this.maxDelayMs = options.maxDelayMs ?? 30_000;
103
+ this.retryStatuses = new Set(options.retryStatuses ?? [408, 425, 429, 500, 502, 503, 504]);
104
+ this.absentStatuses = new Set(options.absentStatuses ?? [204, 404]);
105
+ this.random = options.random ?? Math.random;
106
+ this.sleep = options.sleep ?? defaultSleep;
107
+ if (!Number.isInteger(this.maxAttempts) || this.maxAttempts < 1) throw new RangeError("maxAttempts must be a positive integer.");
108
+ if (!(this.initialDelayMs >= 0) || !(this.maxDelayMs >= 0)) throw new RangeError("Backoff delays must be non-negative.");
109
+ }
110
+
111
+ /**
112
+ * Fetches one tile.
113
+ *
114
+ * @param url - Expanded tile URL.
115
+ * @param signal - Optional abort signal.
116
+ * @returns The tile bytes, or an `absent` result.
117
+ * @throws TileHttpError When the request fails permanently or exhausts its attempts.
118
+ */
119
+ public async fetchTile(url: string, signal?: AbortSignal): Promise<TileFetchResult> {
120
+ let lastError: unknown;
121
+ let lastStatus: number | undefined;
122
+ for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
123
+ if (signal?.aborted) throw abortReason(signal);
124
+ let retryDelay: number | undefined;
125
+ try {
126
+ const response = await this.fetchFunction(url, { headers: this.headers, ...(signal ? { signal } : {}) });
127
+ if (response.ok && response.status !== 204) {
128
+ const bytes = new Uint8Array(await response.arrayBuffer());
129
+ return { status: "ok", url, bytes, contentType: response.headers.get("content-type") ?? undefined };
130
+ }
131
+ if (this.absentStatuses.has(response.status)) return { status: "absent", url, httpStatus: response.status };
132
+ if (!this.retryStatuses.has(response.status)) {
133
+ throw new TileHttpError(`Tile request failed with HTTP ${response.status}: ${url}`, url, attempt, response.status);
134
+ }
135
+ lastStatus = response.status;
136
+ lastError = undefined;
137
+ retryDelay = retryAfterMs(response);
138
+ } catch (error) {
139
+ if (error instanceof TileHttpError) throw error;
140
+ if (signal?.aborted) throw abortReason(signal);
141
+ lastError = error;
142
+ lastStatus = undefined;
143
+ }
144
+ if (attempt < this.maxAttempts) {
145
+ const backoff = Math.min(this.maxDelayMs, this.initialDelayMs * 2 ** (attempt - 1)) + this.random() * this.initialDelayMs;
146
+ await this.sleep(Math.min(this.maxDelayMs, retryDelay ?? backoff), signal);
147
+ }
148
+ }
149
+ const reason = lastStatus === undefined ? "a network error" : `HTTP ${lastStatus}`;
150
+ throw new TileHttpError(`Tile request failed after ${this.maxAttempts} attempts with ${reason}: ${url}`, url, this.maxAttempts, lastStatus, {
151
+ cause: lastError,
152
+ });
153
+ }
154
+ }
@@ -0,0 +1,88 @@
1
+ import type { IGeoBounds } from "../addressing/tile";
2
+
3
+ /**
4
+ * A layer laid over the tiles of a source, such as a vector or a raster draped on imagery: identified by `id`, and
5
+ * covering `bounds`, the whole body without them. A layer whose look changes is a new object with the same `id`.
6
+ */
7
+ export interface ITileLayer {
8
+ readonly id: string;
9
+ readonly bounds?: IGeoBounds;
10
+ }
11
+
12
+ /**
13
+ * What a new set of layers changes in the tiles: nothing, the tiles of an extent, or all of them (a layer touched
14
+ * without bounds covers the whole body).
15
+ */
16
+ export type TileLayerChange = { kind: "none" } | { kind: "area"; bounds: IGeoBounds } | { kind: "all" };
17
+
18
+ /** Throws away the tiles of an extent, all of them without one, so that they load again. */
19
+ export type TileInvalidator = (bounds?: IGeoBounds) => void;
20
+
21
+ /**
22
+ * Smallest extent holding both. An extent crossing the antimeridian (`west > east`) widens the union to every
23
+ * longitude, which holds it whatever the other.
24
+ */
25
+ export function unionGeoBounds(a: IGeoBounds, b: IGeoBounds): IGeoBounds {
26
+ const crosses = a.west > a.east || b.west > b.east;
27
+ return {
28
+ west: crosses ? -180 : Math.min(a.west, b.west),
29
+ south: Math.min(a.south, b.south),
30
+ east: crosses ? 180 : Math.max(a.east, b.east),
31
+ north: Math.max(a.north, b.north),
32
+ };
33
+ }
34
+
35
+ /**
36
+ * The layers a new set touches, compared with the set drawn: a layer added or taken away, a layer replaced by another
37
+ * object of the same `id`, and, when the order of the layers kept changes, all of them, since the order is how they
38
+ * lay over each other. A replaced layer counts with its old and its new extent.
39
+ */
40
+ export function touchedTileLayers<T extends ITileLayer>(before: readonly T[], after: readonly T[]): T[] {
41
+ const previous = new Map(before.map((layer) => [layer.id, layer]));
42
+ const next = new Map(after.map((layer) => [layer.id, layer]));
43
+ const touched: T[] = [];
44
+ for (const layer of before) if (next.get(layer.id) !== layer) touched.push(layer);
45
+ for (const layer of after) if (previous.get(layer.id) !== layer) touched.push(layer);
46
+ const keptBefore = before.filter((layer) => next.has(layer.id)).map((layer) => layer.id);
47
+ const keptAfter = after.filter((layer) => previous.has(layer.id)).map((layer) => layer.id);
48
+ if (keptBefore.some((id, index) => keptAfter[index] !== id)) for (const id of keptAfter) touched.push(previous.get(id)!, next.get(id)!);
49
+ return touched;
50
+ }
51
+
52
+ /** The part of the tiles a new set of layers changes: the union of the extents of the layers it touches. */
53
+ export function tileLayerChange(before: readonly ITileLayer[], after: readonly ITileLayer[]): TileLayerChange {
54
+ let bounds: IGeoBounds | undefined;
55
+ for (const layer of touchedTileLayers(before, after)) {
56
+ if (!layer.bounds) return { kind: "all" };
57
+ bounds = bounds ? unionGeoBounds(bounds, layer.bounds) : { ...layer.bounds };
58
+ }
59
+ return bounds ? { kind: "area", bounds } : { kind: "none" };
60
+ }
61
+
62
+ /**
63
+ * What to do for a change of the layers: nothing, throw away the tiles it touches, or build the source again when its
64
+ * tiles cannot be thrown away.
65
+ */
66
+ export function planTileLayerUpdate(change: TileLayerChange, canInvalidate: boolean): "none" | "invalidate" | "rebuild" {
67
+ if (change.kind === "none") return "none";
68
+ return canInvalidate ? "invalidate" : "rebuild";
69
+ }
70
+
71
+ /**
72
+ * Applies a new set of layers to a running source: `replace` swaps the layers its tiles read, then the tiles they
73
+ * change are thrown away. False when it cannot be done in place (no `invalidate`): the source keeps its layers, and is
74
+ * to be built again by the caller.
75
+ */
76
+ export function applyTileLayers<T extends ITileLayer>(
77
+ current: readonly T[],
78
+ next: readonly T[],
79
+ invalidate: TileInvalidator | undefined,
80
+ replace: (layers: readonly T[]) => void
81
+ ): boolean {
82
+ const change = tileLayerChange(current, next);
83
+ const plan = planTileLayerUpdate(change, !!invalidate);
84
+ if (plan === "rebuild") return false;
85
+ replace(next);
86
+ if (plan === "invalidate") invalidate!(change.kind === "area" ? change.bounds : undefined);
87
+ return true;
88
+ }
@@ -0,0 +1,96 @@
1
+ import { assertValidTileAddress, tileAddressToQuadkey, toTmsY, type ITileAddress } from "../addressing";
2
+
3
+ /** Options used to expand a tile URL template. */
4
+ export interface ITileUrlTemplateOptions {
5
+ /** Values substituted for `{s}`. Required when the template contains `{s}`. */
6
+ subdomains?: readonly string[];
7
+ /**
8
+ * Application variables, for example `{format}` or `{accessToken}`.
9
+ * Values are URI-encoded. Built-in variable names cannot be redefined.
10
+ */
11
+ variables?: Readonly<Record<string, string | number>>;
12
+ }
13
+
14
+ /** Raised when a template contains an unknown variable or misses a required option. */
15
+ export class TileUrlTemplateError extends Error {
16
+ public constructor(message: string) {
17
+ super(message);
18
+ this.name = "TileUrlTemplateError";
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Variables provided for every tile.
24
+ *
25
+ * - `{z}`, `{lod}`, `{level}`: level of detail.
26
+ * - `{x}`: column, growing eastward.
27
+ * - `{y}`: XYZ row, growing southward.
28
+ * - `{-y}`: TMS row, growing northward.
29
+ * - `{quadkey}`: Bing Maps quadkey, within the face.
30
+ * - `{face}`: face of a multi-root pyramid, 0 for single-root pyramids.
31
+ * - `{s}`: subdomain, chosen as `subdomains[(x + y) % subdomains.length]` so a tile always maps to the same host.
32
+ */
33
+ export const BUILT_IN_TILE_URL_VARIABLES: readonly string[] = ["z", "lod", "level", "x", "y", "-y", "quadkey", "face", "s"];
34
+
35
+ const VARIABLE_PATTERN = /\{(-?[A-Za-z_][A-Za-z0-9_]*)\}/g;
36
+
37
+ /** Lists the variable names of a template, without braces, in order of appearance. */
38
+ export function tileUrlTemplateVariables(template: string): string[] {
39
+ return [...template.matchAll(VARIABLE_PATTERN)].map((match) => match[1]!);
40
+ }
41
+
42
+ /**
43
+ * Checks that every variable of a template can be expanded with the given options.
44
+ *
45
+ * @throws TileUrlTemplateError When a variable is unknown, when `{s}` has no subdomains, or when an
46
+ * application variable redefines a built-in variable.
47
+ */
48
+ export function validateTileUrlTemplate(template: string, options: ITileUrlTemplateOptions = {}): void {
49
+ const variables = options.variables ?? {};
50
+ for (const name of Object.keys(variables)) {
51
+ if (BUILT_IN_TILE_URL_VARIABLES.includes(name)) throw new TileUrlTemplateError(`Variable {${name}} is built in and cannot be redefined.`);
52
+ }
53
+ for (const name of tileUrlTemplateVariables(template)) {
54
+ if (name === "s") {
55
+ if (!options.subdomains || options.subdomains.length === 0) throw new TileUrlTemplateError(`Template "${template}" uses {s} but no subdomains were supplied.`);
56
+ } else if (!BUILT_IN_TILE_URL_VARIABLES.includes(name) && !Object.hasOwn(variables, name)) {
57
+ throw new TileUrlTemplateError(`Template "${template}" uses unknown variable {${name}}.`);
58
+ }
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Expands a tile URL template for an XYZ address.
64
+ *
65
+ * @throws TileUrlTemplateError See {@link validateTileUrlTemplate}.
66
+ * @throws RangeError When the address lies outside its pyramid level.
67
+ */
68
+ export function expandTileUrlTemplate(template: string, address: ITileAddress, options: ITileUrlTemplateOptions = {}): string {
69
+ validateTileUrlTemplate(template, options);
70
+ assertValidTileAddress(address);
71
+ const variables = options.variables ?? {};
72
+ return template.replace(VARIABLE_PATTERN, (_match, name: string) => {
73
+ switch (name) {
74
+ case "z":
75
+ case "lod":
76
+ case "level":
77
+ return String(address.lod);
78
+ case "x":
79
+ return String(address.x);
80
+ case "y":
81
+ return String(address.y);
82
+ case "-y":
83
+ return String(toTmsY(address.y, address.lod));
84
+ case "quadkey":
85
+ return tileAddressToQuadkey(address);
86
+ case "face":
87
+ return String(address.face ?? 0);
88
+ case "s": {
89
+ const subdomains = options.subdomains!;
90
+ return subdomains[(address.x + address.y) % subdomains.length]!;
91
+ }
92
+ default:
93
+ return encodeURIComponent(String(variables[name]));
94
+ }
95
+ });
96
+ }
@@ -0,0 +1,73 @@
1
+ import { assertRasterRegistration, type ITileAddress, type ITileMetrics, type RasterRegistration } from "../addressing";
2
+ import { TileHttpClient, type ITileHttpClientOptions, type TileFetchResult } from "./tile-http-client";
3
+ import { expandTileUrlTemplate, validateTileUrlTemplate, type ITileUrlTemplateOptions } from "./url-template";
4
+
5
+ /** Options of {@link WebTileSource}. */
6
+ export interface IWebTileSourceOptions extends ITileUrlTemplateOptions {
7
+ id?: string;
8
+ /** URL template, expanded by {@link expandTileUrlTemplate}. */
9
+ urlTemplate: string;
10
+ /** Addressing, tile size and available levels of the source. */
11
+ metrics: ITileMetrics;
12
+ /** Where the samples of the tiles lie, required: `area` for tiles published as images, whatever they hold. */
13
+ registration: RasterRegistration;
14
+ /** Shared client, or options used to create a dedicated one. */
15
+ client?: TileHttpClient | ITileHttpClientOptions;
16
+ /** Attribution text that applications must display with the tiles. */
17
+ attribution?: string;
18
+ }
19
+
20
+ /**
21
+ * Tile pyramid served over HTTP.
22
+ *
23
+ * The template is validated at construction, so a misspelled variable fails immediately instead of producing
24
+ * invalid URLs. Requests outside `[metrics.minLOD, metrics.maxLOD]` are rejected: deeper levels must be derived
25
+ * from an ancestor by the caller.
26
+ */
27
+ export class WebTileSource {
28
+ public readonly id: string;
29
+ public readonly urlTemplate: string;
30
+ public readonly metrics: ITileMetrics;
31
+ public readonly registration: RasterRegistration;
32
+ public readonly attribution: string | undefined;
33
+ public readonly client: TileHttpClient;
34
+ private readonly templateOptions: ITileUrlTemplateOptions;
35
+
36
+ /** @throws TypeError When `registration` is missing or unknown. */
37
+ public constructor(options: IWebTileSourceOptions) {
38
+ assertRasterRegistration(options.registration);
39
+ this.id = options.id ?? "web-tiles";
40
+ this.urlTemplate = options.urlTemplate;
41
+ this.metrics = options.metrics;
42
+ this.registration = options.registration;
43
+ this.attribution = options.attribution;
44
+ this.templateOptions = {
45
+ ...(options.subdomains ? { subdomains: [...options.subdomains] } : {}),
46
+ ...(options.variables ? { variables: { ...options.variables } } : {}),
47
+ };
48
+ this.client = options.client instanceof TileHttpClient ? options.client : new TileHttpClient(options.client);
49
+ validateTileUrlTemplate(this.urlTemplate, this.templateOptions);
50
+ }
51
+
52
+ /** Returns `true` when the source serves this level of detail. */
53
+ public servesLevel(lod: number): boolean {
54
+ return Number.isInteger(lod) && lod >= this.metrics.minLOD && lod <= this.metrics.maxLOD;
55
+ }
56
+
57
+ /**
58
+ * Returns the URL of a tile.
59
+ *
60
+ * @throws RangeError When the level is not served or the address lies outside its level.
61
+ */
62
+ public urlOf(address: ITileAddress): string {
63
+ if (!this.servesLevel(address.lod)) {
64
+ throw new RangeError(`Source ${this.id} serves levels ${this.metrics.minLOD} to ${this.metrics.maxLOD}, not ${address.lod}.`);
65
+ }
66
+ return expandTileUrlTemplate(this.urlTemplate, address, this.templateOptions);
67
+ }
68
+
69
+ /** Fetches a tile. See {@link TileHttpClient.fetchTile}. */
70
+ public fetchTile(address: ITileAddress, signal?: AbortSignal): Promise<TileFetchResult> {
71
+ return this.client.fetchTile(this.urlOf(address), signal);
72
+ }
73
+ }
@@ -0,0 +1,27 @@
1
+ import type { ICartesian3 } from "@spacexr/geodesy";
2
+ import type { IGeographic2 } from "../addressing/metrics";
3
+ const DEGREES = 180 / Math.PI;
4
+ /** Unit Cartesian direction from planetocentric angles in degrees. */
5
+ export function planetocentricDirection(latitudeDegrees: number, longitudeDegrees: number, target: ICartesian3 = { x: 0, y: 0, z: 0 }): ICartesian3 {
6
+ const latitude = latitudeDegrees / DEGREES;
7
+ const longitude = longitudeDegrees / DEGREES;
8
+ const cosLatitude = Math.cos(latitude);
9
+ target.x = cosLatitude * Math.cos(longitude);
10
+ target.y = cosLatitude * Math.sin(longitude);
11
+ target.z = Math.sin(latitude);
12
+ return target;
13
+ }
14
+
15
+ /**
16
+ * Planetocentric latitude and east-positive longitude of a direction, in degrees, longitudes in `(-180, 180]`. A
17
+ * planetocentric latitude is not a geodetic one on a non-spherical body.
18
+ *
19
+ * @throws RangeError When the direction is zero or not finite.
20
+ */
21
+ export function directionToPlanetocentric(direction: Readonly<ICartesian3>): IGeographic2 {
22
+ const { x, y, z } = direction;
23
+ const horizontal = Math.hypot(x, y);
24
+ if (!(horizontal + Math.abs(z) > 0) || !Number.isFinite(horizontal + z)) throw new RangeError("A direction must be finite and non-zero.");
25
+ const longitude = Math.atan2(y, x) * DEGREES;
26
+ return { latitude: Math.atan2(z, horizontal) * DEGREES, longitude: longitude === -180 ? 180 : longitude };
27
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./reference-surface";
2
+ export * from "./directions";