@enyo-energy/energy-app-sdk 1.43.0 → 1.45.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 (70) hide show
  1. package/README.md +176 -3
  2. package/dist/cjs/energy-app-package-definition.d.cts +46 -1
  3. package/dist/cjs/energy-app-permission.type.cjs +2 -0
  4. package/dist/cjs/energy-app-permission.type.d.cts +3 -1
  5. package/dist/cjs/energy-app.cjs +26 -0
  6. package/dist/cjs/energy-app.d.cts +24 -0
  7. package/dist/cjs/enyo-energy-app-sdk.d.cts +6 -0
  8. package/dist/cjs/implementations/heatpump/heatpump-curve-optimization-rooms.cjs +96 -0
  9. package/dist/cjs/implementations/heatpump/heatpump-curve-optimization-rooms.d.cts +65 -0
  10. package/dist/cjs/implementations/heatpump/heatpump-metadata-validators.cjs +77 -19
  11. package/dist/cjs/implementations/heatpump/heatpump-metadata-validators.d.cts +4 -2
  12. package/dist/cjs/implementations/subscriptions/define-subscription-plan.cjs +48 -0
  13. package/dist/cjs/implementations/subscriptions/define-subscription-plan.d.cts +40 -0
  14. package/dist/cjs/implementations/subscriptions/subscription-offer-validators.cjs +301 -0
  15. package/dist/cjs/implementations/subscriptions/subscription-offer-validators.d.cts +54 -0
  16. package/dist/cjs/implementations/subscriptions/subscription-plan-validators.cjs +8 -0
  17. package/dist/cjs/implementations/subscriptions/subscription-plan-validators.d.cts +8 -3
  18. package/dist/cjs/index.cjs +7 -0
  19. package/dist/cjs/index.d.cts +7 -0
  20. package/dist/cjs/packages/energy-app-room-temperatures.cjs +2 -0
  21. package/dist/cjs/packages/energy-app-room-temperatures.d.cts +51 -0
  22. package/dist/cjs/packages/energy-app-room.cjs +2 -0
  23. package/dist/cjs/packages/energy-app-room.d.cts +59 -0
  24. package/dist/cjs/types/enyo-authentication.d.cts +11 -0
  25. package/dist/cjs/types/enyo-heatpump-appliance.cjs +35 -2
  26. package/dist/cjs/types/enyo-heatpump-appliance.d.cts +98 -39
  27. package/dist/cjs/types/enyo-room-temperature.cjs +2 -0
  28. package/dist/cjs/types/enyo-room-temperature.d.cts +102 -0
  29. package/dist/cjs/types/enyo-room.cjs +37 -0
  30. package/dist/cjs/types/enyo-room.d.cts +60 -0
  31. package/dist/cjs/types/enyo-settings.d.cts +22 -1
  32. package/dist/cjs/types/enyo-subscription-offer.cjs +113 -0
  33. package/dist/cjs/types/enyo-subscription-offer.d.cts +358 -0
  34. package/dist/cjs/version.cjs +1 -1
  35. package/dist/cjs/version.d.cts +1 -1
  36. package/dist/energy-app-package-definition.d.ts +46 -1
  37. package/dist/energy-app-permission.type.d.ts +3 -1
  38. package/dist/energy-app-permission.type.js +2 -0
  39. package/dist/energy-app.d.ts +24 -0
  40. package/dist/energy-app.js +26 -0
  41. package/dist/enyo-energy-app-sdk.d.ts +6 -0
  42. package/dist/implementations/heatpump/heatpump-curve-optimization-rooms.d.ts +65 -0
  43. package/dist/implementations/heatpump/heatpump-curve-optimization-rooms.js +89 -0
  44. package/dist/implementations/heatpump/heatpump-metadata-validators.d.ts +4 -2
  45. package/dist/implementations/heatpump/heatpump-metadata-validators.js +78 -20
  46. package/dist/implementations/subscriptions/define-subscription-plan.d.ts +40 -0
  47. package/dist/implementations/subscriptions/define-subscription-plan.js +45 -0
  48. package/dist/implementations/subscriptions/subscription-offer-validators.d.ts +54 -0
  49. package/dist/implementations/subscriptions/subscription-offer-validators.js +298 -0
  50. package/dist/implementations/subscriptions/subscription-plan-validators.d.ts +8 -3
  51. package/dist/implementations/subscriptions/subscription-plan-validators.js +8 -0
  52. package/dist/index.d.ts +7 -0
  53. package/dist/index.js +7 -0
  54. package/dist/packages/energy-app-room-temperatures.d.ts +51 -0
  55. package/dist/packages/energy-app-room-temperatures.js +1 -0
  56. package/dist/packages/energy-app-room.d.ts +59 -0
  57. package/dist/packages/energy-app-room.js +1 -0
  58. package/dist/types/enyo-authentication.d.ts +11 -0
  59. package/dist/types/enyo-heatpump-appliance.d.ts +98 -39
  60. package/dist/types/enyo-heatpump-appliance.js +34 -1
  61. package/dist/types/enyo-room-temperature.d.ts +102 -0
  62. package/dist/types/enyo-room-temperature.js +1 -0
  63. package/dist/types/enyo-room.d.ts +60 -0
  64. package/dist/types/enyo-room.js +34 -0
  65. package/dist/types/enyo-settings.d.ts +22 -1
  66. package/dist/types/enyo-subscription-offer.d.ts +358 -0
  67. package/dist/types/enyo-subscription-offer.js +110 -0
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/package.json +1 -1
@@ -3,7 +3,8 @@
3
3
  * Client-side validation for the advanced heatpump metadata an integration
4
4
  * publishes: heating curves ({@link EnyoHeatpumpApplianceHeatingCurve}), time
