@itwin/core-quantity 5.9.0-dev.9 → 5.9.1

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 (142) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/lib/cjs/BasicUnitsProvider.d.ts +44 -0
  3. package/lib/cjs/BasicUnitsProvider.d.ts.map +1 -0
  4. package/lib/cjs/BasicUnitsProvider.js +241 -0
  5. package/lib/cjs/BasicUnitsProvider.js.map +1 -0
  6. package/lib/cjs/CompositeUnitsProvider.d.ts +45 -0
  7. package/lib/cjs/CompositeUnitsProvider.d.ts.map +1 -0
  8. package/lib/cjs/CompositeUnitsProvider.js +111 -0
  9. package/lib/cjs/CompositeUnitsProvider.js.map +1 -0
  10. package/lib/cjs/FormatSpecHandle.d.ts +56 -0
  11. package/lib/cjs/FormatSpecHandle.d.ts.map +1 -0
  12. package/lib/cjs/FormatSpecHandle.js +87 -0
  13. package/lib/cjs/FormatSpecHandle.js.map +1 -0
  14. package/lib/cjs/Formatter/FormatEnums.js.map +1 -1
  15. package/lib/cjs/Formatter/Formatter.js.map +1 -1
  16. package/lib/cjs/Formatter/FormatterSpec.d.ts.map +1 -1
  17. package/lib/cjs/Formatter/FormatterSpec.js +14 -0
  18. package/lib/cjs/Formatter/FormatterSpec.js.map +1 -1
  19. package/lib/cjs/Formatter/FormattingReadyCollector.d.ts +16 -0
  20. package/lib/cjs/Formatter/FormattingReadyCollector.d.ts.map +1 -0
  21. package/lib/cjs/Formatter/FormattingReadyCollector.js +44 -0
  22. package/lib/cjs/Formatter/FormattingReadyCollector.js.map +1 -0
  23. package/lib/cjs/Formatter/Interfaces.d.ts +51 -3
  24. package/lib/cjs/Formatter/Interfaces.d.ts.map +1 -1
  25. package/lib/cjs/Formatter/Interfaces.js.map +1 -1
  26. package/lib/cjs/Interfaces.d.ts +31 -1
  27. package/lib/cjs/Interfaces.d.ts.map +1 -1
  28. package/lib/cjs/Interfaces.js.map +1 -1
  29. package/lib/cjs/Parser.d.ts.map +1 -1
  30. package/lib/cjs/Parser.js +16 -1
  31. package/lib/cjs/Parser.js.map +1 -1
  32. package/lib/cjs/ParserSpec.d.ts.map +1 -1
  33. package/lib/cjs/ParserSpec.js +15 -2
  34. package/lib/cjs/ParserSpec.js.map +1 -1
  35. package/lib/cjs/QuantityLoggerCategory.d.ts +16 -0
  36. package/lib/cjs/QuantityLoggerCategory.d.ts.map +1 -0
  37. package/lib/cjs/QuantityLoggerCategory.js +24 -0
  38. package/lib/cjs/QuantityLoggerCategory.js.map +1 -0
  39. package/lib/cjs/SerializedUnitSchema.d.ts +98 -0
  40. package/lib/cjs/SerializedUnitSchema.d.ts.map +1 -0
  41. package/lib/cjs/SerializedUnitSchema.js +25 -0
  42. package/lib/cjs/SerializedUnitSchema.js.map +1 -0
  43. package/lib/cjs/UnitConversion/Graph.d.ts +35 -0
  44. package/lib/cjs/UnitConversion/Graph.d.ts.map +1 -0
  45. package/lib/cjs/UnitConversion/Graph.js +87 -0
  46. package/lib/cjs/UnitConversion/Graph.js.map +1 -0
  47. package/lib/cjs/UnitConversion/Parser.d.ts +9 -0
  48. package/lib/cjs/UnitConversion/Parser.d.ts.map +1 -0
  49. package/lib/cjs/UnitConversion/Parser.js +42 -0
  50. package/lib/cjs/UnitConversion/Parser.js.map +1 -0
  51. package/lib/cjs/UnitConversion/UnitConversion.d.ts +56 -0
  52. package/lib/cjs/UnitConversion/UnitConversion.d.ts.map +1 -0
  53. package/lib/cjs/UnitConversion/UnitConversion.js +80 -0
  54. package/lib/cjs/UnitConversion/UnitConversion.js.map +1 -0
  55. package/lib/cjs/UnitConversion/UnitDefinitionResolver.d.ts +29 -0
  56. package/lib/cjs/UnitConversion/UnitDefinitionResolver.d.ts.map +1 -0
  57. package/lib/cjs/UnitConversion/UnitDefinitionResolver.js +102 -0
  58. package/lib/cjs/UnitConversion/UnitDefinitionResolver.js.map +1 -0
  59. package/lib/cjs/UnitConversion/nameUtils.d.ts +11 -0
  60. package/lib/cjs/UnitConversion/nameUtils.d.ts.map +1 -0
  61. package/lib/cjs/UnitConversion/nameUtils.js +25 -0
  62. package/lib/cjs/UnitConversion/nameUtils.js.map +1 -0
  63. package/lib/cjs/assets/Units.json +4215 -0
  64. package/lib/cjs/core-quantity.d.ts +22 -1
  65. package/lib/cjs/core-quantity.d.ts.map +1 -1
  66. package/lib/cjs/core-quantity.js +24 -1
  67. package/lib/cjs/core-quantity.js.map +1 -1
  68. package/lib/cjs/internal/cross-package.d.ts +4 -0
  69. package/lib/cjs/internal/cross-package.d.ts.map +1 -0
  70. package/lib/cjs/internal/cross-package.js +13 -0
  71. package/lib/cjs/internal/cross-package.js.map +1 -0
  72. package/lib/esm/BasicUnitsProvider.d.ts +44 -0
  73. package/lib/esm/BasicUnitsProvider.d.ts.map +1 -0
  74. package/lib/esm/BasicUnitsProvider.js +213 -0
  75. package/lib/esm/BasicUnitsProvider.js.map +1 -0
  76. package/lib/esm/CompositeUnitsProvider.d.ts +45 -0
  77. package/lib/esm/CompositeUnitsProvider.d.ts.map +1 -0
  78. package/lib/esm/CompositeUnitsProvider.js +108 -0
  79. package/lib/esm/CompositeUnitsProvider.js.map +1 -0
  80. package/lib/esm/FormatSpecHandle.d.ts +56 -0
  81. package/lib/esm/FormatSpecHandle.d.ts.map +1 -0
  82. package/lib/esm/FormatSpecHandle.js +83 -0
  83. package/lib/esm/FormatSpecHandle.js.map +1 -0
  84. package/lib/esm/Formatter/FormatEnums.js.map +1 -1
  85. package/lib/esm/Formatter/Formatter.js.map +1 -1
  86. package/lib/esm/Formatter/FormatterSpec.d.ts.map +1 -1
  87. package/lib/esm/Formatter/FormatterSpec.js +14 -0
  88. package/lib/esm/Formatter/FormatterSpec.js.map +1 -1
  89. package/lib/esm/Formatter/FormattingReadyCollector.d.ts +16 -0
  90. package/lib/esm/Formatter/FormattingReadyCollector.d.ts.map +1 -0
  91. package/lib/esm/Formatter/FormattingReadyCollector.js +40 -0
  92. package/lib/esm/Formatter/FormattingReadyCollector.js.map +1 -0
  93. package/lib/esm/Formatter/Interfaces.d.ts +51 -3
  94. package/lib/esm/Formatter/Interfaces.d.ts.map +1 -1
  95. package/lib/esm/Formatter/Interfaces.js.map +1 -1
  96. package/lib/esm/Interfaces.d.ts +31 -1
  97. package/lib/esm/Interfaces.d.ts.map +1 -1
  98. package/lib/esm/Interfaces.js.map +1 -1
  99. package/lib/esm/Parser.d.ts.map +1 -1
  100. package/lib/esm/Parser.js +16 -1
  101. package/lib/esm/Parser.js.map +1 -1
  102. package/lib/esm/ParserSpec.d.ts.map +1 -1
  103. package/lib/esm/ParserSpec.js +15 -2
  104. package/lib/esm/ParserSpec.js.map +1 -1
  105. package/lib/esm/QuantityLoggerCategory.d.ts +16 -0
  106. package/lib/esm/QuantityLoggerCategory.d.ts.map +1 -0
  107. package/lib/esm/QuantityLoggerCategory.js +21 -0
  108. package/lib/esm/QuantityLoggerCategory.js.map +1 -0
  109. package/lib/esm/SerializedUnitSchema.d.ts +98 -0
  110. package/lib/esm/SerializedUnitSchema.d.ts.map +1 -0
  111. package/lib/esm/SerializedUnitSchema.js +22 -0
  112. package/lib/esm/SerializedUnitSchema.js.map +1 -0
  113. package/lib/esm/UnitConversion/Graph.d.ts +35 -0
  114. package/lib/esm/UnitConversion/Graph.d.ts.map +1 -0
  115. package/lib/esm/UnitConversion/Graph.js +83 -0
  116. package/lib/esm/UnitConversion/Graph.js.map +1 -0
  117. package/lib/esm/UnitConversion/Parser.d.ts +9 -0
  118. package/lib/esm/UnitConversion/Parser.d.ts.map +1 -0
  119. package/lib/esm/UnitConversion/Parser.js +39 -0
  120. package/lib/esm/UnitConversion/Parser.js.map +1 -0
  121. package/lib/esm/UnitConversion/UnitConversion.d.ts +56 -0
  122. package/lib/esm/UnitConversion/UnitConversion.d.ts.map +1 -0
  123. package/lib/esm/UnitConversion/UnitConversion.js +76 -0
  124. package/lib/esm/UnitConversion/UnitConversion.js.map +1 -0
  125. package/lib/esm/UnitConversion/UnitDefinitionResolver.d.ts +29 -0
  126. package/lib/esm/UnitConversion/UnitDefinitionResolver.d.ts.map +1 -0
  127. package/lib/esm/UnitConversion/UnitDefinitionResolver.js +98 -0
  128. package/lib/esm/UnitConversion/UnitDefinitionResolver.js.map +1 -0
  129. package/lib/esm/UnitConversion/nameUtils.d.ts +11 -0
  130. package/lib/esm/UnitConversion/nameUtils.d.ts.map +1 -0
  131. package/lib/esm/UnitConversion/nameUtils.js +21 -0
  132. package/lib/esm/UnitConversion/nameUtils.js.map +1 -0
  133. package/lib/esm/assets/Units.json +4215 -0
  134. package/lib/esm/core-quantity.d.ts +22 -1
  135. package/lib/esm/core-quantity.d.ts.map +1 -1
  136. package/lib/esm/core-quantity.js +22 -1
  137. package/lib/esm/core-quantity.js.map +1 -1
  138. package/lib/esm/internal/cross-package.d.ts +4 -0
  139. package/lib/esm/internal/cross-package.d.ts.map +1 -0
  140. package/lib/esm/internal/cross-package.js +8 -0
  141. package/lib/esm/internal/cross-package.js.map +1 -0
  142. package/package.json +6 -5
