forked from maptiler/tileserver-gl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve_style.js
206 lines (185 loc) · 6.44 KB
/
serve_style.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
'use strict';
import path from 'path';
import fs from 'node:fs';
import clone from 'clone';
import express from 'express';
import { validateStyleMin } from '@maplibre/maplibre-gl-style-spec';
import { fixUrl, allowedOptions } from './utils.js';
const httpTester = /^https?:\/\//i;
const allowedSpriteScales = allowedOptions(['', '@2x', '@3x']);
const allowedSpriteFormats = allowedOptions(['png', 'json']);
export const serve_style = {
init: (options, repo) => {
const app = express().disable('x-powered-by');
app.get('/:id/style.json', (req, res, next) => {
const item = repo[req.params.id];
if (!item) {
return res.sendStatus(404);
}
const styleJSON_ = clone(item.styleJSON);
for (const name of Object.keys(styleJSON_.sources)) {
const source = styleJSON_.sources[name];
source.url = fixUrl(req, source.url, item.publicUrl);
if (typeof source.data == 'string') {
source.data = fixUrl(req, source.data, item.publicUrl);
}
}
// mapbox-gl-js viewer cannot handle sprite urls with query
if (styleJSON_.sprite) {
if (Array.isArray(styleJSON_.sprite)) {
styleJSON_.sprite.forEach((spriteItem) => {
spriteItem.url = fixUrl(req, spriteItem.url, item.publicUrl);
});
} else {
styleJSON_.sprite = fixUrl(req, styleJSON_.sprite, item.publicUrl);
}
}
if (styleJSON_.glyphs) {
styleJSON_.glyphs = fixUrl(req, styleJSON_.glyphs, item.publicUrl);
}
return res.send(styleJSON_);
});
app.get(
'/:id/sprite(/:spriteID)?:scale(@[23]x)?.:format([\\w]+)',
(req, res, next) => {
const { spriteID = 'default', id } = req.params;
const scale = allowedSpriteScales(req.params.scale) || '';
const format = allowedSpriteFormats(req.params.format);
if (format) {
const item = repo[id];
const sprite = item.spritePaths.find(
(sprite) => sprite.id === spriteID,
);
if (sprite) {
const filename = `${sprite.path + scale}.${format}`;
return fs.readFile(filename, (err, data) => {
if (err) {
console.log('Sprite load error:', filename);
return res.sendStatus(404);
} else {
if (format === 'json')
res.header('Content-type', 'application/json');
if (format === 'png') res.header('Content-type', 'image/png');
return res.send(data);
}
});
} else {
return res.status(400).send('Bad Sprite ID or Scale');
}
} else {
return res.status(400).send('Bad Sprite Format');
}
},
);
return app;
},
remove: (repo, id) => {
delete repo[id];
},
add: (options, repo, params, id, publicUrl, reportTiles, reportFont) => {
const styleFile = path.resolve(options.paths.styles, params.style);
let styleFileData;
try {
styleFileData = fs.readFileSync(styleFile); // TODO: could be made async if this function was
} catch (e) {
console.log(`Error reading style file "${params.style}"`);
return false;
}
const styleJSON = JSON.parse(styleFileData);
const validationErrors = validateStyleMin(styleJSON);
if (validationErrors.length > 0) {
console.log(`The file "${params.style}" is not a valid style file:`);
for (const err of validationErrors) {
console.log(`${err.line}: ${err.message}`);
}
return false;
}
for (const name of Object.keys(styleJSON.sources)) {
const source = styleJSON.sources[name];
let url = source.url;
if (
url &&
(url.startsWith('pmtiles://') || url.startsWith('mbtiles://'))
) {
const protocol = url.split(':')[0];
let dataId = url.replace('pmtiles://', '').replace('mbtiles://', '');
if (dataId.startsWith('{') && dataId.endsWith('}')) {
dataId = dataId.slice(1, -1);
}
const mapsTo = (params.mapping || {})[dataId];
if (mapsTo) {
dataId = mapsTo;
}
const identifier = reportTiles(dataId, protocol);
if (!identifier) {
return false;
}
source.url = `local://data/${identifier}.json`;
}
let data = source.data;
if (data && typeof data == 'string' && data.startsWith('file://')) {
source.data =
'local://files' +
path.resolve(
'/',
data.replace('file://', '').replace(options.paths.files, ''),
);
}
}
for (const obj of styleJSON.layers) {
if (obj['type'] === 'symbol') {
const fonts = (obj['layout'] || {})['text-font'];
if (fonts && fonts.length) {
fonts.forEach(reportFont);
} else {
reportFont('Open Sans Regular');
reportFont('Arial Unicode MS Regular');
}
}
}
let spritePaths = [];
if (styleJSON.sprite) {
if (!Array.isArray(styleJSON.sprite)) {
if (!httpTester.test(styleJSON.sprite)) {
let spritePath = path.join(
options.paths.sprites,
styleJSON.sprite
.replace('{style}', path.basename(styleFile, '.json'))
.replace(
'{styleJsonFolder}',
path.relative(options.paths.sprites, path.dirname(styleFile)),
),
);
styleJSON.sprite = `local://styles/${id}/sprite`;
spritePaths.push({ id: 'default', path: spritePath });
}
} else {
for (let spriteItem of styleJSON.sprite) {
if (!httpTester.test(spriteItem.url)) {
let spritePath = path.join(
options.paths.sprites,
spriteItem.url
.replace('{style}', path.basename(styleFile, '.json'))
.replace(
'{styleJsonFolder}',
path.relative(options.paths.sprites, path.dirname(styleFile)),
),
);
spriteItem.url = `local://styles/${id}/sprite/` + spriteItem.id;
spritePaths.push({ id: spriteItem.id, path: spritePath });
}
}
}
}
if (styleJSON.glyphs && !httpTester.test(styleJSON.glyphs)) {
styleJSON.glyphs = 'local://fonts/{fontstack}/{range}.pbf';
}
repo[id] = {
styleJSON,
spritePaths,
publicUrl,
name: styleJSON.name,
};
return true;
},
};