5
5
  * programs ({@link EnyoHeatpumpTimeProgram}), the room-temperature wiring of
6
- * heating circuits and the program-switch modes of circuits and DHW zones.
6
+ * heating circuits, the program-switch modes of circuits and DHW zones, and
7
+ * the SG Ready relays ({@link EnyoHeatpumpApplianceSgReadyRelay}).
7
8
  *
8
9
  * None of these shapes can be checked at the type level — a curve with one
9
10
  * point, an unsorted curve, `'25:00'` as a switching time or a period on day
@@ -47,6 +48,8 @@ const TIME_OF_DAY = /^([01]\d|2[0-3]):([0-5]\d)$/;
47
48
  const LEVELS = new Set(Object.values(enyo_heatpump_appliance_js_1.EnyoHeatpumpTimeProgramLevelEnum));
48
49
  const PROGRAM_MODES = new Set(Object.values(enyo_heatpump_appliance_js_1.EnyoHeatpumpProgramModeEnum));
49
50
  const OVERRIDE_PROGRAM_MODES = new Set([enyo_heatpump_appliance_js_1.EnyoHeatpumpProgramModeEnum.Comfort, enyo_heatpump_appliance_js_1.EnyoHeatpumpProgramModeEnum.Eco]);
51
+ const SG_READY_FUNCTIONS = new Set(Object.values(enyo_heatpump_appliance_js_1.EnyoHeatpumpSgReadyFunctionEnum));
52
+ const SG_READY_STATES = new Set(Object.values(enyo_heatpump_appliance_js_1.EnyoHeatpumpSgReadyStateEnum));
50
53
  /**
51
54
  * Validates the program-switch fields of one heating circuit or DHW zone
52
55
  * (`supportedProgramModes`, `programModeTemperaturesC`, `activeProgramMode`)
@@ -80,17 +83,13 @@ function checkProgramModes(zone, prefix, errors, warnings) {
80
83
  errors.push(`${prefix}: activeProgramMode "${zone.activeProgramMode}" is not a valid value`);
81
84
  }
82
85
  }
83
- /** Range the customer may choose for a room's `targetRoomTemperatureC`, in °C. */
84
- const CURVE_OPTIMIZATION_TARGET_RANGE_C = { min: 16, max: 26 };
85
86
  /**
86
87
  * Validates the heating-curve-offset fields of one heating circuit
87
88
  * (`heatingCurveOffsetRangeK`, `activeHeatingCurveOffsetK`,
88
89
  * `curveOptimization`) and appends the problems to `errors`.
89
90
  *
90
91
  * Errors: the range is not finite or does not contain `0`; the active offset
91
- * is not finite or lies outside the range; a room id is empty; a resolved room
92
- * lacks its `roomId`, a sensor lacks its `applianceId` / `sensorId`, or its
93
- * target lies outside 16…26 °C.
92
+ * is not finite or lies outside the range; a room id is empty.
94
93
  *
95
94
  * @param circuit - The heating circuit.
96
95
  * @param prefix - Path prefix for the messages, e.g. `heatingCircuits[index=0]`.
@@ -124,22 +123,79 @@ function checkHeatingCurveOffset(circuit, prefix, errors) {
124
123
  errors.push(`${prefix}: curveOptimization.roomIds[${i}] must be a non-empty string`);
125
124
  }
126
125
  });
127
- (settings.rooms ?? []).forEach((room, i) => {
128
- if (!room?.roomId) {
129
- errors.push(`${prefix}: curveOptimization.rooms[${i}] needs a roomId`);
126
+ }
127
+ /**
128
+ * Validates the SG Ready relays of a heatpump and appends the problems to
129
+ * `errors` / `warnings`.
130
+ *
131
+ * Errors: duplicate relay `index`, an unknown `function`, an unknown or empty
132
+ * `supportedStates`, an unknown `activeState` or one outside
133
+ * `supportedStates`.
134
+ *
135
+ * Warnings: a `zoneIndex` naming no declared heating circuit / DHW zone, two
136
+ * relays with the same function on the same zone, `supportedStates` without
137
+ * `Normal` or with duplicates, a `dhw-heating-rod` relay while the
138
+ * installation does not list a heating rod in `additionalDevices`.
139
+ *
140
+ * @param relays - The declared SG Ready relays.
141
+ * @param metadata - The heatpump metadata, for zones and additional devices.
142
+ * @param errors - Receives blocking problems.
143
+ * @param warnings - Receives advisory problems.
144
+ */
145
+ function checkSgReadyRelays(relays, metadata, errors, warnings) {
146
+ const indexes = relays.map(relay => relay.index);
147
+ const duplicates = indexes.filter((index, i) => indexes.indexOf(index) !== i);
148
+ if (duplicates.length > 0) {
149
+ errors.push(`sgReadyRelays contains duplicate index ${[...new Set(duplicates)].join(', ')}`);
150
+ }
151
+ const targets = new Set();
152
+ for (const relay of relays) {
153
+ const prefix = `sgReadyRelays[index=${relay.index}]`;
154
+ if (!SG_READY_FUNCTIONS.has(relay.function)) {
155
+ errors.push(`${prefix}: function "${relay.function}" is not a valid value`);
156
+ continue;
157
+ }
158
+ const isHeating = relay.function === enyo_heatpump_appliance_js_1.EnyoHeatpumpSgReadyFunctionEnum.Heating;
159
+ const zones = isHeating ? metadata.heatingCircuits : metadata.domesticHotWater;
160
+ const zoneField = isHeating ? 'heatingCircuits' : 'domesticHotWater';
161
+ const zoneIndex = relay.zoneIndex ?? zones?.[0]?.index ?? 0;
162
+ if (relay.zoneIndex !== undefined && zones?.length && !zones.some(zone => zone.index === relay.zoneIndex)) {
163
+ warnings.push(`${prefix}: zoneIndex ${relay.zoneIndex} is not an index of ${zoneField}`);
164
+ }
165
+ const target = `${relay.function}@${zoneIndex}`;
166
+ if (targets.has(target)) {
167
+ warnings.push(`${prefix}: another relay already has function ${relay.function} on zone ${zoneIndex}`);
168
+ }
169
+ targets.add(target);
170
+ if (relay.function === enyo_heatpump_appliance_js_1.EnyoHeatpumpSgReadyFunctionEnum.DhwHeatingRod
171
+ && !(metadata.additionalDevices ?? []).includes(enyo_heatpump_appliance_js_1.EnyoHeatpumpApplianceAdditionalDeviceEnum.HeatingRod)) {
172
+ warnings.push(`${prefix}: function dhw-heating-rod is declared but additionalDevices does not list a HeatingRod`);
173
+ }
174
+ const supported = relay.supportedStates;
175
+ if (supported !== undefined) {
176
+ if (supported.length === 0) {
177
+ errors.push(`${prefix}: supportedStates must not be empty — omit it when all four states are wired`);
178
+ }
179
+ for (const state of supported) {
180
+ if (!SG_READY_STATES.has(state))
181
+ errors.push(`${prefix}: supportedStates contains unknown state "${state}"`);
182
+ }
183
+ if (new Set(supported).size !== supported.length) {
184
+ warnings.push(`${prefix}: supportedStates contains duplicate states`);
185
+ }
186
+ if (supported.length > 0 && !supported.includes(enyo_heatpump_appliance_js_1.EnyoHeatpumpSgReadyStateEnum.Normal)) {
187
+ warnings.push(`${prefix}: supportedStates does not include normal — the relay could never release the heatpump`);
188
+ }
130
189
  }
131
- (room?.sensors ?? []).forEach((sensor, j) => {
132
- if (!sensor?.applianceId || !sensor?.sensorId) {
133
- errors.push(`${prefix}: curveOptimization.rooms[${i}].sensors[${j}] needs applianceId and sensorId`);
190
+ if (relay.activeState !== undefined) {
191
+ if (!SG_READY_STATES.has(relay.activeState)) {
192
+ errors.push(`${prefix}: activeState "${relay.activeState}" is not a valid value`);
193
+ }
194
+ else if (supported !== undefined && !supported.includes(relay.activeState)) {
195
+ errors.push(`${prefix}: activeState ${relay.activeState} is not one of supportedStates`);
134
196
  }
135
- });
136
- const target = room?.targetRoomTemperatureC;
137
- if (!(isFiniteNumber(target)
138
- && target >= CURVE_OPTIMIZATION_TARGET_RANGE_C.min && target <= CURVE_OPTIMIZATION_TARGET_RANGE_C.max)) {
139
- errors.push(`${prefix}: curveOptimization.rooms[${i}].targetRoomTemperatureC must lie within ` +
140
- `${CURVE_OPTIMIZATION_TARGET_RANGE_C.min}…${CURVE_OPTIMIZATION_TARGET_RANGE_C.max} °C; got ${target}`);
141
197
  }
142
- });
198
+ }
143
199
  }
