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