@dx-do/client 7.14.0 → 7.16.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 (31) hide show
  1. package/dist/index.cjs.js +676 -176
  2. package/dist/index.cjs.js.map +1 -1
  3. package/dist/index.esm.js +665 -177
  4. package/dist/index.esm.js.map +1 -1
  5. package/dist/src/index.d.ts +4 -0
  6. package/dist/src/index.d.ts.map +1 -1
  7. package/dist/src/lib/model/alarm/alarm-record.d.ts +53 -0
  8. package/dist/src/lib/model/alarm/alarm-record.d.ts.map +1 -0
  9. package/dist/src/lib/model/datastore/tas/filters.d.ts +11 -10
  10. package/dist/src/lib/model/datastore/tas/filters.d.ts.map +1 -1
  11. package/dist/src/lib/model/oi/alarms.d.ts +12 -0
  12. package/dist/src/lib/model/oi/alarms.d.ts.map +1 -1
  13. package/dist/src/lib/model/oi/services.d.ts +2 -0
  14. package/dist/src/lib/model/oi/services.d.ts.map +1 -1
  15. package/dist/src/lib/model/security/MeResponse.d.ts +2 -0
  16. package/dist/src/lib/model/security/MeResponse.d.ts.map +1 -1
  17. package/dist/src/lib/services/alarm-export.d.ts +85 -0
  18. package/dist/src/lib/services/alarm-export.d.ts.map +1 -0
  19. package/dist/src/lib/services/alarm-window-search.d.ts +59 -0
  20. package/dist/src/lib/services/alarm-window-search.d.ts.map +1 -0
  21. package/dist/src/lib/services/alarm.service.d.ts +57 -4
  22. package/dist/src/lib/services/alarm.service.d.ts.map +1 -1
  23. package/dist/src/lib/services/dxoi.service.d.ts +15 -3
  24. package/dist/src/lib/services/dxoi.service.d.ts.map +1 -1
  25. package/dist/src/lib/services/lifecycle-pages.d.ts +20 -0
  26. package/dist/src/lib/services/lifecycle-pages.d.ts.map +1 -0
  27. package/dist/src/lib/services/service.service.d.ts +18 -4
  28. package/dist/src/lib/services/service.service.d.ts.map +1 -1
  29. package/dist/src/lib/services/situation.service.d.ts +9 -2
  30. package/dist/src/lib/services/situation.service.d.ts.map +1 -1
  31. package/package.json +1 -1
package/dist/index.cjs.js CHANGED
@@ -2093,6 +2093,65 @@ function buildAlarmFilterUpdateBody(existing, patch) {
2093
2093
  return { body, changes };
2094
2094
  }
2095
2095
 
2096
+ /**
2097
+ * One alarm as stored in the alarms analytics index
2098
+ * (`GET oi/v2/aoanalytics/alarms/alarms_all/_search`): one record per alarm,
2099
+ * updated in place. Times are ISO strings with a `+0000` offset, whole seconds.
2100
+ * Fields vary by source product; the declared ones were present on every
2101
+ * sampled record unless marked optional (demo-dev, 2026-10-22).
2102
+ */
2103
+ const AlarmRecordSchema = v4.z.looseObject({
2104
+ alarm_unique_id: v4.z
2105
+ .string()
2106
+ .describe('The alarm id; the same value the alarm search returns as `alarmId`'),
2107
+ status: v4.z.string().describe('Current status: NEW, UPDATED or CLOSED'),
2108
+ severity: v4.z.string().optional().describe('Current severity, as the source sent it'),
2109
+ startTime: v4.z
2110
+ .string()
2111
+ .describe('When the alarm opened (the search\'s `timeOrigin`), ISO `+0000`'),
2112
+ closedTime: v4.z
2113
+ .string()
2114
+ .optional()
2115
+ .describe('When the alarm closed, ISO `+0000`; present exactly when status is CLOSED'),
2116
+ timestamp: v4.z
2117
+ .string()
2118
+ .optional()
2119
+ .describe('Time of the last document the source sent for this alarm (last update), ISO `+0000` — not the open time'),
2120
+ product: v4.z.string().optional().describe('Source product that raised the alarm'),
2121
+ host: v4.z.string().optional().describe('Host the alarm is about'),
2122
+ alarmType: v4.z.string().optional().describe('Alarm type'),
2123
+ message: v4.z.string().optional().describe('Current alarm message'),
2124
+ external_ids: v4.z
2125
+ .array(v4.z.string())
2126
+ .nullable()
2127
+ .optional()
2128
+ .describe('TAS external ids of the entities the alarm is about; null on some records (demo-dev: 4828 of 72747)'),
2129
+ services_impacted: v4.z
2130
+ .array(v4.z.string())
2131
+ .optional()
2132
+ .describe('Names of the services the alarm impacts (from enrichment)'),
2133
+ '@timestamp': v4.z.number().optional().describe('When the record was last indexed, epoch ms'),
2134
+ });
2135
+ /** The analytics search response: Elasticsearch-shaped hits. */
2136
+ const AlarmRecordSearchResponseSchema = v4.z.looseObject({
2137
+ hits: v4.z.looseObject({
2138
+ total: v4.z
2139
+ .looseObject({
2140
+ value: v4.z.number().describe('Number of matching records'),
2141
+ relation: v4.z
2142
+ .string()
2143
+ .describe('`eq` when `value` is exact, `gte` when it is a lower bound (more than 10000)'),
2144
+ })
2145
+ .describe('Match count for the query'),
2146
+ hits: v4.z
2147
+ .array(v4.z.looseObject({
2148
+ _id: v4.z.string().optional().describe('Index id: tenant id + alarm id'),
2149
+ _source: AlarmRecordSchema,
2150
+ }))
2151
+ .describe('The requested page of records'),
2152
+ }),
2153
+ });
2154
+
2096
2155
  exports.AlertDefinitionResponse = void 0;