144
200
  /**
145
201
  * Parses an `HH:mm` time of day into minutes since midnight.
@@ -394,6 +450,7 @@ function assertValidHeatpumpTimeProgram(program) {
394
450
  * - Heating curve offset: errors from {@link checkHeatingCurveOffset}.
395
451
  * Warning: `HeatingCurveOffset` is declared but no circuit has a
396
452
  * `heatingCurveOffsetRangeK` — no offset other than `0` could be accepted.
453
+ * - SG Ready relays: errors and warnings from {@link checkSgReadyRelays}.
397
454
  *
398
455
  * @param metadata - The heatpump metadata to validate.
399
456
  * @returns The validation result.
@@ -496,5 +553,6 @@ function validateHeatpumpAdvancedMetadata(metadata) {
496
553
  merge(`domesticHotWater[index=${zone.index}].timeProgram`, validateHeatpumpTimeProgram(zone.timeProgram));
497
554
  }
498
555
  }
556
+ checkSgReadyRelays(metadata.sgReadyRelays ?? [], metadata, errors, warnings);
499
557
  return { ok: errors.length === 0, errors, warnings };
500
558
  }
@@ -2,7 +2,8 @@
2
2
  * Client-side validation for the advanced heatpump metadata an integration
3
3
  * publishes: heating curves ({@link EnyoHeatpumpApplianceHeatingCurve}), time
4
4
  * programs ({@link EnyoHeatpumpTimeProgram}), the room-temperature wiring of
5
- * heating circuits and the program-switch modes of circuits and DHW zones.
5
+ * heating circuits, the program-switch modes of circuits and DHW zones, and
6
+ * the SG Ready relays ({@link EnyoHeatpumpApplianceSgReadyRelay}).
6
7
  *
7
8
  * None of these shapes can be checked at the type level — a curve with one
8
9
  * point, an unsorted curve, `'25:00'` as a switching time or a period on day
@@ -116,8 +117,9 @@ export declare function assertValidHeatpumpTimeProgram(program: EnyoHeatpumpTime
116
117
  * - Heating curve offset: errors from {@link checkHeatingCurveOffset}.
117
118
  * Warning: `HeatingCurveOffset` is declared but no circuit has a
118
119
  * `heatingCurveOffsetRangeK` — no offset other than `0` could be accepted.
120
+ * - SG Ready relays: errors and warnings from {@link checkSgReadyRelays}.
119
121
  *
120
122
  * @param metadata - The heatpump metadata to validate.
121
123
  * @returns The validation result.
122
124
  */
