@rangefoundry/importers 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.
Files changed (55) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +20 -1
  3. package/dist/cells.d.ts +31 -0
  4. package/dist/cells.js +22 -0
  5. package/dist/cfb.d.ts +2 -0
  6. package/dist/cfb.js +196 -0
  7. package/dist/csrload.d.ts +12 -0
  8. package/dist/csrload.js +153 -0
  9. package/dist/diagnostics.d.ts +42 -0
  10. package/dist/diagnostics.js +29 -0
  11. package/dist/generic.d.ts +44 -0
  12. package/dist/generic.js +272 -0
  13. package/dist/grtload.d.ts +32 -0
  14. package/dist/grtload.js +264 -0
  15. package/dist/index.d.ts +85 -0
  16. package/dist/index.js +126 -0
  17. package/dist/limits.d.ts +7 -0
  18. package/dist/limits.js +12 -0
  19. package/dist/pressure-history.d.ts +61 -0
  20. package/dist/pressure-history.js +158 -0
  21. package/dist/rangefoundry-json.d.ts +17 -0
  22. package/dist/rangefoundry-json.js +176 -0
  23. package/dist/record-fields.d.ts +35 -0
  24. package/dist/record-fields.js +190 -0
  25. package/dist/record-ids.d.ts +2 -0
  26. package/dist/record-ids.js +28 -0
  27. package/dist/records.d.ts +91 -0
  28. package/dist/records.js +433 -0
  29. package/dist/result.d.ts +65 -0
  30. package/dist/result.js +90 -0
  31. package/dist/shot-rows.d.ts +11 -0
  32. package/dist/shot-rows.js +39 -0
  33. package/dist/shotview.d.ts +16 -0
  34. package/dist/shotview.js +131 -0
  35. package/dist/statistics.d.ts +12 -0
  36. package/dist/statistics.js +48 -0
  37. package/dist/tables.d.ts +41 -0
  38. package/dist/tables.js +277 -0
  39. package/dist/template.d.ts +13 -0
  40. package/dist/template.js +37 -0
  41. package/dist/text.d.ts +28 -0
  42. package/dist/text.js +150 -0
  43. package/dist/units.d.ts +12 -0
  44. package/dist/units.js +62 -0
  45. package/dist/workbook.d.ts +12 -0
  46. package/dist/workbook.js +264 -0
  47. package/dist/worksheet-strings.d.ts +36 -0
  48. package/dist/worksheet-strings.js +50 -0
  49. package/dist/xls.d.ts +3 -0
  50. package/dist/xls.js +486 -0
  51. package/dist/xml.d.ts +26 -0
  52. package/dist/xml.js +261 -0
  53. package/dist/zip.d.ts +27 -0
  54. package/dist/zip.js +183 -0
  55. package/package.json +58 -4