2097
2156
  (function (AlertDefinitionResponse) {
2098
2157
  (function (AlertComparisonOperator) {
@@ -20416,6 +20475,15 @@ RedirectableRequest.prototype._sanitizeOptions = function (options) {
20416
20475
  if (!options.headers) {
20417
20476
  options.headers = {};
20418
20477
  }
20478
+ // Convert [header1, value1, header2, value2, …] to object
20479
+ else if (Array.isArray(options.headers)) {
20480
+ var headerList = options.headers;
20481
+ options.headers = {};
20482
+ for (var i = 0; i < headerList.length; i += 2) {
20483
+ options.headers[headerList[i]] = headerList[i + 1];
20484
+ }
20485
+ }
20486
+ // Ensure sensitive headers are always present
20419
20487
  if (!isArray$3(options.sensitiveHeaders)) {
20420
20488
  options.sensitiveHeaders = [];
20421
20489
  }
@@ -20815,7 +20883,7 @@ function isURL(value) {
20815
20883
  }
20816
20884
 
20817
20885
  function escapeRegex(regex) {
20818
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
20886
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
20819
20887
  }
20820
20888
 
20821
20889
  // Exports
@@ -48704,7 +48772,9 @@ class StrictMap extends Map {
48704
48772
  * Redaction helpers for keeping auth tokens and other secrets out of logs.
48705
48773
  *
48706
48774
  * Auth tokens live in axios `error.config.headers` — e.g. `Authorization: Bearer
48707
- * <userToken>` and `X-Asm-Auth: <dxASMToken>`. Anything that serializes a whole
48775
+ * <userToken>` and `X-Asm-Auth: <dxASMToken>` — and in request bodies that carry a
48776
+ * token field (the audit record), which axios keeps as JSON text in
48777
+ * `error.config.data`. Anything that serializes a whole
48708
48778
  * error / config / headers object (`JSON.stringify`, an AxiosError's `.toJSON()`,
48709
48779
  * `console.log(err)`, or a logger that deep-prints its argument) will spill them.
48710
48780
  * These helpers strip the secrets before anything is logged or re-thrown.
@@ -48724,14 +48794,52 @@ const SENSITIVE_KEYS = new Set([
48724
48794
  'agenttoken',
48725
48795
  'accesstoken',
48726
48796
  'refreshtoken',
48797
+ 'authtoken',
48798
+ 'revoketoken',
48727
48799
  'password',
48728
48800
  'apikey',
48801
+ // Legacy (pre-v3) dx-do profile secrets.
48802
+ 'dashboardapikey',
48803
+ 'camanagementcookie',
48804
+ 'oiuserkey',
48729
48805
  'x-api-key',
48806
+ // Notification-channel write bodies (webhook auth, ServiceNow OAuth).
48807
+ 'tokenvalue',
48808
+ 'clientsecret',
48809
+ 'client_secret',
48810
+ 'certprivatekeybase64',
48730
48811
  ]);
48812
+ /**
48813
+ * Names that mark a credential where the name is data, not the object key: a
48814
+ * custom header inside a `headers` map (`X-Auth-Token`), or a name/value
48815
+ * property entry (`{ propertyName: 'ITSM_ServiceMgmt_Password', propertyValue }`
48816
+ * in a ServiceNow channel body).
48817
+ */
48818
+ const SECRET_NAME = /authorization|token|secret|password|key|cookie/i;
48731
48819
  /** Matches `Bearer <token>` anywhere in a string. */
48732
48820
  const BEARER = /Bearer\s+\S+/gi;
48821
+ /** Matches a `"key": "value"` pair in JSON text, capturing the key and separator. */
48822
+ const JSON_STRING_PAIR = /"([^"\\]+)"(\s*:\s*)"(?:[^"\\]|\\.)*"/g;
48823
+ /**
48824
+ * axios serializes a request body to a JSON string before sending, so an error's
48825
+ * `config.data` is text, not an object — and the audit record carries the user
48826
+ * token in that body (#994). JSON text is parsed and redacted by key; text that
48827
+ * does not parse (truncated, embedded in a message) has its sensitive
48828
+ * `"key": "value"` pairs masked by pattern.
48829
+ */
48733
48830
  function redactString(value) {
48734
- return value.replace(BEARER, `Bearer ${REDACTED}`);
48831
+ const trimmed = value.trimStart();
48832
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
48833
+ try {
48834
+ return JSON.stringify(redactValue(JSON.parse(value)));
48835
+ }
48836
+ catch {
48837
+ // Not JSON — fall through to the pattern scrub.
48838
+ }
48839
+ }
48840
+ return value
48841
+ .replace(BEARER, `Bearer ${REDACTED}`)
48842
+ .replace(JSON_STRING_PAIR, (pair, key, separator) => SENSITIVE_KEYS.has(key.toLowerCase()) ? `"${key}"${separator}"${REDACTED}"` : pair);
48735
48843
  }
48736
48844
  /**
48737
48845
  * Returns a deep copy of `value` with sensitive object keys masked and any
@@ -48758,18 +48866,39 @@ function redactValue(value, seen = new WeakSet()) {
48758
48866
  stack: value.stack ? redactString(value.stack) : undefined,
48759
48867
  };
48760
48868
  }
48869
+ const record = value;
48870
+ const secretProperty = typeof record['propertyName'] === 'string' && SECRET_NAME.test(record['propertyName']);
48761
48871
  const out = {};
48762
- for (const [key, entry] of Object.entries(value)) {
48763
- out[key] = SENSITIVE_KEYS.has(key.toLowerCase())
48764
- ? REDACTED
48765
- : redactValue(entry, seen);
48872
+ for (const [key, entry] of Object.entries(record)) {
48873
+ if (SENSITIVE_KEYS.has(key.toLowerCase())) {
48874
+ out[key] = REDACTED;
48875
+ }
48876
+ else if (secretProperty && key === 'propertyValue') {
48877
+ out[key] = REDACTED;
48878
+ }
48879
+ else if (key.toLowerCase() === 'headers' && entry && typeof entry === 'object') {
48880
+ out[key] = redactHeaders(entry, seen);
48881
+ }
48882
+ else {
48883
+ out[key] = redactValue(entry, seen);
48884
+ }
48885
+ }
48886
+ return out;
48887
+ }
48888
+ function redactHeaders(headers, seen) {
48889
+ if (Array.isArray(headers))
48890
+ return redactValue(headers, seen);
48891
+ const out = {};
48892
+ for (const [name, entry] of Object.entries(headers)) {
48893
+ out[name] = SECRET_NAME.test(name) ? REDACTED : redactValue(entry, seen);
48766
48894
  }
48767
48895
  return out;
48768
48896
  }
48769
48897
  /**
48770
48898
  * Strips auth tokens from an (possibly Axios) error IN PLACE and returns it, so it
48771
48899
  * stays a throwable `Error` with its stack intact but no longer carries the token
48772
- * in `config.headers`, `response.config.headers`, or the raw request header string.
48900
+ * in `config.headers`, `config.data` (the request body), their `response.config`
48901
+ * copies, or the raw request header string.
48773
48902
  * Non-error / non-axios values are returned unchanged.
48774
48903
  *
48775
48904
  * Use this at the axios boundary (a response error interceptor) so every catch,
@@ -48784,9 +48913,14 @@ function sanitizeAxiosError(err) {
48784
48913
  return err;
48785
48914
  if (e.config?.headers)
48786
48915
  e.config.headers = redactValue(e.config.headers);
48916
+ if (e.config?.data !== undefined)
48917
+ e.config.data = redactValue(e.config.data);
48787
48918
  if (e.response?.config?.headers) {
48788
48919
  e.response.config.headers = redactValue(e.response.config.headers);
48789
48920
  }
48921
+ if (e.response?.config?.data !== undefined) {
48922
+ e.response.config.data = redactValue(e.response.config.data);
48923
+ }
48790
48924
  // Node's ClientRequest keeps the raw request (incl. the Authorization line) in `_header`.
48791
48925
  if (e.request && typeof e.request._header === 'string') {
48792
48926
  e.request._header = redactString(e.request._header);
@@ -49338,6 +49472,7 @@ const AttributeExpressionSchema = v4.z.looseObject({
49338
49472
  operator: AttributeExpressionOperatorSchema.optional().describe('Comparison operator; defaults to IN'),
49339
49473
  layer: v4.z
49340
49474
  .string()
49475
+ .nullable()
49341
49476
  .optional()
49342
49477
  .describe('Restrict the expression to attributes on a specific layer (overlays the filter-level layer if both set)'),
49343
49478
  comparator: AttributeExpressionComparatorSchema.optional().describe('Value-parsing mode for ordered comparisons; only consulted by GE/GT/LE/LT'),
@@ -49381,7 +49516,7 @@ const TraversalVertexFilterSchema = v4.z.looseObject({
49381
49516
  op: v4.z.string().optional().describe('Op discriminator (ALL/NONE/AND/OR/NOT/ATTRIBUTE/LAYER/VERTEX)'),
49382
49517
  input: v4.z.lazy(() => v4.z.array(TraversalVertexFilterSchema)).optional(),
49383
49518
  expressions: v4.z.array(AttributeExpressionSchema).optional(),
49384
- layer: v4.z.string().optional(),
49519
+ layer: v4.z.string().nullable().optional(),
49385
49520
  values: v4.z.array(v4.z.string()).optional(),
49386
49521
  vertexId: v4.z.array(v4.z.number()).optional(),
49387
49522
  });
@@ -49619,6 +49754,7 @@ const TasAttributeFilterSchema = v4.z.looseObject({
49619
49754
  .describe('Attribute expressions; all must match (AND)'),
49620
49755
  layer: v4.z
49621
49756
  .string()
49757
+ .nullable()
49622
49758
  .optional()
49623
49759
  .describe('Restrict to attributes on a single layer (overlays per-expression layer)'),
49624
49760
  mode: TasAttributeFilterModeSchema.optional().describe('How vertex/edge matching propagates; defaults to VERTEX_AND_RELATED_EDGES'),
@@ -49673,17 +49809,22 @@ const TasVertexIdFilterSchema = v4.z.looseObject({
49673
49809
  * hierarchy as defined in the Service Definition).
49674
49810
  *
49675
49811
  * Toggle `excludeSubServices=true` for an exact-service-only match;
49676
- * `includeServiceHierarchy=true` includes higher-level service ancestors
49677
- * in addition to descendants.
49812
+ * `includeServiceHierarchy=true` adds the `saService` vertices themselves
49813
+ * (the named services and, unless excluded, their sub-services) to the
49814
+ * member entities. It does not add ancestors (measured 2026-10-21).
49678
49815
  */
49679
49816
  const TasServiceFilterSchema = v4.z.looseObject({
49680
49817
  op: v4.z.literal('SERVICE'),
49681
49818
  input: TasFilterLazy.optional().describe('Optional input filter; defaults to ALL'),
49682
- values: v4.z.array(v4.z.string()).optional().describe('Service names to match'),
49819
+ values: v4.z
49820
+ .array(v4.z.string())
49821
+ .optional()
49822
+ .describe('Service names to match; required by the server (missing or empty is a 400), and no wildcard'),
49683
49823
  includeServiceHierarchy: v4.z
49684
49824
  .boolean()
49685
49825
  .optional()
49686
- .describe('Include the entire service hierarchy (ancestors); defaults to false'),
49826
+ .describe('Also return the saService vertices of the matched services (named + sub-services, never ancestors); ' +
49827
+ 'the only way a direct TAS query reaches service vertices; defaults to false'),
49687
49828
  excludeSubServices: v4.z
49688
49829
  .boolean()
49689
49830
  .optional()
@@ -49936,6 +50077,7 @@ const TasCollectAttributesFilterSchema = v4.z.looseObject({
49936
50077
  .describe('Name of the vertex attribute whose values to collect (e.g. "type", "name")'),
49937
50078
  layer: v4.z
49938
50079
  .string()
50080
+ .nullable()
49939
50081
  .optional()
49940
50082
  .describe('Restrict collection to this layer; omit or null for all layers'),
49941
50083
  includeIds: v4.z
@@ -49970,6 +50112,7 @@ const TasCollectAttributeNamesFilterSchema = v4.z.looseObject({
49970
50112
  .describe('Unique key; result appears in analytics[] under this id'),
49971
50113
  layer: v4.z
49972
50114
  .string()
50115
+ .nullable()
49973
50116
  .optional()
49974
50117
  .describe('Restrict to this layer; omit or null for all layers'),
49975
50118
  });
@@ -50010,6 +50153,7 @@ const TasCollectVertexIdFilterSchema = v4.z.looseObject({
50010
50153
  .describe('Unique key; result appears in analytics[] under this id'),
50011
50154
  layer: v4.z
50012
50155
  .string()
50156
+ .nullable()
50013
50157
  .optional()
50014
50158
  .describe('Restrict to this layer; omit or null for all layers'),
50015
50159
  skipBackends: v4.z
@@ -50094,6 +50238,7 @@ const TasCollectExperienceAttributesFilterSchema = v4.z.looseObject({
50094
50238
  .describe('Attribute whose values to collect'),
50095
50239
  layer: v4.z
50096
50240
  .string()
50241
+ .nullable()
50097
50242
  .optional()
50098
50243
  .describe('Restrict to this layer; omit or null for all'),
50099
50244
  caseInsensitive: v4.z
@@ -63591,6 +63736,10 @@ exports.NASS = void 0;
63591
63736
 
63592
63737
  exports.OIAlarm = void 0;
63593
63738
  (function (OIAlarm) {
63739
+ /**
63740
+ * @deprecated Its `timeFrom`/`timeTo` are fixed when the module loads and it is a shared,
63741
+ * mutable object; build a fresh body per request instead.
63742
+ */
63594
63743
  OIAlarm.DEFAULT_SITUATIONS_REQUEST_BODY = {
63595
63744
  pageNumber: 0,
63596
63745
  pageSize: 50,
@@ -63612,6 +63761,10 @@ exports.OIAlarm = void 0;
63612
63761
  showMaintenanceAlarms: false,
63613
63762
  customFilter: {},
63614
63763
  };
63764
+ /**
63765
+ * @deprecated Its `timeFrom`/`timeTo` are fixed when the module loads and it is a shared,
63766
+ * mutable object; use {@link newAlarmSearchBody}.
63767
+ */
63615
63768
  OIAlarm.DEFAULT_ALARMS_REQUEST_BODY = {
63616
63769
  deviceNames: [],
63617
63770
  includeDeviceTypes: [],
@@ -63631,6 +63784,30 @@ exports.OIAlarm = void 0;
63631
63784
  showMaintenanceAlarms: false,
63632
63785
  customFilter: {},
63633
63786
  };
63787
+ /** A fresh `oi/v2/api/alarms/_search` body for `[timeFrom, timeTo]`, first page, nothing filtered. */
63788
+ function newAlarmSearchBody(timeFrom, timeTo, overrides = {}) {
63789
+ return {
63790
+ deviceNames: [],
63791
+ includeDeviceTypes: [],
63792
+ excludeDeviceTypes: [],
63793
+ groups: [],
63794
+ like: '',
63795
+ timeFrom,
63796
+ timeTo,
63797
+ pageNumber: 0,
63798
+ pageSize: 50,
63799
+ services: [],
63800
+ includeSeverity: [],
63801
+ allOtherSeverity: false,
63802
+ includeAlarmTypes: [],
63803
+ excludeAlarmTypes: [],
63804
+ includeClosedAlarms: false,
63805
+ showMaintenanceAlarms: false,
63806
+ customFilter: {},
63807
+ ...overrides,
63808
+ };
63809
+ }
63810
+ OIAlarm.newAlarmSearchBody = newAlarmSearchBody;
63634
63811
  })(exports.OIAlarm || (exports.OIAlarm = {}));
63635
63812
 
63636
63813
  exports.CreateServices = void 0;
@@ -64169,7 +64346,7 @@ exports.OIService = void 0;
64169
64346
  OIService.DEFAULT_SERVICE_REQUEST_PROJECTION_FILTER = ["maintenance", "availability_lastday", "availability", "health", "extId", "name", "risk", "trend", "healthBucket"];
64170
64347
  OIService.TYPICAL_SERVICE_REQUEST_PROJECTION_FILTER = ["rollupFilteredAlarmCount", "situationCount", "availability", "filteredParent", "availability_lastday",
64171
64348
  "immediateFilteredChildren", "immediateFilterChildrenCount", "health", "extId", "location", "maintenance",
64172
- "name", "risk", "status", "tags", "serviceMetricGroups", "healthBucket"];
64349
+ "name", "risk", "status", "tags", "serviceMetricGroups", "healthBucket", "customProperties"];
64173
64350
  /** @internal */
64174
64351
  OIService.DEFAULT_SERVICE_REQUEST_BODY = {
64175
64352
  "time": DateTime.now().toMillis(),
@@ -70600,7 +70777,283 @@ class AgentService {
70600
70777
  }
70601
70778
  }
70602
70779
 
70603
- var DEFAULT_ALARMS_REQUEST_BODY$1 = exports.OIAlarm.DEFAULT_ALARMS_REQUEST_BODY;
70780
+ /**
70781
+ * Most alarms one `oi/v2/api/alarms/_search` request returns, whatever
70782
+ * `pageSize` asks for (1001, 2000 and 5000 all answered 1000; measured on
70783
+ * demo-dev 2026-10-22). `pageNumber` > 0 answers an empty page, so a range
70784
+ * holding more alarms can only be read by splitting it.
70785
+ */
70786
+ const ALARM_SEARCH_PAGE_CAP = 1000;
70787
+ /**
70788
+ * A complete read of an alarm range was not possible. Thrown instead of
70789
+ * returning a partial set, so a caller never mistakes a short list for the
70790
+ * whole range.
70791
+ */
70792
+ class IncompleteAlarmSearchError extends Error {
70793
+ reason;
70794
+ expected;
70795
+ retrieved;
70796
+ constructor(reason, expected, retrieved, detail) {
70797
+ super(`Alarm search incomplete (${reason}): ${detail}`);
70798
+ this.reason = reason;
70799
+ this.expected = expected;
70800
+ this.retrieved = retrieved;
70801
+ this.name = 'IncompleteAlarmSearchError';
70802
+ }
70803
+ }
70804
+ const updatedAt = (alarm) => Number(alarm.lastUpdateTime ?? 0);
70805
+ /**
70806
+ * Reads every alarm in `[from, to]`, splitting the range until each window
70807
+ * fits in one response.
70808
+ *
70809
+ * A window holds every alarm whose lifetime (`timeOrigin` to `closedTime`, or
70810
+ * now) overlaps it, so windows overlap and their counts do not add up; their
70811
+ * union is the range (measured: 448 of 448, 300 of them in both halves). The
70812
+ * merge keys on `alarmId` and keeps the copy with the later `lastUpdateTime`.
70813
+ *
70814
+ * Fails with {@link IncompleteAlarmSearchError} instead of returning less:
70815
+ * - `unsplittable` — more alarms than one response holds are present at a
70816
+ * single instant (every window containing it is over the cap);
70817
+ * - `changed` — the range's count moved during the read, or the merged set
70818
+ * does not match it (alarms arriving or backdated into the range);
70819
+ * - `request-budget` — `maxRequests` ran out.
70820
+ */
70821
+ async function searchAlarmWindows(search, from, to, options = {}) {
70822
+ const concurrency = options.concurrency ?? 4;
70823
+ const maxRequests = options.maxRequests ?? 2000;
70824
+ const log = options.log ?? new Logging.NullSimpleLog();
70825
+ const alarms = new Map();
70826
+ let requests = 0;
70827
+ let windows = 0;
70828
+ let expected = 0;
70829
+ const merge = (page) => {
70830
+ for (const alarm of page.alarms) {
70831
+ const seen = alarms.get(alarm.alarmId);
70832
+ if (!seen || updatedAt(alarm) > updatedAt(seen))
70833
+ alarms.set(alarm.alarmId, alarm);
70834
+ }
70835
+ };
70836
+ const complete = (page) => page.count <= page.alarms.length;
70837
+ const request = async (w) => {
70838
+ if (requests >= maxRequests) {
70839
+ throw new IncompleteAlarmSearchError('request-budget', expected, alarms.size, `${maxRequests} requests made, ${alarms.size} of ${expected} alarms read`);
70840
+ }
70841
+ requests++;
70842
+ return search(w.from, w.to);
70843
+ };
70844
+ const first = await request({ from, to });
70845
+ expected = first.count;
70846
+ if (complete(first)) {
70847
+ merge(first);
70848
+ return { alarms, expected, requests, windows: 1 };
70849
+ }
70850
+ log.info(`${expected} alarms in range; reading it in windows of at most ${ALARM_SEARCH_PAGE_CAP}`);
70851
+ const pending = [{ from, to }];
70852
+ const split = (w) => {
70853
+ const mid = Math.floor((w.from + w.to) / 2);
70854
+ return [
70855
+ { from: w.from, to: mid },
70856
+ { from: mid, to: w.to },
70857
+ ];
70858
+ };
70859
+ const readWindow = async (w) => {
70860
+ if (w.to - w.from <= 1) {
70861
+ const page = await request(w);
70862
+ if (complete(page)) {
70863
+ merge(page);
70864
+ windows++;
70865
+ return [];
70866
+ }
70867
+ throw new IncompleteAlarmSearchError('unsplittable', expected, alarms.size, `${page.count} alarms are present at ${new Date(w.from).toISOString()}; ` +
70868
+ `one response holds at most ${page.alarms.length}`);
70869
+ }
70870
+ const page = await request(w);
70871
+ if (complete(page)) {
70872
+ merge(page);
70873
+ windows++;
70874
+ return [];
70875
+ }
70876
+ const mid = Math.floor((w.from + w.to) / 2);
70877
+ const instant = await request({ from: mid, to: mid + 1 });
70878
+ if (!complete(instant)) {
70879
+ throw new IncompleteAlarmSearchError('unsplittable', expected, alarms.size, `${instant.count} alarms are present at ${new Date(mid).toISOString()}; ` +
70880
+ `one response holds at most ${instant.alarms.length}`);
70881
+ }
70882
+ return split(w);
70883
+ };
70884
+ // Split the root once without re-reading it.
70885
+ pending.splice(0, 1, ...split({ from, to }));
70886
+ while (pending.length > 0) {
70887
+ const batch = pending.splice(0, concurrency);
70888
+ const next = await Promise.all(batch.map(readWindow));
70889
+ pending.push(...next.flat());
70890
+ }
70891
+ const last = await request({ from, to });
70892
+ if (last.count !== expected || alarms.size !== expected) {
70893
+ throw new IncompleteAlarmSearchError('changed', expected, alarms.size, `the range held ${expected} alarms at the start, ${last.count} at the end, ` +
70894
+ `and ${alarms.size} were read; alarms arrived or changed during the read`);
70895
+ }
70896
+ log.info(`Read ${alarms.size} alarms in ${windows} windows (${requests} requests)`);
70897
+ return { alarms, expected, requests, windows };
70898
+ }
70899
+
70900
+ /**
70901
+ * Most records one analytics query can reach: `from + size` over 10000 is
70902
+ * rejected ("Result window is too large"), and a count above it comes back as
70903
+ * a lower bound (`relation: gte`).
70904
+ */
70905
+ const ALARM_RECORD_WINDOW_CAP = 10_000;
70906
+ const ALARM_RECORD_PAGE_SIZE = 1000;
70907
+ /** An instant as the index's query syntax wants it: whole seconds, `+0000` (`Z` matches nothing). */
70908
+ const alarmRecordTime = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, '+0000');
70909
+ /** Epoch ms of an index time such as `2026-10-22T06:17:39+0000`. */
70910
+ const parseAlarmRecordTime = (value) => Date.parse(value.replace(/([+-]\d{2})(\d{2})$/, '$1:$2'));
70911
+ const windowQuery = (segment, from, to) => {
70912
+ const range = `${segment.field}:[${alarmRecordTime(from)} TO ${alarmRecordTime(to)}}`;
70913
+ return segment.extra ? `${range} AND (${segment.extra})` : range;
70914
+ };
70915
+ /**
70916
+ * Streams every alarm record that `match` selects in `[from, to)`, in open-time
70917
+ * order, reading the analytics index in windows of at most
70918
+ * {@link ALARM_RECORD_WINDOW_CAP} records.
70919
+ *
70920
+ * First the range is planned: count-only requests split it until each window
70921
+ * holds at most the cap, which gives the exact total (the index itself reports
70922
+ * any total over 10000 as "at least 10000"). Then each window is paged with a
70923
+ * fixed sort and checked: the records read must be exactly its planned count. Otherwise it throws
70924
+ * {@link IncompleteAlarmSearchError} rather than yielding a partial export:
70925
+ * - `changed` — the window's count or contents moved during the read;
70926
+ * - `unsplittable` — more than 10000 records share one second;
70927
+ * - `request-budget` — `maxRequests` ran out.
70928
+ * Records already yielded stay valid; the error says where the export stopped.
70929
+ */
70930
+ async function* exportAlarmRecords(source, from, to, match, options = {}) {
70931
+ const maxRequests = options.maxRequests ?? 20_000;
70932
+ const windowCap = options.windowCap ?? ALARM_RECORD_WINDOW_CAP;
70933
+ const pageSize = options.pageSize ?? ALARM_RECORD_PAGE_SIZE;
70934
+ const log = options.log ?? new Logging.NullSimpleLog();
70935
+ const start = Math.floor(from / 1000) * 1000;
70936
+ const end = Math.ceil(to / 1000) * 1000;
70937
+ let requests = 0;
70938
+ let exported = 0;
70939
+ const call = async (fn) => {
70940
+ if (requests >= maxRequests) {
70941
+ throw new IncompleteAlarmSearchError('request-budget', exported, exported, `${maxRequests} requests made; ${exported} alarms exported before stopping`);
70942
+ }
70943
+ requests++;
70944
+ return fn();
70945
+ };
70946
+ const segments = [];
70947
+ if (match === 'opened')
70948
+ segments.push({ field: 'startTime', from: start, to: end });
70949
+ if (match === 'closed')
70950
+ segments.push({ field: 'closedTime', from: start, to: end });
70951
+ if (match === 'active') {
70952
+ segments.push({ field: 'startTime', from: start, to: end });
70953
+ // Opened earlier and still open at `from`: closed after it, or not closed.
70954
+ const stillOpen = `closedTime:{${alarmRecordTime(start)} TO *] OR (*:* -_exists_:closedTime)`;
70955
+ const earlier = `startTime:[* TO ${alarmRecordTime(start)}} AND (${stillOpen})`;
70956
+ const [first] = await call(() => source.page(earlier, 0, 1));
70957
+ if (first) {
70958
+ const earliest = Math.floor(parseAlarmRecordTime(first.startTime) / 1000) * 1000;
70959
+ segments.unshift({ field: 'startTime', from: earliest, to: start, extra: stillOpen });
70960
+ }
70961
+ }
70962
+ const startedAt = Date.now();
70963
+ // Plan: split until every window's count is exact and within the cap.
70964
+ const plan = async (segment, a, b, out) => {
70965
+ const count = await call(() => source.count(windowQuery(segment, a, b)));
70966
+ if (count.exact && count.total <= windowCap) {
70967
+ if (count.total > 0)
70968
+ out.push({ segment, from: a, to: b, count: count.total });
70969
+ return;
70970
+ }
70971
+ if (b - a <= 1000) {
70972
+ throw new IncompleteAlarmSearchError('unsplittable', count.total, 0, `more than ${windowCap} alarms at ${alarmRecordTime(a)}; nothing was exported`);
70973
+ }
70974
+ const mid = a + Math.floor((b - a) / 2000) * 1000;
70975
+ await plan(segment, a, mid, out);
70976
+ await plan(segment, mid, b, out);
70977
+ };
70978
+ const windows = [];
70979
+ for (const segment of segments) {
70980
+ if (segment.to > segment.from)
70981
+ await plan(segment, segment.from, segment.to, windows);
70982
+ }
70983
+ const total = windows.reduce((sum, w) => sum + w.count, 0);
70984
+ options.onPlan?.({ total, windows: windows.length, elapsedMs: Date.now() - startedAt });
70985
+ // Read: page each window with a fixed sort; it must still hold its planned count.
70986
+ for (const [i, w] of windows.entries()) {
70987
+ const query = windowQuery(w.segment, w.from, w.to);
70988
+ const records = [];
70989
+ const ids = new Set();
70990
+ for (let offset = 0; offset < w.count; offset += pageSize) {
70991
+ const page = await call(() => source.page(query, offset, pageSize));
70992
+ if (page.length === 0)
70993
+ break;
70994
+ for (const record of page) {
70995
+ if (!ids.has(record.alarm_unique_id)) {
70996
+ ids.add(record.alarm_unique_id);
70997
+ records.push(record);
70998
+ }
70999
+ }
71000
+ }
71001
+ const recount = await call(() => source.count(query));
71002
+ if (ids.size !== w.count || recount.total !== w.count) {
71003
+ throw new IncompleteAlarmSearchError('changed', total, exported, `window ${alarmRecordTime(w.from)} – ${alarmRecordTime(w.to)} held ${w.count} alarms when planned, ` +
71004
+ `${recount.total} after reading, and ${ids.size} distinct were read; ` +
71005
+ `${exported} of ${total} exported before it. Alarms changed during the read — retry, or end the range further in the past`);
71006
+ }
71007
+ for (const record of records) {
71008
+ exported++;
71009
+ yield record;
71010
+ }
71011
+ options.onWindow?.({
71012
+ from: w.from,
71013
+ to: w.to,
71014
+ records: records.length,
71015
+ index: i + 1,
71016
+ windows: windows.length,
71017
+ exported,
71018
+ total,
71019
+ elapsedMs: Date.now() - startedAt,
71020
+ });
71021
+ }
71022
+ log.info(`Exported ${exported} alarms (${requests} requests)`);
71023
+ }
71024
+
71025
+ /**
71026
+ * Events per `oi/v2/api/alarms/lifecycle/_search` request. The endpoint
71027
+ * reports `totalCount` and pages exactly: for an alarm with 54 events and a
71028
+ * situation with 69, pages of 10 or 20 equalled one read of 1000, same set
71029
+ * and order (THE_LABORATORY and demo-dev, 2026-10-22).
71030
+ */
71031
+ const LIFECYCLE_PAGE_SIZE = 1000;
71032
+ /**
71033
+ * Reads every page of a lifecycle (alarm or situation) until the server's
71034
+ * `totalCount` is reached. `totalCount` is returned as the server reported
71035
+ * it; if a page comes back empty first, the result holds fewer events and a
71036
+ * warning is logged, so a short read stays visible.
71037
+ */
71038
+ async function readLifecyclePages(fetchPage, label, log) {
71039
+ const events = [];
71040
+ let totalCount = '0';
71041
+ for (let pageNumber = 0;; pageNumber++) {
71042
+ const page = await fetchPage(pageNumber, LIFECYCLE_PAGE_SIZE);
71043
+ totalCount = page.totalCount ?? totalCount;
71044
+ const pageEvents = page.lifecycle_events ?? [];
71045
+ events.push(...pageEvents);
71046
+ if (events.length >= Number(totalCount))
71047
+ break;
71048
+ if (pageEvents.length === 0) {
71049
+ log.warn(`Lifecycle of ${label} stopped at ${events.length} of ${totalCount} events: page ${pageNumber} was empty`);
71050
+ break;
71051
+ }
71052
+ }
71053
+ return { totalCount, lifecycle_events: events };
71054
+ }
71055
+
71056
+ var newAlarmSearchBody = exports.OIAlarm.newAlarmSearchBody;
70604
71057
  /**
70605
71058
  * Service for OI alarms: get, search, assign, acknowledge, clear, lifecycle,
70606
71059
  * enrichment rules, alarm queues, and related alarms.
@@ -70633,11 +71086,7 @@ class AlarmService {
70633
71086
  */
70634
71087
  async findAlarm(alarmId, lookbackMs, requestOverrides = {}) {
70635
71088
  const now = Date.now();
70636
- const body = {
70637
- ...DEFAULT_ALARMS_REQUEST_BODY$1,
70638
- timeFrom: now - lookbackMs,
70639
- timeTo: now,
70640
- pageNumber: 0,
71089
+ const body = newAlarmSearchBody(now - lookbackMs, now, {
70641
71090
  pageSize: 10,
70642
71091
  includeClosedAlarms: true,
70643
71092
  customFilter: {
@@ -70658,30 +71107,20 @@ class AlarmService {
70658
71107
  ],
70659
71108
  },
70660
71109
  },
70661
- };
71110
+ });
70662
71111
  const response = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', body, undefined, undefined, requestOverrides);
70663
71112
  return (response.alarms ?? []).find((alarm) => alarm.alarmId === alarmId);
70664
71113
  }
70665
- /** Returns the overview (first alarm in a custom-filter search) for an alarm ID. */
71114
+ /**
71115
+ * Returns an open alarm of the last 30 days by its ID (the payload a channel
71116
+ * notification sends).
71117
+ *
71118
+ * @throws Error when no open alarm has that ID.
71119
+ */
70666
71120
  async getAlarmOverview(alarmId) {
70667
- const singleAlarmQuery = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', {
70668
- deviceNames: [],
70669
- includeDeviceTypes: [],
70670
- excludeDeviceTypes: [],
70671
- groups: [],
70672
- like: '',
70673
- timeFrom: Date.now(),
70674
- timeTo: Date.now() - 30 * 24 * 60 * 60 * 1000,
70675
- pageNumber: 0,
70676
- pageSize: 50,
70677
- services: [],
70678
- includeSeverity: [],
70679
- allOtherSeverity: false,
71121
+ const now = Date.now();
71122
+ const singleAlarmQuery = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', newAlarmSearchBody(now - 30 * 24 * 60 * 60 * 1000, now, {
70680
71123
  sortCol: '',
70681
- includeAlarmTypes: [],
70682
- excludeAlarmTypes: [],
70683
- includeClosedAlarms: false,
70684
- showMaintenanceAlarms: false,
70685
71124
  showAlarmsPartOfSituations: false,
70686
71125
  customFilter: {
70687
71126
  and: {
@@ -70701,13 +71140,12 @@ class AlarmService {
70701
71140
  ],
70702
71141
  },
70703
71142
  },
70704
- });
70705
- if (singleAlarmQuery.alarmCount) {
70706
- return singleAlarmQuery.alarms[0];
70707
- }
70708
- else {
70709
- throw new Error('Bad Alarm Query');
71143
+ }));
71144
+ const alarm = singleAlarmQuery.alarms?.[0];
71145
+ if (Number(singleAlarmQuery.alarmCount) > 0 && alarm) {
71146
+ return alarm;
70710
71147
  }
71148
+ throw new Error(`No open alarm ${alarmId} in the last 30 days`);
70711
71149
  }
70712
71150
  /** Sends a notification for an alarm to the specified channel with optional template/locale. */
70713
71151
  async triggerNotification(alarmId, notificationChannelName, template = '', locale = 'en-US') {
@@ -70824,12 +71262,20 @@ class AlarmService {
70824
71262
  this.simpleLog.debug('update request body', JSON.stringify(body, null, 2));
70825
71263
  return this.dxSaaSService.tenantPost('jarvis/v2/ingestion', body, {}, headers);
70826
71264
  }
70827
- /** Returns the lifecycle event history for a given alarm ID. */
71265
+ /**
71266
+ * Returns an alarm's whole lifecycle event history, newest first.
71267
+ *
71268
+ * @remarks Reads pages of 1000 until the server's `totalCount` is reached
71269
+ * (it used to ask for 20 and stop, dropping the oldest events, "Alarm
71270
+ * Opened" first). `totalCount` is returned as the server reported it; if a
71271
+ * page comes back empty early, the result holds fewer events and a warning
71272
+ * is logged.
71273
+ */
70828
71274
  async getAlarmLifeCycle(alarmId) {
70829
- const alarmLifeCycleRequestBody = {
70830
- alarmId: alarmId,
70831
- pageSize: '20',
70832
- pageNumber: '0',
71275
+ return readLifecyclePages((pageNumber, pageSize) => this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', {
71276
+ alarmId,
71277
+ pageSize: String(pageSize),
71278
+ pageNumber: String(pageNumber),
70833
71279
  sortCol: 'timestamp:desc',
70834
71280
  excludeFields: [
70835
71281
  'isolation_view_link',
@@ -70837,38 +71283,101 @@ class AlarmService {
70837
71283
  'alert_definition_link',
70838
71284
  'occurrence',
70839
71285
  ],
70840
- };
70841
- return this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', alarmLifeCycleRequestBody);
71286
+ }), `alarm ${alarmId}`, this.simpleLog);
70842
71287
  }
70843
- /** Returns all alarms within a time range, with optional type/closed/filter params. */
70844
- async getAlarms(startTime, endTime, includedAlarmTypes = [], includeClosed = false, pageSize = 100, alarmFilter) {
70845
- const alarmRequestBody = {
70846
- ...DEFAULT_ALARMS_REQUEST_BODY$1,
70847
- };
70848
- alarmRequestBody.timeFrom = startTime.toMillis();
70849
- alarmRequestBody.timeTo = endTime.toMillis();
70850
- const alarmIdMap = new Map();
70851
- alarmRequestBody.includeAlarmTypes = includedAlarmTypes;
70852
- alarmRequestBody.includeClosedAlarms = includeClosed;
70853
- alarmRequestBody.pageSize = pageSize;
70854
- if (alarmFilter) {
70855
- alarmRequestBody.customFilter = alarmFilter;
70856
- }
70857
- this.simpleLog.info(`Retrieving first page of alarms with page size ${pageSize}`);
70858
- const alarmFirstPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
70859
- function mapAlarms(alarms) {
70860
- alarms.forEach((alarm) => {
70861
- if (!alarmIdMap.has(alarm.alarmId)) {
70862
- alarmIdMap.set(alarm.alarmId, alarm);
71288
+ /**
71289
+ * One alarm search over `[startTime, endTime]`: the exact number of alarms
71290
+ * in the range and the first `pageSize` of them (at most
71291
+ * {@link ALARM_SEARCH_PAGE_CAP}, whatever is asked). Use it where a sample
71292
+ * plus the true total is enough; {@link getAlarms} reads the whole range.
71293
+ */
71294
+ async searchAlarmPage(startTime, endTime, includedAlarmTypes = [], includeClosed = false, pageSize = ALARM_SEARCH_PAGE_CAP, alarmFilter) {
71295
+ return this.searchPage(startTime.toMillis(), endTime.toMillis(), {
71296
+ includedAlarmTypes,
71297
+ includeClosed,
71298
+ pageSize,
71299
+ alarmFilter,
71300
+ });
71301
+ }
71302
+ /**
71303
+ * Returns every alarm in `[startTime, endTime]`, keyed by `alarmId`.
71304
+ *
71305
+ * One search returns at most {@link ALARM_SEARCH_PAGE_CAP} alarms and cannot
71306
+ * be paged, so a larger range is read in windows and merged
71307
+ * (`searchAlarmWindows`). A window holds every alarm whose lifetime overlaps
71308
+ * it, so long-open alarms appear in all of them; the merge keeps one copy.
71309
+ *
71310
+ * @param pageSize - Ignored: each request asks for the server's
71311
+ * maximum. Kept for signature compatibility.
71312
+ * @throws IncompleteAlarmSearchError when the whole range cannot be read:
71313
+ * more alarms than one response holds at a single instant, alarms arriving
71314
+ * or backdated into the range during the read, or the request budget spent.
71315
+ * A partial set is never returned.
71316
+ */
71317
+ async getAlarms(startTime, endTime, includedAlarmTypes = [], includeClosed = false,
71318
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
71319
+ pageSize = 100, alarmFilter, options = {}) {
71320
+ const result = await searchAlarmWindows((from, to) => this.searchPage(from, to, {
71321
+ includedAlarmTypes,
71322
+ includeClosed,
71323
+ pageSize: ALARM_SEARCH_PAGE_CAP,
71324
+ alarmFilter,
71325
+ }), startTime.toMillis(), endTime.toMillis(), { log: this.simpleLog, ...options });
71326
+ this.simpleLog.info(`Retrieved ${result.alarms.size} of ${result.expected} alarms`);
71327
+ return result.alarms;
71328
+ }
71329
+ /**
71330
+ * Streams every alarm that `match` selects in `[startTime, endTime)` from the
71331
+ * alarms analytics index (`GET oi/v2/aoanalytics/alarms/alarms_all/_search`),
71332
+ * in open-time order — for exports over long ranges.
71333
+ *
71334
+ * Unlike {@link getAlarms} (the alarm search: every alarm active in the range,
71335
+ * 1000 per request), the index filters on the open or close time directly
71336
+ * and allows windows of 10000, so alarms that stay open do not crowd the
71337
+ * windows. Records are the stored documents (see `AlarmRecordSchema`).
71338
+ *
71339
+ * @remarks Responses are validated, not thrown on. The export throws
71340
+ * `IncompleteAlarmSearchError` when a window changes while it is read or
71341
+ * cannot be split; records already yielded are complete and in order.
71342
+ */
71343
+ exportAlarmRecords(startTime, endTime, match = 'opened', options = {}) {
71344
+ // One short warning per distinct mismatch, not one issue dump per page.
71345
+ const warned = new Set();
71346
+ const search = async (params) => {
71347
+ const raw = await this.dxSaaSService.oiGet('oi/v2/aoanalytics/alarms/alarms_all/_search', params);
71348
+ const parsed = AlarmRecordSearchResponseSchema.safeParse(raw);
71349
+ if (!parsed.success) {
71350
+ const fields = [
71351
+ ...new Set(parsed.error.issues.map((issue) => `${issue.path.map((p) => (typeof p === 'number' ? '*' : String(p))).join('.')} (${issue.message})`)),
71352
+ ].join('; ');
71353
+ if (!warned.has(fields)) {
71354
+ warned.add(fields);
71355
+ this.simpleLog.warn(`AlarmRecordSearchResponse validation warning: ${fields}`);
70863
71356
  }
70864
- });
70865
- }
70866
- this.simpleLog.info(`Retrieving ${alarmFirstPage.alarmCount} alarms`);
70867
- alarmRequestBody.pageSize = alarmFirstPage.alarmCount;
70868
- const alarmAllPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
70869
- this.simpleLog.info(`Retrieved ${alarmAllPage.alarms.length} of ${alarmFirstPage.alarmCount} alarms`);
70870
- mapAlarms(alarmAllPage.alarms);
70871
- return alarmIdMap;
71357
+ }
71358
+ return raw;
71359
+ };
71360
+ const source = {
71361
+ count: async (q) => {
71362
+ const total = (await search({ q, size: 0 })).hits?.total;
71363
+ return { total: total?.value ?? 0, exact: total?.relation === 'eq' };
71364
+ },
71365
+ page: async (q, from, size) => ((await search({ q, from, size, sort: 'startTime:asc,alarm_unique_id:asc' })).hits?.hits ?? []).map((hit) => hit._source),
71366
+ };
71367
+ return exportAlarmRecords(source, startTime.toMillis(), endTime.toMillis(), match, {
71368
+ log: this.simpleLog,
71369
+ ...options,
71370
+ });
71371
+ }
71372
+ async searchPage(timeFrom, timeTo, query) {
71373
+ const body = newAlarmSearchBody(timeFrom, timeTo, {
71374
+ includeAlarmTypes: query.includedAlarmTypes,
71375
+ includeClosedAlarms: query.includeClosed,
71376
+ pageSize: Math.min(Math.max(query.pageSize, 1), ALARM_SEARCH_PAGE_CAP),
71377
+ ...(query.alarmFilter ? { customFilter: query.alarmFilter } : {}),
71378
+ });
71379
+ const response = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', body);
71380
+ return { count: Number(response.alarmCount ?? 0), alarms: response.alarms ?? [] };
70872
71381
  }
70873
71382
  /**
70874
71383
  * Lists every alarm enrichment rule of the tenant
@@ -80690,7 +81199,6 @@ class DxSaasService {
80690
81199
  }
80691
81200
  }
80692
81201
 
80693
- var DEFAULT_ALARMS_REQUEST_BODY = exports.OIAlarm.DEFAULT_ALARMS_REQUEST_BODY;
80694
81202
  var DEFAULT_SITUATIONS_REQUEST_BODY = exports.OIAlarm.DEFAULT_SITUATIONS_REQUEST_BODY;
80695
81203
  /**
80696
81204
  * Service for OI (Operations Intelligence) read operations: services, situations,
@@ -80698,9 +81206,11 @@ var DEFAULT_SITUATIONS_REQUEST_BODY = exports.OIAlarm.DEFAULT_SITUATIONS_REQUEST
80698
81206
  */
80699
81207
  class DxoiService {
80700
81208
  dxSaaSService;
81209
+ alarms;
80701
81210
  /** @param dxSaaSService - DX SaaS HTTP client for OI endpoints */
80702
81211
  constructor(dxSaaSService) {
80703
81212
  this.dxSaaSService = dxSaaSService;
81213
+ this.alarms = new AlarmService(dxSaaSService);
80704
81214
  }
80705
81215
  /** Returns top-level OI services using the default service request body. */
80706
81216
  getServices() {
@@ -80709,9 +81219,11 @@ class DxoiService {
80709
81219
  }
80710
81220
  /** Returns cluster alarms (situations) within the given time range. */
80711
81221
  async getSituations(startTime, endTime) {
80712
- const alarmRequestBody = DEFAULT_SITUATIONS_REQUEST_BODY;
80713
- alarmRequestBody.timeFrom = startTime.toMillis();
80714
- alarmRequestBody.timeTo = endTime.toMillis();
81222
+ const alarmRequestBody = {
81223
+ ...DEFAULT_SITUATIONS_REQUEST_BODY,
81224
+ timeFrom: startTime.toMillis(),
81225
+ timeTo: endTime.toMillis(),
81226
+ };
80715
81227
  return this.dxSaaSService.oiPost('oi/v2/api/clusteralarms/_search', alarmRequestBody);
80716
81228
  }
80717
81229
  /** Returns the entity-detail attributes for a given entity external ID. */
@@ -80720,51 +81232,28 @@ class DxoiService {
80720
81232
  externalId: entityExternalId,
80721
81233
  });
80722
81234
  }
80723
- /** Returns a single alarm by its ID. */
81235
+ /**
81236
+ * Returns a single alarm by its ID.
81237
+ * @deprecated Use `AlarmService.getAlarm` (`ServiceMonolith.dxAlarmService`).
81238
+ */
80724
81239
  async getAlarm(alarmId) {
80725
- return this.dxSaaSService.oiGet('oi/v2/api/alarms/_search', {
80726
- alarmId: alarmId,
80727
- });
81240
+ return this.alarms.getAlarm(alarmId);
80728
81241
  }
80729
- /** Returns the lifecycle event history for a given alarm ID. */
81242
+ /**
81243
+ * Returns the lifecycle event history for a given alarm ID.
81244
+ * @deprecated Use `AlarmService.getAlarmLifeCycle` (`ServiceMonolith.dxAlarmService`).
81245
+ */
80730
81246
  async getAlarmLifeCycle(alarmId) {
80731
- const alarmLifeCycleRequestBody = {
80732
- alarmId: alarmId,
80733
- pageSize: '20',
80734
- pageNumber: '0',
80735
- sortCol: 'timestamp:desc',
80736
- excludeFields: [
80737
- 'isolation_view_link',
80738
- 'metric_view_link',
80739
- 'alert_definition_link',
80740
- 'occurrence',
80741
- ],
80742
- };
80743
- return this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', alarmLifeCycleRequestBody);
81247
+ return this.alarms.getAlarmLifeCycle(alarmId);
80744
81248
  }
80745
- /** Returns all alarms in a time range, paginating until the full count is fetched. */
81249
+ /**
81250
+ * Returns every open alarm in a time range.
81251
+ * @deprecated Use `AlarmService.getAlarms`, which this now calls: it reads
81252
+ * ranges over 1000 alarms in windows and throws `IncompleteAlarmSearchError`
81253
+ * instead of returning a partial set (the old page loop could not end).
81254
+ */
80746
81255
  async getAlarms(startTime, endTime) {
80747
- const alarmRequestBody = DEFAULT_ALARMS_REQUEST_BODY;
80748
- alarmRequestBody.timeFrom = startTime.toMillis();
80749
- alarmRequestBody.timeTo = endTime.toMillis();
80750
- const alarmIdMap = new Map();
80751
- const alarmFirstPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
80752
- function mapAlarms(alarms) {
80753
- alarms.forEach((alarm) => {
80754
- if (!alarmIdMap.has(alarm.alarmId)) {
80755
- alarmIdMap.set(alarm.alarmId, alarm);
80756
- }
80757
- });
80758
- }
80759
- mapAlarms(alarmFirstPage.alarms);
80760
- let currentAlarmPage = 1;
80761
- while (alarmIdMap.size < Number.parseInt(alarmFirstPage.alarmCount)) {
80762
- alarmRequestBody.pageNumber = currentAlarmPage;
80763
- const alarmNextPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
80764
- mapAlarms(alarmNextPage.alarms);
80765
- currentAlarmPage++;
80766
- }
80767
- return alarmIdMap;
81256
+ return this.alarms.getAlarms(startTime, endTime);
80768
81257
  }
80769
81258
  }
80770
81259
 
@@ -87539,55 +88028,48 @@ class ServiceService {
87539
88028
  }
87540
88029
  throw new Error(`No Service with name '${serviceName}' Found`);
87541
88030
  }
87542
- /** Returns paginated top-level (grouped) services up to `maxRequests` pages. */
87543
- async getTopLevelServices(pageSize = 100, maxRequests = 20) {
87544
- const returnServices = new Array();
87545
- let totalRequests = 0;
87546
- this.log.info(`Making initial request with pageSize=${pageSize}`);
87547
- const currentRequestBody = this.createParentServiceRequestBody(pageSize);
87548
- return this.dxSaaSService
87549
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87550
- .then(async (response) => {
87551
- totalRequests = 1;
87552
- returnServices.push(...response.services);
87553
- while (response.groupedCnt > returnServices.length ||
87554
- totalRequests > maxRequests) {
87555
- totalRequests++;
87556
- currentRequestBody.pageNum++;
87557
- this.log.info('Retrieving Page initial request with pageSize=100');
87558
- await this.dxSaaSService
87559
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87560
- .then(async (response) => {
87561
- returnServices.push(...response.services);
87562
- });
87563
- }
87564
- return returnServices;
87565
- });
88031
+ /**
88032
+ * Returns the top-level (grouped) services, every page of them.
88033
+ *
88034
+ * @param pageSize - Services per request.
88035
+ * @param maxRequests - Optional cap on the number of requests; omitted = until `groupedCnt` is reached.
88036
+ * @remarks Stops early on an empty page; a short result (cap or empty page) is logged as a warning.
88037
+ */
88038
+ async getTopLevelServices(pageSize = 100, maxRequests) {
88039
+ return this.fetchServicePages(this.createParentServiceRequestBody(pageSize), (response) => response.groupedCnt, maxRequests);
87566
88040
  }
87567
- /** Returns all services (ungrouped) paginating up to `maxRequests` pages. */
87568
- async getAllServices(pageSize = 100, maxRequests = 10) {
87569
- const returnServices = new Array();
87570
- let totalRequests = 0;
87571
- this.log.info(`Making initial request with pageSize=${pageSize}`);
87572
- const currentRequestBody = this.createAllServiceRequestBody(pageSize);
87573
- return this.dxSaaSService
87574
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87575
- .then(async (response) => {
87576
- totalRequests = 1;
87577
- returnServices.push(...response.services);
87578
- while (response.totalCnt > returnServices.length ||
87579
- totalRequests > maxRequests) {
87580
- totalRequests++;
87581
- currentRequestBody.pageNum++;
87582
- this.log.info('Retrieving Page initial request with pageSize=100');
87583
- await this.dxSaaSService
87584
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87585
- .then(async (response) => {
87586
- returnServices.push(...response.services);
87587
- });
88041
+ /**
88042
+ * Returns all services (ungrouped), every page of them.
88043
+ *
88044
+ * @param pageSize - Services per request.
88045
+ * @param maxRequests - Optional cap on the number of requests; omitted = until `totalCnt` is reached.
88046
+ * @remarks Stops early on an empty page; a short result (cap or empty page) is logged as a warning.
88047
+ */
88048
+ async getAllServices(pageSize = 100, maxRequests) {
88049
+ return this.fetchServicePages(this.createAllServiceRequestBody(pageSize), (response) => response.totalCnt, maxRequests);
88050
+ }
88051
+ async fetchServicePages(body, expectedCount, maxRequests) {
88052
+ this.log.info(`Requesting services with pageSize=${body.pageSize}`);
88053
+ const first = await this.dxSaaSService.oiPost('oi/v2/servicerepo/services', body);
88054
+ const services = [...first.services];
88055
+ const expected = expectedCount(first);
88056
+ let requests = 1;
88057
+ while (services.length < expected) {
88058
+ if (maxRequests !== undefined && requests >= maxRequests) {
88059
+ this.log.warn(`Service list truncated at ${services.length} of ${expected}: maxRequests=${maxRequests} reached`);
88060
+ break;
87588
88061
  }
87589
- return returnServices;
87590
- });
88062
+ body.pageNum++;
88063
+ requests++;
88064
+ this.log.info(`Requesting services page ${body.pageNum}`);
88065
+ const page = await this.dxSaaSService.oiPost('oi/v2/servicerepo/services', body);
88066
+ if (page.services.length === 0) {
88067
+ this.log.warn(`Service list stopped at ${services.length} of ${expected}: page ${body.pageNum} was empty`);
88068
+ break;
88069
+ }
88070
+ services.push(...page.services);
88071
+ }
88072
+ return services;
87591
88073
  }
87592
88074
  /** Builds a services request body scoped to parent (top-level) services. */
87593
88075
  createParentServiceRequestBody(pageSize) {
@@ -87997,15 +88479,21 @@ class SituationService {
87997
88479
  async getSituationOverview(situationId) {
87998
88480
  return this.dxSaaSService.oiGet(`oi/v2/api/groupalarms/_search/${situationId}/overview`, { type: 'cluster' });
87999
88481
  }
88000
- /** Returns lifecycle (state change) events for a situation. */
88482
+ /**
88483
+ * Returns a situation's whole lifecycle (state change) history, newest first.
88484
+ *
88485
+ * @remarks Reads every page until the server's `totalCount` (it used to
88486
+ * stop at 50; a demo-dev situation had 69). A short read keeps the server's
88487
+ * `totalCount` and logs a warning.
88488
+ */
88001
88489
  async getSituationLifecycleEvents(situationId) {
88002
- return this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', {
88490
+ return readLifecyclePages((pageNumber, pageSize) => this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', {
88003
88491
  alarmId: situationId,
88004
- pageSize: 50,
88005
- pageNumber: 0,
88492
+ pageSize,
88493
+ pageNumber,
88006
88494
  sortCol: 'timestamp:desc',
88007
88495
  lifeCycleType: 'SITUATION',
88008
- });
88496
+ }), `situation ${situationId}`, this.log);
88009
88497
  }
88010
88498
  /** Returns the inspector inspection result for a situation (related alarms, topology). */
88011
88499
  async getSituationInspection(situationId) {
@@ -89831,6 +90319,9 @@ exports.ALARM_QUEUE_DEFAULT_VISIBLE_COLUMNS = ALARM_QUEUE_DEFAULT_VISIBLE_COLUMN
89831
90319
  exports.ALARM_QUEUE_DISPLAY_COLUMN_KEYS = ALARM_QUEUE_DISPLAY_COLUMN_KEYS;
89832
90320
  exports.ALARM_QUEUE_FILTER_CONDITIONS = ALARM_QUEUE_FILTER_CONDITIONS;
89833
90321
  exports.ALARM_QUEUE_FILTER_SETTING_KEYS = ALARM_QUEUE_FILTER_SETTING_KEYS;
90322
+ exports.ALARM_RECORD_PAGE_SIZE = ALARM_RECORD_PAGE_SIZE;
90323
+ exports.ALARM_RECORD_WINDOW_CAP = ALARM_RECORD_WINDOW_CAP;
90324
+ exports.ALARM_SEARCH_PAGE_CAP = ALARM_SEARCH_PAGE_CAP;
89834
90325
  exports.ALARM_VIEW_CATEGORIES = ALARM_VIEW_CATEGORIES;
89835
90326
  exports.ALARM_VIEW_FIELD_PATHS = ALARM_VIEW_FIELD_PATHS;
89836
90327
  exports.ALARM_VIEW_SEARCH_PATHS = ALARM_VIEW_SEARCH_PATHS;
@@ -89854,6 +90345,8 @@ exports.AlarmQueuePreferencesSchema = AlarmQueuePreferencesSchema;
89854
90345
  exports.AlarmQueueSchema = AlarmQueueSchema;
89855
90346
  exports.AlarmQueueWriteBodySchema = AlarmQueueWriteBodySchema;
89856
90347
  exports.AlarmQueueWriteResponseSchema = AlarmQueueWriteResponseSchema;
90348
+ exports.AlarmRecordSchema = AlarmRecordSchema;
90349
+ exports.AlarmRecordSearchResponseSchema = AlarmRecordSearchResponseSchema;
89857
90350
  exports.AlarmService = AlarmService;
89858
90351
  exports.AlertService = AlertService;
89859
90352
  exports.AlignmentSchema = AlignmentSchema;
@@ -90048,6 +90541,7 @@ exports.INVENTORY_QUEUE_NO_GROUP = INVENTORY_QUEUE_NO_GROUP;
90048
90541
  exports.ITSM_DEFAULT_TICKET_TEMPLATE = ITSM_DEFAULT_TICKET_TEMPLATE;
90049
90542
  exports.ITSM_SECRET_KEYS = ITSM_SECRET_KEYS;
90050
90543
  exports.ImportTokenRequestSchema = ImportTokenRequestSchema;
90544
+ exports.IncompleteAlarmSearchError = IncompleteAlarmSearchError;
90051
90545
  exports.InventorizeDeleteResponseSchema = InventorizeDeleteResponseSchema;
90052
90546
  exports.InventorizeDraftSchema = InventorizeDraftSchema;
90053
90547
  exports.InventorizeLayerSchema = InventorizeLayerSchema;
@@ -90081,6 +90575,7 @@ exports.JexlEvalError = JexlEvalError;
90081
90575
  exports.JexlSyntaxError = JexlSyntaxError;
90082
90576
  exports.JoinTypeSchema = JoinTypeSchema;
90083
90577
  exports.JsExtensionService = JsExtensionService;
90578
+ exports.LIFECYCLE_PAGE_SIZE = LIFECYCLE_PAGE_SIZE;
90084
90579
  exports.LOG_ANALYTICS_PRODUCT = LOG_ANALYTICS_PRODUCT;
90085
90580
  exports.LogsService = LogsService;
90086
90581
  exports.MAX_SLIS_PER_GROUP = MAX_SLIS_PER_GROUP;
@@ -90431,6 +90926,7 @@ exports.WebhookTestResponseSchema = WebhookTestResponseSchema;
90431
90926
  exports.ags = ags;
90432
90927
  exports.agsresponse = agsresponse;
90433
90928
  exports.alarmFilterDisplayColumnsFor = alarmFilterDisplayColumnsFor;
90929
+ exports.alarmRecordTime = alarmRecordTime;
90434
90930
  exports.alertsForSliIndex = alertsForSliIndex;
90435
90931
  exports.algorithmicSituationsEnabled = algorithmicSituationsEnabled;
90436
90932
  exports.allAlarmQueues = allAlarmQueues;
@@ -90497,6 +90993,7 @@ exports.evaluate = evaluate;
90497
90993
  exports.evaluateTemplate = evaluateTemplate;
90498
90994
  exports.example = example;
90499
90995
  exports.excludedAttributes = excludedAttributes;
90996
+ exports.exportAlarmRecords = exportAlarmRecords;
90500
90997
  exports.exportFileLabel = exportFileLabel;
90501
90998
  exports.exportIncludesToken = exportIncludesToken;
90502
90999
  exports.expressionPipelineNames = expressionPipelineNames;
@@ -90602,6 +91099,7 @@ exports.oauthTokenCognateDeleteCurrent = oauthTokenCognateDeleteCurrent;
90602
91099
  exports.oauthTokenDelete = oauthTokenDelete;
90603
91100
  exports.oauthTokenDeleteCurrent = oauthTokenDeleteCurrent;
90604
91101
  exports.orBlocksByField = orBlocksByField;
91102
+ exports.parseAlarmRecordTime = parseAlarmRecordTime;
90605
91103
  exports.parseExpression = parseExpression;
90606
91104
  exports.parseExternalIdFormat = parseExternalIdFormat;
90607
91105
  exports.parseFilter = parseFilter;
@@ -90616,6 +91114,7 @@ exports.producedMetricName = producedMetricName;
90616
91114
  exports.projectCustomAttributes = projectCustomAttributes;
90617
91115
  exports.projectRule = projectRule;
90618
91116
  exports.pruneOrphanSloFunctions = pruneOrphanSloFunctions;
91117
+ exports.readLifecyclePages = readLifecyclePages;
90619
91118
  exports.redactChannelSecrets = redactChannelSecrets;
90620
91119
  exports.reencodeItsmForWrite = reencodeItsmForWrite;
90621
91120
  exports.removeAlert = removeAlert;
@@ -90625,6 +91124,7 @@ exports.resolveAnomalyDetectionProduct = resolveAnomalyDetectionProduct;
90625
91124
  exports.resolveEnrichmentMappings = resolveEnrichmentMappings;
90626
91125
  exports.resolveWebhookPayload = resolveWebhookPayload;
90627
91126
  exports.sampleServiceDetailRequestBody = sampleServiceDetailRequestBody;
91127
+ exports.searchAlarmWindows = searchAlarmWindows;
90628
91128
  exports.searchUniverse = searchUniverse;
90629
91129
  exports.sendWithRetry = sendWithRetry;
90630
91130
  exports.serviceDetailResponseBody = serviceDetailResponseBody;