@pagopa/dx-savemoney 0.6.1 → 0.6.3

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 (118) hide show
  1. package/dist/azure/pricing/pricing-service.d.ts.map +1 -1
  2. package/dist/azure/pricing/pricing-service.js +6 -1
  3. package/dist/azure/pricing/pricing-service.js.map +1 -1
  4. package/dist/azure/pricing/schema.d.ts.map +1 -1
  5. package/dist/azure/pricing/schema.js +22 -14
  6. package/dist/azure/pricing/schema.js.map +1 -1
  7. package/dist/azure/resources/app-service.d.ts.map +1 -1
  8. package/dist/azure/resources/app-service.js +2 -2
  9. package/dist/azure/resources/app-service.js.map +1 -1
  10. package/dist/azure/resources/container-app.d.ts.map +1 -1
  11. package/dist/azure/resources/container-app.js +1 -1
  12. package/dist/azure/resources/container-app.js.map +1 -1
  13. package/dist/azure/resources/disk.js +3 -1
  14. package/dist/azure/resources/disk.js.map +1 -1
  15. package/dist/azure/resources/nic.js +3 -1
  16. package/dist/azure/resources/nic.js.map +1 -1
  17. package/dist/azure/resources/private-endpoint.d.ts.map +1 -1
  18. package/dist/azure/resources/private-endpoint.js +1 -1
  19. package/dist/azure/resources/private-endpoint.js.map +1 -1
  20. package/dist/azure/resources/public-ip.d.ts.map +1 -1
  21. package/dist/azure/resources/public-ip.js +4 -2
  22. package/dist/azure/resources/public-ip.js.map +1 -1
  23. package/dist/azure/resources/static-web-app.d.ts.map +1 -1
  24. package/dist/azure/resources/static-web-app.js +1 -1
  25. package/dist/azure/resources/static-web-app.js.map +1 -1
  26. package/dist/azure/resources/vm.js +6 -2
  27. package/dist/azure/resources/vm.js.map +1 -1
  28. package/dist/azure/utils.d.ts.map +1 -1
  29. package/dist/azure/utils.js +7 -2
  30. package/dist/azure/utils.js.map +1 -1
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +1 -0
  34. package/dist/index.js.map +1 -1
  35. package/dist/telemetry/savemoney-command-telemetry.d.ts +20 -0
  36. package/dist/telemetry/savemoney-command-telemetry.d.ts.map +1 -0
  37. package/dist/telemetry/savemoney-command-telemetry.js +42 -0
  38. package/dist/telemetry/savemoney-command-telemetry.js.map +1 -0
  39. package/package.json +1 -8
  40. package/src/__tests__/savemoney-command-telemetry.test.ts +117 -0
  41. package/src/azure/pricing/__tests__/schema.test.ts +30 -0
  42. package/src/azure/pricing/pricing-service.ts +6 -3
  43. package/src/azure/pricing/schema.ts +22 -14
  44. package/src/azure/resources/app-service.ts +4 -2
  45. package/src/azure/resources/container-app.ts +2 -1
  46. package/src/azure/resources/disk.ts +3 -3
  47. package/src/azure/resources/nic.ts +3 -3
  48. package/src/azure/resources/private-endpoint.ts +2 -1
  49. package/src/azure/resources/public-ip.ts +5 -4
  50. package/src/azure/resources/static-web-app.ts +2 -1
  51. package/src/azure/resources/vm.ts +6 -6
  52. package/src/azure/utils.ts +8 -2
  53. package/src/index.ts +7 -0
  54. package/src/telemetry/savemoney-command-telemetry.ts +83 -0
  55. package/dist/__tests__/finding.test.d.ts +0 -17
  56. package/dist/__tests__/finding.test.d.ts.map +0 -1
  57. package/dist/__tests__/finding.test.js +0 -146
  58. package/dist/__tests__/finding.test.js.map +0 -1
  59. package/dist/azure/__tests__/analyzer-tags.test.d.ts +0 -8
  60. package/dist/azure/__tests__/analyzer-tags.test.d.ts.map +0 -1
  61. package/dist/azure/__tests__/analyzer-tags.test.js +0 -70
  62. package/dist/azure/__tests__/analyzer-tags.test.js.map +0 -1
  63. package/dist/azure/__tests__/azqr.test.d.ts +0 -13
  64. package/dist/azure/__tests__/azqr.test.d.ts.map +0 -1
  65. package/dist/azure/__tests__/azqr.test.js +0 -177
  66. package/dist/azure/__tests__/azqr.test.js.map +0 -1
  67. package/dist/azure/__tests__/config.test.d.ts +0 -9
  68. package/dist/azure/__tests__/config.test.d.ts.map +0 -1
  69. package/dist/azure/__tests__/config.test.js +0 -102
  70. package/dist/azure/__tests__/config.test.js.map +0 -1
  71. package/dist/azure/__tests__/report.test.d.ts +0 -9
  72. package/dist/azure/__tests__/report.test.d.ts.map +0 -1
  73. package/dist/azure/__tests__/report.test.js +0 -191
  74. package/dist/azure/__tests__/report.test.js.map +0 -1
  75. package/dist/azure/__tests__/utils.test.d.ts +0 -15
  76. package/dist/azure/__tests__/utils.test.d.ts.map +0 -1
  77. package/dist/azure/__tests__/utils.test.js +0 -181
  78. package/dist/azure/__tests__/utils.test.js.map +0 -1
  79. package/dist/azure/analyzers/__tests__/advisor.test.d.ts +0 -9
  80. package/dist/azure/analyzers/__tests__/advisor.test.d.ts.map +0 -1
  81. package/dist/azure/analyzers/__tests__/advisor.test.js +0 -314
  82. package/dist/azure/analyzers/__tests__/advisor.test.js.map +0 -1
  83. package/dist/azure/pricing/__tests__/cache.test.d.ts +0 -8
  84. package/dist/azure/pricing/__tests__/cache.test.d.ts.map +0 -1
  85. package/dist/azure/pricing/__tests__/cache.test.js +0 -56
  86. package/dist/azure/pricing/__tests__/cache.test.js.map +0 -1
  87. package/dist/azure/pricing/__tests__/client.test.d.ts +0 -9
  88. package/dist/azure/pricing/__tests__/client.test.d.ts.map +0 -1
  89. package/dist/azure/pricing/__tests__/client.test.js +0 -181
  90. package/dist/azure/pricing/__tests__/client.test.js.map +0 -1
  91. package/dist/azure/pricing/__tests__/pricing-service.test.d.ts +0 -6
  92. package/dist/azure/pricing/__tests__/pricing-service.test.d.ts.map +0 -1
  93. package/dist/azure/pricing/__tests__/pricing-service.test.js +0 -283
  94. package/dist/azure/pricing/__tests__/pricing-service.test.js.map +0 -1
  95. package/dist/azure/pricing/resolvers/__tests__/app-service.test.d.ts +0 -5
  96. package/dist/azure/pricing/resolvers/__tests__/app-service.test.d.ts.map +0 -1
  97. package/dist/azure/pricing/resolvers/__tests__/app-service.test.js +0 -137
  98. package/dist/azure/pricing/resolvers/__tests__/app-service.test.js.map +0 -1
  99. package/dist/azure/pricing/resolvers/__tests__/disk.test.d.ts +0 -5
  100. package/dist/azure/pricing/resolvers/__tests__/disk.test.d.ts.map +0 -1
  101. package/dist/azure/pricing/resolvers/__tests__/disk.test.js +0 -160
  102. package/dist/azure/pricing/resolvers/__tests__/disk.test.js.map +0 -1
  103. package/dist/azure/pricing/resolvers/__tests__/public-ip.test.d.ts +0 -5
  104. package/dist/azure/pricing/resolvers/__tests__/public-ip.test.d.ts.map +0 -1
  105. package/dist/azure/pricing/resolvers/__tests__/public-ip.test.js +0 -113
  106. package/dist/azure/pricing/resolvers/__tests__/public-ip.test.js.map +0 -1
  107. package/dist/azure/pricing/resolvers/__tests__/vm.test.d.ts +0 -9
  108. package/dist/azure/pricing/resolvers/__tests__/vm.test.d.ts.map +0 -1
  109. package/dist/azure/pricing/resolvers/__tests__/vm.test.js +0 -204
  110. package/dist/azure/pricing/resolvers/__tests__/vm.test.js.map +0 -1
  111. package/dist/azure/resources/__tests__/app-service.test.d.ts +0 -5
  112. package/dist/azure/resources/__tests__/app-service.test.d.ts.map +0 -1
  113. package/dist/azure/resources/__tests__/app-service.test.js +0 -105
  114. package/dist/azure/resources/__tests__/app-service.test.js.map +0 -1
  115. package/dist/azure/resources/__tests__/storage.test.d.ts +0 -11
  116. package/dist/azure/resources/__tests__/storage.test.d.ts.map +0 -1
  117. package/dist/azure/resources/__tests__/storage.test.js +0 -99
  118. package/dist/azure/resources/__tests__/storage.test.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pagopa/dx-savemoney",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "type": "module",