123
- export declare function validateHeatpumpAdvancedMetadata(metadata: Pick<EnyoHeatpumpApplianceMetadata, 'availableFeatures' | 'heatingCircuits' | 'domesticHotWater' | 'building'>): HeatpumpMetadataValidationResult;
125
+ export declare function validateHeatpumpAdvancedMetadata(metadata: Pick<EnyoHeatpumpApplianceMetadata, 'availableFeatures' | 'heatingCircuits' | 'domesticHotWater' | 'building'> & Partial<Pick<EnyoHeatpumpApplianceMetadata, 'sgReadyRelays' | 'additionalDevices'>>): HeatpumpMetadataValidationResult;
@@ -20,6 +20,9 @@ exports.isSubscriptionActive = isSubscriptionActive;
20
20
  exports.isPlanActive = isPlanActive;
21
21
  exports.isSameSubscriptionUnit = isSameSubscriptionUnit;
22
22
  exports.isUnitActive = isUnitActive;
23
+ exports.defineSubscriptionFeature = defineSubscriptionFeature;
24
+ exports.defineSubscriptionOfferScreen = defineSubscriptionOfferScreen;
25
+ exports.getIncludedFeatureKey = getIncludedFeatureKey;
23
26
  const enyo_subscription_js_1 = require("../../types/enyo-subscription.cjs");
24
27
  /**
25
28
  * Subscription statuses in which the customer may use what a plan unlocks.
@@ -122,3 +125,48 @@ function isUnitActive(subscriptions, planKey, unit) {
122
125
  && isSubscriptionActive(subscription)
123
126
  && (subscription.units ?? []).some(paid => isSameSubscriptionUnit(paid, unit)));
124
127
  }
128
+ /**
129
+ * Identity helper that type-checks a feature of the package's feature catalog
130
+ * ({@link EnergyAppPackageDefinition.subscriptionFeatures}) where it is
131
+ * written.
132
+ *
133
+ * @param feature - The feature declaration.
134
+ * @returns The same feature, unchanged.
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * defineSubscriptionFeature({
139
+ * featureKey: 'price-optimisation',
140
+ * icon: EnyoSubscriptionOfferIconEnum.PiggyBank,
141
+ * storeEntry: [
142
+ * {language: 'en', title: 'Dynamic price optimisation'},
143
+ * {language: 'de', title: 'Optimierung nach dynamischen Preisen'}
144
+ * ]
145
+ * })
146
+ * ```
147
+ */
148
+ function defineSubscriptionFeature(feature) {
149
+ return feature;
150
+ }
151
+ /**
152
+ * Identity helper that type-checks the package's offer screen
153
+ * ({@link EnergyAppPackageDefinition.subscriptionOfferScreen}) where it is
154
+ * written.
155
+ *
156
+ * @param screen - The offer screen declaration.
157
+ * @returns The same offer screen, unchanged.
158
+ */
159
+ function defineSubscriptionOfferScreen(screen) {
160
+ return screen;
161
+ }
162
+ /**
163
+ * Returns the feature key of an included feature, whether it was declared as
164
+ * a plain key or with a value.
165
+ *
166
+ * @param feature - An entry of {@link EnergyAppPackageSubscriptionPlan.includedFeatures}
167
+ * or {@link EnyoSubscriptionFreeTier.includedFeatures}.
168
+ * @returns Its {@link EnyoSubscriptionFeature.featureKey}.
169
+ */
170
+ function getIncludedFeatureKey(feature) {
171
+ return typeof feature === 'string' ? feature : feature.featureKey;
172
+ }
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import type { EnergyAppPackageSubscriptionPlan } from '../../energy-app-package-definition.cjs';
16
16
  import { EnyoSubscription, EnyoSubscriptionStatus, EnyoSubscriptionUnit } from '../../types/enyo-subscription.cjs';
17
+ import type { EnyoSubscriptionFeature, EnyoSubscriptionIncludedFeature, EnyoSubscriptionOfferScreen } from '../../types/enyo-subscription-offer.cjs';
17
18
  /**
18
19
  * Subscription statuses in which the customer may use what a plan unlocks.
19
20
  *
@@ -98,3 +99,42 @@ export declare function isSameSubscriptionUnit(a: Pick<EnyoSubscriptionUnit, 'ty
98
99
  * ```
99
100
  */
100
101
  export declare function isUnitActive(subscriptions: EnyoSubscription[], planKey: string, unit: Pick<EnyoSubscriptionUnit, 'type' | 'referenceId'>): boolean;
