styled-map-package 4.0.1 → 5.0.0-pre.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 (85) hide show
  1. package/bin/smp-download.js +10 -6
  2. package/bin/smp-mbtiles.js +5 -7
  3. package/bin/smp-view.js +34 -26
  4. package/lib/reporters.js +92 -0
  5. package/package.json +8 -187
  6. package/LICENSE.md +0 -7
  7. package/README.md +0 -28
  8. package/dist/download.cjs +0 -101
  9. package/dist/download.d.cts +0 -65
  10. package/dist/download.d.ts +0 -65
  11. package/dist/download.js +0 -77
  12. package/dist/from-mbtiles.cjs +0 -91
  13. package/dist/from-mbtiles.d.cts +0 -17
  14. package/dist/from-mbtiles.d.ts +0 -17
  15. package/dist/from-mbtiles.js +0 -57
  16. package/dist/index.cjs +0 -49
  17. package/dist/index.d.cts +0 -27
  18. package/dist/index.d.ts +0 -27
  19. package/dist/index.js +0 -18
  20. package/dist/reader-watch.cjs +0 -135
  21. package/dist/reader-watch.d.cts +0 -24
  22. package/dist/reader-watch.d.ts +0 -24
  23. package/dist/reader-watch.js +0 -101
  24. package/dist/reader.cjs +0 -167
  25. package/dist/reader.d.cts +0 -62
  26. package/dist/reader.d.ts +0 -62
  27. package/dist/reader.js +0 -138
  28. package/dist/reporters.cjs +0 -122
  29. package/dist/reporters.d.cts +0 -10
  30. package/dist/reporters.d.ts +0 -10
  31. package/dist/reporters.js +0 -88
  32. package/dist/server.cjs +0 -78
  33. package/dist/server.d.cts +0 -48
  34. package/dist/server.d.ts +0 -48
  35. package/dist/server.js +0 -54
  36. package/dist/style-downloader.cjs +0 -312
  37. package/dist/style-downloader.d.cts +0 -120
  38. package/dist/style-downloader.d.ts +0 -120
  39. package/dist/style-downloader.js +0 -288
  40. package/dist/tile-downloader.cjs +0 -158
  41. package/dist/tile-downloader.d.cts +0 -84
  42. package/dist/tile-downloader.d.ts +0 -84
  43. package/dist/tile-downloader.js +0 -126
  44. package/dist/types-B4Xn1F9K.d.cts +0 -189
  45. package/dist/types-B4Xn1F9K.d.ts +0 -189
  46. package/dist/utils/errors.cjs +0 -41
  47. package/dist/utils/errors.d.cts +0 -18
  48. package/dist/utils/errors.d.ts +0 -18
  49. package/dist/utils/errors.js +0 -16
  50. package/dist/utils/fetch.cjs +0 -96
  51. package/dist/utils/fetch.d.cts +0 -51
  52. package/dist/utils/fetch.d.ts +0 -51
  53. package/dist/utils/fetch.js +0 -62
  54. package/dist/utils/file-formats.cjs +0 -98
  55. package/dist/utils/file-formats.d.cts +0 -35
  56. package/dist/utils/file-formats.d.ts +0 -35
  57. package/dist/utils/file-formats.js +0 -62
  58. package/dist/utils/geo.cjs +0 -84
  59. package/dist/utils/geo.d.cts +0 -46
  60. package/dist/utils/geo.d.ts +0 -46
  61. package/dist/utils/geo.js +0 -56
  62. package/dist/utils/mapbox.cjs +0 -121
  63. package/dist/utils/mapbox.d.cts +0 -43
  64. package/dist/utils/mapbox.d.ts +0 -43
  65. package/dist/utils/mapbox.js +0 -91
  66. package/dist/utils/misc.cjs +0 -39
  67. package/dist/utils/misc.d.cts +0 -22
  68. package/dist/utils/misc.d.ts +0 -22
  69. package/dist/utils/misc.js +0 -13
  70. package/dist/utils/streams.cjs +0 -130
  71. package/dist/utils/streams.d.cts +0 -73
  72. package/dist/utils/streams.d.ts +0 -73
  73. package/dist/utils/streams.js +0 -103
  74. package/dist/utils/style.cjs +0 -126
  75. package/dist/utils/style.d.cts +0 -69
  76. package/dist/utils/style.d.ts +0 -69
  77. package/dist/utils/style.js +0 -98
  78. package/dist/utils/templates.cjs +0 -114
  79. package/dist/utils/templates.d.cts +0 -78
  80. package/dist/utils/templates.d.ts +0 -78
  81. package/dist/utils/templates.js +0 -79
  82. package/dist/writer.cjs +0 -401
  83. package/dist/writer.d.cts +0 -7
  84. package/dist/writer.d.ts +0 -7
  85. package/dist/writer.js +0 -374
