@team581/log-formula 0.0.0-stage → 0.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jonah Snider
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @team581/log-formula
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Calculate numeric entries from other entries in robot logs, ex. acceleration from velocity, or a tracking error from a
4
+ setpoint and a measurement. DogLog writes formulas into logs, and DogLog Studio and Fetch evaluate them with this
5
+ library, so every app gets the same values.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @team581/log-formula
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { check, createEvaluator, parse } from '@team581/log-formula';
17
+
18
+ const { formula, errors } = parse('derivative(`Drive/Velocity`)');
19
+ const plan = check(formula, { units: (path) => (path === '/Drive/Velocity' ? 'm/s' : undefined) });
20
+ plan.unit; // m/s^2
21
+
22
+ const evaluator = createEvaluator(plan);
23
+ evaluator.sync({ '/Drive/Velocity': velocity });
24
+ evaluator.output; // { timestamps, values, length }
25
+ ```
26
+
27
+ Inputs and outputs are columns of timestamps (µs) and values. Call `sync()` again as samples arrive, and only the new
28
+ values are calculated.
29
+
30
+ ## Documentation
31
+
32
+ - [Language](docs/language.md): syntax, units, and functions.
33
+ - [Evaluation](docs/evaluation.md): when a formula has values, and how it handles time.
34
+ - [Add a custom function](docs/custom-functions.md)
35
+ - [Fixtures](fixtures/README.md): test cases shared with DogLog's Java builders.
36
+ - The API reference is generated by API Extractor.
@@ -0,0 +1,194 @@
1
+ /** What functions of change over time know about the evaluation, see `docs/evaluation.md` */
2
+ type TimeContext = {
3
+ /** The index of the time range `time` (µs) is in, `-1` outside them. Always `0` without time ranges. */
4
+ rangeIndex(time: number): number;
5
+ /** Seconds from `from` to `to` (µs) that are in the time ranges */
6
+ secondsInRanges(from: number, to: number): number;
7
+ };
8
+ /** The state of a function whose value depends on its earlier values, see `FormulaFunction.create` */
9
+ type FunctionState = {
10
+ /** The value at `time` (µs) from the arguments' values then */
11
+ step(time: number, args: readonly number[], context: TimeContext): number;
12
+ /** Start over, ex. after a gap */
13
+ reset?(): void;
14
+ };
15
+ /** What units measure. Angle is a dimension, so degrees, radians, and rotations convert to each other. */
16
+ export declare const dimensions: readonly ['length', 'mass', 'time', 'current', 'temperature', 'angle'];
17
+ /** One of `dimensions` */
18
+ type Dimension = (typeof dimensions)[number];
19
+ /**
20
+ * A unit, ex. `m/s^2`. Values convert to base units (meters, kilograms, seconds, amperes, kelvin, and radians) as
21
+ * `value * scale + offset`.
22
+ */
23
+ type Unit = {
24
+ /** Canonical text, ex. `m/s^2`. Empty for a number without a unit. */
25
+ readonly label: string;
26
+ /** The power of each dimension, ex. `{ length: 1, time: -2, … }` for `m/s^2` */
27
+ readonly dimension: Readonly<Record<Dimension, number>>;
28
+ readonly scale: number;
29
+ /** Only `°C` and `°F` have one */
30
+ readonly offset: number;
31
+ /** The named units it's made of and their powers, ex. `[['m', 1], ['s', -2]]` */
32
+ readonly factors: readonly (readonly [symbol: string, power: number])[];
33
+ };
34
+ /**
35
+ * Parse unit text, ex. `m/s^2`, `N*m`, `RPM`, or `meters per second squared`. Names ignore case and plurals. Each `/`
36
+ * divides by the name after it. `undefined` when it isn't a unit.
37
+ */
38
+ export declare function parseUnit(text: string): Unit | undefined;
39
+ /** Whether two units measure the same thing, so values convert between them */
40
+ export declare function sameDimension(a: Unit, b: Unit): boolean;
41
+ /** Convert `value` between two units of the same dimension, see `sameDimension()` */
42
+ export declare function convert(value: number, from: Unit, to: Unit): number;
43
+ /** A function formulas can call, see `defineFunction()` and `docs/custom-functions.md` */
44
+ type FormulaFunction = {
45
+ readonly name: string;
46
+ /** How many arguments it takes */
47
+ readonly arguments: number | {
48
+ readonly min: number;
49
+ readonly max?: number;
50
+ };
51
+ /**
52
+ * Whether its arguments must measure the same thing, ex. `min()`. Arguments with an unknown unit are then read in the
53
+ * first known unit.
54
+ */
55
+ readonly sameDimension?: boolean;
56
+ /**
57
+ * The result's unit from the arguments' units, `undefined` when unknown, or a message saying why they don't work.
58
+ * Defaults to the first argument's unit.
59
+ */
60
+ readonly unit?: (units: readonly (Unit | undefined)[]) => Unit | undefined | string;
61
+ } & ({
62
+ /** The result from the arguments, in base units */
63
+ readonly apply: (args: readonly number[]) => number;
64
+ } | {
65
+ /** State for one evaluation, for a function whose result depends on earlier values */
66
+ readonly create: () => FunctionState;
67
+ });
68
+ /** Define a function to pass to `check()`, see `docs/custom-functions.md` */
69
+ export declare function defineFunction<T extends FormulaFunction>(definition: T): T;
70
+ /** Functions every formula can use, see `docs/language.md` */
71
+ export declare const builtInFunctions: readonly FormulaFunction[];
72
+ /** Where something is in a formula's text, in UTF-16 code units */
73
+ type Span = {
74
+ readonly from: number;
75
+ readonly to: number;
76
+ };
77
+ /** A number, ex. `2` or `2[in]` */
78
+ type NumberLiteral = Span & {
79
+ readonly type: 'number';
80
+ readonly value: number;
81
+ readonly unit?: string;
82
+ };
83
+ /** An entry by its path, which always starts with `/`, with an optional unit */
84
+ type EntryReference = Span & {
85
+ readonly type: 'entry';
86
+ readonly path: string;
87
+ readonly unit?: string;
88
+ };
89
+ /** A name defined on an earlier line */
90
+ type NameReference = Span & {
91
+ readonly type: 'name';
92
+ readonly name: string;
93
+ };
94
+ type Call = Span & {
95
+ readonly type: 'call';
96
+ readonly name: string;
97
+ readonly arguments: readonly Expression[];
98
+ };
99
+ type Negation = Span & {
100
+ readonly type: 'negate';
101
+ readonly operand: Expression;
102
+ };
103
+ type BinaryOperator = '+' | '-' | '*' | '/' | '^';
104
+ type BinaryOperation = Span & {
105
+ readonly type: 'binary';
106
+ readonly operator: BinaryOperator;
107
+ readonly left: Expression;
108
+ readonly right: Expression;
109
+ };
110
+ type Expression = NumberLiteral | EntryReference | NameReference | Call | Negation | BinaryOperation;
111
+ /** A line that names a value, ex. `gyro = 2 * x` */
112
+ type Definition = Span & {
113
+ readonly name: string;
114
+ readonly value: Expression;
115
+ };
116
+ /** A parsed formula, see `parse()` */
117
+ type Formula = {
118
+ readonly definitions: readonly Definition[];
119
+ readonly result: Expression;
120
+ };
121
+ /** Why a formula can't be used, and where in its text */
122
+ type FormulaError = Span & {
123
+ readonly code: 'syntax' | 'unknown-function' | 'arguments' | 'unit' | 'undefined-name' | 'duplicate-name' | 'no-entries';
124
+ readonly message: string;
125
+ };
126
+ type ParseResult = {
127
+ readonly formula: Formula;
128
+ readonly errors: readonly [];
129
+ } | {
130
+ readonly formula: undefined;
131
+ readonly errors: readonly FormulaError[];
132
+ };
133
+ /** An entry's path with a leading `/` */
134
+ export declare function normalizePath(path: string): string;
135
+ /** Parse a formula's text, see `docs/language.md` */
136
+ export declare function parse(text: string): ParseResult;
137
+ /** A formula's text, canonical when the formula has no definitions, see `docs/language.md` */
138
+ export declare function format(formula: Formula): string;
139
+ type CheckOptions = {
140
+ /** The unit of an entry by its path, which starts with `/`, ex. from its metadata. `undefined` when it isn't known. */
141
+ readonly units?: (path: string) => Unit | string | undefined;
142
+ /** The unit to convert the result to */
143
+ readonly unit?: Unit | string;
144
+ /** Functions to add to the built-in ones, see `defineFunction()` */
145
+ readonly functions?: readonly FormulaFunction[];
146
+ };
147
+ /** A checked formula to evaluate with `createEvaluator()` */
148
+ type Plan = {
149
+ /** Paths of the entries the formula uses, each starting with `/` */
150
+ readonly inputs: readonly string[];
151
+ /** The result's unit, `undefined` when it isn't known */
152
+ readonly unit: Unit | undefined;
153
+ /** Why it can't be evaluated, empty when it can */
154
+ readonly errors: readonly FormulaError[];
155
+ };
156
+ /** Check a parsed formula's names, functions, and units, see `docs/language.md` */
157
+ export declare function check(formula: Formula, options?: CheckOptions): Plan;
158
+ /** Samples as columns, timestamps in µs and sorted */
159
+ type Series = {
160
+ readonly timestamps: ArrayLike<number>;
161
+ readonly values: ArrayLike<number>;
162
+ readonly length: number;
163
+ };
164
+ /** From `start` up to but not including `end`, in µs */
165
+ type TimeRange = {
166
+ readonly start: number;
167
+ readonly end: number;
168
+ };
169
+ type EvaluateOptions = {
170
+ /** Longest time (µs) between values before functions of change over time start over, 500 ms by default */
171
+ readonly maxGap?: number;
172
+ /** When nothing was received, sorted, ex. a live session's disconnects */
173
+ readonly gaps?: readonly TimeRange[];
174
+ /** Only evaluate in these ranges, sorted, every time by default */
175
+ readonly ranges?: readonly TimeRange[];
176
+ };
177
+ /** Evaluates a formula as its inputs' samples arrive, see `docs/evaluation.md` */
178
+ type Evaluator = {
179
+ /** Calculate values for samples added to `inputs` since the last call, keyed by the plan's `inputs` */
180
+ sync(inputs: Readonly<Record<string, Series>>): {
181
+ readonly restarted: boolean;
182
+ };
183
+ /** Start over at the next `sync()`, ex. after an input's samples changed */
184
+ reset(): void;
185
+ /** The result in the plan's unit, `NaN` where it's undefined */
186
+ readonly output: {
187
+ readonly timestamps: Float64Array;
188
+ readonly values: Float64Array;
189
+ readonly length: number;
190
+ };
191
+ };
192
+ /** Create an evaluator for a plan without errors */
193
+ export declare function createEvaluator(plan: Plan, options?: EvaluateOptions): Evaluator;
194
+ export type { BinaryOperation, BinaryOperator, Call, CheckOptions, Definition, Dimension, EntryReference, EvaluateOptions, Evaluator, Expression, Formula, FormulaError, FormulaFunction, FunctionState, NameReference, Negation, NumberLiteral, ParseResult, Plan, Series, Span, TimeContext, TimeRange, Unit };
package/dist/index.mjs ADDED
@@ -0,0 +1,857 @@
1
+ import { convert as convert$1 } from "convert";
2
+ import { LRParser } from "@lezer/lr";
3
+ // src/units.ts
4
+ /** What units measure. Angle is a dimension, so degrees, radians, and rotations convert to each other. */
5
+ const dimensions = [
6
+ "length",
7
+ "mass",
8
+ "time",
9
+ "current",
10
+ "temperature",
11
+ "angle"
12
+ ];
13
+ const namedUnits = /* @__PURE__ */ new Map();
14
+ const unitNames = /* @__PURE__ */ new Map();
15
+ function add(symbol, names, scale, dimension, offset = 0) {
16
+ namedUnits.set(symbol, {
17
+ scale,
18
+ offset,
19
+ dimension
20
+ });
21
+ for (const name of [symbol, ...names]) unitNames.set(name.toLowerCase(), symbol);
22
+ }
23
+ add("m", ["meter", "metre"], 1, { length: 1 });
24
+ add("cm", ["centimeter", "centimetre"], convert$1(1, "cm").to("m"), { length: 1 });
25
+ add("mm", ["millimeter", "millimetre"], convert$1(1, "mm").to("m"), { length: 1 });
26
+ add("in", ["inch", "inche"], convert$1(1, "in").to("m"), { length: 1 });
27
+ add("ft", ["foot", "feet"], convert$1(1, "ft").to("m"), { length: 1 });
28
+ add("kg", ["kilogram"], 1, { mass: 1 });
29
+ add("g", ["gram"], convert$1(1, "g").to("kg"), { mass: 1 });
30
+ add("lb", ["pound"], convert$1(1, "lb").to("kg"), { mass: 1 });
31
+ add("s", ["sec", "second"], 1, { time: 1 });
32
+ add("ms", ["millisecond"], convert$1(1, "ms").to("s"), { time: 1 });
33
+ add("us", ["µs", "microsecond"], convert$1(1, "µs").to("s"), { time: 1 });
34
+ add("min", ["minute"], convert$1(1, "min").to("s"), { time: 1 });
35
+ add("A", ["amp", "ampere"], 1, { current: 1 });
36
+ add("mA", ["milliamp", "milliampere"], .001, { current: 1 });
37
+ add("K", ["kelvin"], 1, { temperature: 1 });
38
+ /** A temperature's scale and offset from kelvin, the scale read across a wide span so subtracting the offset keeps its precision */
39
+ function temperature(unit) {
40
+ const offset = convert$1(0, unit).to("K");
41
+ return [(convert$1(1e6, unit).to("K") - offset) / 1e6, offset];
42
+ }
43
+ const [celsiusScale, celsiusOffset] = temperature("°C");
44
+ add("°C", ["c", "celsius"], celsiusScale, { temperature: 1 }, celsiusOffset);
45
+ const [fahrenheitScale, fahrenheitOffset] = temperature("°F");
46
+ add("°F", ["f", "fahrenheit"], fahrenheitScale, { temperature: 1 }, fahrenheitOffset);
47
+ add("rad", ["radian"], 1, { angle: 1 });
48
+ add("deg", ["°", "degree"], convert$1(1, "deg").to("rad"), { angle: 1 });
49
+ add("rot", [
50
+ "r",
51
+ "rotation",
52
+ "rev",
53
+ "revolution"
54
+ ], convert$1(1, "turn").to("rad"), { angle: 1 });
55
+ add("V", ["volt"], 1, {
56
+ mass: 1,
57
+ length: 2,
58
+ time: -3,
59
+ current: -1
60
+ });
61
+ add("mV", ["millivolt"], .001, {
62
+ mass: 1,
63
+ length: 2,
64
+ time: -3,
65
+ current: -1
66
+ });
67
+ add("N", ["newton"], 1, {
68
+ mass: 1,
69
+ length: 1,
70
+ time: -2
71
+ });
72
+ add("J", ["joule"], 1, {
73
+ mass: 1,
74
+ length: 2,
75
+ time: -2
76
+ });
77
+ add("W", ["watt"], 1, {
78
+ mass: 1,
79
+ length: 2,
80
+ time: -3
81
+ });
82
+ add("Hz", ["hertz"], 1, { time: -1 });
83
+ add("rpm", [], namedUnits.get("rot").scale / namedUnits.get("min").scale, {
84
+ angle: 1,
85
+ time: -1
86
+ });
87
+ add("rps", [], namedUnits.get("rot").scale, {
88
+ angle: 1,
89
+ time: -1
90
+ });
91
+ /** Make a unit from named units and their powers, merging repeated names and dropping zero powers */
92
+ function unitOf(factors) {
93
+ const powers = /* @__PURE__ */ new Map();
94
+ for (const [symbol, power] of factors) powers.set(symbol, (powers.get(symbol) ?? 0) + power);
95
+ const kept = [...powers].filter(([, power]) => power !== 0);
96
+ const dimension = Object.fromEntries(dimensions.map((name) => [name, 0]));
97
+ let scale = 1;
98
+ let offset = 0;
99
+ for (const [symbol, power] of kept) {
100
+ const named = namedUnits.get(symbol);
101
+ scale *= named.scale ** power;
102
+ offset = named.offset;
103
+ for (const [name, exponent] of Object.entries(named.dimension)) dimension[name] += exponent * power;
104
+ }
105
+ const text = (items) => items.map(([symbol, power]) => power === 1 ? symbol : `${symbol}^${power}`).join("*");
106
+ const numerator = kept.filter(([, power]) => power > 0);
107
+ const denominator = kept.filter(([, power]) => power < 0).map(([symbol, power]) => [symbol, -power]);
108
+ return {
109
+ label: denominator.length === 0 ? text(numerator) : `${numerator.length === 0 ? "1" : text(numerator)}/${text(denominator)}`,
110
+ dimension,
111
+ scale,
112
+ offset,
113
+ factors: kept
114
+ };
115
+ }
116
+ /** A unit without dimensions, ex. a ratio of two lengths */
117
+ const noUnit = unitOf([]);
118
+ function namedUnit(word) {
119
+ const lower = word.toLowerCase();
120
+ return unitNames.get(lower) ?? (lower.length > 1 && lower.endsWith("s") ? unitNames.get(lower.slice(0, -1)) : void 0);
121
+ }
122
+ /**
123
+ * Parse unit text, ex. `m/s^2`, `N*m`, `RPM`, or `meters per second squared`. Names ignore case and plurals. Each `/`
124
+ * divides by the name after it. `undefined` when it isn't a unit.
125
+ */
126
+ function parseUnit(text) {
127
+ const normalized = text.trim().replaceAll("²", "^2").replaceAll("³", "^3").replaceAll("·", "*").replaceAll(/\s+per\s+/giu, "/").replaceAll(/\s+squared\b/giu, "^2").replaceAll(/\s+cubed\b/giu, "^3").replaceAll(/\s*([*/^])\s*/gu, "$1");
128
+ if (normalized === "") return;
129
+ const factors = [];
130
+ for (const [, operator, word, power] of normalized.matchAll(/([*/\s]?)([^*/^\s]+)(?:\^(-?\d+))?/gu)) {
131
+ if (word === "1" && power === void 0 && factors.length === 0) continue;
132
+ const symbol = namedUnit(word);
133
+ if (symbol === void 0) return;
134
+ factors.push([symbol, (operator === "/" ? -1 : 1) * Number(power ?? 1)]);
135
+ }
136
+ if (normalized.replaceAll(/([*/\s]?)([^*/^\s]+)(?:\^(-?\d+))?/gu, "") !== "") return;
137
+ const unit = unitOf(factors);
138
+ return factors.some(([symbol]) => namedUnits.get(symbol).offset !== 0) && (unit.factors.length !== 1 || unit.factors[0][1] !== 1) ? void 0 : unit;
139
+ }
140
+ /** Whether two units measure the same thing, so values convert between them */
141
+ function sameDimension(a, b) {
142
+ return dimensions.every((name) => a.dimension[name] === b.dimension[name]);
143
+ }
144
+ /** Convert `value` between two units of the same dimension, see `sameDimension()` */
145
+ function convert(value, from, to) {
146
+ return (value * from.scale + from.offset - to.offset) / to.scale;
147
+ }
148
+ /** What a unit measures for error messages, ex. `length`, or its label when it's not one dimension */
149
+ function describeUnit(unit) {
150
+ const used = dimensions.filter((name) => unit.dimension[name] !== 0);
151
+ if (used.length === 0) return "a number without a unit";
152
+ return used.length === 1 && unit.dimension[used[0]] === 1 ? used[0] : unit.label;
153
+ }
154
+ // src/functions.ts
155
+ /** Define a function to pass to `check()`, see `docs/custom-functions.md` */
156
+ function defineFunction(definition) {
157
+ return definition;
158
+ }
159
+ const rad = parseUnit("rad");
160
+ const fullTurn = 2 * Math.PI;
161
+ /** `angle` (rad) from -π up to but not including π */
162
+ function wrapAngle(angle) {
163
+ return angle - fullTurn * Math.floor((angle + Math.PI) / fullTurn);
164
+ }
165
+ /** A unit rule for functions of an angle with a known unit, whose result is `result` or the angle's unit */
166
+ const angleOnly = (name, result) => (units) => {
167
+ const [unit] = units;
168
+ if (unit === void 0) return `${name}() needs an angle with a known unit, ex. \`Gyro/Yaw\`[deg]`;
169
+ return sameDimension(unit, rad) ? result ?? unit : `${name}() needs an angle, not ${describeUnit(unit)}`;
170
+ };
171
+ const withoutUnit = (name) => (units) => units.every((unit) => unit === void 0 || sameDimension(unit, noUnit)) ? noUnit : `${name}() needs a number without a unit, not ${describeUnit(units.find((unit) => unit !== void 0))}`;
172
+ const map = (name, apply, rest = {}) => ({
173
+ name,
174
+ arguments: 1,
175
+ apply,
176
+ ...rest
177
+ });
178
+ const variadic = {
179
+ arguments: { min: 2 },
180
+ sameDimension: true
181
+ };
182
+ /** Functions every formula can use, see `docs/language.md` */
183
+ const builtInFunctions = [
184
+ map("abs", ([x]) => Math.abs(x)),
185
+ map("sign", ([x]) => Math.sign(x), { unit: () => noUnit }),
186
+ map("sqrt", ([x]) => x < 0 ? NaN : Math.sqrt(x), { unit: ([unit]) => {
187
+ if (unit === void 0) return;
188
+ return unit.factors.every(([, power]) => power % 2 === 0) ? unitOf(unit.factors.map(([symbol, power]) => [symbol, power / 2])) : `sqrt() needs a unit with even powers, ex. m^2, not ${unit.label}`;
189
+ } }),
190
+ map("floor", ([x]) => Math.floor(x), { unit: withoutUnit("floor") }),
191
+ map("ceil", ([x]) => Math.ceil(x), { unit: withoutUnit("ceil") }),
192
+ map("round", ([x]) => Math.sign(x) * Math.round(Math.abs(x)), { unit: withoutUnit("round") }),
193
+ map("min", (args) => Math.min(...args), variadic),
194
+ map("max", (args) => Math.max(...args), variadic),
195
+ map("hypot", (args) => Math.hypot(...args), variadic),
196
+ map("clamp", ([x, low, high]) => low > high ? NaN : Math.min(Math.max(x, low), high), {
197
+ arguments: 3,
198
+ sameDimension: true
199
+ }),
200
+ map("deadband", ([x, width]) => Math.abs(x) <= width ? 0 : x, {
201
+ arguments: 2,
202
+ sameDimension: true
203
+ }),
204
+ map("sin", ([x]) => Math.sin(x), { unit: angleOnly("sin", noUnit) }),
205
+ map("cos", ([x]) => Math.cos(x), { unit: angleOnly("cos", noUnit) }),
206
+ map("atan2", ([y, x]) => Math.atan2(y, x), {
207
+ arguments: 2,
208
+ sameDimension: true,
209
+ unit: () => rad
210
+ }),
211
+ map("wrap", ([x]) => wrapAngle(x), { unit: angleOnly("wrap") }),
212
+ {
213
+ name: "unwrap",
214
+ arguments: 1,
215
+ unit: angleOnly("unwrap"),
216
+ create: () => {
217
+ let previous;
218
+ let unwrapped = 0;
219
+ return {
220
+ step: (_time, [angle]) => {
221
+ unwrapped = previous === void 0 ? angle : unwrapped + wrapAngle(angle - previous);
222
+ previous = angle;
223
+ return unwrapped;
224
+ },
225
+ reset: () => {
226
+ previous = void 0;
227
+ }
228
+ };
229
+ }
230
+ },
231
+ {
232
+ name: "integral",
233
+ arguments: 1,
234
+ unit: ([unit]) => unit === void 0 ? void 0 : unitOf([...unit.factors, ["s", 1]]),
235
+ create: () => {
236
+ let previous;
237
+ let total = 0;
238
+ return {
239
+ step: (time, [value], context) => {
240
+ total = previous === void 0 ? 0 : total + previous.value * context.secondsInRanges(previous.time, time);
241
+ previous = {
242
+ time,
243
+ value
244
+ };
245
+ return total;
246
+ },
247
+ reset: () => {
248
+ previous = void 0;
249
+ }
250
+ };
251
+ }
252
+ },
253
+ {
254
+ name: "derivative",
255
+ arguments: 1,
256
+ unit: ([unit]) => unit === void 0 ? void 0 : unitOf([...unit.factors, ["s", -1]]),
257
+ create: () => {
258
+ let previous;
259
+ return {
260
+ step: (time, [value], context) => {
261
+ const range = context.rangeIndex(time);
262
+ const result = previous === void 0 || previous.range !== range ? NaN : (value - previous.value) * 1e6 / (time - previous.time);
263
+ previous = {
264
+ time,
265
+ value,
266
+ range
267
+ };
268
+ return result;
269
+ },
270
+ reset: () => {
271
+ previous = void 0;
272
+ }
273
+ };
274
+ }
275
+ }
276
+ ];
277
+ // src/check.ts
278
+ /** The nodes of each plan without errors, kept out of the public type */
279
+ const compiledPlans = /* @__PURE__ */ new WeakMap();
280
+ var CheckError = class extends Error {
281
+ error;
282
+ constructor(code, message, span) {
283
+ super(message);
284
+ this.error = {
285
+ code,
286
+ message,
287
+ from: span.from,
288
+ to: span.to
289
+ };
290
+ }
291
+ };
292
+ const kelvin = parseUnit("K");
293
+ /** Functions that compare values, which work with units that have an offset like `°C` */
294
+ const comparisons = /* @__PURE__ */ new Set([
295
+ "min",
296
+ "max",
297
+ "clamp"
298
+ ]);
299
+ const offsetMessage = "°C and °F can only be added, subtracted, or compared with min(), max(), or clamp()";
300
+ /** Check a parsed formula's names, functions, and units, see `docs/language.md` */
301
+ function check(formula, options = {}) {
302
+ const functions = new Map(builtInFunctions.map((definition) => [definition.name, definition]));
303
+ for (const definition of options.functions ?? []) {
304
+ if (functions.has(definition.name)) throw new Error(`${definition.name}() is already a function`);
305
+ functions.set(definition.name, definition);
306
+ }
307
+ const nodes = [];
308
+ const inputs = [];
309
+ const names = /* @__PURE__ */ new Map();
310
+ const add = (node) => nodes.push(node) - 1;
311
+ const inputsOf = (children) => [...new Set(children.flatMap((child) => nodes[child].inputs))].toSorted((a, b) => a - b);
312
+ const constantOf = (node) => {
313
+ const found = nodes[node];
314
+ return found.kind === "constant" ? found.value : void 0;
315
+ };
316
+ /** A node applying `apply` to `children`, or a constant when they're all constants */
317
+ const addMap = (children, apply) => {
318
+ const constants = children.map(constantOf);
319
+ if (constants.every((value) => value !== void 0)) return add({
320
+ kind: "constant",
321
+ value: apply(constants),
322
+ inputs: []
323
+ });
324
+ return add({
325
+ kind: "map",
326
+ children,
327
+ apply,
328
+ inputs: inputsOf(children)
329
+ });
330
+ };
331
+ const parseUnitText = (text, span) => {
332
+ const unit = parseUnit(text);
333
+ if (unit === void 0) throw new CheckError("unit", `\`${text}\` isn't a unit.`, span);
334
+ return unit;
335
+ };
336
+ const rejectOffset = (args, span) => {
337
+ if (args.some(({ unit }) => unit !== void 0 && unit.offset !== 0)) throw new CheckError("unit", `${offsetMessage}.`, span);
338
+ };
339
+ /**
340
+ * Arguments that must measure the same thing, with unknown units read in the first known unit, as a difference when
341
+ * `delta` so `°C` offsets aren't added twice
342
+ */
343
+ const sameUnits = (args, span, what, delta) => {
344
+ const first = args.find(({ unit, bare }) => unit !== void 0 && !bare)?.unit;
345
+ if (first === void 0) return {
346
+ nodes: args.map(({ node }) => node),
347
+ unit: void 0
348
+ };
349
+ for (const { unit, bare } of args) if (unit !== void 0 && !bare && !sameDimension(unit, first)) throw new CheckError("unit", `${what} ${describeUnit(first)} and ${describeUnit(unit)}.`, span);
350
+ const offset = delta ? 0 : first.offset;
351
+ return {
352
+ nodes: args.map(({ node, unit, bare }) => unit === void 0 || bare ? addMap([node], ([value]) => value * first.scale + offset) : node),
353
+ unit: first
354
+ };
355
+ };
356
+ const visit = (expression) => {
357
+ switch (expression.type) {
358
+ case "number": {
359
+ const unit = expression.unit === void 0 ? void 0 : parseUnitText(expression.unit, expression);
360
+ const value = unit === void 0 ? expression.value : expression.value * unit.scale + unit.offset;
361
+ return {
362
+ node: add({
363
+ kind: "constant",
364
+ value,
365
+ inputs: []
366
+ }),
367
+ unit,
368
+ bare: unit === void 0
369
+ };
370
+ }
371
+ case "entry": {
372
+ let input = inputs.indexOf(expression.path);
373
+ if (input === -1) input = inputs.push(expression.path) - 1;
374
+ const given = options.units?.(expression.path);
375
+ const unit = expression.unit === void 0 ? typeof given === "string" ? parseUnit(given) : given : parseUnitText(expression.unit, expression);
376
+ return {
377
+ node: add({
378
+ kind: "input",
379
+ input,
380
+ scale: unit?.scale ?? 1,
381
+ offset: unit?.offset ?? 0,
382
+ inputs: [input]
383
+ }),
384
+ unit,
385
+ bare: false
386
+ };
387
+ }
388
+ case "name": {
389
+ const checked = names.get(expression.name);
390
+ if (checked === void 0) throw new CheckError("undefined-name", `\`${expression.name}\` isn't defined.`, expression);
391
+ return checked;
392
+ }
393
+ case "negate": {
394
+ const operand = visit(expression.operand);
395
+ rejectOffset([operand], expression);
396
+ return {
397
+ ...operand,
398
+ node: addMap([operand.node], ([value]) => -value)
399
+ };
400
+ }
401
+ case "binary": return visitBinary(expression);
402
+ case "call": return visitCall(expression);
403
+ }
404
+ };
405
+ const visitBinary = (expression) => {
406
+ const left = visit(expression.left);
407
+ const right = visit(expression.right);
408
+ const bare = left.bare && right.bare;
409
+ switch (expression.operator) {
410
+ case "+":
411
+ case "-": {
412
+ const verb = expression.operator === "+" ? "add" : "subtract";
413
+ const same = sameUnits([left, right], expression, `Can't ${verb}`, true);
414
+ const [a, b] = same.nodes;
415
+ const node = addMap([a, b], expression.operator === "+" ? ([x, y]) => x + y : ([x, y]) => x - y);
416
+ const unit = same.unit !== void 0 && same.unit.offset !== 0 ? kelvin : same.unit;
417
+ return {
418
+ node,
419
+ unit: bare ? void 0 : unit,
420
+ bare
421
+ };
422
+ }
423
+ case "*":
424
+ case "/": {
425
+ rejectOffset([left, right], expression);
426
+ const sign = expression.operator === "*" ? 1 : -1;
427
+ const known = (side) => side.bare ? noUnit : side.unit;
428
+ const [a, b] = [known(left), known(right)];
429
+ const unit = a === void 0 || b === void 0 ? void 0 : unitOf([...a.factors, ...b.factors.map(([symbol, power]) => [symbol, power * sign])]);
430
+ return {
431
+ node: addMap([left.node, right.node], sign === 1 ? ([x, y]) => x * y : ([x, y]) => x / y),
432
+ unit: bare ? void 0 : unit,
433
+ bare
434
+ };
435
+ }
436
+ case "^": {
437
+ rejectOffset([left, right], expression);
438
+ if (!right.bare && right.unit !== void 0 && !sameDimension(right.unit, noUnit)) throw new CheckError("unit", `A power needs a number without a unit, not ${describeUnit(right.unit)}.`, expression.right);
439
+ let unit = left.bare ? void 0 : left.unit;
440
+ if (unit !== void 0 && unit.factors.length > 0) {
441
+ const power = constantOf(right.node);
442
+ if (power === void 0 || !Number.isInteger(power)) throw new CheckError("unit", `A value with a unit can only be raised to a whole number.`, expression.right);
443
+ unit = unitOf(unit.factors.map(([symbol, exponent]) => [symbol, exponent * power]));
444
+ }
445
+ return {
446
+ node: addMap([left.node, right.node], ([x, y]) => x ** y),
447
+ unit,
448
+ bare
449
+ };
450
+ }
451
+ }
452
+ };
453
+ const visitCall = (expression) => {
454
+ const nameSpan = {
455
+ from: expression.from,
456
+ to: expression.from + expression.name.length
457
+ };
458
+ const definition = functions.get(expression.name);
459
+ if (definition === void 0) throw new CheckError("unknown-function", `\`${expression.name}\` isn't a function.`, nameSpan);
460
+ const count = expression.arguments.length;
461
+ const { min, max } = typeof definition.arguments === "number" ? {
462
+ min: definition.arguments,
463
+ max: definition.arguments
464
+ } : {
465
+ min: definition.arguments.min,
466
+ max: definition.arguments.max ?? Number.POSITIVE_INFINITY
467
+ };
468
+ if (count < min || count > max) {
469
+ const expected = min === max ? String(min) : max === Number.POSITIVE_INFINITY ? `at least ${min}` : `${min} to ${max}`;
470
+ throw new CheckError("arguments", `${definition.name}() takes ${expected} argument${expected === "1" ? "" : "s"}, not ${count}.`, expression);
471
+ }
472
+ const args = expression.arguments.map(visit);
473
+ const bare = args.every((arg) => arg.bare);
474
+ if (!comparisons.has(definition.name)) rejectOffset(args, expression);
475
+ let children = args.map(({ node }) => node);
476
+ let units = args.map(({ unit, bare: argBare }) => argBare ? noUnit : unit);
477
+ if (definition.sameDimension) {
478
+ const same = sameUnits(args, expression, `${definition.name}() can't combine`, false);
479
+ children = same.nodes;
480
+ units = units.map(() => same.unit);
481
+ }
482
+ const result = definition.unit === void 0 ? units[0] : definition.unit(units);
483
+ if (typeof result === "string") throw new CheckError("unit", result.endsWith(".") ? result : `${result}.`, expression);
484
+ if ("apply" in definition) return {
485
+ node: addMap(children, definition.apply),
486
+ unit: bare ? void 0 : result,
487
+ bare
488
+ };
489
+ if (children.every((child) => nodes[child].inputs.length === 0)) throw new CheckError("no-entries", `${definition.name}() needs a value from an entry.`, expression);
490
+ return {
491
+ node: add({
492
+ kind: "state",
493
+ children,
494
+ create: definition.create,
495
+ inputs: inputsOf(children)
496
+ }),
497
+ unit: result,
498
+ bare: false
499
+ };
500
+ };
501
+ try {
502
+ for (const definition of formula.definitions) {
503
+ const span = {
504
+ from: definition.from,
505
+ to: definition.from + definition.name.length
506
+ };
507
+ if (names.has(definition.name) || functions.has(definition.name)) {
508
+ const what = functions.has(definition.name) ? "a function" : "already defined";
509
+ throw new CheckError("duplicate-name", `\`${definition.name}\` is ${what}.`, span);
510
+ }
511
+ names.set(definition.name, visit(definition.value));
512
+ }
513
+ const result = visit(formula.result);
514
+ if (nodes[result.node].inputs.length === 0) throw new CheckError("no-entries", "A formula needs at least one entry.", formula.result);
515
+ if (result.node !== nodes.length - 1) addMap([result.node], ([value]) => value);
516
+ let unit = result.unit;
517
+ const wanted = typeof options.unit === "string" ? parseUnit(options.unit) : options.unit;
518
+ if (wanted !== void 0) {
519
+ if (unit !== void 0 && !sameDimension(unit, wanted)) throw new CheckError("unit", `The result is ${describeUnit(unit)}, which can't be converted to ${wanted.label}.`, formula.result);
520
+ unit = wanted;
521
+ }
522
+ const scale = result.unit === void 0 ? 1 : unit?.scale ?? 1;
523
+ const offset = result.unit === void 0 ? 0 : unit?.offset ?? 0;
524
+ const plan = {
525
+ inputs,
526
+ unit,
527
+ errors: []
528
+ };
529
+ compiledPlans.set(plan, {
530
+ nodes,
531
+ inputCount: inputs.length,
532
+ scale,
533
+ offset
534
+ });
535
+ return plan;
536
+ } catch (error) {
537
+ if (error instanceof CheckError) return {
538
+ inputs,
539
+ unit: void 0,
540
+ errors: [error.error]
541
+ };
542
+ throw error;
543
+ }
544
+ }
545
+ // src/evaluate.ts
546
+ function timeContext(ranges) {
547
+ if (ranges === void 0) return {
548
+ rangeIndex: () => 0,
549
+ secondsInRanges: (from, to) => (to - from) / 1e6
550
+ };
551
+ const before = (time) => {
552
+ let low = 0;
553
+ let high = ranges.length;
554
+ while (low < high) {
555
+ const middle = low + high >>> 1;
556
+ if (ranges[middle].start <= time) low = middle + 1;
557
+ else high = middle;
558
+ }
559
+ return low - 1;
560
+ };
561
+ return {
562
+ rangeIndex: (time) => {
563
+ const index = before(time);
564
+ return index >= 0 && time < ranges[index].end ? index : -1;
565
+ },
566
+ secondsInRanges: (from, to) => {
567
+ let total = 0;
568
+ for (let index = Math.max(0, before(from)); index < ranges.length && ranges[index].start < to; index++) {
569
+ const { start, end } = ranges[index];
570
+ total += Math.max(0, Math.min(end, to) - Math.max(start, from));
571
+ }
572
+ return total / 1e6;
573
+ }
574
+ };
575
+ }
576
+ /** Create an evaluator for a plan without errors */
577
+ function createEvaluator(plan, options = {}) {
578
+ const compiled = compiledPlans.get(plan);
579
+ if (compiled === void 0) throw new Error(plan.errors[0]?.message ?? "The plan wasn't made by check().");
580
+ const { nodes, inputCount, scale, offset } = compiled;
581
+ const { maxGap = 5e5, gaps = [], ranges } = options;
582
+ const context = timeContext(ranges);
583
+ const result = nodes.length - 1;
584
+ let timestamps = /* @__PURE__ */ new Float64Array(64);
585
+ let values = /* @__PURE__ */ new Float64Array(64);
586
+ let length = 0;
587
+ let read;
588
+ let latest;
589
+ let seen;
590
+ const changed = Array.from({ length: inputCount }, () => false);
591
+ let nodeValues;
592
+ let states;
593
+ let stepped;
594
+ let lastTime;
595
+ const reset = () => {
596
+ length = 0;
597
+ read = Array.from({ length: inputCount }, () => 0);
598
+ latest = Array.from({ length: inputCount }, () => NaN);
599
+ seen = Array.from({ length: inputCount }, () => false);
600
+ nodeValues = new Float64Array(nodes.length).fill(NaN);
601
+ states = nodes.map((node) => node.kind === "state" ? node.create() : void 0);
602
+ stepped = nodes.map(() => NaN);
603
+ lastTime = Number.NEGATIVE_INFINITY;
604
+ for (const [index, node] of nodes.entries()) if (node.kind === "constant") nodeValues[index] = node.value;
605
+ };
606
+ reset();
607
+ const crossesGap = (from, to) => gaps.some((gap) => gap.start < to && gap.end > from) || context.secondsInRanges(from, to) * 1e6 > maxGap;
608
+ const push = (time, value) => {
609
+ if (length === timestamps.length) {
610
+ const grownTimestamps = new Float64Array(length * 2);
611
+ grownTimestamps.set(timestamps);
612
+ timestamps = grownTimestamps;
613
+ const grownValues = new Float64Array(length * 2);
614
+ grownValues.set(values);
615
+ values = grownValues;
616
+ }
617
+ timestamps[length] = time;
618
+ values[length++] = value;
619
+ };
620
+ /** Calculate the nodes whose inputs were logged at `time` */
621
+ const calculate = (time) => {
622
+ const inRange = context.rangeIndex(time) !== -1;
623
+ for (const [index, node] of nodes.entries()) {
624
+ if (node.kind === "constant" || !node.inputs.some((input) => changed[input]) || !node.inputs.every((input) => seen[input])) continue;
625
+ switch (node.kind) {
626
+ case "input": {
627
+ const value = latest[node.input];
628
+ nodeValues[index] = Number.isFinite(value) ? value * node.scale + node.offset : NaN;
629
+ break;
630
+ }
631
+ case "map":
632
+ nodeValues[index] = node.apply(node.children.map((child) => nodeValues[child]));
633
+ break;
634
+ case "state": {
635
+ const args = node.children.map((child) => nodeValues[child]);
636
+ const state = states[index];
637
+ if (!inRange) {
638
+ nodeValues[index] = NaN;
639
+ break;
640
+ }
641
+ if (args.some((arg) => !Number.isFinite(arg))) {
642
+ state.reset?.();
643
+ stepped[index] = NaN;
644
+ nodeValues[index] = NaN;
645
+ break;
646
+ }
647
+ if (!Number.isNaN(stepped[index]) && crossesGap(stepped[index], time)) state.reset?.();
648
+ stepped[index] = time;
649
+ nodeValues[index] = state.step(time, args, context);
650
+ break;
651
+ }
652
+ }
653
+ if (!Number.isFinite(nodeValues[index])) nodeValues[index] = NaN;
654
+ }
655
+ if (nodes[result].inputs.every((input) => seen[input])) push(time, inRange ? (nodeValues[result] - offset) / scale : NaN);
656
+ };
657
+ const process = (series) => {
658
+ for (;;) {
659
+ let time = Number.POSITIVE_INFINITY;
660
+ for (const [input, samples] of series.entries()) if (read[input] < samples.length) time = Math.min(time, samples.timestamps[read[input]]);
661
+ if (time === Number.POSITIVE_INFINITY) return;
662
+ for (const [input, samples] of series.entries()) {
663
+ changed[input] = false;
664
+ while (read[input] < samples.length && samples.timestamps[read[input]] === time) {
665
+ latest[input] = samples.values[read[input]];
666
+ read[input]++;
667
+ changed[input] = true;
668
+ seen[input] = true;
669
+ }
670
+ }
671
+ lastTime = time;
672
+ calculate(time);
673
+ }
674
+ };
675
+ return {
676
+ sync(inputs) {
677
+ const series = plan.inputs.map((path) => {
678
+ const samples = inputs[path];
679
+ if (samples === void 0) throw new Error(`Missing input ${path}`);
680
+ return samples;
681
+ });
682
+ const restarted = series.some((samples, input) => samples.length < read[input] || read[input] < samples.length && samples.timestamps[read[input]] <= lastTime);
683
+ if (restarted) reset();
684
+ process(series);
685
+ return { restarted };
686
+ },
687
+ reset,
688
+ get output() {
689
+ return {
690
+ timestamps,
691
+ values,
692
+ length
693
+ };
694
+ }
695
+ };
696
+ }
697
+ // src/parser.ts
698
+ const parser = LRParser.deserialize({
699
+ version: 14,
700
+ states: "%|OVQPOOOOQO'#Ct'#CtOVQPOOOkQPO'#CaO!]QPO'#CdO#iQPO'#CfO#pQPO'#ClO#pQPO'#CmQ$dQPOOOOQO'#C{'#C{OfQPO'#CuO$kQPOOOOQO-E6r-E6rOOQO,58{,58{OOQO,59O,59OO#pQPO'#ChOOQO,59R,59RO#pQPO,58xO$|QPO'#CfO%WQPO,59WO%_QPO,59XQfQPOOO#pQPO,59ZO#pQPO,59ZO%|QPO,59aOOQO-E6s-E6sO&bQPO,59SO&lQPO1G.dOOQO1G.r1G.rO'[QPO1G.uO'fQPO1G.uP'pQPO'#C^O#pQPO'#CvO'uQPO1G.nOOQO1G.n1G.nO'}QPO,59bOOQO-E6t-E6tOOQO7+$Y7+$Y",
701
+ stateData: "(X~OmOS~ORTOUROXSO]UObVOnPO~OV]ObTXdTXeTXfTXgTXkTXnTX_TX^TX~OV^ObWXdWXeWXfWXgWXkWXnWX_WX^WX~O]_ObYXdYXeYXfYXgYXkYXnYX~OSaO~P!}ORbOUROXSO]UObVO~ObgOdfOefOffOggO~OnPO~P$RORTOUROXSO]UObVO~O_YX^YX~P!}O_lO~P$ROdfObaaeaafaagaakaanaa_aa^aa~OnPORiaUiaXia]iabia~O^pO_rO~P$ROnQi~P$ROdfObcigcikcinci_ci^ci~Oecifci~P&sOefOffO~P&sOSaO~O^pO_uO~O^ja_ja~P$RO",
702
+ goto: "#_pPPqPPvPPvPvv!SPPPvvPvPPPP!W!f!mPPPP!sVYOQZeXOQUVZ_afgpT`TbQQOU[QehQeWRhYSZOQRiZQqjRtqUWOQZQcUQdVQj_QkaQmfQngRsp",
703
+ nodeNames: "⚠ Formula Definition Identifier = NumberLiteral Number Unit EntryReference Entry Variable Call ArgList ( , ) ParenthesizedExpression UnaryExpression - BinaryExpression ^ * / +",
704
+ maxTerm: 31,
705
+ nodeProps: [[
706
+ "group",
707
+ -7,
708
+ 5,
709
+ 8,
710
+ 10,
711
+ 11,
712
+ 16,
713
+ 17,
714
+ 19,
715
+ "Expression"
716
+ ]],
717
+ skippedNodes: [0],
718
+ repeatNodeCount: 3,
719
+ tokenData: "'c~ReXY!dYZ!r]^!dpq!dxy!wyz!|z{#R{|#W|}#]}!O#b!O!P#g!P!Q$g!Q![$l!]!^!r!_!`$}!c!}%S!}#O%e#Q#R&V#R#S%S#S#T&[#T#o%S~!iRm~XY!d]^!dpq!d~!wOn~~!|O]~~#RO_~~#WOe~~#]Og~~#bO^~~#gOb~~#jP!Q![#m~#rRU~!Q![#m!g!h#{#X#Y#{~$OR{|$X}!O$X!Q![$_~$[P!Q![$_~$dPU~!Q![$_~$lOf~~$qSU~!O!P#m!Q![$l!g!h#{#X#Y#{~%SOS~~%XSR~!Q![%S!c!}%S#R#S%S#T#o%S~%hUOY%eZ#P%e#P#Q%z#Q;'S%e;'S;=`&P<%lO%e~&POV~~&SP;=`<%l%e~&[Od~~&_WOY&[Z#O&[#O#P&w#P#S&[#S#T'^#T;'S&[;'S;=`'W<%lO&[~&zSOY&[Z;'S&[;'S;=`'W<%lO&[~'ZP;=`<%l&[~'cOX~",
720
+ tokenizers: [0],
721
+ topRules: { "Formula": [0, 1] },
722
+ tokenPrec: 0
723
+ });
724
+ // src/syntax.ts
725
+ /** An entry's path with a leading `/` */
726
+ function normalizePath(path) {
727
+ return path.startsWith("/") ? path : `/${path}`;
728
+ }
729
+ /** Parse a formula's text, see `docs/language.md` */
730
+ function parse(text) {
731
+ const tree = parser.parse(text);
732
+ const cursor = tree.cursor();
733
+ do
734
+ if (cursor.type.isError) {
735
+ const { from } = cursor;
736
+ const to = Math.max(cursor.to, Math.min(from + 1, text.length));
737
+ const found = text.slice(from, to).trim();
738
+ return {
739
+ formula: void 0,
740
+ errors: [{
741
+ code: "syntax",
742
+ message: found === "" ? "The formula ends too early." : `\`${found}\` isn't expected here.`,
743
+ from,
744
+ to
745
+ }]
746
+ };
747
+ }
748
+ while (cursor.next());
749
+ const slice = (node) => text.slice(node.from, node.to);
750
+ const unitOf = (node) => {
751
+ const unit = node.getChild("Unit");
752
+ return unit === null ? {} : { unit: slice(unit).slice(1, -1).trim() };
753
+ };
754
+ const expressions = (node) => node.getChildren("Expression");
755
+ const convert = (node) => {
756
+ const span = {
757
+ from: node.from,
758
+ to: node.to
759
+ };
760
+ switch (node.name) {
761
+ case "NumberLiteral": return {
762
+ type: "number",
763
+ value: Number(slice(node.getChild("Number"))),
764
+ ...unitOf(node),
765
+ ...span
766
+ };
767
+ case "EntryReference": return {
768
+ type: "entry",
769
+ path: normalizePath(slice(node.getChild("Entry")).slice(1, -1).replaceAll(/\\(.)/gu, "$1")),
770
+ ...unitOf(node),
771
+ ...span
772
+ };
773
+ case "Variable": return {
774
+ type: "name",
775
+ name: slice(node),
776
+ ...span
777
+ };
778
+ case "Call": return {
779
+ type: "call",
780
+ name: slice(node.getChild("Identifier")),
781
+ arguments: expressions(node.getChild("ArgList")).map(convert),
782
+ ...span
783
+ };
784
+ case "ParenthesizedExpression": return convert(expressions(node)[0]);
785
+ case "UnaryExpression": return {
786
+ type: "negate",
787
+ operand: convert(expressions(node)[0]),
788
+ ...span
789
+ };
790
+ case "BinaryExpression": {
791
+ const [left, right] = expressions(node);
792
+ return {
793
+ type: "binary",
794
+ operator: text.slice(left.to, right.from).trim(),
795
+ left: convert(left),
796
+ right: convert(right),
797
+ ...span
798
+ };
799
+ }
800
+ default: throw new Error(`Unexpected ${node.name} node`);
801
+ }
802
+ };
803
+ const top = tree.topNode;
804
+ return {
805
+ formula: {
806
+ definitions: top.getChildren("Definition").map((node) => {
807
+ return {
808
+ name: slice(node.getChild("Identifier")),
809
+ value: convert(expressions(node)[0]),
810
+ from: node.from,
811
+ to: node.to
812
+ };
813
+ }),
814
+ result: convert(expressions(top).at(-1))
815
+ },
816
+ errors: []
817
+ };
818
+ }
819
+ const precedence = {
820
+ "+": 1,
821
+ "-": 1,
822
+ "*": 2,
823
+ "/": 2,
824
+ negate: 3,
825
+ "^": 4
826
+ };
827
+ function precedenceOf(expression) {
828
+ if (expression.type === "binary") return precedence[expression.operator];
829
+ return expression.type === "negate" ? precedence.negate : 5;
830
+ }
831
+ /** A formula's text, canonical when the formula has no definitions, see `docs/language.md` */
832
+ function format(formula) {
833
+ return [...formula.definitions.map(({ name, value }) => `${name} = ${formatExpression(value)}`), formatExpression(formula.result)].join("\n");
834
+ }
835
+ function formatUnit(unit) {
836
+ return unit === void 0 ? "" : `[${parseUnit(unit)?.label ?? unit}]`;
837
+ }
838
+ function formatExpression(expression) {
839
+ const wrap = (inner, parentheses) => parentheses ? `(${formatExpression(inner)})` : formatExpression(inner);
840
+ switch (expression.type) {
841
+ case "number": return `${String(expression.value)}${formatUnit(expression.unit)}`;
842
+ case "entry": return `\`${expression.path.replaceAll(/[`\\]/gu, "\\$&")}\`${formatUnit(expression.unit)}`;
843
+ case "name": return expression.name;
844
+ case "call": return `${expression.name}(${expression.arguments.map(formatExpression).join(", ")})`;
845
+ case "negate": return `-${wrap(expression.operand, precedenceOf(expression.operand) < precedence.negate)}`;
846
+ case "binary": {
847
+ const own = precedence[expression.operator];
848
+ const left = precedenceOf(expression.left);
849
+ const right = precedenceOf(expression.right);
850
+ const power = expression.operator === "^";
851
+ const leftParentheses = power ? left <= own : left < own;
852
+ const rightParentheses = power ? right < precedence.negate : right <= own;
853
+ return `${wrap(expression.left, leftParentheses)} ${expression.operator} ${wrap(expression.right, rightParentheses)}`;
854
+ }
855
+ }
856
+ }
857
+ export { builtInFunctions, check, convert, createEvaluator, defineFunction, dimensions, format, normalizePath, parse, parseUnit, sameDimension };
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.60.1"
9
+ }
10
+ ]
11
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@team581/log-formula",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Calculate numeric entries from other entries in robot logs",
5
+ "homepage": "https://github.com/jonahsnider/doglog/tree/main/packages/log-formula#readme",
6
+ "license": "MIT",
7
+ "author": {
8
+ "name": "Jonah Snider",
9
+ "email": "jonah@jonahsnider.com",
10
+ "url": "https://jonahsnider.com"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jonahsnider/doglog.git",
15
+ "directory": "packages/log-formula"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "type": "module",
21
+ "exports": {
22
+ ".": "./dist/index.mjs",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "dependencies": {
29
+ "@lezer/common": "^1.5.7",
30
+ "@lezer/lr": "^1.4.13",
31
+ "convert": "^8.2.1"
32
+ },
33
+ "devDependencies": {
34
+ "@lezer/generator": "1.8.1",
35
+ "@microsoft/api-extractor": "7.60.1",
36
+ "@tsconfig/recommended": "1.0.14",
37
+ "@tsconfig/strictest": "2.0.9",
38
+ "@types/node": "26.6.11",
39
+ "@typescript/native-preview": "7.0.0-dev.20260707.2",
40
+ "vite-plus": "1.8.0"
41
+ },
42
+ "tsdocMetadata": "./dist/tsdoc-metadata.json",
43
+ "scripts": {
44
+ "api:check": "api-extractor run",
45
+ "api:update": "api-extractor run --local",
46
+ "bench": "vp test bench",
47
+ "build": "vp pack",
48
+ "check": "vp check",
49
+ "check:fix": "vp check --fix",
50
+ "grammar": "lezer-generator src/formula.grammar --typeScript --noTerms -o src/parser.ts",
51
+ "test": "vp test run"
52
+ }
6
53
  }