-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
283 lines (273 loc) · 10.9 KB
/
Copy pathserver.js
File metadata and controls
283 lines (273 loc) · 10.9 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import http from 'node:http';
import { readFileSync, writeFileSync, renameSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { extractLayers } from './extract.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PDF_PATH = path.join(__dirname, '2025', 'input.pdf');
const PORT = Number(process.env.PORT) || 3000;
const TARGET_LAYERS = [
'Listed Name Callouts',
'Camp Names',
'Camp Outlines',
'Base Map Things',
];
console.log(`Extracting layers from ${PDF_PATH}...`);
const t0 = Date.now();
const layerData = await extractLayers(PDF_PATH, TARGET_LAYERS);
console.log(
`Extracted ${layerData.paths.length} subpaths from ${TARGET_LAYERS.length} layers ` +
`(page ${layerData.width}x${layerData.height} pts) in ${Date.now() - t0} ms`
);
const layerJson = JSON.stringify(layerData);
const appJs = readFileSync(path.join(__dirname, 'public', 'app.js'), 'utf8');
const CAMPS_PATH = path.join(__dirname, '2025', 'camps.json');
const GEOCODED_PATH = path.join(__dirname, '2025', 'camps-geocoded.json');
const GEOCODED_WITH_BORDERS_PATH = path.join(__dirname, '2025', 'camps-geocoded-with-borders.json');
let campsJson = '[]';
try {
const camps = JSON.parse(readFileSync(CAMPS_PATH, 'utf8'));
// Send only the fields the client needs (name for matching; location_string /
// dimensions / exact_location for the hover tooltip). Other fields like
// contact_email / description stay server-side.
const trimmed = [];
for (const c of camps) {
if (!c || typeof c.name !== 'string' || !c.name.length) continue;
const loc = c.location || {};
trimmed.push({
name: c.name,
location_string: typeof c.location_string === 'string' ? c.location_string : '',
dimensions: typeof loc.dimensions === 'string' ? loc.dimensions : '',
exact_location: typeof loc.exact_location === 'string' ? loc.exact_location : '',
});
}
campsJson = JSON.stringify(trimmed);
console.log(`Loaded ${trimmed.length} canonical camp entries from camps.json`);
} catch (err) {
console.warn(`Could not load camps.json (${err.message}); name matching disabled`);
}
// Same normalization the client uses so coord-map keys line up.
const normalizeCampName = s => String(s)
.toLowerCase()
.replace(/&/g, 'and')
.replace(/[^a-z0-9]/g, '');
const CORRECTIONS_PATH = path.join(__dirname, '2025', 'corrections.json');
let correctionsData = { version: 1, corrections: [] };
try {
const parsed = JSON.parse(readFileSync(CORRECTIONS_PATH, 'utf8'));
if (parsed && Array.isArray(parsed.corrections)) {
correctionsData = { version: parsed.version || 1, corrections: parsed.corrections };
console.log(`Loaded ${correctionsData.corrections.length} corrections from corrections.json`);
}
} catch (err) {
if (err.code !== 'ENOENT') console.warn(`Could not load corrections.json (${err.message}); starting empty`);
}
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>BRC Map Tools</title>
<style>
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; background: #fff; }
canvas { display: block; }
#status-bar {
position: absolute;
bottom: 16px;
left: 16px;
background: rgba(255,255,255,0.92);
border: 1px solid rgba(0,0,0,0.2);
border-radius: 4px;
padding: 8px 12px;
font: 12px sans-serif;
display: none;
user-select: none;
}
#status-bar > * { vertical-align: middle; }
#status-bar button {
margin-left: 6px;
font: inherit;
padding: 2px 8px;
cursor: pointer;
}
#status-bar button:disabled { cursor: default; opacity: 0.5; }
#status-bar input {
margin-left: 4px;
margin-right: 4px;
font: inherit;
padding: 2px 6px;
}
#compass {
position: absolute;
top: 16px;
right: 16px;
width: 48px;
height: 48px;
background: rgba(255,255,255,0.92);
border: 1px solid rgba(0,0,0,0.2);
border-radius: 50%;
cursor: pointer;
user-select: none;
box-shadow: 0 1px 3px rgba(0,0,0,0.15);
display: flex;
align-items: center;
justify-content: center;
}
#compass svg {
width: 100%;
height: 100%;
transition: transform 250ms ease-out;
}
</style>
</head>
<body>
<canvas id="map"></canvas>
<div id="status-bar"></div>
<div id="compass" title="Toggle map orientation (12:00 up / North up)">
<svg viewBox="-24 -24 48 48" xmlns="http://www.w3.org/2000/svg">
<circle cx="0" cy="0" r="20" fill="none" stroke="#999" stroke-width="1"/>
<polygon points="0,-10 5,1 0,0 -5,1" fill="#d32f2f" stroke="#7a1a18" stroke-width="0.6" stroke-linejoin="round"/>
<polygon points="0,10 5,-1 0,0 -5,-1" fill="#dddddd" stroke="#666" stroke-width="0.6" stroke-linejoin="round"/>
<text x="0" y="-12" text-anchor="middle" font-family="sans-serif" font-size="10" font-weight="bold" fill="#000">N</text>
</svg>
</div>
<script src="/app.js"></script>
</body>
</html>`;
const server = http.createServer((req, res) => {
const url = req.url || '/';
if (url === '/' || url === '/index.html') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);
} else if (url === '/app.js') {
res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8' });
res.end(appJs);
} else if (url === '/layers.json') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(layerJson);
} else if (url === '/camps.json') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(campsJson);
} else if (url === '/corrections.json') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(correctionsData));
} else if (url === '/corrections' && req.method === 'POST') {
let body = '';
req.on('data', chunk => { body += chunk; if (body.length > 1e6) req.destroy(); });
req.on('end', () => {
let parsed;
try { parsed = JSON.parse(body); }
catch (err) {
res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Invalid JSON'); return;
}
if (!parsed || typeof parsed !== 'object' || typeof parsed.type !== 'string') {
res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Bad correction format'); return;
}
correctionsData.corrections.push(parsed);
try {
const tmp = CORRECTIONS_PATH + '.tmp';
writeFileSync(tmp, JSON.stringify(correctionsData, null, 2));
renameSync(tmp, CORRECTIONS_PATH);
} catch (err) {
console.warn('Failed to write corrections.json:', err.message);
res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Could not write file'); return;
}
console.log(`Correction added (${parsed.type}); total ${correctionsData.corrections.length}`);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ count: correctionsData.corrections.length }));
});
} else if (url === '/camps-geocoded' && req.method === 'POST') {
// Client posts { coords, borders } once mapping is complete:
// coords : { normalizedName: { latitude, longitude } } — polygon centroid
// borders : { normalizedName: { type: 'Polygon', coordinates: [[[lng, lat], ...]] } }
// We merge both against the on-disk camps.json. Two output files are
// written: the slim one (centroid only) and a strict superset with
// location.border attached as well.
let body = '';
req.on('data', chunk => { body += chunk; if (body.length > 5e6) req.destroy(); });
req.on('end', () => {
let parsed;
try { parsed = JSON.parse(body); }
catch (err) {
res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Invalid JSON'); return;
}
const coords = parsed && parsed.coords;
if (!coords || typeof coords !== 'object') {
res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Missing coords'); return;
}
const borders = (parsed && parsed.borders && typeof parsed.borders === 'object')
? parsed.borders
: {};
let camps;
try { camps = JSON.parse(readFileSync(CAMPS_PATH, 'utf8')); }
catch (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Could not read camps.json: ' + err.message);
return;
}
if (!Array.isArray(camps)) {
res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('camps.json is not an array'); return;
}
let geocodedCount = 0;
let borderCount = 0;
const slimOut = [];
const richOut = [];
for (const c of camps) {
if (!c || typeof c !== 'object' || typeof c.name !== 'string') {
slimOut.push(c);
richOut.push(c);
continue;
}
const key = normalizeCampName(c.name);
const ll = coords[key];
const border = borders[key];
const hasCentroid = ll && ll.type === 'Point' && Array.isArray(ll.coordinates)
&& ll.coordinates.length === 2
&& isFinite(ll.coordinates[0]) && isFinite(ll.coordinates[1]);
const hasBorder = border && border.type === 'Polygon' && Array.isArray(border.coordinates);
if (!hasCentroid && !hasBorder) {
slimOut.push(c);
richOut.push(c);
continue;
}
if (hasCentroid) geocodedCount++;
if (hasBorder) borderCount++;
const slimLocation = Object.assign({}, c.location || {});
const richLocation = Object.assign({}, c.location || {});
if (hasCentroid) {
const centroid = { type: 'Point', coordinates: [ll.coordinates[0], ll.coordinates[1]] };
slimLocation.centroid = centroid;
richLocation.centroid = centroid;
}
if (hasBorder) {
richLocation.border = { type: 'Polygon', coordinates: border.coordinates };
}
slimOut.push(Object.assign({}, c, { location: slimLocation }));
richOut.push(Object.assign({}, c, { location: richLocation }));
}
const writeAtomic = (filePath, data) => {
const tmp = filePath + '.tmp';
writeFileSync(tmp, JSON.stringify(data, null, 2));
renameSync(tmp, filePath);
};
try {
writeAtomic(GEOCODED_PATH, slimOut);
writeAtomic(GEOCODED_WITH_BORDERS_PATH, richOut);
} catch (err) {
console.warn('Failed to write geocoded output:', err.message);
res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Could not write file'); return;
}
console.log(
`Wrote camps-geocoded.json (${geocodedCount}/${slimOut.length} centroids) and ` +
`camps-geocoded-with-borders.json (${borderCount} borders)`
);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ total: slimOut.length, geocoded: geocodedCount, withBorders: borderCount }));
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});