@rangefoundry/catalog 0.0.0 → 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.
@@ -0,0 +1,294 @@
1
+ import { conversions, parseRef, } from '@rangefoundry/schema';
2
+ // * 1000, not / conversions.g.factor: the division lands one ulp below the exact 0.06479891 g
3
+ const grain = conversions.gr.factor * 1000;
4
+ const foot = conversions.ft.factor;
5
+ const psi = conversions.psi.factor / conversions.bar.factor;
6
+ const inch = conversions.in.factor / conversions.mm.factor;
7
+ const factors = {
8
+ mass: { g: 1, gr: grain, grs: grain, grain, grains: grain },
9
+ velocity: { 'm/s': 1, ms: 1, 'ft/s': foot, 'ft/sec': foot, fps: foot },
10
+ pressure: { bar: 1, psi },
11
+ length: { mm: 1, cm: 10, m: 1000, in: inch, '"': inch, '″': inch, inch, inches: inch },
12
+ };
13
+ /** The relative difference below which a stored value follows its printed number (7 significant digits). */
14
+ const tolerance = 1e-6;
15
+ /** The readings of a printed number: with commas as thousands marks, and with a comma as decimal mark. */
16
+ const readings = (text) => {
17
+ const plain = /^\.?\d+$|^\d+\.\d+$/.test(text) ? [Number(text)] : [];
18
+ const commas = /^\d{1,3}(,\d{3})+(\.\d+)?$/.test(text) ? [Number(text.replace(/,/g, ''))] : [];
19
+ const decimal = /^\d+,\d+$/.test(text) ? [Number(text.replace(',', '.'))] : [];
20
+ return [...plain, ...commas, ...decimal];
21
+ };
22
+ /** Some number printed in `raw`, read in the unit printed next to it (or the assumed unit for the first number), gives `value` to 7 significant digits; a text that prints no number or no known unit (`Flush`) is not checked, and a twist `1:12"` is its second number. */
23
+ function follows(kind, figure, twist) {
24
+ const table = factors[kind];
25
+ const text = twist ? figure.raw.replace(/^\s*1\s*(?:[:/-]|in\b)\s*/, '') : figure.raw;
26
+ const found = [...text.matchAll(/(\d[\d.,]*|\.\d+)\s*("|″|[A-Za-z]+(?:\/[A-Za-z]+)?)?/g)];
27
+ let known = false;
28
+ for (const [i, [, number, unit]] of found.entries()) {
29
+ const factor = table[(unit ?? (i === 0 ? figure.assumedUnit : undefined) ?? '').toLowerCase()];
30
+ if (factor === undefined)
31
+ continue;
32
+ known = true;
33
+ if (
34
+ // group 1 always takes part in a match
35
+ readings(number ?? '').some((n) => Math.abs(n * factor - figure.value) <= tolerance * Math.abs(figure.value)))
36
+ return true;
37
+ }
38
+ return !known;
39
+ }
40
+ /** The figure at `path`, none when it has no value. */
41
+ const figureAt = (path, kind, figure, twist = false) => figure.value === undefined
42
+ ? []
43
+ : [{ path, kind, twist, figure: { ...figure, value: figure.value } }];
44
+ /** The printed figures of charge `i` of a load. */
45
+ function chargeFigures(c, i) {
46
+ const distance = c.velocity?.point?.distance;
47
+ return [
48
+ ...figureAt(`charges.${i}.charge`, 'mass', c.charge),
49
+ ...(c.velocity ? figureAt(`charges.${i}.velocity`, 'velocity', c.velocity) : []),
50
+ ...(distance ? figureAt(`charges.${i}.velocity.point.distance`, 'length', distance) : []),
51
+ ...(c.pressure
52
+ ? figureAt(`charges.${i}.pressure.peak`, 'pressure', {
53
+ ...c.pressure.peak,
54
+ assumedUnit: c.pressure.peak.assumedUnit ?? c.pressure.unit,
55
+ })
56
+ : []),
57
+ ];
58
+ }
59
+ /** Every printed figure of a load with its path, quantity and whether it is a twist. */
60
+ function figures(l) {
61
+ const { diameter } = l.bullet;
62
+ const length = l.barrel?.length;
63
+ const twist = l.barrel?.twist;
64
+ return [
65
+ ...figureAt('bullet.mass', 'mass', l.bullet.mass),
66
+ ...(diameter ? figureAt('bullet.diameter', 'length', diameter) : []),
67
+ ...(l.coal ? figureAt('coal', 'length', l.coal) : []),
68
+ ...(length ? figureAt('barrel.length', 'length', length) : []),
69
+ ...(twist ? figureAt('barrel.twist', 'length', twist, true) : []),
70
+ ...l.charges.flatMap((c, i) => chargeFigures(c, i)),
71
+ ];
72
+ }
73
+ /** A pressure whose printed text names a unit other than its `unit`. */
74
+ function checkPressureUnits(l, where, errors) {
75
+ for (const [i, c] of l.charges.entries()) {
76
+ const p = c.pressure;
77
+ if (p && /[a-z]/i.test(p.peak.raw) && !p.peak.raw.toLowerCase().includes(p.unit.toLowerCase()))
78
+ errors.push(`${where}: loads ${l.id}: charges.${i}.pressure.unit ${p.unit} is not in "${p.peak.raw}"`);
79
+ }
80
+ }
81
+ /** The findings of one load's printed figures: a value that does not follow its printed text. */
82
+ function checkPrintedFigures(l, where, errors) {
83
+ for (const { path, kind, twist, figure } of figures(l))
84
+ if (!follows(kind, figure, twist))
85
+ errors.push(`${where}: loads ${l.id}: ${path}: value ${figure.value} does not follow "${figure.raw}"`);
86
+ }
87
+ /** The record id a reference names, or the reference as it is. */
88
+ const refId = (ref) => parseRef(ref)?.id ?? ref;
89
+ /** Where a printed primer size or magnum disagrees with the primer record it names. */
90
+ function primerDifferences(record, { size, magnum }) {
91
+ const found = [];
92
+ if (size !== undefined && size !== record.size)
93
+ found.push(`primer size ${size} differs from ${record.id} (${record.size})`);
94
+ // a primer record leaves magnum out when no source states it, which is not a disagreement
95
+ if (magnum !== undefined && record.magnum !== undefined && magnum !== record.magnum)
96
+ found.push(`primer magnum differs from ${record.id}`);
97
+ return found;
98
+ }
99
+ /** The primers of one load: each named record exists, and a printed size or magnum agrees with it. */
100
+ function checkLoadPrimers(l, where, known, errors) {
101
+ const { records = [], size, magnum } = l.primer ?? {};
102
+ for (const ref of records) {
103
+ const record = known.primers.get(refId(ref));
104
+ const messages = record
105
+ ? primerDifferences(record, { size, magnum })
106
+ : [`unknown primer "${ref}"`];
107
+ for (const message of messages)
108
+ errors.push(`${where}: loads ${l.id}: ${message}`);
109
+ }
110
+ }
111
+ /** The references of one load: bullet, powder and primers exist, and a printed size agrees with them. */
112
+ function checkLoadReferences(l, where, known, errors) {
113
+ const unknown = (field, ref) => errors.push(`${where}: loads ${l.id}: unknown ${field} "${ref}"`);
114
+ if (l.bullet.record !== undefined && !known.bullets.has(refId(l.bullet.record)))
115
+ unknown('bullet', l.bullet.record);
116
+ if (l.powder.record !== undefined && !known.powders.has(refId(l.powder.record)))
117
+ unknown('powder', l.powder.record);
118
+ checkLoadPrimers(l, where, known, errors);
119
+ }
120
+ /** Load ids are unique in their file and the loads are sorted by id, so a re-import edits in place. */
121
+ function checkLoadOrder(file, where, errors) {
122
+ const ids = file.loads.map((l) => l.id);
123
+ let previous;
124
+ for (const [i, id] of ids.entries()) {
125
+ if (ids.indexOf(id) !== i)
126
+ errors.push(`${where}: duplicate load id "${id}"`);
127
+ else if (previous !== undefined && previous > id)
128
+ errors.push(`${where}: load "${id}" is not in id order`);
129
+ previous = id;
130
+ }
131
+ }
132
+ /**
133
+ * The rules of published load files, each finding one error:
134
+ * - the folder is the file's cartridge, which exists;
135
+ * - the maker is a manufacturer record, and the file name is the maker's id (`<maker>-customer`
136
+ * for a table of loads customers sent);
137
+ * - the loads have unique ids and are sorted by them;
138
+ * - a bullet, powder or primer record a load names exists, and a printed primer size agrees with
139
+ * the records;
140
+ * - the value of a printed figure follows its printed text.
141
+ */
142
+ export function checkPublishedLoads(files, targets, errors) {
143
+ const known = {
144
+ cartridges: targets.cartridges,
145
+ manufacturers: targets.manufacturers,
146
+ bullets: new Set(targets.bullets.map((b) => b.id)),
147
+ powders: new Set(targets.powders.map((p) => p.id)),
148
+ primers: new Map(targets.primers.map((p) => [p.id, p])),
149
+ };
150
+ for (const { folder, file } of files) {
151
+ const where = `loads/${folder}/${file.id}.json`;
152
+ const cartridge = parseRef(file.cartridge)?.id ?? file.cartridge;
153
+ if (cartridge !== folder)
154
+ errors.push(`${where}: cartridge "${file.cartridge}" is not the folder "${folder}"`);
155
+ else if (!known.cartridges.has(cartridge))
156
+ errors.push(`${where}: unknown cartridge "${file.cartridge}"`);
157
+ if (!known.manufacturers.has(file.maker))
158
+ errors.push(`${where}: unknown maker "${file.maker}"`);
159
+ const name = file.producedBy === 'customer' ? `${file.maker}-customer` : file.maker;
160
+ if (file.id !== name)
161
+ errors.push(`${where}: a table produced by the ${file.producedBy} is named "${name}"`);
162
+ checkLoadOrder(file, where, errors);
163
+ for (const l of file.loads) {
164
+ checkLoadReferences(l, where, known, errors);
165
+ checkPrintedFigures(l, where, errors);
166
+ checkPressureUnits(l, where, errors);
167
+ }
168
+ }
169
+ }
170
+ /** The start and the max charge of a load, where it prints both. */
171
+ function startAndMax(l) {
172
+ const start = l.charges.find((c) => c.kind === 'start');
173
+ const max = l.charges.find((c) => c.kind === 'max');
174
+ return start && max ? [start, max] : undefined;
175
+ }
176
+ /** The largest value of `symbol` (any variant) of a cartridge record, where it has one. */
177
+ function largest(cartridge, symbol, side) {
178
+ const values = cartridge.values
179
+ .filter((v) => v.symbol === symbol && (side === undefined || v.side === side))
180
+ .flatMap((v) => (v.value === undefined ? [] : [v.value]));
181
+ return values.length > 0 ? Math.max(...values) : undefined;
182
+ }
183
+ /** Two printed distances agree where both are printed. */
184
+ const sameDistance = (d, e) => d === undefined || e === undefined || d === e;
185
+ /** Where two velocities apply: the same printed symbol (or none), and the same distance where both print one. */
186
+ function samePoint(a, b) {
187
+ const [p, q] = [a.point, b.point];
188
+ if (p?.label !== q?.label)
189
+ return false;
190
+ return sameDistance(p?.distance?.value, q?.distance?.value);
191
+ }
192
+ /** The start charge above the max charge. */
193
+ function chargeOrder(start, max) {
194
+ if (!(start.charge.value > max.charge.value))
195
+ return [];
196
+ return [
197
+ {
198
+ finding: 'start-above-max',
199
+ message: `the start charge ${start.charge.raw} is above the max charge ${max.charge.raw}`,
200
+ },
201
+ ];
202
+ }
203
+ /** The velocity of the max charge below that of the start charge, at the same point. */
204
+ function velocityOrder(start, max) {
205
+ const [v, w] = [start.velocity, max.velocity];
206
+ if (!v || !w || !samePoint(v, w) || !(w.value < v.value))
207
+ return [];
208
+ return [
209
+ {
210
+ finding: 'velocity-order',
211
+ message: `the velocity of the max charge, ${w.raw}, is below that of the start charge, ${v.raw}`,
212
+ },
213
+ ];
214
+ }
215
+ /** The pressure of the max charge below that of the start charge, on the same unit and method. */
216
+ function pressureOrder(start, max) {
217
+ const [p, q] = [start.pressure, max.pressure];
218
+ if (p?.peak.value === undefined || q?.peak.value === undefined)
219
+ return [];
220
+ if (p.unit !== q.unit || p.method !== q.method || !(q.peak.value < p.peak.value))
221
+ return [];
222
+ return [
223
+ {
224
+ finding: 'pressure-order',
225
+ message: `the pressure of the max charge, ${q.peak.raw}, is below that of the start charge, ${p.peak.raw}`,
226
+ },
227
+ ];
228
+ }
229
+ /** The order findings of a load's start and max charge: charge, velocity and pressure. */
230
+ function orderFindings(l) {
231
+ const pair = startAndMax(l);
232
+ if (!pair)
233
+ return [];
234
+ const [start, max] = pair;
235
+ return [...chargeOrder(start, max), ...velocityOrder(start, max), ...pressureOrder(start, max)];
236
+ }
237
+ /** The pressures on the cartridge record's own basis above its largest Pmax. */
238
+ function pressureAboveMax(l, cartridge) {
239
+ const pmax = largest(cartridge, 'Pmax');
240
+ const method = cartridge.pressureMethod;
241
+ // only a value on the record's own basis; no value is converted between bases
242
+ if (pmax === undefined || method === undefined)
243
+ return [];
244
+ return l.charges.flatMap((c) => {
245
+ const p = c.pressure;
246
+ // a case-contact gauge reads on its own basis: Pmax is not its limit (#855)
247
+ if (p?.peak.value === undefined || p.method !== method || p.method === 'case-contact')
248
+ return [];
249
+ if (!(p.peak.value > pmax))
250
+ return [];
251
+ return [
252
+ {
253
+ finding: 'pressure-above-cartridge-max',
254
+ message: `the ${c.kind} pressure ${p.peak.raw} (${p.method}) is above Pmax ${pmax} bar of ${cartridge.id}`,
255
+ },
256
+ ];
257
+ });
258
+ }
259
+ /** COAL above the cartridge record's largest L6. */
260
+ function coalAboveMax(l, cartridge) {
261
+ const l6 = largest(cartridge, 'L6', 'cartridge');
262
+ if (l6 === undefined || l.coal?.value === undefined || !(l.coal.value > l6))
263
+ return [];
264
+ return [
265
+ {
266
+ finding: 'coal-above-cartridge-max',
267
+ message: `COAL ${l.coal.raw} is above L6 ${l6} mm of ${cartridge.id}`,
268
+ },
269
+ ];
270
+ }
271
+ /** The findings of a load against its cartridge record: pressure above Pmax, COAL above L6. */
272
+ function cartridgeFindings(l, cartridge) {
273
+ return [...pressureAboveMax(l, cartridge), ...coalAboveMax(l, cartridge)];
274
+ }
275
+ /**
276
+ * The plausibility findings of a published load file, each a warning: a printed value that looks
277
+ * wrong is still the maker's value and stays as printed. Findings:
278
+ * - `start-above-max`: the start charge is above the max charge of the same load;
279
+ * - `velocity-order`: the velocity of the max charge is below that of the start charge (same point);
280
+ * - `pressure-order`: the pressure of the max charge is below that of the start charge (same unit
281
+ * and method, both with a value in bar);
282
+ * - `pressure-above-cartridge-max`: a pressure with a value in bar whose method is the cartridge
283
+ * record's `pressureMethod` is above the record's largest `Pmax`. Other methods, and case-contact
284
+ * pressure always, are not compared: no value is converted between pressure bases;
285
+ * - `coal-above-cartridge-max`: COAL above the record's largest `L6` (maximum cartridge length).
286
+ * Without a cartridge record only the order findings apply.
287
+ */
288
+ export function checkPublishedLoadPlausibility(file, cartridge) {
289
+ return file.loads.flatMap((l) => [...orderFindings(l), ...(cartridge ? cartridgeFindings(l, cartridge) : [])].map((f) => ({
290
+ ...f,
291
+ load: l.id,
292
+ })));
293
+ }
294
+ //# sourceMappingURL=published-loads.js.map
@@ -0,0 +1,40 @@
1
+ import type { Bullet, CaliberClass, Cartridge, CatalogueCase, CatalogueCaseCapacity, CatalogueLoad, CatalogueSession, Discipline, EventType, Federation, FiringSeries, LoadTables, Manufacturer, Powder, Primer, RangeFirings, TargetFace, TargetMapping } from '@rangefoundry/schema';
2
+ import { type LocatedPublishedLoads } from './published-loads.ts';
3
+ /** The records of a records root, one array per kind. */
4
+ export type Bundle = {
5
+ cartridges: Cartridge[];
6
+ caliberClasses: CaliberClass[];
7
+ manufacturers: Manufacturer[];
8
+ powders: Powder[];
9
+ primers: Primer[];
10
+ bullets: Bullet[];
11
+ cases: CatalogueCase[];
12
+ capacities: CatalogueCaseCapacity[];
13
+ loads: CatalogueLoad[];
14
+ chronoSessions: CatalogueSession[];
15
+ firings: FiringSeries[];
16
+ rangeFirings: RangeFirings[];
17
+ targetFaces: TargetFace[];
18
+ federations: Federation[];
19
+ disciplines: Discipline[];
20
+ targetMappings: TargetMapping[];
21
+ /** Event types of competitions (`records/event-types/`); absent: none. */
22
+ eventTypes?: EventType[] | undefined;
23
+ };
24
+ /** What the checks of {@link checkRecords} take: the records, the published load files and the load tables. */
25
+ export type RecordsRead = {
26
+ bundle: Bundle;
27
+ published: LocatedPublishedLoads[];
28
+ /** Absent when no records root has a `load-tables.json`, as in the public catalog. */
29
+ loadTables: LoadTables | undefined;
30
+ /** Whether the records come from one root, so a cartridge with a capacity that is no estimate has to name its default. */
31
+ singleRoot: boolean;
32
+ };
33
+ /**
34
+ * Cross-checks records read from a records root. Valid data has no errors; the warnings are
35
+ * plausibility findings that do not fail validation, as a published load stays as printed.
36
+ */
37
+ export declare function checkRecords({ bundle, published, loadTables, singleRoot }: RecordsRead): {
38
+ errors: string[];
39
+ warnings: string[];
40
+ };
@@ -0,0 +1,160 @@
1
+ import { parseRef } from '@rangefoundry/schema';
2
+ import { checkCaliberClasses } from './caliber-classes.js';
3
+ import { checkCoverage } from './coverage.js';
4
+ import { checkEventTypes } from './event-types.js';
5
+ import { checkFederations } from './federations.js';
6
+ import { checkFittedSources } from './load-tables.js';
7
+ import { checkNames } from './names.js';
8
+ import { checkBullet, checkCapacity, checkCase, checkChronoSession, checkPowder, checkSpec, } from './plausibility.js';
9
+ import { checkPublishedLoadPlausibility, checkPublishedLoads, } from './published-loads.js';
10
+ import { checkCartridgeReferences, checkDefaultCapacityReferences, checkLoadCapacityReferences, checkLoadCaseReferences, checkLoadComponentReferences, checkLoadPrimerReferences, checkLoadReferences, checkLoadSessionReferences, checkManufacturerReferences, recordIds, } from './references.js';
11
+ /** A value may appear once per side, symbol and variant. */
12
+ function checkSpecValues(spec, errors) {
13
+ const seen = new Set();
14
+ for (const value of spec.values) {
15
+ const key = `${value.side ?? '-'} ${value.symbol} ${value.variant ?? '-'}`;
16
+ if (seen.has(key))
17
+ errors.push(`cartridges/${spec.id}.json: duplicate value ${key}`);
18
+ seen.add(key);
19
+ }
20
+ }
21
+ /** Every plausibility finding of the sheet is in its `exceptions`, and every exception still occurs. */
22
+ function applyExceptions(spec, errors) {
23
+ const where = `cartridges/${spec.id}.json`;
24
+ const findings = checkSpec(spec);
25
+ const acknowledged = new Set(spec.exceptions?.map((e) => e.finding));
26
+ for (const finding of findings) {
27
+ if (!acknowledged.has(finding.finding)) {
28
+ errors.push(`${where}: ${finding.finding}: ${finding.message}`);
29
+ }
30
+ }
31
+ const found = new Set(findings.map((f) => f.finding));
32
+ for (const exception of spec.exceptions ?? []) {
33
+ if (!found.has(exception.finding)) {
34
+ errors.push(`${where}: exception "${exception.finding}" no longer applies; remove it`);
35
+ }
36
+ }
37
+ }
38
+ /** Every field of the source-backed kinds that needs a source has one, bullets, powders and manufacturers by their field classes; the third-party kinds have provenance. */
39
+ function checkSourceCoverage(bundle, errors) {
40
+ const check = (dir, records, kind) => {
41
+ for (const record of records) {
42
+ for (const error of checkCoverage(record, kind))
43
+ errors.push(`${dir}/${record.id}.json: ${error}`);
44
+ }
45
+ };
46
+ check('manufacturers', bundle.manufacturers, 'manufacturer');
47
+ check('powders', bundle.powders, 'powder');
48
+ check('bullets', bundle.bullets, 'bullet');
49
+ for (const [dir, records] of [
50
+ ['caliber-classes', bundle.caliberClasses],
51
+ ['primers', bundle.primers],
52
+ ['cases', bundle.cases],
53
+ ['capacities', bundle.capacities],
54
+ ['federations', bundle.federations],
55
+ ['disciplines', bundle.disciplines],
56
+ ['target-mappings', bundle.targetMappings],
57
+ ['event-types', bundle.eventTypes ?? []],
58
+ ])
59
+ check(dir, records);
60
+ // permanent rule: these kinds hold third-party data and need provenance; chrono sessions need provenance too
61
+ for (const [dir, records] of [
62
+ ['cartridges', bundle.cartridges],
63
+ ['loads', bundle.loads],
64
+ ['chrono', bundle.chronoSessions],
65
+ ['firings', bundle.firings],
66
+ ['range', bundle.rangeFirings],
67
+ ['target-faces', bundle.targetFaces],
68
+ ]) {
69
+ for (const record of records)
70
+ if (!record.provenance)
71
+ errors.push(`${dir}/${record.id}.json: needs provenance`);
72
+ }
73
+ }
74
+ /** The same round number of the same report (its one source, by sha256) in two range records is a copy error, as a round belongs to one projectile. */
75
+ function checkRangeRounds(records, errors) {
76
+ const roundOwner = new Map();
77
+ for (const r of records) {
78
+ const report = r.provenance?.sources[0]?.sha256;
79
+ if (!report)
80
+ continue;
81
+ for (const { label: round } of r.rounds) {
82
+ // The base round number: a split reduction "(a)" or a yaw-card mark "*" is part of one round.
83
+ const key = `${report} ${round.replace(/\(.\)|\*/g, '')}`;
84
+ const owner = roundOwner.get(key);
85
+ if (owner && owner !== r.id) {
86
+ errors.push(`range/${r.id}.json: round ${round} is also in ${owner}`);
87
+ }
88
+ else
89
+ roundOwner.set(key, r.id);
90
+ }
91
+ }
92
+ }
93
+ /** The findings of the record `<dir>/<id>.json`. */
94
+ const located = (dir, id, findings) => findings.map((f) => ({ file: `${dir}/${id}.json`, ...f }));
95
+ /** The findings of duplicate names, cases, capacities, powders and sessions; each is an error. */
96
+ function collectFindings(bundle, cartridges) {
97
+ const cartridgeOf = (ref) => cartridges.get(parseRef(ref)?.id ?? ref);
98
+ return [
99
+ ...checkNames(bundle),
100
+ ...bundle.capacities.flatMap((c) => located('capacities', c.id, checkCapacity(c, cartridgeOf(c.cartridge)))),
101
+ ...bundle.cases.flatMap((c) => located('cases', c.id, checkCase(c, cartridgeOf(c.cartridge)))),
102
+ ...bundle.powders.flatMap((p) => located('powders', p.id, checkPowder(p))),
103
+ ...bundle.chronoSessions.flatMap((s) => located('chrono', s.id, checkChronoSession(s))),
104
+ ];
105
+ }
106
+ /** The references between records: cartridges, manufacturers, range rounds, loads and their parts. */
107
+ function checkReferences(bundle, ids, loadTables, errors) {
108
+ checkCartridgeReferences(bundle, ids, errors);
109
+ checkManufacturerReferences(bundle, loadTables, ids, errors);
110
+ checkRangeRounds(bundle.rangeFirings, errors);
111
+ checkLoadReferences(bundle, ids, errors);
112
+ checkLoadComponentReferences(bundle, errors);
113
+ checkLoadPrimerReferences(bundle, errors);
114
+ checkLoadCapacityReferences(bundle, errors);
115
+ checkLoadCaseReferences(bundle, ids, errors);
116
+ checkLoadSessionReferences(bundle, errors);
117
+ }
118
+ /**
119
+ * Cross-checks records read from a records root. Valid data has no errors; the warnings are
120
+ * plausibility findings that do not fail validation, as a published load stays as printed.
121
+ */
122
+ export function checkRecords({ bundle, published, loadTables, singleRoot }) {
123
+ const errors = [];
124
+ const ids = recordIds(bundle);
125
+ for (const c of bundle.cartridges) {
126
+ checkSpecValues(c, errors);
127
+ applyExceptions(c, errors);
128
+ }
129
+ checkSourceCoverage(bundle, errors);
130
+ // a published-load file holds third-party data and needs provenance, the permanent rule beside the kinds in checkSourceCoverage
131
+ for (const { folder, file } of published)
132
+ if (!file.provenance)
133
+ errors.push(`loads/${folder}/${file.id}.json: needs provenance`);
134
+ errors.push(...checkFederations(bundle));
135
+ errors.push(...checkEventTypes(bundle));
136
+ errors.push(...checkCaliberClasses(bundle));
137
+ for (const p of bundle.powders) {
138
+ for (const error of checkFittedSources(p, loadTables))
139
+ errors.push(`powders/${p.id}.json: ${error}`);
140
+ }
141
+ for (const b of bundle.bullets) {
142
+ for (const f of checkBullet(b))
143
+ errors.push(`bullets/${b.id}.json: ${f.finding}: ${f.message}`);
144
+ }
145
+ checkReferences(bundle, ids, loadTables, errors);
146
+ checkDefaultCapacityReferences(bundle, singleRoot, errors);
147
+ checkPublishedLoads(published, {
148
+ cartridges: ids.cartridges,
149
+ manufacturers: ids.manufacturers,
150
+ bullets: bundle.bullets,
151
+ powders: bundle.powders,
152
+ primers: bundle.primers,
153
+ }, errors);
154
+ const cartridges = new Map(bundle.cartridges.map((c) => [c.id, c]));
155
+ for (const f of collectFindings(bundle, cartridges))
156
+ errors.push(`${f.file}: ${f.finding}: ${f.message}`);
157
+ const warnings = published.flatMap(({ folder, file }) => checkPublishedLoadPlausibility(file, cartridges.get(folder)).map((f) => `loads/${folder}/${file.id}.json: loads ${f.load}: ${f.finding}: ${f.message}`));
158
+ return { errors, warnings };
159
+ }
160
+ //# sourceMappingURL=records.js.map
@@ -0,0 +1,30 @@
1
+ import type { LoadTables } from './load-tables.ts';
2
+ import type { Bundle } from './records.ts';
3
+ /** The ids a record may reference, by kind. */
4
+ type RecordIds = {
5
+ cartridges: Set<string>;
6
+ cases: Set<string>;
7
+ loads: Set<string>;
8
+ manufacturers: Set<string>;
9
+ };
10
+ /** The ids of the referenced kinds in `bundle`. */
11
+ export declare function recordIds(bundle: Pick<Bundle, 'cartridges' | 'cases' | 'loads' | 'manufacturers'>): RecordIds;
12
+ /** The cartridge of every case, capacity, load and firing series, and the cartridges a powder is listed for. */
13
+ export declare function checkCartridgeReferences(bundle: Pick<Bundle, 'cartridges' | 'cases' | 'capacities' | 'loads' | 'firings' | 'powders'>, ids: RecordIds, errors: string[]): void;
14
+ /** The bullet and powder of every load that names a record. */
15
+ export declare function checkLoadComponentReferences(bundle: Pick<Bundle, 'loads' | 'bullets' | 'powders'>, errors: string[]): void;
16
+ /** The primer of every load that names one. */
17
+ export declare function checkLoadPrimerReferences(bundle: Pick<Bundle, 'loads' | 'primers'>, errors: string[]): void;
18
+ /** The capacity of every load that names one. */
19
+ export declare function checkLoadCapacityReferences(bundle: Pick<Bundle, 'loads' | 'capacities'>, errors: string[]): void;
20
+ /** The default capacity of every cartridge is a published or measured capacity of it; from a single root, a cartridge with a capacity that is no estimate names one. */
21
+ export declare function checkDefaultCapacityReferences(bundle: Pick<Bundle, 'cartridges' | 'capacities'>, singleRoot: boolean, errors: string[]): void;
22
+ /** The case record of every load that names one: it exists and is a case of the load's cartridge. */
23
+ export declare function checkLoadCaseReferences(bundle: Pick<Bundle, 'loads' | 'cases'>, ids: RecordIds, errors: string[]): void;
24
+ /** The session of every load that names one. */
25
+ export declare function checkLoadSessionReferences(bundle: Pick<Bundle, 'loads' | 'chronoSessions'>, errors: string[]): void;
26
+ /** The load of every shot string of a chronograph session. */
27
+ export declare function checkLoadReferences(bundle: Pick<Bundle, 'chronoSessions'>, ids: RecordIds, errors: string[]): void;
28
+ /** Of every powder (and of its burn-rate charts), primer, bullet, case and listed load table, the case manufacturer of a capacity, the device manufacturer of a chronograph session and the manufacturers a load names (a described bullet or powder and the case). */
29
+ export declare function checkManufacturerReferences(bundle: Pick<Bundle, 'powders' | 'primers' | 'bullets' | 'cases' | 'capacities' | 'chronoSessions' | 'loads'>, loadTables: LoadTables | undefined, ids: RecordIds, errors: string[]): void;
30
+ export {};