trilean 1.13.12 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +1 -1
  2. package/dist/evaluator-operations.js +24 -4
  3. package/dist-cli/trilean.mjs +25 -5
  4. package/package.json +10 -20
  5. package/schemas/trilean.schema.json +1 -1
  6. package/dist/builtin-functions.cjs +0 -242
  7. package/dist/builtin-functions.d.cts +0 -13
  8. package/dist/complex-division.cjs +0 -47
  9. package/dist/complex-division.d.cts +0 -23
  10. package/dist/complex.cjs +0 -35
  11. package/dist/complex.d.cts +0 -23
  12. package/dist/computed-value.cjs +0 -80
  13. package/dist/computed-value.d.cts +0 -48
  14. package/dist/derived-aggregates.cjs +0 -73
  15. package/dist/derived-aggregates.d.cts +0 -9
  16. package/dist/derived-connectives.cjs +0 -39
  17. package/dist/derived-connectives.d.cts +0 -14
  18. package/dist/derived-patterns.cjs +0 -93
  19. package/dist/derived-patterns.d.cts +0 -4
  20. package/dist/derived-values.cjs +0 -23
  21. package/dist/derived-values.d.cts +0 -7
  22. package/dist/dist-ed78Tuwe.js +0 -1612
  23. package/dist/dist-ySX7cb5d.cjs +0 -1612
  24. package/dist/duration-order.cjs +0 -83
  25. package/dist/duration-order.d.cts +0 -21
  26. package/dist/evaluate-document.cjs +0 -92
  27. package/dist/evaluate-document.d.cts +0 -42
  28. package/dist/evaluation.cjs +0 -47
  29. package/dist/evaluation.d.cts +0 -29
  30. package/dist/evaluator-budget.cjs +0 -37
  31. package/dist/evaluator-budget.d.cts +0 -22
  32. package/dist/evaluator-collection.cjs +0 -33
  33. package/dist/evaluator-collection.d.cts +0 -21
  34. package/dist/evaluator-compiled.cjs +0 -310
  35. package/dist/evaluator-compiled.d.cts +0 -18
  36. package/dist/evaluator-effect.cjs +0 -57
  37. package/dist/evaluator-effect.d.cts +0 -40
  38. package/dist/evaluator-factory.cjs +0 -31
  39. package/dist/evaluator-factory.d.cts +0 -34
  40. package/dist/evaluator-literals.cjs +0 -42
  41. package/dist/evaluator-literals.d.cts +0 -8
  42. package/dist/evaluator-operations.cjs +0 -440
  43. package/dist/evaluator-operations.d.cts +0 -27
  44. package/dist/evaluator-test-helpers.cjs +0 -15030
  45. package/dist/evaluator-test-helpers.d.cts +0 -10
  46. package/dist/evaluator-test-helpers.d.ts +0 -10
  47. package/dist/evaluator-test-helpers.js +0 -14902
  48. package/dist/evaluator.cjs +0 -228
  49. package/dist/evaluator.d.cts +0 -12
  50. package/dist/functions.cjs +0 -4
  51. package/dist/functions.d.cts +0 -12
  52. package/dist/index.cjs +0 -97
  53. package/dist/index.d.cts +0 -18
  54. package/dist/input-resolvers.cjs +0 -109
  55. package/dist/input-resolvers.d.cts +0 -22
  56. package/dist/integer-power.cjs +0 -19
  57. package/dist/integer-power.d.cts +0 -11
  58. package/dist/json-value.cjs +0 -12
  59. package/dist/json-value.d.cts +0 -8
  60. package/dist/plain-record.cjs +0 -7
  61. package/dist/plain-record.d.cts +0 -2
  62. package/dist/resolvers.cjs +0 -0
  63. package/dist/resolvers.d.cts +0 -54
  64. package/dist/tree.cjs +0 -332
  65. package/dist/tree.d.cts +0 -446