102
+ /**
103
+ * Identity helper that type-checks a feature of the package's feature catalog
104
+ * ({@link EnergyAppPackageDefinition.subscriptionFeatures}) where it is
105
+ * written.
106
+ *
107
+ * @param feature - The feature declaration.
108
+ * @returns The same feature, unchanged.
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * defineSubscriptionFeature({
113
+ * featureKey: 'price-optimisation',
114
+ * icon: EnyoSubscriptionOfferIconEnum.PiggyBank,
115
+ * storeEntry: [
116
+ * {language: 'en', title: 'Dynamic price optimisation'},
117
+ * {language: 'de', title: 'Optimierung nach dynamischen Preisen'}
118
+ * ]
119
+ * })
120
+ * ```
121
+ */
122
+ export declare function defineSubscriptionFeature(feature: EnyoSubscriptionFeature): EnyoSubscriptionFeature;
123
+ /**
124
+ * Identity helper that type-checks the package's offer screen
125
+ * ({@link EnergyAppPackageDefinition.subscriptionOfferScreen}) where it is
126
+ * written.
127
+ *
128
+ * @param screen - The offer screen declaration.
129
+ * @returns The same offer screen, unchanged.
130
+ */
131
+ export declare function defineSubscriptionOfferScreen(screen: EnyoSubscriptionOfferScreen): EnyoSubscriptionOfferScreen;
132
+ /**
133
+ * Returns the feature key of an included feature, whether it was declared as
134
+ * a plain key or with a value.
135
+ *
136
+ * @param feature - An entry of {@link EnergyAppPackageSubscriptionPlan.includedFeatures}
137
+ * or {@link EnyoSubscriptionFreeTier.includedFeatures}.
138
+ * @returns Its {@link EnyoSubscriptionFeature.featureKey}.
139
+ */
140
+ export declare function getIncludedFeatureKey(feature: EnyoSubscriptionIncludedFeature): string;
@@ -0,0 +1,301 @@
1
+ "use strict";
2
+ /**
3
+ * Client-side validator for how a package promotes its subscription plans:
4
+ * the feature catalog ({@link EnergyAppPackageDefinition.subscriptionFeatures}),
5
+ * the free tier ({@link EnergyAppPackageDefinition.subscriptionFreeTier}), the
6
+ * offer screen blocks ({@link EnergyAppPackageDefinition.subscriptionOfferScreen})
7
+ * and the plans' `includedFeatures` and `highlight`.
8
+ *
9
+ * `validatePackageSubscriptionPlans()` runs these checks as part of the plan
10
+ * validation, so most callers never call {@link validatePackageSubscriptionOffer}
11
+ * directly.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.validatePackageSubscriptionOffer = validatePackageSubscriptionOffer;
15
+ const enyo_subscription_js_1 = require("../../types/enyo-subscription.cjs");
16
+ const enyo_subscription_offer_js_1 = require("../../types/enyo-subscription-offer.cjs");
17
+ const define_subscription_plan_js_1 = require("./define-subscription-plan.cjs");
18
+ /** A feature key — the same kebab-case slug shape as a plan key. */
19
+ const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
20
+ /** Languages every text on the offer screen must be translated into. */
21
+ const REQUIRED_LANGUAGES = ['de', 'en'];
22
+ /**
23
+ * Checks that a list of localized entries has no duplicate language, covers
24
+ * every required language, and fills the required fields in every entry.
25
+ *
26
+ * @param entries - The localized entries, e.g. a feature's `storeEntry`.
27
+ * @param at - Location prefix for messages.
28
+ * @param requiredFields - Fields that must be non-empty in every entry.
29
+ * @param errors - Collector for blocking errors.
30
+ */
31
+ function validateTranslations(entries, at, requiredFields, errors) {
32
+ const languages = new Set();
33
+ for (const [index, entry] of (entries ?? []).entries()) {
34
+ const entryAt = `${at}[${index}] (${entry.language || '?'})`;
35
+ if (languages.has(entry.language)) {
36
+ errors.push(`${entryAt}: duplicate language "${entry.language}".`);
37
+ }
38
+ languages.add(entry.language);
39
+ for (const field of requiredFields) {
40
+ const value = entry[field];
41
+ if (typeof value !== 'string' || !value.trim()) {
42
+ errors.push(`${entryAt}: ${field} is required.`);
43
+ }
44
+ }
45
+ }
46
+ for (const language of REQUIRED_LANGUAGES) {
47
+ if (!languages.has(language)) {
48
+ errors.push(`${at}: entry for language "${language}" is required.`);
49
+ }
50
+ }
51
+ }
52
+ /**
53
+ * Checks the included features of a plan or of the free tier: every entry
54
+ * names a declared feature, no feature is listed twice, and every value is
55
+ * translated.
56
+ *
57
+ * @param included - The included features, or `undefined` when none are declared.
58
+ * @param featureKeys - The keys of the feature catalog.
59
+ * @param at - Location prefix for messages.
60
+ * @param errors - Collector for blocking errors.
61
+ */
62
+ function validateIncludedFeatures(included, featureKeys, at, errors) {
63
+ const seen = new Set();
64
+ for (const [index, feature] of (included ?? []).entries()) {
65
+ const key = (0, define_subscription_plan_js_1.getIncludedFeatureKey)(feature);
66
+ const featureAt = `${at}.includedFeatures[${index}] (${key || '?'})`;
67
+ if (!featureKeys.has(key)) {
68
+ errors.push(`${featureAt}: "${key}" is not a feature of subscriptionFeatures.`);
69
+ }
70
+ else if (seen.has(key)) {
71
+ errors.push(`${featureAt}: feature "${key}" is listed twice.`);
72
+ }
73
+ seen.add(key);
74
+ if (typeof feature !== 'string') {
75
+ validateTranslations(feature.value, `${featureAt}.value`, ['value'], errors);
76
+ }
77
+ }
78
+ }
79
+ /**
80
+ * Checks that every key of a block's key list is declared.
81
+ *
82
+ * @param keys - The keys the block refers to, or `undefined` for "all".
83
+ * @param known - The declared keys.
84
+ * @param kind - `'feature'` or `'plan'`, used in messages.
85
+ * @param at - Location prefix for messages.
86
+ * @param errors - Collector for blocking errors.
87
+ */
88
+ function validateBlockKeys(keys, known, kind, at, errors) {
89
+ if (keys === undefined)
90
+ return;
91
+ if (keys.length === 0) {
92
+ errors.push(`${at}: ${kind}Keys must not be empty — omit it to use every ${kind}.`);
93
+ }
94
+ const seen = new Set();
95
+ for (const key of keys) {
96
+ if (!known.has(key))
97
+ errors.push(`${at}: "${key}" is not a declared ${kind}.`);
98
+ else if (seen.has(key))
99
+ errors.push(`${at}: ${kind} "${key}" is listed twice.`);
100
+ seen.add(key);
101
+ }
102
+ }
103
+ /**
104
+ * Checks a block's optional heading and text: when set, they must be
105
+ * translated into every required language.
106
+ *
107
+ * @param storeEntry - The block's localized texts.
108
+ * @param at - Location prefix for messages.
109
+ * @param requiredFields - Fields that must be non-empty in every entry.
110
+ * @param errors - Collector for blocking errors.
111
+ */
112
+ function validateBlockTexts(storeEntry, at, requiredFields, errors) {
113
+ validateTranslations(storeEntry, `${at}.storeEntry`, requiredFields, errors);
114
+ for (const [index, entry] of (storeEntry ?? []).entries()) {
115
+ if (!entry.title?.trim() && !entry.text?.trim()) {
116
+ errors.push(`${at}.storeEntry[${index}] (${entry.language || '?'}): title or text is required.`);
117
+ }
118
+ }
119
+ }
120
+ /**
121
+ * Checks an optional icon against {@link EnyoSubscriptionOfferIconEnum}.
122
+ *
123
+ * @param icon - The icon, or `undefined`.
124
+ * @param at - Location prefix for messages.
125
+ * @param errors - Collector for blocking errors.
126
+ */
127
+ function validateIcon(icon, at, errors) {
128
+ if (icon !== undefined && !Object.values(enyo_subscription_offer_js_1.EnyoSubscriptionOfferIconEnum).includes(icon)) {
129
+ errors.push(`${at}: icon "${icon}" is not supported — use one of EnyoSubscriptionOfferIconEnum.`);
130
+ }
131
+ }
132
+ /**
133
+ * Validates how a package promotes its plans:
134
+ *
135
+ * - **Features**: keys are unique kebab-case slugs, icons are known, and every
136
+ * feature has a German and English title.
137
+ * - **Plans**: `includedFeatures` name declared features, at most once each,
138
+ * with translated values; `highlight` is known and set on at most one plan.
139
+ * - **Free tier**: only with `subscriptionMode: 'optional'`, translated, and
140
+ * its `includedFeatures` follow the plan rules.
141
+ * - **Offer screen**: at least one block, every block type is known, texts are
142
+ * translated (a `hero` needs a title, a `hint` a known kind and a text),
143
+ * referenced features and plans exist, a comparison has at least two
144
+ * columns and a free column only with a free tier, and there is at most one
145
+ * `plans` block.
146
+ *
147
+ * Warnings flag features no tier includes, comparison rows no column
148
+ * includes, and offer declarations without plans.
149
+ *
150
+ * @param definition - The package definition, or just the fields listed in
151
+ * {@link PackageSubscriptionOfferSource}.
152
+ * @returns The {@link PackageSubscriptionOfferValidationResult}.
153
+ *
154
+ * @example
155
+ * ```typescript
156
+ * const {ok, errors} = validatePackageSubscriptionOffer(packageDef);
157
+ * if (!ok) throw new Error(errors.join('\n'));
158
+ * ```
159
+ */
160
+ function validatePackageSubscriptionOffer(definition) {
161
+ const errors = [];
162
+ const warnings = [];
163
+ const plans = definition.subscriptionPlans ?? [];
164
+ const features = definition.subscriptionFeatures ?? [];
165
+ const freeTier = definition.subscriptionFreeTier;
166
+ const screen = definition.subscriptionOfferScreen;
167
+ if (!plans.length) {
168
+ if (definition.subscriptionFeatures || freeTier || screen) {
169
+ warnings.push('subscriptionFeatures, subscriptionFreeTier or subscriptionOfferScreen is set but no subscriptionPlans are declared — it has no effect.');
170
+ }
171
+ return { ok: true, errors, warnings };
172
+ }
173
+ const featureKeys = new Set();
174
+ for (const [index, feature] of features.entries()) {
175
+ const at = `subscriptionFeatures[${index}] (${feature.featureKey || '?'})`;
176
+ if (!feature.featureKey?.trim()) {
177
+ errors.push(`${at}: featureKey is required.`);
178
+ }
179
+ else if (!SLUG_RE.test(feature.featureKey)) {
180
+ errors.push(`${at}: featureKey must be a kebab-case slug, e.g. "price-optimisation".`);
181
+ }
182
+ else if (featureKeys.has(feature.featureKey)) {
183
+ errors.push(`${at}: duplicate featureKey "${feature.featureKey}" — feature keys must be unique within the package.`);
184
+ }
185
+ featureKeys.add(feature.featureKey);
186
+ validateIcon(feature.icon, at, errors);
187
+ validateTranslations(feature.storeEntry, `${at}.storeEntry`, ['title'], errors);
188
+ }
189
+ const includedSomewhere = new Set();
190
+ const highlighted = [];
191
+ for (const [index, plan] of plans.entries()) {
192
+ const at = `subscriptionPlans[${index}] (${plan.planKey || '?'})`;
193
+ validateIncludedFeatures(plan.includedFeatures, featureKeys, at, errors);
194
+ plan.includedFeatures?.forEach(feature => includedSomewhere.add((0, define_subscription_plan_js_1.getIncludedFeatureKey)(feature)));
195
+ if (plan.highlight !== undefined) {
196
+ if (!Object.values(enyo_subscription_offer_js_1.EnyoSubscriptionPlanHighlightEnum).includes(plan.highlight)) {
197
+ errors.push(`${at}: highlight "${plan.highlight}" is not supported.`);
198
+ }
199
+ highlighted.push(plan.planKey);
200
+ }
201
+ }
202
+ if (highlighted.length > 1) {
203
+ errors.push(`Only one plan may be highlighted, but ${highlighted.map(key => `"${key}"`).join(', ')} are.`);
204
+ }
205
+ if (freeTier) {
206
+ if (definition.subscriptionMode === enyo_subscription_js_1.EnyoSubscriptionModeEnum.Required) {
207
+ errors.push('subscriptionFreeTier is not allowed with subscriptionMode "required" — the app has no free base.');
208
+ }
209
+ validateTranslations(freeTier.storeEntry, 'subscriptionFreeTier.storeEntry', ['title'], errors);
210
+ validateIncludedFeatures(freeTier.includedFeatures, featureKeys, 'subscriptionFreeTier', errors);
211
+ freeTier.includedFeatures?.forEach(feature => includedSomewhere.add((0, define_subscription_plan_js_1.getIncludedFeatureKey)(feature)));
212
+ }
213
+ for (const feature of features) {
214
+ if (feature.featureKey && !includedSomewhere.has(feature.featureKey)) {
215
+ warnings.push(`Feature "${feature.featureKey}" is not included in any plan or the free tier.`);
216
+ }
217
+ }
218
+ if (screen) {
219
+ validateOfferScreenBlocks(screen.blocks, definition, featureKeys, errors, warnings);
220
+ }
221
+ return { ok: errors.length === 0, errors, warnings };
222
+ }
223
+ /**
224
+ * Checks the blocks of the offer screen.
225
+ *
226
+ * @param blocks - The declared blocks.
227
+ * @param definition - The package definition, for plans and the free tier.
228
+ * @param featureKeys - The keys of the feature catalog.
229
+ * @param errors - Collector for blocking errors.
230
+ * @param warnings - Collector for advisory problems.
231
+ */
232
+ function validateOfferScreenBlocks(blocks, definition, featureKeys, errors, warnings) {
233
+ if (!Array.isArray(blocks) || blocks.length === 0) {
234
+ errors.push('subscriptionOfferScreen.blocks must contain at least one block — omit subscriptionOfferScreen to show only the plans.');
235
+ return;
236
+ }
237
+ const plans = definition.subscriptionPlans ?? [];
238
+ const planKeys = new Set(plans.map(plan => plan.planKey));
239
+ let plansBlocks = 0;
240
+ for (const [index, block] of blocks.entries()) {
241
+ const at = `subscriptionOfferScreen.blocks[${index}] (${block?.type || '?'})`;
242
+ switch (block?.type) {
243
+ case enyo_subscription_offer_js_1.EnyoSubscriptionOfferBlockTypeEnum.Hero:
244
+ validateIcon(block.icon, at, errors);
245
+ validateBlockTexts(block.storeEntry, at, ['title'], errors);
246
+ break;
247
+ case enyo_subscription_offer_js_1.EnyoSubscriptionOfferBlockTypeEnum.Features:
248
+ if (featureKeys.size === 0) {
249
+ errors.push(`${at}: a features block needs subscriptionFeatures to list.`);
250
+ }
251
+ validateBlockKeys(block.featureKeys, featureKeys, 'feature', at, errors);
252
+ if (block.storeEntry)
253
+ validateBlockTexts(block.storeEntry, at, [], errors);
254
+ break;
255
+ case enyo_subscription_offer_js_1.EnyoSubscriptionOfferBlockTypeEnum.Comparison: {
256
+ if (featureKeys.size === 0) {
257
+ errors.push(`${at}: a comparison block needs subscriptionFeatures as its rows.`);
258
+ }
259
+ validateBlockKeys(block.featureKeys, featureKeys, 'feature', at, errors);
260
+ validateBlockKeys(block.planKeys, planKeys, 'plan', at, errors);
261
+ const freeColumn = block.includeFreeTier ?? definition.subscriptionFreeTier !== undefined;
262
+ if (freeColumn && !definition.subscriptionFreeTier) {
263
+ errors.push(`${at}: includeFreeTier needs subscriptionFreeTier to fill the free column.`);
264
+ }
265
+ const columnPlans = plans.filter(plan => block.planKeys?.includes(plan.planKey) ?? true);
266
+ if (columnPlans.length + (freeColumn ? 1 : 0) < 2) {
267
+ errors.push(`${at}: a comparison needs at least two columns — add the free tier or another plan.`);
268
+ }
269
+ const included = new Set([
270
+ ...(freeColumn ? definition.subscriptionFreeTier?.includedFeatures ?? [] : []),
271
+ ...columnPlans.flatMap(plan => plan.includedFeatures ?? []),
272
+ ].map(define_subscription_plan_js_1.getIncludedFeatureKey));
273
+ for (const key of block.featureKeys ?? featureKeys) {
274
+ if (featureKeys.has(key) && !included.has(key)) {
275
+ warnings.push(`${at}: feature "${key}" is not included in any compared column — its row stays empty.`);
276
+ }
277
+ }
278
+ if (block.storeEntry)
279
+ validateBlockTexts(block.storeEntry, at, [], errors);
280
+ break;
281
+ }
282
+ case enyo_subscription_offer_js_1.EnyoSubscriptionOfferBlockTypeEnum.Hint:
283
+ if (!Object.values(enyo_subscription_offer_js_1.EnyoSubscriptionOfferHintKindEnum).includes(block.kind)) {
284
+ errors.push(`${at}: kind "${block.kind}" is not supported.`);
285
+ }
286
+ validateIcon(block.icon, at, errors);
287
+ validateBlockTexts(block.storeEntry, at, ['text'], errors);
288
+ break;
289
+ case enyo_subscription_offer_js_1.EnyoSubscriptionOfferBlockTypeEnum.Plans:
290
+ plansBlocks++;
291
+ if (block.storeEntry)
292
+ validateBlockTexts(block.storeEntry, at, [], errors);
293
+ break;
294
+ default:
295
+ errors.push(`${at}: block type "${block?.type}" is not supported.`);
296
+ }
297
+ }
298
+ if (plansBlocks > 1) {
299
+ errors.push('subscriptionOfferScreen.blocks may contain at most one "plans" block.');
300
+ }
301
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Client-side validator for how a package promotes its subscription plans:
3
+ * the feature catalog ({@link EnergyAppPackageDefinition.subscriptionFeatures}),
4
+ * the free tier ({@link EnergyAppPackageDefinition.subscriptionFreeTier}), the
5
+ * offer screen blocks ({@link EnergyAppPackageDefinition.subscriptionOfferScreen})
6
+ * and the plans' `includedFeatures` and `highlight`.
7
+ *
8
+ * `validatePackageSubscriptionPlans()` runs these checks as part of the plan
9
+ * validation, so most callers never call {@link validatePackageSubscriptionOffer}
10
+ * directly.
11
+ */
12
+ import type { EnergyAppPackageDefinition } from '../../energy-app-package-definition.cjs';
13
+ /** The outcome of validating how a package promotes its plans. */
14
+ export interface PackageSubscriptionOfferValidationResult {
15
+ /** True when there are no blocking `errors` (warnings are still allowed). */
16
+ ok: boolean;
17
+ /** Blocking problems — these must be fixed before releasing. */
18
+ errors: string[];
19
+ /** Advisory problems — allowed, but usually worth reviewing. */
20
+ warnings: string[];
21
+ }
22
+ /**
23
+ * The parts of a package definition the offer validator reads.
24
+ */
25
+ export type PackageSubscriptionOfferSource = Pick<EnergyAppPackageDefinition, 'subscriptionPlans' | 'subscriptionMode' | 'subscriptionFeatures' | 'subscriptionFreeTier' | 'subscriptionOfferScreen'>;
26
+ /**
27
+ * Validates how a package promotes its plans:
28
+ *
29
+ * - **Features**: keys are unique kebab-case slugs, icons are known, and every
30
+ * feature has a German and English title.
31
+ * - **Plans**: `includedFeatures` name declared features, at most once each,
32
+ * with translated values; `highlight` is known and set on at most one plan.
33
+ * - **Free tier**: only with `subscriptionMode: 'optional'`, translated, and
34
+ * its `includedFeatures` follow the plan rules.
35
+ * - **Offer screen**: at least one block, every block type is known, texts are
36
+ * translated (a `hero` needs a title, a `hint` a known kind and a text),
37
+ * referenced features and plans exist, a comparison has at least two
38
+ * columns and a free column only with a free tier, and there is at most one
39
+ * `plans` block.
40
+ *
41
+ * Warnings flag features no tier includes, comparison rows no column
42
+ * includes, and offer declarations without plans.
43
+ *
44
+ * @param definition - The package definition, or just the fields listed in
45
+ * {@link PackageSubscriptionOfferSource}.
46
+ * @returns The {@link PackageSubscriptionOfferValidationResult}.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const {ok, errors} = validatePackageSubscriptionOffer(packageDef);
51
+ * if (!ok) throw new Error(errors.join('\n'));
52
+ * ```
53
+ */
54
+ export declare function validatePackageSubscriptionOffer(definition: PackageSubscriptionOfferSource): PackageSubscriptionOfferValidationResult;
@@ -22,6 +22,7 @@ const energy_app_permission_type_js_1 = require("../../energy-app-permission.typ
22
22
  const enyo_energy_app_sdk_js_1 = require("../../enyo-energy-app-sdk.cjs");
23
23
  const enyo_currency_js_1 = require("../../types/enyo-currency.cjs");
24
24
  const enyo_subscription_js_1 = require("../../types/enyo-subscription.cjs");
25
+ const subscription_offer_validators_js_1 = require("./subscription-offer-validators.cjs");
25
26
  /**
26
27
  * Thrown by {@link assertValidPackageSubscriptionPlans} when a package's
27
28
  * subscription plans fail validation. The message lists every blocking error
@@ -128,6 +129,10 @@ function validateStoreEntries(plan, at, errors) {
128
129
  *
129
130
  * A `subscriptionMode` without plans is a warning: it has no effect.
130
131
  *
132
+ * Also runs `validatePackageSubscriptionOffer()` on the feature catalog, the
133
+ * free tier, the offer screen and the plans' `includedFeatures` and
134
+ * `highlight`, and merges its errors and warnings into the result.
135
+ *
131
136
  * @param definition - The package definition, or just its `subscriptionPlans`,
132
137
  * `subscriptionMode` and `permissions`. A package without plans is valid.
133
138
  * @returns The {@link PackageSubscriptionPlansValidationResult}.
@@ -143,6 +148,8 @@ function validatePackageSubscriptionPlans(definition) {
143
148
  const warnings = [];
144
149
  const plans = definition.subscriptionPlans;
145
150
  const mode = definition.subscriptionMode;
151
+ const offer = (0, subscription_offer_validators_js_1.validatePackageSubscriptionOffer)(definition);
152
+ warnings.push(...offer.warnings);
146
153
  if (!plans?.length) {
147
154
  if (mode !== undefined) {
148
155
  warnings.push('subscriptionMode is set but no subscriptionPlans are declared — it has no effect.');
@@ -192,6 +199,7 @@ function validatePackageSubscriptionPlans(definition) {
192
199
  }
193
200
  validateStoreEntries(plan, at, errors);
194
201
  }
202
+ errors.push(...offer.errors);
195
203
  return { ok: errors.length === 0, errors, warnings };
196
204
  }
197
205
  /**