@@ -1,120 +0,0 @@
1
- import * as ky from 'ky';
2
- import { BBox } from './utils/geo.cjs';
3
- import * as stream from 'stream';
4
- import { b as StyleInlinedSources, G as GlyphInfo, T as TileInfo } from './types-B4Xn1F9K.cjs';
5
- import { TileDownloadStats } from './tile-downloader.cjs';
6
- import { StyleSpecification } from '@maplibre/maplibre-gl-style-spec';
7
- import 'geojson';
8
- import 'type-fest';
9
- import 'readable-stream';
10
- import 'events';
11
- import './utils/fetch.cjs';
12
- import './utils/streams.cjs';
13
-
14
- /** @import { SourceSpecification, StyleSpecification } from '@maplibre/maplibre-gl-style-spec' */
15
- /** @import { TileInfo, GlyphInfo, GlyphRange } from './writer.js' */
16
- /** @import { TileDownloadStats } from './tile-downloader.js' */
17
- /** @import { StyleInlinedSources, InlinedSource } from './types.js'*/
18
- /** @typedef { import('ky').ResponsePromise & { body: ReadableStream<Uint8Array> } } ResponsePromise */
19
- /** @import { DownloadResponse } from './utils/fetch.js' */
20
- /**
21
- * @typedef {object} GlyphDownloadStats
22
- * @property {number} total
23
- * @property {number} downloaded
24
- * @property {number} totalBytes
25
- */
26
- /**
27
- * Download a style and its resources for offline use. Please check the terms of
28
- * service of the map provider you are using before downloading any resources.
29
- */
30
- declare class StyleDownloader {
31
- /**
32
- * @param {string | StyleSpecification} style A url to a style JSON file or a style object
33
- * @param {object} [opts]
34
- * @param {number} [opts.concurrency=8]
35
- * @param {string} [opts.mapboxAccessToken] Downloading a style from Mapbox requires an access token
36
- */
37
- constructor(style: string | StyleSpecification, { concurrency, mapboxAccessToken }?: {
38
- concurrency?: number | undefined;
39
- mapboxAccessToken?: string | undefined;
40
- });
41
- /**
42
- * Number of active downloads.
43
- */
44
- get active(): number;
45
- /**
46
- * Download the style JSON for this style and inline the sources
47
- *
48
- * @returns {Promise<StyleInlinedSources>}
49
- */
50
- getStyle(): Promise<StyleInlinedSources>;
51
- /**
52
- * Download the sprite PNGs and JSON files for this style. Returns an async
53
- * generator of json and png readable streams, and the sprite id and pixel
54
- * ratio. Downloads pixel ratios `1` and `2`.
55
- *
56
- * @returns {AsyncGenerator<{ json: import('stream').Readable, png: import('stream').Readable, id: string, pixelRatio: number }>}
57
- */
58
- getSprites(): AsyncGenerator<{
59
- json: stream.Readable;
60
- png: stream.Readable;
61
- id: string;
62
- pixelRatio: number;
63
- }>;
64
- /**
65
- * Download all the glyphs for the fonts used in this style. When font stacks
66
- * are used in the style.json (e.g. lists of prefered fonts like with CSS),
67
- * then the first font in the stack is downloaded. Defaults to downloading all
68
- * UTF character ranges, which may be overkill for some styles. TODO: add more
69
- * options here.
70
- *
71
- * Returns an async generator of readable streams of glyph data and glyph info
72
- * objects.
73
- *
74
- * @param {object} opts
75
- * @param {(progress: GlyphDownloadStats) => void} [opts.onprogress]
76
- * @returns {AsyncGenerator<[import('stream').Readable, GlyphInfo]>}
77
- */
78
- getGlyphs({ onprogress }?: {
79
- onprogress?: ((progress: GlyphDownloadStats) => void) | undefined;
80
- }): AsyncGenerator<[stream.Readable, GlyphInfo]>;
81
- /**
82
- * Get all the tiles for this style within the given bounds and zoom range.
83
- * Returns an async generator of readable streams of tile data and tile info
84
- * objects.
85
- *
86
- * The returned iterator also has a `skipped` property which is an
87
- * array of tiles which could not be downloaded, and a `stats` property which
88
- * is an object with the total number of tiles, downloaded tiles, and total
89
- * bytes downloaded.
90
- *
91
- * @param {object} opts
92
- * @param {import('./utils/geo.js').BBox} opts.bounds
93
- * @param {number} opts.maxzoom
94
- * @param {(progress: TileDownloadStats) => void} [opts.onprogress]
95
- * @param {boolean} [opts.trackErrors=false] Include errors in the returned array of skipped tiles - this has memory overhead so should only be used for debugging.
96
- * @returns {AsyncGenerator<[import('stream').Readable, TileInfo]> & { readonly skipped: Array<TileInfo & { error?: Error }>, readonly stats: TileDownloadStats }}
97
- */
98
- getTiles({ bounds, maxzoom, onprogress, trackErrors }: {
99
- bounds: BBox;
100
- maxzoom: number;
101
- onprogress?: ((progress: TileDownloadStats) => void) | undefined;
102
- trackErrors?: boolean | undefined;
103
- }): AsyncGenerator<[stream.Readable, TileInfo]> & {
104
- readonly skipped: Array<TileInfo & {
105
- error?: Error;
106
- }>;
107
- readonly stats: TileDownloadStats;
108
- };
109
- #private;
110
- }
111
- type ResponsePromise = ky.ResponsePromise & {
112
- body: ReadableStream<Uint8Array>;
113
- };
114
- type GlyphDownloadStats = {
115
- total: number;
116
- downloaded: number;
117
- totalBytes: number;
118
- };
119
-
120
- export { type GlyphDownloadStats, type ResponsePromise, StyleDownloader };
@@ -1,120 +0,0 @@
1
- import * as ky from 'ky';
2
- import { BBox } from './utils/geo.js';
3
- import * as stream from 'stream';
4
- import { b as StyleInlinedSources, G as GlyphInfo, T as TileInfo } from './types-B4Xn1F9K.js';
5
- import { TileDownloadStats } from './tile-downloader.js';
6
- import { StyleSpecification } from '@maplibre/maplibre-gl-style-spec';
7
- import 'geojson';
8
- import 'type-fest';
9
- import 'readable-stream';
10
- import 'events';
11
- import './utils/fetch.js';
12
- import './utils/streams.js';
13
-
14
- /** @import { SourceSpecification, StyleSpecification } from '@maplibre/maplibre-gl-style-spec' */
15
- /** @import { TileInfo, GlyphInfo, GlyphRange } from './writer.js' */
16
- /** @import { TileDownloadStats } from './tile-downloader.js' */
17
- /** @import { StyleInlinedSources, InlinedSource } from './types.js'*/
18
- /** @typedef { import('ky').ResponsePromise & { body: ReadableStream<Uint8Array> } } ResponsePromise */
19
- /** @import { DownloadResponse } from './utils/fetch.js' */
20
- /**
21
- * @typedef {object} GlyphDownloadStats
22
- * @property {number} total
23
- * @property {number} downloaded
24
- * @property {number} totalBytes
25
- */
26
- /**
27
- * Download a style and its resources for offline use. Please check the terms of
28
- * service of the map provider you are using before downloading any resources.
29
- */
30
- declare class StyleDownloader {
31
- /**
32
- * @param {string | StyleSpecification} style A url to a style JSON file or a style object
33
- * @param {object} [opts]
34
- * @param {number} [opts.concurrency=8]
35
- * @param {string} [opts.mapboxAccessToken] Downloading a style from Mapbox requires an access token
36
- */
37
- constructor(style: string | StyleSpecification, { concurrency, mapboxAccessToken }?: {
38
- concurrency?: number | undefined;
39
- mapboxAccessToken?: string | undefined;
40
- });
41
- /**
42
- * Number of active downloads.
43
- */
44
- get active(): number;
45
- /**
46
- * Download the style JSON for this style and inline the sources
47
- *
48
- * @returns {Promise<StyleInlinedSources>}
49
- */
50
- getStyle(): Promise<StyleInlinedSources>;
51
- /**
52
- * Download the sprite PNGs and JSON files for this style. Returns an async
53
- * generator of json and png readable streams, and the sprite id and pixel
54
- * ratio. Downloads pixel ratios `1` and `2`.
55
- *
56
- * @returns {AsyncGenerator<{ json: import('stream').Readable, png: import('stream').Readable, id: string, pixelRatio: number }>}
57
- */
58
- getSprites(): AsyncGenerator<{
59
- json: stream.Readable;
60
- png: stream.Readable;
61
- id: string;
62
- pixelRatio: number;
63
- }>;
64
- /**
65
- * Download all the glyphs for the fonts used in this style. When font stacks
66
- * are used in the style.json (e.g. lists of prefered fonts like with CSS),
67
- * then the first font in the stack is downloaded. Defaults to downloading all
68
- * UTF character ranges, which may be overkill for some styles. TODO: add more
69
- * options here.
70
- *
71
- * Returns an async generator of readable streams of glyph data and glyph info
72
- * objects.
73
- *
74
- * @param {object} opts
75
- * @param {(progress: GlyphDownloadStats) => void} [opts.onprogress]
76
- * @returns {AsyncGenerator<[import('stream').Readable, GlyphInfo]>}
77
- */
78
- getGlyphs({ onprogress }?: {
79
- onprogress?: ((progress: GlyphDownloadStats) => void) | undefined;
80
- }): AsyncGenerator<[stream.Readable, GlyphInfo]>;
81
- /**
82
- * Get all the tiles for this style within the given bounds and zoom range.
83
- * Returns an async generator of readable streams of tile data and tile info
84
- * objects.
85
- *
86
- * The returned iterator also has a `skipped` property which is an
87
- * array of tiles which could not be downloaded, and a `stats` property which
88
- * is an object with the total number of tiles, downloaded tiles, and total
89
- * bytes downloaded.
90
- *
91
- * @param {object} opts
92
- * @param {import('./utils/geo.js').BBox} opts.bounds
93
- * @param {number} opts.maxzoom
94
- * @param {(progress: TileDownloadStats) => void} [opts.onprogress]
95
- * @param {boolean} [opts.trackErrors=false] Include errors in the returned array of skipped tiles - this has memory overhead so should only be used for debugging.
96
- * @returns {AsyncGenerator<[import('stream').Readable, TileInfo]> & { readonly skipped: Array<TileInfo & { error?: Error }>, readonly stats: TileDownloadStats }}
97
- */
98
- getTiles({ bounds, maxzoom, onprogress, trackErrors }: {
99
- bounds: BBox;
100
- maxzoom: number;
101
- onprogress?: ((progress: TileDownloadStats) => void) | undefined;
102
- trackErrors?: boolean | undefined;
103
- }): AsyncGenerator<[stream.Readable, TileInfo]> & {
104
- readonly skipped: Array<TileInfo & {
105
- error?: Error;
106
- }>;
107
- readonly stats: TileDownloadStats;
108
- };
109
- #private;
110
- }
111
- type ResponsePromise = ky.ResponsePromise & {
112
- body: ReadableStream<Uint8Array>;
113
- };
114
- type GlyphDownloadStats = {
115
- total: number;
116
- downloaded: number;
117
- totalBytes: number;
118
- };
119
-
120
- export { type GlyphDownloadStats, type ResponsePromise, StyleDownloader };
@@ -1,288 +0,0 @@
1
- import { check as checkGeoJson } from "@placemarkio/check-geojson";
2
- import { includeKeys } from "filter-obj";
3
- import ky from "ky";
4
- import Queue from "yocto-queue";
5
- import zlib from "zlib";
6
- import { downloadTiles } from "./tile-downloader.js";
7
- import { FetchQueue } from "./utils/fetch.js";
8
- import {
9
- normalizeGlyphsURL,
10
- normalizeSourceURL,
11
- normalizeSpriteURL,
12
- normalizeStyleURL
13
- } from "./utils/mapbox.js";
14
- import { clone, noop } from "./utils/misc.js";
15
- import {
16
- assertTileJSON,
17
- isInlinedSource,
18
- mapFontStacks,
19
- validateStyle
20
- } from "./utils/style.js";
21
- class StyleDownloader {
22
- /** @type {null | string} */
23
- #styleURL = null;
24
- /** @type {null | StyleSpecification} */
25
- #inputStyle = null;
26
- /** @type {FetchQueue} */
27
- #fetchQueue;
28
- #mapboxAccessToken;
29
- /**
30
- * @param {string | StyleSpecification} style A url to a style JSON file or a style object
31
- * @param {object} [opts]
32
- * @param {number} [opts.concurrency=8]
33
- * @param {string} [opts.mapboxAccessToken] Downloading a style from Mapbox requires an access token
34
- */
35
- constructor(style, { concurrency = 8, mapboxAccessToken } = {}) {
36
- if (typeof style === "string") {
37
- const { searchParams } = new URL(style);
38
- this.#mapboxAccessToken = searchParams.get("access_token") || mapboxAccessToken;
39
- this.#styleURL = normalizeStyleURL(style, this.#mapboxAccessToken);
40
- } else if (validateStyle(style)) {
41
- this.#inputStyle = clone(style);
42
- } else {
43
- throw new AggregateError(validateStyle.errors, "Invalid style");
44
- }
45
- this.#fetchQueue = new FetchQueue(concurrency);
46
- }
47
- /**
48
- * Number of active downloads.
49
- */
50
- get active() {
51
- return this.#fetchQueue.activeCount;
52
- }
53
- /**
54
- * Download the style JSON for this style and inline the sources
55
- *
56
- * @returns {Promise<StyleInlinedSources>}
57
- */
58
- async getStyle() {
59
- if (!this.#inputStyle && this.#styleURL) {
60
- const downloadedStyle = await ky(this.#styleURL).json();
61
- if (!validateStyle(downloadedStyle)) {
62
- throw new AggregateError(
63
- validateStyle.errors,
64
- "Invalid style: " + this.#styleURL
65
- );
66
- }
67
- this.#inputStyle = downloadedStyle;
68
- } else if (!this.#inputStyle) {
69
- throw new Error("Unexpected state: no style or style URL provided");
70
- }
71
- const inlinedSources = {};
72
- for (const [sourceId, source] of Object.entries(this.#inputStyle.sources)) {
73
- inlinedSources[sourceId] = await this.#getInlinedSource(source);
74
- }
75
- return {
76
- ...this.#inputStyle,
77
- sources: inlinedSources
78
- };
79
- }
80
- /**
81
- * @param {SourceSpecification} source
82
- * @returns {Promise<InlinedSource>}
83
- */
84
- async #getInlinedSource(source) {
85
- if (isInlinedSource(source)) {
86
- return source;
87
- }
88
- if (source.type === "raster" || source.type === "vector" || source.type === "raster-dem") {
89
- if (!source.url) {
90
- throw new Error("Source is missing both url and tiles properties");
91
- }
92
- const sourceUrl = normalizeSourceURL(source.url, this.#mapboxAccessToken);
93
- const tilejson = await ky(sourceUrl).json();
94
- assertTileJSON(tilejson);
95
- return {
96
- ...source,
97
- ...includeKeys(tilejson, [
98
- "bounds",
99
- "maxzoom",
100
- "minzoom",
101
- "tiles",
102
- "description",
103
- "attribution",
104
- "vector_layers"
105
- ])
106
- };
107
- } else if (source.type === "geojson") {
108
- if (typeof source.data !== "string") {
109
- throw new Error("Unexpected data property for GeoJson source");
110
- }
111
- const geojsonUrl = normalizeSourceURL(
112
- source.data,
113
- this.#mapboxAccessToken
114
- );
115
- const data = checkGeoJson(await ky(geojsonUrl).text());
116
- return {
117
- ...source,
118
- data
119
- };
120
- }
121
- return source;
122
- }
123
- /**
124
- * Download the sprite PNGs and JSON files for this style. Returns an async
125
- * generator of json and png readable streams, and the sprite id and pixel
126
- * ratio. Downloads pixel ratios `1` and `2`.
127
- *
128
- * @returns {AsyncGenerator<{ json: import('stream').Readable, png: import('stream').Readable, id: string, pixelRatio: number }>}
129
- */
130
- async *getSprites() {
131
- const style = await this.getStyle();
132
- if (!style.sprite) return;
133
- const accessToken = this.#mapboxAccessToken;
134
- const spriteDefs = Array.isArray(style.sprite) ? style.sprite : [{ id: "default", url: style.sprite }];
135
- for (const { id, url } of spriteDefs) {
136
- for (const pixelRatio of [1, 2]) {
137
- const format = pixelRatio === 1 ? "" : "@2x";
138
- const jsonUrl = normalizeSpriteURL(url, format, ".json", accessToken);
139
- const pngUrl = normalizeSpriteURL(url, format, ".png", accessToken);
140
- const [{ body: json }, { body: png }] = await Promise.all([
141
- this.#fetchQueue.fetch(jsonUrl),
142
- this.#fetchQueue.fetch(pngUrl)
143
- ]);
144
- yield { json, png, id, pixelRatio };
145
- }
146
- }
147
- }
148
- /**
149
- * Download all the glyphs for the fonts used in this style. When font stacks
150
- * are used in the style.json (e.g. lists of prefered fonts like with CSS),
151
- * then the first font in the stack is downloaded. Defaults to downloading all
152
- * UTF character ranges, which may be overkill for some styles. TODO: add more
153
- * options here.
154
- *
155
- * Returns an async generator of readable streams of glyph data and glyph info
156
- * objects.
157
- *
158
- * @param {object} opts
159
- * @param {(progress: GlyphDownloadStats) => void} [opts.onprogress]
160
- * @returns {AsyncGenerator<[import('stream').Readable, GlyphInfo]>}
161
- */
162
- async *getGlyphs({ onprogress = noop } = {}) {
163
- const style = await this.getStyle();
164
- if (!style.glyphs) return;
165
- let completed = 0;
166
- let stats = {
167
- total: 0,
168
- downloaded: 0,
169
- totalBytes: 0
170
- };
171
- function onDownloadProgress({ chunkBytes }) {
172
- stats.totalBytes += chunkBytes;
173
- onprogress(stats);
174
- }
175
- function onDownloadComplete() {
176
- stats.downloaded = ++completed;
177
- onprogress(stats);
178
- }
179
- const queue = new Queue();
180
- const fontStacks = /* @__PURE__ */ new Map();
181
- mapFontStacks(style.layers, (fontStack) => {
182
- fontStacks.set(fontStack[0], fontStack.join(","));
183
- return [];
184
- });
185
- const glyphUrl = normalizeGlyphsURL(style.glyphs, this.#mapboxAccessToken);
186
- for (const [font, fontStack] of fontStacks.entries()) {
187
- for (let i = 0; i < Math.pow(2, 16); i += 256) {
188
- const range = `${i}-${i + 255}`;
189
- const url = glyphUrl.replace("{fontstack}", fontStack).replace("{range}", range);
190
- const result = this.#fetchQueue.fetch(url, { onprogress: onDownloadProgress }).catch(noop);
191
- queue.enqueue([result, { font, range }]);
192
- }
193
- }
194
- stats.total = queue.size;
195
- if (onprogress) onprogress(stats);
196
- for (const [result, glyphInfo] of queue) {
197
- const downloadResponse = await result.catch(noop);
198
- if (!downloadResponse) continue;
199
- const { body } = downloadResponse;
200
- const gzipper = zlib.createGzip();
201
- body.on("error", (err) => gzipper.destroy(err));
202
- body.on("end", onDownloadComplete);
203
- yield [body.pipe(gzipper), glyphInfo];
204
- }
205
- }
206
- /**
207
- * Get all the tiles for this style within the given bounds and zoom range.
208
- * Returns an async generator of readable streams of tile data and tile info
209
- * objects.
210
- *
211
- * The returned iterator also has a `skipped` property which is an
212
- * array of tiles which could not be downloaded, and a `stats` property which
213
- * is an object with the total number of tiles, downloaded tiles, and total
214
- * bytes downloaded.
215
- *
216
- * @param {object} opts
217
- * @param {import('./utils/geo.js').BBox} opts.bounds
218
- * @param {number} opts.maxzoom
219
- * @param {(progress: TileDownloadStats) => void} [opts.onprogress]
220
- * @param {boolean} [opts.trackErrors=false] Include errors in the returned array of skipped tiles - this has memory overhead so should only be used for debugging.
221
- * @returns {AsyncGenerator<[import('stream').Readable, TileInfo]> & { readonly skipped: Array<TileInfo & { error?: Error }>, readonly stats: TileDownloadStats }}
222
- */
223
- getTiles({ bounds, maxzoom, onprogress = noop, trackErrors = false }) {
224
- const _this = this;
225
- const skipped = [];
226
- let stats = {
227
- total: 0,
228
- downloaded: 0,
229
- skipped: 0,
230
- totalBytes: 0
231
- };
232
- const tiles = async function* () {
233
- const inlinedStyle = await _this.getStyle();
234
- for await (const [sourceId, source] of Object.entries(
235
- inlinedStyle.sources
236
- )) {
237
- if (source.type !== "raster" && source.type !== "vector") {
238
- continue;
239
- }
240
- const statsBaseline = { ...stats };
241
- const sourceTiles = downloadTiles({
242
- tileUrls: source.tiles,
243
- bounds,
244
- maxzoom: Math.min(maxzoom, source.maxzoom || maxzoom),
245
- minzoom: source.minzoom,
246
- sourceBounds: source.bounds,
247
- boundsBuffer: true,
248
- scheme: source.scheme,
249
- fetchQueue: _this.#fetchQueue,
250
- onprogress: (sourceStats) => {
251
- stats = addStats(statsBaseline, sourceStats);
252
- onprogress(stats);
253
- },
254
- trackErrors
255
- });
256
- for await (const [tileDataStream, tileInfo] of sourceTiles) {
257
- yield [tileDataStream, { ...tileInfo, sourceId }];
258
- }
259
- Array.prototype.push.apply(
260
- skipped,
261
- sourceTiles.skipped.map((tile) => ({ ...tile, sourceId }))
262
- );
263
- }
264
- }();
265
- Object.defineProperty(tiles, "skipped", {
266
- get() {
267
- return skipped;
268
- }
269
- });
270
- Object.defineProperty(tiles, "stats", {
271
- get() {
272
- return stats;
273
- }
274
- });
275
- return tiles;
276
- }
277
- }
278
- function addStats(statsA, statsB) {
279
- return {
280
- total: statsA.total + statsB.total,
281
- downloaded: statsA.downloaded + statsB.downloaded,
282
- skipped: statsA.skipped + statsB.skipped,
283
- totalBytes: statsA.totalBytes + statsB.totalBytes
284
- };
285
- }
286
- export {
287
- StyleDownloader
288
- };
@@ -1,158 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var tile_downloader_exports = {};
30
- __export(tile_downloader_exports, {
31
- downloadTiles: () => downloadTiles,
32
- tileIterator: () => tileIterator
33
- });
34
- module.exports = __toCommonJS(tile_downloader_exports);
35
- var import_sphericalmercator = __toESM(require("@mapbox/sphericalmercator"), 1);
36
- var import_yocto_queue = __toESM(require("yocto-queue"), 1);
37
- var import_zlib = __toESM(require("zlib"), 1);
38
- var import_fetch = require('./utils/fetch.cjs');
39
- var import_file_formats = require('./utils/file-formats.cjs');
40
- var import_geo = require('./utils/geo.cjs');
41
- var import_misc = require('./utils/misc.cjs');
42
- function downloadTiles({
43
- tileUrls,
44
- bounds,
45
- maxzoom,
46
- onprogress = import_misc.noop,
47
- trackErrors = false,
48
- sourceBounds = import_geo.MAX_BOUNDS,
49
- boundsBuffer = false,
50
- minzoom = 0,
51
- concurrency = 8,
52
- fetchQueue = new import_fetch.FetchQueue(concurrency),
53
- scheme = "xyz"
54
- }) {
55
- const skipped = [];
56
- let completed = 0;
57
- let stats = {
58
- total: 0,
59
- downloaded: 0,
60
- skipped: 0,
61
- totalBytes: 0
62
- };
63
- function onDownloadProgress({ chunkBytes }) {
64
- stats.totalBytes += chunkBytes;
65
- onprogress(stats);
66
- }
67
- function onDownloadError(error, tileInfo) {
68
- if (trackErrors) {
69
- skipped.push({ ...tileInfo, error });
70
- } else {
71
- skipped.push(tileInfo);
72
- }
73
- onprogress(stats);
74
- }
75
- function onDownloadComplete() {
76
- stats.downloaded = ++completed - skipped.length;
77
- stats.skipped = skipped.length;
78
- onprogress(stats);
79
- }
80
- const tiles = async function* () {
81
- const queue = new import_yocto_queue.default();
82
- const tiles2 = tileIterator({
83
- bounds,
84
- minzoom,
85
- maxzoom,
86
- sourceBounds,
87
- boundsBuffer
88
- });
89
- for (const { x, y, z } of tiles2) {
90
- const tileURL = (0, import_geo.getTileUrl)(tileUrls, { x, y, z, scheme });
91
- const tileInfo = { z, x, y };
92
- const result = fetchQueue.fetch(tileURL, { onprogress: onDownloadProgress }).catch((err) => onDownloadError(err, tileInfo));
93
- queue.enqueue([result, tileInfo]);
94
- }
95
- stats.total = queue.size;
96
- if (onprogress) onprogress(stats);
97
- for (const [result, tileInfo] of queue) {
98
- const downloadResponse = await result.catch(import_misc.noop);
99
- if (!downloadResponse) continue;
100
- let { body, mimeType } = downloadResponse;
101
- body.on("end", onDownloadComplete);
102
- body.on("error", (err) => onDownloadError(err, tileInfo));
103
- let format;
104
- if (mimeType) {
105
- format = (0, import_file_formats.getFormatFromMimeType)(mimeType);
106
- } else {
107
- ;
108
- [format, body] = await (0, import_file_formats.getTileFormatFromStream)(body);
109
- }
110
- let stream = body;
111
- if (format === "mvt") {
112
- const gzipStream = import_zlib.default.createGzip();
113
- stream = body.pipe(gzipStream);
114
- stream.on("error", (err) => gzipStream.destroy(err));
115
- }
116
- yield [stream, { ...tileInfo, format }];
117
- }
118
- }();
119
- Object.defineProperty(tiles, "skipped", {
120
- get() {
121
- return skipped;
122
- }
123
- });
124
- Object.defineProperty(tiles, "stats", {
125
- get() {
126
- return stats;
127
- }
128
- });
129
- return tiles;
130
- }
131
- function* tileIterator({
132
- bounds = [...import_geo.MAX_BOUNDS],
133
- minzoom = 0,
134
- maxzoom,
135
- sourceBounds,
136
- boundsBuffer = false
137
- }) {
138
- const sm = new import_sphericalmercator.default({ size: 256 });
139
- for (let z = minzoom; z <= maxzoom; z++) {
140
- let { minX, minY, maxX, maxY } = sm.xyz([...bounds], z);
141
- let sourceXYBounds = sourceBounds ? sm.xyz([...sourceBounds], z) : { minX, minY, maxX, maxY };
142
- const buffer = boundsBuffer ? 1 : 0;
143
- minX = Math.max(0, minX - buffer, sourceXYBounds.minX);
144
- minY = Math.max(0, minY - buffer, sourceXYBounds.minY);
145
- maxX = Math.min(Math.pow(2, z) - 1, maxX + buffer, sourceXYBounds.maxX);
146
- maxY = Math.min(Math.pow(2, z) - 1, maxY + buffer, sourceXYBounds.maxY);
147
- for (let x = minX; x <= maxX; x++) {
148
- for (let y = minY; y <= maxY; y++) {
149
- yield { x, y, z };
150
- }
151
- }
152
- }
153
- }
154
- // Annotate the CommonJS export names for ESM import in node:
155
- 0 && (module.exports = {
156
- downloadTiles,
157
- tileIterator
158
- });