styled-map-package-api 5.0.0-pre.3 → 5.0.0-pre.4

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 (94) hide show
  1. package/README.md +94 -0
  2. package/dist/download.d.ts +11 -21
  3. package/dist/fallbacks.d.ts +32 -0
  4. package/dist/from-mbtiles.d.ts +1 -3
  5. package/dist/index.d.ts +11 -24
  6. package/dist/reader.d.ts +28 -12
  7. package/dist/server.d.ts +23 -14
  8. package/dist/style-downloader.d.ts +13 -19
  9. package/dist/tile-downloader.d.ts +13 -23
  10. package/dist/types.d.ts +61 -0
  11. package/dist/utils/errors.d.ts +2 -4
  12. package/dist/utils/fetch.d.ts +3 -8
  13. package/dist/utils/file-formats.d.ts +3 -10
  14. package/dist/utils/geo.d.ts +17 -9
  15. package/dist/utils/mapbox.d.ts +8 -10
  16. package/dist/utils/misc.d.ts +3 -5
  17. package/dist/utils/streams.d.ts +6 -10
  18. package/dist/utils/style.d.ts +27 -16
  19. package/dist/utils/templates.d.ts +30 -25
  20. package/dist/validator.d.ts +66 -0
  21. package/dist/writer.d.ts +157 -4
  22. package/lib/download.js +125 -0
  23. package/lib/fallbacks.js +157 -0
  24. package/lib/from-mbtiles.js +131 -0
  25. package/lib/index.js +12 -0
  26. package/lib/reader.js +360 -0
  27. package/lib/server.js +222 -0
  28. package/lib/style-downloader.js +369 -0
  29. package/lib/tile-downloader.js +189 -0
  30. package/lib/types.ts +99 -0
  31. package/lib/utils/errors.js +24 -0
  32. package/lib/utils/fetch.js +104 -0
  33. package/lib/utils/file-formats.js +92 -0
  34. package/lib/utils/geo.js +97 -0
  35. package/lib/utils/mapbox.js +155 -0
  36. package/{dist/utils/misc.d.cts → lib/utils/misc.js} +9 -5
  37. package/lib/utils/streams.js +101 -0
  38. package/lib/utils/style.js +206 -0
  39. package/lib/utils/templates.js +165 -0
  40. package/lib/validator.js +789 -0
  41. package/lib/writer.js +652 -0
  42. package/package.json +30 -78
  43. package/dist/download.cjs +0 -100
  44. package/dist/download.d.cts +0 -63
  45. package/dist/download.js +0 -76
  46. package/dist/from-mbtiles.cjs +0 -127
  47. package/dist/from-mbtiles.d.cts +0 -14
  48. package/dist/from-mbtiles.js +0 -103
  49. package/dist/index.cjs +0 -46
  50. package/dist/index.d.cts +0 -24
  51. package/dist/index.js +0 -16
  52. package/dist/reader.cjs +0 -287
  53. package/dist/reader.d.cts +0 -67
  54. package/dist/reader.js +0 -259
  55. package/dist/server.cjs +0 -73
  56. package/dist/server.d.cts +0 -45
  57. package/dist/server.js +0 -49
  58. package/dist/style-downloader.cjs +0 -314
  59. package/dist/style-downloader.d.cts +0 -118
  60. package/dist/style-downloader.js +0 -290
  61. package/dist/tile-downloader.cjs +0 -156
  62. package/dist/tile-downloader.d.cts +0 -82
  63. package/dist/tile-downloader.js +0 -124
  64. package/dist/types-Bhn0-Ldk.d.cts +0 -201
  65. package/dist/types-Bhn0-Ldk.d.ts +0 -201
  66. package/dist/utils/errors.cjs +0 -41
  67. package/dist/utils/errors.d.cts +0 -18
  68. package/dist/utils/errors.js +0 -16
  69. package/dist/utils/fetch.cjs +0 -97
  70. package/dist/utils/fetch.d.cts +0 -50
  71. package/dist/utils/fetch.js +0 -63
  72. package/dist/utils/file-formats.cjs +0 -96
  73. package/dist/utils/file-formats.d.cts +0 -32
  74. package/dist/utils/file-formats.js +0 -70
  75. package/dist/utils/geo.cjs +0 -84
  76. package/dist/utils/geo.d.cts +0 -46
  77. package/dist/utils/geo.js +0 -56
  78. package/dist/utils/mapbox.cjs +0 -121
  79. package/dist/utils/mapbox.d.cts +0 -43
  80. package/dist/utils/mapbox.js +0 -91
  81. package/dist/utils/misc.cjs +0 -39
  82. package/dist/utils/misc.js +0 -13
  83. package/dist/utils/streams.cjs +0 -99
  84. package/dist/utils/streams.d.cts +0 -49
  85. package/dist/utils/streams.js +0 -73
  86. package/dist/utils/style.cjs +0 -126
  87. package/dist/utils/style.d.cts +0 -66
  88. package/dist/utils/style.js +0 -98
  89. package/dist/utils/templates.cjs +0 -124
  90. package/dist/utils/templates.d.cts +0 -79
  91. package/dist/utils/templates.js +0 -85
  92. package/dist/writer.cjs +0 -539
  93. package/dist/writer.d.cts +0 -4
  94. package/dist/writer.js +0 -516