package/README.md CHANGED
@@ -401,7 +401,7 @@ A text-matching leaf, symmetric in the same way as `compare`: both `left` and `r
401
401
 
402
402
  **`portableMatches`/`portableNotMatches`** answer the same question as `matches`/`notMatches` but interpret `right` as a pattern in [`trilean-regex`](https://www.npmjs.com/package/trilean-regex)'s own grammar instead of ECMAScript's — a genuine regular language (no backreferences, no lookaround), matched by that package's Thompson-construction NFA simulation rather than the host's native `RegExp` engine. Two consequences follow from that restriction, and are the reason to reach for the portable pair instead of the plain one:
403
403
 
404
- - **No catastrophic-backtracking risk.** An NFA simulation runs in time linear in the pattern's compiled state count and the input's length, regardless of the pattern's shape — there is no input a `portableMatches` pattern can be made to hang on the way a pathological ECMAScript pattern can hang `matches`.
404
+ - **No catastrophic-backtracking risk.** An NFA simulation runs in time linear in the pattern's compiled state count and the input's length, regardless of the pattern's shape: there is no input a `portableMatches` pattern can be made to hang on the way a pathological ECMAScript pattern can hang `matches`. The work is limited as well as bounded: a pattern past the limits of `trilean-regex` is `wrong-type` like any pattern outside the grammar, and `left` text too long for the pattern, by the limits that package states for an input, is `domain-error` and names them.
405
405
  - **Provable pushdown equivalence.** Because the grammar is a true regular language, [`trilean-sql`](https://www.npmjs.com/package/trilean-sql)'s dialect compilers can translate a `portableMatches`/`portableNotMatches` pattern into a database's own `LIKE`/`GLOB`/native-regex operators and prove the translation agrees with this package's own evaluator row for row — the same "compile and measure agreement against the reference matcher" discipline `trilean-sql` already applies to everything else it compiles. `matches`/`notMatches` carry no such guarantee: what a SQL engine's own native regex operator accepts is a different language from ECMAScript's, and `trilean-sql` refuses to push either operator down for exactly that reason (see `trilean-sql`'s README).
406
406
 
407
407
  This is additive, not a redefinition: `matches`/`notMatches` keep their existing ECMAScript semantics unchanged, and nothing already written against them is affected. Reach for `portableMatches`/`portableNotMatches` specifically when a tree might be compiled to SQL (or when the backtracking-safety guarantee alone is worth the smaller grammar), and keep `matches`/`notMatches` for in-process-only trees that need ECMAScript's full expressiveness. An invalid `trilean-regex` pattern is `wrong-type`, exactly like an invalid ECMAScript pattern under `matches` — see `trilean-regex`'s own README for the grammar's precise definition and what it deliberately excludes.
@@ -3,7 +3,7 @@ import { definite, firstIndeterminate, indeterminate } from "./evaluation.js";
3
3
  import { divideComplexComponents } from "./complex-division.js";
4
4
  import { compareDurations, millisecondsPerDurationUnit } from "./duration-order.js";
5
5
  import { powerByRepeatedSquaring } from "./integer-power.js";
6
- import { RegexParseError, compilePattern } from "trilean-regex";
6
+ import { RegexInputError, RegexParseError, compilePattern } from "trilean-regex";
7
7
  // src/evaluator-operations.ts
8
8
  /** The indeterminate result for a resolver's report of absence: `not-yet-known` when the resolver said the value has not been supplied yet, `not-found` otherwise. The two share every propagation rule except `exists` (and so `coalesce`), which is why every resolver call site goes through this one function. */
9
9
  function absenceEvaluation(absence, notFoundMessage, notYetKnownMessage) {
@@ -96,6 +96,20 @@ function compareValues(op, left, right) {
96
96
  default: throw new Error("unreachable computed-value kind");
97
97
  }
98
98
  }
99
+ /** Tests `text` against `compiled` and frees it. The compiled pattern owns memory inside the wasm module until it is freed, and the finaliser frees it only after the event loop has turned, so a synchronous pass over many rows would hold every pattern: it is freed as soon as it has answered, or has failed to. A failure of the test is the one thrown, even when the free that follows it fails too, since a module that has panicked is spent and its second failure says less than its first. */
100
+ function testAndFree(compiled, text) {
101
+ let isMatch;
102
+ try {
103
+ isMatch = compiled.test(text);
104
+ } catch (error) {
105
+ try {
106
+ compiled.free();
107
+ } catch {}
108
+ throw error;
109
+ }
110
+ compiled.free();
111
+ return isMatch;
112
+ }
99
113
  /** `textCompare`'s two operands must both resolve to the `text` computed-value kind -- any other kind, on either operand, is `wrong-type` (see the `textCompare` section of README.md). `equals`/`notEquals` are exact string equality; `matches`/`notMatches` interpret `right`'s text as an ECMAScript regular expression tested against `left`'s text; `portableMatches`/`portableNotMatches` interpret it as a pattern in `trilean-regex`'s own restricted grammar instead, matched by that package's finite-automaton reference matcher rather than the host's native `RegExp` engine -- see the `textCompare` section of README.md for when to reach for the portable pair instead of the plain one. An invalid pattern is `wrong-type` rather than a thrown exception either way -- every data-quality problem stays inside the `Evaluation` result, per `Evaluation<T>`'s own doc comment in evaluation.ts. */
100
114
  function compareText(op, left, right) {
101
115
  if (left.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the left operand is '${left.kind}'`);
@@ -120,10 +134,16 @@ function compareText(op, left, right) {
120
134
  try {
121
135
  compiled = compilePattern(right.value);
122
136
  } catch (error) {
123
- const reason = error instanceof RegexParseError ? error.message : String(error);
124
- return indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${reason}`);
137
+ if (!(error instanceof RegexParseError)) throw error;
138
+ return indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${error.message}`);
139
+ }
140
+ let isMatch;
141
+ try {
142
+ isMatch = testAndFree(compiled, left.value);
143
+ } catch (error) {
144
+ if (!(error instanceof RegexInputError)) throw error;
145
+ return indeterminate("domain-error", `the text cannot be tested against '${right.value}': ${error.message}`);
125
146
  }
126
- const isMatch = compiled.test(left.value);
127
147
  return definite(op === "portableMatches" ? isMatch : !isMatch);
128
148
  }
129
149
  default: throw new Error("unreachable text comparison operator");
@@ -2,9 +2,9 @@
2
2
  import { readFileSync } from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
4
  import { z } from "zod";
5
- import { RegexParseError, compilePattern } from "trilean-regex";
5
+ import { RegexInputError, RegexParseError, compilePattern } from "trilean-regex";
6
6
  // package.json
7
- var version = "1.13.12";
7
+ var version = "2.0.0";
8
8
  // src/computed-value.ts
9
9
  /** Dimension symbol -\> exponent, e.g. `{ m: 1, s: -1 }` for metres per second. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`. */
10
10
  const UnitSchema = z.record(z.string(), z.number());
@@ -453,6 +453,20 @@ function compareValues(op, left, right) {
453
453
  default: throw new Error("unreachable computed-value kind");
454
454
  }
455
455
  }
