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