package/CHANGELOG.md CHANGED
@@ -1,6 +1,37 @@
1
1
  # Change Log - @itwin/core-quantity
2
2
 
3
- This log was last generated on Fri, 10 Apr 2026 13:03:16 GMT and should not be manually modified.
3
+ This log was last generated on Tue, 05 May 2026 17:43:30 GMT and should not be manually modified.
4
+
5
+ ## 5.9.1
6
+ Tue, 05 May 2026 17:43:30 GMT
7
+
8
+ _Version update only_
9
+
10
+ ## 5.9.0
11
+ Mon, 04 May 2026 16:32:08 GMT
12
+
13
+ ### Minor changes
14
+
15
+ - Add Units namespace with typed constants, findPersistenceUnitForPhenomenon helper, and impliedUnitSystem to FormatsChangedArgs.
16
+
17
+ ### Updates
18
+
19
+ - Added BasicUnitsProvider (bundled BIS units), createUnitsProvider factory, and CreateUnitsProviderOptions interface. Added UnitConversion math, parseDefinition, and Graph utilities (moved from ecschema-metadata). Added SerializedUnitSchema types and UnitDefinitionResolver.
20
+
21
+ ## 5.8.4
22
+ Thu, 23 Apr 2026 18:05:14 GMT
23
+
24
+ _Version update only_
25
+
26
+ ## 5.8.3
27
+ Thu, 23 Apr 2026 14:52:42 GMT
28
+
29
+ _Version update only_
30
+
31
+ ## 5.8.2
32
+ Thu, 16 Apr 2026 11:05:01 GMT
33
+
34
+ _Version update only_
4
35
 
5
36
  ## 5.8.1
6
37
  Fri, 10 Apr 2026 13:02:00 GMT