456
+ /** Tests `text` against `compiled` and frees it. The compiled pattern owns memory inside the wasm module until it is freed, and the finaliser frees it only after the event loop has turned, so a synchronous pass over many rows would hold every pattern: it is freed as soon as it has answered, or has failed to. A failure of the test is the one thrown, even when the free that follows it fails too, since a module that has panicked is spent and its second failure says less than its first. */
457
+ function testAndFree(compiled, text) {
458
+ let isMatch;
459
+ try {
460
+ isMatch = compiled.test(text);
461
+ } catch (error) {
462
+ try {
463
+ compiled.free();
464
+ } catch {}
465
+ throw error;
466
+ }
467
+ compiled.free();
468
+ return isMatch;
469
+ }
456
470
  /** `textCompare`'s two operands must both resolve to the `text` computed-value kind -- any other kind, on either operand, is `wrong-type` (see the `textCompare` section of README.md). `equals`/`notEquals` are exact string equality; `matches`/`notMatches` interpret `right`'s text as an ECMAScript regular expression tested against `left`'s text; `portableMatches`/`portableNotMatches` interpret it as a pattern in `trilean-regex`'s own restricted grammar instead, matched by that package's finite-automaton reference matcher rather than the host's native `RegExp` engine -- see the `textCompare` section of README.md for when to reach for the portable pair instead of the plain one. An invalid pattern is `wrong-type` rather than a thrown exception either way -- every data-quality problem stays inside the `Evaluation` result, per `Evaluation<T>`'s own doc comment in evaluation.ts. */