package/dist/server.cjs DELETED
@@ -1,73 +0,0 @@
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
- });
package/dist/server.d.cts DELETED
@@ -1,45 +0,0 @@
1
- import { RequestLike } from 'itty-router';
2
- import { Reader } from './reader.cjs';
3
- import { IttyRouter } from 'itty-router/IttyRouter';
4
- import './types-Bhn0-Ldk.cjs';
5
- import '@maplibre/maplibre-gl-style-spec';
6
- import 'geojson';
7
- import 'type-fest';
8
- import '@gmaclennan/zip-reader';
9
-
10
- /**
11
- * Create a server for serving styled map packages (SMP) over http. The server
12
- * is a `fetch` handler that must be provided a WHATWG `Request` and a SMP
13
- * `Reader` instance. Use `@whatwg-node/server` to use with Node.js HTTP server.
14
- *
15
- * To handle errors, catch errors from `fetch` and return appropriate HTTP responses.
16
- * You can use `itty-router/error` for this.
17
- *
18
- * @example
19
- * ```js
20
- * import { createServer } from 'node:http'
21
- * import { error } from 'itty-router/error'
22
- * import { createServerAdapter } from '@whatwg-node/server'
23
- * import { createServer as createSMPServer } from 'styled-map-package-api/server'
24
- * import { Reader } from 'styled-map-package-api/reader'
25
- *
26
- * const reader = new Reader('path/to/your-style.smp')
27
- * const smpServer = createSMPServer()
28
- * const httpServer = createServer(createServerAdapter((request) => {
29
- * return smpServer.fetch(request, reader).catch(error)
30
- * }))
31
- * ```
32
- *
33
- * @param {object} [options]
34
- * @param {string} [options.base='/'] Base path for the server routes
35
- * @returns {{ fetch: (request: RequestLike, reader: ReaderLike) => Promise<Response> }} server instance
36
- */
37
- declare function createServer({ base }?: {
38
- base?: string | undefined;
39
- }): {
40
- fetch: (request: RequestLike, reader: ReaderLike) => Promise<Response>;
41
- };
42
- type ReaderLike = Pick<Reader, keyof Reader>;
43
- type RouterType = typeof IttyRouter<IRequestStrict, [ReaderLike], Response>;
44
-
45
- export { type ReaderLike, type RouterType, createServer };
package/dist/server.js DELETED
@@ -1,49 +0,0 @@
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
- };
@@ -1,314 +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 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
- });
@@ -1,118 +0,0 @@
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-Bhn0-Ldk.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 './utils/fetch.cjs';
9
- import './utils/streams.cjs';
10
- import 'stream/web';
11
-
12
- /** @import { SourceSpecification, StyleSpecification } from '@maplibre/maplibre-gl-style-spec' */
13
- /** @import { TileInfo, GlyphInfo, GlyphRange } from './writer.js' */
14
- /** @import { TileDownloadStats } from './tile-downloader.js' */
15
- /** @import { StyleInlinedSources, InlinedSource } from './types.js'*/
16
- /** @typedef { import('ky').ResponsePromise & { body: ReadableStream<Uint8Array> } } ResponsePromise */
17
- /** @import { DownloadResponse } from './utils/fetch.js' */
18
- /**
19
- * @typedef {object} GlyphDownloadStats
20
- * @property {number} total
21
- * @property {number} downloaded
22
- * @property {number} totalBytes
23
- */
24
- /**
25
- * Download a style and its resources for offline use. Please check the terms of
26
- * service of the map provider you are using before downloading any resources.
27
- */
28
- declare class StyleDownloader {
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: string | StyleSpecification, { concurrency, mapboxAccessToken }?: {
36
- concurrency?: number | undefined;
37
- mapboxAccessToken?: string | undefined;
38
- });
39
- /**
40
- * Number of active downloads.
41
- */
42
- get active(): number;
43
- /**
44
- * Download the style JSON for this style and inline the sources
45
- *
46
- * @returns {Promise<StyleInlinedSources>}
47
- */
48
- getStyle(): Promise<StyleInlinedSources>;
49
- /**
50
- * Download the sprite PNGs and JSON files for this style. Returns an async
51
- * generator of json and png readable streams, and the sprite id and pixel
52
- * ratio. Downloads pixel ratios `1` and `2`.
53
- *
54
- * @returns {AsyncGenerator<{ json: ReadableStream<Uint8Array>, png: ReadableStream<Uint8Array>, id: string, pixelRatio: number }>}
55
- */
56
- getSprites(): AsyncGenerator<{
57
- json: ReadableStream<Uint8Array>;
58
- png: ReadableStream<Uint8Array>;
59
- id: string;
60
- pixelRatio: number;
61
- }>;
62
- /**
63
- * Download all the glyphs for the fonts used in this style. When font stacks
64
- * are used in the style.json (e.g. lists of prefered fonts like with CSS),
65
- * then the first font in the stack is downloaded. Defaults to downloading all
66
- * UTF character ranges, which may be overkill for some styles. TODO: add more
67
- * options here.
68
- *
69
- * Returns an async generator of readable streams of glyph data and glyph info
70
- * objects.
71
- *
72
- * @param {object} opts
73
- * @param {(progress: GlyphDownloadStats) => void} [opts.onprogress]
74
- * @returns {AsyncGenerator<[ReadableStream<Uint8Array>, GlyphInfo]>}
75
- */
76
- getGlyphs({ onprogress }?: {
77
- onprogress?: ((progress: GlyphDownloadStats) => void) | undefined;
78
- }): AsyncGenerator<[ReadableStream<Uint8Array>, GlyphInfo]>;
79
- /**
80
- * Get all the tiles for this style within the given bounds and zoom range.
81
- * Returns an async generator of readable streams of tile data and tile info
82
- * objects.
83
- *
84
- * The returned iterator also has a `skipped` property which is an
85
- * array of tiles which could not be downloaded, and a `stats` property which
86
- * is an object with the total number of tiles, downloaded tiles, and total
87
- * bytes downloaded.
88
- *
89
- * @param {object} opts
90
- * @param {import('./utils/geo.js').BBox} opts.bounds
91
- * @param {number} opts.maxzoom
92
- * @param {(progress: TileDownloadStats) => void} [opts.onprogress]
93
- * @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.
94
- * @returns {AsyncGenerator<[ReadableStream<Uint8Array>, TileInfo]> & { readonly skipped: Array<TileInfo & { error?: Error }>, readonly stats: TileDownloadStats }}
95
- */
96
- getTiles({ bounds, maxzoom, onprogress, trackErrors }: {
97
- bounds: BBox;
98
- maxzoom: number;
99
- onprogress?: ((progress: TileDownloadStats) => void) | undefined;
100
- trackErrors?: boolean | undefined;
101
- }): AsyncGenerator<[ReadableStream<Uint8Array>, TileInfo]> & {
102
- readonly skipped: Array<TileInfo & {
103
- error?: Error;
104
- }>;
105
- readonly stats: TileDownloadStats;
106
- };
107
- #private;
108
- }
109
- type ResponsePromise = ky.ResponsePromise & {
110
- body: ReadableStream<Uint8Array>;
111
- };
112
- type GlyphDownloadStats = {
113
- total: number;
114
- downloaded: number;
115
- totalBytes: number;
116
- };
117
-
118
- export { type GlyphDownloadStats, type ResponsePromise, StyleDownloader };