@@ -0,0 +1,44 @@
1
+ import { type UnitConversionProps, type UnitProps, type UnitsProvider } from "./Interfaces";
2
+ /** @internal — test use only. Resets the module-level lazy cache. */
3
+ export declare function _testResetUnitsCache(): void;
4
+ /**
5
+ * A `UnitsProvider` backed by the full BIS `Units.ecschema.json` bundled as a JSON asset.
6
+ *
7
+ * The ~90 KB bundled JSON is loaded lazily via dynamic `import()` on the first provider method
8
+ * call and cached at module scope — construction is essentially free, and multiple instances
9
+ * share the same immutable lookup indexes.
10
+ *
11
+ * This is the zero-dependency default for backends, tools, and any frontend that doesn't need
12
+ * iModel overrides. Equivalent to calling `createUnitsProvider()` with no arguments.
13
+ *
14
+ * @see createUnitsProvider for layering schema-defined units on top of basic BIS units.
15
+ * @beta
16
+ */
17
+ export declare class BasicUnitsProvider implements UnitsProvider {
18
+ /** Find a unit by its display label, optionally filtering by schema name, phenomenon, and unit system.
19
+ * @param unitLabel - The display label to search for (case-insensitive).
20
+ * @param schemaName - Optional schema name filter. Returns `BadUnit` if provided and not `"Units"`.
21
+ * @param phenomenon - Optional phenomenon filter (e.g. `"Units.LENGTH"`).
22
+ * @param unitSystem - Optional unit system filter (e.g. `"Units.METRIC"`).
23
+ * @returns The matching `UnitProps`, or a `BadUnit` if no match is found.
24
+ */
25
+ findUnit(unitLabel: string, schemaName?: string, phenomenon?: string, unitSystem?: string): Promise<UnitProps>;
26
+ /** Return all units belonging to the given phenomenon (unit family).
27
+ * @param phenomenon - The phenomenon full name (e.g. `"Units.LENGTH"`).
28
+ * @returns An array of matching `UnitProps`, or an empty array if none.
29
+ */
30
+ getUnitsByFamily(phenomenon: string): Promise<UnitProps[]>;
31
+ /** Find a unit by its fully-qualified name (e.g. `"Units.M"`).
32
+ * @param unitName - The qualified unit name.
33
+ * @returns The matching `UnitProps`, or a `BadUnit` if not found.
34
+ */
35
+ findUnitByName(unitName: string): Promise<UnitProps>;
36
+ /** Compute the conversion factors from `fromUnit` to `toUnit`.
37
+ * Handles normal units, inverted units, and mixed (inverted ↔ non-inverted) conversions.
38
+ * @param fromUnit - The source unit.
39
+ * @param toUnit - The target unit.
40
+ * @returns A `UnitConversionProps` with `factor`, `offset`, and optionally `inversion` and `error`.
41
+ */
42
+ getConversion(fromUnit: UnitProps, toUnit: UnitProps): Promise<UnitConversionProps>;
43
+ }
44
+ //# sourceMappingURL=BasicUnitsProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BasicUnitsProvider.d.ts","sourceRoot":"","sources":["../../src/BasicUnitsProvider.ts"],"names":[],"mappings":"AAIA,OAAO,EAAwB,KAAK,mBAAmB,EAAE,KAAK,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAgDlH,qEAAqE;AACrE,wBAAgB,oBAAoB,IAAI,IAAI,CAG3C;AAsFD;;;;;;;;;;;;GAYG;AACH,qBAAa,kBAAmB,YAAW,aAAa;IAItD;;;;;;OAMG;IACU,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;IAuB3H;;;OAGG;IACU,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAMvE;;;OAGG;IACU,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;IAMjE;;;;;OAKG;IACU,aAAa,CAAC,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,GAAG,OAAO,CAAC,mBAAmB,CAAC;CAkDjG"}
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.BasicUnitsProvider = void 0;
27
+ exports._testResetUnitsCache = _testResetUnitsCache;
28
+ /*---------------------------------------------------------------------------------------------
29
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
30
+ * See LICENSE.md in the project root for license terms and full copyright notice.
31
+ *--------------------------------------------------------------------------------------------*/
32
+ const Interfaces_1 = require("./Interfaces");
33
+ const UnitDefinitionResolver_1 = require("./UnitConversion/UnitDefinitionResolver");
34
+ const nameUtils_1 = require("./UnitConversion/nameUtils");
35
+ const Unit_1 = require("./Unit");
36
+ // Module-level cache: the unit data is derived deterministically from the bundled Units.json
37
+ // asset, so the resolved indexes are effectively an immutable constant. Caching at module
38
+ // scope avoids redundant work when multiple BasicUnitsProvider instances are created (e.g.
39
+ // in tests or when composed inside CompositeUnitsProvider).
40
+ // The JSON is loaded lazily via dynamic import() on first use, keeping the module footprint
41
+ // near-zero until a provider method is actually called.
42
+ let _resolvePromise;
43
+ let _permanentError;
44
+ async function resolveState() {
45
+ if (_permanentError !== undefined) {
46
+ throw _permanentError;
47
+ }
48
+ if (!_resolvePromise) {
49
+ _resolvePromise = _buildState().catch((err) => {
50
+ _permanentError = err instanceof Error ? err : new Error(String(err));
51
+ _resolvePromise = undefined;
52
+ throw _permanentError;
53
+ });
54
+ }
55
+ return _resolvePromise;
56
+ }
57
+ /** @internal — test use only. Resets the module-level lazy cache. */
58
+ function _testResetUnitsCache() {
59
+ _resolvePromise = undefined;
60
+ _permanentError = undefined;
61
+ }
62
+ async function _buildState() {
63
+ const { default: schema } = await Promise.resolve().then(() => __importStar(require("./assets/Units.json")));
64
+ const nameMap = new Map();
65
+ const labelMap = new Map();
66
+ const phenomenonMap = new Map();
67
+ const invertedUnits = new Map();
68
+ const s = schema;
69
+ const resolver = new UnitDefinitionResolver_1.UnitDefinitionResolver(s);
70
+ const resolved = resolver.resolveAll();
71
+ for (const [name, entry] of resolved) {
72
+ const item = s.items[name];
73
+ const phenomenon = item.phenomenon;
74
+ const unitSystem = item.unitSystem;
75
+ const fullName = `${s.name}.${name}`;
76
+ const props = {
77
+ name: fullName,
78
+ label: entry.label,
79
+ phenomenon,
80
+ isValid: true,
81
+ system: unitSystem,
82
+ };
83
+ const indexed = { props, resolved: entry };
84
+ nameMap.set(fullName, indexed);
85
+ const lowerLabel = entry.label.toLowerCase();
86
+ const byLabel = labelMap.get(lowerLabel) ?? [];
87
+ byLabel.push(indexed);
88
+ labelMap.set(lowerLabel, byLabel);
89
+ const byPhen = phenomenonMap.get(phenomenon) ?? [];
90
+ byPhen.push(indexed);
91
+ phenomenonMap.set(phenomenon, byPhen);
92
+ }
93
+ // Handle InvertedUnit items — must run after nameMap is fully populated above because
94
+ // invertedSource lookup requires the inverted unit's target to already be in nameMap.
95
+ for (const [name, item] of Object.entries(s.items)) {
96
+ if (item.schemaItemType !== "InvertedUnit") {
97
+ continue;
98
+ }
99
+ const inv = item;
100
+ const fullName = `${s.name}.${name}`;
101
+ const invertsName = (0, nameUtils_1.qualifyItemName)(inv.invertsUnit, s.name);
102
+ const unitSystem = inv.unitSystem;
103
+ const invertedSource = nameMap.get(invertsName);
104
+ const phenomenon = invertedSource?.props.phenomenon ?? "";
105
+ const props = {
106
+ name: fullName,
107
+ label: inv.label ?? name,
108
+ phenomenon,
109
+ isValid: true,
110
+ system: unitSystem,
111
+ };
112
+ invertedUnits.set(fullName, { props, invertsUnitName: invertsName });
113
+ if (invertedSource) {
114
+ const indexed = {
115
+ props,
116
+ resolved: { ...invertedSource.resolved, name: fullName, label: props.label, unitSystem },
117
+ };
118
+ nameMap.set(fullName, indexed);
119
+ const lowerLabel = props.label.toLowerCase();
120
+ const byLabel = labelMap.get(lowerLabel) ?? [];
121
+ byLabel.push(indexed);
122
+ labelMap.set(lowerLabel, byLabel);
123
+ const byPhen = phenomenonMap.get(phenomenon) ?? [];
124
+ byPhen.push(indexed);
125
+ phenomenonMap.set(phenomenon, byPhen);
126
+ }
127
+ }
128
+ return { nameMap, labelMap, phenomenonMap, invertedUnits, schemaName: s.name };
129
+ }
130
+ /**
131
+ * A `UnitsProvider` backed by the full BIS `Units.ecschema.json` bundled as a JSON asset.
132
+ *
133
+ * The ~90 KB bundled JSON is loaded lazily via dynamic `import()` on the first provider method
134
+ * call and cached at module scope — construction is essentially free, and multiple instances
135
+ * share the same immutable lookup indexes.
136
+ *
137
+ * This is the zero-dependency default for backends, tools, and any frontend that doesn't need
138
+ * iModel overrides. Equivalent to calling `createUnitsProvider()` with no arguments.
139
+ *
140
+ * @see createUnitsProvider for layering schema-defined units on top of basic BIS units.
141
+ * @beta
142
+ */
143
+ class BasicUnitsProvider {
144
+ // ── UnitsProvider implementation ─────────────────────────────────────
145
+ /** Find a unit by its display label, optionally filtering by schema name, phenomenon, and unit system.
146
+ * @param unitLabel - The display label to search for (case-insensitive).
147
+ * @param schemaName - Optional schema name filter. Returns `BadUnit` if provided and not `"Units"`.
148
+ * @param phenomenon - Optional phenomenon filter (e.g. `"Units.LENGTH"`).
149
+ * @param unitSystem - Optional unit system filter (e.g. `"Units.METRIC"`).
150
+ * @returns The matching `UnitProps`, or a `BadUnit` if no match is found.
151
+ */
152
+ async findUnit(unitLabel, schemaName, phenomenon, unitSystem) {
153
+ const state = await resolveState();
154
+ if (schemaName && schemaName !== state.schemaName) {
155
+ return new Unit_1.BadUnit();
156
+ }
157
+ const candidates = state.labelMap.get(unitLabel.toLowerCase());
158
+ if (!candidates || candidates.length === 0) {
159
+ return new Unit_1.BadUnit();
160
+ }
161
+ for (const c of candidates) {
162
+ if (phenomenon && c.props.phenomenon !== phenomenon) {
163
+ continue;
164
+ }
165
+ if (unitSystem && c.props.system !== unitSystem) {
166
+ continue;
167
+ }
168
+ return c.props;
169
+ }
170
+ return new Unit_1.BadUnit();
171
+ }
172
+ /** Return all units belonging to the given phenomenon (unit family).
173
+ * @param phenomenon - The phenomenon full name (e.g. `"Units.LENGTH"`).
174
+ * @returns An array of matching `UnitProps`, or an empty array if none.
175
+ */
176
+ async getUnitsByFamily(phenomenon) {
177
+ const state = await resolveState();
178
+ const entries = state.phenomenonMap.get(phenomenon);
179
+ return entries ? entries.map((e) => e.props) : [];
180
+ }
181
+ /** Find a unit by its fully-qualified name (e.g. `"Units.M"`).
182
+ * @param unitName - The qualified unit name.
183
+ * @returns The matching `UnitProps`, or a `BadUnit` if not found.
184
+ */
185
+ async findUnitByName(unitName) {
186
+ const state = await resolveState();
187
+ const entry = state.nameMap.get(unitName);
188
+ return entry ? entry.props : new Unit_1.BadUnit();
189
+ }
190
+ /** Compute the conversion factors from `fromUnit` to `toUnit`.
191
+ * Handles normal units, inverted units, and mixed (inverted ↔ non-inverted) conversions.
192
+ * @param fromUnit - The source unit.
193
+ * @param toUnit - The target unit.
194
+ * @returns A `UnitConversionProps` with `factor`, `offset`, and optionally `inversion` and `error`.
195
+ */
196
+ async getConversion(fromUnit, toUnit) {
197
+ const state = await resolveState();
198
+ const from = state.nameMap.get(fromUnit.name);
199
+ const to = state.nameMap.get(toUnit.name);
200
+ if (!from || !to) {
201
+ return { factor: 1.0, offset: 0.0, error: true };
202
+ }
203
+ const fromInverted = state.invertedUnits.get(fromUnit.name);
204
+ const toInverted = state.invertedUnits.get(toUnit.name);
205
+ const fromPhenomenon = fromInverted
206
+ ? state.nameMap.get(fromInverted.invertsUnitName)?.props.phenomenon
207
+ : from.props.phenomenon;
208
+ const toPhenomenon = toInverted
209
+ ? state.nameMap.get(toInverted.invertsUnitName)?.props.phenomenon
210
+ : to.props.phenomenon;
211
+ if (fromPhenomenon !== toPhenomenon) {
212
+ return { factor: 1.0, offset: 0.0, error: true };
213
+ }
214
+ if (fromInverted && toInverted) {
215
+ const innerFrom = state.nameMap.get(fromInverted.invertsUnitName);
216
+ const innerTo = state.nameMap.get(toInverted.invertsUnitName);
217
+ if (innerFrom && innerTo) {
218
+ const c = innerFrom.resolved.conversion.inverse().compose(innerTo.resolved.conversion);
219
+ return { factor: c.factor, offset: c.offset };
220
+ }
221
+ }
222
+ if (fromInverted) {
223
+ const innerFrom = state.nameMap.get(fromInverted.invertsUnitName);
224
+ if (innerFrom) {
225
+ const c = innerFrom.resolved.conversion.inverse().compose(to.resolved.conversion);
226
+ return { factor: c.factor, offset: c.offset, inversion: Interfaces_1.UnitConversionInvert.InvertPreConversion };
227
+ }
228
+ }
229
+ if (toInverted) {
230
+ const innerTo = state.nameMap.get(toInverted.invertsUnitName);
231
+ if (innerTo) {
232
+ const c = from.resolved.conversion.inverse().compose(innerTo.resolved.conversion);
233
+ return { factor: c.factor, offset: c.offset, inversion: Interfaces_1.UnitConversionInvert.InvertPostConversion };
234
+ }
235
+ }
236
+ const conv = from.resolved.conversion.inverse().compose(to.resolved.conversion);
237
+ return { factor: conv.factor, offset: conv.offset };
238
+ }
239
+ }
240
+ exports.BasicUnitsProvider = BasicUnitsProvider;
241
+ //# sourceMappingURL=BasicUnitsProvider.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CAAC;QACH,CAAC;QAED,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC;YAClE,IAAI,SAAS,EAAE,CAAC;gBACd,MAAM,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;gBAClF,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,iCAAoB,CAAC,mBAAmB,EAAE,CAAC;YACrG,CAAC;QACH,CAAC;QAED,IAAI,UAAU,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC;YAC9D,IAAI,OAAO,EAAE,CAAC;gBACZ,MAAM,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;gBAClF,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,iCAAoB,CAAC,oBAAoB,EAAE,CAAC;YACtG,CAAC;QACH,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;QAChF,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;IACtD,CAAC;CACF;AA9GD,gDA8GC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\nimport { UnitConversionInvert, type UnitConversionProps, type UnitProps, type UnitsProvider } from \"./Interfaces\";\nimport type { SerializedInvertedUnit, SerializedUnit, SerializedUnitSchema } from \"./SerializedUnitSchema\";\nimport { type ResolvedUnit, UnitDefinitionResolver } from \"./UnitConversion/UnitDefinitionResolver\";\nimport { qualifyItemName } from \"./UnitConversion/nameUtils\";\nimport { BadUnit } from \"./Unit\";\n\ninterface IndexedUnit {\n readonly props: UnitProps;\n readonly resolved: ResolvedUnit;\n}\n\ninterface InvertedEntry {\n readonly props: UnitProps;\n readonly invertsUnitName: string;\n}\n\n/** Immutable lookup indexes resolved from the bundled Units.json. */\ninterface ResolvedState {\n readonly nameMap: Map<string, IndexedUnit>;\n readonly labelMap: Map<string, IndexedUnit[]>;\n readonly phenomenonMap: Map<string, IndexedUnit[]>;\n readonly invertedUnits: Map<string, InvertedEntry>;\n readonly schemaName: string;\n}\n\n// Module-level cache: the unit data is derived deterministically from the bundled Units.json\n// asset, so the resolved indexes are effectively an immutable constant. Caching at module\n// scope avoids redundant work when multiple BasicUnitsProvider instances are created (e.g.\n// in tests or when composed inside CompositeUnitsProvider).\n// The JSON is loaded lazily via dynamic import() on first use, keeping the module footprint\n// near-zero until a provider method is actually called.\nlet _resolvePromise: Promise<ResolvedState> | undefined;\nlet _permanentError: Error | undefined;\n\nasync function resolveState(): Promise<ResolvedState> {\n if (_permanentError !== undefined) {\n throw _permanentError;\n }\n if (!_resolvePromise) {\n _resolvePromise = _buildState().catch((err) => {\n _permanentError = err instanceof Error ? err : new Error(String(err));\n _resolvePromise = undefined;\n throw _permanentError;\n });\n }\n return _resolvePromise;\n}\n\n/** @internal — test use only. Resets the module-level lazy cache. */\nexport function _testResetUnitsCache(): void {\n _resolvePromise = undefined;\n _permanentError = undefined;\n}\n\nasync function _buildState(): Promise<ResolvedState> {\n const { default: schema } = await import(\"./assets/Units.json\");\n\n const nameMap = new Map<string, IndexedUnit>();\n const labelMap = new Map<string, IndexedUnit[]>();\n const phenomenonMap = new Map<string, IndexedUnit[]>();\n const invertedUnits = new Map<string, InvertedEntry>();\n\n const s = schema as SerializedUnitSchema;\n const resolver = new UnitDefinitionResolver(s);\n const resolved = resolver.resolveAll();\n\n for (const [name, entry] of resolved) {\n const item = s.items[name] as SerializedUnit;\n const phenomenon = item.phenomenon;\n const unitSystem = item.unitSystem;\n\n const fullName = `${s.name}.${name}`;\n const props: UnitProps = {\n name: fullName,\n label: entry.label,\n phenomenon,\n isValid: true,\n system: unitSystem,\n };\n\n const indexed: IndexedUnit = { props, resolved: entry };\n\n nameMap.set(fullName, indexed);\n const lowerLabel = entry.label.toLowerCase();\n const byLabel = labelMap.get(lowerLabel) ?? [];\n byLabel.push(indexed);\n labelMap.set(lowerLabel, byLabel);\n\n const byPhen = phenomenonMap.get(phenomenon) ?? [];\n byPhen.push(indexed);\n phenomenonMap.set(phenomenon, byPhen);\n }\n\n // Handle InvertedUnit items — must run after nameMap is fully populated above because\n // invertedSource lookup requires the inverted unit's target to already be in nameMap.\n for (const [name, item] of Object.entries(s.items)) {\n if (item.schemaItemType !== \"InvertedUnit\") {\n continue;\n }\n const inv: SerializedInvertedUnit = item;\n const fullName = `${s.name}.${name}`;\n const invertsName = qualifyItemName(inv.invertsUnit, s.name);\n const unitSystem = inv.unitSystem;\n\n const invertedSource = nameMap.get(invertsName);\n const phenomenon = invertedSource?.props.phenomenon ?? \"\";\n\n const props: UnitProps = {\n name: fullName,\n label: inv.label ?? name,\n phenomenon,\n isValid: true,\n system: unitSystem,\n };\n\n invertedUnits.set(fullName, { props, invertsUnitName: invertsName });\n\n if (invertedSource) {\n const indexed: IndexedUnit = {\n props,\n resolved: { ...invertedSource.resolved, name: fullName, label: props.label, unitSystem },\n };\n nameMap.set(fullName, indexed);\n\n const lowerLabel = props.label.toLowerCase();\n const byLabel = labelMap.get(lowerLabel) ?? [];\n byLabel.push(indexed);\n labelMap.set(lowerLabel, byLabel);\n\n const byPhen = phenomenonMap.get(phenomenon) ?? [];\n byPhen.push(indexed);\n phenomenonMap.set(phenomenon, byPhen);\n }\n }\n\n return { nameMap, labelMap, phenomenonMap, invertedUnits, schemaName: s.name };\n}\n\n/**\n * A `UnitsProvider` backed by the full BIS `Units.ecschema.json` bundled as a JSON asset.\n *\n * The ~90 KB bundled JSON is loaded lazily via dynamic `import()` on the first provider method\n * call and cached at module scope — construction is essentially free, and multiple instances\n * share the same immutable lookup indexes.\n *\n * This is the zero-dependency default for backends, tools, and any frontend that doesn't need\n * iModel overrides. Equivalent to calling `createUnitsProvider()` with no arguments.\n *\n * @see createUnitsProvider for layering schema-defined units on top of basic BIS units.\n * @beta\n */\nexport class BasicUnitsProvider implements UnitsProvider {\n\n // ── UnitsProvider implementation ─────────────────────────────────────\n\n /** Find a unit by its display label, optionally filtering by schema name, phenomenon, and unit system.\n * @param unitLabel - The display label to search for (case-insensitive).\n * @param schemaName - Optional schema name filter. Returns `BadUnit` if provided and not `\"Units\"`.\n * @param phenomenon - Optional phenomenon filter (e.g. `\"Units.LENGTH\"`).\n * @param unitSystem - Optional unit system filter (e.g. `\"Units.METRIC\"`).\n * @returns The matching `UnitProps`, or a `BadUnit` if no match is found.\n */\n public async findUnit(unitLabel: string, schemaName?: string, phenomenon?: string, unitSystem?: string): Promise<UnitProps> {\n const state = await resolveState();\n if (schemaName && schemaName !== state.schemaName) {\n return new BadUnit();\n }\n const candidates = state.labelMap.get(unitLabel.toLowerCase());\n if (!candidates || candidates.length === 0) {\n return new BadUnit();\n }\n\n for (const c of candidates) {\n if (phenomenon && c.props.phenomenon !== phenomenon) {\n continue;\n }\n if (unitSystem && c.props.system !== unitSystem) {\n continue;\n }\n return c.props;\n }\n\n return new BadUnit();\n }\n\n /** Return all units belonging to the given phenomenon (unit family).\n * @param phenomenon - The phenomenon full name (e.g. `\"Units.LENGTH\"`).\n * @returns An array of matching `UnitProps`, or an empty array if none.\n */\n public async getUnitsByFamily(phenomenon: string): Promise<UnitProps[]> {\n const state = await resolveState();\n const entries = state.phenomenonMap.get(phenomenon);\n return entries ? entries.map((e) => e.props) : [];\n }\n\n /** Find a unit by its fully-qualified name (e.g. `\"Units.M\"`).\n * @param unitName - The qualified unit name.\n * @returns The matching `UnitProps`, or a `BadUnit` if not found.\n */\n public async findUnitByName(unitName: string): Promise<UnitProps> {\n const state = await resolveState();\n const entry = state.nameMap.get(unitName);\n return entry ? entry.props : new BadUnit();\n }\n\n /** Compute the conversion factors from `fromUnit` to `toUnit`.\n * Handles normal units, inverted units, and mixed (inverted ↔ non-inverted) conversions.\n * @param fromUnit - The source unit.\n * @param toUnit - The target unit.\n * @returns A `UnitConversionProps` with `factor`, `offset`, and optionally `inversion` and `error`.\n */\n public async getConversion(fromUnit: UnitProps, toUnit: UnitProps): Promise<UnitConversionProps> {\n const state = await resolveState();\n const from = state.nameMap.get(fromUnit.name);\n const to = state.nameMap.get(toUnit.name);\n\n if (!from || !to) {\n return { factor: 1.0, offset: 0.0, error: true };\n }\n\n const fromInverted = state.invertedUnits.get(fromUnit.name);\n const toInverted = state.invertedUnits.get(toUnit.name);\n\n const fromPhenomenon = fromInverted\n ? state.nameMap.get(fromInverted.invertsUnitName)?.props.phenomenon\n : from.props.phenomenon;\n const toPhenomenon = toInverted\n ? state.nameMap.get(toInverted.invertsUnitName)?.props.phenomenon\n : to.props.phenomenon;\n if (fromPhenomenon !== toPhenomenon) {\n return { factor: 1.0, offset: 0.0, error: true };\n }\n\n if (fromInverted && toInverted) {\n const innerFrom = state.nameMap.get(fromInverted.invertsUnitName);\n const innerTo = state.nameMap.get(toInverted.invertsUnitName);\n if (innerFrom && innerTo) {\n const c = innerFrom.resolved.conversion.inverse().compose(innerTo.resolved.conversion);\n return { factor: c.factor, offset: c.offset };\n }\n }\n\n if (fromInverted) {\n const innerFrom = state.nameMap.get(fromInverted.invertsUnitName);\n if (innerFrom) {\n const c = innerFrom.resolved.conversion.inverse().compose(to.resolved.conversion);\n return { factor: c.factor, offset: c.offset, inversion: UnitConversionInvert.InvertPreConversion };\n }\n }\n\n if (toInverted) {\n const innerTo = state.nameMap.get(toInverted.invertsUnitName);\n if (innerTo) {\n const c = from.resolved.conversion.inverse().compose(innerTo.resolved.conversion);\n return { factor: c.factor, offset: c.offset, inversion: UnitConversionInvert.InvertPostConversion };\n }\n }\n\n const conv = from.resolved.conversion.inverse().compose(to.resolved.conversion);\n return { factor: conv.factor, offset: conv.offset };\n }\n}\n"]}
@@ -0,0 +1,45 @@
1
+ import type { UnitsProvider } from "./Interfaces";
2
+ /**
3
+ * Options for [[createUnitsProvider]].
4
+ * @beta
5
+ */
6
+ export interface CreateUnitsProviderOptions {
7
+ /**
8
+ * A `UnitsProvider` consulted before the basic BIS units (e.g. a `SchemaUnitProvider`
9
+ * for an open iModel's `SchemaContext`). When omitted, the returned provider behaves
10
+ * exactly like `new BasicUnitsProvider()`.
11
+ */
12
+ primary?: UnitsProvider;
13
+ /**
14
+ * Controls which provider is consulted first and wins ties.
15
+ * - `"preferSchema"` (default): `primary` is authoritative; bundled BIS units are fallback.
16
+ * - `"preferBundled"`: bundled BIS units win; `primary` is consulted only for units not in
17
+ * the bundled set. Use when the iModel's schema may be stale.
18
+ *
19
+ * Affects `findUnit`, `findUnitByName`, and `getConversion` (first-consulted wins or
20
+ * falls through). `getUnitsByFamily` always merges both providers — the first-consulted
21
+ * provider wins name collisions.
22
+ *
23
+ * Has no effect when `primary` is omitted — the returned provider is a plain `BasicUnitsProvider`.
24
+ */
25
+ bisUnitsPolicy?: "preferSchema" | "preferBundled";
26
+ }
27
+ /**
28
+ * Returns a `UnitsProvider` that layers the basic BIS units under (or over) an optional
29
+ * `primary` provider. Typical use: layer an iModel's schema units on top of the bundled
30
+ * defaults from `@itwin/core-quantity`.
31
+ *
32
+ * Precedence rules:
33
+ * - When `primary` is supplied and `bisUnitsPolicy` is `"preferSchema"` (the default): `primary` wins;
34
+ * basic BIS units fill any gaps where `primary` returns an invalid unit or throws.
35
+ * - When `bisUnitsPolicy` is `"preferBundled"`: basic BIS units win; `primary` is consulted only when the
36
+ * basic provider can't answer.
37
+ * - `getUnitsByFamily` always merges results from both providers, deduplicated by
38
+ * `UnitProps.name` (fully-qualified). The first-consulted provider wins ties.
39
+ * - When no `primary` is supplied, the returned provider is exactly `new BasicUnitsProvider()`
40
+ * (no wrapper), preserving `instanceof` checks and keeping the hot path fast.
41
+ *
42
+ * @beta
43
+ */
44
+ export declare function createUnitsProvider(options?: CreateUnitsProviderOptions): UnitsProvider;
45
+ //# sourceMappingURL=CompositeUnitsProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CompositeUnitsProvider.d.ts","sourceRoot":"","sources":["../../src/CompositeUnitsProvider.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAkC,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlF;;;GAGG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;;OAIG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC;IAExB;;;;;;;;;;;OAWG;IACH,cAAc,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC;CACnD;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,0BAA+B,GAAG,aAAa,CAY3F"}
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createUnitsProvider = createUnitsProvider;
4
+ /*---------------------------------------------------------------------------------------------
5
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
6
+ * See LICENSE.md in the project root for license terms and full copyright notice.
7
+ *--------------------------------------------------------------------------------------------*/
8
+ const BasicUnitsProvider_1 = require("./BasicUnitsProvider");
9
+ const Unit_1 = require("./Unit");
10
+ /**
11
+ * Returns a `UnitsProvider` that layers the basic BIS units under (or over) an optional
12
+ * `primary` provider. Typical use: layer an iModel's schema units on top of the bundled
13
+ * defaults from `@itwin/core-quantity`.
14
+ *
15
+ * Precedence rules:
16
+ * - When `primary` is supplied and `bisUnitsPolicy` is `"preferSchema"` (the default): `primary` wins;
17
+ * basic BIS units fill any gaps where `primary` returns an invalid unit or throws.
18
+ * - When `bisUnitsPolicy` is `"preferBundled"`: basic BIS units win; `primary` is consulted only when the
19
+ * basic provider can't answer.
20
+ * - `getUnitsByFamily` always merges results from both providers, deduplicated by
21
+ * `UnitProps.name` (fully-qualified). The first-consulted provider wins ties.
22
+ * - When no `primary` is supplied, the returned provider is exactly `new BasicUnitsProvider()`
23
+ * (no wrapper), preserving `instanceof` checks and keeping the hot path fast.
24
+ *
25
+ * @beta
26
+ */
27
+ function createUnitsProvider(options = {}) {
28
+ const basic = new BasicUnitsProvider_1.BasicUnitsProvider();
29
+ const primary = options.primary;
30
+ // NOTE: returns BasicUnitsProvider directly when no primary is provided.
31
+ // QuantityFormatter.resetToUseInternalUnitsProvider uses instanceof BasicUnitsProvider to detect this.
32
+ // If this fast-path is ever wrapped (e.g. for telemetry), that guard must be updated.
33
+ if (!primary) {
34
+ return basic;
35
+ }
36
+ const providers = options.bisUnitsPolicy === "preferBundled" ? [basic, primary] : [primary, basic];
37
+ return new CompositeUnitsProvider(providers);
38
+ }
39
+ class CompositeUnitsProvider {
40
+ _providers;
41
+ constructor(_providers) {
42
+ this._providers = _providers;
43
+ }
44
+ async findUnit(label, schemaName, phenomenon, unitSystem) {
45
+ for (let i = 0; i < this._providers.length - 1; i++) {
46
+ const hit = await tryFind(async () => this._providers[i].findUnit(label, schemaName, phenomenon, unitSystem));
47
+ if (hit?.isValid) {
48
+ return hit;
49
+ }
50
+ }
51
+ return tryFind(async () => this._providers[this._providers.length - 1].findUnit(label, schemaName, phenomenon, unitSystem)).then((hit) => hit ?? new Unit_1.BadUnit());
52
+ }
53
+ async findUnitByName(name) {
54
+ for (let i = 0; i < this._providers.length - 1; i++) {
55
+ const hit = await tryFind(async () => this._providers[i].findUnitByName(name));
56
+ if (hit?.isValid) {
57
+ return hit;
58
+ }
59
+ }
60
+ return tryFind(async () => this._providers[this._providers.length - 1].findUnitByName(name)).then((hit) => hit ?? new Unit_1.BadUnit());
61
+ }
62
+ async getUnitsByFamily(phenomenon) {
63
+ const seen = new Set();
64
+ const out = [];
65
+ // Query all providers in parallel; process results in declaration order to honour precedence.
66
+ const results = await Promise.all(this._providers.map(async (p) => tryList(async () => p.getUnitsByFamily(phenomenon))));
67
+ for (const units of results) {
68
+ for (const u of units) {
69
+ if (!seen.has(u.name)) {
70
+ seen.add(u.name);
71
+ out.push(u);
72
+ }
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ async getConversion(from, to) {
78
+ for (let i = 0; i < this._providers.length - 1; i++) {
79
+ try {
80
+ const result = await this._providers[i].getConversion(from, to);
81
+ if (!result.error) {
82
+ return result;
83
+ }
84
+ }
85
+ catch { /* fall through to next provider */ }
86
+ }
87
+ try {
88
+ return await this._providers[this._providers.length - 1].getConversion(from, to);
89
+ }
90
+ catch {
91
+ return { factor: 1.0, offset: 0.0, error: true };
92
+ }
93
+ }
94
+ }
95
+ async function tryFind(fn) {
96
+ try {
97
+ return await fn();
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ }
103
+ async function tryList(fn) {
104
+ try {
105
+ return await fn();
106
+ }
107
+ catch {
108
+ return [];
109
+ }
110
+ }
111
+ //# sourceMappingURL=CompositeUnitsProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CompositeUnitsProvider.js","sourceRoot":"","sources":["../../src/CompositeUnitsProvider.ts"],"names":[],"mappings":";;AAoDA,kDAYC;AAhED;;;+FAG+F;AAC/F,6DAA0D;AAE1D,iCAAiC;AA6BjC;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,mBAAmB,CAAC,UAAsC,EAAE;IAC1E,MAAM,KAAK,GAAG,IAAI,uCAAkB,EAAE,CAAC;IACvC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAChC,yEAAyE;IACzE,uGAAuG;IACvG,sFAAsF;IACt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AAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;IAEM,KAAK,CAAC,aAAa,CAAC,IAAe,EAAE,EAAa;QACvD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YACpD,IAAI,CAAC;gBACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;gBAChE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;oBAClB,OAAO,MAAM,CAAC;gBAChB,CAAC;YACH,CAAC;YAAC,MAAM,CAAC,CAAC,mCAAmC,CAAC,CAAC;QACjD,CAAC;QACD,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACnF,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QACnD,CAAC;IACH,CAAC;CACF;AAED,KAAK,UAAU,OAAO,CAAC,EAA4B;IACjD,IAAI,CAAC;QAAC,OAAO,MAAM,EAAE,EAAE,CAAC;IAAC,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,SAAS,CAAC;IAAC,CAAC;AACxD,CAAC;AAED,KAAK,UAAU,OAAO,CAAC,EAA8B;IACnD,IAAI,CAAC;QAAC,OAAO,MAAM,EAAE,EAAE,CAAC;IAAC,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,EAAE,CAAC;IAAC,CAAC;AACjD,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\nimport { BasicUnitsProvider } from \"./BasicUnitsProvider\";\nimport type { UnitConversionProps, UnitProps, UnitsProvider } from \"./Interfaces\";\nimport { BadUnit } from \"./Unit\";\n\n/**\n * Options for [[createUnitsProvider]].\n * @beta\n */\nexport interface CreateUnitsProviderOptions {\n /**\n * A `UnitsProvider` consulted before the basic BIS units (e.g. a `SchemaUnitProvider`\n * for an open iModel's `SchemaContext`). When omitted, the returned provider behaves\n * exactly like `new BasicUnitsProvider()`.\n */\n primary?: UnitsProvider;\n\n /**\n * Controls which provider is consulted first and wins ties.\n * - `\"preferSchema\"` (default): `primary` is authoritative; bundled BIS units are fallback.\n * - `\"preferBundled\"`: bundled BIS units win; `primary` is consulted only for units not in\n * the bundled set. Use when the iModel's schema may be stale.\n *\n * Affects `findUnit`, `findUnitByName`, and `getConversion` (first-consulted wins or\n * falls through). `getUnitsByFamily` always merges both providers — the first-consulted\n * provider wins name collisions.\n *\n * Has no effect when `primary` is omitted — the returned provider is a plain `BasicUnitsProvider`.\n */\n bisUnitsPolicy?: \"preferSchema\" | \"preferBundled\";\n}\n\n/**\n * Returns a `UnitsProvider` that layers the basic BIS units under (or over) an optional\n * `primary` provider. Typical use: layer an iModel's schema units on top of the bundled\n * defaults from `@itwin/core-quantity`.\n *\n * Precedence rules:\n * - When `primary` is supplied and `bisUnitsPolicy` is `\"preferSchema\"` (the default): `primary` wins;\n * basic BIS units fill any gaps where `primary` returns an invalid unit or throws.\n * - When `bisUnitsPolicy` is `\"preferBundled\"`: basic BIS units win; `primary` is consulted only when the\n * basic provider can't answer.\n * - `getUnitsByFamily` always merges results from both providers, deduplicated by\n * `UnitProps.name` (fully-qualified). The first-consulted provider wins ties.\n * - When no `primary` is supplied, the returned provider is exactly `new BasicUnitsProvider()`\n * (no wrapper), preserving `instanceof` checks and keeping the hot path fast.\n *\n * @beta\n */\nexport function createUnitsProvider(options: CreateUnitsProviderOptions = {}): UnitsProvider {\n const basic = new BasicUnitsProvider();\n const primary = options.primary;\n // NOTE: returns BasicUnitsProvider directly when no primary is provided.\n // QuantityFormatter.resetToUseInternalUnitsProvider uses instanceof BasicUnitsProvider to detect this.\n // If this fast-path is ever wrapped (e.g. for telemetry), that guard must be updated.\n if (!primary) {\n return basic;\n }\n\n const providers = options.bisUnitsPolicy === \"preferBundled\" ? [basic, primary] : [primary, basic];\n return new CompositeUnitsProvider(providers);\n}\n\nclass CompositeUnitsProvider implements UnitsProvider {\n constructor(private readonly _providers: UnitsProvider[]) {}\n\n public async findUnit(label: string, schemaName?: string, phenomenon?: string, unitSystem?: string): Promise<UnitProps> {\n for (let i = 0; i < this._providers.length - 1; i++) {\n const hit = await tryFind(async () => this._providers[i].findUnit(label, schemaName, phenomenon, unitSystem));\n if (hit?.isValid) {\n return hit;\n }\n }\n return tryFind(async () => this._providers[this._providers.length - 1].findUnit(label, schemaName, phenomenon, unitSystem)).then((hit) => hit ?? new BadUnit());\n }\n\n public async findUnitByName(name: string): Promise<UnitProps> {\n for (let i = 0; i < this._providers.length - 1; i++) {\n const hit = await tryFind(async () => this._providers[i].findUnitByName(name));\n if (hit?.isValid) {\n return hit;\n }\n }\n return tryFind(async () => this._providers[this._providers.length - 1].findUnitByName(name)).then((hit) => hit ?? new BadUnit());\n }\n\n public async getUnitsByFamily(phenomenon: string): Promise<UnitProps[]> {\n const seen = new Set<string>();\n const out: UnitProps[] = [];\n // Query all providers in parallel; process results in declaration order to honour precedence.\n const results = await Promise.all(this._providers.map(async (p) => tryList(async () => p.getUnitsByFamily(phenomenon))));\n for (const units of results) {\n for (const u of units) {\n if (!seen.has(u.name)) {\n seen.add(u.name);\n out.push(u);\n }\n }\n }\n return out;\n }\n\n public async getConversion(from: UnitProps, to: UnitProps): Promise<UnitConversionProps> {\n for (let i = 0; i < this._providers.length - 1; i++) {\n try {\n const result = await this._providers[i].getConversion(from, to);\n if (!result.error) {\n return result;\n }\n } catch { /* fall through to next provider */ }\n }\n try {\n return await this._providers[this._providers.length - 1].getConversion(from, to);\n } catch {\n return { factor: 1.0, offset: 0.0, error: true };\n }\n }\n}\n\nasync function tryFind(fn: () => Promise<UnitProps>): Promise<UnitProps | undefined> {\n try { return await fn(); } catch { return undefined; }\n}\n\nasync function tryList(fn: () => Promise<UnitProps[]>): Promise<UnitProps[]> {\n try { return await fn(); } catch { return []; }\n}\n"]}
@@ -0,0 +1,56 @@
1
+ /** @packageDocumentation
2
+ * @module Quantity
3
+ */
4
+ import type { FormatterSpec } from "./Formatter/FormatterSpec";
5
+ import type { FormattingSpecArgs, FormattingSpecProvider } from "./Formatter/Interfaces";
6
+ import type { ParserSpec } from "./ParserSpec";
7
+ import type { UnitSystemKey } from "./Interfaces";
8
+ /** Arguments for constructing a [[FormatSpecHandle]].
9
+ * @internal
10
+ */
11
+ export interface FormatSpecHandleArgs extends FormattingSpecArgs {
12
+ /** The provider that supplies spec lookups and reload events. */
13
+ provider: FormattingSpecProvider;
14
+ }
15
+ /** A cacheable handle to formatting and parsing specs for a specific KoQ and persistence unit.
16
+ * Automatically refreshes when the QuantityFormatter reloads. Use [[QuantityFormatter.getFormatSpecHandle]]
17
+ * to create instances.
18
+ *
19
+ * When formatting is not yet ready, [[format]] returns a `value.toString()` fallback.
20
+ * Call [[dispose]] when the handle is no longer needed to unsubscribe from reload events.
21
+ *
22
+ * @beta
23
+ */
24
+ export declare class FormatSpecHandle implements Disposable {
25
+ private _formatterSpec;
26
+ private _parserSpec;
27
+ private _removeListener;
28
+ private readonly _provider;
29
+ private readonly _koqName;
30
+ private readonly _persistenceUnit;
31
+ private readonly _system;
32
+ /** @internal */
33
+ constructor(args: FormatSpecHandleArgs);
34
+ /** The KoQ name this handle is keyed to. */
35
+ get koqName(): string;
36
+ /** The persistence unit this handle is keyed to. */
37
+ get persistenceUnit(): string;
38
+ /** The unit system this handle is pinned to, or `undefined` for the active system. */
39
+ get system(): UnitSystemKey | undefined;
40
+ /** The current FormatterSpec, or undefined if not yet loaded. */
41
+ get formatterSpec(): FormatterSpec | undefined;
42
+ /** The current ParserSpec, or undefined if not yet loaded. */
43
+ get parserSpec(): ParserSpec | undefined;
44
+ /** Format a quantity value using the current spec.
45
+ * If the formatter is not yet ready, returns `value.toString()` as a fallback.
46
+ * @param value - The numeric value to format.
47
+ * @returns The formatted string.
48
+ */
49
+ format(value: number): string;
50
+ /** Unsubscribe from reload events and clear cached specs.
51
+ * Idempotent and safe to call during a pending reload.
52
+ */
53
+ [Symbol.dispose](): void;
54
+ private _refresh;
55
+ }
56
+ //# sourceMappingURL=FormatSpecHandle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FormatSpecHandle.d.ts","sourceRoot":"","sources":["../../src/FormatSpecHandle.ts"],"names":[],"mappings":"AAKA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,kBAAkB,EAAuB,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAC9G,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,oBAAqB,SAAQ,kBAAkB;IAC9D,iEAAiE;IACjE,QAAQ,EAAE,sBAAsB,CAAC;CAClC;AAED;;;;;;;;GAQG;AACH,qBAAa,gBAAiB,YAAW,UAAU;IACjD,OAAO,CAAC,cAAc,CAA4B;IAClD,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,eAAe,CAA2B;IAClD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyB;IACnD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;IAC1C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA4B;IAEpD,gBAAgB;gBACJ,IAAI,EAAE,oBAAoB;IAWtC,4CAA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