5
5
  "description": "Azure resource analyzer for finding unused or cost-inefficient resources.",
6
6
  "repository": {
@@ -51,12 +51,5 @@
51
51
  "typescript": "~5.9.3",
52
52
  "vitest": "^4.1.10",
53
53
  "@pagopa/eslint-config": "^6.2.2"
54
- },
55
- "scripts": {
56
- "build": "rm -rf dist && tsc",
57
- "dev": "tsc --watch",
58
- "format": "prettier --write .",
59
- "format:check": "prettier --check .",
60
- "test:coverage": "vitest run --coverage"
61
54
  }
62
55
  }
@@ -0,0 +1,117 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import type { Finding } from "../finding.js";
4
+
5
+ import {
6
+ buildSavemoneyInvocationTelemetryAttributes,
7
+ buildSavemoneyOutcomeTelemetryAttributes,
8
+ } from "../telemetry/savemoney-command-telemetry.js";
9
+
10
+ const BASE_FINDING: Finding = {
11
+ category: "cost",
12
+ code: "vm.low-cpu",
13
+ reason: "Low CPU usage.",
14
+ resourceId:
15
+ "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm",
16
+ severity: "low",
17
+ source: "custom",
18
+ };
19
+
20
+ describe("buildSavemoneyInvocationTelemetryAttributes", () => {
21
+ it("sets azqr_report_source to cli when --azqr-report is provided", () => {
22
+ const attributes = buildSavemoneyInvocationTelemetryAttributes({
23
+ azqrReportPathOption: "./azqr.json",
24
+ format: "table",
25
+ resolvedConfig: {
26
+ azqrReportPath: "./from-config.json",
27
+ pricing: { enabled: true },
28
+ sources: ["advisor", "custom"],
29
+ subscriptionIds: ["sub-a"],
30
+ },
31
+ });
32
+
33
+ expect(attributes["savemoney.azqr_report_source"]).toBe("cli");
34
+ });
35
+
36
+ it("sets azqr_report_source to config when only config path is present", () => {
37
+ const attributes = buildSavemoneyInvocationTelemetryAttributes({
38
+ format: "table",
39
+ resolvedConfig: {
40
+ azqrReportPath: "./from-config.json",
41
+ pricing: { enabled: true },
42
+ sources: ["advisor", "custom"],
43
+ subscriptionIds: ["sub-a"],
44
+ },
45
+ });
46
+
47
+ expect(attributes["savemoney.azqr_report_source"]).toBe("config");
48
+ });
49
+
50
+ it("sets azqr_report_source to none when azqr is absent", () => {
51
+ const attributes = buildSavemoneyInvocationTelemetryAttributes({
52
+ format: "table",
53
+ resolvedConfig: {
54
+ pricing: { enabled: true },
55
+ sources: ["advisor", "custom"],
56
+ subscriptionIds: ["sub-a"],
57
+ },
58
+ });
59
+
60
+ expect(attributes["savemoney.azqr_report_source"]).toBe("none");
61
+ });
62
+
63
+ it("derives subscriptions_source as config, env, or prompt", () => {
64
+ const fromConfig = buildSavemoneyInvocationTelemetryAttributes({
65
+ configPathOption: "./config.yaml",
66
+ format: "table",
67
+ resolvedConfig: {
68
+ pricing: { enabled: true },
69
+ sources: ["advisor", "custom"],
70
+ subscriptionIds: ["sub-a"],
71
+ },
72
+ subscriptionIdsEnv: "sub-env",
73
+ });
74
+ const fromEnv = buildSavemoneyInvocationTelemetryAttributes({
75
+ format: "table",
76
+ resolvedConfig: {
77
+ pricing: { enabled: true },
78
+ sources: ["advisor", "custom"],
79
+ subscriptionIds: ["sub-a"],
80
+ },
81
+ subscriptionIdsEnv: "sub-env",
82
+ });
83
+ const fromPrompt = buildSavemoneyInvocationTelemetryAttributes({
84
+ format: "table",
85
+ resolvedConfig: {
86
+ pricing: { enabled: true },
87
+ sources: ["advisor", "custom"],
88
+ subscriptionIds: ["sub-a"],
89
+ },
90
+ });
91
+
92
+ expect(fromConfig["savemoney.subscriptions_source"]).toBe("config");
93
+ expect(fromEnv["savemoney.subscriptions_source"]).toBe("env");
94
+ expect(fromPrompt["savemoney.subscriptions_source"]).toBe("prompt");
95
+ });
96
+ });
97
+
98
+ describe("buildSavemoneyOutcomeTelemetryAttributes", () => {
99
+ it("counts findings and analyzed resources", () => {
100
+ const attributes = buildSavemoneyOutcomeTelemetryAttributes([
101
+ {
102
+ findings: [BASE_FINDING, { ...BASE_FINDING, code: "disk.unattached" }],
103
+ },
104
+ {
105
+ findings: [
106
+ { ...BASE_FINDING, code: "advisor.right-size", source: "advisor" },
107
+ ],
108
+ },
109
+ {},
110
+ ]);
111
+
112
+ expect(attributes).toEqual({
113
+ "savemoney.findings_count": 3,
114
+ "savemoney.resources_analyzed": 3,
115
+ });
116
+ });
117
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Tests for the Retail Prices API zod schemas, focused on the API's real
3
+ * (and easy to overlook) quirks rather than the happy path already covered
4
+ * indirectly by client.test.ts.
5
+ */
6
+
7
+ import { describe, expect, it } from "vitest";
8
+
9
+ import { PriceItemSchema } from "../schema.js";
10
+
11
+ describe("PriceItemSchema", () => {
12
+ it("accepts empty strings for optional metadata fields", () => {
13
+ // The Retail Prices API returns "" (not the field omitted) for meters
14
+ // that don't have a given attribute, e.g. `armSkuName` on
15
+ // Bandwidth/Support meters. Resolvers already treat "" and `undefined`
16
+ // the same way (`?.toLowerCase() ?? ""`), so the schema must tolerate it.
17
+ const item = {
18
+ armSkuName: "",
19
+ currencyCode: "EUR",
20
+ retailPrice: 1,
21
+ type: "Consumption",
22
+ unitOfMeasure: "1 Hour",
23
+ unitPrice: 1,
24
+ };
25
+
26
+ const result = PriceItemSchema.parse(item);
27
+
28
+ expect(result.armSkuName).toBe("");
29
+ });
30
+ });
@@ -116,9 +116,12 @@ export class PricingService {
116
116
  try {
117
117
  return await factory();
118
118
  } catch (error) {
119
- logger.warn(
120
- `Pricing lookup failed: ${error instanceof Error ? error.message : String(error)}`,
121
- );
119
+ // Passed as a template property, not string-interpolated: logtape parses
120
+ // `{...}` in the message itself as placeholders (e.g. a ZodError's
121
+ // JSON-formatted issues would otherwise get swallowed as `undefined`).
122
+ logger.warn("Pricing lookup failed: {message}", {
123
+ message: error instanceof Error ? error.message : String(error),
124
+ });
122
125
  return undefined;
123
126
  }
124
127
  }
@@ -12,6 +12,14 @@
12
12
  import { z } from "zod";
13
13
 
14
14
  const NonEmptyStringSchema = z.string().min(1);
15
+ /**
16
+ * Optional metadata fields. The Retail Prices API returns `""` (not the
17
+ * field omitted) for meters where a given attribute doesn't apply (e.g.
18
+ * `armSkuName` for Bandwidth/Support meters), so these must tolerate empty
19
+ * strings — resolvers already treat empty and missing values the same way
20
+ * (`?.toLowerCase() ?? ""`).
21
+ */
22
+ const OptionalStringSchema = z.string().optional();
15
23
  const PriceTypeSchema = z.enum([
16
24
  "Consumption",
17
25
  "DevTestConsumption",
@@ -31,23 +39,23 @@ const PriceValueSchema = z.number().finite().nonnegative();
31
39
  * want on-demand pricing must filter by `type === "Consumption"`.
32
40
  */
33
41
  export const PriceItemSchema = z.object({
34
- armRegionName: NonEmptyStringSchema.optional(),
35
- armSkuName: NonEmptyStringSchema.optional(),
42
+ armRegionName: OptionalStringSchema,
43
+ armSkuName: OptionalStringSchema,
36
44
  currencyCode: z.string().length(3),
37
- effectiveStartDate: NonEmptyStringSchema.optional(),
45
+ effectiveStartDate: OptionalStringSchema,
38
46
  isPrimaryMeterRegion: z.boolean().optional(),
39
- location: NonEmptyStringSchema.optional(),
40
- meterId: NonEmptyStringSchema.optional(),
41
- meterName: NonEmptyStringSchema.optional(),
42
- productId: NonEmptyStringSchema.optional(),
43
- productName: NonEmptyStringSchema.optional(),
44
- reservationTerm: NonEmptyStringSchema.optional(),
47
+ location: OptionalStringSchema,
48
+ meterId: OptionalStringSchema,
49
+ meterName: OptionalStringSchema,
50
+ productId: OptionalStringSchema,
51
+ productName: OptionalStringSchema,
52
+ reservationTerm: OptionalStringSchema,
45
53
  retailPrice: PriceValueSchema,
46
- serviceFamily: NonEmptyStringSchema.optional(),
47
- serviceId: NonEmptyStringSchema.optional(),
48
- serviceName: NonEmptyStringSchema.optional(),
49
- skuId: NonEmptyStringSchema.optional(),
50
- skuName: NonEmptyStringSchema.optional(),
54
+ serviceFamily: OptionalStringSchema,
55
+ serviceId: OptionalStringSchema,
56
+ serviceName: OptionalStringSchema,
57
+ skuId: OptionalStringSchema,
58
+ skuName: OptionalStringSchema,
51
59
  tierMinimumUnits: PriceValueSchema.optional(),
52
60
  /** "Consumption" | "Reservation" | "DevTestConsumption". */
53
61
  type: PriceTypeSchema,
@@ -139,7 +139,8 @@ export async function analyzeAppServicePlan(
139
139
  } catch (error) {
140
140
  const logger = getLogger(["savemoney", "azure"]);
141
141
  logger.warn(
142
- `Failed to get App Service Plan details for ${planName}: ${error instanceof Error ? error.message : error}`,
142
+ `Failed to get App Service Plan details for ${planName}: {message}`,
143
+ { message: error instanceof Error ? error.message : error },
143
144
  );
144
145
  reason += "Could not retrieve detailed App Service Plan information. ";
145
146
  }
@@ -184,7 +185,8 @@ async function enrichWithPricing(
184
185
  } catch (error) {
185
186
  const logger = getLogger(["savemoney", "azure"]);
186
187
  logger.warn(
187
- `Failed to enrich App Service Plan ${resource.name ?? "unknown"} with pricing: ${error instanceof Error ? error.message : error}`,
188
+ `Failed to enrich App Service Plan ${resource.name ?? "unknown"} with pricing: {message}`,
189
+ { message: error instanceof Error ? error.message : error },
188
190
  );
189
191
  return result;
190
192
  }
@@ -100,7 +100,8 @@ export async function analyzeContainerApp(
100
100
  } catch (error) {
101
101
  const logger = getLogger(["savemoney", "azure"]);
102
102
  logger.warn(
103
- `Failed to get Container App details for ${containerAppName}: ${error instanceof Error ? error.message : error}`,
103
+ `Failed to get Container App details for ${containerAppName}: {message}`,
104
+ { message: error instanceof Error ? error.message : error },
104
105
  );
105
106
  reason += "Could not retrieve detailed Container App information. ";
106
107
  }
@@ -81,9 +81,9 @@ export async function analyzeDisk(
81
81
  }
82
82
  } catch (error) {
83
83
  const logger = getLogger(["savemoney", "azure"]);
84
- logger.warn(
85
- `Failed to get disk details for ${diskName}: ${error instanceof Error ? error.message : error}`,
86
- );
84
+ logger.warn(`Failed to get disk details for ${diskName}: {message}`, {
85
+ message: error instanceof Error ? error.message : error,
86
+ });
87
87
  // Fallback to checking properties if API call fails
88
88
  // Note: GenericResource doesn't have diskState property
89
89
  // Without API access, we can't determine if disk is unattached
@@ -77,9 +77,9 @@ export async function analyzeNic(
77
77
  // The primary checks (attachment to VM and public IP assignment) are sufficient
78
78
  } catch (error) {
79
79
  const logger = getLogger(["savemoney", "azure"]);
80
- logger.warn(
81
- `Failed to get NIC details for ${nicName}: ${error instanceof Error ? error.message : error}`,
82
- );
80
+ logger.warn(`Failed to get NIC details for ${nicName}: {message}`, {
81
+ message: error instanceof Error ? error.message : error,
82
+ });
83
83
  reason += "Could not retrieve detailed NIC information. ";
84
84
  }
85
85
 
@@ -100,7 +100,8 @@ export async function analyzePrivateEndpoint(
100
100
  } catch (error) {
101
101
  const logger = getLogger(["savemoney", "azure"]);
102
102
  logger.warn(
103
- `Failed to get Private Endpoint details for ${privateEndpointName}: ${error instanceof Error ? error.message : error}`,
103
+ `Failed to get Private Endpoint details for ${privateEndpointName}: {message}`,
104
+ { message: error instanceof Error ? error.message : error },
104
105
  );
105
106
  reason += "Could not retrieve detailed Private Endpoint information. ";
106
107
  }
@@ -106,7 +106,8 @@ export async function analyzePublicIp(
106
106
  } catch (error) {
107
107
  const logger = getLogger(["savemoney", "azure"]);
108
108
  logger.warn(
109
- `Failed to get Public IP details for ${publicIpName}: ${error instanceof Error ? error.message : error}`,
109
+ `Failed to get Public IP details for ${publicIpName}: {message}`,
110
+ { message: error instanceof Error ? error.message : error },
110
111
  );
111
112
  reason += "Could not retrieve detailed Public IP information. ";
112
113
  }
@@ -160,9 +161,9 @@ async function enrichWithPricing(
160
161
  return { ...result, estimatedMonthlySavings };
161
162
  } catch (error) {
162
163
  const logger = getLogger(["savemoney", "azure"]);
163
- logger.warn(
164
- `Failed to enrich Public IP with pricing: ${error instanceof Error ? error.message : error}`,
165
- );
164
+ logger.warn("Failed to enrich Public IP with pricing: {message}", {
165
+ message: error instanceof Error ? error.message : error,
166
+ });
166
167
  return result;
167
168
  }
168
169
  }
@@ -101,7 +101,8 @@ export async function analyzeStaticSite(
101
101
  } catch (error) {
102
102
  const logger = getLogger(["savemoney", "azure"]);
103
103
  logger.warn(
104
- `Failed to get metrics for Static Web App ${resource.name}: ${error instanceof Error ? error.message : error}`,
104
+ `Failed to get metrics for Static Web App ${resource.name}: {message}`,
105
+ { message: error instanceof Error ? error.message : error },
105
106
  );
106
107
  }
107
108
 
@@ -114,9 +114,9 @@ export async function analyzeVM(
114
114
  }
115
115
  } catch (error) {
116
116
  const logger = getLogger(["savemoney", "azure"]);
117
- logger.warn(
118
- `Failed to get VM instance view for ${vmName}: ${error instanceof Error ? error.message : error}`,
119
- );
117
+ logger.warn(`Failed to get VM instance view for ${vmName}: {message}`, {
118
+ message: error instanceof Error ? error.message : error,
119
+ });
120
120
  // Continue with metric analysis if instance view fails
121
121
  }
122
122
 
@@ -203,9 +203,9 @@ async function enrichWithPricing(
203
203
  return { ...result, estimatedMonthlySavings };
204
204
  } catch (error) {
205
205
  const logger = getLogger(["savemoney", "azure"]);
206
- logger.warn(
207
- `Failed to enrich VM ${vmName} with pricing: ${error instanceof Error ? error.message : error}`,
208
- );
206
+ logger.warn(`Failed to enrich VM ${vmName} with pricing: {message}`, {
207
+ message: error instanceof Error ? error.message : error,
208
+ });
209
209
  return result;
210
210
  }
211
211
  }
@@ -219,7 +219,11 @@ export function verboseLog(
219
219
  if (verbose) {
220
220
  const logger = getLogger(["savemoney", "azure", "verbose"]);
221
221
  if (object !== undefined) {
222
- logger.debug(`${message} ${JSON.stringify(object, null, 2)}`);
222
+ // Passed as a template property (see pricing-service.ts for why: avoids
223
+ // logtape misparsing literal `{`/`}` in the JSON as placeholders).
224
+ logger.debug(`${message} {object}`, {
225
+ object: JSON.stringify(object, null, 2),
226
+ });
223
227
  } else {
224
228
  logger.debug(message);
225
229
  }
@@ -308,8 +312,10 @@ async function fetchMetric(
308
312
  return aggregatedValue;
309
313
  } catch (error) {
310
314
  const logger = getLogger(["savemoney", "azure", "metrics"]);
315
+ // Passed as a template property (see pricing-service.ts for why).
311
316
  logger.error(
312
- `Failed to fetch metric ${metricName} for resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
317
+ `Failed to fetch metric ${metricName} for resource ${resourceId}: {message}`,
318
+ { message: error instanceof Error ? error.message : String(error) },
313
319
  );
314
320
  return null;
315
321
  }
package/src/index.ts CHANGED
@@ -38,6 +38,13 @@ export {
38
38
  type ResourceReport,
39
39
  } from "./finding.js";
40
40
  export { AZURE_SOURCE_VALUES } from "./schema.js";
41
+ export {
42
+ buildSavemoneyInvocationTelemetryAttributes,
43
+ buildSavemoneyOutcomeTelemetryAttributes,
44
+ type SavemoneyAzqrReportSource,
45
+ type SavemoneyCommandInput,
46
+ type SavemoneySubscriptionsSource,
47
+ } from "./telemetry/savemoney-command-telemetry.js";
41
48
 
42
49
  export * from "./types.js";
43
50
 
@@ -0,0 +1,83 @@
1
+ /**
2
+ * SaveMoney command telemetry helpers.
3
+ *
4
+ * Keeps telemetry attribute derivation close to the SaveMoney domain so the
5
+ * same mapping can be reused by both the DX CLI adapter and a future standalone
6
+ * SaveMoney CLI entrypoint.
7
+ */
8
+
9
+ import type {
10
+ AzureConfig,
11
+ AzureDetailedResourceReport,
12
+ } from "../azure/types.js";
13
+
14
+ export type SavemoneyAzqrReportSource = "cli" | "config" | "none";
15
+
16
+ export type SavemoneyCommandInput = {
17
+ azqrReportPathOption?: string;
18
+ configPathOption?: string;
19
+ format: string;
20
+ resolvedConfig: Pick<
21
+ AzureConfig,
22
+ "azqrReportPath" | "pricing" | "sources" | "subscriptionIds"
23
+ >;
24
+ subscriptionIdsEnv?: string;
25
+ };
26
+
27
+ export type SavemoneySubscriptionsSource = "config" | "env" | "prompt";
28
+
29
+ export function buildSavemoneyInvocationTelemetryAttributes(
30
+ input: SavemoneyCommandInput,
31
+ ): Record<string, boolean | number | string> {
32
+ const azqrReportSource = resolveAzqrReportSource(
33
+ input.azqrReportPathOption,
34
+ input.resolvedConfig.azqrReportPath,
35
+ );
36
+ const subscriptionsSource = resolveSubscriptionsSource(
37
+ input.configPathOption,
38
+ input.subscriptionIdsEnv,
39
+ );
40
+
41
+ return {
42
+ "savemoney.azqr_report_source": azqrReportSource,
43
+ "savemoney.format": input.format,
44
+ "savemoney.has_config": Boolean(input.configPathOption),
45
+ "savemoney.pricing_enabled":
46
+ input.resolvedConfig.pricing?.enabled !== false,
47
+ "savemoney.sources": input.resolvedConfig.sources.join(","),
48
+ "savemoney.subscriptions_count":
49
+ input.resolvedConfig.subscriptionIds.length,
50
+ "savemoney.subscriptions_source": subscriptionsSource,
51
+ };
52
+ }
53
+
54
+ export function buildSavemoneyOutcomeTelemetryAttributes(
55
+ reports: readonly Pick<AzureDetailedResourceReport, "findings">[],
56
+ ): Record<string, number> {
57
+ return {
58
+ "savemoney.findings_count": reports.reduce(
59
+ (sum, report) => sum + (report.findings?.length ?? 0),
60
+ 0,
61
+ ),
62
+ "savemoney.resources_analyzed": reports.length,
63
+ };
64
+ }
65
+
66
+ function resolveAzqrReportSource(
67
+ azqrReportPathOption: string | undefined,
68
+ azqrReportPathResolved: string | undefined,
69
+ ): SavemoneyAzqrReportSource {
70
+ if (azqrReportPathOption) return "cli";
71
+ if (azqrReportPathResolved) return "config";
72
+ return "none";
73
+ }
74
+
75
+ function resolveSubscriptionsSource(
76
+ configPathOption: string | undefined,
77
+ subscriptionIdsEnv: string | undefined,
78
+ ): SavemoneySubscriptionsSource {
79
+ // Mirrors loadAzureConfig() priority: config file > ARM_SUBSCRIPTION_ID > prompt.
80
+ if (configPathOption) return "config";
81
+ if (subscriptionIdsEnv) return "env";
82
+ return "prompt";
83
+ }
@@ -1,17 +0,0 @@
1
- /**
2
- * Tests for findingsFromAnalysisResult — verifies the adapter that converts
3
- * a legacy `AnalysisResult.reason` string into a structured `Finding[]`.
4
- *
5
- * Behaviours covered:
6
- * 1. Empty / whitespace-only reason → empty array.
7
- * 2. Single sentence (with or without trailing period) → one finding.
8
- * 3. Multi-sentence reason (". " separator) → one finding per sentence.
9
- * 4. Trailing period on the whole string → not duplicated.
10
- * 5. Custom `code` → propagated to every finding.
11
- * 6. Omitted `code` → defaults to "custom.unknown".
12
- * 7. Custom `source` → propagated.
13
- * 8. Omitted `source` → defaults to "custom".
14
- * 9. Every finding carries the correct `resourceId`, `severity`, `category`.
15
- */
16
- export {};
17
- //# sourceMappingURL=finding.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"finding.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/finding.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG"}
@@ -1,146 +0,0 @@
1
- /**
2
- * Tests for findingsFromAnalysisResult — verifies the adapter that converts
3
- * a legacy `AnalysisResult.reason` string into a structured `Finding[]`.
4
- *
5
- * Behaviours covered:
6
- * 1. Empty / whitespace-only reason → empty array.
7
- * 2. Single sentence (with or without trailing period) → one finding.
8
- * 3. Multi-sentence reason (". " separator) → one finding per sentence.
9
- * 4. Trailing period on the whole string → not duplicated.
10
- * 5. Custom `code` → propagated to every finding.
11
- * 6. Omitted `code` → defaults to "custom.unknown".
12
- * 7. Custom `source` → propagated.
13
- * 8. Omitted `source` → defaults to "custom".
14
- * 9. Every finding carries the correct `resourceId`, `severity`, `category`.
15
- */
16
- import { describe, expect, it } from "vitest";
17
- import { findingsFromAnalysisResult } from "../finding.js";
18
- const BASE_ARGS = {
19
- reason: "Low CPU usage.",
20
- resourceId: "/subscriptions/sub1/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm",
21
- severity: "high",
22
- };
23
- describe("findingsFromAnalysisResult", () => {
24
- describe("empty / whitespace input", () => {
25
- it("returns [] for an empty string", () => {
26
- expect(findingsFromAnalysisResult({ ...BASE_ARGS, reason: "" })).toEqual([]);
27
- });
28
- it("returns [] for a whitespace-only string", () => {
29
- expect(findingsFromAnalysisResult({ ...BASE_ARGS, reason: " " })).toEqual([]);
30
- });
31
- it("returns [] for a bare period", () => {
32
- expect(findingsFromAnalysisResult({ ...BASE_ARGS, reason: "." })).toEqual([]);
33
- });
34
- });
35
- describe("single sentence", () => {
36
- it("returns one finding with a trailing period", () => {
37
- const result = findingsFromAnalysisResult({
38
- ...BASE_ARGS,
39
- reason: "VM is deallocated.",
40
- });
41
- expect(result).toHaveLength(1);
42
- expect(result[0].reason).toBe("VM is deallocated.");
43
- });
44
- it("appends a trailing period when missing", () => {
45
- const result = findingsFromAnalysisResult({
46
- ...BASE_ARGS,
47
- reason: "VM is deallocated",
48
- });
49
- expect(result).toHaveLength(1);
50
- expect(result[0].reason).toBe("VM is deallocated.");
51
- });
52
- });
53
- describe("multi-sentence reason", () => {
54
- it("splits on '. ' into separate findings", () => {
55
- const result = findingsFromAnalysisResult({
56
- ...BASE_ARGS,
57
- reason: "VM is deallocated. No tags found. Low CPU usage.",
58
- });
59
- expect(result).toHaveLength(3);
60
- expect(result[0].reason).toBe("VM is deallocated.");
61
- expect(result[1].reason).toBe("No tags found.");
62
- expect(result[2].reason).toBe("Low CPU usage.");
63
- });
64
- it("does not create an extra empty finding for a trailing period", () => {
65
- const result = findingsFromAnalysisResult({
66
- ...BASE_ARGS,
67
- reason: "Sentence one. Sentence two.",
68
- });
69
- expect(result).toHaveLength(2);
70
- });
71
- });
72
- describe("code field", () => {
73
- it("uses the provided code for every finding", () => {
74
- const result = findingsFromAnalysisResult({
75
- ...BASE_ARGS,
76
- code: "vm.deallocated",
77
- reason: "A. B.",
78
- });
79
- expect(result.every((f) => f.code === "vm.deallocated")).toBe(true);
80
- });
81
- it("defaults code to 'custom.unknown' when omitted", () => {
82
- const result = findingsFromAnalysisResult(BASE_ARGS);
83
- expect(result[0].code).toBe("custom.unknown");
84
- });
85
- });
86
- describe("source field", () => {
87
- it("uses the provided source for every finding", () => {
88
- const result = findingsFromAnalysisResult({
89
- ...BASE_ARGS,
90
- source: "advisor",
91
- });
92
- expect(result.every((f) => f.source === "advisor")).toBe(true);
93
- });
94
- it("defaults source to 'custom' when omitted", () => {
95
- const result = findingsFromAnalysisResult(BASE_ARGS);
96
- expect(result[0].source).toBe("custom");
97
- });
98
- });
99
- describe("static fields on every finding", () => {
100
- it("propagates resourceId to every finding", () => {
101
- const result = findingsFromAnalysisResult({
102
- ...BASE_ARGS,
103
- reason: "A. B.",
104
- });
105
- expect(result.every((f) => f.resourceId === BASE_ARGS.resourceId)).toBe(true);
106
- });
107
- it("propagates severity to every finding", () => {
108
- const result = findingsFromAnalysisResult({
109
- ...BASE_ARGS,
110
- reason: "A. B.",
111
- severity: "medium",
112
- });
113
- expect(result.every((f) => f.severity === "medium")).toBe(true);
114
- });
115
- it("sets category to 'cost' on every finding", () => {
116
- const result = findingsFromAnalysisResult({
117
- ...BASE_ARGS,
118
- reason: "A. B.",
119
- });
120
- expect(result.every((f) => f.category === "cost")).toBe(true);
121
- });
122
- it("never attaches estimatedMonthlySavings to custom findings", () => {
123
- // Custom analyzers carry the resource's monthly cost on
124
- // `AnalysisResult.estimatedMonthlySavings` and the report layer
125
- // renders it at the resource level. Propagating it down to a
126
- // single finding sentence (e.g. "No tags found") would falsely
127
- // suggest that fixing that sentence yields the full saving.
128
- const result = findingsFromAnalysisResult({
129
- ...BASE_ARGS,
130
- reason: "Low CPU. Low network. Idle.",
131
- });
132
- expect(result).toHaveLength(3);
133
- for (const f of result) {
134
- expect(f.estimatedMonthlySavings).toBeUndefined();
135
- }
136
- });
137
- it("omits estimatedMonthlySavings entirely", () => {
138
- const result = findingsFromAnalysisResult({
139
- ...BASE_ARGS,
140
- reason: "Low CPU.",
141
- });
142
- expect(result[0].estimatedMonthlySavings).toBeUndefined();
143
- });
144
- });
145
- });
146
- //# sourceMappingURL=finding.test.js.map