@rulecad/variables 0.1.6 → 0.2.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/package.json +1 -1
- package/variables.d.mts +14 -7
- package/variables.mjs +89 -15
package/package.json
CHANGED
package/variables.d.mts
CHANGED
|
@@ -6,11 +6,20 @@ export function checkName(name: any, d: any, v: any): string | number;
|
|
|
6
6
|
* @returns {number}
|
|
7
7
|
*/
|
|
8
8
|
export function evaluate(src: string | number, lookup: (name: string) => number): number;
|
|
9
|
+
/**
|
|
10
|
+
* The unit an expression comes to, and any mixing of units on the way (mm added to degrees, a sine of millimetres).
|
|
11
|
+
* @param {string | number} src @param {(name: string) => string | undefined} unitOf a name's unit
|
|
12
|
+
* @returns {{ unit: string | null, problems: string[] }}
|
|
13
|
+
*/
|
|
14
|
+
export function unitsOf(src: string | number, unitOf: (name: string) => string | undefined): {
|
|
15
|
+
unit: string | null;
|
|
16
|
+
problems: string[];
|
|
17
|
+
};
|
|
9
18
|
/**
|
|
10
19
|
* Every variable's value, and an entry for each variable and rule for checks and rule cards.
|
|
11
20
|
* @param {DesignObject} object
|
|
12
21
|
* @param {{ sets?: Record<string, RuleSet>, set?: Record<string, number | string>, display?: Record<string, number | string>, load?: (name: string) => RuleSet }} [options]
|
|
13
|
-
* @returns {{ values: Record<string, any>, entries: Entry[] }}
|
|
22
|
+
* @returns {{ values: Record<string, any>, entries: Entry[], deps: Record<string, string[]> }} deps: each name with the names its own expression reads
|
|
14
23
|
*/
|
|
15
24
|
export function resolve(object: DesignObject, { sets, set, display, load }?: {
|
|
16
25
|
sets?: Record<string, RuleSet>;
|
|
@@ -20,6 +29,7 @@ export function resolve(object: DesignObject, { sets, set, display, load }?: {
|
|
|
20
29
|
}): {
|
|
21
30
|
values: Record<string, any>;
|
|
22
31
|
entries: Entry[];
|
|
32
|
+
deps: Record<string, string[]>;
|
|
23
33
|
};
|
|
24
34
|
/**
|
|
25
35
|
* Number literals in a design's code other than 0, 1 and 2 (outside comments and strings).
|
|
@@ -30,10 +40,6 @@ export function lint(source: string): {
|
|
|
30
40
|
line: number;
|
|
31
41
|
text: string;
|
|
32
42
|
}[];
|
|
33
|
-
/** @typedef {{ value: number | string, unit?: string, rule?: string, kind?: 'spec' | 'community' | 'default' | 'estimate' | 'measured', source?: string, checked?: string, label?: string, show?: boolean, interface?: boolean, tweak?: { min: number, max: number }, choice?: string[], type?: 'text' | 'anchor' | 'layout' }} Variable */
|
|
34
|
-
/** @typedef {{ name?: string, rules: Record<string, Variable> }} RuleSet */
|
|
35
|
-
/** @typedef {{ uses?: string[], variables?: Record<string, Variable>, [field: string]: any }} DesignObject */
|
|
36
|
-
/** @typedef {{ name: string, value: number | string, used?: boolean, set?: boolean, [field: string]: any }} Entry */
|
|
37
43
|
export const ANCHORS: string[];
|
|
38
44
|
export function isName(d: any): boolean;
|
|
39
45
|
export function options(d: any): any;
|
|
@@ -42,8 +48,9 @@ export type Variable = {
|
|
|
42
48
|
value: number | string;
|
|
43
49
|
unit?: string;
|
|
44
50
|
rule?: string;
|
|
45
|
-
kind?: "spec" | "community" | "default" | "estimate" | "measured";
|
|
51
|
+
kind?: "spec" | "community" | "default" | "estimate" | "measured" | "derived";
|
|
46
52
|
source?: string;
|
|
53
|
+
licence?: string;
|
|
47
54
|
checked?: string;
|
|
48
55
|
label?: string;
|
|
49
56
|
show?: boolean;
|
|
@@ -53,7 +60,7 @@ export type Variable = {
|
|
|
53
60
|
max: number;
|
|
54
61
|
};
|
|
55
62
|
choice?: string[];
|
|
56
|
-
type?: "text" | "anchor" | "layout";
|
|
63
|
+
type?: "text" | "anchor" | "layout" | "problem";
|
|
57
64
|
};
|
|
58
65
|
export type RuleSet = {
|
|
59
66
|
name?: string;
|
package/variables.mjs
CHANGED
|
@@ -7,14 +7,17 @@
|
|
|
7
7
|
// No imports and no file access: it runs in a browser as well. Rule sets are handed in (sets) or fetched by name
|
|
8
8
|
// through load(name), such as one that reads rules/<name>.json.
|
|
9
9
|
|
|
10
|
-
/** @typedef {{ value: number | string, unit?: string, rule?: string, kind?: 'spec' | 'community' | 'default' | 'estimate' | 'measured', source?: string, checked?: string, label?: string, show?: boolean, interface?: boolean, tweak?: { min: number, max: number }, choice?: string[], type?: 'text' | 'anchor' | 'layout' }} Variable */
|
|
10
|
+
/** @typedef {{ value: number | string, unit?: string, rule?: string, kind?: 'spec' | 'community' | 'default' | 'estimate' | 'measured' | 'derived', source?: string, licence?: string, checked?: string, label?: string, show?: boolean, interface?: boolean, tweak?: { min: number, max: number }, choice?: string[], type?: 'text' | 'anchor' | 'layout' | 'problem' }} Variable */
|
|
11
11
|
/** @typedef {{ name?: string, rules: Record<string, Variable> }} RuleSet */
|
|
12
12
|
/** @typedef {{ uses?: string[], variables?: Record<string, Variable>, [field: string]: any }} DesignObject */
|
|
13
13
|
/** @typedef {{ name: string, value: number | string, used?: boolean, set?: boolean, [field: string]: any }} Entry */
|
|
14
14
|
|
|
15
|
+
// An error with a code (var.unknown, set.range, …) and, where known, the JSON path to fix (variables.cap_h.value)
|
|
16
|
+
const fail = (code, message, path) => Object.assign(new Error(message), { code, ...(path ? { path } : {}) });
|
|
17
|
+
|
|
15
18
|
export const ANCHORS = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'];
|
|
16
19
|
// A variable that holds a name or text, and the names it may hold (null: any text)
|
|
17
|
-
export const isName = (d) => !!(d.choice || ['text', 'anchor', 'layout'].includes(d.type));
|
|
20
|
+
export const isName = (d) => !!(d.choice || ['text', 'anchor', 'layout', 'problem'].includes(d.type));
|
|
18
21
|
export const options = (d) => (d.type === 'anchor' ? ANCHORS : d.type === 'text' ? null : d.choice);
|
|
19
22
|
export function checkName(name, d, v) {
|
|
20
23
|
const s = String(v), opts = options(d), match = opts?.find((o) => String(o) === s);
|
|
@@ -75,6 +78,58 @@ export function evaluate(src, lookup) {
|
|
|
75
78
|
}
|
|
76
79
|
|
|
77
80
|
|
|
81
|
+
// ---------- units ----------
|
|
82
|
+
// A unit as powers of its parts: "mm" {mm: 1}, "mm²" {mm: 2}, "deg" {deg: 1}. Numbers and names with no unit are
|
|
83
|
+
// unknown (null), which matches anything: only units that are both known and different are a problem.
|
|
84
|
+
const SUP = { '²': 2, '³': 3 }, ALIAS = { '°': 'deg', degrees: 'deg', degree: 'deg' };
|
|
85
|
+
// Physical units only: counts (keys, u, rows, %) are plain numbers, so 12 keys × 19.05 mm is a length
|
|
86
|
+
const PHYSICAL = new Set(['mm', 'cm', 'm', 'in', 'deg', 'rad', 'g', 'kg', 'N', 'W', 'V', 'A', 's', 'ms', 'Hz', 'mAh', 'Wh']);
|
|
87
|
+
function parseUnit(u) {
|
|
88
|
+
if (u == null || u === '') return null;
|
|
89
|
+
const base = /^([a-zA-Z°]+)/.exec(String(u).trim())?.[1];
|
|
90
|
+
if (!PHYSICAL.has(ALIAS[base] || base)) return null;
|
|
91
|
+
const m = /^([a-zA-Z°]+)([²³])?$/.exec(String(u).trim());
|
|
92
|
+
if (!m) return { [String(u)]: 1 };
|
|
93
|
+
return { [ALIAS[m[1]] || m[1]]: m[2] ? SUP[m[2]] : 1 };
|
|
94
|
+
}
|
|
95
|
+
const showUnit = (x) => (x == null ? 'a number' : Object.keys(x).length ? Object.entries(x).map(([k, n]) => (n === 1 ? k : n === 2 ? `${k}²` : n === 3 ? `${k}³` : `${k}^${n}`)).join('·') : 'a plain number');
|
|
96
|
+
const sameUnit = (a, b) => a == null || b == null || (Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, n]) => b[k] === n));
|
|
97
|
+
const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : null; if (b == null) return a; const o = { ...a }; for (const [k, n] of Object.entries(b)) { o[k] = (o[k] || 0) + sign * n; if (!o[k]) delete o[k]; } return o; };
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The unit an expression comes to, and any mixing of units on the way (mm added to degrees, a sine of millimetres).
|
|
101
|
+
* @param {string | number} src @param {(name: string) => string | undefined} unitOf a name's unit
|
|
102
|
+
* @returns {{ unit: string | null, problems: string[] }}
|
|
103
|
+
*/
|
|
104
|
+
export function unitsOf(src, unitOf) {
|
|
105
|
+
if (typeof src === 'number') return { unit: null, problems: [] };
|
|
106
|
+
const t = tokens(String(src)), problems = [];
|
|
107
|
+
let i = 0;
|
|
108
|
+
const take = (op) => (t[i]?.op === op ? (i++, true) : false);
|
|
109
|
+
const add = (a, b, op) => { if (!sameUnit(a, b)) problems.push(`${op === '+' ? 'adds' : 'takes'} ${showUnit(b)} ${op === '+' ? 'to' : 'from'} ${showUnit(a)}`); return a ?? b; };
|
|
110
|
+
const expr = () => { let v = term(); for (;;) { if (take('+')) v = add(v, term(), '+'); else if (take('-')) v = add(v, term(), '-'); else return v; } };
|
|
111
|
+
const term = () => { let v = unary(); for (;;) { if (take('*')) v = combine(v, unary(), 1); else if (take('/')) v = combine(v, unary(), -1); else return v; } };
|
|
112
|
+
const unary = () => (take('-') || take('+') ? unary() : atom());
|
|
113
|
+
const atom = () => {
|
|
114
|
+
const k = t[i++];
|
|
115
|
+
if (!k) return null;
|
|
116
|
+
if (k.n != null) return null;
|
|
117
|
+
if (k.op === '(') { const v = expr(); take(')'); return v; }
|
|
118
|
+
if (k.id && FNS[k.id] && take('(')) {
|
|
119
|
+
const args = [expr()];
|
|
120
|
+
while (take(',')) args.push(expr());
|
|
121
|
+
take(')');
|
|
122
|
+
if (['sind', 'cosd', 'tand'].includes(k.id)) { if (args[0] && !sameUnit(args[0], { deg: 1 })) problems.push(`takes ${k.id} of ${showUnit(args[0])}, not degrees`); return {}; }
|
|
123
|
+
if (k.id === 'round') return args[0];
|
|
124
|
+
return args.reduce((a, b) => add(a, b, '+'));
|
|
125
|
+
}
|
|
126
|
+
return k.id ? parseUnit(unitOf(k.id)) : null;
|
|
127
|
+
};
|
|
128
|
+
const v = expr();
|
|
129
|
+
return { unit: v == null ? null : showUnit(v), problems, value: v };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
|
|
78
133
|
|
|
79
134
|
// resolve(object, { sets, set }) -> { values, entries }
|
|
80
135
|
// values: { stem_arm: 1.27, x1c: { line: 0.42, … }, mx: { … } } for the design's main()
|
|
@@ -90,48 +145,58 @@ export function evaluate(src, lookup) {
|
|
|
90
145
|
// { "type": "text", "value": "", "max": 8 } free text, e.g. a keycap's legend
|
|
91
146
|
// { "type": "anchor", "value": "mc" } one of 9 places on a face: tl tc tr, ml mc mr, bl bc br
|
|
92
147
|
// { "type": "layout", "value": "grid", "choice": [...] } a layout file in the project's layouts/ (or a built-in)
|
|
148
|
+
// { "type": "problem", "value": "lever" } an optimisation problem in the project's problems/
|
|
93
149
|
/**
|
|
94
150
|
* Every variable's value, and an entry for each variable and rule for checks and rule cards.
|
|
95
151
|
* @param {DesignObject} object
|
|
96
152
|
* @param {{ sets?: Record<string, RuleSet>, set?: Record<string, number | string>, display?: Record<string, number | string>, load?: (name: string) => RuleSet }} [options]
|
|
97
|
-
* @returns {{ values: Record<string, any>, entries: Entry[] }}
|
|
153
|
+
* @returns {{ values: Record<string, any>, entries: Entry[], deps: Record<string, string[]> }} deps: each name with the names its own expression reads
|
|
98
154
|
*/
|
|
99
155
|
export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}) {
|
|
100
156
|
const ruleSets = Object.fromEntries((object.uses || []).map((u) => {
|
|
101
157
|
const s = sets[u] || (load ? load(u) : null);
|
|
102
|
-
if (!s) throw
|
|
158
|
+
if (!s) throw fail('rules.missing', `no rule set "${u}" (hand it in as sets.${u}, or give a load function)`, 'uses');
|
|
103
159
|
return [s.name || u, s];
|
|
104
160
|
}));
|
|
105
161
|
const vars = object.variables || {};
|
|
106
162
|
for (const [k, v] of Object.entries(set)) {
|
|
107
163
|
const d = vars[k];
|
|
108
|
-
if (!d) throw
|
|
164
|
+
if (!d) throw fail('set.unknown', `no variable "${k}" to set (variables: ${Object.keys(vars).join(', ')})`, `variables.${k}`);
|
|
109
165
|
if (isName(d)) { checkName(k, d, v); continue; }
|
|
110
|
-
if (!d.tweak) throw
|
|
166
|
+
if (!d.tweak) throw fail('set.fixed', `"${k}" is fixed by its rule; only variables with a tweak range can be set`, `variables.${k}.tweak`);
|
|
111
167
|
const n = Number(v);
|
|
112
|
-
if (!Number.isFinite(n) || n < d.tweak.min || n > d.tweak.max) throw
|
|
168
|
+
if (!Number.isFinite(n) || n < d.tweak.min || n > d.tweak.max) throw fail('set.range', `${k} must be a number from ${d.tweak.min} to ${d.tweak.max}`, `variables.${k}.tweak`);
|
|
113
169
|
}
|
|
114
170
|
|
|
115
|
-
|
|
171
|
+
// deps: each name's own references (what its expression reads), for explaining a value; stack: whose expression is being read
|
|
172
|
+
const done = new Map(), busy = new Set(), deps = new Map(), stack = [];
|
|
173
|
+
const pathOf = (name) => (name.includes('.') ? `rules.${name}.value` : `variables.${name}.value`);
|
|
116
174
|
const lookup = (name) => {
|
|
175
|
+
if (stack.length) deps.get(stack[stack.length - 1]).add(name);
|
|
117
176
|
if (done.has(name)) return done.get(name);
|
|
118
|
-
if (busy.has(name)) throw
|
|
177
|
+
if (busy.has(name)) throw fail('var.cycle', `"${name}" refers back to itself`, pathOf(name));
|
|
119
178
|
busy.add(name);
|
|
120
179
|
let src, where;
|
|
121
180
|
if (name.includes('.')) {
|
|
122
181
|
let [s, r] = name.split('.');
|
|
123
182
|
if (!ruleSets[s] && ruleSets[s.replace(/_/g, '-')]) s = s.replace(/_/g, '-'); // mx_switch.housing_top reads the set named mx-switch (a - is a minus here)
|
|
124
|
-
if (!ruleSets[s]) throw
|
|
125
|
-
if (!ruleSets[s].rules[r]) throw
|
|
183
|
+
if (!ruleSets[s]) throw fail('var.unknown-set', `"${name}": rule set "${s}" isn't in uses (${Object.keys(ruleSets).join(', ') || 'none'})`);
|
|
184
|
+
if (!ruleSets[s].rules[r]) throw fail('var.unknown-rule', `"${name}": no rule "${r}" in ${s}`);
|
|
126
185
|
src = ruleSets[s].rules[r].value; where = (n) => (n.includes('.') ? n : `${s}.${n}`); // a rule's names are its own set's
|
|
127
186
|
} else {
|
|
128
|
-
if (!vars[name]) throw
|
|
187
|
+
if (!vars[name]) throw fail('var.unknown', `no variable "${name}"`);
|
|
129
188
|
if (isName(vars[name])) { busy.delete(name); const c = checkName(name, vars[name], name in display ? display[name] : name in set ? set[name] : vars[name].value); done.set(name, c); return c; }
|
|
130
189
|
src = name in display ? display[name] : name in set ? Number(set[name]) : vars[name].value; where = (n) => n; // display: the screen's settings win
|
|
131
190
|
}
|
|
132
191
|
let v;
|
|
133
|
-
|
|
134
|
-
|
|
192
|
+
deps.set(name, new Set()); stack.push(name);
|
|
193
|
+
try { v = evaluate(src, (n) => lookup(where(n))); } catch (e) {
|
|
194
|
+
busy.delete(name); stack.pop();
|
|
195
|
+
const out = e.message.startsWith('"') || e.message.startsWith('no ') ? e : fail(e.code || 'var.expression', `"${name}" = ${JSON.stringify(src)}: ${e.message}`);
|
|
196
|
+
if (!out.path) out.path = pathOf(name); // the first expression that reads the bad name: where to fix it
|
|
197
|
+
throw out;
|
|
198
|
+
}
|
|
199
|
+
stack.pop(); busy.delete(name); done.set(name, v);
|
|
135
200
|
return v;
|
|
136
201
|
};
|
|
137
202
|
|
|
@@ -140,6 +205,15 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
|
|
|
140
205
|
values[name] = lookup(name);
|
|
141
206
|
entries.push({ name, ...d, value: values[name], expr: typeof d.value === 'string' ? d.value : undefined, set: name in set });
|
|
142
207
|
}
|
|
208
|
+
// Units: each variable's expression, its names' units mixed only where they agree, and coming to the unit it says
|
|
209
|
+
const unitOf = (n) => (n.includes('.') ? ruleSets[n.split('.')[0].replace(/_/g, '-')]?.rules[n.split('.')[1]]?.unit ?? ruleSets[n.split('.')[0]]?.rules[n.split('.')[1]]?.unit : vars[n]?.unit);
|
|
210
|
+
const units = [];
|
|
211
|
+
for (const [name, d] of Object.entries(vars)) {
|
|
212
|
+
if (typeof d.value !== 'string' || isName(d)) continue;
|
|
213
|
+
const r = unitsOf(d.value, unitOf), said = parseUnit(d.unit);
|
|
214
|
+
for (const p of r.problems) units.push({ name, path: `variables.${name}.value`, message: `"${name}" = ${d.value}: ${p}` });
|
|
215
|
+
if (said && r.value && !sameUnit(said, r.value)) units.push({ name, path: `variables.${name}.unit`, message: `"${name}" comes to ${r.unit}, but its unit says ${showUnit(said)}` });
|
|
216
|
+
}
|
|
143
217
|
const used = new Set(done.keys()); // rules the variables actually refer to (directly or through other rules)
|
|
144
218
|
for (const [s, rs] of Object.entries(ruleSets)) {
|
|
145
219
|
values[s] = {};
|
|
@@ -149,7 +223,7 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
|
|
|
149
223
|
}
|
|
150
224
|
if (rs.footprints) values[s].footprints = rs.footprints; // pad data for boards (v.esp32c6.footprints.module), as the set gives it
|
|
151
225
|
}
|
|
152
|
-
return { values, entries };
|
|
226
|
+
return { values, entries, deps: Object.fromEntries([...deps].map(([k, v]) => [k, [...v]])), units };
|
|
153
227
|
}
|
|
154
228
|
|
|
155
229
|
// Round for display: at most 2 decimals, no trailing zeros.
|