457
471
  function compareText(op, left, right) {
458
472
  if (left.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the left operand is '${left.kind}'`);
@@ -477,10 +491,16 @@ function compareText(op, left, right) {
477
491
  try {
478
492
  compiled = compilePattern(right.value);
479
493
  } catch (error) {
480
- const reason = error instanceof RegexParseError ? error.message : String(error);
481
- return indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${reason}`);
494
+ if (!(error instanceof RegexParseError)) throw error;
495
+ return indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${error.message}`);
496
+ }
497
+ let isMatch;
498
+ try {
499
+ isMatch = testAndFree(compiled, left.value);
500
+ } catch (error) {
501
+ if (!(error instanceof RegexInputError)) throw error;
502
+ return indeterminate("domain-error", `the text cannot be tested against '${right.value}': ${error.message}`);
482
503
  }
483
- const isMatch = compiled.test(left.value);
484
504
  return definite(op === "portableMatches" ? isMatch : !isMatch);
485
505
  }
486
506
  default: throw new Error("unreachable text comparison operator");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "trilean",
3
- "description": "Three-valued predicate and expression evaluation trees, stored as JSON and evaluated against injected resolvers, for domain logic — business rules, eligibility checks, formulas, search filters, and more — that needs to be data instead of code.",
4
- "version": "1.13.12",
3
+ "description": "Three-valued predicate and expression evaluation trees, stored as JSON and evaluated against injected resolvers, for domain logic (business rules, eligibility checks, formulas, search filters, and more) that needs to be data instead of code.",
4
+ "version": "2.0.0",
5
5
  "bin": {
6
6
  "trilean": "./dist-cli/trilean.mjs"
7
7
  },
@@ -9,7 +9,7 @@
9
9
  "url": "https://github.com/ExaDev/trilean/issues"
10
10
  },
11
11
  "dependencies": {
12
- "trilean-regex": "1.0.24",
12
+ "trilean-regex": "2.0.0",
13
13
  "zod": "^4.6.7"
14
14
  },
15
15
  "devDependencies": {
@@ -34,24 +34,16 @@
34
34
  "vitest": "^5.1.0"
35
35
  },
36
36
  "engines": {
37
- "node": ">=20"
37
+ "node": "^20.19.0 || >=22.12.0"
38
38
  },
39
39
  "exports": {
40
40
  ".": {
41
- "types": {
42
- "import": "./dist/index.d.ts",
43
- "require": "./dist/index.d.cts"
44
- },
45
- "import": "./dist/index.js",
46
- "require": "./dist/index.cjs"
41
+ "types": "./dist/index.d.ts",
42
+ "default": "./dist/index.js"
47
43
  },
48
44
  "./*": {
49
- "types": {
50
- "import": "./dist/*.d.ts",
51
- "require": "./dist/*.d.cts"
52
- },
53
- "import": "./dist/*.js",
54
- "require": "./dist/*.cjs"
45
+ "types": "./dist/*.d.ts",
46
+ "default": "./dist/*.js"
55
47
  },
56
48
  "./schemas/*.schema.json": "./schemas/*.schema.json"
57
49
  },
@@ -72,8 +64,6 @@
72
64
  "zod"
73
65
  ],
74
66
  "license": "MIT",
75
- "main": "./dist/index.cjs",
76
- "module": "./dist/index.js",
77
67
  "publishConfig": {
78
68
  "access": "public",
79
69
  "provenance": true,
@@ -94,10 +84,10 @@
94
84
  "_test:smoke": "vitest run --project smoke",
95
85
  "_test:workers": "vitest run --project workers",
96
86
  "_typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.node.json",
97
- "_typecheck:attw": "attw --pack",
87
+ "_typecheck:attw": "attw --pack --profile esm-only",
98
88
  "build": "turbo run _build",
99
89
  "lint": "turbo run _lint",
100
- "prepublishOnly": "pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:integration && pnpm run build && pnpm run test:smoke && publint && attw --pack",
90
+ "prepublishOnly": "pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:integration && pnpm run build && pnpm run test:smoke && publint && attw --pack --profile esm-only",
101
91
  "prepush": "turbo run _prepush",
102
92
  "test": "turbo run _test",
103
93
  "test:coverage": "turbo run _test:coverage",
@@ -1 +1 @@
1
- {"$defs":{"ExpressionNode":{"anyOf":[{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"numberLiteral","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"},"value":{"type":"number"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"booleanLiteral","type":"string"},"value":{"type":"boolean"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"instantLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"durationLiteral","type":"string"},"unit":{"enum":["ms","s","min","h","d"],"type":"string"},"value":{"type":"number"}},"required":["kind","value","unit"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"reference","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","key"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"arithmetic","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["add","subtract","multiply","divide","power","modulo"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"negate","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"fn":{"type":"string"},"kind":{"const":"call","type":"string"}},"required":["kind","fn","args"],"type":"object"},{"additionalProperties":false,"properties":{"keys":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"lookup","type":"string"},"table":{"$ref":"#/$defs/schema0"}},"required":["kind","table","keys"],"type":"object"},{"additionalProperties":false,"properties":{"cases":{"items":{"additionalProperties":false,"properties":{"then":{"$ref":"#/$defs/ExpressionNode"},"when":{"$ref":"#/$defs/PredicateNode"}},"required":["when","then"],"type":"object"},"type":"array"},"fallback":{"$ref":"#/$defs/ExpressionNode"},"hitPolicy":{"enum":["first","unique"],"type":"string"},"kind":{"const":"conditional","type":"string"}},"required":["kind","cases","fallback"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"combiner":{"oneOf":[{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"max","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"min","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"combine":{"$ref":"#/$defs/ExpressionNode"},"initial":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"reduce","type":"string"}},"required":["mode","initial","combine"],"type":"object"}]},"filter":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"fold","type":"string"}},"required":["kind","collection","combiner"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"accumulator","type":"string"}},"required":["kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"delegate","type":"string"},"payload":{"$ref":"#/$defs/schema0"},"system":{"type":"string"}},"required":["kind","system","payload"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},{"anyOf":[{"additionalProperties":false,"properties":{"im":{"type":"number"},"kind":{"const":"complexLiteral","type":"string"},"re":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","re","im"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"complexLiteral","type":"string"},"magnitude":{"type":"number"},"phase":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","magnitude","phase"],"type":"object"}]}]},"PredicateNode":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"not","type":"string"},"operand":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"and","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"or","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"allOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"anyOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["gt","gte","lt","lte","eq","neq"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textCompare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["equals","notEquals","matches","notMatches","portableMatches","portableNotMatches"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"candidates":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"memberOf","type":"string"},"op":{"enum":["in","notIn"],"type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","operand","candidates"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"exists","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"some","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"every","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},"schema0":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"items":{"$ref":"#/$defs/schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$id":"https://cdn.jsdelivr.net/npm/trilean@1.13.12/schemas/trilean.schema.json","$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/PredicateNode"},{"$ref":"#/$defs/ExpressionNode"}]}
1
+ {"$defs":{"ExpressionNode":{"anyOf":[{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"numberLiteral","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"},"value":{"type":"number"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"booleanLiteral","type":"string"},"value":{"type":"boolean"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"instantLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"durationLiteral","type":"string"},"unit":{"enum":["ms","s","min","h","d"],"type":"string"},"value":{"type":"number"}},"required":["kind","value","unit"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"reference","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","key"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"arithmetic","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["add","subtract","multiply","divide","power","modulo"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"negate","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"fn":{"type":"string"},"kind":{"const":"call","type":"string"}},"required":["kind","fn","args"],"type":"object"},{"additionalProperties":false,"properties":{"keys":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"lookup","type":"string"},"table":{"$ref":"#/$defs/schema0"}},"required":["kind","table","keys"],"type":"object"},{"additionalProperties":false,"properties":{"cases":{"items":{"additionalProperties":false,"properties":{"then":{"$ref":"#/$defs/ExpressionNode"},"when":{"$ref":"#/$defs/PredicateNode"}},"required":["when","then"],"type":"object"},"type":"array"},"fallback":{"$ref":"#/$defs/ExpressionNode"},"hitPolicy":{"enum":["first","unique"],"type":"string"},"kind":{"const":"conditional","type":"string"}},"required":["kind","cases","fallback"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"combiner":{"oneOf":[{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"max","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"min","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"combine":{"$ref":"#/$defs/ExpressionNode"},"initial":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"reduce","type":"string"}},"required":["mode","initial","combine"],"type":"object"}]},"filter":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"fold","type":"string"}},"required":["kind","collection","combiner"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"accumulator","type":"string"}},"required":["kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"delegate","type":"string"},"payload":{"$ref":"#/$defs/schema0"},"system":{"type":"string"}},"required":["kind","system","payload"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},{"anyOf":[{"additionalProperties":false,"properties":{"im":{"type":"number"},"kind":{"const":"complexLiteral","type":"string"},"re":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","re","im"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"complexLiteral","type":"string"},"magnitude":{"type":"number"},"phase":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","magnitude","phase"],"type":"object"}]}]},"PredicateNode":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"not","type":"string"},"operand":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"and","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"or","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"allOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"anyOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["gt","gte","lt","lte","eq","neq"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textCompare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["equals","notEquals","matches","notMatches","portableMatches","portableNotMatches"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"candidates":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"memberOf","type":"string"},"op":{"enum":["in","notIn"],"type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","operand","candidates"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"exists","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"some","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"every","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},"schema0":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"items":{"$ref":"#/$defs/schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$id":"https://cdn.jsdelivr.net/npm/trilean@2.0.0/schemas/trilean.schema.json","$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/PredicateNode"},{"$ref":"#/$defs/ExpressionNode"}]}
@@ -1,242 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_computed_value = require("./computed-value.cjs");
3
- const require_complex = require("./complex.cjs");
4
- // src/builtin-functions.ts
5
- const DECIMAL_BASE = 10;
6
- const BINARY_BASE = 2;
7
- /** Beyond this many decimal places a double either has no digit left to round (positive places) or rounds to zero (negative places): the decimal exponent range of a finite double, from the largest value's order of magnitude down to the smallest subnormal's. Clamping to it keeps the exponent written into a number string well formed whatever count a caller passes. */
8
- const DECIMAL_PLACES_LIMIT = Math.ceil(Math.log10(Number.MAX_VALUE) - Math.log10(Number.MIN_VALUE));
9
- function isNumberValue(value) {
10
- return value?.kind === "number";
11
- }
12
- function isDimensionless(value) {
13
- return require_computed_value.unitsEqual(value.unit, void 0);
14
- }
15
- /** The magnitude of a number that carries no unit, or `undefined` for any other value. */
16
- function dimensionlessNumber(value) {
17
- return isNumberValue(value) && isDimensionless(value) ? value.value : void 0;
18
- }
19
- function withUnit(value, unit) {
20
- return unit === void 0 ? {
21
- kind: "number",
22
- value
23
- } : {
24
- kind: "number",
25
- value,
26
- unit
27
- };
28
- }
29
- /** The one exit for every numeric result: a value that left the finite range (an overflow or a limit) would otherwise surface as `Infinity` or `NaN` inside a definite value, which JSON writes as `null`. */
30
- function finiteNumber(name, value, unit) {
31
- return Number.isFinite(value) ? withUnit(value, unit) : { domainError: `${name} produced a result that is not a finite number` };
32
- }
33
- function singleNumber(name, args) {
34
- const [arg] = args;
35
- if (args.length !== 1 || !isNumberValue(arg)) return { wrongType: `${name} requires exactly one number argument` };
36
- return arg;
37
- }
38
- /** The one exit for every complex result, as `finiteNumber` is for real ones. A complex argument always gives a complex result, even when the imaginary part comes out zero, as the evaluator's own complex arithmetic does: the result kind follows the argument kind, never the value. */
39
- function finiteComplex(name, { re, im }, unit) {
40
- if (!Number.isFinite(re) || !Number.isFinite(im)) return { domainError: `${name} produced a result that is not a finite number` };
41
- return unit === void 0 ? {
42
- kind: "complex",
43
- re,
44
- im
45
- } : {
46
- kind: "complex",
47
- re,
48
- im,
49
- unit
50
- };
51
- }
52
- function singleNumberOrComplex(name, args) {
53
- const [arg] = args;
54
- if (args.length !== 1 || arg?.kind !== "number" && arg?.kind !== "complex") return { wrongType: `${name} requires exactly one number or complex number argument` };
55
- return arg;
56
- }
57
- /** The value of a single dimensionless real argument, or the `wrongType` refusing anything else (a complex value included). */
58
- function singleDimensionless(name, args) {
59
- const arg = singleNumber(name, args);
60
- if ("wrongType" in arg) return arg;
61
- if (!isDimensionless(arg)) return { wrongType: `${name} requires a dimensionless number` };
62
- return arg.value;
63
- }
64
- /** A real function of one dimensionless number, returning a dimensionless number. */
65
- function dimensionlessFunction(name, apply) {
66
- return (args) => {
67
- const value = singleDimensionless(name, args);
68
- if (typeof value !== "number") return value;
69
- return finiteNumber(name, apply(value));
70
- };
71
- }
72
- /** An inverse sine or cosine, whose real domain is the closed interval from -1 to 1; outside it the inverse is not a real number, which is a `domainError` rather than the `NaN` `Math.asin` and `Math.acos` return. */
73
- function unitIntervalInverse(name, apply) {
74
- return (args) => {
75
- const value = singleDimensionless(name, args);
76
- if (typeof value !== "number") return value;
77
- if (!(Math.abs(value) <= 1)) return { domainError: `${name} requires a number from -1 to 1` };
78
- return finiteNumber(name, apply(value));
79
- };
80
- }
81
- /**
82
- * The principal square root of a complex value: the root whose real part is not negative, with the branch cut along the negative real axis. On the cut the root lies on the positive imaginary axis whatever the sign of the zero imaginary part, matching `complexPhase`'s +pi for a negative real number, so `sqrt(z)` is `sqrt(|z|) * e^(i * phase(z) / 2)` everywhere.
83
- *
84
- * It is computed by the closed form rather than through that polar expression: with `t = sqrt((|re| + |z|) / 2)`, the root is `t + (im / 2t)i` when `re` is not negative and `|im| / 2t + t i` (with the sign of `im` on `t`) otherwise. Neither form subtracts two nearly equal quantities, and an exactly representable root comes out exact (`sqrt(-4)` is `2i`, where `cos(pi / 2)` would leave a stray real part of about 1e-16).
85
- */
86
- function principalSquareRoot(value) {
87
- const modulus = require_complex.complexMagnitude(value).value;
88
- if (modulus === 0) return {
89
- re: 0,
90
- im: 0
91
- };
92
- const sum = Math.abs(value.re) + modulus;
93
- const half = Number.isFinite(sum) ? sum / 2 : Math.abs(value.re) / 2 + modulus / 2;
94
- const t = Math.sqrt(half);
95
- const { im } = value;
96
- if (value.re >= 0) return {
97
- re: t,
98
- im: im / (2 * t)
99
- };
100
- return {
101
- re: Math.abs(im) / (2 * t),
102
- im: im < 0 ? -t : t
103
- };
104
- }
105
- /** The logarithm of a positive real number, natural or to a base already checked to be above zero and not one. */
106
- function realLogarithm(value, base) {
107
- if (base === void 0) return Math.log(value);
108
- if (base === DECIMAL_BASE) return Math.log10(value);
109
- if (base === BINARY_BASE) return Math.log2(value);
110
- return Math.log(value) / Math.log(base);
111
- }
112
- /** Halves every dimension's exponent, or `false` when one is odd and the root would need a fractional exponent. */
113
- function halveUnit(unit) {
114
- if (unit === void 0) return void 0;
115
- const halved = {};
116
- for (const [dimension, exponent] of Object.entries(unit)) {
117
- if (exponent === 0) continue;
118
- if (exponent % 2 !== 0) return false;
119
- halved[dimension] = exponent / 2;
120
- }
121
- return halved;
122
- }
123
- function extremum(name, args, prefer) {
124
- const [first, ...rest] = args;
125
- if (!isNumberValue(first)) return { wrongType: `${name} requires at least one number argument` };
126
- let best = first;
127
- for (const arg of rest) {
128
- if (!isNumberValue(arg)) return { wrongType: `${name} requires number arguments only` };
129
- if (!require_computed_value.unitsEqual(arg.unit, first.unit)) return { wrongType: `${name} requires arguments in the same unit` };
130
- if (prefer(arg.value, best.value)) best = arg;
131
- }
132
- return finiteNumber(name, best.value, best.unit);
133
- }
134
- /** Moves the decimal point of a number by editing the exponent of its shortest decimal form, so `1.005` shifted by 2 places is parsed from the text `1.005e2` (exactly 100.5) rather than computed as `1.005 * 100` (100.49999999999999). `String` writes a large or small value in exponent form already (`1.5e-7`), so the existing exponent is read and added to rather than appended to. */
135
- function shiftDecimalPoint(value, places) {
136
- const text = String(value);
137
- const marker = text.indexOf("e");
138
- const mantissa = marker === -1 ? text : text.slice(0, marker);
139
- const exponent = marker === -1 ? 0 : Number(text.slice(marker + 1));
140
- return Number(`${mantissa}e${String(exponent + places)}`);
141
- }
142
- /** Rounds to `places` decimal places, halves away from zero, working on the decimal number the value is written as. A value whose shifted magnitude reaches the largest safe integer has no fractional digit at that precision (or shifts out of the finite range altogether), so it is returned as it is. */
143
- function roundHalfAwayFromZero(value, places) {
144
- const clamped = Math.max(-DECIMAL_PLACES_LIMIT, Math.min(DECIMAL_PLACES_LIMIT, places));
145
- const shifted = shiftDecimalPoint(Math.abs(value), clamped);
146
- if (!(shifted < Number.MAX_SAFE_INTEGER)) return value;
147
- const rounded = shiftDecimalPoint(Math.round(shifted), -clamped);
148
- return rounded === 0 ? 0 : Math.sign(value) * rounded;
149
- }
150
- /**
151
- * The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, `logarithm` (natural, or to an optional real base), the two projections of a complex value onto the reals, `magnitude` and `phase`, and the trigonometric functions `sine`, `cosine`, `tangent`, `arcSine`, `arcCosine`, `arcTangent` and `arcTangent2` (the angle of the point `(x, y)`, called with `y` first).
152
- *
153
- * Which take a complex value: `squareRoot`, `exponential`, `logarithm` and `magnitude` take a real or a complex number, and `phase` a complex one only. Every other function takes real numbers only and refuses a complex value. A real argument to `squareRoot`, `exponential` or `logarithm` gives a real result, so a negative `squareRoot` or a `logarithm` of zero or a negative number stays a `domainError` rather than becoming complex; a complex argument gives a complex result, the principal value, even when its imaginary part comes out zero, as the evaluator's own complex arithmetic does. The principal values take the branch cut along the negative real axis with `phase`'s convention on it: `logarithm` is `log|z| + i phase(z)` (divided through by the natural logarithm of a base when one is given), so its imaginary part lies in [-pi, pi], and `squareRoot` is the root with a real part that is not negative, on the positive imaginary axis for a negative real number whatever the sign of its zero imaginary part.
154
- *
155
- * Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative real `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places, an `arcSine` or `arcCosine` outside -1 to 1) or a result that is not a finite number (in either component of a complex one) is a `domainError`. A `tangent` near a pole is large but finite, since no double is an odd multiple of pi/2 exactly.
156
- *
157
- * Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit (and the first two require all arguments to share one); `phase` returns a dimensionless angle in radians in the range [-pi, pi], whatever unit its argument carries, with a negative real number +pi whatever the sign of its zero imaginary part (a signed zero never gives -pi, though a tiny negative imaginary part can round to it) and zero 0 (a component that is not finite is a `domainError`); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential`, `logarithm` and the trigonometric functions accept only dimensionless numbers and return one, angles in radians. `arcTangent2` is the `phase` of `x + yi`, so it shares that range and signed-zero handling, and its two arguments must be finite.
158
- *
159
- * Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
160
- */
161
- const builtinFunctions = Object.freeze({
162
- minimum: (args) => extremum("minimum", args, (candidate, best) => candidate < best),
163
- maximum: (args) => extremum("maximum", args, (candidate, best) => candidate > best),
164
- absoluteValue: (args) => {
165
- const arg = singleNumber("absoluteValue", args);
166
- if ("wrongType" in arg) return arg;
167
- return finiteNumber("absoluteValue", Math.abs(arg.value), arg.unit);
168
- },
169
- round: (args) => {
170
- const [value, places, ...extra] = args;
171
- if (!isNumberValue(value) || extra.length > 0) return { wrongType: "round requires a number and an optional count of decimal places" };
172
- if (places === void 0) return finiteNumber("round", roundHalfAwayFromZero(value.value, 0), value.unit);
173
- if (!isNumberValue(places) || !isDimensionless(places)) return { wrongType: "round requires its decimal places to be a dimensionless number" };
174
- if (!Number.isInteger(places.value)) return { domainError: "round requires its decimal places to be an integer" };
175
- return finiteNumber("round", roundHalfAwayFromZero(value.value, places.value), value.unit);
176
- },
177
- squareRoot: (args) => {
178
- const arg = singleNumberOrComplex("squareRoot", args);
179
- if ("wrongType" in arg) return arg;
180
- const unit = halveUnit(arg.unit);
181
- if (unit === false) return { wrongType: "squareRoot requires every unit exponent to be even" };
182
- if (arg.kind === "complex") return finiteComplex("squareRoot", principalSquareRoot(arg), unit);
183
- if (arg.value < 0) return { domainError: "squareRoot of a negative number is not a real number" };
184
- return finiteNumber("squareRoot", Math.sqrt(arg.value), unit);
185
- },
186
- exponential: (args) => {
187
- const arg = singleNumberOrComplex("exponential", args);
188
- if ("wrongType" in arg) return arg;
189
- if (!require_computed_value.unitsEqual(arg.unit, void 0)) return { wrongType: "exponential requires a dimensionless number" };
190
- if (arg.kind === "complex") return finiteComplex("exponential", require_complex.complexFromPolar(Math.exp(arg.re), arg.im));
191
- return finiteNumber("exponential", Math.exp(arg.value));
192
- },
193
- logarithm: (args) => {
194
- const [value, base, ...extra] = args;
195
- if (value?.kind !== "number" && value?.kind !== "complex" || extra.length > 0) return { wrongType: "logarithm requires a number or a complex number and an optional base" };
196
- if (!require_computed_value.unitsEqual(value.unit, void 0)) return { wrongType: "logarithm requires a dimensionless number" };
197
- const baseNumber = base === void 0 ? void 0 : dimensionlessNumber(base);
198
- if (base !== void 0 && baseNumber === void 0) return { wrongType: "logarithm requires its base to be a dimensionless number" };
199
- if (value.kind === "number" && value.value <= 0) return { domainError: "logarithm requires a number above zero" };
200
- if (value.kind === "complex" && value.re === 0 && value.im === 0) return { domainError: "logarithm requires a complex number other than zero" };
201
- if (baseNumber !== void 0 && (baseNumber <= 0 || baseNumber === 1)) return { domainError: "logarithm requires its base to be above zero and not one" };
202
- if (value.kind === "number") return finiteNumber("logarithm", realLogarithm(value.value, baseNumber));
203
- return finiteComplex("logarithm", {
204
- re: realLogarithm(require_complex.complexMagnitude(value).value, baseNumber),
205
- im: require_complex.complexPhase(value).value / (baseNumber === void 0 ? 1 : Math.log(baseNumber))
206
- });
207
- },
208
- magnitude: (args) => {
209
- const [arg] = args;
210
- if (args.length !== 1) return { wrongType: "magnitude requires exactly one argument" };
211
- if (arg?.kind === "complex") {
212
- const { value, unit } = require_complex.complexMagnitude(arg);
213
- return finiteNumber("magnitude", value, unit);
214
- }
215
- if (arg?.kind !== "number") return { wrongType: "magnitude requires a number or a complex number" };
216
- return finiteNumber("magnitude", Math.abs(arg.value), arg.unit);
217
- },
218
- phase: (args) => {
219
- const [arg] = args;
220
- if (args.length !== 1 || arg?.kind !== "complex") return { wrongType: "phase requires exactly one complex argument" };
221
- if (!Number.isFinite(arg.re) || !Number.isFinite(arg.im)) return { domainError: "phase requires finite components" };
222
- return require_complex.complexPhase(arg);
223
- },
224
- sine: dimensionlessFunction("sine", Math.sin),
225
- cosine: dimensionlessFunction("cosine", Math.cos),
226
- tangent: dimensionlessFunction("tangent", Math.tan),
227
- arcSine: unitIntervalInverse("arcSine", Math.asin),
228
- arcCosine: unitIntervalInverse("arcCosine", Math.acos),
229
- arcTangent: dimensionlessFunction("arcTangent", Math.atan),
230
- arcTangent2: (args) => {
231
- const [y, x] = args;
232
- if (args.length !== 2 || !isNumberValue(y) || !isNumberValue(x)) return { wrongType: "arcTangent2 requires exactly two number arguments" };
233
- if (!isDimensionless(y) || !isDimensionless(x)) return { wrongType: "arcTangent2 requires dimensionless numbers" };
234
- if (!Number.isFinite(y.value) || !Number.isFinite(x.value)) return { domainError: "arcTangent2 requires finite arguments" };
235
- return require_complex.complexPhase({
236
- kind: "complex",
237
- re: x.value,
238
- im: y.value
239
- });
240
- }
241
- });
242
- exports.builtinFunctions = builtinFunctions;
@@ -1,13 +0,0 @@
1
- import { FunctionRegistry } from "./functions.cjs";
2
- /**
3
- * The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, `logarithm` (natural, or to an optional real base), the two projections of a complex value onto the reals, `magnitude` and `phase`, and the trigonometric functions `sine`, `cosine`, `tangent`, `arcSine`, `arcCosine`, `arcTangent` and `arcTangent2` (the angle of the point `(x, y)`, called with `y` first).
4
- *
5
- * Which take a complex value: `squareRoot`, `exponential`, `logarithm` and `magnitude` take a real or a complex number, and `phase` a complex one only. Every other function takes real numbers only and refuses a complex value. A real argument to `squareRoot`, `exponential` or `logarithm` gives a real result, so a negative `squareRoot` or a `logarithm` of zero or a negative number stays a `domainError` rather than becoming complex; a complex argument gives a complex result, the principal value, even when its imaginary part comes out zero, as the evaluator's own complex arithmetic does. The principal values take the branch cut along the negative real axis with `phase`'s convention on it: `logarithm` is `log|z| + i phase(z)` (divided through by the natural logarithm of a base when one is given), so its imaginary part lies in [-pi, pi], and `squareRoot` is the root with a real part that is not negative, on the positive imaginary axis for a negative real number whatever the sign of its zero imaginary part.
6
- *
7
- * Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative real `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places, an `arcSine` or `arcCosine` outside -1 to 1) or a result that is not a finite number (in either component of a complex one) is a `domainError`. A `tangent` near a pole is large but finite, since no double is an odd multiple of pi/2 exactly.
8
- *
9
- * Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit (and the first two require all arguments to share one); `phase` returns a dimensionless angle in radians in the range [-pi, pi], whatever unit its argument carries, with a negative real number +pi whatever the sign of its zero imaginary part (a signed zero never gives -pi, though a tiny negative imaginary part can round to it) and zero 0 (a component that is not finite is a `domainError`); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential`, `logarithm` and the trigonometric functions accept only dimensionless numbers and return one, angles in radians. `arcTangent2` is the `phase` of `x + yi`, so it shares that range and signed-zero handling, and its two arguments must be finite.
10
- *
11
- * Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
12
- */
13
- export declare const builtinFunctions: FunctionRegistry;
@@ -1,47 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- // src/complex-division.ts
3
- /**
4
- * `value * 2 ** exponent`, applied in two halves because `2 ** exponent` is infinite beyond 1023 and a quotient can need a shift of about twice that. A power of two multiplies a double exactly while the result stays normal, so when the result can be non-zero and finite (a shift between about -1077 and 1024 for a scaled quotient of order one) each half is at most about 540 in magnitude, the first multiplication is exact, and the second rounds only where the result is subnormal. Outside that range the result overflows or is below the smallest subnormal: a non-zero value gives an infinity or zero, which is correct, and a zero value with a shift of 2047 or more gives NaN (zero times an infinite half), which the caller's finite check treats as it does an infinity.
5
- */
6
- function scaleByPowerOfTwo(value, exponent) {
7
- const firstHalf = Math.trunc(exponent / 2);
8
- return value * 2 ** firstHalf * 2 ** (exponent - firstHalf);
9
- }
10
- /** The exponent of the power of two that brings a magnitude to between a quarter and a half, which this file calls about a quarter. `Math.log2` is rounded, so for a magnitude just under a power of two it can return that power itself and the result lands just under a quarter instead. The magnitude must be non-zero. */
11
- function scaleToAboutAQuarter(larger) {
12
- return -Math.floor(Math.log2(larger)) - 2;
13
- }
14
- /**
15
- * The components of `dividend / divisor` for a non-zero divisor.
16
- *
17
- * The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
18
- *
19
- * Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
20
- *
21
- * The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
22
- *
23
- * Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
24
- *
25
- * A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
26
- */
27
- function divideComplexComponents(dividend, divisor) {
28
- const largerDividend = Math.max(Math.abs(dividend.re), Math.abs(dividend.im));
29
- if (largerDividend === 0) return {
30
- re: 0,
31
- im: 0
32
- };
33
- const largerDivisor = Math.max(Math.abs(divisor.re), Math.abs(divisor.im));
34
- const dividendScale = scaleToAboutAQuarter(largerDividend);
35
- const divisorScale = scaleToAboutAQuarter(largerDivisor);
36
- const a = scaleByPowerOfTwo(dividend.re, dividendScale);
37
- const b = scaleByPowerOfTwo(dividend.im, dividendScale);
38
- const c = scaleByPowerOfTwo(divisor.re, divisorScale);
39
- const d = scaleByPowerOfTwo(divisor.im, divisorScale);
40
- const denominator = c * c + d * d;
41
- const shift = divisorScale - dividendScale;
42
- return {
43
- re: scaleByPowerOfTwo((a * c + b * d) / denominator, shift),
44
- im: scaleByPowerOfTwo((b * c - a * d) / denominator, shift)
45
- };
46
- }
47
- exports.divideComplexComponents = divideComplexComponents;
@@ -1,23 +0,0 @@
1
- /**
2
- * The components of `dividend / divisor` for a non-zero divisor.
3
- *
4
- * The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
5
- *
6
- * Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
7
- *
8
- * The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
9
- *
10
- * Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
11
- *
12
- * A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
13
- */
14
- export declare function divideComplexComponents(dividend: Readonly<{
15
- re: number;
16
- im: number;
17
- }>, divisor: Readonly<{
18
- re: number;
19
- im: number;
20
- }>): {
21
- re: number;
22
- im: number;
23
- };