Repository navigation
Expand file tree
/
Copy pathrefresh_static_artifacts.js
More file actions
247 lines (215 loc) · 5.97 KB
/
Copy pathrefresh_static_artifacts.js
File metadata and controls
247 lines (215 loc) · 5.97 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
#!/usr/bin/env node
const fs = require('fs/promises');
const path = require('path');
const ROOT = path.resolve(__dirname, '..');
const SOURCE_PATH = path.join(ROOT, 'data', 'locations.json');
const MIRROR_PATH = path.join(ROOT, 'locations.json');
const CSV_PATH = path.join(ROOT, 'super_goode_locations.csv');
const INDEX_PATH = path.join(ROOT, 'index.html');
const DEFAULT_HEADERS = [
'name',
'score',
'subtitle',
'address',
'city',
'state',
'lat',
'lng',
'reviewUrl',
'googlePlaceUrl',
'directionsUrl',
'sourceType',
'confidence',
'notes',
];
const CANONICAL_EXPORT_FIELDS = new Set(DEFAULT_HEADERS);
function normalizeName(value) {
return String(value ?? '')
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/&/g, ' and ')
.replace(/['"`]/g, '')
.replace(/[^a-z0-9]+/gi, '')
.toLowerCase();
}
function stringifyJson(value) {
return `${JSON.stringify(value, null, 2)}\n`;
}
function stringifyCell(value) {
if (value === null || value === undefined) return '';
if (typeof value === 'number') return Number.isFinite(value) ? String(value) : '';
return String(value);
}
function escapeCsv(value) {
const text = stringifyCell(value);
if (!/[",\r\n]/.test(text)) return text;
return `"${text.replace(/"/g, '""')}"`;
}
function parseCsv(text) {
const rows = [];
const input = String(text ?? '').replace(/^\uFEFF/, '');
let row = [];
let cell = '';
let i = 0;
let inQuotes = false;
const pushCell = () => {
row.push(cell);
cell = '';
};
const pushRow = () => {
if (row.length || cell.length) {
pushCell();
rows.push(row);
}
row = [];
};
while (i < input.length) {
const ch = input[i];
const next = input[i + 1];
if (inQuotes) {
if (ch === '"' && next === '"') {
cell += '"';
i += 2;
continue;
}
if (ch === '"') {
inQuotes = false;
i += 1;
continue;
}
cell += ch;
i += 1;
continue;
}
if (ch === '"') {
inQuotes = true;
i += 1;
continue;
}
if (ch === ',') {
pushCell();
i += 1;
continue;
}
if (ch === '\r') {
if (next === '\n') i += 1;
pushRow();
i += 1;
continue;
}
if (ch === '\n') {
pushRow();
i += 1;
continue;
}
cell += ch;
i += 1;
}
if (inQuotes) {
throw new Error('CSV parse failed: unterminated quoted field.');
}
if (cell.length || row.length) {
pushRow();
}
return rows;
}
async function readExistingCsv() {
try {
const raw = await fs.readFile(CSV_PATH, 'utf8');
const rows = parseCsv(raw);
if (!rows.length) {
return { headers: [...DEFAULT_HEADERS], rowMap: new Map() };
}
const [headers, ...values] = rows;
const rowMap = new Map();
for (const valueRow of values) {
const row = {};
headers.forEach((header, index) => {
row[header] = valueRow[index] ?? '';
});
const key = normalizeName(row.name);
if (key && !rowMap.has(key)) {
rowMap.set(key, row);
}
}
return { headers, rowMap };
} catch (err) {
if (err.code === 'ENOENT') {
return { headers: [...DEFAULT_HEADERS], rowMap: new Map() };
}
throw err;
}
}
function determineHeaders(existingHeaders, locations) {
const headers = existingHeaders.length ? [...existingHeaders] : [...DEFAULT_HEADERS];
if (!headers.includes('googlePlaceUrl')) {
const directionsIndex = headers.indexOf('directionsUrl');
if (directionsIndex >= 0) {
headers.splice(directionsIndex, 0, 'googlePlaceUrl');
} else {
headers.push('googlePlaceUrl');
}
}
const locationKeys = new Set(headers);
for (const location of locations) {
for (const key of Object.keys(location || {})) {
if (locationKeys.has(key)) continue;
headers.push(key);
locationKeys.add(key);
}
}
return headers;
}
function buildCsvText(locations, headers, rowMap) {
const lines = [headers.map(escapeCsv).join(',')];
for (const location of locations) {
const preserved = rowMap.get(normalizeName(location.name)) || {};
const line = headers.map((header) => {
if (CANONICAL_EXPORT_FIELDS.has(header)) {
return escapeCsv(location[header] ?? '');
}
if (Object.prototype.hasOwnProperty.call(location, header)) {
return escapeCsv(location[header]);
}
return escapeCsv(preserved[header] ?? '');
});
lines.push(line.join(','));
}
return `${lines.join('\r\n')}\r\n`;
}
function replaceEmbeddedData(indexHtml, locations) {
const replacement = `const DATA = ${JSON.stringify(locations)};`;
const pattern = /const DATA = \[[\s\S]*?\];/;
if (!pattern.test(indexHtml)) {
throw new Error('Failed to locate embedded DATA array in index.html.');
}
return indexHtml.replace(pattern, replacement);
}
async function main() {
const locations = JSON.parse(await fs.readFile(SOURCE_PATH, 'utf8'));
if (!Array.isArray(locations)) {
throw new Error('data/locations.json must contain an array.');
}
const [{ headers: existingHeaders, rowMap }, indexHtml] = await Promise.all([
readExistingCsv(),
fs.readFile(INDEX_PATH, 'utf8'),
]);
const headers = determineHeaders(existingHeaders, locations);
const csvText = buildCsvText(locations, headers, rowMap);
const mirroredJson = stringifyJson(locations);
const nextIndexHtml = replaceEmbeddedData(indexHtml, locations);
await Promise.all([
fs.writeFile(MIRROR_PATH, mirroredJson, 'utf8'),
fs.writeFile(CSV_PATH, csvText, 'utf8'),
fs.writeFile(INDEX_PATH, nextIndexHtml, 'utf8'),
]);
console.log(`Refreshed static artifacts from ${path.relative(ROOT, SOURCE_PATH)}.`);
console.log(`- Mirror: ${path.relative(ROOT, MIRROR_PATH)}`);
console.log(`- CSV rows: ${locations.length}`);
console.log(`- CSV headers: ${headers.length}`);
console.log(`- Embedded fallback rows: ${locations.length}`);
}
main().catch((err) => {
console.error(err.message);
process.exitCode = 1;
});