@rangefoundry/importers 0.0.0-stage → 0.1.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.
- package/LICENSE +661 -0
- package/README.md +21 -2
- package/dist/cells.d.ts +31 -0
- package/dist/cells.js +22 -0
- package/dist/cfb.d.ts +2 -0
- package/dist/cfb.js +196 -0
- package/dist/csrload.d.ts +12 -0
- package/dist/csrload.js +153 -0
- package/dist/diagnostics.d.ts +42 -0
- package/dist/diagnostics.js +29 -0
- package/dist/generic.d.ts +44 -0
- package/dist/generic.js +272 -0
- package/dist/grtload.d.ts +32 -0
- package/dist/grtload.js +264 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.js +126 -0
- package/dist/limits.d.ts +7 -0
- package/dist/limits.js +12 -0
- package/dist/pressure-history.d.ts +61 -0
- package/dist/pressure-history.js +158 -0
- package/dist/rangefoundry-json.d.ts +17 -0
- package/dist/rangefoundry-json.js +176 -0
- package/dist/record-fields.d.ts +35 -0
- package/dist/record-fields.js +190 -0
- package/dist/record-ids.d.ts +2 -0
- package/dist/record-ids.js +28 -0
- package/dist/records.d.ts +91 -0
- package/dist/records.js +433 -0
- package/dist/result.d.ts +65 -0
- package/dist/result.js +90 -0
- package/dist/shot-rows.d.ts +11 -0
- package/dist/shot-rows.js +39 -0
- package/dist/shotview.d.ts +16 -0
- package/dist/shotview.js +131 -0
- package/dist/statistics.d.ts +12 -0
- package/dist/statistics.js +48 -0
- package/dist/tables.d.ts +41 -0
- package/dist/tables.js +277 -0
- package/dist/template.d.ts +13 -0
- package/dist/template.js +37 -0
- package/dist/text.d.ts +28 -0
- package/dist/text.js +150 -0
- package/dist/units.d.ts +12 -0
- package/dist/units.js +62 -0
- package/dist/workbook.d.ts +12 -0
- package/dist/workbook.js +264 -0
- package/dist/worksheet-strings.d.ts +36 -0
- package/dist/worksheet-strings.js +50 -0
- package/dist/xls.d.ts +3 -0
- package/dist/xls.js +486 -0
- package/dist/xml.d.ts +26 -0
- package/dist/xml.js +261 -0
- package/dist/zip.d.ts +27 -0
- package/dist/zip.js +183 -0
- package/package.json +62 -3
package/dist/records.js
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import { fieldSpecs, tableKinds, } from './record-fields.js';
|
|
2
|
+
import { idOfKey } from './record-ids.js';
|
|
3
|
+
import { guessDecimal, headerUnit, headerWords, readNumber } from './tables.js';
|
|
4
|
+
/** Lowest kind score that suggests a kind, and the scores from which the tier is medium and high. */
|
|
5
|
+
export const tierFloors = { low: 0.4, medium: 0.6, high: 0.8 };
|
|
6
|
+
function tierOf(score) {
|
|
7
|
+
if (score >= tierFloors.high)
|
|
8
|
+
return 'high';
|
|
9
|
+
if (score >= tierFloors.medium)
|
|
10
|
+
return 'medium';
|
|
11
|
+
return score >= tierFloors.low ? 'low' : undefined;
|
|
12
|
+
}
|
|
13
|
+
const sampleOf = (table, column) => table.rows
|
|
14
|
+
.slice(0, 200)
|
|
15
|
+
.map((r) => r[column] ?? '')
|
|
16
|
+
.filter((c) => c !== '');
|
|
17
|
+
/** A unit symbol folded for comparison: lower case, letters and digits only, ² and ³ as digits. */
|
|
18
|
+
const plain = (s) => s
|
|
19
|
+
.toLowerCase()
|
|
20
|
+
.replaceAll('²', '2')
|
|
21
|
+
.replaceAll('³', '3')
|
|
22
|
+
.replace(/[^a-z0-9]/g, '');
|
|
23
|
+
/** The unit the header names, `unknown` for a unit in brackets or after a slash or underscore the field does not take. */
|
|
24
|
+
const unitFromHeader = (header, units) => {
|
|
25
|
+
const raw = headerUnit(header);
|
|
26
|
+
if (!raw)
|
|
27
|
+
return undefined;
|
|
28
|
+
const key = raw.replace(/inch(es)?|"/g, 'in').replace(/grains?/g, 'gr');
|
|
29
|
+
const named = units.find((u) => plain(u.symbol) === plain(key));
|
|
30
|
+
// a last word after a space may be a word of the name (Case length, Max OAL), not a unit
|
|
31
|
+
return named ?? (header.toLowerCase().endsWith(` ${raw}`) ? undefined : 'unknown');
|
|
32
|
+
};
|
|
33
|
+
/** Share of `cells` read as numbers in `unit` that fall in `range` of the stored unit. */
|
|
34
|
+
const inRange = (cells, decimal, unit, range) => {
|
|
35
|
+
let n = 0;
|
|
36
|
+
for (const c of cells) {
|
|
37
|
+
const x = readNumber(c, decimal);
|
|
38
|
+
if (x === undefined)
|
|
39
|
+
continue;
|
|
40
|
+
const v = unit.toStored(x);
|
|
41
|
+
if (v >= range[0] && v <= range[1])
|
|
42
|
+
n++;
|
|
43
|
+
}
|
|
44
|
+
return cells.length === 0 ? 0 : n / cells.length;
|
|
45
|
+
};
|
|
46
|
+
/** The unit of a numeric column: from its header, else the one that fits the usual range best, else the stored unit. */
|
|
47
|
+
function unitOf(field, first, header, sample) {
|
|
48
|
+
const all = field.units ?? [first];
|
|
49
|
+
const named = unitFromHeader(header, all);
|
|
50
|
+
if (named === 'unknown')
|
|
51
|
+
return { from: 'unknown' };
|
|
52
|
+
if (named)
|
|
53
|
+
return { unit: named, from: 'header' };
|
|
54
|
+
const units = all.filter((u) => !u.named);
|
|
55
|
+
if (units.length === 1 || !field.range)
|
|
56
|
+
return { unit: first, from: 'default' };
|
|
57
|
+
const spans = { range: field.range, typical: field.typical ?? field.range };
|
|
58
|
+
const best = bestFit(units, first, sample, spans);
|
|
59
|
+
return { unit: best.unit, from: best.fit > 0 ? 'values' : 'default' };
|
|
60
|
+
}
|
|
61
|
+
/** The unit whose reading puts most sample values in `range`, ties broken by `typical`; `first` with no fit when the sample has no number. */
|
|
62
|
+
function bestFit(units, first, { cells, decimal }, { range, typical }) {
|
|
63
|
+
let best = { unit: first, fit: -1, usual: -1 };
|
|
64
|
+
for (const unit of units) {
|
|
65
|
+
const fit = inRange(cells, decimal, unit, range);
|
|
66
|
+
const usual = inRange(cells, decimal, unit, typical);
|
|
67
|
+
if (fit > best.fit || (fit === best.fit && usual > best.usual))
|
|
68
|
+
best = { unit, fit, usual };
|
|
69
|
+
}
|
|
70
|
+
return best;
|
|
71
|
+
}
|
|
72
|
+
/** How much the words of a header say it names a field: 1 for the whole header, 0.8 for a word, 0.5 for a part. */
|
|
73
|
+
function headerScore(field, header) {
|
|
74
|
+
const words = headerWords(header);
|
|
75
|
+
const joined = words.join('');
|
|
76
|
+
if (field.aliases.includes(joined))
|
|
77
|
+
return 1;
|
|
78
|
+
if (words.some((w) => field.aliases.includes(w)))
|
|
79
|
+
return 0.8;
|
|
80
|
+
return field.aliases.some((a) => a.length >= 4 && joined.includes(a)) ? 0.5 : 0;
|
|
81
|
+
}
|
|
82
|
+
/** How well the cells fit a field, 0 to 1: spelled choices, numbers in the usual and the possible range, else text. */
|
|
83
|
+
function valueScore(field, cells) {
|
|
84
|
+
if (cells.length === 0)
|
|
85
|
+
return 0;
|
|
86
|
+
const { decimal } = guessDecimal(cells);
|
|
87
|
+
const { choices, units, range } = field;
|
|
88
|
+
if (choices)
|
|
89
|
+
return cells.filter((c) => Object.hasOwn(choices, c.trim().toLowerCase())).length / cells.length;
|
|
90
|
+
if (units && range) {
|
|
91
|
+
const typical = field.typical ?? range;
|
|
92
|
+
return Math.max(...units
|
|
93
|
+
.filter((u) => !u.named)
|
|
94
|
+
.map((u) => inRange(cells, decimal, u, typical) * 0.5 + inRange(cells, decimal, u, range) * 0.5));
|
|
95
|
+
}
|
|
96
|
+
return cells.filter((c) => readNumber(c, decimal) === undefined).length / cells.length;
|
|
97
|
+
}
|
|
98
|
+
/** How well a column fills a field, 0 to 1: the header's words weigh most, the values confirm. */
|
|
99
|
+
function columnScore(field, header, cells) {
|
|
100
|
+
const h = headerScore(field, header);
|
|
101
|
+
const v = valueScore(field, cells);
|
|
102
|
+
if (h > 0)
|
|
103
|
+
return 0.65 * h + 0.35 * v;
|
|
104
|
+
if (field.choices)
|
|
105
|
+
return 0.5 * v;
|
|
106
|
+
return field.units ? 0.2 * v : 0;
|
|
107
|
+
}
|
|
108
|
+
/** Best one-to-one assignment (greedy by score) of columns to the fields of `kind`; scores of the fields that got one. */
|
|
109
|
+
function assign(table, kind) {
|
|
110
|
+
const cells = table.header.map((_, i) => sampleOf(table, i));
|
|
111
|
+
const pairs = [];
|
|
112
|
+
for (const field of fieldSpecs[kind]) {
|
|
113
|
+
table.header.forEach((h, column) => {
|
|
114
|
+
const score = columnScore(field, h, cells[column] ?? []);
|
|
115
|
+
if (score >= 0.3)
|
|
116
|
+
pairs.push({ column, field, score });
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
pairs.sort((a, b) => b.score - a.score);
|
|
120
|
+
const column = new Map();
|
|
121
|
+
const used = new Set();
|
|
122
|
+
for (const p of pairs) {
|
|
123
|
+
if (column.has(p.column) || used.has(p.field.key))
|
|
124
|
+
continue;
|
|
125
|
+
column.set(p.column, { field: p.field, score: p.score });
|
|
126
|
+
used.add(p.field.key);
|
|
127
|
+
}
|
|
128
|
+
return { column, cells };
|
|
129
|
+
}
|
|
130
|
+
/** The score of every kind for `table`, best first. */
|
|
131
|
+
function scoreKinds(table) {
|
|
132
|
+
return tableKinds
|
|
133
|
+
.map((kind) => {
|
|
134
|
+
const { column } = assign(table, kind);
|
|
135
|
+
const score = Math.min(1, [...column.values()].reduce((s, c) => s + c.field.weight * c.score, 0));
|
|
136
|
+
return { kind, score };
|
|
137
|
+
})
|
|
138
|
+
.toSorted((a, b) => b.score - a.score);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The kind a table suggests from its header words and value ranges: high from 0.80, medium from
|
|
142
|
+
* 0.60, low from 0.40. Below 0.40 no kind is suggested and the refusal carries the scores and the floor.
|
|
143
|
+
*/
|
|
144
|
+
export function suggestKind(table) {
|
|
145
|
+
const scores = scoreKinds(table);
|
|
146
|
+
const best = scores[0];
|
|
147
|
+
const tier = best && tierOf(best.score);
|
|
148
|
+
if (best && tier)
|
|
149
|
+
return { scores, kind: best.kind, tier };
|
|
150
|
+
return { scores, refusal: { code: 'noKind', params: { scores, floor: tierFloors.low } } };
|
|
151
|
+
}
|
|
152
|
+
/** The column map the headers and values suggest for `kind`, one entry per column. */
|
|
153
|
+
export function autoMap(table, kind) {
|
|
154
|
+
const { column, cells } = assign(table, kind);
|
|
155
|
+
return table.header.map((header, i) => {
|
|
156
|
+
const sample = cells[i] ?? [];
|
|
157
|
+
const { decimal, ambiguous } = guessDecimal(sample);
|
|
158
|
+
const hit = column.get(i);
|
|
159
|
+
if (!hit)
|
|
160
|
+
return { decimal };
|
|
161
|
+
const map = { field: hit.field.key, decimal, ambiguousDecimal: ambiguous };
|
|
162
|
+
const first = hit.field.units?.[0];
|
|
163
|
+
if (first) {
|
|
164
|
+
const u = unitOf(hit.field, first, header, { cells: sample, decimal });
|
|
165
|
+
map.unit = u.unit?.symbol;
|
|
166
|
+
map.unitFrom = u.from;
|
|
167
|
+
}
|
|
168
|
+
return map;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
const stored = (map, field) => field.units?.find((u) => u.symbol === map.unit) ?? field.units?.[0];
|
|
172
|
+
/** The unit the cells of a column are read in, or why the column has none. */
|
|
173
|
+
function columnUnit(map, field) {
|
|
174
|
+
if (map.unitFrom === 'unknown' && map.unit === undefined) {
|
|
175
|
+
const symbols = field.units?.map((u) => u.symbol) ?? [];
|
|
176
|
+
return { problem: { code: 'unitOther', params: { field: field.key, symbols } } };
|
|
177
|
+
}
|
|
178
|
+
return stored(map, field) ?? { problem: { code: 'noUnit', params: { field: field.key } } };
|
|
179
|
+
}
|
|
180
|
+
/** The warning for a value in the stored unit outside the field's usual range. */
|
|
181
|
+
function rangeWarning(field, cell, unit, value) {
|
|
182
|
+
const range = field.range;
|
|
183
|
+
if (!range || (value >= range[0] && value <= range[1]))
|
|
184
|
+
return undefined;
|
|
185
|
+
return {
|
|
186
|
+
code: 'outsideUsual',
|
|
187
|
+
params: {
|
|
188
|
+
field: field.key,
|
|
189
|
+
cell,
|
|
190
|
+
unit: unit.symbol,
|
|
191
|
+
low: range[0],
|
|
192
|
+
high: range[1],
|
|
193
|
+
stored: field.units?.[0]?.symbol ?? '',
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/** A number cell in the stored unit with its raw text when the unit differs and a plausibility warning, or why the row is rejected. */
|
|
198
|
+
function numberCell(cell, map, field) {
|
|
199
|
+
const unit = columnUnit(map, field);
|
|
200
|
+
if ('problem' in unit)
|
|
201
|
+
return unit;
|
|
202
|
+
const x = readNumber(cell, map.decimal);
|
|
203
|
+
if (x === undefined)
|
|
204
|
+
return {
|
|
205
|
+
problem: { code: 'notNumber', params: { field: field.key, cell, mark: map.decimal } },
|
|
206
|
+
};
|
|
207
|
+
const value = unit.toStored(x);
|
|
208
|
+
if (!(value > 0))
|
|
209
|
+
return { problem: { code: 'notAboveZero', params: { field: field.key, cell } } };
|
|
210
|
+
const warning = rangeWarning(field, cell, unit, value);
|
|
211
|
+
return {
|
|
212
|
+
value,
|
|
213
|
+
...(unit !== field.units?.[0] && { raw: cell }),
|
|
214
|
+
...(warning && { warning }),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const quantityOf = (c) => c !== undefined && typeof c !== 'string'
|
|
218
|
+
? { value: c.value, ...(c.raw && { raw: c.raw }) }
|
|
219
|
+
: undefined;
|
|
220
|
+
/** The candidate of one row of `kind`; `makerId` is the id of its maker's candidate. */
|
|
221
|
+
function candidateOf(kind, head, c, makerId) {
|
|
222
|
+
if (kind === 'bullet')
|
|
223
|
+
return { kind, ...head, data: bulletData(head.name, c, makerId) };
|
|
224
|
+
if (kind === 'powder')
|
|
225
|
+
return { kind, ...head, data: powderData(c) };
|
|
226
|
+
return { kind, ...head, data: cartridgeData(head.name, c) };
|
|
227
|
+
}
|
|
228
|
+
/** The data of a bullet row: its name, maker and the numbers it gives as overrides. */
|
|
229
|
+
function bulletData(name, c, makerId) {
|
|
230
|
+
const coefficients = ['G1', 'G7'].flatMap((m) => {
|
|
231
|
+
const q = quantityOf(c[`bc${m}`]);
|
|
232
|
+
return q ? [{ dragModel: m, value: q.value }] : [];
|
|
233
|
+
});
|
|
234
|
+
const diameter = quantityOf(c['diameter']);
|
|
235
|
+
const mass = quantityOf(c['mass']);
|
|
236
|
+
const length = quantityOf(c['length']);
|
|
237
|
+
const caliber = typeof c['caliber'] === 'string' ? c['caliber'] : undefined;
|
|
238
|
+
return {
|
|
239
|
+
origin: 'user',
|
|
240
|
+
...(makerId && { manufacturer: `user:${makerId}` }),
|
|
241
|
+
overrides: {
|
|
242
|
+
name,
|
|
243
|
+
...(caliber && { caliber }),
|
|
244
|
+
...(diameter && { diameter }),
|
|
245
|
+
...(mass && { mass }),
|
|
246
|
+
...(length && { length }),
|
|
247
|
+
...(coefficients.length > 0 && { ballisticCoefficients: coefficients }),
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/** The data of a powder row: a measured draft with the grain form, base and bulk density it gives. */
|
|
252
|
+
function powderData(c) {
|
|
253
|
+
const bulk = quantityOf(c['bulkDensity']);
|
|
254
|
+
return {
|
|
255
|
+
origin: 'user',
|
|
256
|
+
provenanceKind: 'measured',
|
|
257
|
+
draft: {
|
|
258
|
+
...(typeof c['grainForm'] === 'string' && {
|
|
259
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the choices of the field spell only these values
|
|
260
|
+
grainForm: c['grainForm'],
|
|
261
|
+
}),
|
|
262
|
+
...(typeof c['propellantBase'] === 'string' && {
|
|
263
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the choices of the field spell only these values
|
|
264
|
+
propellantBase: c['propellantBase'],
|
|
265
|
+
}),
|
|
266
|
+
...(bulk && { bulkDensity: bulk }),
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
/** The data of a cartridge row: its name and the case length, overall length, bullet diameter and Pmax it gives. */
|
|
271
|
+
function cartridgeData(name, c) {
|
|
272
|
+
const spec = (symbol, key, quantity, side) => {
|
|
273
|
+
const q = quantityOf(c[key]);
|
|
274
|
+
return q
|
|
275
|
+
? [{ ...(side && { side }), symbol, quantity, value: q.value, ...(q.raw && { raw: q.raw }) }]
|
|
276
|
+
: [];
|
|
277
|
+
};
|
|
278
|
+
const values = [
|
|
279
|
+
...spec('L3', 'caseLength', 'length', 'cartridge'),
|
|
280
|
+
...spec('L6', 'overallLength', 'length', 'cartridge'),
|
|
281
|
+
...spec('G1', 'bulletDiameter', 'length', 'cartridge'),
|
|
282
|
+
...spec('Pmax', 'maxPressure', 'pressure'),
|
|
283
|
+
];
|
|
284
|
+
return { origin: 'user', overrides: { name, ...(values.length > 0 && { values }) } };
|
|
285
|
+
}
|
|
286
|
+
/** Lower case, accents and extra spaces folded: the form of a name in a key. */
|
|
287
|
+
export const keyText = (s) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/\s+/g, ' ').trim();
|
|
288
|
+
/** The text the id of a row is made from: kind, name, maker and, for a bullet, its diameter and mass. */
|
|
289
|
+
function keyOf(kind, name, maker, c) {
|
|
290
|
+
const num = (k) => {
|
|
291
|
+
const q = c[k];
|
|
292
|
+
return q !== undefined && typeof q !== 'string' ? Number(q.value.toPrecision(6)) : '';
|
|
293
|
+
};
|
|
294
|
+
const parts = [kind, keyText(name), keyText(maker ?? '')];
|
|
295
|
+
if (kind === 'bullet')
|
|
296
|
+
parts.push(String(num('diameter')), String(num('mass')));
|
|
297
|
+
return parts.join('|');
|
|
298
|
+
}
|
|
299
|
+
/** One cell into `c` as the field says: a choice, a number in the stored unit, or text. Returns the issue that rejects the row. */
|
|
300
|
+
function readCell(col, cell, at, { c, warnings }) {
|
|
301
|
+
const { f } = col;
|
|
302
|
+
const issue = (reason) => ({
|
|
303
|
+
row: at.row,
|
|
304
|
+
column: at.header,
|
|
305
|
+
cell,
|
|
306
|
+
reason,
|
|
307
|
+
});
|
|
308
|
+
if (cell === '')
|
|
309
|
+
return f.required ? issue({ code: 'emptyCell', params: { field: f.key } }) : undefined;
|
|
310
|
+
if (f.choices) {
|
|
311
|
+
const key = cell.toLowerCase();
|
|
312
|
+
const v = Object.hasOwn(f.choices, key) ? f.choices[key] : undefined;
|
|
313
|
+
if (v === undefined) {
|
|
314
|
+
const choices = [...new Set(Object.values(f.choices))];
|
|
315
|
+
warnings.push(issue({ code: 'notChoice', params: { field: f.key, cell, choices } }));
|
|
316
|
+
}
|
|
317
|
+
else
|
|
318
|
+
c[f.key] = v;
|
|
319
|
+
return undefined;
|
|
320
|
+
}
|
|
321
|
+
if (!f.units) {
|
|
322
|
+
c[f.key] = cell;
|
|
323
|
+
return undefined;
|
|
324
|
+
}
|
|
325
|
+
const n = numberCell(cell, at.map, f);
|
|
326
|
+
if ('problem' in n)
|
|
327
|
+
return issue(n.problem);
|
|
328
|
+
c[f.key] = { value: n.value, ...(n.raw && { raw: n.raw }) };
|
|
329
|
+
if (n.warning)
|
|
330
|
+
warnings.push(issue(n.warning));
|
|
331
|
+
return undefined;
|
|
332
|
+
}
|
|
333
|
+
/** The cells of one row by field, or the issue that rejects it. */
|
|
334
|
+
function readRow({ table, columns, map }, cells, row, warnings) {
|
|
335
|
+
const c = {};
|
|
336
|
+
for (const col of columns) {
|
|
337
|
+
if (col.i < 0)
|
|
338
|
+
continue;
|
|
339
|
+
const bad = readCell(col, (cells[col.i] ?? '').trim(), { row, header: table.header[col.i] ?? col.f.label, map: map[col.i] ?? { decimal: '.' } }, { c, warnings });
|
|
340
|
+
if (bad)
|
|
341
|
+
return bad;
|
|
342
|
+
}
|
|
343
|
+
return c;
|
|
344
|
+
}
|
|
345
|
+
/** `out` with every row rejected because no column is mapped to the `missing` required fields. */
|
|
346
|
+
function rejectAll(out, missing, rows) {
|
|
347
|
+
out.rejected.push({
|
|
348
|
+
row: 1,
|
|
349
|
+
column: missing.map((c) => c.f.label).join(', '),
|
|
350
|
+
cell: '',
|
|
351
|
+
reason: {
|
|
352
|
+
code: missing.length > 1 ? 'noColumns' : 'noColumn',
|
|
353
|
+
params: { fields: missing.map((c) => c.f.key) },
|
|
354
|
+
},
|
|
355
|
+
});
|
|
356
|
+
out.counts.rejected = rows;
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
/** The id of a maker's candidate by its name, adding the candidate to `makers` the first time. */
|
|
360
|
+
function makerCandidates(makers) {
|
|
361
|
+
const ids = new Map();
|
|
362
|
+
return (maker) => {
|
|
363
|
+
const key = `manufacturer|${keyText(maker)}`;
|
|
364
|
+
const known = ids.get(key);
|
|
365
|
+
if (known)
|
|
366
|
+
return known;
|
|
367
|
+
const id = idOfKey(key);
|
|
368
|
+
ids.set(key, id);
|
|
369
|
+
makers.push({ kind: 'manufacturer', key, name: maker, data: { origin: 'user' } });
|
|
370
|
+
return id;
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** Why the row `row` is not imported: it gives the same id as the earlier row `first`. */
|
|
374
|
+
const sameIdReason = (kind, first, row) => ({
|
|
375
|
+
code: kind === 'bullet' ? 'sameBulletId' : 'sameId',
|
|
376
|
+
params: { first, row },
|
|
377
|
+
});
|
|
378
|
+
const isIssue = (x) => typeof x.row === 'number' && 'reason' in x;
|
|
379
|
+
/**
|
|
380
|
+
* The record candidates of `table` read with `map` as `kind`. A row that fails is listed with row,
|
|
381
|
+
* column, cell and reason and never blocks the others. Keys are deterministic (kind, name, maker
|
|
382
|
+
* and, for a bullet, diameter and mass), so the same row read again gets the same id
|
|
383
|
+
* (`idOfKey(key)`). A row whose key repeats an earlier row's gets a warning naming both rows; the
|
|
384
|
+
* caller keeps the first record of an id. The caller makes each candidate a record and parses it
|
|
385
|
+
* with the user record schema before storing it.
|
|
386
|
+
*/
|
|
387
|
+
export function buildRecords(table, kind, map) {
|
|
388
|
+
const columns = fieldSpecs[kind].map((f) => ({ f, i: map.findIndex((m) => m.field === f.key) }));
|
|
389
|
+
const out = {
|
|
390
|
+
entries: [],
|
|
391
|
+
makers: [],
|
|
392
|
+
counts: { accepted: 0, warned: 0, rejected: 0 },
|
|
393
|
+
rejected: [],
|
|
394
|
+
warnings: [],
|
|
395
|
+
};
|
|
396
|
+
const missing = columns.filter((c) => c.f.required && c.i < 0);
|
|
397
|
+
if (missing.length > 0)
|
|
398
|
+
return rejectAll(out, missing, table.rows.length);
|
|
399
|
+
const makerOf = makerCandidates(out.makers);
|
|
400
|
+
const warned = new Set();
|
|
401
|
+
const firstRow = new Map();
|
|
402
|
+
const nameColumn = columns.find((col) => col.f.key === 'name');
|
|
403
|
+
const nameHeader = nameColumn ? (table.header[nameColumn.i] ?? nameColumn.f.label) : 'Name';
|
|
404
|
+
table.rows.forEach((cells, r) => {
|
|
405
|
+
const row = r + (table.hasHeader ? 2 : 1);
|
|
406
|
+
const before = out.warnings.length;
|
|
407
|
+
const c = readRow({ table, columns, map }, cells, row, out.warnings);
|
|
408
|
+
if (isIssue(c)) {
|
|
409
|
+
// warnings of a rejected row are dropped with it
|
|
410
|
+
out.warnings.length = before;
|
|
411
|
+
out.rejected.push(c);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
const nameCell = c['name'];
|
|
415
|
+
const name = typeof nameCell === 'string' ? nameCell : '';
|
|
416
|
+
const maker = typeof c['maker'] === 'string' ? c['maker'] : undefined;
|
|
417
|
+
const key = keyOf(kind, name, maker, c);
|
|
418
|
+
const first = firstRow.get(key);
|
|
419
|
+
if (first === undefined)
|
|
420
|
+
firstRow.set(key, row);
|
|
421
|
+
else {
|
|
422
|
+
const reason = sameIdReason(kind, first, row);
|
|
423
|
+
out.warnings.push({ row, column: nameHeader, cell: name, reason });
|
|
424
|
+
}
|
|
425
|
+
if (out.warnings.length > before)
|
|
426
|
+
warned.add(row);
|
|
427
|
+
const candidate = candidateOf(kind, { key, name }, c, maker && makerOf(maker));
|
|
428
|
+
out.entries.push({ row, candidate });
|
|
429
|
+
});
|
|
430
|
+
out.counts = { accepted: out.entries.length, warned: warned.size, rejected: out.rejected.length };
|
|
431
|
+
return out;
|
|
432
|
+
}
|
|
433
|
+
//# sourceMappingURL=records.js.map
|
package/dist/result.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ChronoSession, ChronoShot, QuantityValue } from '@rangefoundry/schema';
|
|
2
|
+
import { type ChronoDiagnostic } from './diagnostics.ts';
|
|
3
|
+
import type { ChronoFormatId } from './index.ts';
|
|
4
|
+
import { type VelocityUnit } from './units.ts';
|
|
5
|
+
export type { ChronoFormatId };
|
|
6
|
+
/** Options every chronograph parser takes. */
|
|
7
|
+
export interface ChronoParserOptions {
|
|
8
|
+
/** Unit for velocities whose unit the file does not name or names in an unknown way. */
|
|
9
|
+
velocityUnit?: VelocityUnit | undefined;
|
|
10
|
+
/** File name, used as the provenance source title. */
|
|
11
|
+
fileName?: string | undefined;
|
|
12
|
+
/** Lowercase hex sha256 of the file bytes, computed by the caller. */
|
|
13
|
+
sha256?: string | undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The parts of a `ChronoSession` a file can supply. `device.manufacturerName` is the text the file
|
|
17
|
+
* gives; the session's `device.manufacturer` is a reference the caller resolves from it.
|
|
18
|
+
*/
|
|
19
|
+
export interface SessionCandidate {
|
|
20
|
+
date?: string | undefined;
|
|
21
|
+
device: {
|
|
22
|
+
kind: ChronoSession['device']['kind'];
|
|
23
|
+
manufacturerName?: string | undefined;
|
|
24
|
+
model?: string | undefined;
|
|
25
|
+
};
|
|
26
|
+
muzzleDistance?: QuantityValue;
|
|
27
|
+
strings: {
|
|
28
|
+
shots: ChronoShot[];
|
|
29
|
+
}[];
|
|
30
|
+
note?: string;
|
|
31
|
+
provenance: {
|
|
32
|
+
kind: 'measured';
|
|
33
|
+
sources: [{
|
|
34
|
+
title?: string;
|
|
35
|
+
sha256?: string;
|
|
36
|
+
note?: string;
|
|
37
|
+
}];
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Result of a chronograph import: the session the file supplies, a label per string, the units
|
|
42
|
+
* found and what the user still has to enter.
|
|
43
|
+
*/
|
|
44
|
+
export interface ChronoImport {
|
|
45
|
+
format: ChronoFormatId;
|
|
46
|
+
session: SessionCandidate;
|
|
47
|
+
/** One label per string (session name, Notes text, series number), offered for choosing its load. */
|
|
48
|
+
stringLabels: (string | undefined)[];
|
|
49
|
+
/** Distinct units of the velocities in first-seen order: named in the file, or by the caller. */
|
|
50
|
+
velocityUnits: {
|
|
51
|
+
unit: VelocityUnit;
|
|
52
|
+
source: 'file' | 'caller';
|
|
53
|
+
}[];
|
|
54
|
+
/**
|
|
55
|
+
* Dot paths the user should enter: the ones a catalogue session (`catalogueSession`) requires, plus `device.firmware`
|
|
56
|
+
* and, for optical devices, `muzzleDistance`.
|
|
57
|
+
*/
|
|
58
|
+
missingPaths: string[];
|
|
59
|
+
warnings: ChronoDiagnostic[];
|
|
60
|
+
}
|
|
61
|
+
/** Lists every field the file could not supply; `labels` names the strings of `session`, `warnings` holds what the parser warned of so far. */
|
|
62
|
+
export declare function buildChronoImport(format: ChronoFormatId, session: Omit<SessionCandidate, 'provenance'>, { labels, warnings }: {
|
|
63
|
+
labels: (string | undefined)[];
|
|
64
|
+
warnings: ChronoDiagnostic[];
|
|
65
|
+
}, options: ChronoParserOptions): ChronoImport;
|
package/dist/result.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { refuse } from './diagnostics.js';
|
|
2
|
+
import { parseVelocityUnit } from './units.js';
|
|
3
|
+
/** The sha256 lowercase; throws unless it is 64 hex digits. */
|
|
4
|
+
function checkSha256(sha256) {
|
|
5
|
+
const lower = sha256.toLowerCase();
|
|
6
|
+
if (!/^[0-9a-f]{64}$/.test(lower))
|
|
7
|
+
refuse('sha256Malformed');
|
|
8
|
+
return lower;
|
|
9
|
+
}
|
|
10
|
+
// assumed small-arms range, not a cited bound: it flags unit, column and footer-row errors only
|
|
11
|
+
const minVelocity = 30;
|
|
12
|
+
const maxVelocity = 2000;
|
|
13
|
+
/** File name, hash and, when a velocity unit named by the caller was used, a note saying so. */
|
|
14
|
+
function provenanceSource(options, warnings) {
|
|
15
|
+
const source = {};
|
|
16
|
+
if (options.fileName)
|
|
17
|
+
source.title = options.fileName;
|
|
18
|
+
if (options.sha256)
|
|
19
|
+
source.sha256 = checkSha256(options.sha256);
|
|
20
|
+
// raw keeps only the file's text, so the record states the unit the user named
|
|
21
|
+
const unit = options.velocityUnit;
|
|
22
|
+
const named = ['unknownUnitNamedByCaller', 'missingUnitNamedByCaller'];
|
|
23
|
+
if (unit && warnings.some((w) => named.includes(w.code))) {
|
|
24
|
+
source.note = `velocities without a known unit in the file are read as ${unit}, as named by the user at import`;
|
|
25
|
+
}
|
|
26
|
+
return source;
|
|
27
|
+
}
|
|
28
|
+
/** One warning per string listing the shots outside the assumed small-arms range. */
|
|
29
|
+
function rangeWarnings(strings, warnings) {
|
|
30
|
+
strings.forEach((s, i) => {
|
|
31
|
+
const out = s.shots.flatMap((shot, j) => shot.velocity.value < minVelocity || shot.velocity.value > maxVelocity ? [j + 1] : []);
|
|
32
|
+
if (out.length > 0) {
|
|
33
|
+
warnings.push({
|
|
34
|
+
code: 'outsideRange',
|
|
35
|
+
params: { string: i + 1, shots: out.map(String), min: minVelocity, max: maxVelocity },
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** Distinct units of the shots in first-seen order; `raw` ends in the file's unit text whenever the file names one. */
|
|
41
|
+
function velocityUnitsOf(strings, callerUnit) {
|
|
42
|
+
const velocityUnits = [];
|
|
43
|
+
for (const shot of strings.flatMap((s) => s.shots)) {
|
|
44
|
+
const named = parseVelocityUnit(shot.velocity.raw?.split(' ').at(-1));
|
|
45
|
+
const entry = named
|
|
46
|
+
? { unit: named, source: 'file' }
|
|
47
|
+
: callerUnit && { unit: callerUnit, source: 'caller' };
|
|
48
|
+
if (entry && !velocityUnits.some((e) => e.unit === entry.unit && e.source === entry.source)) {
|
|
49
|
+
velocityUnits.push(entry);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return velocityUnits;
|
|
53
|
+
}
|
|
54
|
+
/** Dot paths of what the file could not supply, in the order the user enters them. */
|
|
55
|
+
function missingPaths(session, source) {
|
|
56
|
+
const missing = ['id'];
|
|
57
|
+
if (!session.date)
|
|
58
|
+
missing.push('date');
|
|
59
|
+
// a reference needs the catalogue, which the parsers do not read: the caller resolves a name the file gives
|
|
60
|
+
missing.push('device.manufacturer');
|
|
61
|
+
if (!session.device.model)
|
|
62
|
+
missing.push('device.model');
|
|
63
|
+
missing.push('device.firmware');
|
|
64
|
+
// the chronograph protocol asks for the screen distance; the schema keeps it optional
|
|
65
|
+
if (session.device.kind === 'optical' && !session.muzzleDistance)
|
|
66
|
+
missing.push('muzzleDistance');
|
|
67
|
+
missing.push('conditions.airTemperature');
|
|
68
|
+
session.strings.forEach((_, i) => {
|
|
69
|
+
missing.push(`strings.${i}.load`);
|
|
70
|
+
});
|
|
71
|
+
if (!source.title)
|
|
72
|
+
missing.push('provenance.sources.0.title');
|
|
73
|
+
return missing;
|
|
74
|
+
}
|
|
75
|
+
/** Lists every field the file could not supply; `labels` names the strings of `session`, `warnings` holds what the parser warned of so far. */
|
|
76
|
+
export function buildChronoImport(format, session, { labels, warnings }, options) {
|
|
77
|
+
if (session.strings.length === 0)
|
|
78
|
+
refuse('noShots');
|
|
79
|
+
const source = provenanceSource(options, warnings);
|
|
80
|
+
rangeWarnings(session.strings, warnings);
|
|
81
|
+
return {
|
|
82
|
+
format,
|
|
83
|
+
session: { ...session, provenance: { kind: 'measured', sources: [source] } },
|
|
84
|
+
stringLabels: labels,
|
|
85
|
+
velocityUnits: velocityUnitsOf(session.strings, options.velocityUnit),
|
|
86
|
+
missingPaths: missingPaths(session, source),
|
|
87
|
+
warnings,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=result.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ChronoShot } from '@rangefoundry/schema';
|
|
2
|
+
import { type VelocityUnit } from './units.ts';
|
|
3
|
+
/** Until the first row for which `footerStarts` holds, that row and the non-empty rows after it being the footer; velocity in column 2, CLEAN BORE and COLD BORE by position (columns 7 and 8), read by `isSet`. */
|
|
4
|
+
export declare function readShotRows(rows: string[][], unitText: string | undefined, unit: VelocityUnit, footerStarts: (cells: string[]) => boolean): {
|
|
5
|
+
shots: ChronoShot[];
|
|
6
|
+
values: number[];
|
|
7
|
+
flags: string[];
|
|
8
|
+
footer: string[][];
|
|
9
|
+
};
|
|
10
|
+
/** In a workbook the shots end at the first row whose first cell is neither empty nor a whole number. */
|
|
11
|
+
export declare const workbookFooterStarts: (cells: string[]) => boolean;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { parseNumber } from './text.js';
|
|
2
|
+
import { parseVelocity } from './units.js';
|
|
3
|
+
/** A bore flag cell is set unless it is empty, `0`, `no`, `false` or `n` (any case). */
|
|
4
|
+
const isSet = (cell = '') => !['', '0', 'no', 'false', 'n'].includes(cell.trim().toLowerCase());
|
|
5
|
+
/** The bore flags set in a shot row, `clean bore and cold bore`, or empty text. */
|
|
6
|
+
function boreFlagText(cells) {
|
|
7
|
+
return [isSet(cells[6]) ? 'clean bore' : '', isSet(cells[7]) ? 'cold bore' : '']
|
|
8
|
+
.filter(Boolean)
|
|
9
|
+
.join(' and ');
|
|
10
|
+
}
|
|
11
|
+
/** Until the first row for which `footerStarts` holds, that row and the non-empty rows after it being the footer; velocity in column 2, CLEAN BORE and COLD BORE by position (columns 7 and 8), read by `isSet`. */
|
|
12
|
+
export function readShotRows(rows, unitText, unit, footerStarts) {
|
|
13
|
+
const shots = [];
|
|
14
|
+
const values = [];
|
|
15
|
+
const flags = [];
|
|
16
|
+
const footer = [];
|
|
17
|
+
for (const cells of rows) {
|
|
18
|
+
if (footer.length > 0 || footerStarts(cells)) {
|
|
19
|
+
if (cells.length > 0)
|
|
20
|
+
footer.push(cells);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (!/^\d+$/.test(cells[0] ?? ''))
|
|
24
|
+
continue;
|
|
25
|
+
const velocityText = cells[1] ?? '';
|
|
26
|
+
const shot = { velocity: parseVelocity(velocityText, unitText, unit) };
|
|
27
|
+
values.push(parseNumber(velocityText));
|
|
28
|
+
const which = boreFlagText(cells);
|
|
29
|
+
if (which) {
|
|
30
|
+
shot.coldBore = true;
|
|
31
|
+
flags.push(`shot ${cells[0]} ${which}`);
|
|
32
|
+
}
|
|
33
|
+
shots.push(shot);
|
|
34
|
+
}
|
|
35
|
+
return { shots, values, flags, footer };
|
|
36
|
+
}
|
|
37
|
+
/** In a workbook the shots end at the first row whose first cell is neither empty nor a whole number. */
|
|
38
|
+
export const workbookFooterStarts = (cells) => (cells[0] ?? '') !== '' && !/^\d+$/.test(cells[0] ?? '');
|
|
39
|
+
//# sourceMappingURL=shot-rows.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Workbook } from './cells.ts';
|
|
2
|
+
import { type ChronoImport, type ChronoParserOptions } from './result.ts';
|
|
3
|
+
import { type WorkbookOptions } from './worksheet-strings.ts';
|
|
4
|
+
/** A ShotView header row: first cell `#`, the velocity unit in brackets in the second. */
|
|
5
|
+
export declare const isShotViewHeader: (cells: string[]) => boolean;
|
|
6
|
+
/** Index of the `#` header row whose second cell names the velocity unit in brackets, or -1. */
|
|
7
|
+
export declare function shotViewHeaderIndex(lines: string[]): number;
|
|
8
|
+
/**
|
|
9
|
+
* Parses a ShotView CSV text into one session with one string; velocity unit from the header brackets.
|
|
10
|
+
*/
|
|
11
|
+
export declare function parseShotView(text: string, options?: ChronoParserOptions): ChronoImport;
|
|
12
|
+
/**
|
|
13
|
+
* Garmin Xero ShotView XLSX export: one session, one string per worksheet with a ShotView header
|
|
14
|
+
* row. The date row is found by its label, the first cell above the header.
|
|
15
|
+
*/
|
|
16
|
+
export declare function parseShotViewWorkbook(book: Workbook, options?: WorkbookOptions): ChronoImport;
|