@constructorfleet/sketchforge-engine 1.31.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +120 -1
  2. package/dist/apiErrors.d.ts +84 -0
  3. package/dist/apiErrors.d.ts.map +1 -0
  4. package/dist/apiErrors.js +292 -0
  5. package/dist/apiErrors.js.map +1 -0
  6. package/dist/apiParameters.d.ts +426 -0
  7. package/dist/apiParameters.d.ts.map +1 -0
  8. package/dist/apiParameters.js +144 -0
  9. package/dist/apiParameters.js.map +1 -0
  10. package/dist/apiShapeSummary.d.ts +128 -0
  11. package/dist/apiShapeSummary.d.ts.map +1 -0
  12. package/dist/apiShapeSummary.js +96 -0
  13. package/dist/apiShapeSummary.js.map +1 -0
  14. package/dist/apiSketchConstraints.d.ts +80 -0
  15. package/dist/apiSketchConstraints.d.ts.map +1 -0
  16. package/dist/apiSketchConstraints.js +59 -0
  17. package/dist/apiSketchConstraints.js.map +1 -0
  18. package/dist/domain/sketchforge.d.ts +31 -0
  19. package/dist/domain/sketchforge.d.ts.map +1 -1
  20. package/dist/editorHistory.d.ts +25 -4
  21. package/dist/editorHistory.d.ts.map +1 -1
  22. package/dist/editorHistory.js +75 -14
  23. package/dist/editorHistory.js.map +1 -1
  24. package/dist/engine.d.ts +105 -3
  25. package/dist/engine.d.ts.map +1 -1
  26. package/dist/engine.js +1281 -655
  27. package/dist/engine.js.map +1 -1
  28. package/dist/expressionBindings.d.ts +113 -0
  29. package/dist/expressionBindings.d.ts.map +1 -0
  30. package/dist/expressionBindings.js +353 -0
  31. package/dist/expressionBindings.js.map +1 -0
  32. package/dist/index.d.ts +11 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +9 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/parameterBindingPlan.d.ts +64 -0
  37. package/dist/parameterBindingPlan.d.ts.map +1 -0
  38. package/dist/parameterBindingPlan.js +138 -0
  39. package/dist/parameterBindingPlan.js.map +1 -0
  40. package/dist/parameterExpressions.d.ts +128 -0
  41. package/dist/parameterExpressions.d.ts.map +1 -0
  42. package/dist/parameterExpressions.js +666 -0
  43. package/dist/parameterExpressions.js.map +1 -0
  44. package/dist/parametricRecompute.d.ts.map +1 -1
  45. package/dist/parametricRecompute.js +25 -2
  46. package/dist/parametricRecompute.js.map +1 -1
  47. package/dist/projectParameters.d.ts +126 -0
  48. package/dist/projectParameters.d.ts.map +1 -0
  49. package/dist/projectParameters.js +534 -0
  50. package/dist/projectParameters.js.map +1 -0
  51. package/dist/revolveRequests.d.ts +1 -0
  52. package/dist/revolveRequests.d.ts.map +1 -1
  53. package/dist/revolveRequests.js +1 -0
  54. package/dist/revolveRequests.js.map +1 -1
  55. package/dist/sceneExport.d.ts.map +1 -1
  56. package/dist/sceneExport.js +3 -0
  57. package/dist/sceneExport.js.map +1 -1
  58. package/dist/serverProjectDocument.d.ts +7 -2
  59. package/dist/serverProjectDocument.d.ts.map +1 -1
  60. package/dist/serverProjectDocument.js +16 -1
  61. package/dist/serverProjectDocument.js.map +1 -1
  62. package/dist/serverShapeGroups.d.ts +5 -0
  63. package/dist/serverShapeGroups.d.ts.map +1 -1
  64. package/dist/serverShapeGroups.js +45 -0
  65. package/dist/serverShapeGroups.js.map +1 -1
  66. package/dist/shapeRequestExpressions.d.ts +31 -0
  67. package/dist/shapeRequestExpressions.d.ts.map +1 -0
  68. package/dist/shapeRequestExpressions.js +64 -0
  69. package/dist/shapeRequestExpressions.js.map +1 -0
  70. package/dist/shapeRequests.d.ts +1 -1
  71. package/dist/shapeRequests.d.ts.map +1 -1
  72. package/dist/shapeRequests.js +3 -1
  73. package/dist/shapeRequests.js.map +1 -1
  74. package/dist/sketchConstraintBindings.d.ts +131 -0
  75. package/dist/sketchConstraintBindings.d.ts.map +1 -0
  76. package/dist/sketchConstraintBindings.js +353 -0
  77. package/dist/sketchConstraintBindings.js.map +1 -0
  78. package/dist/sketchConstraints.d.ts +34 -0
  79. package/dist/sketchConstraints.d.ts.map +1 -0
  80. package/dist/sketchConstraints.js +919 -0
  81. package/dist/sketchConstraints.js.map +1 -0
  82. package/dist/skfProject.d.ts +41 -4
  83. package/dist/skfProject.d.ts.map +1 -1
  84. package/dist/skfProject.js +154 -16
  85. package/dist/skfProject.js.map +1 -1
  86. package/dist/support/lib/operator-configuration.json +3 -3
  87. package/package.json +1 -1
