@rulecad/variables 0.3.6 → 0.4.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/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  What changed in each release, for someone upgrading a workspace.
4
4
 
5
+ ## 0.4.0: needs Node 22.13 or later, the version the kit is tested on
6
+
7
+ ### Changed
8
+
9
+ - @rulecad/variables now states Node 22.13 or later in its `engines`, the same lowest Node as every rulecad package, and
10
+ the tests run on exactly Node 22.13.0 as well as the newest Node 24. Node 20 reached the end of its support on 30
11
+ April 2026, and the kit's packages stated five different lowest versions, some of them too low: on Node 20.6 to 20.9
12
+ `cad` stopped at start-up with "Unexpected token 'with'", and on Node 22.0 to 22.12 every `cad` command that runs a
13
+ design stops, because the sandbox designs run in cannot start there. npm gave no warning at install for either.
14
+
15
+ Upgrading: on a Node older than 22.13, npm now warns at install that this package needs Node 22.13; install Node 22.13
16
+ or later (24 recommended). Nothing else changes, and no printed size moves.
17
+
18
+ ## 0.3.7: range ends in expressions
19
+ ### Added
20
+
21
+ - An expression reads either end of a rule's range: `pa_cf.strength.low`, `pa_cf.strength.high`, in the rule's unit.
22
+ An end the rule does not give is refused by name (`var.range`). Names with two dots that are not `low` or `high` are
23
+ refused as before. No value read by an existing name changes.
24
+
5
25
  ## 0.3.6: material ranges
6
26
  ### Added
7
27
 
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Design values you can trace. Every measurement is a variable, and every variable can say where it comes from: a
4
4
  printer's spec, a standard, a community figure, or something you measured (`kind`: spec, community, measured or
5
5
  estimate, with its `source`). Expressions are parsed, never `eval`'d, so a JSON file can't run code. No dependencies;
6
- browsers and Node 20+.
6
+ browsers and Node 22.13 or later.
7
7
 
8
8
  ```js
9
9
  import { resolve } from '@rulecad/variables';
@@ -31,6 +31,10 @@ entries // every variable and rule with its value, source and whet
31
31
  - **Lists:** a rule may hold a list, `"value": [5, 6, 8, 10]` with one `unit` for all of it (the lengths a screw is
32
32
  sold in). Each entry is a number or an expression. A design reads it as an array; in an expression only `min()` and
33
33
  `max()` take a list, and anything else refuses it by name.
34
+ - **Ranges:** a rule may give the range it is found in, `"low"` and `"high"` beside its value, in its unit. An
35
+ expression reads either end as `<set>.<rule>.low` or `<set>.<rule>.high` (`pa_cf.strength.low`), and the plain name
36
+ still reads the value. Reading an end a rule does not give is refused by name (`var.range`), with the rules in that set
37
+ that do give one.
34
38
  - **Rule sets** are handed in through `sets`, or fetched by name with `load: (name) => …` (from files, a URL, anywhere).
35
39
  - **Tweaks:** only variables with a `tweak` range can be set, and only within it. Errors say which variable and why.
36
40
  - **Names, not numbers:** `choice: [...]`, `type: 'text'` or `type: 'anchor'` (one of `ANCHORS`: tl tc tr / ml mc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/variables",
3
- "version": "0.3.6",
3
+ "version": "0.4.0",
4
4
  "description": "Design values you can trace: every number says where it comes from, and expressions are parsed, never run.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -23,7 +23,7 @@
23
23
  "provenance"
24
24
  ],
25
25
  "engines": {
26
- "node": ">=20"
26
+ "node": ">=22.13"
27
27
  },
28
28
  "sideEffects": false,
29
29
  "repository": {
package/variables.mjs CHANGED
@@ -23,22 +23,35 @@ export const ANCHORS = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'];
23
23
  export const isName = (d) => !!(d.choice || ['text', 'anchor', 'layout', 'problem'].includes(d.type));
24
24
  export const options = (d) => (d.type === 'anchor' ? ANCHORS : d.type === 'text' ? null : d.choice);
25
25
  export function checkName(name, d, v) {
26
- const s = String(v), opts = options(d), match = opts?.find((o) => String(o) === s);
26
+ const s = String(v),
27
+ opts = options(d),
28
+ match = opts?.find((o) => String(o) === s);
27
29
  if (opts && match === undefined) throw new Error(`${name} is one of ${opts.join(', ')} (got "${s}")`);
28
30
  if (!opts && s.length > (d.max ?? 16)) throw new Error(`${name} is at most ${d.max ?? 16} characters`);
29
31
  return typeof match === 'number' ? match : s; // choices can be numbers too (a rotation: 0, 90, 180, 270)
30
32
  }
31
33
  const DEG = Math.PI / 180;
32
- const FNS = { min: Math.min, max: Math.max, round: (x, step = 1) => Math.round(x / step) * step,
33
- sind: (d) => Math.sin(d * DEG), cosd: (d) => Math.cos(d * DEG), tand: (d) => Math.tan(d * DEG) }; // angles in degrees
34
+ const FNS = {
35
+ min: Math.min,
36
+ max: Math.max,
37
+ round: (x, step = 1) => Math.round(x / step) * step,
38
+ sind: (d) => Math.sin(d * DEG),
39
+ cosd: (d) => Math.cos(d * DEG),
40
+ tand: (d) => Math.tan(d * DEG),
41
+ }; // angles in degrees
34
42
 
35
43
  // ---------- expressions ----------
36
44
  function tokens(src) {
37
- const out = [], re = /\s*(?:(\d+(?:\.\d+)?|\.\d+)|([a-z_][\w]*(?:\.[a-z_][\w]*)*)|([-+*/(),]))/giy;
38
- let m, at = 0;
45
+ const out = [],
46
+ re = /\s*(?:(\d+(?:\.\d+)?|\.\d+)|([a-z_][\w]*(?:\.[a-z_][\w]*)*)|([-+*/(),]))/giy;
47
+ let m,
48
+ at = 0;
39
49
  while (at < src.length) {
40
50
  re.lastIndex = at;
41
- if (!(m = re.exec(src))) { if (/^\s*$/.test(src.slice(at))) break; throw new Error(`can't read "${src.slice(at).trim()}"`); }
51
+ if (!(m = re.exec(src))) {
52
+ if (/^\s*$/.test(src.slice(at))) break;
53
+ throw new Error(`can't read "${src.slice(at).trim()}"`);
54
+ }
42
55
  out.push(m[1] ? { n: Number(m[1]) } : m[2] ? { id: m[2] } : { op: m[3] });
