@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.
- package/LICENSE +661 -0
- package/README.md +20 -1
- 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 +58 -4
package/dist/text.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Text of export files: bytes to text, lines, cells, numbers and dates.
|
|
2
|
+
import { refuseFile } from './diagnostics.js';
|
|
3
|
+
/**
|
|
4
|
+
* UTF-16 LE after FF FE, UTF-16 BE after FE FF, else UTF-8, all strict: other encodings (Windows-1252
|
|
5
|
+
* from spreadsheets) and damaged text throw, so labels and reasons never hold replacement
|
|
6
|
+
* characters. A UTF-8 byte order mark stays as U+FEFF; the parsers remove it.
|
|
7
|
+
*/
|
|
8
|
+
export function decodeText(bytes) {
|
|
9
|
+
const utf16 = utf16Order(bytes);
|
|
10
|
+
if (utf16 && bytes.length % 2 !== 0)
|
|
11
|
+
refuseFile('utf16OddBytes');
|
|
12
|
+
const decoder = new TextDecoder(utf16 ?? 'utf-8', { fatal: true, ignoreBOM: true });
|
|
13
|
+
try {
|
|
14
|
+
return decoder.decode(utf16 ? bytes.subarray(2) : bytes);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return refuseFile('notUnicodeText');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** The UTF-16 byte order the byte order mark at the start gives, or undefined. */
|
|
21
|
+
function utf16Order(bytes) {
|
|
22
|
+
if (bytes[0] === 0xff && bytes[1] === 0xfe)
|
|
23
|
+
return 'utf-16le';
|
|
24
|
+
if (bytes[0] === 0xfe && bytes[1] === 0xff)
|
|
25
|
+
return 'utf-16be';
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
/** True for a character skipped before a cell: a space, or a tab unless tabs delimit. */
|
|
29
|
+
const skippedBefore = (c, delimiter) => c === ' ' || (c === '\t' && delimiter !== '\t');
|
|
30
|
+
/** The text of a quoted cell from `from`, after its opening quote, and the position after its closing quote. */
|
|
31
|
+
function readQuoted(line, from) {
|
|
32
|
+
let cell = '';
|
|
33
|
+
let i = from;
|
|
34
|
+
while (i < line.length && !(line[i] === '"' && line[i + 1] !== '"')) {
|
|
35
|
+
if (line[i] === '"')
|
|
36
|
+
i++;
|
|
37
|
+
cell += line[i++];
|
|
38
|
+
}
|
|
39
|
+
return { cell, next: i + 1 };
|
|
40
|
+
}
|
|
41
|
+
/** 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. */
|
|
42
|
+
export function splitDelimited(line, delimiter = ',') {
|
|
43
|
+
const cells = [];
|
|
44
|
+
let i = 0;
|
|
45
|
+
let end;
|
|
46
|
+
do {
|
|
47
|
+
while (skippedBefore(line[i], delimiter))
|
|
48
|
+
i++;
|
|
49
|
+
let cell = '';
|
|
50
|
+
if (line[i] === '"') {
|
|
51
|
+
const quoted = readQuoted(line, i + 1);
|
|
52
|
+
cell = quoted.cell;
|
|
53
|
+
i = quoted.next;
|
|
54
|
+
}
|
|
55
|
+
end = line.indexOf(delimiter, i);
|
|
56
|
+
cell += line.slice(i, end < 0 ? line.length : end);
|
|
57
|
+
i = end + 1;
|
|
58
|
+
cells.push(cell.trim());
|
|
59
|
+
} while (end >= 0);
|
|
60
|
+
return cells;
|
|
61
|
+
}
|
|
62
|
+
/** Whether `line` ends inside a quoted cell as `splitDelimited` reads it, given whether it starts in one. */
|
|
63
|
+
function endsInQuote(line, delimiter, open) {
|
|
64
|
+
let quoted = open;
|
|
65
|
+
let cellStart = !open;
|
|
66
|
+
for (let i = 0; i < line.length; i++) {
|
|
67
|
+
const c = line[i];
|
|
68
|
+
if (quoted && c === '"' && line[i + 1] === '"')
|
|
69
|
+
i++;
|
|
70
|
+
else if (quoted)
|
|
71
|
+
quoted = c !== '"';
|
|
72
|
+
else if (c === delimiter)
|
|
73
|
+
cellStart = true;
|
|
74
|
+
else if (!(cellStart && skippedBefore(c, delimiter))) {
|
|
75
|
+
quoted = cellStart && c === '"';
|
|
76
|
+
cellStart = false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return quoted;
|
|
80
|
+
}
|
|
81
|
+
/** 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. */
|
|
82
|
+
export function joinQuotedLines(lines, delimiter) {
|
|
83
|
+
const joined = [];
|
|
84
|
+
let start = 0;
|
|
85
|
+
let open = false;
|
|
86
|
+
for (const [n, line] of lines.entries()) {
|
|
87
|
+
open = endsInQuote(line, delimiter, open);
|
|
88
|
+
if (open)
|
|
89
|
+
continue;
|
|
90
|
+
joined.push({ text: lines.slice(start, n + 1).join('\n'), index: start });
|
|
91
|
+
start = n + 1;
|
|
92
|
+
}
|
|
93
|
+
for (let n = start; n < lines.length; n++)
|
|
94
|
+
joined.push({ text: lines[n] ?? '', index: n });
|
|
95
|
+
return joined;
|
|
96
|
+
}
|
|
97
|
+
/** Lines without byte order marks or NUL characters, which exports carry in varying places. */
|
|
98
|
+
export function splitLines(text) {
|
|
99
|
+
return text
|
|
100
|
+
.replaceAll('', '')
|
|
101
|
+
.replaceAll('\0', '')
|
|
102
|
+
.split(/\r\n|\r|\n/);
|
|
103
|
+
}
|
|
104
|
+
/** 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. */
|
|
105
|
+
export function parseNumber(text) {
|
|
106
|
+
const t = text.trim();
|
|
107
|
+
if (t.includes(',') && t.includes('.'))
|
|
108
|
+
return Number.NaN;
|
|
109
|
+
if (/^[+-]?\d{1,3},\d{3}$/.test(t))
|
|
110
|
+
return Number.NaN;
|
|
111
|
+
const s = t.replace(',', '.');
|
|
112
|
+
const n = /^[+-]?\d+(\.\d+)?$/.test(s) ? Number(s) : Number.NaN;
|
|
113
|
+
return Number.isFinite(n) ? n : Number.NaN;
|
|
114
|
+
}
|
|
115
|
+
/** 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). */
|
|
116
|
+
export function readDecimal(text) {
|
|
117
|
+
const t = text.trim();
|
|
118
|
+
if (t.includes(',') && t.includes('.'))
|
|
119
|
+
return Number.NaN;
|
|
120
|
+
const s = t.replace(',', '.');
|
|
121
|
+
return /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(s) ? Number(s) : Number.NaN;
|
|
122
|
+
}
|
|
123
|
+
/** Text from the first `(` to the last `)` when it is not empty, else undefined; linear time. */
|
|
124
|
+
export function bracketed(text) {
|
|
125
|
+
const a = text.indexOf('(');
|
|
126
|
+
const b = text.lastIndexOf(')');
|
|
127
|
+
return a >= 0 && b > a + 1 ? text.slice(a + 1, b) : undefined;
|
|
128
|
+
}
|
|
129
|
+
/** The text without the commas that end it and the white space after them; linear time. */
|
|
130
|
+
export function withoutTrailingCommas(text) {
|
|
131
|
+
let end = text.trimEnd().length;
|
|
132
|
+
while (end > 0 && text[end - 1] === ',')
|
|
133
|
+
end--;
|
|
134
|
+
return text.slice(0, end);
|
|
135
|
+
}
|
|
136
|
+
/** Seconds as minutes with up to two decimals, `90.5 min`. */
|
|
137
|
+
export const formatMinutes = (seconds) => `${Number((seconds / 60).toFixed(2))} min`;
|
|
138
|
+
export function isoDate(year, month, day) {
|
|
139
|
+
const d = new Date(Date.UTC(year, month - 1, day));
|
|
140
|
+
if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day) {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
return d.toISOString().slice(0, 10);
|
|
144
|
+
}
|
|
145
|
+
/** Year-first dates only (2026-03-05, 2026/3/5); day-month order is never guessed. */
|
|
146
|
+
export function yearFirstDate(text) {
|
|
147
|
+
const m = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/.exec(text.trim());
|
|
148
|
+
return m ? isoDate(Number(m[1]), Number(m[2]), Number(m[3])) : undefined;
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=text.js.map
|
package/dist/units.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { QuantityValue } from '@rangefoundry/schema';
|
|
2
|
+
import { type ChronoDiagnostic } from './diagnostics.ts';
|
|
3
|
+
/** A velocity unit the importers recognize. Parsed velocities are stored in m/s. */
|
|
4
|
+
export type VelocityUnit = 'ft/s' | 'm/s' | 'km/h' | 'mph';
|
|
5
|
+
/** `fps`, `ft/s`, `mps`, `m/s`, `kph`, `km/h` or `mph` in any case, else undefined. */
|
|
6
|
+
export declare function parseVelocityUnit(text: string | undefined): VelocityUnit | undefined;
|
|
7
|
+
/** The file's unit, else the caller's; throws when neither is known or they differ. */
|
|
8
|
+
export declare function resolveUnit(text: string | undefined, options: {
|
|
9
|
+
velocityUnit?: VelocityUnit | undefined;
|
|
10
|
+
}, warnings: ChronoDiagnostic[]): VelocityUnit;
|
|
11
|
+
/** A velocity in m/s; `raw` keeps the cell and the unit as written in the file. */
|
|
12
|
+
export declare function parseVelocity(cell: string, unitText: string | undefined, unit: VelocityUnit): QuantityValue;
|
package/dist/units.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Velocity units of export files and the conversion to stored m/s.
|
|
2
|
+
import { conversions } from '@rangefoundry/units';
|
|
3
|
+
import { refuse } from './diagnostics.js';
|
|
4
|
+
import { parseNumber } from './text.js';
|
|
5
|
+
/** `fps`, `ft/s`, `mps`, `m/s`, `kph`, `km/h` or `mph` in any case, else undefined. */
|
|
6
|
+
export function parseVelocityUnit(text) {
|
|
7
|
+
const t = text?.trim().toLowerCase();
|
|
8
|
+
if (t === 'fps' || t === 'ft/s')
|
|
9
|
+
return 'ft/s';
|
|
10
|
+
if (t === 'mps' || t === 'm/s')
|
|
11
|
+
return 'm/s';
|
|
12
|
+
if (t === 'kph' || t === 'km/h')
|
|
13
|
+
return 'km/h';
|
|
14
|
+
if (t === 'mph')
|
|
15
|
+
return 'mph';
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
// m/s per unit; the customary ones from the conversion table
|
|
19
|
+
const toMps = {
|
|
20
|
+
'm/s': 1,
|
|
21
|
+
'ft/s': conversions.ft.factor,
|
|
22
|
+
'km/h': 1 / 3.6,
|
|
23
|
+
mph: conversions.mph.factor,
|
|
24
|
+
};
|
|
25
|
+
/** `x` rounded to 1e-6, which drops binary float noise of a unit conversion. */
|
|
26
|
+
const roundToMillionths = (x) => Math.round(x * 1e6) / 1e6;
|
|
27
|
+
/** Throws when the caller names a unit other than the recognized `unit` the file names as `text`. */
|
|
28
|
+
function checkCallerUnit(text, unit, options) {
|
|
29
|
+
const caller = options.velocityUnit;
|
|
30
|
+
if (caller && caller !== unit)
|
|
31
|
+
refuse('unitDiffersFromCaller', { text: text.trim(), unit, caller });
|
|
32
|
+
}
|
|
33
|
+
/** The file's unit, else the caller's; throws when neither is known or they differ. */
|
|
34
|
+
export function resolveUnit(text, options, warnings) {
|
|
35
|
+
const unit = parseVelocityUnit(text);
|
|
36
|
+
if (text && unit)
|
|
37
|
+
checkCallerUnit(text, unit, options);
|
|
38
|
+
if (unit)
|
|
39
|
+
return unit;
|
|
40
|
+
const shown = text?.trim();
|
|
41
|
+
if (!options.velocityUnit)
|
|
42
|
+
refuse(shown ? 'unknownUnit' : 'missingUnit', shown ? { text: shown } : {});
|
|
43
|
+
const warning = shown
|
|
44
|
+
? { code: 'unknownUnitNamedByCaller', params: { text: shown, unit: options.velocityUnit } }
|
|
45
|
+
: { code: 'missingUnitNamedByCaller', params: { unit: options.velocityUnit } };
|
|
46
|
+
const same = (w) => w.code === warning.code && w.params['text'] === warning.params['text'];
|
|
47
|
+
if (!warnings.some(same))
|
|
48
|
+
warnings.push(warning);
|
|
49
|
+
return options.velocityUnit;
|
|
50
|
+
}
|
|
51
|
+
/** A velocity in m/s; `raw` keeps the cell and the unit as written in the file. */
|
|
52
|
+
export function parseVelocity(cell, unitText, unit) {
|
|
53
|
+
const n = parseNumber(cell);
|
|
54
|
+
if (Number.isNaN(n))
|
|
55
|
+
refuse('velocityNotNumber', { cell: cell.trim() });
|
|
56
|
+
if (n <= 0)
|
|
57
|
+
refuse('velocityNotPositive', { cell: cell.trim() });
|
|
58
|
+
const value = unit === 'm/s' ? n : roundToMillionths(n * toMps[unit]);
|
|
59
|
+
const raw = unitText?.trim() ? `${cell.trim()} ${unitText.trim()}` : cell.trim();
|
|
60
|
+
return { value, raw };
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=units.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Workbook } from './cells.ts';
|
|
2
|
+
import { type Inflate } from './zip.ts';
|
|
3
|
+
/** True for bytes starting with a ZIP local header or the legacy Excel (OLE2) signature. */
|
|
4
|
+
export declare function isWorkbook(bytes: Uint8Array): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Reads an XLSX workbook, or a legacy BIFF8 `.xls` workbook (`readXls`), from its file bytes: the
|
|
7
|
+
* worksheets in workbook order with their names and cell text. Only the relationships, workbook,
|
|
8
|
+
* shared strings and worksheet parts of an XLSX archive are read.
|
|
9
|
+
*/
|
|
10
|
+
export declare function readWorkbook(bytes: Uint8Array, options?: {
|
|
11
|
+
inflate?: Inflate;
|
|
12
|
+
}): Promise<Workbook>;
|
package/dist/workbook.js
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// XLSX workbooks (ECMA-376 Part 1 SpreadsheetML, Part 2 Open Packaging Conventions; https://ecma-international.org/publications-and-standards/standards/ecma-376/) read into rows of cell text, no styles, number formats or formulas applied
|
|
2
|
+
import { clean, placeCell, } from './cells.js';
|
|
3
|
+
import { locatedError, ReaderError, refuseFile } from './diagnostics.js';
|
|
4
|
+
import { maxCellCharacters, maxCells, maxElements, maxTotalSize, maxXmlCharacters, } from './limits.js';
|
|
5
|
+
import { readXls } from './xls.js';
|
|
6
|
+
import { parseXml, scanXml } from './xml.js';
|
|
7
|
+
import { inflateRaw, readEntry, zipEntries, } from './zip.js';
|
|
8
|
+
// assumed bound, not a cited one, for the relationships and workbook parts read into an element tree
|
|
9
|
+
const maxTreePartSize = 1024 * 1024;
|
|
10
|
+
const zipSignature = [0x50, 0x4b, 0x03, 0x04];
|
|
11
|
+
const legacySignature = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
|
|
12
|
+
const startsWith = (bytes, signature) => signature.every((b, i) => bytes[i] === b);
|
|
13
|
+
/** True for bytes starting with a ZIP local header or the legacy Excel (OLE2) signature. */
|
|
14
|
+
export function isWorkbook(bytes) {
|
|
15
|
+
return startsWith(bytes, zipSignature) || startsWith(bytes, legacySignature);
|
|
16
|
+
}
|
|
17
|
+
const elements = (e, name) => (e?.children ?? []).filter((c) => typeof c !== 'string' && c.name === name);
|
|
18
|
+
/** True when the text event at `path` is a `t` child of a shared string `si` or an inline string `is` at depth `d`, or the `t` of its `r` runs; phonetic runs (`rPh`) and other children are left out. */
|
|
19
|
+
const richTextAt = (path, d) => (path.length === d + 2 && path[d + 1] === 't') ||
|
|
20
|
+
(path.length === d + 3 && path[d + 1] === 'r' && path[d + 2] === 't');
|
|
21
|
+
/** Part name for a relationship target, relative to the folder of `source` unless absolute. */
|
|
22
|
+
function resolveTarget(source, target) {
|
|
23
|
+
const segments = target.startsWith('/') ? [] : source.split('/').slice(0, -1);
|
|
24
|
+
for (const s of target.split('/')) {
|
|
25
|
+
if (s === '' || s === '.')
|
|
26
|
+
continue;
|
|
27
|
+
if (s !== '..')
|
|
28
|
+
segments.push(s);
|
|
29
|
+
else if (segments.pop() === undefined)
|
|
30
|
+
refuseFile('relationshipLeaves', { target });
|
|
31
|
+
}
|
|
32
|
+
return segments.join('/');
|
|
33
|
+
}
|
|
34
|
+
/** Column number of the letters of a cell reference, bijective base 26 (`A` 1, `IV` 256). */
|
|
35
|
+
const columnOf = (letters) => Array.from(letters).reduce((col, l) => col * 26 + l.charCodeAt(0) - 64, 0);
|
|
36
|
+
/** The shared string a cell's `v` text indexes; refused when the index is not in the table. */
|
|
37
|
+
function sharedString(text, strings, at) {
|
|
38
|
+
const k = /^\d+$/.test(text.trim()) ? Number(text) : Number.NaN;
|
|
39
|
+
const shared = strings[k];
|
|
40
|
+
if (shared === undefined) {
|
|
41
|
+
refuseFile('sharedStringOutOfRange', { ...at(), index: text, count: strings.length });
|
|
42
|
+
}
|
|
43
|
+
return shared;
|
|
44
|
+
}
|
|
45
|
+
/** From its type, the text of its first `v` and of its first `is`; `at` places the cell, built only for a refusal. */
|
|
46
|
+
function cellText({ t, v, is }, strings, at) {
|
|
47
|
+
let text;
|
|
48
|
+
if (t === 'inlineStr') {
|
|
49
|
+
text = is ?? '';
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
text = v ?? '';
|
|
53
|
+
// shared strings are cleaned once when the table is read
|
|
54
|
+
if (t === 's' && text !== '')
|
|
55
|
+
return sharedString(text, strings, at);
|
|
56
|
+
if (t === 'b' && text.trim() === '0')
|
|
57
|
+
return '';
|
|
58
|
+
}
|
|
59
|
+
return clean(text);
|
|
60
|
+
}
|
|
61
|
+
/** Shared strings, read in one pass: each `si` child of the root, trimmed and U+FEFF removed. */
|
|
62
|
+
function sharedStrings(text, xmlRemaining) {
|
|
63
|
+
const strings = [];
|
|
64
|
+
let current;
|
|
65
|
+
scanXml(text, {
|
|
66
|
+
open(name, _attributes, path) {
|
|
67
|
+
if (path.length === 1 && name === 'si')
|
|
68
|
+
current = '';
|
|
69
|
+
},
|
|
70
|
+
text(t, path) {
|
|
71
|
+
if (current !== undefined && path[1] === 'si' && richTextAt(path, 1))
|
|
72
|
+
current += t;
|
|
73
|
+
},
|
|
74
|
+
close(name, path) {
|
|
75
|
+
if (path.length === 1 && name === 'si' && current !== undefined) {
|
|
76
|
+
strings.push(clean(current));
|
|
77
|
+
current = undefined;
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
}, xmlRemaining);
|
|
81
|
+
return strings;
|
|
82
|
+
}
|
|
83
|
+
/** Counts a `v` or `is` child of a cell; the first of each starts its text. */
|
|
84
|
+
function countCellChild(cell, name) {
|
|
85
|
+
if (name === 'v' && ++cell.vs === 1)
|
|
86
|
+
cell.v = '';
|
|
87
|
+
else if (name === 'is' && ++cell.iss === 1)
|
|
88
|
+
cell.is = '';
|
|
89
|
+
}
|
|
90
|
+
/** Places a closed cell in its row by its reference, or after the cells so far without one. */
|
|
91
|
+
function closeCell(cell, cells, strings, remaining) {
|
|
92
|
+
const ref = cell.r;
|
|
93
|
+
let column = cells.length + 1;
|
|
94
|
+
if (ref !== undefined) {
|
|
95
|
+
const letters = /^([A-Z]{1,3})[0-9]+$/.exec(ref)?.[1];
|
|
96
|
+
if (letters === undefined)
|
|
97
|
+
refuseFile('cellRefMalformed', { ref });
|
|
98
|
+
column = columnOf(letters);
|
|
99
|
+
}
|
|
100
|
+
const at = () => (ref === undefined ? { column } : { cell: ref });
|
|
101
|
+
placeCell(cells, { column, text: cellText(cell, strings, at), at }, remaining);
|
|
102
|
+
}
|
|
103
|
+
/** The element at each depth of a worksheet the scan reads: the sheet data, a row, a cell. */
|
|
104
|
+
const sheetPath = ['sheetData', 'row', 'c'];
|
|
105
|
+
/** One pass over the `row` children of the root's first `sheetData` and their `c` children; `remaining` counts down the cells (gaps included) and characters every worksheet may still produce, a shared string at each cell that refers to it; each cell is placed when its element closes. */
|
|
106
|
+
function sheetRows(text, strings, remaining, xmlRemaining) {
|
|
107
|
+
const rows = [];
|
|
108
|
+
let sheetData = 'before';
|
|
109
|
+
let cells;
|
|
110
|
+
let cell;
|
|
111
|
+
scanXml(text, {
|
|
112
|
+
open(name, attributes, path) {
|
|
113
|
+
const depth = path.length;
|
|
114
|
+
if (depth === 4) {
|
|
115
|
+
if (cell)
|
|
116
|
+
countCellChild(cell, name);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (name !== sheetPath[depth - 1])
|
|
120
|
+
return;
|
|
121
|
+
if (depth === 1) {
|
|
122
|
+
if (sheetData === 'before')
|
|
123
|
+
sheetData = 'open';
|
|
124
|
+
}
|
|
125
|
+
else if (depth === 2) {
|
|
126
|
+
if (sheetData === 'open')
|
|
127
|
+
cells = [];
|
|
128
|
+
}
|
|
129
|
+
else if (cells)
|
|
130
|
+
cell = { t: attributes['t'], r: attributes['r'], vs: 0, iss: 0 };
|
|
131
|
+
},
|
|
132
|
+
text(t, path) {
|
|
133
|
+
if (!cell || path.length < 5)
|
|
134
|
+
return;
|
|
135
|
+
if (path.length === 5 && path[4] === 'v' && cell.vs === 1)
|
|
136
|
+
cell.v += t;
|
|
137
|
+
else if (path[4] === 'is' && cell.iss === 1 && richTextAt(path, 4))
|
|
138
|
+
cell.is += t;
|
|
139
|
+
},
|
|
140
|
+
close(name, path) {
|
|
141
|
+
const depth = path.length;
|
|
142
|
+
if (name !== sheetPath[depth - 1])
|
|
143
|
+
return;
|
|
144
|
+
if (depth === 1) {
|
|
145
|
+
if (sheetData === 'open')
|
|
146
|
+
sheetData = 'after';
|
|
147
|
+
}
|
|
148
|
+
else if (depth === 2) {
|
|
149
|
+
if (cells && cells.length > 0)
|
|
150
|
+
rows.push(cells);
|
|
151
|
+
cells = undefined;
|
|
152
|
+
}
|
|
153
|
+
else if (cells && cell) {
|
|
154
|
+
closeCell(cell, cells, strings, remaining);
|
|
155
|
+
cell = undefined;
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
}, xmlRemaining);
|
|
159
|
+
return rows;
|
|
160
|
+
}
|
|
161
|
+
/** The refusal of the XML limit a shared budget ran out of, or undefined while it holds. */
|
|
162
|
+
function exhausted(xmlRemaining, part) {
|
|
163
|
+
if (xmlRemaining.elements < 0)
|
|
164
|
+
return { code: 'xmlElementsExceeded', params: { max: maxElements, part } };
|
|
165
|
+
if (xmlRemaining.characters < 0)
|
|
166
|
+
return { code: 'xmlCharactersExceeded', params: { max: maxXmlCharacters, part } };
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
/** `budget.left` is the declared size the workbook may still read, `xmlRemaining` the XML budget, both shared by all parts. */
|
|
170
|
+
function partReader(archive, budget, xmlRemaining) {
|
|
171
|
+
return async (name, read, limit) => {
|
|
172
|
+
const entry = archive.entries.get(name.toLowerCase());
|
|
173
|
+
if (!entry)
|
|
174
|
+
refuseFile('partMissing', { name });
|
|
175
|
+
const data = await readEntry(archive, entry, budget, limit);
|
|
176
|
+
try {
|
|
177
|
+
// the Encoding Standard's UTF-8 reading drops a byte order mark and marks bad bytes U+FFFD
|
|
178
|
+
const text = await new Response(data).text();
|
|
179
|
+
if (text.includes('\uFFFD'))
|
|
180
|
+
refuseFile('notUtf8');
|
|
181
|
+
return read(text);
|
|
182
|
+
}
|
|
183
|
+
catch (e) {
|
|
184
|
+
// the budget is shared by all parts, so name it, not only the part that used it up
|
|
185
|
+
const over = exhausted(xmlRemaining, entry.name);
|
|
186
|
+
throw over ? new ReaderError(over, { cause: e }) : locatedError(e, { part: entry.name });
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/** Of the part `source` (`''` for the package), targets resolved, read as an element tree by `tree`; a repeated relationship id is refused. */
|
|
191
|
+
async function readRelationships(tree, source) {
|
|
192
|
+
const slash = source.lastIndexOf('/');
|
|
193
|
+
const path = `${source.slice(0, slash + 1)}_rels/${source.slice(slash + 1)}.rels`;
|
|
194
|
+
const all = elements(await tree(path), 'Relationship').map((r) => r.attributes);
|
|
195
|
+
const ids = new Set();
|
|
196
|
+
for (const r of all) {
|
|
197
|
+
const id = r['Id'] ?? '';
|
|
198
|
+
if (ids.has(id))
|
|
199
|
+
refuseFile('relationshipTwice', { part: path, id });
|
|
200
|
+
ids.add(id);
|
|
201
|
+
}
|
|
202
|
+
return all
|
|
203
|
+
.filter((r) => r['TargetMode'] !== 'External')
|
|
204
|
+
.map((r) => ({
|
|
205
|
+
id: r['Id'] ?? '',
|
|
206
|
+
type: r['Type'] ?? '',
|
|
207
|
+
target: resolveTarget(source, r['Target'] ?? ''),
|
|
208
|
+
}));
|
|
209
|
+
}
|
|
210
|
+
/** Those the `sheet` elements of the workbook part `office` list, in that order, each part read at most once; chart and dialog sheets are left out. */
|
|
211
|
+
async function readWorksheets(part, { office, sheetList, rels }, strings, xmlRemaining) {
|
|
212
|
+
const byId = new Map(rels.map((r) => [r.id, r]));
|
|
213
|
+
const remaining = { cells: maxCells, characters: maxCellCharacters };
|
|
214
|
+
const read = new Set();
|
|
215
|
+
const worksheets = [];
|
|
216
|
+
for (const sheet of sheetList) {
|
|
217
|
+
const rel = byId.get(sheet['id'] ?? '');
|
|
218
|
+
if (!rel)
|
|
219
|
+
refuseFile('sheetNoRelationship', { part: office, sheet: sheet['name'] ?? '' });
|
|
220
|
+
// chart sheets and dialog sheets hold no cells
|
|
221
|
+
if (!rel.type.endsWith('/worksheet'))
|
|
222
|
+
continue;
|
|
223
|
+
if (read.has(rel.target)) {
|
|
224
|
+
refuseFile('sheetPartAgain', { part: office, sheet: sheet['name'] ?? '', target: rel.target });
|
|
225
|
+
}
|
|
226
|
+
read.add(rel.target);
|
|
227
|
+
const rows = await part(rel.target, (text) => sheetRows(text, strings, remaining, xmlRemaining));
|
|
228
|
+
worksheets.push({ name: sheet['name'] ?? '', rows });
|
|
229
|
+
}
|
|
230
|
+
return worksheets;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Reads an XLSX workbook, or a legacy BIFF8 `.xls` workbook (`readXls`), from its file bytes: the
|
|
234
|
+
* worksheets in workbook order with their names and cell text. Only the relationships, workbook,
|
|
235
|
+
* shared strings and worksheet parts of an XLSX archive are read.
|
|
236
|
+
*/
|
|
237
|
+
export async function readWorkbook(bytes, options = {}) {
|
|
238
|
+
if (startsWith(bytes, legacySignature))
|
|
239
|
+
return readXls(bytes);
|
|
240
|
+
if (!options.inflate && typeof DecompressionStream === 'undefined')
|
|
241
|
+
refuseFile('noDecompressionStream');
|
|
242
|
+
const inflate = options.inflate ?? inflateRaw;
|
|
243
|
+
const entries = zipEntries(bytes);
|
|
244
|
+
const budget = { left: maxTotalSize };
|
|
245
|
+
const xmlRemaining = { elements: maxElements, characters: maxXmlCharacters };
|
|
246
|
+
const part = partReader({ bytes, entries, inflate }, budget, xmlRemaining);
|
|
247
|
+
const tree = (name) => part(name, (text) => parseXml(text, xmlRemaining), maxTreePartSize);
|
|
248
|
+
const office = (await readRelationships(tree, '')).find((r) => r.type.endsWith('/officeDocument'));
|
|
249
|
+
if (!office)
|
|
250
|
+
refuseFile('noWorkbookPart', { part: '_rels/.rels' });
|
|
251
|
+
// only the sheet attributes are kept, so the workbook tree can be collected
|
|
252
|
+
const sheetList = elements(elements(await tree(office.target), 'sheets')[0], 'sheet').map((s) => s.attributes);
|
|
253
|
+
const rels = await readRelationships(tree, office.target);
|
|
254
|
+
const shared = rels.find((r) => r.type.endsWith('/sharedStrings'));
|
|
255
|
+
const declared = [shared, ...rels.filter((r) => r.type.endsWith('/worksheet'))].reduce((n, r) => n + (r ? (entries.get(r.target.toLowerCase())?.size ?? 0) : 0), 0);
|
|
256
|
+
if (declared > budget.left)
|
|
257
|
+
refuseFile('partsTooLarge', { max: maxTotalSize });
|
|
258
|
+
const strings = shared
|
|
259
|
+
? await part(shared.target, (text) => sharedStrings(text, xmlRemaining))
|
|
260
|
+
: [];
|
|
261
|
+
const worksheets = await readWorksheets(part, { office: office.target, sheetList, rels }, strings, xmlRemaining);
|
|
262
|
+
return { worksheets };
|
|
263
|
+
}
|
|
264
|
+
//# sourceMappingURL=workbook.js.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ChronoShot } from '@rangefoundry/schema';
|
|
2
|
+
import { type ChronoDiagnostic } from './diagnostics.ts';
|
|
3
|
+
import type { ChronoParserOptions } from './result.ts';
|
|
4
|
+
/**
|
|
5
|
+
* `ChronoParserOptions` plus `date`: `YYYY-MM-DD`, keeps the worksheets of that day and the worksheets
|
|
6
|
+
* without a date.
|
|
7
|
+
*/
|
|
8
|
+
export interface WorkbookOptions extends ChronoParserOptions {
|
|
9
|
+
/** Keep only the worksheets of this day (`YYYY-MM-DD`). */
|
|
10
|
+
date?: string | undefined;
|
|
11
|
+
}
|
|
12
|
+
/** The shots, label and bore flags of one worksheet, read as one string of shots. */
|
|
13
|
+
export interface WorksheetString {
|
|
14
|
+
shots: ChronoShot[];
|
|
15
|
+
label: string;
|
|
16
|
+
/** Bore flags as `shot <n> <flag>`. */
|
|
17
|
+
flags: string[];
|
|
18
|
+
}
|
|
19
|
+
/** A worksheet a workbook parser found, with its date and a reader for its string. */
|
|
20
|
+
export interface FoundWorksheet {
|
|
21
|
+
/** Position in the workbook, from 1. */
|
|
22
|
+
position: number;
|
|
23
|
+
date?: string;
|
|
24
|
+
dateWarning?: ChronoDiagnostic;
|
|
25
|
+
/** The string, or undefined when the worksheet holds no shot row. */
|
|
26
|
+
read: (warnings: ChronoDiagnostic[]) => WorksheetString | undefined;
|
|
27
|
+
}
|
|
28
|
+
/** Keeps the worksheets of the `date` option (all without it) and sets the date when every kept string has the same one, other days adding no warning; the option also keeps undated worksheets and is the session date, each undated one warning that it was taken when some worksheet has a date. */
|
|
29
|
+
export declare function collectWorksheetStrings(found: FoundWorksheet[], options: WorkbookOptions, warnings: ChronoDiagnostic[]): {
|
|
30
|
+
strings: {
|
|
31
|
+
shots: ChronoShot[];
|
|
32
|
+
}[];
|
|
33
|
+
labels: string[];
|
|
34
|
+
flags: string[];
|
|
35
|
+
date?: string;
|
|
36
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { refuse } from './diagnostics.js';
|
|
2
|
+
/** The distinct dates of the worksheets, ascending. */
|
|
3
|
+
const datesOf = (list) => [...new Set(list.flatMap((f) => (f.date ? [f.date] : [])))].toSorted((a, b) => a.localeCompare(b, 'en'));
|
|
4
|
+
/** Warns about the date of a kept worksheet: a date taken from the option, or its own date warning once. */
|
|
5
|
+
function warnDate(f, options, fill, warnings) {
|
|
6
|
+
if (options.date && !fill && !f.date) {
|
|
7
|
+
warnings.push({ code: 'dateFromOption', params: { worksheet: f.position, date: options.date } });
|
|
8
|
+
}
|
|
9
|
+
else if (!fill && f.dateWarning && !warnings.includes(f.dateWarning)) {
|
|
10
|
+
warnings.push(f.dateWarning);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Keeps the worksheets of the `date` option (all without it) and sets the date when every kept string has the same one, other days adding no warning; the option also keeps undated worksheets and is the session date, each undated one warning that it was taken when some worksheet has a date. */
|
|
14
|
+
export function collectWorksheetStrings(found, options, warnings) {
|
|
15
|
+
const fill = options.date !== undefined && found.every((f) => !f.date);
|
|
16
|
+
const kept = options.date ? found.filter((f) => !f.date || f.date === options.date) : found;
|
|
17
|
+
checkDateOption(found, options.date, fill);
|
|
18
|
+
const strings = [];
|
|
19
|
+
const labels = [];
|
|
20
|
+
const flags = [];
|
|
21
|
+
const read = [];
|
|
22
|
+
for (const f of kept) {
|
|
23
|
+
warnDate(f, options, fill, warnings);
|
|
24
|
+
const s = f.read(warnings);
|
|
25
|
+
if (!s) {
|
|
26
|
+
warnings.push({ code: 'noShotRows', params: { worksheet: f.position } });
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
strings.push({ shots: s.shots });
|
|
30
|
+
labels.push(s.label);
|
|
31
|
+
flags.push(...s.flags.map((flag) => `string ${strings.length} ${flag}`));
|
|
32
|
+
read.push(f);
|
|
33
|
+
}
|
|
34
|
+
const date = commonDate(read, options.date, warnings);
|
|
35
|
+
return { strings, labels, flags, ...(date ? { date } : {}) };
|
|
36
|
+
}
|
|
37
|
+
/** Refuses a `date` option that no worksheet has while some worksheet has a date (`fill` unset). */
|
|
38
|
+
function checkDateOption(found, date, fill) {
|
|
39
|
+
// `fill` is unset, so some worksheet has a date and the list is never empty
|
|
40
|
+
if (date && !fill && !found.some((f) => f.date === date))
|
|
41
|
+
refuse('noStringOnDate', { date, dates: datesOf(found) });
|
|
42
|
+
}
|
|
43
|
+
/** The `date` option, else the one date every read worksheet has; warns when the read worksheets have several. */
|
|
44
|
+
function commonDate(read, option, warnings) {
|
|
45
|
+
const dates = datesOf(read);
|
|
46
|
+
if (dates.length > 1)
|
|
47
|
+
warnings.push({ code: 'severalDays', params: { dates } });
|
|
48
|
+
return (option || (dates.length === 1 && read.every((f) => f.date === dates[0]) ? dates[0] : undefined));
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=worksheet-strings.js.map
|
package/dist/xls.d.ts
ADDED