@@ -0,0 +1,666 @@
1
+ /**
2
+ * Evaluates unit-aware parameter expressions. Pure: no shapes, no project model. Validates its
3
+ * inputs at runtime, since they can arrive as JSON.
4
+ *
5
+ * Values are in base units: mm for length, degrees for angle, products of these for derived
6
+ * dimensions (mm² for area).
7
+ *
8
+ * Bare numbers have no dimension until context gives one:
9
+ * - `+`, `-`, `min`, `max`: takes the other operand's dimension (`wall + 3` is wall + 3 mm).
10
+ * - `*`, `/`: stays unitless (`wall * 2` is a length).
11
+ * - `abs`, `round`, `floor`, `ceil`, `sqrt`, and `min`/`max` of bare arguments: stays bare
12
+ * (`wall + abs(-3)` is wall + 3 mm; `sqrt(16)` in a length field is 4 mm).
13
+ * - trig argument: an angle in degrees (`sin(30)`).
14
+ * - whole result: the field dimension (`3` and `2 * 3` in a length field are 3 mm and 6 mm),
15
+ * or unitless when no field dimension is given.
16
+ * Unit literals, references and trig results always have a fixed dimension.
17
+ *
18
+ * Names are ASCII identifiers. A non-ASCII letter is an invalid character, so `wäll` reads as
19
+ * the names `w` and `ll` around it.
20
+ */
21
+ export const DIMENSIONS = Object.freeze({
22
+ unitless: Object.freeze({ length: 0, angle: 0 }),
23
+ length: Object.freeze({ length: 1, angle: 0 }),
24
+ area: Object.freeze({ length: 2, angle: 0 }),
25
+ volume: Object.freeze({ length: 3, angle: 0 }),
26
+ angle: Object.freeze({ length: 0, angle: 1 }),
27
+ });
28
+ const UNIT_SCALES = {
29
+ mm: { scale: 1, dimension: DIMENSIONS.length },
30
+ cm: { scale: 10, dimension: DIMENSIONS.length },
31
+ m: { scale: 1000, dimension: DIMENSIONS.length },
32
+ in: { scale: 25.4, dimension: DIMENSIONS.length },
33
+ ft: { scale: 304.8, dimension: DIMENSIONS.length },
34
+ deg: { scale: 1, dimension: DIMENSIONS.angle },
35
+ rad: { scale: 180 / Math.PI, dimension: DIMENSIONS.angle },
36
+ };
37
+ export const EXPRESSION_UNITS = Object.freeze(["mm", "cm", "m", "in", "ft", "deg", "rad"]);
38
+ /** Rounding functions work on base-unit values: `floor(1in)` is 25 mm. */
39
+ export const EXPRESSION_FUNCTIONS = Object.freeze([
40
+ "min",
41
+ "max",
42
+ "abs",
43
+ "sqrt",
44
+ "round",
45
+ "floor",
46
+ "ceil",
47
+ "sin",
48
+ "cos",
49
+ "tan",
50
+ ]);
51
+ const MAX_NAME_LENGTH = 64;
52
+ const MAX_EXPRESSION_LENGTH = 10_000;
53
+ // Bounds parser and evaluator recursion; flat chains and sign runs do not recurse.
54
+ const MAX_NESTING = 128;
55
+ const MAX_PARAMETERS = 10_000;
56
+ const NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
57
+ const RESERVED = new Set([...EXPRESSION_UNITS, ...EXPRESSION_FUNCTIONS]);
58
+ /** Accepts ASCII identifiers of up to 64 characters that are not unit or function names. */
59
+ export function isValidParameterName(name) {
60
+ return typeof name === "string" && name.length <= MAX_NAME_LENGTH && NAME_PATTERN.test(name) && !RESERVED.has(name);
61
+ }
62
+ function isUnit(name) {
63
+ return Object.hasOwn(UNIT_SCALES, name);
64
+ }
65
+ function isFunction(name) {
66
+ return EXPRESSION_FUNCTIONS.includes(name);
67
+ }
68
+ const NUMBER_AT = /(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y;
69
+ const NAME_AT = /[A-Za-z_][A-Za-z0-9_]*/y;
70
+ // Unknown characters become `invalid` tokens so names after them stay visible to rename.
71
+ function tokenize(source) {
72
+ const tokens = [];
73
+ let index = 0;
74
+ while (index < source.length) {
75
+ const char = source[index];
76
+ if (/\s/.test(char)) {
77
+ index += 1;
78
+ continue;
79
+ }
80
+ NUMBER_AT.lastIndex = index;
81
+ NAME_AT.lastIndex = index;
82
+ const number = NUMBER_AT.exec(source);
83
+ const name = number ? null : NAME_AT.exec(source);
84
+ if (number) {
85
+ tokens.push({ kind: "number", text: number[0], start: index, end: index + number[0].length });
86
+ }
87
+ else if (name) {
88
+ tokens.push({ kind: "name", text: name[0], start: index, end: index + name[0].length });
89
+ }
90
+ else if ("+-*/(),".includes(char)) {
91
+ tokens.push({ kind: "symbol", text: char, start: index, end: index + 1 });
92
+ }
93
+ else {
94
+ const width = String.fromCodePoint(source.codePointAt(index)).length;
95
+ tokens.push({ kind: "invalid", text: source.slice(index, index + width), start: index, end: index + width });
96
+ }
97
+ index = tokens[tokens.length - 1].end;
98
+ }
99
+ tokens.push({ kind: "end", text: "", start: source.length, end: source.length });
100
+ return tokens;
101
+ }
102
+ function isReferenceToken(tokens, index) {
103
+ const token = tokens[index];
104
+ if (token.kind !== "name" || RESERVED.has(token.text))
105
+ return false;
106
+ const next = tokens[index + 1];
107
+ return !(next?.kind === "symbol" && next.text === "(");
108
+ }
109
+ function referenceTokens(source) {
110
+ const tokens = tokenize(source);
111
+ return tokens.filter((_, index) => isReferenceToken(tokens, index));
112
+ }
113
+ /** Lists referenced parameter names once each, in first-use order. Reads malformed input too. */
114
+ export function expressionDependencies(expression) {
115
+ if (typeof expression !== "string")
116
+ return [];
117
+ return [...new Set(referenceTokens(expression).map((token) => token.text))];
118
+ }
119
+ /**
120
+ * Renames references to `oldName`, leaving all other text intact. Does not check that `newName`
121
+ * is unused; callers must. Throws `RangeError` when `newName` is not a valid parameter name.
122
+ */
123
+ export function renameExpressionReference(expression, oldName, newName) {
124
+ if (typeof expression !== "string")
125
+ throw new TypeError("Expression must be a string.");
126
+ if (!isValidParameterName(newName))
127
+ throw new RangeError(`Invalid parameter name: ${JSON.stringify(newName)}`);
128
+ let output = "";
129
+ let cursor = 0;
130
+ for (const token of referenceTokens(expression)) {
131
+ if (token.text !== oldName)
132
+ continue;
133
+ output += expression.slice(cursor, token.start) + newName;
134
+ cursor = token.end;
135
+ }
136
+ return output + expression.slice(cursor);
137
+ }
138
+ class ExpressionFailure {
139
+ error;
140
+ constructor(error) {
141
+ this.error = error;
142
+ }
143
+ }
144
+ function fail(code, message, span) {
145
+ throw new ExpressionFailure({ code, message, span });
146
+ }
147
+ function spanOf(token) {
148
+ return { start: token.start, end: token.end };
149
+ }
150
+ function join(left, right) {
151
+ return { start: left.start, end: right.end };
152
+ }
153
+ class Parser {
154
+ tokens;
155
+ index = 0;
156
+ depth = 0;
157
+ constructor(tokens) {
158
+ this.tokens = tokens;
159
+ }
160
+ parse() {
161
+ const node = this.expression();
162
+ const token = this.peek();
163
+ if (token.kind !== "end")
164
+ this.unexpected(token);
165
+ return node;
166
+ }
167
+ peek() {
168
+ return this.tokens[this.index];
169
+ }
170
+ next() {
171
+ return this.tokens[this.index++];
172
+ }
173
+ isSymbol(text) {
174
+ const token = this.peek();
175
+ return token.kind === "symbol" && token.text === text;
176
+ }
177
+ unexpected(token) {
178
+ if (token.kind === "end")
179
+ fail("parseError", "Expression ends too early.", spanOf(token));
180
+ fail("parseError", `Unexpected "${token.text}".`, spanOf(token));
181
+ }
182
+ nest(token, parse) {
183
+ if (++this.depth > MAX_NESTING)
184
+ fail("limitExceeded", "Expression nests too deeply.", spanOf(token));
185
+ try {
186
+ return parse();
187
+ }
188
+ finally {
189
+ this.depth -= 1;
190
+ }
191
+ }
192
+ chain(operators, operand) {
193
+ const first = operand();
194
+ const rest = [];
195
+ while (operators.some((operator) => this.isSymbol(operator))) {
196
+ const operator = this.next().text;
197
+ rest.push({ operator, operand: operand() });
198
+ }
199
+ if (rest.length === 0)
200
+ return first;
201
+ return { kind: "chain", first, rest, span: join(first.span, rest[rest.length - 1].operand.span) };
202
+ }
203
+ expression() {
204
+ return this.chain(["+", "-"], () => this.chain(["*", "/"], () => this.unary()));
205
+ }
206
+ // Folds a run of signs into at most one negation.
207
+ unary() {
208
+ let first = null;
209
+ let negative = false;
210
+ while (this.isSymbol("-") || this.isSymbol("+")) {
211
+ const sign = this.next();
212
+ first ??= sign;
213
+ if (sign.text === "-")
214
+ negative = !negative;
215
+ }
216
+ const node = this.primary();
217
+ if (!first)
218
+ return node;
219
+ const span = join(spanOf(first), node.span);
220
+ return negative ? { kind: "negate", operand: node, span } : { ...node, span };
221
+ }
222
+ primary() {
223
+ const token = this.next();
224
+ if (token.kind === "number")
225
+ return this.literal(token);
226
+ if (token.kind === "name") {
227
+ if (this.isSymbol("("))
228
+ return this.call(token);
229
+ if (isUnit(token.text))
230
+ fail("parseError", `Unit "${token.text}" must follow a number.`, spanOf(token));
231
+ if (isFunction(token.text))
232
+ fail("parseError", `Function "${token.text}" needs arguments in parentheses.`, spanOf(token));
233
+ return { kind: "reference", name: token.text, span: spanOf(token) };
234
+ }
235
+ if (token.kind === "symbol" && token.text === "(") {
236
+ return this.nest(token, () => {
237
+ const inner = this.expression();
238
+ const close = this.closing();
239
+ return { kind: "group", inner, span: join(spanOf(token), spanOf(close)) };
240
+ });
241
+ }
242
+ return this.unexpected(token);
243
+ }
244
+ closing() {
245
+ const close = this.next();
246
+ if (close.kind === "symbol" && close.text === ")")
247
+ return close;
248
+ if (close.kind === "end")
249
+ fail("parseError", 'Missing ")".', spanOf(close));
250
+ return this.unexpected(close);
251
+ }
252
+ literal(token) {
253
+ const value = Number(token.text);
254
+ const unit = this.peek();
255
+ if (unit.kind === "name" && isUnit(unit.text)) {
256
+ this.next();
257
+ return { kind: "number", value, unit: unit.text, span: join(spanOf(token), spanOf(unit)) };
258
+ }
259
+ return { kind: "number", value, unit: null, span: spanOf(token) };
260
+ }
261
+ call(name) {
262
+ return this.nest(name, () => {
263
+ this.next();
264
+ const args = [];
265
+ if (!this.isSymbol(")")) {
266
+ args.push(this.expression());
267
+ while (this.isSymbol(",")) {
268
+ this.next();
269
+ args.push(this.expression());
270
+ }
271
+ }
272
+ const close = this.closing();
273
+ return { kind: "call", name: name.text, nameSpan: spanOf(name), args, span: join(spanOf(name), spanOf(close)) };
274
+ });
275
+ }
276
+ }
277
+ // Returns null for anything but a known name or an integer exponent record.
278
+ function parseDimension(input) {
279
+ if (typeof input === "string")
280
+ return Object.hasOwn(DIMENSIONS, input) ? DIMENSIONS[input] : null;
281
+ if (typeof input !== "object" || input === null)
282
+ return null;
283
+ const { length, angle } = input;
284
+ if (!Number.isInteger(length) || !Number.isInteger(angle))
285
+ return null;
286
+ return { length: length, angle: angle };
287
+ }
288
+ function sameDimension(a, b) {
289
+ return a.length === b.length && a.angle === b.angle;
290
+ }
291
+ /** Names a dimension for messages: "area", or "length^-1" for unnamed ones. */
292
+ export function formatDimension(dimension) {
293
+ const resolved = parseDimension(dimension);
294
+ if (!resolved)
295
+ return "invalid dimension";
296
+ const named = Object.keys(DIMENSIONS).find((name) => sameDimension(DIMENSIONS[name], resolved));
297
+ if (named)
298
+ return named;
299
+ const part = (base, power) => (power === 0 ? [] : [power === 1 ? base : `${base}^${power}`]);
300
+ return [...part("length", resolved.length), ...part("angle", resolved.angle)].join("·");
301
+ }
302
+ function lookup(scope, name) {
303
+ if (scope instanceof Map)
304
+ return scope.get(name);
305
+ const record = scope;
306
+ return Object.hasOwn(record, name) ? record[name] : undefined;
307
+ }
308
+ function resolveReference(scope, node) {
309
+ const quantity = lookup(scope, node.name);
310
+ if (quantity === undefined)
311
+ fail("unknownName", `Unknown parameter "${node.name}".`, node.span);
312
+ if (typeof quantity !== "object" || quantity === null || typeof quantity.value !== "number") {
313
+ fail("invalidArgument", `Parameter "${node.name}" has no numeric value.`, node.span);
314
+ }
315
+ const dimension = parseDimension(quantity.dimension);
316
+ if (!dimension)
317
+ fail("invalidDimension", `Parameter "${node.name}" has an invalid dimension.`, node.span);
318
+ return finite({ value: quantity.value, dimension }, node.span);
319
+ }
320
+ function finite(result, span) {
321
+ if (!Number.isFinite(result.value))
322
+ fail("nonFinite", "Result is not a finite number.", span);
323
+ return result;
324
+ }
325
+ // Fixes a bare number's dimension from its additive partner.
326
+ function unify(values, spanAt) {
327
+ let dimension = null;
328
+ values.forEach((item, index) => {
329
+ if (!item.dimension)
330
+ return;
331
+ if (dimension && !sameDimension(dimension, item.dimension)) {
332
+ fail("dimensionMismatch", `Cannot combine ${formatDimension(dimension)} with ${formatDimension(item.dimension)}.`, spanAt(index));
333
+ }
334
+ dimension = item.dimension;
335
+ });
336
+ return dimension;
337
+ }
338
+ function combine(a, b, sign) {
339
+ if (!a && !b)
340
+ return null;
341
+ const left = a ?? DIMENSIONS.unitless;
342
+ const right = b ?? DIMENSIONS.unitless;
343
+ return { length: left.length + sign * right.length, angle: left.angle + sign * right.angle };
344
+ }
345
+ const ARITY = {
346
+ min: [1, Infinity],
347
+ max: [1, Infinity],
348
+ abs: [1, 1],
349
+ sqrt: [1, 1],
350
+ round: [1, 1],
351
+ floor: [1, 1],
352
+ ceil: [1, 1],
353
+ sin: [1, 1],
354
+ cos: [1, 1],
355
+ tan: [1, 1],
356
+ };
357
+ const DEGREES = Math.PI / 180;
358
+ function evaluateCall(node, scope) {
359
+ if (!isFunction(node.name))
360
+ fail("unknownFunction", `Unknown function "${node.name}".`, node.nameSpan);
361
+ const [min, max] = ARITY[node.name];
362
+ if (node.args.length < min || node.args.length > max) {
363
+ const expected = max === Infinity ? `at least ${min}` : `${min}`;
364
+ fail("argumentCount", `${node.name} takes ${expected} argument${min === 1 && max === 1 ? "" : "s"}.`, node.span);
365
+ }
366
+ const args = node.args.map((arg) => evaluateNode(arg, scope));
367
+ const [first] = args;
368
+ switch (node.name) {
369
+ case "min":
370
+ case "max": {
371
+ const dimension = unify(args, (index) => node.args[index].span);
372
+ const pick = node.name === "min" ? Math.min : Math.max;
373
+ return { value: pick(...args.map((arg) => arg.value)), dimension };
374
+ }
375
+ case "abs":
376
+ return { value: Math.abs(first.value), dimension: first.dimension };
377
+ case "round":
378
+ return { value: Math.round(first.value), dimension: first.dimension };
379
+ case "floor":
380
+ return { value: Math.floor(first.value), dimension: first.dimension };
381
+ case "ceil":
382
+ return { value: Math.ceil(first.value), dimension: first.dimension };
383
+ case "sqrt": {
384
+ const dimension = first.dimension;
385
+ if (dimension && (dimension.length % 2 !== 0 || dimension.angle % 2 !== 0)) {
386
+ fail("dimensionMismatch", `Cannot take the square root of ${formatDimension(dimension)}.`, node.args[0].span);
387
+ }
388
+ return { value: Math.sqrt(first.value), dimension: dimension && { length: dimension.length / 2, angle: dimension.angle / 2 } };
389
+ }
390
+ case "sin":
391
+ case "cos":
392
+ case "tan": {
393
+ if (first.dimension && !sameDimension(first.dimension, DIMENSIONS.angle)) {
394
+ fail("dimensionMismatch", `${node.name} needs angle, got ${formatDimension(first.dimension)}.`, node.args[0].span);
395
+ }
396
+ return { value: Math[node.name](first.value * DEGREES), dimension: DIMENSIONS.unitless };
397
+ }
398
+ }
399
+ }
400
+ function applyOperator(operator, left, right, rightSpan, span) {
401
+ switch (operator) {
402
+ case "+":
403
+ case "-": {
404
+ const dimension = unify([left, right], () => span);
405
+ const value = operator === "+" ? left.value + right.value : left.value - right.value;
406
+ return finite({ value, dimension }, span);
407
+ }
408
+ case "*":
409
+ return finite({ value: left.value * right.value, dimension: combine(left.dimension, right.dimension, 1) }, span);
410
+ case "/":
411
+ if (right.value === 0)
412
+ fail("divisionByZero", "Division by zero.", rightSpan);
413
+ return finite({ value: left.value / right.value, dimension: combine(left.dimension, right.dimension, -1) }, span);
414
+ }
415
+ }
416
+ function evaluateNode(node, scope) {
417
+ switch (node.kind) {
418
+ case "number": {
419
+ if (!node.unit)
420
+ return finite({ value: node.value, dimension: null }, node.span);
421
+ const unit = UNIT_SCALES[node.unit];
422
+ return finite({ value: node.value * unit.scale, dimension: unit.dimension }, node.span);
423
+ }
424
+ case "reference":
425
+ return resolveReference(scope, node);
426
+ case "group":
427
+ return evaluateNode(node.inner, scope);
428
+ case "negate": {
429
+ const operand = evaluateNode(node.operand, scope);
430
+ return { value: -operand.value, dimension: operand.dimension };
431
+ }
432
+ case "call":
433
+ return finite(evaluateCall(node, scope), node.span);
434
+ case "chain": {
435
+ let result = evaluateNode(node.first, scope);
436
+ for (const { operator, operand } of node.rest) {
437
+ result = applyOperator(operator, result, evaluateNode(operand, scope), operand.span, join(node.first.span, operand.span));
438
+ }
439
+ return result;
440
+ }
441
+ }
442
+ }
443
+ function attempt(expression, run) {
444
+ try {
445
+ return run();
446
+ }
447
+ catch (caught) {
448
+ if (caught instanceof ExpressionFailure)
449
+ return { ok: false, error: caught.error };
450
+ // Last resort; the nesting and length limits should prevent stack exhaustion.
451
+ if (caught instanceof RangeError) {
452
+ return { ok: false, error: { code: "limitExceeded", message: "Expression is too complex.", span: { start: 0, end: expression.length } } };
453
+ }
454
+ throw caught;
455
+ }
456
+ }
457
+ const EMPTY_SPAN = { start: 0, end: 0 };
458
+ function failure(code, message, span = EMPTY_SPAN) {
459
+ return { ok: false, error: { code, message, span } };
460
+ }
461
+ /**
462
+ * Evaluates `expression` against `scope`. The result is in base units and must have
463
+ * `expectedDimension` when given. Never throws.
464
+ */
465
+ export function evaluateExpression(expression, scope = {}, expectedDimension) {
466
+ if (typeof expression !== "string")
467
+ return failure("invalidArgument", "Expression must be a string.");
468
+ if (typeof scope !== "object" || scope === null)
469
+ return failure("invalidArgument", "Scope must be a Map or an object.");
470
+ const expected = expectedDimension === undefined ? null : parseDimension(expectedDimension);
471
+ if (expectedDimension !== undefined && !expected) {
472
+ return failure("invalidDimension", `Unknown dimension ${JSON.stringify(expectedDimension) ?? String(expectedDimension)}.`);
473
+ }
474
+ if (expression.length > MAX_EXPRESSION_LENGTH) {
475
+ return failure("limitExceeded", `Expression is longer than ${MAX_EXPRESSION_LENGTH} characters.`, {
476
+ start: MAX_EXPRESSION_LENGTH,
477
+ end: expression.length,
478
+ });
479
+ }
480
+ return attempt(expression, () => {
481
+ const root = new Parser(tokenize(expression)).parse();
482
+ const result = evaluateNode(root, scope);
483
+ const dimension = result.dimension ?? expected ?? DIMENSIONS.unitless;
484
+ if (expected && !sameDimension(dimension, expected)) {
485
+ fail("dimensionMismatch", `Expected ${formatDimension(expected)}, got ${formatDimension(dimension)}.`, root.span);
486
+ }
487
+ // Normalizes -0 so stored values compare and serialize as 0.
488
+ return { ok: true, value: result.value === 0 ? 0 : result.value, dimension };
489
+ });
490
+ }
491
+ const CYCLE_MESSAGE_NAMES = 6;
492
+ function cycleMessage(names) {
493
+ if (names.length <= CYCLE_MESSAGE_NAMES + 1)
494
+ return `Reference cycle: ${names.join(" → ")}.`;
495
+ const head = names.slice(0, CYCLE_MESSAGE_NAMES).join(" → ");
496
+ return `Reference cycle: ${head} → … → ${names[0]} (${names.length - 1} parameters).`;
497
+ }
498
+ /**
499
+ * Resolves every entry in dependency order, up to 10,000 entries. Reports cycles with a path and
500
+ * dependents of failed entries as `dependencyFailed`. Name errors use an empty span.
501
+ * Throws `TypeError` when `entries` is not an array.
502
+ */
503
+ export function resolveParameterTable(entries) {
504
+ if (!Array.isArray(entries))
505
+ throw new TypeError("Parameter table entries must be an array.");
506
+ const results = new Array(entries.length);
507
+ const scope = new Map();
508
+ const order = [];
509
+ if (entries.length > MAX_PARAMETERS) {
510
+ results.fill(failure("limitExceeded", `Parameter table has more than ${MAX_PARAMETERS} entries.`));
511
+ return { results, order, scope };
512
+ }
513
+ const names = entries.map((entry) => (typeof entry === "object" && entry !== null && typeof entry.name === "string" ? entry.name : null));
514
+ const counts = new Map();
515
+ for (const name of names)
516
+ if (name !== null)
517
+ counts.set(name, (counts.get(name) ?? 0) + 1);
518
+ // Index of the single usable entry for each name; failed names map to -1.
519
+ const indexByName = new Map();
520
+ entries.forEach((entry, index) => {
521
+ const name = names[index];
522
+ const error = entryError(entry, name, counts);
523
+ if (error)
524
+ results[index] = error;
525
+ if (name !== null)
526
+ indexByName.set(name, error ? -1 : index);
527
+ });
528
+ const references = entries.map((entry, index) => (results[index] ? [] : referenceTokens(entry.expression)));
529
+ const edges = references.map((tokens) => [
530
+ ...new Set(tokens.map((token) => indexByName.get(token.text)).filter((target) => target !== undefined && target >= 0)),
531
+ ]);
532
+ const settle = (component) => {
533
+ if (component.length > 1 || edges[component[0]].includes(component[0])) {
534
+ markCycle(component, entries, references, edges, indexByName, results);
535
+ return;
536
+ }
537
+ const index = component[0];
538
+ const entry = entries[index];
539
+ const broken = references[index].find((token) => {
540
+ const target = indexByName.get(token.text);
541
+ return target !== undefined && (target < 0 || !results[target].ok);
542
+ });
543
+ const result = broken
544
+ ? failure("dependencyFailed", `Parameter "${broken.text}" has an error.`, spanOf(broken))
545
+ : evaluateExpression(entry.expression, scope, entry.dimension);
546
+ results[index] = result;
547
+ if (result.ok) {
548
+ scope.set(entry.name, { value: result.value, dimension: result.dimension });
549
+ order.push(entry.name);
550
+ }
551
+ };
552
+ stronglyConnectedComponents(entries.map((_, index) => !results[index]), edges, settle);
553
+ return { results, order, scope };
554
+ }
555
+ function entryError(entry, name, counts) {
556
+ if (name === null)
557
+ return failure("invalidArgument", "Entry must be an object with a string name.");
558
+ const { expression, dimension } = entry;
559
+ if (!isValidParameterName(name))
560
+ return failure("invalidName", `"${name}" is not a valid parameter name.`);
561
+ if (counts.get(name) > 1)
562
+ return failure("duplicateName", `Parameter "${name}" is defined more than once.`);
563
+ if (typeof expression !== "string")
564
+ return failure("invalidArgument", `Parameter "${name}" needs a string expression.`);
565
+ if (dimension !== undefined && !parseDimension(dimension)) {
566
+ return failure("invalidDimension", `Parameter "${name}" has an unknown dimension ${JSON.stringify(dimension) ?? String(dimension)}.`);
567
+ }
568
+ return null;
569
+ }
570
+ /**
571
+ * Runs iterative Tarjan over `active` nodes. Emits each component after every component it
572
+ * references, which is dependency order.
573
+ */
574
+ function stronglyConnectedComponents(active, edges, emit) {
575
+ const count = edges.length;
576
+ const index = new Int32Array(count).fill(-1);
577
+ const low = new Int32Array(count);
578
+ const onStack = new Uint8Array(count);
579
+ const stack = [];
580
+ let counter = 0;
581
+ const open = (node) => {
582
+ index[node] = low[node] = counter++;
583
+ stack.push(node);
584
+ onStack[node] = 1;
585
+ };
586
+ for (let root = 0; root < count; root += 1) {
587
+ if (!active[root] || index[root] !== -1)
588
+ continue;
589
+ open(root);
590
+ const work = [[root, 0]];
591
+ while (work.length > 0) {
592
+ const frame = work[work.length - 1];
593
+ const [node, next] = frame;
594
+ const targets = edges[node];
595
+ if (next < targets.length) {
596
+ frame[1] += 1;
597
+ const target = targets[next];
598
+ if (index[target] === -1) {
599
+ open(target);
600
+ work.push([target, 0]);
601
+ }
602
+ else if (onStack[target]) {
603
+ low[node] = Math.min(low[node], index[target]);
604
+ }
605
+ continue;
606
+ }
607
+ work.pop();
608
+ const parent = work[work.length - 1];
609
+ if (parent)
610
+ low[parent[0]] = Math.min(low[parent[0]], low[node]);
611
+ if (low[node] !== index[node])
612
+ continue;
613
+ const component = [];
614
+ let member;
615
+ do {
616
+ member = stack.pop();
617
+ onStack[member] = 0;
618
+ component.push(member);
619
+ } while (member !== node);
620
+ emit(component);
621
+ }
622
+ }
623
+ }
624
+ // All members share one path, so a long cycle costs linear memory.
625
+ function markCycle(component, entries, references, edges, indexByName, results) {
626
+ const members = new Set(component);
627
+ const start = Math.min(...component);
628
+ const path = cyclePath(start, members, edges);
629
+ const names = Object.freeze(path.map((node) => entries[node].name));
630
+ const successor = new Map();
631
+ for (let step = 0; step < path.length - 1; step += 1)
632
+ successor.set(path[step], path[step + 1]);
633
+ const message = cycleMessage(names);
634
+ for (const node of component) {
635
+ const target = successor.get(node);
636
+ const token = references[node].find((candidate) => {
637
+ const referenced = indexByName.get(candidate.text);
638
+ return target === undefined ? referenced !== undefined && members.has(referenced) : referenced === target;
639
+ });
640
+ results[node] = { ok: false, error: { code: "cycle", message, span: token ? spanOf(token) : EMPTY_SPAN, cycle: names } };
641
+ }
642
+ }
643
+ // Shortest path from `start` back to itself inside one component.
644
+ function cyclePath(start, members, edges) {
645
+ const previous = new Map();
646
+ const queue = [start];
647
+ for (let head = 0; head < queue.length; head += 1) {
648
+ const node = queue[head];
649
+ for (const target of edges[node]) {
650
+ if (!members.has(target))
651
+ continue;
652
+ if (target === start) {
653
+ const between = [];
654
+ for (let step = node; step !== start; step = previous.get(step))
655
+ between.push(step);
656
+ return [start, ...between.reverse(), start];
657
+ }
658
+ if (!previous.has(target)) {
659
+ previous.set(target, node);
660
+ queue.push(target);
661
+ }
662
+ }
663
+ }
664
+ return [start, start];
665
+ }
666
+ //# sourceMappingURL=parameterExpressions.js.map