43
56
  at = re.lastIndex;
44
57
  }
@@ -55,15 +68,34 @@ function parse(src) {
55
68
  if (trees.has(key)) return trees.get(key);
56
69
  const t = tokens(key);
57
70
  let i = 0;
58
- const peek = () => t[i], take = (op) => (t[i]?.op === op ? (i++, true) : false);
59
- const expr = () => { let v = term(); for (;;) { if (take('+')) v = { op: '+', a: v, b: term() }; else if (take('-')) v = { op: '-', a: v, b: term() }; else return v; } };
60
- const term = () => { let v = unary(); for (;;) { if (take('*')) v = { op: '*', a: v, b: unary() }; else if (take('/')) v = { op: '/', a: v, b: unary() }; else return v; } };
71
+ const peek = () => t[i],
72
+ take = (op) => (t[i]?.op === op ? (i++, true) : false);
73
+ const expr = () => {
74
+ let v = term();
75
+ for (;;) {
76
+ if (take('+')) v = { op: '+', a: v, b: term() };
77
+ else if (take('-')) v = { op: '-', a: v, b: term() };
78
+ else return v;
79
+ }
80
+ };
81
+ const term = () => {
82
+ let v = unary();
83
+ for (;;) {
84
+ if (take('*')) v = { op: '*', a: v, b: unary() };
85
+ else if (take('/')) v = { op: '/', a: v, b: unary() };
86
+ else return v;
87
+ }
88
+ };
61
89
  const unary = () => (take('-') ? { neg: unary() } : take('+') ? { pos: unary() } : atom());
62
90
  const atom = () => {
63
91
  const k = t[i++];
64
92
  if (!k) throw new Error('ends too soon');
65
93
  if (k.n != null) return { n: k.n };
66
- if (k.op === '(') { const v = expr(); if (!take(')')) throw new Error('missing )'); return v; }
94
+ if (k.op === '(') {
95
+ const v = expr();
96
+ if (!take(')')) throw new Error('missing )');
97
+ return v;
98
+ }
67
99
  if (k.id && Object.hasOwn(FNS, k.id) && take('(')) {
68
100
  const args = [expr()];
69
101
  while (take(',')) args.push(expr());
@@ -87,15 +119,33 @@ function parse(src) {
87
119
  * @param {(name: string) => number} lookup the value of a name
88
120
  * @returns {number}
89
121
  */
90
- export function evaluate(src, lookup = (name) => { throw new Error(`no value for "${name}"`); }) {
91
- if (typeof src === 'number') { if (!Number.isFinite(src)) throw new Error('is not a finite number'); return src; }
92
- const walk = (x, list = false) => { // list: inside min() or max(), where a name may be a list rule
122
+ export function evaluate(
123
+ src,
124
+ lookup = (name) => {
125
+ throw new Error(`no value for "${name}"`);
126
+ },
127
+ ) {
128
+ if (typeof src === 'number') {
129
+ if (!Number.isFinite(src)) throw new Error('is not a finite number');
130
+ return src;
131
+ }
132
+ const walk = (x, list = false) => {
133
+ // list: inside min() or max(), where a name may be a list rule
93
134
  if (x.n != null) return x.n;
94
- if (x.id != null) { const v = lookup(x.id); if (Array.isArray(v) && !list) throw new Error(`"${x.id}" is a list: take min(${x.id}) or max(${x.id}), or read it in the design`); return v; }
135
+ if (x.id != null) {
136
+ const v = lookup(x.id);
137
+ if (Array.isArray(v) && !list)
138
+ throw new Error(`"${x.id}" is a list: take min(${x.id}) or max(${x.id}), or read it in the design`);
139
+ return v;
140
+ }
95
141
  if (x.neg) return -walk(x.neg);
96
142
  if (x.pos) return walk(x.pos);
97
- if (x.fn) { const spread = x.fn === 'min' || x.fn === 'max'; return FNS[x.fn](...x.args.flatMap((a) => walk(a, spread))); }
98
- const a = walk(x.a), b = walk(x.b);
143
+ if (x.fn) {
144
+ const spread = x.fn === 'min' || x.fn === 'max';
145
+ return FNS[x.fn](...x.args.flatMap((a) => walk(a, spread)));
146
+ }
147
+ const a = walk(x.a),
148
+ b = walk(x.b);
99
149
  return x.op === '+' ? a + b : x.op === '-' ? a - b : x.op === '*' ? a * b : a / b;
100
150
  };
101
151
  const v = walk(parse(src));
@@ -103,13 +153,31 @@ export function evaluate(src, lookup = (name) => { throw new Error(`no value for
103
153
  return v;
104
154
  }
105
155
 
106
-
107
156
  // ---------- units ----------
108
157
  // A unit as powers of its parts: "mm" {mm: 1}, "mm²" {mm: 2}, "deg" {deg: 1}. Numbers and names with no unit are
109
158
  // unknown (null), which matches anything: only units that are both known and different are a problem.
110
- const SUP = { '²': 2, '³': 3 }, ALIAS = { '°': 'deg', degrees: 'deg', degree: 'deg' };
159
+ const SUP = { '²': 2, '³': 3 },
160
+ ALIAS = { '°': 'deg', degrees: 'deg', degree: 'deg' };
111
161
  // Physical units only: counts (keys, u, rows, %) are plain numbers, so 12 keys × 19.05 mm is a length
112
- const PHYSICAL = new Set(['mm', 'cm', 'm', 'in', 'deg', 'rad', 'g', 'kg', 'N', 'W', 'V', 'A', 's', 'ms', 'Hz', 'mAh', 'Wh']);
162
+ const PHYSICAL = new Set([
163
+ 'mm',
164
+ 'cm',
165
+ 'm',
166
+ 'in',
167
+ 'deg',
168
+ 'rad',
169
+ 'g',
170
+ 'kg',
171
+ 'N',
172
+ 'W',
173
+ 'V',
174
+ 'A',
175
+ 's',
176
+ 'ms',
177
+ 'Hz',
178
+ 'mAh',
179
+ 'Wh',
180
+ ]);
113
181
  function parseUnit(u) {
114
182
  if (u == null || u === '') return null;
115
183
  const base = /^([a-zA-Z°]+)/.exec(String(u).trim())?.[1];
@@ -118,9 +186,29 @@ function parseUnit(u) {
118
186
  if (!m) return { [String(u)]: 1 };
119
187
  return { [ALIAS[m[1]] || m[1]]: m[2] ? SUP[m[2]] : 1 };
120
188
  }
121
- 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');
122
- 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));
123
- const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : b == null ? null : Object.fromEntries(Object.entries(b).map(([k, n]) => [k, -n])); /* (a plain number over a unit: 2 / w is per mm) */ 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; };
189
+ const showUnit = (x) =>
190
+ x == null
191
+ ? 'a number'
192
+ : Object.keys(x).length
193
+ ? Object.entries(x)
194
+ .map(([k, n]) => (n === 1 ? k : n === 2 ? `${k}²` : n === 3 ? `${k}³` : `${k}^${n}`))
195
+ .join('·')
196
+ : 'a plain number';
197
+ const sameUnit = (a, b) =>
198
+ a == null ||
199
+ b == null ||
200
+ (Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, n]) => b[k] === n));
201
+ const combine = (a, b, sign) => {
202
+ if (a == null)
203
+ return sign > 0 ? b : b == null ? null : Object.fromEntries(Object.entries(b).map(([k, n]) => [k, -n]));
204
+ /* (a plain number over a unit: 2 / w is per mm) */ if (b == null) return a;
205
+ const o = { ...a };
206
+ for (const [k, n] of Object.entries(b)) {
207
+ o[k] = (o[k] || 0) + sign * n;
208
+ if (!o[k]) delete o[k];
209
+ }
210
+ return o;
211
+ };
124
212
 
125
213
  /**
126
214
  * The unit an expression comes to, and any mixing of units on the way (mm added to degrees, a sine of millimetres).
@@ -130,9 +218,17 @@ const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : b == null
130
218
  export function unitsOf(src, unitOf) {
131
219
  if (typeof src === 'number') return { unit: null, problems: [] };
132
220
  let tree;
133
- try { tree = parse(src); } catch { return { unit: null, problems: [] }; } // (an expression that doesn't parse: evaluate says so)
221
+ try {
222
+ tree = parse(src);
223
+ } catch {
224
+ return { unit: null, problems: [] };
225
+ } // (an expression that doesn't parse: evaluate says so)
134
226
  const problems = [];
135
- const add = (a, b, op) => { if (!sameUnit(a, b)) problems.push(`${op === '+' ? 'adds' : 'takes'} ${showUnit(b)} ${op === '+' ? 'to' : 'from'} ${showUnit(a)}`); return a ?? b; };
227
+ const add = (a, b, op) => {
228
+ if (!sameUnit(a, b))
229
+ problems.push(`${op === '+' ? 'adds' : 'takes'} ${showUnit(b)} ${op === '+' ? 'to' : 'from'} ${showUnit(a)}`);
230
+ return a ?? b;
231
+ };
136
232
  const walk = (x) => {
137
233
  if (x.n != null) return null;
138
234
  if (x.id != null) return parseUnit(unitOf(x.id));
@@ -140,19 +236,22 @@ export function unitsOf(src, unitOf) {
140
236
  if (x.pos) return walk(x.pos);
141
237
  if (x.fn) {
142
238
  const args = x.args.map(walk);
143
- if (['sind', 'cosd', 'tand'].includes(x.fn)) { if (args[0] && !sameUnit(args[0], { deg: 1 })) problems.push(`takes ${x.fn} of ${showUnit(args[0])}, not degrees`); return {}; }
239
+ if (['sind', 'cosd', 'tand'].includes(x.fn)) {
240
+ if (args[0] && !sameUnit(args[0], { deg: 1 }))
241
+ problems.push(`takes ${x.fn} of ${showUnit(args[0])}, not degrees`);
242
+ return {};
243
+ }
144
244
  if (x.fn === 'round') return args[0];
145
245
  return args.reduce((a, b) => add(a, b, '+'));
146
246
  }
147
- const a = walk(x.a), b = walk(x.b);
247
+ const a = walk(x.a),
248
+ b = walk(x.b);
148
249
  return x.op === '+' || x.op === '-' ? add(a, b, x.op) : combine(a, b, x.op === '*' ? 1 : -1);
149
250
  };
150
251
  const v = walk(tree);
151
252
  return { unit: v == null ? null : showUnit(v), problems, value: v };
152
253
  }
153
254
 
154
-
155
-
156
255
  // resolve(object, { sets, set }) -> { values, entries }
157
256
  // values: { stem_arm: 1.27, x1c: { line: 0.42, … }, mx: { … } } for the design's main()
158
257
  // entries: every variable and every rule in the sets used, with its resolved value, for checks and the rules
@@ -178,28 +277,63 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
178
277
  // Names are looked up as an object's own, never inherited: a variable called constructor is a variable, and a
179
278
  // name nobody defined (toString) is unknown, not whatever every object happens to carry
180
279
  const own = (o, k) => (o != null && Object.hasOwn(o, k) ? o[k] : undefined);
181
- const ruleSets = Object.fromEntries((object.uses || []).map((u) => {
182
- const s = own(sets, u) || (load ? load(u) : null);
183
- if (!s) throw fail('rules.missing', `no rule set "${u}" (hand it in as sets.${u}, or give a load function)`, 'uses');
184
- if (typeof s.then === 'function') throw fail('rules.async', `the load function gave a promise for "${u}": load must return the rule set itself (fetch it first, and hand it in as sets.${u})`, 'uses');
185
- if (!s.rules || typeof s.rules !== 'object') throw fail('rules.shape', `rule set "${u}" has no "rules"`, 'uses');
186
- return [s.name || u, s];
187
- }));
280
+ const ruleSets = Object.fromEntries(
281
+ (object.uses || []).map((u) => {
282
+ const s = own(sets, u) || (load ? load(u) : null);
283
+ if (!s)
284
+ throw fail('rules.missing', `no rule set "${u}" (hand it in as sets.${u}, or give a load function)`, 'uses');
285
+ if (typeof s.then === 'function')
286
+ throw fail(
287
+ 'rules.async',
288
+ `the load function gave a promise for "${u}": load must return the rule set itself (fetch it first, and hand it in as sets.${u})`,
289
+ 'uses',
290
+ );
291
+ if (!s.rules || typeof s.rules !== 'object') throw fail('rules.shape', `rule set "${u}" has no "rules"`, 'uses');
292
+ return [s.name || u, s];
293
+ }),
294
+ );
188
295
  const vars = object.variables || {};
189
- for (const name of Object.keys(ruleSets)) if (own(vars, name) || own(vars, name.replace(/-/g, '_'))) throw fail('var.clash', `"${name}" is a rule set in uses and a variable too: rename the variable, so each name means one thing`, `variables.${own(vars, name) ? name : name.replace(/-/g, '_')}`);
296
+ for (const name of Object.keys(ruleSets))
297
+ if (own(vars, name) || own(vars, name.replace(/-/g, '_')))
298
+ throw fail(
299
+ 'var.clash',
300
+ `"${name}" is a rule set in uses and a variable too: rename the variable, so each name means one thing`,
301
+ `variables.${own(vars, name) ? name : name.replace(/-/g, '_')}`,
302
+ );
190
303
  for (const [k, v] of Object.entries(set)) {
191
304
  const d = own(vars, k);
192
- if (!d) throw fail('set.unknown', `no variable "${k}" to set (variables: ${Object.keys(vars).join(', ')})`, `variables.${k}`);
193
- if (isName(d)) { checkName(k, d, v); continue; }
194
- 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`);
305
+ if (!d)
306
+ throw fail(
307
+ 'set.unknown',
308
+ `no variable "${k}" to set (variables: ${Object.keys(vars).join(', ')})`,
309
+ `variables.${k}`,
310
+ );
311
+ if (isName(d)) {
312
+ checkName(k, d, v);
313
+ continue;
314
+ }
315
+ if (!d.tweak)
316
+ throw fail(
317
+ 'set.fixed',
318
+ `"${k}" is fixed by its rule; only variables with a tweak range can be set`,
319
+ `variables.${k}.tweak`,
320
+ );
195
321
  const n = Number(v);
196
- 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`);
322
+ if (!Number.isFinite(n) || n < d.tweak.min || n > d.tweak.max)
323
+ throw fail('set.range', `${k} must be a number from ${d.tweak.min} to ${d.tweak.max}`, `variables.${k}.tweak`);
197
324
  }
198
325
 
199
326
  // deps: each name's own references (what its expression reads), for explaining a value; stack: whose expression is being read
200
- const done = new Map(), busy = new Set(), deps = new Map(), stack = [];
327
+ const done = new Map(),
328
+ busy = new Set(),
329
+ deps = new Map(),
330
+ stack = [];
201
331
  const pathOf = (name) => (name.includes('.') ? `rules.${name}.value` : `variables.${name}.value`);
202
- const ruleOf = (name) => { let [t, r] = name.split('.'); if (!own(ruleSets, t)) t = t.replace(/_/g, '-'); return ruleSets[t]?.rules[r]; };
332
+ const ruleOf = (name) => {
333
+ let [t, r] = name.split('.');
334
+ if (!own(ruleSets, t)) t = t.replace(/_/g, '-');
335
+ return ruleSets[t]?.rules[r];
336
+ };
203
337
  const lookup = (name) => {
204
338
  if (stack.length) deps.get(stack[stack.length - 1]).add(name);
205
339
  if (done.has(name)) return done.get(name);
@@ -207,57 +341,142 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
207
341
  busy.add(name);
208
342
  let src, where;
209
343
  if (name.includes('.')) {
210
- let [s, r, more] = name.split('.');
211
- if (more !== undefined) throw fail('var.unknown-rule', `"${name}": a rule is named <set>.<rule>, with one dot`);
344
+ let [s, r, end, more] = name.split('.');
345
+ if (more !== undefined || (end !== undefined && end !== 'low' && end !== 'high'))
346
+ throw fail(
347
+ 'var.unknown-rule',
348
+ `"${name}": a rule is named <set>.<rule>, with one dot, and the ends of its range <set>.<rule>.low and <set>.<rule>.high`,
349
+ );
212
350
  if (!own(ruleSets, s) && own(ruleSets, s.replace(/_/g, '-'))) s = s.replace(/_/g, '-'); // mx_switch.housing_top reads the set named mx-switch (a - is a minus here)
213
- if (!own(ruleSets, s)) throw fail('var.unknown-set', `"${name}": rule set "${s}" isn't in uses (${Object.keys(ruleSets).join(', ') || 'none'})`);
351
+ if (!own(ruleSets, s))
352
+ throw fail(
353
+ 'var.unknown-set',
354
+ `"${name}": rule set "${s}" isn't in uses (${Object.keys(ruleSets).join(', ') || 'none'})`,
355
+ );
214
356
  if (!own(ruleSets[s].rules, r)) throw fail('var.unknown-rule', `"${name}": no rule "${r}" in ${s}`);
215
- src = ruleSets[s].rules[r].value; where = (n) => (n.includes('.') ? n : `${s}.${n}`); // a rule's names are its own set's
357
+ // An end of the range a value is found in (pa_cf.strength.low): a number beside the value, in the same unit
358
+ if (end !== undefined) {
359
+ const d = ruleSets[s].rules[r],
360
+ ranged = Object.entries(ruleSets[s].rules)
361
+ .filter(([, x]) => typeof x[end] === 'number')
362
+ .map(([k]) => k);
363
+ busy.delete(name);
364
+ if (typeof d[end] !== 'number')
365
+ throw fail(
366
+ 'var.range',
367
+ `"${name}": ${s}.${r} gives no ${end} (${ranged.length ? `the rules in ${s} with a range: ${ranged.join(', ')}` : `no rule in ${s} gives a range`}), so read its value, ${s}.${r}`,
368
+ `rules.${s}.${r}`,
369
+ );
370
+ deps.set(name, new Set([`${s}.${r}`]));
371
+ done.set(name, d[end]);
372
+ return d[end];
373
+ }
374
+ src = ruleSets[s].rules[r].value;
375
+ where = (n) => (n.includes('.') ? n : `${s}.${n}`); // a rule's names are its own set's
216
376
  } else {
217
377
  const d = own(vars, name);
218
378
  if (!d) throw fail('var.unknown', `no variable "${name}"`);
219
- const shown = Object.hasOwn(display, name), given = Object.hasOwn(set, name);
220
- if (isName(d)) { busy.delete(name); const c = checkName(name, d, shown ? display[name] : given ? set[name] : d.value); done.set(name, c); return c; }
221
- src = shown ? display[name] : given ? Number(set[name]) : d.value; where = (n) => n; // display: the screen's settings win
379
+ const shown = Object.hasOwn(display, name),
380
+ given = Object.hasOwn(set, name);
381
+ if (isName(d)) {
382
+ busy.delete(name);
383
+ const c = checkName(name, d, shown ? display[name] : given ? set[name] : d.value);
384
+ done.set(name, c);
385
+ return c;
386
+ }
387
+ src = shown ? display[name] : given ? Number(set[name]) : d.value;
388
+ where = (n) => n; // display: the screen's settings win
222
389
  if (src === undefined) throw fail('var.value', `"${name}" has no value`, `variables.${name}`);
223
- if (Array.isArray(src)) throw fail('var.list', `"${name}" is a list: only a rule in a rule set holds a list (a design reads it as v.<set>.<rule>)`, `variables.${name}.value`);
390
+ if (Array.isArray(src))
391
+ throw fail(
392
+ 'var.list',
393
+ `"${name}" is a list: only a rule in a rule set holds a list (a design reads it as v.<set>.<rule>)`,
394
+ `variables.${name}.value`,
395
+ );
224
396
  }
225
397
  let v;
226
- deps.set(name, new Set()); stack.push(name);
398
+ deps.set(name, new Set());
399
+ stack.push(name);
227
400
  // A list rule: each entry through the same grammar, so the list is numbers by the time a design reads it
228
- const each = (x) => { if (typeof x !== 'number' && typeof x !== 'string') throw new Error('each entry of a list is a number or an expression'); const n = evaluate(x, (k) => lookup(where(k))); if (Array.isArray(n)) throw new Error('holds a list inside a list'); return n; };
229
- try { v = Array.isArray(src) ? src.map(each) : evaluate(src, (n) => lookup(where(n))); if (Array.isArray(v) && !v.length) throw new Error('is an empty list'); } catch (e) {
230
- busy.delete(name); stack.pop();
401
+ const each = (x) => {
402
+ if (typeof x !== 'number' && typeof x !== 'string')
403
+ throw new Error('each entry of a list is a number or an expression');
404
+ const n = evaluate(x, (k) => lookup(where(k)));
405
+ if (Array.isArray(n)) throw new Error('holds a list inside a list');
406
+ return n;
407
+ };
408
+ try {
409
+ v = Array.isArray(src) ? src.map(each) : evaluate(src, (n) => lookup(where(n)));
410
+ if (Array.isArray(v) && !v.length) throw new Error('is an empty list');
411
+ } catch (e) {
412
+ busy.delete(name);
413
+ stack.pop();
231
414
  // A rule with words for a value and no unit (a bearing's "radial", a pinout) is text, read as it is
232
- if (name.includes('.') && typeof src === 'string' && !ruleOf(name)?.unit) { done.set(name, src); return src; }
233
- const out = e.message.startsWith('"') || e.message.startsWith('no ') ? e : fail(e.code || 'var.expression', `"${name}" = ${JSON.stringify(src)}: ${e.message}`);
415
+ if (name.includes('.') && typeof src === 'string' && !ruleOf(name)?.unit) {
416
+ done.set(name, src);
417
+ return src;
418
+ }
419
+ const out =
420
+ e.message.startsWith('"') || e.message.startsWith('no ')
421
+ ? e
422
+ : fail(e.code || 'var.expression', `"${name}" = ${JSON.stringify(src)}: ${e.message}`);
234
423
  if (!out.path) out.path = pathOf(name); // the first expression that reads the bad name: where to fix it
235
424
  throw out;
236
425
  }
237
- stack.pop(); busy.delete(name); done.set(name, v);
426
+ stack.pop();
427
+ busy.delete(name);
428
+ done.set(name, v);
238
429
  return v;
239
430
  };
240
431
 
241
- const values = {}, entries = [];
432
+ const values = {},
433
+ entries = [];
242
434
  for (const [name, d] of Object.entries(vars)) {
243
435
  values[name] = lookup(name);
244
- entries.push({ name, ...d, value: values[name], expr: typeof d.value === 'string' ? d.value : undefined, set: Object.hasOwn(set, name) });
436
+ entries.push({
437
+ name,
438
+ ...d,
439
+ value: values[name],
440
+ expr: typeof d.value === 'string' ? d.value : undefined,
441
+ set: Object.hasOwn(set, name),
442
+ });
245
443
  }
246
444
  // Units: each variable's expression, its names' units mixed only where they agree, and coming to the unit it says
247
- 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);
445
+ const unitOf = (n) =>
446
+ n.includes('.')
447
+ ? (ruleSets[n.split('.')[0].replace(/_/g, '-')]?.rules[n.split('.')[1]]?.unit ??
448
+ ruleSets[n.split('.')[0]]?.rules[n.split('.')[1]]?.unit)
449
+ : vars[n]?.unit;
248
450
  const units = [];
249
451
  for (const [name, d] of Object.entries(vars)) {
250
452
  if (typeof d.value !== 'string' || isName(d)) continue;
251
- const r = unitsOf(d.value, unitOf), said = parseUnit(d.unit);
252
- for (const p of r.problems) units.push({ name, path: `variables.${name}.value`, message: `"${name}" = ${d.value}: ${p}` });
253
- 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)}` });
453
+ const r = unitsOf(d.value, unitOf),
454
+ said = parseUnit(d.unit);
455
+ for (const p of r.problems)
456
+ units.push({ name, path: `variables.${name}.value`, message: `"${name}" = ${d.value}: ${p}` });
457
+ if (said && r.value && !sameUnit(said, r.value))
458
+ units.push({
459
+ name,
460
+ path: `variables.${name}.unit`,
461
+ message: `"${name}" comes to ${r.unit}, but its unit says ${showUnit(said)}`,
462
+ });
254
463
  }
255
- const used = new Set(done.keys()); // rules the variables actually refer to (directly or through other rules)
464
+ const used = new Set([
465
+ ...done.keys(),
466
+ ...[...deps].filter(([k]) => k.split('.').length === 3).flatMap(([, v]) => [...v]),
467
+ ]); // rules the variables actually refer to (directly or through other rules)
256
468
  for (const [s, rs] of Object.entries(ruleSets)) {
257
469
  values[s] = {};
258
470
  for (const [r, d] of Object.entries(rs.rules)) {
259
471
  values[s][r] = lookup(`${s}.${r}`);
260
- entries.push({ name: `${s}.${r}`, ...d, value: values[s][r], expr: typeof d.value === 'string' ? d.value : undefined, used: used.has(`${s}.${r}`), ...(rs.private ? { private: true } : {}) });
472
+ entries.push({
473
+ name: `${s}.${r}`,
474
+ ...d,
475
+ value: values[s][r],
476
+ expr: typeof d.value === 'string' ? d.value : undefined,
477
+ used: used.has(`${s}.${r}`),
478
+ ...(rs.private ? { private: true } : {}),
479
+ });
261
480
  }
262
481
  if (rs.footprints) values[s].footprints = rs.footprints; // pad data for boards (v.esp32c6.footprints.module), as the set gives it
263
482
  if (rs.circuit) values[s].circuit = rs.circuit;
@@ -286,46 +505,139 @@ const finite = (x) => typeof x === 'number' && Number.isFinite(x);
286
505
  * @returns {{ level: 'fail', code: string, text: string, rule?: string, values?: Record<string, number> }[]} what's wrong with it: nothing, if it passes
287
506
  */
288
507
  export function checkRuleSet(set, vocabulary) {
289
- const out = [], f = (code, text, rule, values) => out.push({ level: 'fail', code, text, ...(rule ? { rule } : {}), ...(values ? { values } : {}) }), { units, prefixes, fields, parts } = vocabulary, rules = set?.rules;
290
- if (!rules || typeof rules !== 'object' || !Object.keys(rules).length) { f('rules.shape', 'it has no rules'); return out; }
508
+ const out = [],
509
+ f = (code, text, rule, values) =>
510
+ out.push({ level: 'fail', code, text, ...(rule ? { rule } : {}), ...(values ? { values } : {}) }),
511
+ { units, prefixes, fields, parts } = vocabulary,
512
+ rules = set?.rules;
513
+ if (!rules || typeof rules !== 'object' || !Object.keys(rules).length) {
514
+ f('rules.shape', 'it has no rules');
515
+ return out;
516
+ }
291
517
  for (const [name, r] of Object.entries(rules)) {
292
518
  const list = Array.isArray(r.value);
293
- if (!(list ? r.value.length && r.value.every(finite) : finite(r.value) || (typeof r.value === 'string' && r.value))) f('rules.value', list ? `${name} is a list, so every entry is a number and there is at least one` : `${name} has no value`, name);
294
- else if (list && fields?.[name]?.points) { const n = fields[name].points; if (r.value.length % n) f('rules.list', `${name} is points of ${n} numbers each, one after another: ${r.value.length} numbers is not a whole number of them`, name); } // (points: in the order they are, not ascending)
295
- else if (list) { const i = r.value.findIndex((x, k) => k && x <= r.value[k - 1]); if (i > 0) f('rules.order', `${name} is a list in ascending order: ${r.value[i]} follows ${r.value[i - 1]}`, name, { before: r.value[i - 1], after: r.value[i] }); }
296
- if (!(typeof r.rule === 'string' && r.rule.length > 5)) f('rules.says', `${name} doesn't say what it is ("rule")`, name);
297
- if (!KINDS.includes(r.kind)) f('rules.kind', `${name}: kind ${JSON.stringify(r.kind)} is not one of ${KINDS.join(', ')}`, name);
519
+ if (!(list ? r.value.length && r.value.every(finite) : finite(r.value) || (typeof r.value === 'string' && r.value)))
520
+ f(
521
+ 'rules.value',
522
+ list ? `${name} is a list, so every entry is a number and there is at least one` : `${name} has no value`,
523
+ name,
524
+ );
525
+ else if (list && fields?.[name]?.points) {
526
+ const n = fields[name].points;
527
+ if (r.value.length % n)
528
+ f(
529
+ 'rules.list',
530
+ `${name} is points of ${n} numbers each, one after another: ${r.value.length} numbers is not a whole number of them`,
531
+ name,
532
+ );
533
+ } // (points: in the order they are, not ascending)
534
+ else if (list) {
535
+ const i = r.value.findIndex((x, k) => k && x <= r.value[k - 1]);
536
+ if (i > 0)
537
+ f('rules.order', `${name} is a list in ascending order: ${r.value[i]} follows ${r.value[i - 1]}`, name, {
538
+ before: r.value[i - 1],
539
+ after: r.value[i],
540
+ });
541
+ }
542
+ if (!(typeof r.rule === 'string' && r.rule.length > 5))
543
+ f('rules.says', `${name} doesn't say what it is ("rule")`, name);
544
+ if (!KINDS.includes(r.kind))
545
+ f('rules.kind', `${name}: kind ${JSON.stringify(r.kind)} is not one of ${KINDS.join(', ')}`, name);
298
546
  if (!(typeof r.source === 'string' && r.source)) f('rules.source', `${name} has no source`, name);
299
- for (const [k, ok] of [['low', (v) => v <= r.value], ['high', (v) => v >= r.value]]) {
547
+ for (const [k, ok] of [
548
+ ['low', (v) => v <= r.value],
549
+ ['high', (v) => v >= r.value],
550
+ ]) {
300
551
  if (r[k] == null) continue;
301
- if (!finite(r[k]) || !finite(r.value)) f('rules.range', `${name}: ${k} is a number in the rule's unit, beside a number value (got ${JSON.stringify(r[k])})`, name);
302
- else if (!ok(r[k])) f('rules.range', `${name}: ${k} (${r[k]}) is ${k === 'low' ? 'above' : 'below'} its value (${r.value}): the range it is found in holds the value`, name, { value: r.value, [k]: r[k] });
552
+ if (!finite(r[k]) || !finite(r.value))
553
+ f(
554
+ 'rules.range',
555
+ `${name}: ${k} is a number in the rule's unit, beside a number value (got ${JSON.stringify(r[k])})`,
556
+ name,
557
+ );
558
+ else if (!ok(r[k]))
559
+ f(
560
+ 'rules.range',
561
+ `${name}: ${k} (${r[k]}) is ${k === 'low' ? 'above' : 'below'} its value (${r.value}): the range it is found in holds the value`,
562
+ name,
563
+ { value: r.value, [k]: r[k] },
564
+ );
303
565
  }
304
- if (!/^\d{4}-\d{2}-\d{2}$/.test(String(r.checked))) f('rules.checked', `${name}: checked is the date it was last checked, YYYY-MM-DD (got ${JSON.stringify(r.checked)})`, name);
566
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(r.checked)))
567
+ f(
568
+ 'rules.checked',
569
+ `${name}: checked is the date it was last checked, YYYY-MM-DD (got ${JSON.stringify(r.checked)})`,
570
+ name,
571
+ );
305
572
  if (set.part) {
306
- if (r.unit != null && !units.includes(r.unit)) f('rules.unit', `${name}: unit ${JSON.stringify(r.unit)} is not one of ${units.filter(Boolean).join(', ')}`, name);
307
- if ((typeof r.value === 'number' || list) && r.unit == null) f('rules.unit', `${name} is a number with no unit (give "unit", "" if it has none)`, name);
573
+ if (r.unit != null && !units.includes(r.unit))
574
+ f(
575
+ 'rules.unit',
576
+ `${name}: unit ${JSON.stringify(r.unit)} is not one of ${units.filter(Boolean).join(', ')}`,
577
+ name,
578
+ );
579
+ if ((typeof r.value === 'number' || list) && r.unit == null)
580
+ f('rules.unit', `${name} is a number with no unit (give "unit", "" if it has none)`, name);
308
581
  const field = fields[name];
309
- if (prefixes.some((p) => name.startsWith(p)) && !field) f('rules.name', `${name} is not in the vocabulary (a name starting ${prefixes.join(', ')} says how a part mounts, so everything reads it the same way)`, name);
310
- if (field?.unit != null && r.unit !== field.unit) f('rules.unit', `${name} is in ${JSON.stringify(field.unit)}, not ${JSON.stringify(r.unit ?? null)}`, name);
311
- if (field?.choice && !field.choice.includes(r.value)) f('rules.choice', `${name} is one of ${field.choice.join(', ')} (got ${JSON.stringify(r.value)})`, name);
312
- if (field && !!field.list !== list) f('rules.list', field.list ? `${name} is a list: "value": [ … ] (got ${JSON.stringify(r.value)})` : `${name} is one value, not a list`, name);
582
+ if (prefixes.some((p) => name.startsWith(p)) && !field)
583
+ f(
584
+ 'rules.name',
585
+ `${name} is not in the vocabulary (a name starting ${prefixes.join(', ')} says how a part mounts, so everything reads it the same way)`,
586
+ name,
587
+ );
588
+ if (field?.unit != null && r.unit !== field.unit)
589
+ f('rules.unit', `${name} is in ${JSON.stringify(field.unit)}, not ${JSON.stringify(r.unit ?? null)}`, name);
590
+ if (field?.choice && !field.choice.includes(r.value))
591
+ f('rules.choice', `${name} is one of ${field.choice.join(', ')} (got ${JSON.stringify(r.value)})`, name);
592
+ if (field && !!field.list !== list)
593
+ f(
594
+ 'rules.list',
595
+ field.list
596
+ ? `${name} is a list: "value": [ … ] (got ${JSON.stringify(r.value)})`
597
+ : `${name} is one value, not a list`,
598
+ name,
599
+ );
313
600
  }
314
601
  }
315
602
  if (set.part) {
316
- if (!parts[set.part]) f('rules.part', `part ${JSON.stringify(set.part)} is not one of ${Object.keys(parts).join(', ')}`);
603
+ if (!parts[set.part])
604
+ f('rules.part', `part ${JSON.stringify(set.part)} is not one of ${Object.keys(parts).join(', ')}`);
317
605
  else for (const name of parts[set.part]) if (!rules[name]) f('rules.missing', `a ${set.part} needs ${name}`, name);
318
606
  // What must hold between its figures: only over the numbers it has, so a size made without a head form passes
319
607
  const num = (name) => (finite(rules[name]?.value) ? rules[name].value : undefined);
320
- const work = (src) => { try { return evaluate(src, (n) => { const v = num(n); if (v === undefined) throw new Error('absent'); return v; }); } catch { return undefined; } };
608
+ const work = (src) => {
609
+ try {
610
+ return evaluate(src, (n) => {
611
+ const v = num(n);
612
+ if (v === undefined) throw new Error('absent');
613
+ return v;
614
+ });
615
+ } catch {
616
+ return undefined;
617
+ }
618
+ };
321
619
  for (const c of vocabulary.checks?.[set.part] || []) {
322
620
  if (c.ascending) {
323
621
  const have = c.ascending.filter((n) => num(n) !== undefined);
324
- for (let i = 1; i < have.length; i++) if (!(num(have[i]) > num(have[i - 1]))) f('rules.order', `${have[i]} (${num(have[i])}) is not larger than ${have[i - 1]} (${num(have[i - 1])}): ${c.says}`, have[i], { [have[i - 1]]: num(have[i - 1]), [have[i]]: num(have[i]) });
622
+ for (let i = 1; i < have.length; i++)
623
+ if (!(num(have[i]) > num(have[i - 1])))
624
+ f(
625
+ 'rules.order',
626
+ `${have[i]} (${num(have[i])}) is not larger than ${have[i - 1]} (${num(have[i - 1])}): ${c.says}`,
627
+ have[i],
628
+ { [have[i - 1]]: num(have[i - 1]), [have[i]]: num(have[i]) },
629
+ );
325
630
  }
326
631
  if (c.near) {
327
- const v = num(c.near), to = work(c.to), within = work(c.within);
328
- if (v !== undefined && to !== undefined && within !== undefined && !(Math.abs(v - to) <= within + 1e-9)) f('rules.near', `${c.near} (${v}) is not within ${fmt(within)} of ${c.to} (${fmt(to)}): ${c.says}`, c.near, { [c.near]: v, expected: to, within });
632
+ const v = num(c.near),
633
+ to = work(c.to),
634
+ within = work(c.within);
635
+ if (v !== undefined && to !== undefined && within !== undefined && !(Math.abs(v - to) <= within + 1e-9))
636
+ f('rules.near', `${c.near} (${v}) is not within ${fmt(within)} of ${c.to} (${fmt(to)}): ${c.says}`, c.near, {
637
+ [c.near]: v,
638
+ expected: to,
639
+ within,
640
+ });
329
641
  }
330
642
  }
331
643
  }
@@ -334,14 +646,17 @@ export function checkRuleSet(set, vocabulary) {
334
646
  if (!rules[own]) f('rules.interface', `interface: ${shared} names ${own}, which isn't one of its rules`, own);
335
647
  }
336
648
  for (const [name, v] of Object.entries(set.variants || {})) {
337
- if (!KINDS.includes(v.kind)) f('rules.kind', `variant ${name}: kind ${JSON.stringify(v.kind)} is not one of ${KINDS.join(', ')}`);
649
+ if (!KINDS.includes(v.kind))
650
+ f('rules.kind', `variant ${name}: kind ${JSON.stringify(v.kind)} is not one of ${KINDS.join(', ')}`);
338
651
  if (!(typeof v.source === 'string' && v.source)) f('rules.source', `variant ${name} has no source`);
339
- for (const rule of Object.keys(v.values || {})) if (!rules[rule]) f('rules.variant', `variant ${name} changes ${rule}, which isn't one of its rules`, rule);
652
+ for (const rule of Object.keys(v.values || {}))
653
+ if (!rules[rule]) f('rules.variant', `variant ${name} changes ${rule}, which isn't one of its rules`, rule);
340
654
  }
341
655
  return out;
342
656
  }
343
657
 
344
- export const fmt = (n) => (typeof n === 'number' ? String(Number(n.toFixed(2))) : Array.isArray(n) ? n.map(fmt).join(', ') : String(n)); // choices are names; a list rule, each entry
658
+ export const fmt = (n) =>
659
+ typeof n === 'number' ? String(Number(n.toFixed(2))) : Array.isArray(n) ? n.map(fmt).join(', ') : String(n); // choices are names; a list rule, each entry
345
660
 
346
661
  // lint(source) -> [{ line, text }]: number literals in a design's code that should be variables. Every measurement
347
662
  // belongs in a variable that says where it comes from; only 0, 1 and 2 (and numbers in comments and strings) pass.
@@ -353,34 +668,96 @@ export const fmt = (n) => (typeof n === 'number' ? String(Number(n.toFixed(2)))
353
668
  export function lint(source) {
354
669
  // A small tokeniser, so a // inside a string doesn't hide the rest of the line, code inside a template's ${…} is read
355
670
  // as code, and every way of writing a number is seen (1e3, 0x1F, 1_000, .5)
356
- const found = [], n = source.length, NUM = /^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)n?/;
357
- let line = 1, i = 0;
671
+ const found = [],
672
+ n = source.length,
673
+ NUM = /^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)n?/;
674
+ let line = 1,
675
+ i = 0;
358
676
  const depth = []; // open template literals: the brace depth their ${ started at
359
677
  let braces = 0;
360
- const skipString = (q) => { i++; while (i < n && source[i] !== q) { if (source[i] === '\\') i++; else if (source[i] === '\n') line++; i++; } i++; };
361
- const template = () => { // from just after a backtick (or a closing } of ${…}) to the next ${ or the closing backtick
678
+ const skipString = (q) => {
679
+ i++;
680
+ while (i < n && source[i] !== q) {
681
+ if (source[i] === '\\') i++;
682
+ else if (source[i] === '\n') line++;
683
+ i++;
684
+ }
685
+ i++;
686
+ };
687
+ const template = () => {
688
+ // from just after a backtick (or a closing } of ${…}) to the next ${ or the closing backtick
362
689
  while (i < n) {
363
690
  const c = source[i];
364
- if (c === '\\') { i += 2; continue; }
691
+ if (c === '\\') {
692
+ i += 2;
693
+ continue;
694
+ }
365
695
  if (c === '\n') line++;
366
- if (c === '`') { i++; return; }
367
- if (c === '$' && source[i + 1] === '{') { i += 2; depth.push(braces); braces++; return; }
696
+ if (c === '`') {
697
+ i++;
698
+ return;
699
+ }
700
+ if (c === '$' && source[i + 1] === '{') {
701
+ i += 2;
702
+ depth.push(braces);
703
+ braces++;
704
+ return;
705
+ }
368
706
  i++;
369
707
  }
370
708
  };
371
709
  while (i < n) {
372
710
  const c = source[i];
373
- if (c === '\n') { line++; i++; continue; }
374
- if (c === '/' && source[i + 1] === '/') { while (i < n && source[i] !== '\n') i++; continue; }
375
- if (c === '/' && source[i + 1] === '*') { const end = source.indexOf('*/', i + 2), stop = end < 0 ? n : end + 2; for (let k = i; k < stop; k++) if (source[k] === '\n') line++; i = stop; continue; }
376
- if (c === '"' || c === "'") { skipString(c); continue; }
377
- if (c === '`') { i++; template(); continue; }
378
- if (c === '{') { braces++; i++; continue; }
379
- if (c === '}') { braces--; i++; if (depth.length && braces === depth.at(-1)) { depth.pop(); template(); } continue; }
380
- if (/[\w$]/.test(c) && !/\d/.test(c)) { while (i < n && /[\w$]/.test(source[i])) i++; continue; } // a name (x1, v2: not numbers)
711
+ if (c === '\n') {
712
+ line++;
713
+ i++;
714
+ continue;
715
+ }
716
+ if (c === '/' && source[i + 1] === '/') {
717
+ while (i < n && source[i] !== '\n') i++;
718
+ continue;
719
+ }
720
+ if (c === '/' && source[i + 1] === '*') {
721
+ const end = source.indexOf('*/', i + 2),
722
+ stop = end < 0 ? n : end + 2;
723
+ for (let k = i; k < stop; k++) if (source[k] === '\n') line++;
724
+ i = stop;
725
+ continue;
726
+ }
727
+ if (c === '"' || c === "'") {
728
+ skipString(c);
729
+ continue;
730
+ }
731
+ if (c === '`') {
732
+ i++;
733
+ template();
734
+ continue;
735
+ }
736
+ if (c === '{') {
737
+ braces++;
738
+ i++;
739
+ continue;
740
+ }
741
+ if (c === '}') {
742
+ braces--;
743
+ i++;
744
+ if (depth.length && braces === depth.at(-1)) {
745
+ depth.pop();
746
+ template();
747
+ }
748
+ continue;
749
+ }
750
+ if (/[\w$]/.test(c) && !/\d/.test(c)) {
751
+ while (i < n && /[\w$]/.test(source[i])) i++;
752
+ continue;
753
+ } // a name (x1, v2: not numbers)
381
754
  if (/\d/.test(c) || (c === '.' && /\d/.test(source[i + 1] || '') && !/[\w$)\]]/.test(source[i - 1] || ''))) {
382
- if (c === '.' && /[\w$)\].]/.test(source[i - 1] || '')) { i++; continue; } // (a property after a dot)
383
- const m = source.slice(i).match(NUM), text = m[0];
755
+ if (c === '.' && /[\w$)\].]/.test(source[i - 1] || '')) {
756
+ i++;
757
+ continue;
758
+ } // (a property after a dot)
759
+ const m = source.slice(i).match(NUM),
760
+ text = m[0];
384
761
  const value = Number(text.replace(/_/g, '').replace(/n$/, ''));
385
762
  if (!(value === 0 || value === 1 || value === 2)) found.push({ line, text });
386
763
  i += text.length;