@@ -0,0 +1,131 @@
1
+ import { refuse } from './diagnostics.js';
2
+ import { buildChronoImport } from './result.js';
3
+ import { readShotRows, workbookFooterStarts } from './shot-rows.js';
4
+ import { warnStatistics } from './statistics.js';
5
+ import { bracketed, isoDate, joinQuotedLines, parseNumber, splitDelimited, splitLines, withoutTrailingCommas, } from './text.js';
6
+ import { resolveUnit } from './units.js';
7
+ import { collectWorksheetStrings, } from './worksheet-strings.js';
8
+ /** A ShotView header row: first cell `#`, the velocity unit in brackets in the second. */
9
+ export const isShotViewHeader = (cells) => cells[0] === '#' && bracketed(cells[1] ?? '') !== undefined;
10
+ /** Index of the `#` header row whose second cell names the velocity unit in brackets, or -1. */
11
+ export function shotViewHeaderIndex(lines) {
12
+ return lines.findIndex((line) => isShotViewHeader(splitDelimited(line)));
13
+ }
14
+ const months = {};
15
+ for (const names of [
16
+ 'january february march april may june july august september october november december',
17
+ 'januar februar m\u00E4rz april mai juni juli august september oktober november dezember',
18
+ ]) {
19
+ names.split(' ').forEach((name, i) => {
20
+ months[name] = i + 1;
21
+ });
22
+ }
23
+ /** Footer dates such as `April 6, 2026 at 1:36 PM` or `8. Februar 2026 um 10:08`; English and German month names only. */
24
+ function footerDate(text) {
25
+ const words = text
26
+ .replace(/\d{1,2}:\d{2}(:\d{2})?/g, ' ')
27
+ .toLowerCase()
28
+ .match(/\p{L}+|\d+/gu) ?? [];
29
+ const month = words.map((w) => months[w]).find((m) => m !== undefined);
30
+ const year = words.find((w) => /^\d{4}$/.test(w));
31
+ const day = words.find((w) => /^\d{1,2}$/.test(w));
32
+ return month && year && day ? isoDate(Number(year), month, Number(day)) : undefined;
33
+ }
34
+ const footerLabels = [
35
+ ['AVERAGE SPEED'],
36
+ ['STD DEV', 'STANDARDABWEICHUNG'],
37
+ ['SPREAD', 'STREUUNG'],
38
+ ];
39
+ /**
40
+ * Parses a ShotView CSV text into one session with one string; velocity unit from the header brackets.
41
+ */
42
+ export function parseShotView(text, options = {}) {
43
+ const lines = splitLines(text);
44
+ const h = shotViewHeaderIndex(lines);
45
+ const headerLine = lines[h];
46
+ if (headerLine === undefined)
47
+ refuse('notShotView');
48
+ const warnings = [];
49
+ const unitText = bracketed(splitDelimited(headerLine)[1] ?? '');
50
+ const unit = resolveUnit(unitText, options, warnings);
51
+ const nameLine = lines.slice(0, h).find((l) => l.trim()) ?? '';
52
+ const name = nameLine.trim().startsWith('"')
53
+ ? splitDelimited(nameLine)[0]
54
+ : withoutTrailingCommas(nameLine).trim();
55
+ // only rows after the header can hold quoted line breaks; blank lines become empty rows
56
+ const rows = joinQuotedLines(lines.slice(h + 1), ',').map(({ text: row }) => row.trim() ? splitDelimited(row) : []);
57
+ // the first `-` row ends the shots
58
+ const { shots, values, flags, footer } = readShotRows(rows, unitText, unit, (c) => c[0] === '-');
59
+ const date = dateFromFooter(footer, warnings);
60
+ checkFooter(footer, values, warnings);
61
+ return buildChronoImport('shotview-csv', {
62
+ ...(date ? { date } : {}),
63
+ device: { kind: 'doppler-radar', manufacturerName: 'Garmin' },
64
+ strings: shots.length > 0 ? [{ shots }] : [],
65
+ ...(flags.length > 0 ? { note: `ShotView bore flags: ${flags.join('; ')}` } : {}),
66
+ }, { labels: [name || undefined], warnings }, options);
67
+ }
68
+ /** The date row follows the last `-` row; its label depends on the phone's language. */
69
+ function dateFromFooter(footer, warnings) {
70
+ const dash = footer.findLastIndex((cells) => cells[0] === '-');
71
+ const text = dash < 0 ? undefined : footer[dash + 1]?.[1];
72
+ if (!text)
73
+ return undefined;
74
+ const date = footerDate(text);
75
+ if (!date)
76
+ warnings.push({ code: 'footerDateUnknown', params: { text } });
77
+ return date;
78
+ }
79
+ /** Footer statistics against the shots, as warnings; `at` names the worksheet. */
80
+ function checkFooter(footer, values, warnings, at = {}) {
81
+ warnStatistics({ rows: footer, rowLabels: footerLabels, readNumber: parseNumber }, values, {
82
+ warnings,
83
+ at,
84
+ });
85
+ }
86
+ const dateLabels = ['DATE', 'DATUM'];
87
+ /**
88
+ * Garmin Xero ShotView XLSX export: one session, one string per worksheet with a ShotView header
89
+ * row. The date row is found by its label, the first cell above the header.
90
+ */
91
+ export function parseShotViewWorkbook(book, options = {}) {
92
+ const warnings = [];
93
+ const found = [];
94
+ book.worksheets.forEach((sheet, k) => {
95
+ const n = k + 1;
96
+ const h = sheet.rows.findIndex(isShotViewHeader);
97
+ const headerCells = sheet.rows[h];
98
+ if (headerCells === undefined) {
99
+ warnings.push({ code: 'noShotViewHeader', params: { worksheet: n } });
100
+ return;
101
+ }
102
+ const after = sheet.rows.slice(h + 1);
103
+ const dateRow = after.find((cells) => dateLabels.includes((cells[0] ?? '').toUpperCase()));
104
+ const date = footerDate(dateRow?.[1] ?? '');
105
+ const dateWarning = !dateRow
106
+ ? { code: 'footerDateMissing', params: { worksheet: n } }
107
+ : { code: 'footerDateUnknown', params: { worksheet: n, text: dateRow[1] ?? '' } };
108
+ found.push({
109
+ position: n,
110
+ ...(date ? { date } : { dateWarning }),
111
+ read: (sheetWarnings) => {
112
+ const unitText = bracketed(headerCells[1] ?? '');
113
+ const unit = resolveUnit(unitText, options, sheetWarnings);
114
+ const r = readShotRows(after, unitText, unit, workbookFooterStarts);
115
+ if (r.shots.length === 0)
116
+ return undefined;
117
+ checkFooter(r.footer, r.values, sheetWarnings, { worksheet: n });
118
+ const label = sheet.rows.slice(0, h).flat().find(Boolean) || sheet.name;
119
+ return { shots: r.shots, flags: r.flags, label };
120
+ },
121
+ });
122
+ });
123
+ const s = collectWorksheetStrings(found, options, warnings);
124
+ return buildChronoImport('shotview-xlsx', {
125
+ ...(s.date ? { date: s.date } : {}),
126
+ device: { kind: 'doppler-radar', manufacturerName: 'Garmin' },
127
+ strings: s.strings,
128
+ ...(s.flags.length > 0 ? { note: `ShotView bore flags: ${s.flags.join('; ')}` } : {}),
129
+ }, { labels: s.labels, warnings }, options);
130
+ }
131
+ //# sourceMappingURL=shotview.js.map
@@ -0,0 +1,12 @@
1
+ import type { ChronoDiagnostic } from './diagnostics.ts';
2
+ /** Per printed footer statistics row (`compareStatistics`) that is not a number or differs from the shots, each with the params of `at`, and once when no row is found; no warning without values. */
3
+ export declare function warnStatistics({ rows, rowLabels, readNumber, }: {
4
+ rows: string[][];
5
+ rowLabels: [string[], string[], string[]];
6
+ readNumber: (cell: string) => number;
7
+ }, values: number[], { warnings, at }: {
8
+ warnings: ChronoDiagnostic[];
9
+ at: {
10
+ worksheet?: number;
11
+ };
12
+ }): void;
@@ -0,0 +1,48 @@
1
+ // printed statistics come from unrounded device values; shots are printed to 0.1
2
+ const statisticsTolerance = 0.2;
3
+ /** Population standard deviation (divides by n, as the devices print it); `values` must not be empty. */
4
+ function shotStatistics(values) {
5
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
6
+ const standardDeviation = Math.sqrt(values.reduce((a, v) => a + (v - mean) ** 2, 0) / values.length);
7
+ const extremeSpread = values.reduce((a, b) => Math.max(a, b), Number.NEGATIVE_INFINITY) -
8
+ values.reduce((a, b) => Math.min(a, b), Number.POSITIVE_INFINITY);
9
+ return { mean, standardDeviation, extremeSpread };
10
+ }
11
+ /** Against the printed values in the rows labeled (upper case) `rowLabels[0]`, `rowLabels[1]` and `rowLabels[2]`, as read by `readNumber`. */
12
+ function compareStatistics(rows, values, rowLabels, readNumber) {
13
+ const { mean, standardDeviation, extremeSpread } = shotStatistics(values);
14
+ const compared = [
15
+ [mean, rowLabels[0]],
16
+ [standardDeviation, rowLabels[1]],
17
+ [extremeSpread, rowLabels[2]],
18
+ ];
19
+ return compared.flatMap(([computed, labels]) => {
20
+ const row = rows.find((cells) => labels.includes((cells[0] ?? '').toUpperCase()));
21
+ if (!row)
22
+ return [];
23
+ const printed = readNumber(row[1] ?? '');
24
+ const unreadable = Number.isNaN(printed);
25
+ const withinTolerance = !unreadable && Math.abs(printed - computed) <= statisticsTolerance;
26
+ return [{ row, computed, withinTolerance, unreadable }];
27
+ });
28
+ }
29
+ /** Per printed footer statistics row (`compareStatistics`) that is not a number or differs from the shots, each with the params of `at`, and once when no row is found; no warning without values. */
30
+ export function warnStatistics({ rows, rowLabels, readNumber, }, values, { warnings, at }) {
31
+ if (values.length === 0)
32
+ return;
33
+ const checks = compareStatistics(rows, values, rowLabels, readNumber);
34
+ for (const { row, computed, withinTolerance, unreadable } of checks) {
35
+ const printed = { ...at, label: row[0] ?? '', value: row[1] ?? '' };
36
+ if (unreadable)
37
+ warnings.push({ code: 'statisticNotNumber', params: printed });
38
+ else if (!withinTolerance) {
39
+ warnings.push({
40
+ code: 'statisticDiffers',
41
+ params: { ...printed, computed },
42
+ });
43
+ }
44
+ }
45
+ if (checks.length === 0)
46
+ warnings.push({ code: 'footerStatisticsMissing', params: at });
47
+ }
48
+ //# sourceMappingURL=statistics.js.map
@@ -0,0 +1,41 @@
1
+ import type { ReaderDiagnostic } from './diagnostics.ts';
2
+ /** A table of cell text: the header and the data rows. */
3
+ export interface Table {
4
+ /** Header cells, or `Column A`, `Column B`, ... when the first row holds numbers. */
5
+ header: string[];
6
+ hasHeader: boolean;
7
+ /** Data rows of cell text, each as long as the header. */
8
+ rows: string[][];
9
+ }
10
+ /**
11
+ * Why a text or rows are no table: below two columns, more than `max` columns or cells, a header
12
+ * without rows, JSON that does not parse or is no list of objects, or no delimiter. The app words it.
13
+ */
14
+ export type TableReadDiagnostic = ReaderDiagnostic<'noTwoColumns' | 'tooManyColumns' | 'tooManyCells' | 'headerOnly' | 'jsonMalformed' | 'jsonNotTable' | 'noDelimiter'>;
15
+ /** A table, or the refusal that says why the input is none. */
16
+ export type TableRead = {
17
+ table: Table;
18
+ } | {
19
+ refusal: TableReadDiagnostic;
20
+ };
21
+ /**
22
+ * A table from rows of cell text, such as the rows of a worksheet; the first row is the header
23
+ * unless most of its cells are numbers. Refused below two columns or without data rows.
24
+ */
25
+ export declare function tableOfRows(raw: string[][]): TableRead;
26
+ /**
27
+ * The table of a text: a JSON list of objects, or delimited text (comma, semicolon or tab) with
28
+ * two or more rows of equal width. Otherwise the refusal's code names the cause.
29
+ */
30
+ export declare function readTable(raw: string): TableRead;
31
+ /** The header as words: lower case, accents and umlauts folded, units in brackets removed. */
32
+ export declare function headerWords(header: string): string[];
33
+ /** The unit word a header carries in brackets or after a slash, underscore or space, lower case; undefined for none. */
34
+ export declare function headerUnit(header: string): string | undefined;
35
+ /** A number in text with `decimal` as its mark: spaces and the other mark are grouping. Undefined for no finite number. */
36
+ export declare function readNumber(text: string, decimal: '.' | ','): number | undefined;
37
+ /** The decimal mark of a column from its cells, and whether a cell could also read as a grouped integer. */
38
+ export declare function guessDecimal(cells: string[]): {
39
+ decimal: '.' | ',';
40
+ ambiguous: boolean;
41
+ };
package/dist/tables.js ADDED
@@ -0,0 +1,277 @@
1
+ // Tables out of delimited text, JSON lists and worksheet rows: cell text, the header row, numbers in either decimal mark.
2
+ import { maxCells, maxColumn } from './limits.js';
3
+ const refused = (code, params = {}) => ({ refusal: { code, params } });
4
+ /** The text of a quoted cell from `from`, after its opening quote, and the position after its closing quote (`""` is a quote). */
5
+ function readQuoted(text, from) {
6
+ let cell = '';
7
+ let i = from;
8
+ while (i < text.length) {
9
+ const c = text.charAt(i);
10
+ if (c === '"' && text.charAt(i + 1) === '"') {
11
+ cell += '"';
12
+ i += 2;
13
+ }
14
+ else if (c === '"')
15
+ return { cell, next: i + 1 };
16
+ else {
17
+ cell += c;
18
+ i++;
19
+ }
20
+ }
21
+ return { cell, next: i };
22
+ }
23
+ const spaceOrTab = /^[ \t]$/;
24
+ const isBlank = (row) => row.every((x) => x.trim() === '');
25
+ /** The length of the line break at `i`: 2 for CR LF, else 1. */
26
+ const lineBreakLength = (text, i) => text.charAt(i) === '\r' && text.charAt(i + 1) === '\n' ? 2 : 1;
27
+ /** A quoted cell may follow spaces and span lines, blank rows are left out; cells past `maxColumn + 1` in a row are dropped and splitting stops past `maxCells` cells, enough for the size refusal. */
28
+ function splitRows(text, delimiter) {
29
+ const rows = [];
30
+ let row = [];
31
+ let cell = '';
32
+ // Whether `cell` holds only spaces and tabs, kept as it grows so a quote does not rescan it.
33
+ let blank = true;
34
+ let cells = 0;
35
+ let droppedFilled = false;
36
+ let i = 0;
37
+ const endCell = () => {
38
+ if (row.length <= maxColumn)
39
+ row.push(cell);
40
+ else if (cell.trim() !== '')
41
+ droppedFilled = true;
42
+ cell = '';
43
+ blank = true;
44
+ };
45
+ /** Ends the row; the number of its cells when it is kept, else 0. */
46
+ const endRow = () => {
47
+ endCell();
48
+ const kept = droppedFilled || !isBlank(row);
49
+ if (kept)
50
+ rows.push(row);
51
+ const count = kept ? row.length : 0;
52
+ row = [];
53
+ droppedFilled = false;
54
+ return count;
55
+ };
56
+ while (i < text.length && cells <= maxCells) {
57
+ const c = text.charAt(i);
58
+ if (c === '"' && blank) {
59
+ const q = readQuoted(text, i + 1);
60
+ cell = q.cell;
61
+ blank = /^[ \t]*$/.test(cell);
62
+ i = q.next;
63
+ }
64
+ else if (c === delimiter) {
65
+ endCell();
66
+ i++;
67
+ }
68
+ else if (c === '\n' || c === '\r') {
69
+ cells += endRow();
70
+ i += lineBreakLength(text, i);
71
+ }
72
+ else {
73
+ cell += c;
74
+ blank &&= spaceOrTab.test(c);
75
+ i++;
76
+ }
77
+ }
78
+ endRow();
79
+ return rows;
80
+ }
81
+ /** The one that gives most rows as wide as the first, which must be two cells or more and repeat in a second row; none when no delimiter makes a table; tab is tried first and wins a tie, as cell text holds commas far more often than tabs. */
82
+ function detectDelimiter(text) {
83
+ const sample = text.slice(0, 20_000);
84
+ let best;
85
+ for (const d of ['\t', ',', ';']) {
86
+ const rows = splitRows(sample, d).slice(0, 30);
87
+ const width = rows[0]?.length ?? 0;
88
+ const same = rows.filter((r) => r.length === width).length;
89
+ if (width < 2 || same < 2)
90
+ continue;
91
+ const score = same * width;
92
+ if (!best || score > best.score)
93
+ best = { d, score };
94
+ }
95
+ return best?.d;
96
+ }
97
+ const numberLike = /^[+-]?(\d+([.,]\d+)?|[.,]\d+)$/;
98
+ /** Letters of a spreadsheet column: 0 is A, 26 is AA. */
99
+ function columnLetters(i) {
100
+ let letters = '';
101
+ for (let n = i + 1; n > 0; n = Math.floor((n - 1) / 26))
102
+ letters = String.fromCharCode(65 + ((n - 1) % 26)) + letters;
103
+ return letters;
104
+ }
105
+ /** The refusal of a table of `width` columns and `rows` rows beyond the size the readers take. */
106
+ function tooLarge(width, rows) {
107
+ if (width > maxColumn)
108
+ return refused('tooManyColumns', { max: maxColumn });
109
+ if (width * rows > maxCells)
110
+ return refused('tooManyCells', { max: maxCells });
111
+ return undefined;
112
+ }
113
+ /**
114
+ * A table from rows of cell text, such as the rows of a worksheet; the first row is the header
115
+ * unless most of its cells are numbers. Refused below two columns or without data rows.
116
+ */
117
+ export function tableOfRows(raw) {
118
+ const width = raw.reduce((m, r) => Math.max(m, r.length), 0);
119
+ if (width < 2)
120
+ return refused('noTwoColumns');
121
+ const large = tooLarge(width, raw.length);
122
+ if (large)
123
+ return large;
124
+ const padded = raw.map((r) => Array.from({ length: width }, (_, i) => (r[i] ?? '').trim()));
125
+ const first = padded[0] ?? [];
126
+ const filled = first.filter((c) => c !== '');
127
+ const hasHeader = filled.length > 0 && filled.filter((c) => numberLike.test(c)).length * 2 < filled.length;
128
+ const header = hasHeader
129
+ ? first.map((c, i) => c || `Column ${columnLetters(i)}`)
130
+ : first.map((_, i) => `Column ${columnLetters(i)}`);
131
+ const rows = hasHeader ? padded.slice(1) : padded;
132
+ return rows.length === 0 ? refused('headerOnly') : { table: { header, hasHeader, rows } };
133
+ }
134
+ /** The text of a JSON value in a cell: empty for none, JSON for an object or a list, else its text. */
135
+ function jsonCellText(v) {
136
+ if (typeof v === 'string')
137
+ return v;
138
+ if (typeof v === 'number' || typeof v === 'boolean')
139
+ return String(v);
140
+ return v === null || v === undefined ? '' : JSON.stringify(v);
141
+ }
142
+ /** A table from a JSON list of objects: the keys of all objects as columns. Undefined for no such list. */
143
+ function tableOfObjects(list) {
144
+ if (!Array.isArray(list))
145
+ return undefined;
146
+ const objects = list.filter((x) => typeof x === 'object' && x !== null && !Array.isArray(x));
147
+ if (objects.length === 0 || objects.length !== list.length)
148
+ return undefined;
149
+ const keys = [...new Set(objects.flatMap((o) => Object.keys(o)))];
150
+ if (keys.length < 2)
151
+ return undefined;
152
+ const large = tooLarge(keys.length, objects.length);
153
+ if (large)
154
+ return large;
155
+ return {
156
+ table: {
157
+ header: keys,
158
+ hasHeader: true,
159
+ rows: objects.map((o) => keys.map((k) => jsonCellText(Object.hasOwn(o, k) ? o[k] : undefined))),
160
+ },
161
+ };
162
+ }
163
+ /**
164
+ * The table of a text: a JSON list of objects, or delimited text (comma, semicolon or tab) with
165
+ * two or more rows of equal width. Otherwise the refusal's code names the cause.
166
+ */
167
+ export function readTable(raw) {
168
+ const text = raw.replace(/^\uFEFF/, '');
169
+ if (/^\s*[[{]/.test(text)) {
170
+ let json;
171
+ try {
172
+ json = JSON.parse(text);
173
+ }
174
+ catch {
175
+ return refused('jsonMalformed');
176
+ }
177
+ return tableOfObjects(json) ?? refused('jsonNotTable');
178
+ }
179
+ const delimiter = detectDelimiter(text);
180
+ if (!delimiter)
181
+ return refused('noDelimiter');
182
+ return tableOfRows(splitRows(text, delimiter));
183
+ }
184
+ const opening = '([{';
185
+ const closing = ')]}';
186
+ /** Each bracketed part on one line replaced by a space, from an opening bracket to the next closing one of any kind; linear time. */
187
+ function withoutBrackets(text) {
188
+ let out = '';
189
+ let open;
190
+ for (const c of text) {
191
+ if (open === undefined) {
192
+ if (opening.includes(c))
193
+ open = c;
194
+ else
195
+ out += c;
196
+ }
197
+ else if (closing.includes(c)) {
198
+ out += ' ';
199
+ open = undefined;
200
+ }
201
+ else if ('\n\r\u2028\u2029'.includes(c)) {
202
+ out += open + c;
203
+ open = undefined;
204
+ }
205
+ else
206
+ open += c;
207
+ }
208
+ return out + (open ?? '');
209
+ }
210
+ /** The trimmed text inside the first brackets that hold any, their last character when they hold only white space; linear time. */
211
+ function firstBracketed(text) {
212
+ let open = -1;
213
+ for (let i = 0; i < text.length; i++) {
214
+ const c = text.charAt(i);
215
+ if (open < 0) {
216
+ if (opening.includes(c))
217
+ open = i;
218
+ }
219
+ else if (closing.includes(c)) {
220
+ if (i > open + 1)
221
+ return text.slice(open + 1, i).trim() || text.charAt(i - 1);
222
+ open = -1;
223
+ }
224
+ }
225
+ return undefined;
226
+ }
227
+ /** The header as words: lower case, accents and umlauts folded, units in brackets removed. */
228
+ export function headerWords(header) {
229
+ return withoutBrackets(header)
230
+ .toLowerCase()
231
+ .replaceAll('ä', 'ae')
232
+ .replaceAll('ö', 'oe')
233
+ .replaceAll('ü', 'ue')
234
+ .replaceAll('ß', 'ss')
235
+ .normalize('NFD')
236
+ .replace(/[̀-ͯ]/g, '')
237
+ .split(/[^a-z0-9]+/)
238
+ .filter(Boolean);
239
+ }
240
+ /** The unit word a header carries in brackets or after a slash, underscore or space, lower case; undefined for none. */
241
+ export function headerUnit(header) {
242
+ const bracket = firstBracketed(header);
243
+ const tail = /[_/ ]([a-z]{1,6})$/i.exec(header)?.[1];
244
+ return (bracket ?? tail)?.toLowerCase();
245
+ }
246
+ /** A number in text with `decimal` as its mark: spaces and the other mark are grouping. Undefined for no finite number. */
247
+ export function readNumber(text, decimal) {
248
+ const t = text.trim().replace(/[\s ']/g, '');
249
+ if (t === '')
250
+ return undefined;
251
+ const group = decimal === '.' ? ',' : '.';
252
+ const plain = t.replaceAll(group, '').replace(decimal, '.');
253
+ if (!/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i.test(plain))
254
+ return undefined;
255
+ const n = Number(plain);
256
+ return Number.isFinite(n) ? n : undefined;
257
+ }
258
+ /** The decimal mark of a column from its cells, and whether a cell could also read as a grouped integer. */
259
+ export function guessDecimal(cells) {
260
+ let comma = 0;
261
+ let point = 0;
262
+ let ambiguous = false;
263
+ for (const c of cells) {
264
+ const t = c.trim();
265
+ if (/^[+-]?\d+,\d+$/.test(t)) {
266
+ comma++;
267
+ if (/^[+-]?\d{1,3},\d{3}$/.test(t))
268
+ ambiguous = true;
269
+ }
270
+ else if (/^[+-]?\d*\.\d+$/.test(t))
271
+ point++;
272
+ else if (/^[+-]?\d{1,3}(\.\d{3})+,\d+$/.test(t))
273
+ comma++;
274
+ }
275
+ return { decimal: comma > point ? ',' : '.', ambiguous: ambiguous && comma > 0 && point === 0 };
276
+ }
277
+ //# sourceMappingURL=tables.js.map
@@ -0,0 +1,13 @@
1
+ import type { ChronoImport, ChronoParserOptions, SessionCandidate } from './result.ts';
2
+ /** Options of `parseRangeFoundryCsv`: the parser options and the device of the session. */
3
+ export interface TemplateOptions extends ChronoParserOptions {
4
+ /** Device of the session; kind `other` without manufacturer name or model when absent. */
5
+ device?: SessionCandidate['device'] | undefined;
6
+ }
7
+ /** RangeFoundry CSV template: a first row of known column names, `velocity` among them. */
8
+ export declare function isRangeFoundryCsv(text: string): boolean;
9
+ /**
10
+ * Parses a RangeFoundry CSV template (first row names columns, delimiter read from it);
11
+ * velocities in the unit of the `velocityUnit` column or the `velocityUnit` option.
12
+ */
13
+ export declare function parseRangeFoundryCsv(text: string, options?: TemplateOptions): ChronoImport;
@@ -0,0 +1,37 @@
1
+ // The RangeFoundry CSV template: delimited text whose first row names the columns.
2
+ import { refuse } from './diagnostics.js';
3
+ import { detectDelimiter, parseDelimitedRows, splitCells, } from './generic.js';
4
+ import { splitLines } from './text.js';
5
+ const templateNames = ['string', 'velocity', 'velocityUnit', 'coldBore', 'excluded'];
6
+ function templateHeader(text) {
7
+ const first = splitLines(text).find((l) => l.trim());
8
+ if (first === undefined)
9
+ return undefined;
10
+ const delimiter = detectDelimiter([first]);
11
+ const cells = splitCells(first, delimiter);
12
+ while (cells.length > 1 && cells[cells.length - 1] === '')
13
+ cells.pop();
14
+ const names = cells.map((c) => templateNames.find((n) => n.toLowerCase() === c.toLowerCase()));
15
+ const known = names.filter((n) => n !== undefined);
16
+ if (!known.includes('velocity') || known.length !== names.length)
17
+ return undefined;
18
+ return { names: known, delimiter };
19
+ }
20
+ /** RangeFoundry CSV template: a first row of known column names, `velocity` among them. */
21
+ export function isRangeFoundryCsv(text) {
22
+ return templateHeader(text) !== undefined;
23
+ }
24
+ /**
25
+ * Parses a RangeFoundry CSV template (first row names columns, delimiter read from it);
26
+ * velocities in the unit of the `velocityUnit` column or the `velocityUnit` option.
27
+ */
28
+ export function parseRangeFoundryCsv(text, options = {}) {
29
+ const h = templateHeader(text);
30
+ if (!h)
31
+ refuse('notTemplate', { columns: templateNames });
32
+ const columns = { velocity: 'velocity' };
33
+ for (const n of h.names)
34
+ columns[n] = n;
35
+ return parseDelimitedRows('rangefoundry-csv', text, { ...options, columns, delimiter: h.delimiter }, true);
36
+ }
37
+ //# sourceMappingURL=template.js.map
package/dist/text.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * UTF-16 LE after FF FE, UTF-16 BE after FE FF, else UTF-8, all strict: other encodings (Windows-1252
3
+ * from spreadsheets) and damaged text throw, so labels and reasons never hold replacement
4
+ * characters. A UTF-8 byte order mark stays as U+FEFF; the parsers remove it.
5
+ */
6
+ export declare function decodeText(bytes: Uint8Array): string;
7
+ /** Quotes may follow spaces, `""` is a quote inside a quoted cell, and text between a closing quote and the delimiter is kept; tabs before a cell are skipped only when the delimiter is not a tab. */
8
+ export declare function splitDelimited(line: string, delimiter?: ',' | ';' | '\t'): string[];
9
+ /** Joined where a quoted cell holds a line break, each with the index of its first line, so `splitDelimited` reads the joined text as one row; a quote that never closes joins nothing. */
10
+ export declare function joinQuotedLines(lines: string[], delimiter: ',' | ';' | '\t'): {
11
+ text: string;
12
+ index: number;
13
+ }[];
14
+ /** Lines without byte order marks or NUL characters, which exports carry in varying places. */
15
+ export declare function splitLines(text: string): string[];
16
+ /** A decimal point or a decimal comma; NaN for anything else, including a lone comma before exactly three digits (`2,800`), which may be a thousands separator, and a digit run too long for a finite number. */
17
+ export declare function parseNumber(text: string): number;
18
+ /** The lone mark is always the decimal mark: a point or a comma (`0,125`) and an optional exponent (`1.0E-05`); NaN for both marks or anything else (`0x10`, `Infinity`, empty). */
19
+ export declare function readDecimal(text: string): number;
20
+ /** Text from the first `(` to the last `)` when it is not empty, else undefined; linear time. */
21
+ export declare function bracketed(text: string): string | undefined;
22
+ /** The text without the commas that end it and the white space after them; linear time. */
23
+ export declare function withoutTrailingCommas(text: string): string;
24
+ /** Seconds as minutes with up to two decimals, `90.5 min`. */
25
+ export declare const formatMinutes: (seconds: number) => string;
26
+ export declare function isoDate(year: number, month: number, day: number): string | undefined;
27
+ /** Year-first dates only (2026-03-05, 2026/3/5); day-month order is never guessed. */
28
+ export declare function yearFirstDate(text: string): string | undefined;