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,73 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var server_exports = {};
20
+ __export(server_exports, {
21
+ createServer: () => createServer
22
+ });
23
+ module.exports = __toCommonJS(server_exports);
24
+ var import_IttyRouter = require("itty-router/IttyRouter");
25
+ var import_StatusError = require("itty-router/StatusError");
26
+ var import_createResponse = require("itty-router/createResponse");
27
+ var import_errors = require('./utils/errors.cjs');
28
+ function resourceResponse(resource, options = {}) {
29
+ const response = new Response(resource.stream, options);
30
+ response.headers.set("Content-Type", resource.contentType);
31
+ response.headers.set("Content-Length", resource.contentLength.toString());
32
+ if (resource.contentEncoding) {
33
+ response.headers.set("Content-Encoding", resource.contentEncoding);
34
+ }
35
+ return response;
36
+ }
37
+ const jsonRaw = (0, import_createResponse.createResponse)("application/json; charset=utf-8");
38
+ const encoder = new TextEncoder();
39
+ function json(obj) {
40
+ const data = encoder.encode(JSON.stringify(obj));
41
+ return jsonRaw(data, {
42
+ headers: { "Content-Length": data.length.toString() }
43
+ });
44
+ }
45
+ function createServer({ base = "/" } = {}) {
46
+ base = base.endsWith("/") ? base : base + "/";
47
+ const router = (0, import_IttyRouter.IttyRouter)({
48
+ base
49
+ }).get("/style.json", async (request, reader) => {
50
+ const baseUrl = new URL(".", request.url);
51
+ const style = await reader.getStyle(baseUrl.href);
52
+ return json(style);
53
+ }).get(":path+", async (request, reader) => {
54
+ const path = decodeURIComponent(request.params.path);
55
+ const resource = await reader.getResource(path);
56
+ return resourceResponse(resource);
57
+ });
58
+ return {
59
+ fetch: (request, reader) => {
60
+ return router.fetch(request, reader).catch((err) => {
61
+ if ((0, import_errors.isFileNotThereError)(err)) {
62
+ throw new import_StatusError.StatusError(404, "Not Found");
63
+ } else {
64
+ throw err;
65
+ }
66
+ });
67
+ }
68
+ };
69
+ }
70
+ // Annotate the CommonJS export names for ESM import in node:
71
+ 0 && (module.exports = {
72
+ createServer
73
+ });
@@ -0,0 +1,46 @@
1
+ import { RequestLike } from 'itty-router';
2
+ import { Reader } from './reader.cjs';
3
+ import { IttyRouter } from 'itty-router/IttyRouter';
4
+ import './types-CJq90eOB.cjs';
5
+ import '@maplibre/maplibre-gl-style-spec';
6
+ import 'geojson';
7
+ import 'type-fest';
8
+ import 'events';
9
+ import '@gmaclennan/zip-reader';
10
+
11
+ /**
12
+ * Create a server for serving styled map packages (SMP) over http. The server
13
+ * is a `fetch` handler that must be provided a WHATWG `Request` and a SMP
14
+ * `Reader` instance. Use `@whatwg-node/server` to use with Node.js HTTP server.
15
+ *
16
+ * To handle errors, catch errors from `fetch` and return appropriate HTTP responses.
17
+ * You can use `itty-router/error` for this.
18
+ *
19
+ * @example
20
+ * ```js
21
+ * import { createServer } from 'node:http'
22
+ * import { error } from 'itty-router/error'
23
+ * import { createServerAdapter } from '@whatwg-node/server'
24
+ * import { createServer as createSMPServer } from 'styled-map-package-api/server'
25
+ * import { Reader } from 'styled-map-package-api/reader'
26
+ *
27
+ * const reader = new Reader('path/to/your-style.smp')
28
+ * const smpServer = createSMPServer()
29
+ * const httpServer = createServer(createServerAdapter((request) => {
30
+ * return smpServer.fetch(request, reader).catch(error)
31
+ * }))
32
+ * ```
33
+ *
34
+ * @param {object} [options]
35
+ * @param {string} [options.base='/'] Base path for the server routes
36
+ * @returns {{ fetch: (request: RequestLike, reader: ReaderLike) => Promise<Response> }} server instance
37
+ */
38
+ declare function createServer({ base }?: {
39
+ base?: string | undefined;
40
+ }): {
41
+ fetch: (request: RequestLike, reader: ReaderLike) => Promise<Response>;
42
+ };
43
+ type ReaderLike = Pick<Reader, keyof Reader>;
44
+ type RouterType = typeof IttyRouter<IRequestStrict, [ReaderLike], Response>;
45
+
46
+ export { type ReaderLike, type RouterType, createServer };
@@ -0,0 +1,46 @@
1
+ import { RequestLike } from 'itty-router';
2
+ import { Reader } from './reader.js';
3
+ import { IttyRouter } from 'itty-router/IttyRouter';
4
+ import './types-CJq90eOB.js';
5
+ import '@maplibre/maplibre-gl-style-spec';
6
+ import 'geojson';
7
+ import 'type-fest';
8
+ import 'events';
9
+ import '@gmaclennan/zip-reader';
10
+
11
+ /**
12
+ * Create a server for serving styled map packages (SMP) over http. The server
13
+ * is a `fetch` handler that must be provided a WHATWG `Request` and a SMP
14
+ * `Reader` instance. Use `@whatwg-node/server` to use with Node.js HTTP server.
15
+ *
16
+ * To handle errors, catch errors from `fetch` and return appropriate HTTP responses.
17
+ * You can use `itty-router/error` for this.
18
+ *
19
+ * @example
20
+ * ```js
21
+ * import { createServer } from 'node:http'
22
+ * import { error } from 'itty-router/error'
23
+ * import { createServerAdapter } from '@whatwg-node/server'
24
+ * import { createServer as createSMPServer } from 'styled-map-package-api/server'
25
+ * import { Reader } from 'styled-map-package-api/reader'
26
+ *
27
+ * const reader = new Reader('path/to/your-style.smp')
28
+ * const smpServer = createSMPServer()
29
+ * const httpServer = createServer(createServerAdapter((request) => {
30
+ * return smpServer.fetch(request, reader).catch(error)
31
+ * }))
32
+ * ```
33
+ *
34
+ * @param {object} [options]
35
+ * @param {string} [options.base='/'] Base path for the server routes
36
+ * @returns {{ fetch: (request: RequestLike, reader: ReaderLike) => Promise<Response> }} server instance
37
+ */
38
+ declare function createServer({ base }?: {
39
+ base?: string | undefined;
40
+ }): {
41
+ fetch: (request: RequestLike, reader: ReaderLike) => Promise<Response>;
42
+ };
43
+ type ReaderLike = Pick<Reader, keyof Reader>;
44
+ type RouterType = typeof IttyRouter<IRequestStrict, [ReaderLike], Response>;
45
+
46
+ export { type ReaderLike, type RouterType, createServer };
package/dist/server.js ADDED
@@ -0,0 +1,49 @@
1
+ import { IttyRouter } from "itty-router/IttyRouter";
2
+ import { StatusError } from "itty-router/StatusError";
3
+ import { createResponse } from "itty-router/createResponse";
4
+ import { isFileNotThereError } from "./utils/errors.js";
5
+ function resourceResponse(resource, options = {}) {
6
+ const response = new Response(resource.stream, options);
7
+ response.headers.set("Content-Type", resource.contentType);
8
+ response.headers.set("Content-Length", resource.contentLength.toString());
9
+ if (resource.contentEncoding) {
10
+ response.headers.set("Content-Encoding", resource.contentEncoding);
11
+ }
12
+ return response;
13
+ }
14
+ const jsonRaw = createResponse("application/json; charset=utf-8");
15
+ const encoder = new TextEncoder();
16
+ function json(obj) {
17
+ const data = encoder.encode(JSON.stringify(obj));
18
+ return jsonRaw(data, {
19
+ headers: { "Content-Length": data.length.toString() }
20
+ });
21
+ }
22
+ function createServer({ base = "/" } = {}) {
23
+ base = base.endsWith("/") ? base : base + "/";
24
+ const router = IttyRouter({
25
+ base
26
+ }).get("/style.json", async (request, reader) => {
27
+ const baseUrl = new URL(".", request.url);
28
+ const style = await reader.getStyle(baseUrl.href);
29
+ return json(style);
30
+ }).get(":path+", async (request, reader) => {
31
+ const path = decodeURIComponent(request.params.path);
32
+ const resource = await reader.getResource(path);
33
+ return resourceResponse(resource);
34
+ });
35
+ return {
36
+ fetch: (request, reader) => {
37
+ return router.fetch(request, reader).catch((err) => {
38
+ if (isFileNotThereError(err)) {
39
+ throw new StatusError(404, "Not Found");
40
+ } else {
41
+ throw err;
42
+ }
43
+ });
44
+ }
45
+ };
46
+ }
47
+ export {
48
+ createServer
49
+ };
@@ -0,0 +1,314 @@
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 style_downloader_exports = {};
30
+ __export(style_downloader_exports, {
31
+ StyleDownloader: () => StyleDownloader
32
+ });
33
+ module.exports = __toCommonJS(style_downloader_exports);
34
+ var import_check_geojson = require("@placemarkio/check-geojson");
35
+ var import_filter_obj = require("filter-obj");
36
+ var import_ky = __toESM(require("ky"), 1);
37
+ var import_yocto_queue = __toESM(require("yocto-queue"), 1);
38
+ var import_tile_downloader = require('./tile-downloader.cjs');
39
+ var import_fetch = require('./utils/fetch.cjs');
40
+ var import_mapbox = require('./utils/mapbox.cjs');
41
+ var import_misc = require('./utils/misc.cjs');
42
+ var import_style = require('./utils/style.cjs');
43
+ class StyleDownloader {
44
+ /** @type {null | string} */
45
+ #styleURL = null;
46
+ /** @type {null | StyleSpecification} */
47
+ #inputStyle = null;
48
+ /** @type {FetchQueue} */
49
+ #fetchQueue;
50
+ #mapboxAccessToken;
51
+ /**
52
+ * @param {string | StyleSpecification} style A url to a style JSON file or a style object
53
+ * @param {object} [opts]
54
+ * @param {number} [opts.concurrency=8]
55
+ * @param {string} [opts.mapboxAccessToken] Downloading a style from Mapbox requires an access token
56
+ */
57
+ constructor(style, { concurrency = 8, mapboxAccessToken } = {}) {
58
+ if (typeof style === "string") {
59
+ const { searchParams } = new URL(style);
60
+ this.#mapboxAccessToken = searchParams.get("access_token") || mapboxAccessToken;
61
+ this.#styleURL = (0, import_mapbox.normalizeStyleURL)(style, this.#mapboxAccessToken);
62
+ } else if ((0, import_style.validateStyle)(style)) {
63
+ this.#inputStyle = (0, import_misc.clone)(style);
64
+ } else {
65
+ throw new AggregateError(import_style.validateStyle.errors, "Invalid style");
66
+ }
67
+ this.#fetchQueue = new import_fetch.FetchQueue(concurrency);
68
+ }
69
+ /**
70
+ * Number of active downloads.
71
+ */
72
+ get active() {
73
+ return this.#fetchQueue.activeCount;
74
+ }
75
+ /**
76
+ * Download the style JSON for this style and inline the sources
77
+ *
78
+ * @returns {Promise<StyleInlinedSources>}
79
+ */
80
+ async getStyle() {
81
+ if (!this.#inputStyle && this.#styleURL) {
82
+ const downloadedStyle = await (0, import_ky.default)(this.#styleURL).json();
83
+ if (!(0, import_style.validateStyle)(downloadedStyle)) {
84
+ throw new AggregateError(
85
+ import_style.validateStyle.errors,
86
+ "Invalid style: " + this.#styleURL
87
+ );
88
+ }
89
+ this.#inputStyle = downloadedStyle;
90
+ } else if (!this.#inputStyle) {
91
+ throw new Error("Unexpected state: no style or style URL provided");
92
+ }
93
+ const inlinedSources = {};
94
+ for (const [sourceId, source] of Object.entries(this.#inputStyle.sources)) {
95
+ inlinedSources[sourceId] = await this.#getInlinedSource(source);
96
+ }
97
+ return {
98
+ ...this.#inputStyle,
99
+ sources: inlinedSources
100
+ };
101
+ }
102
+ /**
103
+ * @param {SourceSpecification} source
104
+ * @returns {Promise<InlinedSource>}
105
+ */
106
+ async #getInlinedSource(source) {
107
+ if ((0, import_style.isInlinedSource)(source)) {
108
+ return source;
109
+ }
110
+ if (source.type === "raster" || source.type === "vector" || source.type === "raster-dem") {
111
+ if (!source.url) {
112
+ throw new Error("Source is missing both url and tiles properties");
113
+ }
114
+ const sourceUrl = (0, import_mapbox.normalizeSourceURL)(source.url, this.#mapboxAccessToken);
115
+ const tilejson = await (0, import_ky.default)(sourceUrl).json();
116
+ (0, import_style.assertTileJSON)(tilejson);
117
+ return {
118
+ ...source,
119
+ ...(0, import_filter_obj.includeKeys)(tilejson, [
120
+ "bounds",
121
+ "maxzoom",
122
+ "minzoom",
123
+ "tiles",
124
+ "description",
125
+ "attribution",
126
+ "vector_layers"
127
+ ])
128
+ };
129
+ } else if (source.type === "geojson") {
130
+ if (typeof source.data !== "string") {
131
+ throw new Error("Unexpected data property for GeoJson source");
132
+ }
133
+ const geojsonUrl = (0, import_mapbox.normalizeSourceURL)(
134
+ source.data,
135
+ this.#mapboxAccessToken
136
+ );
137
+ const data = (0, import_check_geojson.check)(await (0, import_ky.default)(geojsonUrl).text());
138
+ return {
139
+ ...source,
140
+ data
141
+ };
142
+ }
143
+ return source;
144
+ }
145
+ /**
146
+ * Download the sprite PNGs and JSON files for this style. Returns an async
147
+ * generator of json and png readable streams, and the sprite id and pixel
148
+ * ratio. Downloads pixel ratios `1` and `2`.
149
+ *
150
+ * @returns {AsyncGenerator<{ json: ReadableStream<Uint8Array>, png: ReadableStream<Uint8Array>, id: string, pixelRatio: number }>}
151
+ */
152
+ async *getSprites() {
153
+ const style = await this.getStyle();
154
+ if (!style.sprite) return;
155
+ const accessToken = this.#mapboxAccessToken;
156
+ const spriteDefs = Array.isArray(style.sprite) ? style.sprite : [{ id: "default", url: style.sprite }];
157
+ for (const { id, url } of spriteDefs) {
158
+ for (const pixelRatio of [1, 2]) {
159
+ const format = pixelRatio === 1 ? "" : "@2x";
160
+ const jsonUrl = (0, import_mapbox.normalizeSpriteURL)(url, format, ".json", accessToken);
161
+ const pngUrl = (0, import_mapbox.normalizeSpriteURL)(url, format, ".png", accessToken);
162
+ const [{ body: json }, { body: png }] = await Promise.all([
163
+ this.#fetchQueue.fetch(jsonUrl),
164
+ this.#fetchQueue.fetch(pngUrl)
165
+ ]);
166
+ yield { json, png, id, pixelRatio };
167
+ }
168
+ }
169
+ }
170
+ /**
171
+ * Download all the glyphs for the fonts used in this style. When font stacks
172
+ * are used in the style.json (e.g. lists of prefered fonts like with CSS),
173
+ * then the first font in the stack is downloaded. Defaults to downloading all
174
+ * UTF character ranges, which may be overkill for some styles. TODO: add more
175
+ * options here.
176
+ *
177
+ * Returns an async generator of readable streams of glyph data and glyph info
178
+ * objects.
179
+ *
180
+ * @param {object} opts
181
+ * @param {(progress: GlyphDownloadStats) => void} [opts.onprogress]
182
+ * @returns {AsyncGenerator<[ReadableStream<Uint8Array>, GlyphInfo]>}
183
+ */
184
+ async *getGlyphs({ onprogress = import_misc.noop } = {}) {
185
+ const style = await this.getStyle();
186
+ if (!style.glyphs) return;
187
+ let completed = 0;
188
+ let stats = {
189
+ total: 0,
190
+ downloaded: 0,
191
+ totalBytes: 0
192
+ };
193
+ function onDownloadProgress({ chunkBytes }) {
194
+ stats.totalBytes += chunkBytes;
195
+ onprogress(stats);
196
+ }
197
+ function onDownloadComplete() {
198
+ stats.downloaded = ++completed;
199
+ onprogress(stats);
200
+ }
201
+ const queue = new import_yocto_queue.default();
202
+ const fontStacks = /* @__PURE__ */ new Map();
203
+ (0, import_style.mapFontStacks)(style.layers, (fontStack) => {
204
+ fontStacks.set(fontStack[0], fontStack.join(","));
205
+ return [];
206
+ });
207
+ const glyphUrl = (0, import_mapbox.normalizeGlyphsURL)(style.glyphs, this.#mapboxAccessToken);
208
+ for (const [font, fontStack] of fontStacks.entries()) {
209
+ for (let i = 0; i < Math.pow(2, 16); i += 256) {
210
+ const range = `${i}-${i + 255}`;
211
+ const url = glyphUrl.replace("{fontstack}", fontStack).replace("{range}", range);
212
+ const result = this.#fetchQueue.fetch(url, { onprogress: onDownloadProgress }).catch(import_misc.noop);
213
+ queue.enqueue([result, { font, range }]);
214
+ }
215
+ }
216
+ stats.total = queue.size;
217
+ if (onprogress) onprogress(stats);
218
+ for (const [result, glyphInfo] of queue) {
219
+ const downloadResponse = await result.catch(import_misc.noop);
220
+ if (!downloadResponse) continue;
221
+ const { body } = downloadResponse;
222
+ const gzip = (
223
+ /** @type {TransformStream<Uint8Array, Uint8Array>} */
224
+ new CompressionStream("gzip")
225
+ );
226
+ body.pipeTo(gzip.writable).then(onDownloadComplete, import_misc.noop);
227
+ const gzippedStream = gzip.readable;
228
+ yield [gzippedStream, glyphInfo];
229
+ }
230
+ }
231
+ /**
232
+ * Get all the tiles for this style within the given bounds and zoom range.
233
+ * Returns an async generator of readable streams of tile data and tile info
234
+ * objects.
235
+ *
236
+ * The returned iterator also has a `skipped` property which is an
237
+ * array of tiles which could not be downloaded, and a `stats` property which
238
+ * is an object with the total number of tiles, downloaded tiles, and total
239
+ * bytes downloaded.
240
+ *
241
+ * @param {object} opts
242
+ * @param {import('./utils/geo.js').BBox} opts.bounds
243
+ * @param {number} opts.maxzoom
244
+ * @param {(progress: TileDownloadStats) => void} [opts.onprogress]
245
+ * @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.
246
+ * @returns {AsyncGenerator<[ReadableStream<Uint8Array>, TileInfo]> & { readonly skipped: Array<TileInfo & { error?: Error }>, readonly stats: TileDownloadStats }}
247
+ */
248
+ getTiles({ bounds, maxzoom, onprogress = import_misc.noop, trackErrors = false }) {
249
+ const _this = this;
250
+ const skipped = [];
251
+ let stats = {
252
+ total: 0,
253
+ downloaded: 0,
254
+ skipped: 0,
255
+ totalBytes: 0
256
+ };
257
+ const tiles = (async function* () {
258
+ const inlinedStyle = await _this.getStyle();
259
+ for await (const [sourceId, source] of Object.entries(
260
+ inlinedStyle.sources
261
+ )) {
262
+ if (source.type !== "raster" && source.type !== "vector") {
263
+ continue;
264
+ }
265
+ const statsBaseline = { ...stats };
266
+ const sourceTiles = (0, import_tile_downloader.downloadTiles)({
267
+ tileUrls: source.tiles,
268
+ bounds,
269
+ maxzoom: Math.min(maxzoom, source.maxzoom || maxzoom),
270
+ minzoom: source.minzoom,
271
+ sourceBounds: source.bounds,
272
+ boundsBuffer: true,
273
+ scheme: source.scheme,
274
+ fetchQueue: _this.#fetchQueue,
275
+ onprogress: (sourceStats) => {
276
+ stats = addStats(statsBaseline, sourceStats);
277
+ onprogress(stats);
278
+ },
279
+ trackErrors
280
+ });
281
+ for await (const [tileDataStream, tileInfo] of sourceTiles) {
282
+ yield [tileDataStream, { ...tileInfo, sourceId }];
283
+ }
284
+ Array.prototype.push.apply(
285
+ skipped,
286
+ sourceTiles.skipped.map((tile) => ({ ...tile, sourceId }))
287
+ );
288
+ }
289
+ })();
290
+ Object.defineProperty(tiles, "skipped", {
291
+ get() {
292
+ return skipped;
293
+ }
294
+ });
295
+ Object.defineProperty(tiles, "stats", {
296
+ get() {
297
+ return stats;
298
+ }
299
+ });
300
+ return tiles;
301
+ }
302
+ }
303
+ function addStats(statsA, statsB) {
304
+ return {
305
+ total: statsA.total + statsB.total,
306
+ downloaded: statsA.downloaded + statsB.downloaded,
307
+ skipped: statsA.skipped + statsB.skipped,
308
+ totalBytes: statsA.totalBytes + statsB.totalBytes
309
+ };
310
+ }
311
+ // Annotate the CommonJS export names for ESM import in node:
312
+ 0 && (module.exports = {
313
+ StyleDownloader
314
+ });
@@ -0,0 +1,119 @@
1
+ import * as ky from 'ky';
2
+ import { BBox } from './utils/geo.cjs';
3
+ import { b as StyleInlinedSources, G as GlyphInfo, T as TileInfo } from './types-CJq90eOB.cjs';
4
+ import { TileDownloadStats } from './tile-downloader.cjs';
5
+ import { StyleSpecification } from '@maplibre/maplibre-gl-style-spec';
6
+ import 'geojson';
7
+ import 'type-fest';
8
+ import 'events';
9
+ import './utils/fetch.cjs';
10
+ import './utils/streams.cjs';
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 };