@dx-do/client 7.15.0 → 7.17.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 (47) hide show
  1. package/dist/index.cjs.js +2075 -292
  2. package/dist/index.cjs.js.map +1 -1
  3. package/dist/index.esm.js +2061 -293
  4. package/dist/index.esm.js.map +1 -1
  5. package/dist/src/index.d.ts +7 -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/datastore-schemas.d.ts +2 -7
  10. package/dist/src/lib/model/datastore/datastore-schemas.d.ts.map +1 -1
  11. package/dist/src/lib/model/datastore/metrics-metadata/attribute-name-specifier.d.ts +2 -2
  12. package/dist/src/lib/model/datastore/metrics-metadata/folder-name-specifier.d.ts +2 -2
  13. package/dist/src/lib/model/datastore/metrics-metadata/source-name-specifier.d.ts +2 -2
  14. package/dist/src/lib/model/datastore/nassql/operations.d.ts.map +1 -1
  15. package/dist/src/lib/model/datastore/tas/filters.d.ts +11 -10
  16. package/dist/src/lib/model/datastore/tas/filters.d.ts.map +1 -1
  17. package/dist/src/lib/model/oi/alarms.d.ts +12 -0
  18. package/dist/src/lib/model/oi/alarms.d.ts.map +1 -1
  19. package/dist/src/lib/model/oi/services.bulk-select.d.ts +109 -0
  20. package/dist/src/lib/model/oi/services.bulk-select.d.ts.map +1 -0
  21. package/dist/src/lib/model/oi/services.bulk.d.ts +243 -0
  22. package/dist/src/lib/model/oi/services.bulk.d.ts.map +1 -0
  23. package/dist/src/lib/model/oi/services.d.ts +2 -0
  24. package/dist/src/lib/model/oi/services.d.ts.map +1 -1
  25. package/dist/src/lib/model/oi/services.export.d.ts +10 -0
  26. package/dist/src/lib/model/oi/services.export.d.ts.map +1 -1
  27. package/dist/src/lib/model/oi/services.import.d.ts +43 -0
  28. package/dist/src/lib/model/oi/services.import.d.ts.map +1 -0
  29. package/dist/src/lib/model/oi/services.transform.d.ts +10 -1
  30. package/dist/src/lib/model/oi/services.transform.d.ts.map +1 -1
  31. package/dist/src/lib/model/service/service-overview.d.ts +20 -0
  32. package/dist/src/lib/model/service/service-overview.d.ts.map +1 -1
  33. package/dist/src/lib/services/alarm-export.d.ts +85 -0
  34. package/dist/src/lib/services/alarm-export.d.ts.map +1 -0
  35. package/dist/src/lib/services/alarm-window-search.d.ts +59 -0
  36. package/dist/src/lib/services/alarm-window-search.d.ts.map +1 -0
  37. package/dist/src/lib/services/alarm.service.d.ts +57 -4
  38. package/dist/src/lib/services/alarm.service.d.ts.map +1 -1
  39. package/dist/src/lib/services/dxoi.service.d.ts +15 -3
  40. package/dist/src/lib/services/dxoi.service.d.ts.map +1 -1
  41. package/dist/src/lib/services/lifecycle-pages.d.ts +20 -0
  42. package/dist/src/lib/services/lifecycle-pages.d.ts.map +1 -0
  43. package/dist/src/lib/services/service.service.d.ts +107 -10
  44. package/dist/src/lib/services/service.service.d.ts.map +1 -1
  45. package/dist/src/lib/services/situation.service.d.ts +9 -2
  46. package/dist/src/lib/services/situation.service.d.ts.map +1 -1
  47. 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
@@ -48415,6 +48483,21 @@ factory(name$9, ['typed', 'equalScalar'], _ref2 => {
48415
48483
  });
48416
48484
  });
48417
48485
 
48486
+ function cyrb53(str, seed = 0) {
48487
+ let h1 = 0xdeadbeef ^ seed;
48488
+ let h2 = 0x41c6ce57 ^ seed;
48489
+ for (let i = 0, ch; i < str.length; i++) {
48490
+ ch = str.charCodeAt(i);
48491
+ h1 = Math.imul(h1 ^ ch, 2654435761);
48492
+ h2 = Math.imul(h2 ^ ch, 1597334677);
48493
+ }
48494
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
48495
+ h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
48496
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
48497
+ h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
48498
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
48499
+ }
48500
+
48418
48501
  var Interpolation;
48419
48502
  (function (Interpolation) {
48420
48503
  function splitWithEscape(text, delimiter, escapeChar) {
@@ -48730,6 +48813,10 @@ const SENSITIVE_KEYS = new Set([
48730
48813
  'revoketoken',
48731
48814
  'password',
48732
48815
  'apikey',
48816
+ // Legacy (pre-v3) dx-do profile secrets.
48817
+ 'dashboardapikey',
48818
+ 'camanagementcookie',
48819
+ 'oiuserkey',
48733
48820
  'x-api-key',
48734
48821
  // Notification-channel write bodies (webhook auth, ServiceNow OAuth).
48735
48822
  'tokenvalue',
@@ -49400,6 +49487,7 @@ const AttributeExpressionSchema = v4.z.looseObject({
49400
49487
  operator: AttributeExpressionOperatorSchema.optional().describe('Comparison operator; defaults to IN'),
49401
49488
  layer: v4.z
49402
49489
  .string()
49490
+ .nullable()
49403
49491
  .optional()
49404
49492
  .describe('Restrict the expression to attributes on a specific layer (overlays the filter-level layer if both set)'),
49405
49493
  comparator: AttributeExpressionComparatorSchema.optional().describe('Value-parsing mode for ordered comparisons; only consulted by GE/GT/LE/LT'),
@@ -49443,7 +49531,7 @@ const TraversalVertexFilterSchema = v4.z.looseObject({
49443
49531
  op: v4.z.string().optional().describe('Op discriminator (ALL/NONE/AND/OR/NOT/ATTRIBUTE/LAYER/VERTEX)'),
49444
49532
  input: v4.z.lazy(() => v4.z.array(TraversalVertexFilterSchema)).optional(),
49445
49533
  expressions: v4.z.array(AttributeExpressionSchema).optional(),
49446
- layer: v4.z.string().optional(),
49534
+ layer: v4.z.string().nullable().optional(),
49447
49535
  values: v4.z.array(v4.z.string()).optional(),
49448
49536
  vertexId: v4.z.array(v4.z.number()).optional(),
49449
49537
  });
@@ -49681,6 +49769,7 @@ const TasAttributeFilterSchema = v4.z.looseObject({
49681
49769
  .describe('Attribute expressions; all must match (AND)'),
49682
49770
  layer: v4.z
49683
49771
  .string()
49772
+ .nullable()
49684
49773
  .optional()
49685
49774
  .describe('Restrict to attributes on a single layer (overlays per-expression layer)'),
49686
49775
  mode: TasAttributeFilterModeSchema.optional().describe('How vertex/edge matching propagates; defaults to VERTEX_AND_RELATED_EDGES'),
@@ -49735,17 +49824,22 @@ const TasVertexIdFilterSchema = v4.z.looseObject({
49735
49824
  * hierarchy as defined in the Service Definition).
49736
49825
  *
49737
49826
  * Toggle `excludeSubServices=true` for an exact-service-only match;
49738
- * `includeServiceHierarchy=true` includes higher-level service ancestors
49739
- * in addition to descendants.
49827
+ * `includeServiceHierarchy=true` adds the `saService` vertices themselves
49828
+ * (the named services and, unless excluded, their sub-services) to the
49829
+ * member entities. It does not add ancestors (measured 2026-10-21).
49740
49830
  */
49741
49831
  const TasServiceFilterSchema = v4.z.looseObject({
49742
49832
  op: v4.z.literal('SERVICE'),
49743
49833
  input: TasFilterLazy.optional().describe('Optional input filter; defaults to ALL'),
49744
- values: v4.z.array(v4.z.string()).optional().describe('Service names to match'),
49834
+ values: v4.z
49835
+ .array(v4.z.string())
49836
+ .optional()
49837
+ .describe('Service names to match; required by the server (missing or empty is a 400), and no wildcard'),
49745
49838
  includeServiceHierarchy: v4.z
49746
49839
  .boolean()
49747
49840
  .optional()
49748
- .describe('Include the entire service hierarchy (ancestors); defaults to false'),
49841
+ .describe('Also return the saService vertices of the matched services (named + sub-services, never ancestors); ' +
49842
+ 'the only way a direct TAS query reaches service vertices; defaults to false'),
49749
49843
  excludeSubServices: v4.z
49750
49844
  .boolean()
49751
49845
  .optional()
@@ -49998,6 +50092,7 @@ const TasCollectAttributesFilterSchema = v4.z.looseObject({
49998
50092
  .describe('Name of the vertex attribute whose values to collect (e.g. "type", "name")'),
49999
50093
  layer: v4.z
50000
50094
  .string()
50095
+ .nullable()
50001
50096
  .optional()
50002
50097
  .describe('Restrict collection to this layer; omit or null for all layers'),
50003
50098
  includeIds: v4.z
@@ -50032,6 +50127,7 @@ const TasCollectAttributeNamesFilterSchema = v4.z.looseObject({
50032
50127
  .describe('Unique key; result appears in analytics[] under this id'),
50033
50128
  layer: v4.z
50034
50129
  .string()
50130
+ .nullable()
50035
50131
  .optional()
50036
50132
  .describe('Restrict to this layer; omit or null for all layers'),
50037
50133
  });
@@ -50072,6 +50168,7 @@ const TasCollectVertexIdFilterSchema = v4.z.looseObject({
50072
50168
  .describe('Unique key; result appears in analytics[] under this id'),
50073
50169
  layer: v4.z
50074
50170
  .string()
50171
+ .nullable()
50075
50172
  .optional()
50076
50173
  .describe('Restrict to this layer; omit or null for all layers'),
50077
50174
  skipBackends: v4.z
@@ -50156,6 +50253,7 @@ const TasCollectExperienceAttributesFilterSchema = v4.z.looseObject({
50156
50253
  .describe('Attribute whose values to collect'),
50157
50254
  layer: v4.z
50158
50255
  .string()
50256
+ .nullable()
50159
50257
  .optional()
50160
50258
  .describe('Restrict to this layer; omit or null for all'),
50161
50259
  caseInsensitive: v4.z
@@ -50728,7 +50826,7 @@ const SourceNameNotSpecifierSchema = v4.z.looseObject({
50728
50826
  */
50729
50827
  const SourceNameExactSpecifierSchema = v4.z.looseObject({
50730
50828
  op: v4.z.literal('EXACT'),
50731
- names: v4.z.array(v4.z.string()).optional().describe('Exact source name strings; any matching name passes'),
50829
+ names: v4.z.array(v4.z.string()).describe('Exact source name strings; any matching name passes. Required: without it the server answers 400 "EXACT specifier - names field is required" (an empty list is accepted)'),
50732
50830
  ignoreCase: v4.z.boolean().optional().describe('Case-insensitive comparison; default false'),
50733
50831
  });
50734
50832
  /**
@@ -50737,7 +50835,7 @@ const SourceNameExactSpecifierSchema = v4.z.looseObject({
50737
50835
  */
50738
50836
  const SourceNameRegExSpecifierSchema = v4.z.looseObject({
50739
50837
  op: v4.z.literal('REGEX'),
50740
- pattern: v4.z.string().optional().describe('Java regex pattern matched against the full source name'),
50838
+ pattern: v4.z.string().describe('Java regex pattern matched against the full source name. Required, and named `pattern`: without it the server answers 400 "REGEX specifier - specifier field is required", naming the wrong field'),
50741
50839
  ignoreCase: v4.z.boolean().optional().describe('Case-insensitive match; default false'),
50742
50840
  });
50743
50841
  /**
@@ -50822,7 +50920,7 @@ const FolderNameNotSpecifierSchema = v4.z.looseObject({
50822
50920
  */
50823
50921
  const FolderNameExactSpecifierSchema = v4.z.looseObject({
50824
50922
  op: v4.z.literal('EXACT'),
50825
- names: v4.z.array(v4.z.string()).optional().describe('Exact folder name strings; any matching name passes'),
50923
+ names: v4.z.array(v4.z.string()).describe('Exact folder name strings; any matching name passes. Required: without it the server answers 400 "EXACT specifier - names field is required" (an empty list is accepted)'),
50826
50924
  ignoreCase: v4.z.boolean().optional().describe('Case-insensitive comparison; default false'),
50827
50925
  });
50828
50926
  /**
@@ -50831,7 +50929,7 @@ const FolderNameExactSpecifierSchema = v4.z.looseObject({
50831
50929
  */
50832
50930
  const FolderNameRegExSpecifierSchema = v4.z.looseObject({
50833
50931
  op: v4.z.literal('REGEX'),
50834
- pattern: v4.z.string().optional().describe('Java regex pattern matched against the full folder name'),
50932
+ pattern: v4.z.string().describe('Java regex pattern matched against the full folder name. Required, and named `pattern`: without it the server answers 400 "REGEX specifier - specifier field is required", naming the wrong field'),
50835
50933
  ignoreCase: v4.z.boolean().optional().describe('Case-insensitive match; default false'),
50836
50934
  });
50837
50935
  /**
@@ -50939,7 +51037,7 @@ const AttributeNameNotSpecifierSchema = v4.z.looseObject({
50939
51037
  */
50940
51038
  const AttributeNameExactSpecifierSchema = v4.z.looseObject({
50941
51039
  op: v4.z.literal('EXACT'),
50942
- names: v4.z.array(v4.z.string()).optional().describe('Exact attribute name strings'),
51040
+ names: v4.z.array(v4.z.string()).describe('Exact attribute name strings. Required: without it the server answers 400 "EXACT specifier - names field is required" (an empty list is accepted)'),
50943
51041
  type: v4.z.number().optional().describe('Optional attribute type bitmask filter'),
50944
51042
  ignoreCase: v4.z.boolean().optional().describe('Case-insensitive comparison; default false'),
50945
51043
  });
@@ -50949,7 +51047,7 @@ const AttributeNameExactSpecifierSchema = v4.z.looseObject({
50949
51047
  */
50950
51048
  const AttributeNameRegExSpecifierSchema = v4.z.looseObject({
50951
51049
  op: v4.z.literal('REGEX'),
50952
- pattern: v4.z.string().optional().describe('Java regex pattern matched against the full attribute name'),
51050
+ pattern: v4.z.string().describe('Java regex pattern matched against the full attribute name. Required, and named `pattern`: without it the server answers 400 "REGEX specifier - specifier field is required", naming the wrong field'),
50953
51051
  ignoreCase: v4.z.boolean().optional().describe('Case-insensitive match; default false'),
50954
51052
  });
50955
51053
  /**
@@ -51938,17 +52036,17 @@ const QueryCalendarWindowSpecSchema = v4.z.looseObject({
51938
52036
  * per-entity grouping column to survive into `KEEP` — otherwise WINDOW
51939
52037
  * + aggregation collapses non-grouped columns away.
51940
52038
  *
51941
- * Java side accepts an empty `columns[]` to clear the grouping ("flatten"
51942
- * pattern); the Zod schema requires `min(1)` so use `--no-validate` if
51943
- * you need that variant.
52039
+ * An empty `columns[]` clears the grouping. It is what makes `TOP` /
52040
+ * `BOTTOM` rank across rows after `GROUP` › an aggregation: without it they
52041
+ * rank within each group and every group comes back (measured on
52042
+ * THE_LABORATORY 2026-10-23: 42 sources, `TOP` 10 returned all 42; after
52043
+ * `GROUP []` it returned the 10 largest, in order).
51944
52044
  */
51945
52045
  const QueryGroupSpecSchema = v4.z.looseObject({
51946
52046
  op: v4.z.literal('GROUP'),
51947
- // No grouping key = no grouping; server rejects empty.
51948
52047
  columns: v4.z
51949
52048
  .array(v4.z.string())
51950
- .min(1)
51951
- .describe('Compound grouping-key columns; must be non-empty'),
52049
+ .describe('Compound grouping-key columns. Empty clears the grouping: put GROUP [] after an aggregation and before TOP / BOTTOM so they rank across all rows, not within each group'),
51952
52050
  });
51953
52051
  /**
51954
52052
  * `ORDER` — SQL-style multi-key sort. Mixed types are ordered: nulls
@@ -52879,6 +52977,27 @@ function discriminatorValueOf(option) {
52879
52977
  *
52880
52978
  * Order matches the union's declaration; not alphabetical.
52881
52979
  */
52980
+ /** The name specifiers a Metrics Metadata `SPEC` holds, each a union of its own ops (REGEX, EXACT, …). */
52981
+ const NAME_SPECIFIERS = [
52982
+ { field: 'sourceNameSpecifier', union: SourceNameSpecifierSchema },
52983
+ { field: 'attributeNameSpecifier', union: AttributeNameSpecifierSchema },
52984
+ { field: 'folderNameSpecifier', union: FolderNameSpecifierSchema },
52985
+ ];
52986
+ const optionsOf = (union) => union.options ?? [];
52987
+ /** The name-specifier ops, which a SPEC (metadata, or a NASSQL FROM / FROM_METADATA `querySpecifier`) carries. */
52988
+ function listNameSpecifierOps() {
52989
+ return [...new Set(NAME_SPECIFIERS.flatMap(({ union }) => optionsOf(union).map(discriminatorValueOf).filter((v) => !!v)))];
52990
+ }
52991
+ /** A name-specifier op's schema, saying which SPEC fields it goes in (#1195); undefined when `op` is none. */
52992
+ function nameSpecifierSchema(op) {
52993
+ const found = NAME_SPECIFIERS.flatMap(({ field, union }) => optionsOf(union).filter((o) => discriminatorValueOf(o) === op).map((o) => ({ field, o })));
52994
+ const first = found[0];
52995
+ if (!first)
52996
+ return undefined;
52997
+ const json = zod.z.toJSONSchema(first.o);
52998
+ const where = `A name-specifier op: it goes in a SPEC's ${found.map((f) => f.field).join(' / ')}, not at the top level.`;
52999
+ return { ...json, description: typeof json['description'] === 'string' ? `${json['description']} ${where}` : where };
53000
+ }
52882
53001
  function listDataStoreSchemaOps(type) {
52883
53002
  const { union } = resolveSchemas(type);
52884
53003
  const out = [];
@@ -52918,8 +53037,14 @@ function getDataStoreSchema(type, op) {
52918
53037
  return zod.z.toJSONSchema(opt);
52919
53038
  }
52920
53039
  }
53040
+ if (type !== 'tas') {
53041
+ const named = nameSpecifierSchema(op);
53042
+ if (named)
53043
+ return named;
53044
+ }
52921
53045
  const valid = listDataStoreSchemaOps(type);
52922
- throw new Error(`Unknown ${type} op "${op}". Valid ops: ${valid.join(', ')}`);
53046
+ const names = type === 'tas' ? '' : `; inside a SPEC's name specifiers: ${listNameSpecifierOps().join(', ')}`;
53047
+ throw new Error(`Unknown ${type} op "${op}". Valid ops: ${valid.join(', ')}${names}`);
52923
53048
  }
52924
53049
  function describeType(prop) {
52925
53050
  if (Array.isArray(prop['oneOf'])) {
@@ -63653,6 +63778,10 @@ exports.NASS = void 0;
63653
63778
 
63654
63779
  exports.OIAlarm = void 0;
63655
63780
  (function (OIAlarm) {
63781
+ /**
63782
+ * @deprecated Its `timeFrom`/`timeTo` are fixed when the module loads and it is a shared,
63783
+ * mutable object; build a fresh body per request instead.
63784
+ */
63656
63785
  OIAlarm.DEFAULT_SITUATIONS_REQUEST_BODY = {
63657
63786
  pageNumber: 0,
63658
63787
  pageSize: 50,
@@ -63674,6 +63803,10 @@ exports.OIAlarm = void 0;
63674
63803
  showMaintenanceAlarms: false,
63675
63804
  customFilter: {},
63676
63805
  };
63806
+ /**
63807
+ * @deprecated Its `timeFrom`/`timeTo` are fixed when the module loads and it is a shared,
63808
+ * mutable object; use {@link newAlarmSearchBody}.
63809
+ */
63677
63810
  OIAlarm.DEFAULT_ALARMS_REQUEST_BODY = {
63678
63811
  deviceNames: [],
63679
63812
  includeDeviceTypes: [],
@@ -63693,6 +63826,30 @@ exports.OIAlarm = void 0;
63693
63826
  showMaintenanceAlarms: false,
63694
63827
  customFilter: {},
63695
63828
  };
63829
+ /** A fresh `oi/v2/api/alarms/_search` body for `[timeFrom, timeTo]`, first page, nothing filtered. */
63830
+ function newAlarmSearchBody(timeFrom, timeTo, overrides = {}) {
63831
+ return {
63832
+ deviceNames: [],
63833
+ includeDeviceTypes: [],
63834
+ excludeDeviceTypes: [],
63835
+ groups: [],
63836
+ like: '',
63837
+ timeFrom,
63838
+ timeTo,
63839
+ pageNumber: 0,
63840
+ pageSize: 50,
63841
+ services: [],
63842
+ includeSeverity: [],
63843
+ allOtherSeverity: false,
63844
+ includeAlarmTypes: [],
63845
+ excludeAlarmTypes: [],
63846
+ includeClosedAlarms: false,
63847
+ showMaintenanceAlarms: false,
63848
+ customFilter: {},
63849
+ ...overrides,
63850
+ };
63851
+ }
63852
+ OIAlarm.newAlarmSearchBody = newAlarmSearchBody;
63696
63853
  })(exports.OIAlarm || (exports.OIAlarm = {}));
63697
63854
 
63698
63855
  exports.CreateServices = void 0;
@@ -63701,57 +63858,6 @@ exports.CreateServices = void 0;
63701
63858
  CreateServices.SERVICE_TYPES = ['Service', 'Application', 'Group'];
63702
63859
  })(exports.CreateServices || (exports.CreateServices = {}));
63703
63860
 
63704
- /**
63705
- * The `service export` / `service export-hierarchy` file format and the
63706
- * `service import` boundary validator.
63707
- *
63708
- * The envelope wraps a re-postable store body ({@link CreateServices.CreateServiceBody})
63709
- * with provenance metadata. `import` accepts either the envelope or a bare body.
63710
- */
63711
- exports.ServiceExport = void 0;
63712
- (function (ServiceExport) {
63713
- ServiceExport.SCHEMA_VERSION = 1;
63714
- // Structural guard for a store body — does not re-validate every field
63715
- // (the server is the authority); just enough to reject obviously-wrong files.
63716
- const BodyShape = v4.z.looseObject({
63717
- vertices: v4.z.array(v4.z.looseObject({ attributes: v4.z.looseObject({ name: v4.z.string() }) })),
63718
- edges: v4.z.array(v4.z.looseObject({
63719
- sourceExternalId: v4.z.string(),
63720
- targetExternalId: v4.z.string(),
63721
- })),
63722
- });
63723
- const EnvelopeShape = v4.z.looseObject({
63724
- schemaVersion: v4.z.literal(1),
63725
- kind: v4.z.enum(['service', 'service-hierarchy']),
63726
- sourceTenant: v4.z.string().optional(),
63727
- exportedAt: v4.z.string(),
63728
- body: BodyShape,
63729
- });
63730
- /** Wrap a store body in an export envelope. */
63731
- function envelope(kind, body, sourceTenant, exportedAt) {
63732
- return { schemaVersion: ServiceExport.SCHEMA_VERSION, kind, sourceTenant, exportedAt, body };
63733
- }
63734
- ServiceExport.envelope = envelope;
63735
- /**
63736
- * Validate an import file (already JSON-parsed) and return the store body.
63737
- * Accepts a full export envelope or a bare `{ vertices, edges }` body.
63738
- * @throws Error when the input is neither shape.
63739
- */
63740
- function parseImport(raw) {
63741
- const asEnvelope = EnvelopeShape.safeParse(raw);
63742
- if (asEnvelope.success) {
63743
- return asEnvelope.data.body;
63744
- }
63745
- const asBody = BodyShape.safeParse(raw);
63746
- if (asBody.success) {
63747
- return raw;
63748
- }
63749
- throw new Error('Import file is neither a service export envelope nor a bare {vertices, edges} body. ' +
63750
- `Envelope error: ${asEnvelope.error.message}`);
63751
- }
63752
- ServiceExport.parseImport = parseImport;
63753
- })(exports.ServiceExport || (exports.ServiceExport = {}));
63754
-
63755
63861
  /**
63756
63862
  * Pure (HTTP-free) transforms between the Service read shapes and the store
63757
63863
  * (`/oi/v2/sa/save`) body. Kept separate from {@link ServiceService} so the
@@ -63878,6 +63984,7 @@ exports.ServiceTransform = void 0;
63878
63984
  * dropped — this is exactly the incoming edge(s) from the root's parent, which
63879
63985
  * `saTopologyGraph` returns without the parent vertex (and which must not be
63880
63986
  * re-posted: the parent isn't re-saved, so its edge survives anyway).
63987
+ * Also accepts a `?subservices=true` read, which has the same id/edge shape.
63881
63988
  */
63882
63989
  function edgesFromTopology(topo) {
63883
63990
  const idToName = new Map(topo.vertices.map((v) => [v.externalId, v.attributes.name]));
@@ -63996,6 +64103,915 @@ exports.ServiceTransform = void 0;
63996
64103
  ServiceTransform.assertWeightsWithinLimit = assertWeightsWithinLimit;
63997
64104
  })(exports.ServiceTransform || (exports.ServiceTransform = {}));
63998
64105
 
64106
+ /**
64107
+ * Pure (HTTP-free) planning for multi-service edits saved in ONE `sa/save`.
64108
+ *
64109
+ * Measured on a lab tenant (docs/internal/service-bulk-save-findings-2026-10.md):
64110
+ * - Every vertex in a save payload is fully overwritten — attributes AND outgoing
64111
+ * edges — so a payload carries each changed service plus all its descendants,
64112
+ * each complete. Services left out of the payload are untouched, as are
64113
+ * incoming edges; a changed leaf is saved alone.
64114
+ * - A save that fails validation changes nothing.
64115
+ * - `GET sa/services/{name}?subservices=true` returns every hierarchy that
64116
+ * CONTAINS the service; descendants are computed from its edges here.
64117
+ *
64118
+ * Locking is a field-level rebase: a plan records the value each change
64119
+ * replaces; a commit re-reads, refuses only when one of those values moved
64120
+ * ({@link findConflicts}), then re-applies the changes onto the fresh read.
64121
+ */
64122
+ exports.ServiceBulk = void 0;
64123
+ (function (ServiceBulk) {
64124
+ const ServiceNameSchema = v4.z
64125
+ .string()
64126
+ .min(1)
64127
+ .describe('Service name: case-sensitive and unique in the tenant.');
64128
+ const TagsSchema = v4.z
64129
+ .array(v4.z.string().min(1))
64130
+ .min(1)
64131
+ .describe('Tags, compared as a set.');
64132
+ const WeightSchema = v4.z
64133
+ .number()
64134
+ .min(0)
64135
+ .max(1)
64136
+ .describe("Fraction (0–1) of the child's health/risk rolled up into the parent; a parent's children may total at most 1.");
64137
+ const CustomPropertySchema = v4.z.strictObject({
64138
+ name: v4.z.string().min(1).describe('Custom property name.'),
64139
+ value: v4.z.string().describe('Custom property value.'),
64140
+ });
64141
+ ServiceBulk.ServiceChangeSchema = v4.z
64142
+ .discriminatedUnion('op', [
64143
+ v4.z
64144
+ .strictObject({ op: v4.z.literal('addTags'), service: ServiceNameSchema, tags: TagsSchema })
64145
+ .describe('Add tags to a service; tags it already has are left alone.'),
64146
+ v4.z
64147
+ .strictObject({ op: v4.z.literal('removeTags'), service: ServiceNameSchema, tags: TagsSchema })
64148
+ .describe('Remove tags from a service; tags it lacks are ignored.'),
64149
+ v4.z
64150
+ .strictObject({
64151
+ op: v4.z.literal('setProperty'),
64152
+ service: ServiceNameSchema,
64153
+ name: v4.z.string().min(1).describe('Custom property name.'),
64154
+ value: v4.z.string().describe('New value; replaces every existing value of the property.'),
64155
+ })
64156
+ .describe('Set one custom property, adding it when absent.'),
64157
+ v4.z
64158
+ .strictObject({
64159
+ op: v4.z.literal('removeProperty'),
64160
+ service: ServiceNameSchema,
64161
+ name: v4.z.string().min(1).describe('Custom property name.'),
64162
+ })
64163
+ .describe('Remove one custom property; a property the service lacks is ignored.'),
64164
+ v4.z
64165
+ .strictObject({
64166
+ op: v4.z.literal('setAttributes'),
64167
+ service: ServiceNameSchema,
64168
+ description: v4.z.string().optional().describe('New description.'),
64169
+ location: v4.z.string().optional().describe('New location.'),
64170
+ situationsIncludeChildServices: v4.z
64171
+ .boolean()
64172
+ .optional()
64173
+ .describe("Whether the service's situations include its child services."),
64174
+ })
64175
+ .describe('Set scalar attributes; omitted fields keep their values.'),
64176
+ v4.z
64177
+ .strictObject({
64178
+ op: v4.z.literal('createService'),
64179
+ service: ServiceNameSchema,
64180
+ serviceType: v4.z
64181
+ .enum(exports.CreateServices.SERVICE_TYPES)
64182
+ .optional()
64183
+ .describe('Service | Application | Group (default Service); fixed once created.'),
64184
+ description: v4.z.string().optional().describe('Description (default empty).'),
64185
+ location: v4.z.string().optional().describe('Location (default empty).'),
64186
+ tags: v4.z.array(v4.z.string().min(1)).optional().describe('Initial tags.'),
64187
+ customProperties: v4.z
64188
+ .array(CustomPropertySchema)
64189
+ .optional()
64190
+ .describe('Initial custom properties.'),
64191
+ })
64192
+ .describe('Create a service; it is a top-level service unless a link change adds a parent.'),
64193
+ v4.z
64194
+ .strictObject({
64195
+ op: v4.z.literal('link'),
64196
+ parent: ServiceNameSchema,
64197
+ child: ServiceNameSchema,
64198
+ healthWeight: WeightSchema.optional(),
64199
+ riskWeight: WeightSchema.optional(),
64200
+ })
64201
+ .describe("Make child a direct child of parent, or re-weight an existing link. With no weights the parent's children are re-split evenly; one weight given sets both."),
64202
+ v4.z
64203
+ .strictObject({ op: v4.z.literal('unlink'), parent: ServiceNameSchema, child: ServiceNameSchema })
64204
+ .describe("Remove the parent→child link; the remaining children's weights are kept."),
64205
+ ])
64206
+ .describe('One change to one service or to one parent→child link.');
64207
+ class ServiceConflictError extends Error {
64208
+ conflicts;
64209
+ constructor(conflicts) {
64210
+ super(`Services changed since the plan was made — re-plan to see the current state:\n ${conflicts.join('\n ')}`);
64211
+ this.conflicts = conflicts;
64212
+ }
64213
+ }
64214
+ ServiceBulk.ServiceConflictError = ServiceConflictError;
64215
+ const IGNORED_FIELDS = new Set(['metrics', 'root_service', 'type', 'state']);
64216
+ /** Parse untrusted changes (CLI file, MCP input); throws ZodError. */
64217
+ function parseChanges(raw) {
64218
+ return v4.z.array(ServiceBulk.ServiceChangeSchema).min(1).parse(raw);
64219
+ }
64220
+ ServiceBulk.parseChanges = parseChanges;
64221
+ const ChildLinkSchema = v4.z.looseObject({
64222
+ child: v4.z.string(),
64223
+ healthWeight: v4.z.number(),
64224
+ riskWeight: v4.z.number(),
64225
+ });
64226
+ ServiceBulk.ServicePlanSchema = v4.z
64227
+ .looseObject({
64228
+ targets: v4.z.array(v4.z.string()).describe('Services read to build the plan.'),
64229
+ changes: v4.z.array(ServiceBulk.ServiceChangeSchema).min(1).describe('The changes, in order.'),
64230
+ diff: v4.z
64231
+ .array(v4.z.looseObject({
64232
+ service: v4.z.string(),
64233
+ status: v4.z.enum(['created', 'changed']),
64234
+ fields: v4.z.array(v4.z.looseObject({ field: v4.z.string(), before: v4.z.unknown(), after: v4.z.unknown() })),
64235
+ children: v4.z
64236
+ .looseObject({ before: v4.z.array(ChildLinkSchema), after: v4.z.array(ChildLinkSchema) })
64237
+ .optional(),
64238
+ }))
64239
+ .describe('Per-service before/after; the before values are what a commit checks.'),
64240
+ save: v4.z.array(v4.z.string()).describe('Every service the save payload carries.'),
64241
+ })
64242
+ .describe('A plan returned by planServiceChanges, passed back unchanged to commit it.');
64243
+ /** Parse an untrusted plan (file, MCP input); throws ZodError. */
64244
+ function parsePlan(raw) {
64245
+ return ServiceBulk.ServicePlanSchema.parse(raw);
64246
+ }
64247
+ ServiceBulk.parsePlan = parsePlan;
64248
+ /**
64249
+ * Every existing service the changes name — what to read before planning.
64250
+ * Services created by an earlier change in the list are excluded.
64251
+ */
64252
+ function targetsOf(changes) {
64253
+ const created = new Set();
64254
+ const targets = new Set();
64255
+ for (const c of changes) {
64256
+ const names = c.op === 'link' || c.op === 'unlink' ? [c.parent, c.child] : [c.service];
64257
+ if (c.op === 'createService')
64258
+ created.add(c.service);
64259
+ for (const n of names)
64260
+ if (!created.has(n))
64261
+ targets.add(n);
64262
+ }
64263
+ return [...targets];
64264
+ }
64265
+ ServiceBulk.targetsOf = targetsOf;
64266
+ /**
64267
+ * Convert one `?subservices=true` read into a name-keyed graph.
64268
+ * @throws Error when the read is paged — never observed, so refused rather than guessed at.
64269
+ */
64270
+ function graphFromRead(read) {
64271
+ const paged = (read.nextOffset !== undefined && read.nextOffset !== -1) ||
64272
+ (read.totalVertices !== undefined && read.vertices.length < read.totalVertices);
64273
+ if (paged) {
64274
+ throw new Error(`Service hierarchy read is paged (${read.vertices.length} of ${read.totalVertices} services, nextOffset=${read.nextOffset}); bulk edits do not support paged hierarchies yet`);
64275
+ }
64276
+ const vertices = {};
64277
+ for (const v of read.vertices) {
64278
+ vertices[v.attributes.name] = exports.ServiceTransform.retrievedToServiceVertex(v);
64279
+ }
64280
+ return { vertices, edges: exports.ServiceTransform.edgesFromTopology(read) };
64281
+ }
64282
+ ServiceBulk.graphFromRead = graphFromRead;
64283
+ /** Union two graphs; a service or edge present in both keeps the first copy. */
64284
+ function mergeGraphs(a, b) {
64285
+ return {
64286
+ vertices: { ...b.vertices, ...a.vertices },
64287
+ edges: exports.ServiceTransform.mergeBodies({ vertices: [], edges: a.edges }, { vertices: [], edges: b.edges })
64288
+ .edges,
64289
+ };
64290
+ }
64291
+ ServiceBulk.mergeGraphs = mergeGraphs;
64292
+ /** Direct children of a parent, sorted by name. */
64293
+ function childLinks(graph, parent) {
64294
+ return exports.ServiceTransform.childEdges(graph.edges, parent)
64295
+ .map((e) => ({
64296
+ child: e.targetExternalId,
64297
+ healthWeight: e.attributes.health_weight,
64298
+ riskWeight: e.attributes.risk_weight,
64299
+ }))
64300
+ .sort((x, y) => x.child.localeCompare(y.child));
64301
+ }
64302
+ ServiceBulk.childLinks = childLinks;
64303
+ /** The services reachable from the seeds through parent→child edges, seeds included. */
64304
+ function descendantClosure(graph, seeds) {
64305
+ const seen = new Set();
64306
+ const queue = [...seeds];
64307
+ while (queue.length) {
64308
+ const name = queue.shift();
64309
+ if (seen.has(name))
64310
+ continue;
64311
+ seen.add(name);
64312
+ for (const e of exports.ServiceTransform.childEdges(graph.edges, name))
64313
+ queue.push(e.targetExternalId);
64314
+ }
64315
+ return [...seen];
64316
+ }
64317
+ ServiceBulk.descendantClosure = descendantClosure;
64318
+ /** The store body for a set of services: each one complete, with all its outgoing edges. */
64319
+ function bodyFor(graph, services) {
64320
+ const names = new Set(services);
64321
+ const missing = services.filter((n) => !graph.vertices[n]);
64322
+ if (missing.length)
64323
+ throw new Error(`Services not in the graph: ${missing.join(', ')}`);
64324
+ const edges = graph.edges.filter((e) => names.has(e.sourceExternalId));
64325
+ const dangling = edges.filter((e) => !names.has(e.targetExternalId));
64326
+ if (dangling.length) {
64327
+ throw new Error(`Edges leave the payload: ${dangling.map((e) => `${e.sourceExternalId}→${e.targetExternalId}`).join(', ')}`);
64328
+ }
64329
+ return { vertices: services.map((n) => graph.vertices[n]), edges };
64330
+ }
64331
+ ServiceBulk.bodyFor = bodyFor;
64332
+ /** A service and its whole subtree as one store body (export-hierarchy, associate, …). */
64333
+ function subtreeBody(graph, root) {
64334
+ if (!graph.vertices[root])
64335
+ throw new Error(`No service with name '${root}' found`);
64336
+ return bodyFor(graph, descendantClosure(graph, [root]));
64337
+ }
64338
+ ServiceBulk.subtreeBody = subtreeBody;
64339
+ function newVertex(c) {
64340
+ return {
64341
+ externalId: c.service,
64342
+ attributes: {
64343
+ type: 'saService',
64344
+ name: c.service,
64345
+ serviceType: c.serviceType ?? 'Service',
64346
+ state: 'ACTIVE',
64347
+ maintenance: false,
64348
+ situationsIncludeChildServices: false,
64349
+ serviceContent: [],
64350
+ root_service: null,
64351
+ tags: c.tags ? [...new Set(c.tags)] : [],
64352
+ location: c.location ?? '',
64353
+ description: c.description ?? '',
64354
+ customProperties: (c.customProperties ?? []).map((p) => ({ ...p })),
64355
+ customMetrics: [],
64356
+ metrics: [],
64357
+ },
64358
+ };
64359
+ }
64360
+ function isAncestor(graph, candidate, of) {
64361
+ return descendantClosure(graph, [candidate]).includes(of);
64362
+ }
64363
+ /**
64364
+ * Apply changes to a copy of the graph, in order.
64365
+ * @throws Error naming the offending change (unknown service, duplicate create, cycle, missing link).
64366
+ */
64367
+ function applyChanges(graph, changes) {
64368
+ const g = structuredClone(graph);
64369
+ const vertex = (name, i) => {
64370
+ const v = g.vertices[name];
64371
+ if (!v)
64372
+ throw new Error(`change ${i + 1}: no service with name '${name}' found`);
64373
+ return v.attributes;
64374
+ };
64375
+ changes.forEach((c, i) => {
64376
+ switch (c.op) {
64377
+ case 'addTags': {
64378
+ const a = vertex(c.service, i);
64379
+ a.tags = [...new Set([...a.tags, ...c.tags])];
64380
+ break;
64381
+ }
64382
+ case 'removeTags': {
64383
+ const a = vertex(c.service, i);
64384
+ a.tags = a.tags.filter((t) => !c.tags.includes(t));
64385
+ break;
64386
+ }
64387
+ case 'setProperty': {
64388
+ const a = vertex(c.service, i);
64389
+ const rest = a.customProperties.filter((p) => p.name !== c.name);
64390
+ a.customProperties = [...rest, { name: c.name, value: c.value }];
64391
+ break;
64392
+ }
64393
+ case 'removeProperty': {
64394
+ const a = vertex(c.service, i);
64395
+ a.customProperties = a.customProperties.filter((p) => p.name !== c.name);
64396
+ break;
64397
+ }
64398
+ case 'setAttributes': {
64399
+ const a = vertex(c.service, i);
64400
+ if (c.description !== undefined)
64401
+ a.description = c.description;
64402
+ if (c.location !== undefined)
64403
+ a.location = c.location;
64404
+ if (c.situationsIncludeChildServices !== undefined) {
64405
+ a.situationsIncludeChildServices = c.situationsIncludeChildServices;
64406
+ }
64407
+ break;
64408
+ }
64409
+ case 'createService': {
64410
+ if (g.vertices[c.service]) {
64411
+ throw new Error(`change ${i + 1}: service '${c.service}' already exists`);
64412
+ }
64413
+ g.vertices[c.service] = newVertex(c);
64414
+ break;
64415
+ }
64416
+ case 'link': {
64417
+ vertex(c.parent, i);
64418
+ vertex(c.child, i);
64419
+ if (c.parent === c.child || isAncestor(g, c.child, c.parent)) {
64420
+ throw new Error(`change ${i + 1}: linking '${c.child}' under '${c.parent}' would create a cycle`);
64421
+ }
64422
+ const weighted = c.healthWeight !== undefined || c.riskWeight !== undefined;
64423
+ const exists = g.edges.some((e) => e.sourceExternalId === c.parent && e.targetExternalId === c.child);
64424
+ if (weighted) {
64425
+ const h = c.healthWeight ?? c.riskWeight;
64426
+ const r = c.riskWeight ?? h;
64427
+ g.edges = exports.ServiceTransform.upsertEdge(g.edges, c.parent, c.child, h, r);
64428
+ }
64429
+ else if (!exists) {
64430
+ g.edges = exports.ServiceTransform.rebalanceChildren(exports.ServiceTransform.upsertEdge(g.edges, c.parent, c.child, 0, 0), c.parent);
64431
+ }
64432
+ break;
64433
+ }
64434
+ case 'unlink': {
64435
+ vertex(c.parent, i);
64436
+ vertex(c.child, i);
64437
+ const before = g.edges.length;
64438
+ g.edges = exports.ServiceTransform.removeEdge(g.edges, c.parent, c.child);
64439
+ if (g.edges.length === before) {
64440
+ throw new Error(`change ${i + 1}: '${c.child}' is not a direct child of '${c.parent}'`);
64441
+ }
64442
+ break;
64443
+ }
64444
+ }
64445
+ });
64446
+ return g;
64447
+ }
64448
+ ServiceBulk.applyChanges = applyChanges;
64449
+ /** Order-insensitive form of an attribute value, for comparison and display. */
64450
+ function normalize(field, value) {
64451
+ if (field === 'tags' && Array.isArray(value))
64452
+ return [...value].sort();
64453
+ if (field === 'customProperties' && Array.isArray(value)) {
64454
+ return [...value]
64455
+ .map((p) => ({ name: p.name, value: p.value }))
64456
+ .sort((x, y) => x.name.localeCompare(y.name) || x.value.localeCompare(y.value));
64457
+ }
64458
+ return value;
64459
+ }
64460
+ ServiceBulk.normalize = normalize;
64461
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
64462
+ function fieldChanges(before, after) {
64463
+ const out = [];
64464
+ const keys = Object.keys(after);
64465
+ for (const key of keys) {
64466
+ if (IGNORED_FIELDS.has(key))
64467
+ continue;
64468
+ const b = before ? normalize(key, before[key]) : undefined;
64469
+ const a = normalize(key, after[key]);
64470
+ if (!same(a, b))
64471
+ out.push({ field: key, before: b, after: a });
64472
+ }
64473
+ return out;
64474
+ }
64475
+ /** Per-service differences between two graphs (services removed from `after` are not reported). */
64476
+ function diffGraphs(before, after) {
64477
+ const out = [];
64478
+ for (const name of Object.keys(after.vertices).sort()) {
64479
+ const b = before.vertices[name];
64480
+ const fields = fieldChanges(b?.attributes, after.vertices[name].attributes);
64481
+ const kidsBefore = childLinks(before, name);
64482
+ const kidsAfter = childLinks(after, name);
64483
+ const childrenChanged = !same(kidsBefore, kidsAfter);
64484
+ if (b && !fields.length && !childrenChanged)
64485
+ continue;
64486
+ out.push({
64487
+ service: name,
64488
+ status: b ? 'changed' : 'created',
64489
+ fields,
64490
+ ...(childrenChanged ? { children: { before: kidsBefore, after: kidsAfter } } : {}),
64491
+ });
64492
+ }
64493
+ return out;
64494
+ }
64495
+ ServiceBulk.diffGraphs = diffGraphs;
64496
+ /**
64497
+ * Plan changes against a graph read for `targets`: the diff, the services the
64498
+ * payload must carry, and the store body.
64499
+ * @throws Error when a change is invalid or a parent's weights exceed 100 %.
64500
+ */
64501
+ function planChanges(graph, targets, changes) {
64502
+ const after = applyChanges(graph, changes);
64503
+ const diff = diffGraphs(graph, after);
64504
+ const save = descendantClosure(after, diff.map((d) => d.service)).sort();
64505
+ for (const name of save) {
64506
+ try {
64507
+ exports.ServiceTransform.assertWeightsWithinLimit(after.edges, name);
64508
+ }
64509
+ catch (e) {
64510
+ throw new Error(`'${name}': ${e.message}`);
64511
+ }
64512
+ }
64513
+ return { plan: { targets, changes, diff, save }, body: diff.length ? bodyFor(after, save) : { vertices: [], edges: [] } };
64514
+ }
64515
+ ServiceBulk.planChanges = planChanges;
64516
+ /**
64517
+ * What moved between a plan and a fresh read, limited to the values the plan
64518
+ * replaces: a changed field, a changed set of children, a service the plan
64519
+ * edits that is gone, or one it creates that now exists. Empty = safe to commit.
64520
+ */
64521
+ function findConflicts(planned, fresh) {
64522
+ const conflicts = [];
64523
+ for (const d of planned.diff) {
64524
+ const now = fresh.vertices[d.service];
64525
+ if (d.status === 'created') {
64526
+ if (now)
64527
+ conflicts.push(`'${d.service}' was created by someone else`);
64528
+ continue;
64529
+ }
64530
+ if (!now) {
64531
+ conflicts.push(`'${d.service}' no longer exists`);
64532
+ continue;
64533
+ }
64534
+ for (const f of d.fields) {
64535
+ const current = normalize(f.field, now.attributes[f.field]);
64536
+ if (!same(current, f.before)) {
64537
+ conflicts.push(`'${d.service}' ${f.field}: planned from ${JSON.stringify(f.before)}, now ${JSON.stringify(current)}`);
64538
+ }
64539
+ }
64540
+ if (d.children && !same(childLinks(fresh, d.service), d.children.before)) {
64541
+ conflicts.push(`'${d.service}' children changed since the plan`);
64542
+ }
64543
+ }
64544
+ return conflicts;
64545
+ }
64546
+ ServiceBulk.findConflicts = findConflicts;
64547
+ })(exports.ServiceBulk || (exports.ServiceBulk = {}));
64548
+
64549
+ /**
64550
+ * Pure selection and edit expansion for `service bulk-update`: which services a
64551
+ * selector picks, and which concrete {@link ServiceBulk.ServiceChange}s one set of
64552
+ * edits produces for each — only the ones that would change something, with the
64553
+ * reason for every edit that would not (already tagged, text not found, …).
64554
+ */
64555
+ exports.ServiceBulkSelect = void 0;
64556
+ (function (ServiceBulkSelect) {
64557
+ const names = (what) => v4.z.array(v4.z.string().min(1)).min(1).describe(what);
64558
+ ServiceBulkSelect.ServiceSelectorSchema = v4.z
64559
+ .strictObject({
64560
+ services: names('Exactly these services (exact, case-sensitive names).').optional(),
64561
+ root: v4.z
64562
+ .string()
64563
+ .min(1)
64564
+ .describe('This service and its descendants (exact name).')
64565
+ .optional(),
64566
+ depth: v4.z
64567
+ .number()
64568
+ .int()
64569
+ .min(0)
64570
+ .describe('With root: 0 = root only, 1 = root and direct children, … (default: all).')
64571
+ .optional(),
64572
+ name: names('Name matches any of these globs (* and ?, case-insensitive).').optional(),
64573
+ hasTag: names('Has every one of these tags (exact).').optional(),
64574
+ lacksTag: names('Has none of these tags (exact).').optional(),
64575
+ hasProperty: names('Has every one of these custom properties (exact names).').optional(),
64576
+ lacksProperty: names('Has none of these custom properties (exact names).').optional(),
64577
+ where: v4.z
64578
+ .record(v4.z.string().min(1), v4.z.string())
64579
+ .describe('Custom property name → glob its value must match (case-insensitive; no * = equals).')
64580
+ .optional(),
64581
+ location: v4.z.string().describe('Location matches this glob (case-insensitive).').optional(),
64582
+ })
64583
+ .refine((s) => Object.values(s).some((v) => v !== undefined), {
64584
+ message: 'a selector needs at least one criterion',
64585
+ })
64586
+ .refine((s) => s.depth === undefined || s.root !== undefined, {
64587
+ message: 'depth needs root',
64588
+ })
64589
+ .describe('Which services to edit; every criterion given must hold (AND).');
64590
+ ServiceBulkSelect.BulkEditSchema = v4.z
64591
+ .strictObject({
64592
+ addTags: names('Tags to add.').optional(),
64593
+ removeTags: names('Tags to remove.').optional(),
64594
+ setProperties: v4.z
64595
+ .record(v4.z.string().min(1), v4.z.string())
64596
+ .describe('Custom properties to set (name → value); other properties are kept.')
64597
+ .optional(),
64598
+ removeProperties: names('Custom properties to remove.').optional(),
64599
+ replaceInProperty: v4.z
64600
+ .strictObject({
64601
+ property: v4.z.string().min(1).describe("Property name, or '*' for every property."),
64602
+ find: v4.z.string().min(1).describe('Text to find (case-sensitive substring).'),
64603
+ replaceWith: v4.z.string().describe('Replacement for every occurrence.'),
64604
+ })
64605
+ .describe('Search and replace inside custom property values.')
64606
+ .optional(),
64607
+ setLocation: v4.z.string().describe('New location.').optional(),
64608
+ setDescription: v4.z.string().describe('New description.').optional(),
64609
+ })
64610
+ .refine((e) => Object.values(e).some((v) => v !== undefined), {
64611
+ message: 'at least one edit is needed',
64612
+ })
64613
+ .describe('The edits applied to every selected service.');
64614
+ function subjectFromVertex(v) {
64615
+ const a = v.attributes;
64616
+ return { name: a.name, tags: a.tags, properties: a.customProperties, location: a.location };
64617
+ }
64618
+ ServiceBulkSelect.subjectFromVertex = subjectFromVertex;
64619
+ /** From a services-list row, whose custom properties are a name → value map. */
64620
+ function subjectFromListRow(row) {
64621
+ return {
64622
+ name: row.name,
64623
+ tags: row.tags ?? [],
64624
+ properties: Object.entries(row.customProperties ?? {}).map(([name, value]) => ({ name, value })),
64625
+ location: row.location ?? '',
64626
+ };
64627
+ }
64628
+ ServiceBulkSelect.subjectFromListRow = subjectFromListRow;
64629
+ /** A case-insensitive, anchored glob: `*` any run, `?` one character. */
64630
+ function globToRegExp(glob) {
64631
+ const body = glob
64632
+ .split('')
64633
+ .map((c) => (c === '*' ? '.*' : c === '?' ? '.' : c.replace(/[.+^${}()|[\]\\]/g, '\\$&')))
64634
+ .join('');
64635
+ return new RegExp(`^${body}$`, 'i');
64636
+ }
64637
+ ServiceBulkSelect.globToRegExp = globToRegExp;
64638
+ /** The non-scope criteria (everything but services/root/depth) against one service. */
64639
+ function matchesFilters(s, sel) {
64640
+ const has = (p) => s.properties.some((x) => x.name === p);
64641
+ if (sel.name && !sel.name.some((g) => globToRegExp(g).test(s.name)))
64642
+ return false;
64643
+ if (sel.hasTag && !sel.hasTag.every((t) => s.tags.includes(t)))
64644
+ return false;
64645
+ if (sel.lacksTag && sel.lacksTag.some((t) => s.tags.includes(t)))
64646
+ return false;
64647
+ if (sel.hasProperty && !sel.hasProperty.every(has))
64648
+ return false;
64649
+ if (sel.lacksProperty && sel.lacksProperty.some(has))
64650
+ return false;
64651
+ if (sel.location !== undefined && !globToRegExp(sel.location).test(s.location))
64652
+ return false;
64653
+ for (const [prop, glob] of Object.entries(sel.where ?? {})) {
64654
+ const re = globToRegExp(glob);
64655
+ if (!s.properties.some((x) => x.name === prop && re.test(x.value)))
64656
+ return false;
64657
+ }
64658
+ return true;
64659
+ }
64660
+ ServiceBulkSelect.matchesFilters = matchesFilters;
64661
+ /** The selector as one line, for messages: `name="*virt*" AND hasTag=internal`. */
64662
+ function describeSelector(sel) {
64663
+ const parts = [];
64664
+ const list = (xs) => xs.join(',');
64665
+ if (sel.services)
64666
+ parts.push(`services=${list(sel.services)}`);
64667
+ if (sel.root)
64668
+ parts.push(`root="${sel.root}"`);
64669
+ if (sel.depth !== undefined)
64670
+ parts.push(`depth=${sel.depth}`);
64671
+ if (sel.name)
64672
+ parts.push(`name="${list(sel.name)}"`);
64673
+ if (sel.hasTag)
64674
+ parts.push(`hasTag=${list(sel.hasTag)}`);
64675
+ if (sel.lacksTag)
64676
+ parts.push(`lacksTag=${list(sel.lacksTag)}`);
64677
+ if (sel.hasProperty)
64678
+ parts.push(`hasProperty=${list(sel.hasProperty)}`);
64679
+ if (sel.lacksProperty)
64680
+ parts.push(`lacksProperty=${list(sel.lacksProperty)}`);
64681
+ for (const [p, g] of Object.entries(sel.where ?? {}))
64682
+ parts.push(`where.${p}="${g}"`);
64683
+ if (sel.location !== undefined)
64684
+ parts.push(`location="${sel.location}"`);
64685
+ return parts.join(' AND ');
64686
+ }
64687
+ ServiceBulkSelect.describeSelector = describeSelector;
64688
+ /** `root` and its descendants down to `depth` levels (all when undefined). */
64689
+ function withinDepth(graph, root, depth) {
64690
+ const seen = new Set([root]);
64691
+ let frontier = [root];
64692
+ for (let level = 0; frontier.length && (depth === undefined || level < depth); level++) {
64693
+ const next = [];
64694
+ for (const parent of frontier) {
64695
+ for (const link of exports.ServiceBulk.childLinks(graph, parent)) {
64696
+ if (!seen.has(link.child)) {
64697
+ seen.add(link.child);
64698
+ next.push(link.child);
64699
+ }
64700
+ }
64701
+ }
64702
+ frontier = next;
64703
+ }
64704
+ return [...seen];
64705
+ }
64706
+ ServiceBulkSelect.withinDepth = withinDepth;
64707
+ /** Edits that contradict each other; any entry blocks the update. */
64708
+ function editBlockers(e) {
64709
+ const out = [];
64710
+ for (const t of e.addTags ?? []) {
64711
+ if (e.removeTags?.includes(t))
64712
+ out.push(`tag '${t}' is both added and removed`);
64713
+ }
64714
+ for (const p of Object.keys(e.setProperties ?? {})) {
64715
+ if (e.removeProperties?.includes(p))
64716
+ out.push(`property '${p}' is both set and removed`);
64717
+ }
64718
+ const r = e.replaceInProperty;
64719
+ if (r) {
64720
+ if (r.find === r.replaceWith)
64721
+ out.push('find and replaceWith are the same — nothing would change');
64722
+ const named = r.property === '*' ? [] : [r.property];
64723
+ for (const p of named) {
64724
+ if (e.setProperties?.[p] !== undefined || e.removeProperties?.includes(p)) {
64725
+ out.push(`property '${p}' is both replaced and set or removed`);
64726
+ }
64727
+ }
64728
+ }
64729
+ return out;
64730
+ }
64731
+ ServiceBulkSelect.editBlockers = editBlockers;
64732
+ /**
64733
+ * Turn the edits into concrete changes for each named service, emitting a
64734
+ * change only where it alters the service. The services must be in the graph.
64735
+ */
64736
+ function expandEdits(graph, services, e) {
64737
+ const changes = [];
64738
+ const outcomes = [];
64739
+ const warnings = [];
64740
+ for (const service of [...services].sort()) {
64741
+ const v = graph.vertices[service];
64742
+ if (!v)
64743
+ throw new Error(`No service with name '${service}' found`);
64744
+ const a = v.attributes;
64745
+ const will = [];
64746
+ const already = [];
64747
+ const values = (p) => a.customProperties.filter((x) => x.name === p).map((x) => x.value);
64748
+ const add = (e.addTags ?? []).filter((t) => {
64749
+ if (a.tags.includes(t)) {
64750
+ already.push(`already has tag '${t}'`);
64751
+ return false;
64752
+ }
64753
+ const variant = a.tags.find((x) => x.toLowerCase() === t.toLowerCase());
64754
+ if (variant)
64755
+ warnings.push(`'${service}' has tag '${variant}'; adding '${t}' as well`);
64756
+ return true;
64757
+ });
64758
+ if (add.length) {
64759
+ changes.push({ op: 'addTags', service, tags: add });
64760
+ will.push(`add tag ${add.map((t) => `'${t}'`).join(', ')}`);
64761
+ }
64762
+ const remove = (e.removeTags ?? []).filter((t) => {
64763
+ if (a.tags.includes(t))
64764
+ return true;
64765
+ already.push(`does not have tag '${t}'`);
64766
+ return false;
64767
+ });
64768
+ if (remove.length) {
64769
+ changes.push({ op: 'removeTags', service, tags: remove });
64770
+ will.push(`remove tag ${remove.map((t) => `'${t}'`).join(', ')}`);
64771
+ }
64772
+ for (const [name, value] of Object.entries(e.setProperties ?? {})) {
64773
+ const now = values(name);
64774
+ if (now.length === 1 && now[0] === value) {
64775
+ already.push(`property '${name}' is already '${value}'`);
64776
+ continue;
64777
+ }
64778
+ if (now.length > 1) {
64779
+ warnings.push(`'${service}' has ${now.length} values for property '${name}'; setting leaves one`);
64780
+ }
64781
+ changes.push({ op: 'setProperty', service, name, value });
64782
+ will.push(now.length ? `set '${name}': '${now.join("', '")}' → '${value}'` : `add property '${name}' = '${value}'`);
64783
+ }
64784
+ for (const name of e.removeProperties ?? []) {
64785
+ if (!values(name).length) {
64786
+ already.push(`has no property '${name}'`);
64787
+ continue;
64788
+ }
64789
+ changes.push({ op: 'removeProperty', service, name });
64790
+ will.push(`remove property '${name}'`);
64791
+ }
64792
+ const r = e.replaceInProperty;
64793
+ if (r) {
64794
+ const targets = r.property === '*' ? [...new Set(a.customProperties.map((x) => x.name))] : [r.property];
64795
+ let replaced = false;
64796
+ for (const name of targets) {
64797
+ const now = values(name);
64798
+ if (!now.some((x) => x.includes(r.find)))
64799
+ continue;
64800
+ if (now.length > 1) {
64801
+ warnings.push(`'${service}' has ${now.length} values for property '${name}'; not replaced`);
64802
+ already.push(`property '${name}' has ${now.length} values — skipped`);
64803
+ continue;
64804
+ }
64805
+ const value = now[0].split(r.find).join(r.replaceWith);
64806
+ changes.push({ op: 'setProperty', service, name, value });
64807
+ will.push(`set '${name}': '${now[0]}' → '${value}'`);
64808
+ replaced = true;
64809
+ }
64810
+ if (!replaced && !already.some((x) => x.includes('— skipped'))) {
64811
+ already.push(`text '${r.find}' not found in ${r.property === '*' ? 'any property' : `'${r.property}'`}`);
64812
+ }
64813
+ }
64814
+ const attrs = {};
64815
+ if (e.setLocation !== undefined) {
64816
+ if (a.location === e.setLocation)
64817
+ already.push(`location is already '${e.setLocation}'`);
64818
+ else {
64819
+ attrs.location = e.setLocation;
64820
+ will.push(`location: '${a.location}' → '${e.setLocation}'`);
64821
+ }
64822
+ }
64823
+ if (e.setDescription !== undefined) {
64824
+ if (a.description === e.setDescription)
64825
+ already.push('description is already as given');
64826
+ else {
64827
+ attrs.description = e.setDescription;
64828
+ will.push(`description: '${a.description}' → '${e.setDescription}'`);
64829
+ }
64830
+ }
64831
+ if (Object.keys(attrs).length)
64832
+ changes.push({ op: 'setAttributes', service, ...attrs });
64833
+ outcomes.push({ service, will, already });
64834
+ }
64835
+ return { changes, outcomes, warnings };
64836
+ }
64837
+ ServiceBulkSelect.expandEdits = expandEdits;
64838
+ /**
64839
+ * A short, stable hash of what a plan would save (its diff and save set). A
64840
+ * dry-run prints it; an apply must present it, and refuses when the fresh
64841
+ * plan hashes differently — so what was reviewed is what gets saved.
64842
+ */
64843
+ function planToken(plan) {
64844
+ return cyrb53(JSON.stringify({ diff: plan.diff, save: plan.save }))
64845
+ .toString(16)
64846
+ .padStart(14, '0')
64847
+ .slice(0, 10);
64848
+ }
64849
+ ServiceBulkSelect.planToken = planToken;
64850
+ })(exports.ServiceBulkSelect || (exports.ServiceBulkSelect = {}));
64851
+
64852
+ /**
64853
+ * The `service export` / `service export-hierarchy` file format and the
64854
+ * `service import` boundary validator.
64855
+ *
64856
+ * The envelope wraps a re-postable store body ({@link CreateServices.CreateServiceBody})
64857
+ * with provenance metadata. `import` accepts either the envelope or a bare body.
64858
+ */
64859
+ exports.ServiceExport = void 0;
64860
+ (function (ServiceExport) {
64861
+ ServiceExport.SCHEMA_VERSION = 1;
64862
+ // Structural guard for a store body — does not re-validate every field
64863
+ // (the server is the authority); just enough to reject obviously-wrong files.
64864
+ const BodyShape = v4.z.looseObject({
64865
+ vertices: v4.z.array(v4.z.looseObject({ attributes: v4.z.looseObject({ name: v4.z.string() }) })),
64866
+ edges: v4.z.array(v4.z.looseObject({
64867
+ sourceExternalId: v4.z.string(),
64868
+ targetExternalId: v4.z.string(),
64869
+ })),
64870
+ });
64871
+ const EnvelopeShape = v4.z.looseObject({
64872
+ schemaVersion: v4.z.literal(1),
64873
+ kind: v4.z.enum(['service', 'service-hierarchy']),
64874
+ sourceTenant: v4.z.string().optional(),
64875
+ exportedAt: v4.z.string(),
64876
+ body: BodyShape,
64877
+ });
64878
+ /** Wrap a store body in an export envelope. */
64879
+ function envelope(kind, body, sourceTenant, exportedAt) {
64880
+ return { schemaVersion: ServiceExport.SCHEMA_VERSION, kind, sourceTenant, exportedAt, body };
64881
+ }
64882
+ ServiceExport.envelope = envelope;
64883
+ /**
64884
+ * Validate an import file (already JSON-parsed) and return the store body.
64885
+ * Accepts a full export envelope or a bare `{ vertices, edges }` body.
64886
+ * @throws Error when the input is neither shape.
64887
+ */
64888
+ function parseImport(raw) {
64889
+ const asEnvelope = EnvelopeShape.safeParse(raw);
64890
+ if (asEnvelope.success) {
64891
+ return asEnvelope.data.body;
64892
+ }
64893
+ const asBody = BodyShape.safeParse(raw);
64894
+ if (asBody.success) {
64895
+ return raw;
64896
+ }
64897
+ throw new Error('Import file is neither a service export envelope nor a bare {vertices, edges} body. ' +
64898
+ `Envelope error: ${asEnvelope.error.message}`);
64899
+ }
64900
+ ServiceExport.parseImport = parseImport;
64901
+ /**
64902
+ * As {@link parseImport}, plus the envelope's provenance: which tenant the file came from
64903
+ * (absent for a bare body or an envelope that did not record it) and when.
64904
+ * @throws Error when the input is neither shape.
64905
+ */
64906
+ function parseImportFile(raw) {
64907
+ const body = parseImport(raw);
64908
+ const asEnvelope = EnvelopeShape.safeParse(raw);
64909
+ if (!asEnvelope.success)
64910
+ return { body };
64911
+ return {
64912
+ body,
64913
+ ...(asEnvelope.data.sourceTenant ? { sourceTenant: asEnvelope.data.sourceTenant } : {}),
64914
+ exportedAt: asEnvelope.data.exportedAt,
64915
+ };
64916
+ }
64917
+ ServiceExport.parseImportFile = parseImportFile;
64918
+ })(exports.ServiceExport || (exports.ServiceExport = {}));
64919
+
64920
+ /**
64921
+ * Pure planning for `service import` into any tenant
64922
+ * (docs/internal/service-bulk-save-findings-2026-10.md → "Cross-tenant import"):
64923
+ *
64924
+ * - A service's `metrics` are tenant identity: a save carrying another tenant's (or a
64925
+ * re-created service's stale) metrics is stored verbatim and the server assigns none, so
64926
+ * health, risk and availability point at nothing. Metrics therefore always come from the
64927
+ * target: an existing service keeps its current ones, a new one is sent with `[]`.
64928
+ * - Every saved service is overwritten (attributes and child links), so an import into a
64929
+ * tenant that already has some of the names is a diff to review, not a blind write.
64930
+ */
64931
+ exports.ServiceImport = void 0;
64932
+ (function (ServiceImport) {
64933
+ /** Prefix every service name (and link endpoint) in a body. */
64934
+ function renameBody(body, prefix) {
64935
+ const rename = (n) => `${prefix}${n}`;
64936
+ return {
64937
+ vertices: body.vertices.map((v) => ({
64938
+ ...v,
64939
+ externalId: rename(v.attributes.name),
64940
+ attributes: { ...v.attributes, name: rename(v.attributes.name) },
64941
+ })),
64942
+ edges: body.edges.map((e) => ({
64943
+ ...e,
64944
+ sourceExternalId: rename(e.sourceExternalId),
64945
+ targetExternalId: rename(e.targetExternalId),
64946
+ })),
64947
+ };
64948
+ }
64949
+ ServiceImport.renameBody = renameBody;
64950
+ /**
64951
+ * Plan saving `file` into a target whose current state for the same names is `target`
64952
+ * (missing names = new services).
64953
+ */
64954
+ function planImport(file, target) {
64955
+ const blockers = [];
64956
+ const names = new Set(file.vertices.map((v) => v.attributes.name));
64957
+ const dangling = file.edges.filter((e) => !names.has(e.sourceExternalId) || !names.has(e.targetExternalId));
64958
+ if (dangling.length) {
64959
+ blockers.push(`links to services not in the file: ${dangling.map((e) => `${e.sourceExternalId}→${e.targetExternalId}`).join(', ')}`);
64960
+ }
64961
+ const metricsDropped = [];
64962
+ const metricsKeptFromTarget = [];
64963
+ const vertices = file.vertices.map((v) => {
64964
+ const name = v.attributes.name;
64965
+ const current = target.vertices[name];
64966
+ const fileMetrics = v.attributes.metrics ?? [];
64967
+ if (!current) {
64968
+ if (fileMetrics.length)
64969
+ metricsDropped.push(name);
64970
+ return { ...v, externalId: name, attributes: { ...v.attributes, root_service: null, metrics: [] } };
64971
+ }
64972
+ const targetMetrics = current.attributes.metrics ?? [];
64973
+ if (JSON.stringify(fileMetrics) !== JSON.stringify(targetMetrics))
64974
+ metricsKeptFromTarget.push(name);
64975
+ return { ...v, externalId: name, attributes: { ...v.attributes, root_service: null, metrics: targetMetrics } };
64976
+ });
64977
+ const body = { vertices, edges: file.edges };
64978
+ for (const parent of names) {
64979
+ try {
64980
+ exports.ServiceTransform.assertWeightsWithinLimit(file.edges, parent);
64981
+ }
64982
+ catch (e) {
64983
+ blockers.push(`'${parent}': ${e.message}`);
64984
+ }
64985
+ }
64986
+ const after = {
64987
+ vertices: { ...target.vertices, ...Object.fromEntries(vertices.map((v) => [v.attributes.name, v])) },
64988
+ edges: [...target.edges.filter((e) => !names.has(e.sourceExternalId)), ...file.edges],
64989
+ };
64990
+ const diff = exports.ServiceBulk.diffGraphs(target, after).filter((d) => names.has(d.service));
64991
+ const created = diff.filter((d) => d.status === 'created').map((d) => d.service).sort();
64992
+ const overwritten = diff.filter((d) => d.status === 'changed');
64993
+ const unchanged = [...names].filter((n) => target.vertices[n] && !overwritten.some((d) => d.service === n)).sort();
64994
+ return {
64995
+ body,
64996
+ created,
64997
+ overwritten,
64998
+ unchanged,
64999
+ metricsDropped: metricsDropped.sort(),
65000
+ metricsKeptFromTarget: metricsKeptFromTarget.sort(),
65001
+ blockers,
65002
+ };
65003
+ }
65004
+ ServiceImport.planImport = planImport;
65005
+ /** Stable short hash of what an import would change; the apply must present it when overwriting. */
65006
+ function importToken(plan) {
65007
+ return cyrb53(JSON.stringify({ created: plan.created, overwritten: plan.overwritten }))
65008
+ .toString(16)
65009
+ .padStart(14, '0')
65010
+ .slice(0, 10);
65011
+ }
65012
+ ServiceImport.importToken = importToken;
65013
+ })(exports.ServiceImport || (exports.ServiceImport = {}));
65014
+
63999
65015
  exports.OIService = void 0;
64000
65016
  (function (OIService) {
64001
65017
  /** @internal */
@@ -64231,7 +65247,7 @@ exports.OIService = void 0;
64231
65247
  OIService.DEFAULT_SERVICE_REQUEST_PROJECTION_FILTER = ["maintenance", "availability_lastday", "availability", "health", "extId", "name", "risk", "trend", "healthBucket"];
64232
65248
  OIService.TYPICAL_SERVICE_REQUEST_PROJECTION_FILTER = ["rollupFilteredAlarmCount", "situationCount", "availability", "filteredParent", "availability_lastday",
64233
65249
  "immediateFilteredChildren", "immediateFilterChildrenCount", "health", "extId", "location", "maintenance",
64234
- "name", "risk", "status", "tags", "serviceMetricGroups", "healthBucket"];
65250
+ "name", "risk", "status", "tags", "serviceMetricGroups", "healthBucket", "customProperties"];
64235
65251
  /** @internal */
64236
65252
  OIService.DEFAULT_SERVICE_REQUEST_BODY = {
64237
65253
  "time": DateTime.now().toMillis(),
@@ -66396,6 +67412,82 @@ const serviceDetailResponseBody = {
66396
67412
  },
66397
67413
  };
66398
67414
 
67415
+ /** How far back a listed service metric counts as published. */
67416
+ const SERVICE_METRIC_PRESENCE_WINDOW_MS = 30 * 86_400_000;
67417
+ /**
67418
+ * Marks each metric a service record lists with `published`: whether the metric store holds it within
67419
+ * {@link SERVICE_METRIC_PRESENCE_WINDOW_MS}. A service record lists `service_availability` for every service, but the
67420
+ * platform computes it only when the service has an `availability` metric configured (measured 2026-10-26 across 108
67421
+ * services: none of the 93 without one had it in 30 days; 10 of the 15 with one did), so an agent that reads the id
67422
+ * from the record otherwise spends calls on a metric that does not exist. `service_health` / `service_risk` were
67423
+ * published for all 108.
67424
+ */
67425
+ function markServiceMetricPresence(overview, publishedIds) {
67426
+ const metrics = overview.attributes.metrics ?? [];
67427
+ const configured = metrics.find((m) => m.type === 'availability');
67428
+ const marked = metrics.map((m) => {
67429
+ if (publishedIds.has(m.id))
67430
+ return { ...m, published: true };
67431
+ const note = m.type === 'service_availability' && !configured
67432
+ ? 'Never computed: a service publishes service_availability only when it has an availability metric configured, and this one has none. Read service_health and service_risk instead.'
67433
+ : m.type === 'service_availability' && configured
67434
+ ? `Not published in the last 30 days, although an availability metric is configured (${configured.attributeName}): that metric may not be reporting.`
67435
+ : 'Not published in the last 30 days: there is no data under this id.';
67436
+ return { ...m, published: false, note };
67437
+ });
67438
+ return { ...overview, attributes: { ...overview.attributes, metrics: marked } };
67439
+ }
67440
+ // export const SERVICE_OVERVIEW_EXAMPLE: ServiceOverviewVertex = {
67441
+ // externalId:
67442
+ // 'SA:AA0725E0-0402-4320-A2B7-407025E9D673:2ee14366-6460-4606-9d5b-fbae9a4100b6',
67443
+ // attributes: {
67444
+ // type: 'saService',
67445
+ // name: 'ACME NetOps Salisbury DC - NetOps-O2',
67446
+ // state: 'ACTIVE',
67447
+ // root_service: ['ACME NetOps Salisbury DC - NetOps-O2'],
67448
+ // serviceContent: [],
67449
+ // tags: [],
67450
+ // location: '',
67451
+ // source: 'OI',
67452
+ // description: '',
67453
+ // createTimestamp: 1744572230371,
67454
+ // timestamp: 1744589912503,
67455
+ // maintenance: false,
67456
+ // situationsIncludeChildServices: false,
67457
+ // restrictSLOOnMaintenance: false,
67458
+ // serviceType: 'service',
67459
+ // customProperties: [],
67460
+ // metrics: [
67461
+ // {
67462
+ // type: 'service_risk',
67463
+ // sourceName: 'OI|SA|SERVICES|ALL',
67464
+ // attributeName: '2ee14366-6460-4606-9d5b-fbae9a4100b6:service_risk',
67465
+ // id: 'f.l-AE-H9B-OopMDK0B',
67466
+ // firstSeen: 1744571774000,
67467
+ // },
67468
+ // {
67469
+ // type: 'service_health',
67470
+ // sourceName: 'OI|SA|SERVICES|ALL',
67471
+ // attributeName: '2ee14366-6460-4606-9d5b-fbae9a4100b6:service_health',
67472
+ // id: '7Nm-AAB-H9B-kB8SIJ0B',
67473
+ // firstSeen: 1744571774000,
67474
+ // },
67475
+ // {
67476
+ // type: 'service_availability',
67477
+ // sourceName: 'OI|SA|SERVICES|ALL',
67478
+ // attributeName:
67479
+ // '2ee14366-6460-4606-9d5b-fbae9a4100b6:service_availability',
67480
+ // id: 'ddm-AAB-H9B-BCFeKK0B',
67481
+ // firstSeen: 1744571774000,
67482
+ // },
67483
+ // ],
67484
+ // customMetrics: [],
67485
+ // },
67486
+ // endTime: 7537103999999,
67487
+ // id: 3330,
67488
+ // startTime: 1744589912513,
67489
+ // };
67490
+
66399
67491
  exports.SituationLifecycle = void 0;
66400
67492
  (function (SituationLifecycle) {
66401
67493
  })(exports.SituationLifecycle || (exports.SituationLifecycle = {}));
@@ -70662,7 +71754,283 @@ class AgentService {
70662
71754
  }
70663
71755
  }
70664
71756
 
70665
- var DEFAULT_ALARMS_REQUEST_BODY$1 = exports.OIAlarm.DEFAULT_ALARMS_REQUEST_BODY;
71757
+ /**
71758
+ * Most alarms one `oi/v2/api/alarms/_search` request returns, whatever
71759
+ * `pageSize` asks for (1001, 2000 and 5000 all answered 1000; measured on
71760
+ * demo-dev 2026-10-22). `pageNumber` > 0 answers an empty page, so a range
71761
+ * holding more alarms can only be read by splitting it.
71762
+ */
71763
+ const ALARM_SEARCH_PAGE_CAP = 1000;
71764
+ /**
71765
+ * A complete read of an alarm range was not possible. Thrown instead of
71766
+ * returning a partial set, so a caller never mistakes a short list for the
71767
+ * whole range.
71768
+ */
71769
+ class IncompleteAlarmSearchError extends Error {
71770
+ reason;
71771
+ expected;
71772
+ retrieved;
71773
+ constructor(reason, expected, retrieved, detail) {
71774
+ super(`Alarm search incomplete (${reason}): ${detail}`);
71775
+ this.reason = reason;
71776
+ this.expected = expected;
71777
+ this.retrieved = retrieved;
71778
+ this.name = 'IncompleteAlarmSearchError';
71779
+ }
71780
+ }
71781
+ const updatedAt = (alarm) => Number(alarm.lastUpdateTime ?? 0);
71782
+ /**
71783
+ * Reads every alarm in `[from, to]`, splitting the range until each window
71784
+ * fits in one response.
71785
+ *
71786
+ * A window holds every alarm whose lifetime (`timeOrigin` to `closedTime`, or
71787
+ * now) overlaps it, so windows overlap and their counts do not add up; their
71788
+ * union is the range (measured: 448 of 448, 300 of them in both halves). The
71789
+ * merge keys on `alarmId` and keeps the copy with the later `lastUpdateTime`.
71790
+ *
71791
+ * Fails with {@link IncompleteAlarmSearchError} instead of returning less:
71792
+ * - `unsplittable` — more alarms than one response holds are present at a
71793
+ * single instant (every window containing it is over the cap);
71794
+ * - `changed` — the range's count moved during the read, or the merged set
71795
+ * does not match it (alarms arriving or backdated into the range);
71796
+ * - `request-budget` — `maxRequests` ran out.
71797
+ */
71798
+ async function searchAlarmWindows(search, from, to, options = {}) {
71799
+ const concurrency = options.concurrency ?? 4;
71800
+ const maxRequests = options.maxRequests ?? 2000;
71801
+ const log = options.log ?? new Logging.NullSimpleLog();
71802
+ const alarms = new Map();
71803
+ let requests = 0;
71804
+ let windows = 0;
71805
+ let expected = 0;
71806
+ const merge = (page) => {
71807
+ for (const alarm of page.alarms) {
71808
+ const seen = alarms.get(alarm.alarmId);
71809
+ if (!seen || updatedAt(alarm) > updatedAt(seen))
71810
+ alarms.set(alarm.alarmId, alarm);
71811
+ }
71812
+ };
71813
+ const complete = (page) => page.count <= page.alarms.length;
71814
+ const request = async (w) => {
71815
+ if (requests >= maxRequests) {
71816
+ throw new IncompleteAlarmSearchError('request-budget', expected, alarms.size, `${maxRequests} requests made, ${alarms.size} of ${expected} alarms read`);
71817
+ }
71818
+ requests++;
71819
+ return search(w.from, w.to);
71820
+ };
71821
+ const first = await request({ from, to });
71822
+ expected = first.count;
71823
+ if (complete(first)) {
71824
+ merge(first);
71825
+ return { alarms, expected, requests, windows: 1 };
71826
+ }
71827
+ log.info(`${expected} alarms in range; reading it in windows of at most ${ALARM_SEARCH_PAGE_CAP}`);
71828
+ const pending = [{ from, to }];
71829
+ const split = (w) => {
71830
+ const mid = Math.floor((w.from + w.to) / 2);
71831
+ return [
71832
+ { from: w.from, to: mid },
71833
+ { from: mid, to: w.to },
71834
+ ];
71835
+ };
71836
+ const readWindow = async (w) => {
71837
+ if (w.to - w.from <= 1) {
71838
+ const page = await request(w);
71839
+ if (complete(page)) {
71840
+ merge(page);
71841
+ windows++;
71842
+ return [];
71843
+ }
71844
+ throw new IncompleteAlarmSearchError('unsplittable', expected, alarms.size, `${page.count} alarms are present at ${new Date(w.from).toISOString()}; ` +
71845
+ `one response holds at most ${page.alarms.length}`);
71846
+ }
71847
+ const page = await request(w);
71848
+ if (complete(page)) {
71849
+ merge(page);
71850
+ windows++;
71851
+ return [];
71852
+ }
71853
+ const mid = Math.floor((w.from + w.to) / 2);
71854
+ const instant = await request({ from: mid, to: mid + 1 });
71855
+ if (!complete(instant)) {
71856
+ throw new IncompleteAlarmSearchError('unsplittable', expected, alarms.size, `${instant.count} alarms are present at ${new Date(mid).toISOString()}; ` +
71857
+ `one response holds at most ${instant.alarms.length}`);
71858
+ }
71859
+ return split(w);
71860
+ };
71861
+ // Split the root once without re-reading it.
71862
+ pending.splice(0, 1, ...split({ from, to }));
71863
+ while (pending.length > 0) {
71864
+ const batch = pending.splice(0, concurrency);
71865
+ const next = await Promise.all(batch.map(readWindow));
71866
+ pending.push(...next.flat());
71867
+ }
71868
+ const last = await request({ from, to });
71869
+ if (last.count !== expected || alarms.size !== expected) {
71870
+ throw new IncompleteAlarmSearchError('changed', expected, alarms.size, `the range held ${expected} alarms at the start, ${last.count} at the end, ` +
71871
+ `and ${alarms.size} were read; alarms arrived or changed during the read`);
71872
+ }
71873
+ log.info(`Read ${alarms.size} alarms in ${windows} windows (${requests} requests)`);
71874
+ return { alarms, expected, requests, windows };
71875
+ }
71876
+
71877
+ /**
71878
+ * Most records one analytics query can reach: `from + size` over 10000 is
71879
+ * rejected ("Result window is too large"), and a count above it comes back as
71880
+ * a lower bound (`relation: gte`).
71881
+ */
71882
+ const ALARM_RECORD_WINDOW_CAP = 10_000;
71883
+ const ALARM_RECORD_PAGE_SIZE = 1000;
71884
+ /** An instant as the index's query syntax wants it: whole seconds, `+0000` (`Z` matches nothing). */
71885
+ const alarmRecordTime = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, '+0000');
71886
+ /** Epoch ms of an index time such as `2026-10-22T06:17:39+0000`. */
71887
+ const parseAlarmRecordTime = (value) => Date.parse(value.replace(/([+-]\d{2})(\d{2})$/, '$1:$2'));
71888
+ const windowQuery = (segment, from, to) => {
71889
+ const range = `${segment.field}:[${alarmRecordTime(from)} TO ${alarmRecordTime(to)}}`;
71890
+ return segment.extra ? `${range} AND (${segment.extra})` : range;
71891
+ };
71892
+ /**
71893
+ * Streams every alarm record that `match` selects in `[from, to)`, in open-time
71894
+ * order, reading the analytics index in windows of at most
71895
+ * {@link ALARM_RECORD_WINDOW_CAP} records.
71896
+ *
71897
+ * First the range is planned: count-only requests split it until each window
71898
+ * holds at most the cap, which gives the exact total (the index itself reports
71899
+ * any total over 10000 as "at least 10000"). Then each window is paged with a
71900
+ * fixed sort and checked: the records read must be exactly its planned count. Otherwise it throws
71901
+ * {@link IncompleteAlarmSearchError} rather than yielding a partial export:
71902
+ * - `changed` — the window's count or contents moved during the read;
71903
+ * - `unsplittable` — more than 10000 records share one second;
71904
+ * - `request-budget` — `maxRequests` ran out.
71905
+ * Records already yielded stay valid; the error says where the export stopped.
71906
+ */
71907
+ async function* exportAlarmRecords(source, from, to, match, options = {}) {
71908
+ const maxRequests = options.maxRequests ?? 20_000;
71909
+ const windowCap = options.windowCap ?? ALARM_RECORD_WINDOW_CAP;
71910
+ const pageSize = options.pageSize ?? ALARM_RECORD_PAGE_SIZE;
71911
+ const log = options.log ?? new Logging.NullSimpleLog();
71912
+ const start = Math.floor(from / 1000) * 1000;
71913
+ const end = Math.ceil(to / 1000) * 1000;
71914
+ let requests = 0;
71915
+ let exported = 0;
71916
+ const call = async (fn) => {
71917
+ if (requests >= maxRequests) {
71918
+ throw new IncompleteAlarmSearchError('request-budget', exported, exported, `${maxRequests} requests made; ${exported} alarms exported before stopping`);
71919
+ }
71920
+ requests++;
71921
+ return fn();
71922
+ };
71923
+ const segments = [];
71924
+ if (match === 'opened')
71925
+ segments.push({ field: 'startTime', from: start, to: end });
71926
+ if (match === 'closed')
71927
+ segments.push({ field: 'closedTime', from: start, to: end });
71928
+ if (match === 'active') {
71929
+ segments.push({ field: 'startTime', from: start, to: end });
71930
+ // Opened earlier and still open at `from`: closed after it, or not closed.
71931
+ const stillOpen = `closedTime:{${alarmRecordTime(start)} TO *] OR (*:* -_exists_:closedTime)`;
71932
+ const earlier = `startTime:[* TO ${alarmRecordTime(start)}} AND (${stillOpen})`;
71933
+ const [first] = await call(() => source.page(earlier, 0, 1));
71934
+ if (first) {
71935
+ const earliest = Math.floor(parseAlarmRecordTime(first.startTime) / 1000) * 1000;
71936
+ segments.unshift({ field: 'startTime', from: earliest, to: start, extra: stillOpen });
71937
+ }
71938
+ }
71939
+ const startedAt = Date.now();
71940
+ // Plan: split until every window's count is exact and within the cap.
71941
+ const plan = async (segment, a, b, out) => {
71942
+ const count = await call(() => source.count(windowQuery(segment, a, b)));
71943
+ if (count.exact && count.total <= windowCap) {
71944
+ if (count.total > 0)
71945
+ out.push({ segment, from: a, to: b, count: count.total });
71946
+ return;
71947
+ }
71948
+ if (b - a <= 1000) {
71949
+ throw new IncompleteAlarmSearchError('unsplittable', count.total, 0, `more than ${windowCap} alarms at ${alarmRecordTime(a)}; nothing was exported`);
71950
+ }
71951
+ const mid = a + Math.floor((b - a) / 2000) * 1000;
71952
+ await plan(segment, a, mid, out);
71953
+ await plan(segment, mid, b, out);
71954
+ };
71955
+ const windows = [];
71956
+ for (const segment of segments) {
71957
+ if (segment.to > segment.from)
71958
+ await plan(segment, segment.from, segment.to, windows);
71959
+ }
71960
+ const total = windows.reduce((sum, w) => sum + w.count, 0);
71961
+ options.onPlan?.({ total, windows: windows.length, elapsedMs: Date.now() - startedAt });
71962
+ // Read: page each window with a fixed sort; it must still hold its planned count.
71963
+ for (const [i, w] of windows.entries()) {
71964
+ const query = windowQuery(w.segment, w.from, w.to);
71965
+ const records = [];
71966
+ const ids = new Set();
71967
+ for (let offset = 0; offset < w.count; offset += pageSize) {
71968
+ const page = await call(() => source.page(query, offset, pageSize));
71969
+ if (page.length === 0)
71970
+ break;
71971
+ for (const record of page) {
71972
+ if (!ids.has(record.alarm_unique_id)) {
71973
+ ids.add(record.alarm_unique_id);
71974
+ records.push(record);
71975
+ }
71976
+ }
71977
+ }
71978
+ const recount = await call(() => source.count(query));
71979
+ if (ids.size !== w.count || recount.total !== w.count) {
71980
+ throw new IncompleteAlarmSearchError('changed', total, exported, `window ${alarmRecordTime(w.from)} – ${alarmRecordTime(w.to)} held ${w.count} alarms when planned, ` +
71981
+ `${recount.total} after reading, and ${ids.size} distinct were read; ` +
71982
+ `${exported} of ${total} exported before it. Alarms changed during the read — retry, or end the range further in the past`);
71983
+ }
71984
+ for (const record of records) {
71985
+ exported++;
71986
+ yield record;
71987
+ }
71988
+ options.onWindow?.({
71989
+ from: w.from,
71990
+ to: w.to,
71991
+ records: records.length,
71992
+ index: i + 1,
71993
+ windows: windows.length,
71994
+ exported,
71995
+ total,
71996
+ elapsedMs: Date.now() - startedAt,
71997
+ });
71998
+ }
71999
+ log.info(`Exported ${exported} alarms (${requests} requests)`);
72000
+ }
72001
+
72002
+ /**
72003
+ * Events per `oi/v2/api/alarms/lifecycle/_search` request. The endpoint
72004
+ * reports `totalCount` and pages exactly: for an alarm with 54 events and a
72005
+ * situation with 69, pages of 10 or 20 equalled one read of 1000, same set
72006
+ * and order (THE_LABORATORY and demo-dev, 2026-10-22).
72007
+ */
72008
+ const LIFECYCLE_PAGE_SIZE = 1000;
72009
+ /**
72010
+ * Reads every page of a lifecycle (alarm or situation) until the server's
72011
+ * `totalCount` is reached. `totalCount` is returned as the server reported
72012
+ * it; if a page comes back empty first, the result holds fewer events and a
72013
+ * warning is logged, so a short read stays visible.
72014
+ */
72015
+ async function readLifecyclePages(fetchPage, label, log) {
72016
+ const events = [];
72017
+ let totalCount = '0';
72018
+ for (let pageNumber = 0;; pageNumber++) {
72019
+ const page = await fetchPage(pageNumber, LIFECYCLE_PAGE_SIZE);
72020
+ totalCount = page.totalCount ?? totalCount;
72021
+ const pageEvents = page.lifecycle_events ?? [];
72022
+ events.push(...pageEvents);
72023
+ if (events.length >= Number(totalCount))
72024
+ break;
72025
+ if (pageEvents.length === 0) {
72026
+ log.warn(`Lifecycle of ${label} stopped at ${events.length} of ${totalCount} events: page ${pageNumber} was empty`);
72027
+ break;
72028
+ }
72029
+ }
72030
+ return { totalCount, lifecycle_events: events };
72031
+ }
72032
+
72033
+ var newAlarmSearchBody = exports.OIAlarm.newAlarmSearchBody;
70666
72034
  /**
70667
72035
  * Service for OI alarms: get, search, assign, acknowledge, clear, lifecycle,
70668
72036
  * enrichment rules, alarm queues, and related alarms.
@@ -70695,11 +72063,7 @@ class AlarmService {
70695
72063
  */
70696
72064
  async findAlarm(alarmId, lookbackMs, requestOverrides = {}) {
70697
72065
  const now = Date.now();
70698
- const body = {
70699
- ...DEFAULT_ALARMS_REQUEST_BODY$1,
70700
- timeFrom: now - lookbackMs,
70701
- timeTo: now,
70702
- pageNumber: 0,
72066
+ const body = newAlarmSearchBody(now - lookbackMs, now, {
70703
72067
  pageSize: 10,
70704
72068
  includeClosedAlarms: true,
70705
72069
  customFilter: {
@@ -70720,30 +72084,20 @@ class AlarmService {
70720
72084
  ],
70721
72085
  },
70722
72086
  },
70723
- };
72087
+ });
70724
72088
  const response = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', body, undefined, undefined, requestOverrides);
70725
72089
  return (response.alarms ?? []).find((alarm) => alarm.alarmId === alarmId);
70726
72090
  }
70727
- /** Returns the overview (first alarm in a custom-filter search) for an alarm ID. */
72091
+ /**
72092
+ * Returns an open alarm of the last 30 days by its ID (the payload a channel
72093
+ * notification sends).
72094
+ *
72095
+ * @throws Error when no open alarm has that ID.
72096
+ */
70728
72097
  async getAlarmOverview(alarmId) {
70729
- const singleAlarmQuery = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', {
70730
- deviceNames: [],
70731
- includeDeviceTypes: [],
70732
- excludeDeviceTypes: [],
70733
- groups: [],
70734
- like: '',
70735
- timeFrom: Date.now(),
70736
- timeTo: Date.now() - 30 * 24 * 60 * 60 * 1000,
70737
- pageNumber: 0,
70738
- pageSize: 50,
70739
- services: [],
70740
- includeSeverity: [],
70741
- allOtherSeverity: false,
72098
+ const now = Date.now();
72099
+ const singleAlarmQuery = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', newAlarmSearchBody(now - 30 * 24 * 60 * 60 * 1000, now, {
70742
72100
  sortCol: '',
70743
- includeAlarmTypes: [],
70744
- excludeAlarmTypes: [],
70745
- includeClosedAlarms: false,
70746
- showMaintenanceAlarms: false,
70747
72101
  showAlarmsPartOfSituations: false,
70748
72102
  customFilter: {
70749
72103
  and: {
@@ -70763,13 +72117,12 @@ class AlarmService {
70763
72117
  ],
70764
72118
  },
70765
72119
  },
70766
- });
70767
- if (singleAlarmQuery.alarmCount) {
70768
- return singleAlarmQuery.alarms[0];
70769
- }
70770
- else {
70771
- throw new Error('Bad Alarm Query');
72120
+ }));
72121
+ const alarm = singleAlarmQuery.alarms?.[0];
72122
+ if (Number(singleAlarmQuery.alarmCount) > 0 && alarm) {
72123
+ return alarm;
70772
72124
  }
72125
+ throw new Error(`No open alarm ${alarmId} in the last 30 days`);
70773
72126
  }
70774
72127
  /** Sends a notification for an alarm to the specified channel with optional template/locale. */
70775
72128
  async triggerNotification(alarmId, notificationChannelName, template = '', locale = 'en-US') {
@@ -70886,12 +72239,20 @@ class AlarmService {
70886
72239
  this.simpleLog.debug('update request body', JSON.stringify(body, null, 2));
70887
72240
  return this.dxSaaSService.tenantPost('jarvis/v2/ingestion', body, {}, headers);
70888
72241
  }
70889
- /** Returns the lifecycle event history for a given alarm ID. */
72242
+ /**
72243
+ * Returns an alarm's whole lifecycle event history, newest first.
72244
+ *
72245
+ * @remarks Reads pages of 1000 until the server's `totalCount` is reached
72246
+ * (it used to ask for 20 and stop, dropping the oldest events, "Alarm
72247
+ * Opened" first). `totalCount` is returned as the server reported it; if a
72248
+ * page comes back empty early, the result holds fewer events and a warning
72249
+ * is logged.
72250
+ */
70890
72251
  async getAlarmLifeCycle(alarmId) {
70891
- const alarmLifeCycleRequestBody = {
70892
- alarmId: alarmId,
70893
- pageSize: '20',
70894
- pageNumber: '0',
72252
+ return readLifecyclePages((pageNumber, pageSize) => this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', {
72253
+ alarmId,
72254
+ pageSize: String(pageSize),
72255
+ pageNumber: String(pageNumber),
70895
72256
  sortCol: 'timestamp:desc',
70896
72257
  excludeFields: [
70897
72258
  'isolation_view_link',
@@ -70899,38 +72260,101 @@ class AlarmService {
70899
72260
  'alert_definition_link',
70900
72261
  'occurrence',
70901
72262
  ],
70902
- };
70903
- return this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', alarmLifeCycleRequestBody);
72263
+ }), `alarm ${alarmId}`, this.simpleLog);
70904
72264
  }
70905
- /** Returns all alarms within a time range, with optional type/closed/filter params. */
70906
- async getAlarms(startTime, endTime, includedAlarmTypes = [], includeClosed = false, pageSize = 100, alarmFilter) {
70907
- const alarmRequestBody = {
70908
- ...DEFAULT_ALARMS_REQUEST_BODY$1,
70909
- };
70910
- alarmRequestBody.timeFrom = startTime.toMillis();
70911
- alarmRequestBody.timeTo = endTime.toMillis();
70912
- const alarmIdMap = new Map();
70913
- alarmRequestBody.includeAlarmTypes = includedAlarmTypes;
70914
- alarmRequestBody.includeClosedAlarms = includeClosed;
70915
- alarmRequestBody.pageSize = pageSize;
70916
- if (alarmFilter) {
70917
- alarmRequestBody.customFilter = alarmFilter;
70918
- }
70919
- this.simpleLog.info(`Retrieving first page of alarms with page size ${pageSize}`);
70920
- const alarmFirstPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
70921
- function mapAlarms(alarms) {
70922
- alarms.forEach((alarm) => {
70923
- if (!alarmIdMap.has(alarm.alarmId)) {
70924
- alarmIdMap.set(alarm.alarmId, alarm);
72265
+ /**
72266
+ * One alarm search over `[startTime, endTime]`: the exact number of alarms
72267
+ * in the range and the first `pageSize` of them (at most
72268
+ * {@link ALARM_SEARCH_PAGE_CAP}, whatever is asked). Use it where a sample
72269
+ * plus the true total is enough; {@link getAlarms} reads the whole range.
72270
+ */
72271
+ async searchAlarmPage(startTime, endTime, includedAlarmTypes = [], includeClosed = false, pageSize = ALARM_SEARCH_PAGE_CAP, alarmFilter) {
72272
+ return this.searchPage(startTime.toMillis(), endTime.toMillis(), {
72273
+ includedAlarmTypes,
72274
+ includeClosed,
72275
+ pageSize,
72276
+ alarmFilter,
72277
+ });
72278
+ }
72279
+ /**
72280
+ * Returns every alarm in `[startTime, endTime]`, keyed by `alarmId`.
72281
+ *
72282
+ * One search returns at most {@link ALARM_SEARCH_PAGE_CAP} alarms and cannot
72283
+ * be paged, so a larger range is read in windows and merged
72284
+ * (`searchAlarmWindows`). A window holds every alarm whose lifetime overlaps
72285
+ * it, so long-open alarms appear in all of them; the merge keeps one copy.
72286
+ *
72287
+ * @param pageSize - Ignored: each request asks for the server's
72288
+ * maximum. Kept for signature compatibility.
72289
+ * @throws IncompleteAlarmSearchError when the whole range cannot be read:
72290
+ * more alarms than one response holds at a single instant, alarms arriving
72291
+ * or backdated into the range during the read, or the request budget spent.
72292
+ * A partial set is never returned.
72293
+ */
72294
+ async getAlarms(startTime, endTime, includedAlarmTypes = [], includeClosed = false,
72295
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
72296
+ pageSize = 100, alarmFilter, options = {}) {
72297
+ const result = await searchAlarmWindows((from, to) => this.searchPage(from, to, {
72298
+ includedAlarmTypes,
72299
+ includeClosed,
72300
+ pageSize: ALARM_SEARCH_PAGE_CAP,
72301
+ alarmFilter,
72302
+ }), startTime.toMillis(), endTime.toMillis(), { log: this.simpleLog, ...options });
72303
+ this.simpleLog.info(`Retrieved ${result.alarms.size} of ${result.expected} alarms`);
72304
+ return result.alarms;
72305
+ }
72306
+ /**
72307
+ * Streams every alarm that `match` selects in `[startTime, endTime)` from the
72308
+ * alarms analytics index (`GET oi/v2/aoanalytics/alarms/alarms_all/_search`),
72309
+ * in open-time order — for exports over long ranges.
72310
+ *
72311
+ * Unlike {@link getAlarms} (the alarm search: every alarm active in the range,
72312
+ * 1000 per request), the index filters on the open or close time directly
72313
+ * and allows windows of 10000, so alarms that stay open do not crowd the
72314
+ * windows. Records are the stored documents (see `AlarmRecordSchema`).
72315
+ *
72316
+ * @remarks Responses are validated, not thrown on. The export throws
72317
+ * `IncompleteAlarmSearchError` when a window changes while it is read or
72318
+ * cannot be split; records already yielded are complete and in order.
72319
+ */
72320
+ exportAlarmRecords(startTime, endTime, match = 'opened', options = {}) {
72321
+ // One short warning per distinct mismatch, not one issue dump per page.
72322
+ const warned = new Set();
72323
+ const search = async (params) => {
72324
+ const raw = await this.dxSaaSService.oiGet('oi/v2/aoanalytics/alarms/alarms_all/_search', params);
72325
+ const parsed = AlarmRecordSearchResponseSchema.safeParse(raw);
72326
+ if (!parsed.success) {
72327
+ const fields = [
72328
+ ...new Set(parsed.error.issues.map((issue) => `${issue.path.map((p) => (typeof p === 'number' ? '*' : String(p))).join('.')} (${issue.message})`)),
72329
+ ].join('; ');
72330
+ if (!warned.has(fields)) {
72331
+ warned.add(fields);
72332
+ this.simpleLog.warn(`AlarmRecordSearchResponse validation warning: ${fields}`);
70925
72333
  }
70926
- });
70927
- }
70928
- this.simpleLog.info(`Retrieving ${alarmFirstPage.alarmCount} alarms`);
70929
- alarmRequestBody.pageSize = alarmFirstPage.alarmCount;
70930
- const alarmAllPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
70931
- this.simpleLog.info(`Retrieved ${alarmAllPage.alarms.length} of ${alarmFirstPage.alarmCount} alarms`);
70932
- mapAlarms(alarmAllPage.alarms);
70933
- return alarmIdMap;
72334
+ }
72335
+ return raw;
72336
+ };
72337
+ const source = {
72338
+ count: async (q) => {
72339
+ const total = (await search({ q, size: 0 })).hits?.total;
72340
+ return { total: total?.value ?? 0, exact: total?.relation === 'eq' };
72341
+ },
72342
+ page: async (q, from, size) => ((await search({ q, from, size, sort: 'startTime:asc,alarm_unique_id:asc' })).hits?.hits ?? []).map((hit) => hit._source),
72343
+ };
72344
+ return exportAlarmRecords(source, startTime.toMillis(), endTime.toMillis(), match, {
72345
+ log: this.simpleLog,
72346
+ ...options,
72347
+ });
72348
+ }
72349
+ async searchPage(timeFrom, timeTo, query) {
72350
+ const body = newAlarmSearchBody(timeFrom, timeTo, {
72351
+ includeAlarmTypes: query.includedAlarmTypes,
72352
+ includeClosedAlarms: query.includeClosed,
72353
+ pageSize: Math.min(Math.max(query.pageSize, 1), ALARM_SEARCH_PAGE_CAP),
72354
+ ...(query.alarmFilter ? { customFilter: query.alarmFilter } : {}),
72355
+ });
72356
+ const response = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', body);
72357
+ return { count: Number(response.alarmCount ?? 0), alarms: response.alarms ?? [] };
70934
72358
  }
70935
72359
  /**
70936
72360
  * Lists every alarm enrichment rule of the tenant
@@ -71289,7 +72713,7 @@ var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
71289
72713
  var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
71290
72714
  var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
71291
72715
  var booleanValueOf = Boolean.prototype.valueOf;
71292
- var objectToString = Object.prototype.toString;
72716
+ var objectToString$1 = Object.prototype.toString;
71293
72717
  var functionToString = Function.prototype.toString;
71294
72718
  var $match = String.prototype.match;
71295
72719
  var $slice = String.prototype.slice;
@@ -71609,7 +73033,7 @@ function has$2(obj, key) {
71609
73033
  }
71610
73034
 
71611
73035
  function toStr$2(obj) {
71612
- return objectToString.call(obj);
73036
+ return objectToString$1.call(obj);
71613
73037
  }
71614
73038
 
71615
73039
  function nameOf(f) {
@@ -72190,6 +73614,23 @@ var setMaxIndex = function setMaxIndex(obj, maxIndex) {
72190
73614
  overflowChannel.set(obj, maxIndex);
72191
73615
  };
72192
73616
 
73617
+ // Track containers produced by a `strictMerge` conflict wrap, and their current max numeric index,
73618
+ // so repeated conflicts on one path append instead of nesting a new wrapper each time
73619
+ var conflictChannel = getSideChannel$1();
73620
+
73621
+ var markConflict = function markConflict(obj, maxIndex) {
73622
+ conflictChannel.set(obj, maxIndex);
73623
+ return obj;
73624
+ };
73625
+
73626
+ var isConflict = function isConflict(obj) {
73627
+ return conflictChannel.has(obj);
73628
+ };
73629
+
73630
+ var getConflictIndex = function getConflictIndex(obj) {
73631
+ return conflictChannel.get(obj);
73632
+ };
73633
+
72193
73634
  var hexTable = (function () {
72194
73635
  var array = [];
72195
73636
  for (var i = 0; i < 256; ++i) {
@@ -72242,6 +73683,30 @@ var setProperty = function setProperty(obj, key, value) {
72242
73683
  }
72243
73684
  };
72244
73685
 
73686
+ var maxNumericIndex = function maxNumericIndex(obj, min) {
73687
+ var max = min;
73688
+ var keys = Object.keys(obj);
73689
+ for (var i = 0; i < keys.length; ++i) {
73690
+ var num = parseInt(keys[i], 10);
73691
+ if (String(num) === keys[i] && num > max) {
73692
+ max = num;
73693
+ }
73694
+ }
73695
+
73696
+ return max;
73697
+ };
73698
+
73699
+ var limitedPair = function limitedPair(first, second, options) {
73700
+ var pair = [first, second];
73701
+ if (options && typeof options.arrayLimit === 'number' && pair.length > options.arrayLimit) {
73702
+ if (options.throwOnLimitExceeded) {
73703
+ throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
73704
+ }
73705
+ return markOverflow(arrayToObject(pair, options), 1);
73706
+ }
73707
+ return pair;
73708
+ };
73709
+
72245
73710
  var merge = function merge(target, source, options) {
72246
73711
  /* eslint no-param-reassign: 0 */
72247
73712
  if (!source) {
@@ -72264,8 +73729,20 @@ var merge = function merge(target, source, options) {
72264
73729
  var newIndex = getMaxIndex(target) + 1;
72265
73730
  target[newIndex] = source;
72266
73731
  setMaxIndex(target, newIndex);
73732
+ } else if (options && options.strictMerge && isConflict(target)) {
73733
+ var nextConflict = getConflictIndex(target) + 1;
73734
+ if (
73735
+ options.throwOnLimitExceeded
73736
+ && typeof options.arrayLimit === 'number'
73737
+ && nextConflict >= options.arrayLimit
73738
+ ) {
73739
+ throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
73740
+ }
73741
+ target[nextConflict] = source;
73742
+ markConflict(target, nextConflict);
72267
73743
  } else if (options && options.strictMerge) {
72268
- return [target, source];
73744
+ var conflict = limitedPair(target, source, options);
73745
+ return isArray$1(conflict) ? markConflict(conflict, 1) : conflict;
72269
73746
  } else if (
72270
73747
  (options && (options.plainObjects || options.allowPrototypes))
72271
73748
  || !has$1.call(Object.prototype, source)
@@ -72273,7 +73750,7 @@ var merge = function merge(target, source, options) {
72273
73750
  target[source] = true;
72274
73751
  }
72275
73752
  } else {
72276
- return [target, source];
73753
+ return limitedPair(target, source, options);
72277
73754
  }
72278
73755
 
72279
73756
  return target;
@@ -72305,6 +73782,10 @@ var merge = function merge(target, source, options) {
72305
73782
  var mergeTarget = target;
72306
73783
  if (isArray$1(target) && !isArray$1(source)) {
72307
73784
  mergeTarget = arrayToObject(target, options);
73785
+ if (isConflict(target)) {
73786
+ // the array may have grown past its last conflict, so continue after its last index
73787
+ markConflict(mergeTarget, target.length - 1);
73788
+ }
72308
73789
  }
72309
73790
 
72310
73791
  if (isArray$1(target) && isArray$1(source)) {
@@ -72339,7 +73820,7 @@ var merge = function merge(target, source, options) {
72339
73820
  }
72340
73821
 
72341
73822
  if (isOverflow(source) && !isOverflow(acc)) {
72342
- markOverflow(acc, getMaxIndex(source));
73823
+ markOverflow(acc, maxNumericIndex(acc, getMaxIndex(source)));
72343
73824
  }
72344
73825
  if (isOverflow(acc)) {
72345
73826
  var keyNum = parseInt(key, 10);
@@ -72347,6 +73828,12 @@ var merge = function merge(target, source, options) {
72347
73828
  setMaxIndex(acc, keyNum);
72348
73829
  }
72349
73830
  }
73831
+ if (isConflict(acc)) {
73832
+ var conflictKey = parseInt(key, 10);
73833
+ if (String(conflictKey) === key && conflictKey > getConflictIndex(acc)) {
73834
+ markConflict(acc, conflictKey);
73835
+ }
73836
+ }
72350
73837
 
72351
73838
  return acc;
72352
73839
  }, mergeTarget);
@@ -72360,6 +73847,13 @@ var assign = function assignSingleSource(target, source) {
72360
73847
  };
72361
73848
 
72362
73849
  var decode = function (str, defaultDecoder, charset) {
73850
+ // With no `%` there is no escape to expand, in either charset: `unescape` has
73851
+ // nothing to match, and `decodeURIComponent` is the identity on such a string
73852
+ // (and cannot throw). So only `+` -> ' ' remains, and often not even that.
73853
+ if (typeof str === 'string' && str.indexOf('%') === -1) {
73854
+ return str.indexOf('+') === -1 ? str : str.replace(/\+/g, ' ');
73855
+ }
73856
+
72363
73857
  var strWithoutPlus = str.replace(/\+/g, ' ');
72364
73858
  if (charset === 'iso-8859-1') {
72365
73859
  // unescape never throws, no try...catch needed:
@@ -72373,6 +73867,57 @@ var decode = function (str, defaultDecoder, charset) {
72373
73867
  }
72374
73868
  };
72375
73869
 
73870
+ var hasToPrimitive = typeof Symbol === 'function' && typeof Symbol.toPrimitive === 'symbol';
73871
+ var arrayJoin = Array.prototype.join;
73872
+ var arrayToString = Array.prototype.toString;
73873
+ var objectToString = Object.prototype.toString;
73874
+
73875
+ // an object with no callable toString (eg, from JSON, or null-prototype) would make String() or join() throw,
73876
+ // so it becomes its primitive valueOf or else Object.prototype.toString; arrays are walked like join walks them,
73877
+ // copied only once an element changes, with an array already being joined becoming '' as engines do for cycles
73878
+ var toCoercible = function toCoercible(value, joining) {
73879
+ if (!value || (typeof value !== 'object' && typeof value !== 'function')) {
73880
+ return value;
73881
+ }
73882
+ if (hasToPrimitive && value[Symbol.toPrimitive] != null) {
73883
+ return value;
73884
+ }
73885
+ if (isArray$1(value) && value.toString === arrayToString && value.join === arrayJoin) {
73886
+ var ancestors = joining || getSideChannel$1();
73887
+ if (ancestors.has(value)) {
73888
+ return '';
73889
+ }
73890
+ ancestors.set(value, true);
73891
+ var copy;
73892
+ for (var i = 0; i < value.length; i += 1) {
73893
+ var item = value[i];
73894
+ var coerced = toCoercible(item, ancestors);
73895
+ if (!copy && coerced !== item) {
73896
+ copy = [];
73897
+ for (var j = 0; j < i; j += 1) {
73898
+ copy[j] = value[j];
73899
+ }
73900
+ }
73901
+ if (copy) {
73902
+ copy[i] = coerced;
73903
+ }
73904
+ }
73905
+ ancestors['delete'](value);
73906
+ return copy || value;
73907
+ }
73908
+ if (typeof value.toString === 'function') {
73909
+ return value;
73910
+ }
73911
+ var valueOf = value.valueOf;
73912
+ if (typeof valueOf === 'function') {
73913
+ var primitive = valueOf.call(value);
73914
+ if (!primitive || (typeof primitive !== 'object' && typeof primitive !== 'function')) {
73915
+ return String(primitive);
73916
+ }
73917
+ }
73918
+ return objectToString.call(value);
73919
+ };
73920
+
72376
73921
  var limit = 1024;
72377
73922
 
72378
73923
  /* eslint operator-linebreak: [2, "before"] */
@@ -72388,13 +73933,15 @@ var encode = function encode(str, defaultEncoder, charset, kind, format) {
72388
73933
  if (typeof str === 'symbol') {
72389
73934
  string = Symbol.prototype.toString.call(str);
72390
73935
  } else if (typeof str !== 'string') {
72391
- string = String(str);
73936
+ string = String(toCoercible(str));
72392
73937
  }
72393
73938
 
72394
73939
  if (charset === 'iso-8859-1') {
73940
+ // `escape` leaves `+` untouched, but a literal `+` is decoded back to a space,
73941
+ // so it must be percent-encoded to round-trip (the utf-8 path already does this).
72395
73942
  return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
72396
73943
  return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
72397
- });
73944
+ }).replace(/\+/g, '%2B');
72398
73945
  }
72399
73946
 
72400
73947
  var out = '';
@@ -72546,7 +74093,8 @@ var utils$1 = {
72546
74093
  isRegExp: isRegExp,
72547
74094
  markOverflow: markOverflow,
72548
74095
  maybeMap: maybeMap,
72549
- merge: merge
74096
+ merge: merge,
74097
+ toCoercible: toCoercible
72550
74098
  };
72551
74099
 
72552
74100
  var getSideChannel = sideChannel;
@@ -72699,10 +74247,10 @@ var stringify$2 = function stringify(
72699
74247
  // we need to join elements in
72700
74248
  if (encodeValuesOnly && encoder) {
72701
74249
  obj = utils.maybeMap(obj, function (v) {
72702
- return v == null ? v : encoder(v);
74250
+ return v == null ? v : encoder(v, defaults.encoder, charset, 'value', format);
72703
74251
  });
72704
74252
  }
72705
- objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
74253
+ objKeys = [{ value: obj.length > 0 ? utils.toCoercible(obj).join(',') || null : void undefined }];
72706
74254
  } else if (isArray(filter)) {
72707
74255
  objKeys = filter;
72708
74256
  } else {
@@ -72710,7 +74258,7 @@ var stringify$2 = function stringify(
72710
74258
  objKeys = sort ? keys.sort(sort) : keys;
72711
74259
  }
72712
74260
 
72713
- var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix);
74261
+ var encodedPrefix = String(prefix);
72714
74262
 
72715
74263
  var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix;
72716
74264
 
@@ -72800,7 +74348,7 @@ var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
72800
74348
  }
72801
74349
 
72802
74350
  var arrayFormat;
72803
- if (opts.arrayFormat in arrayPrefixGenerators) {
74351
+ if (has.call(arrayPrefixGenerators, opts.arrayFormat)) {
72804
74352
  arrayFormat = opts.arrayFormat;
72805
74353
  } else if ('indices' in opts) {
72806
74354
  arrayFormat = opts.indices ? 'indices' : 'repeat';
@@ -80752,7 +82300,6 @@ class DxSaasService {
80752
82300
  }
80753
82301
  }
80754
82302
 
80755
- var DEFAULT_ALARMS_REQUEST_BODY = exports.OIAlarm.DEFAULT_ALARMS_REQUEST_BODY;
80756
82303
  var DEFAULT_SITUATIONS_REQUEST_BODY = exports.OIAlarm.DEFAULT_SITUATIONS_REQUEST_BODY;
80757
82304
  /**
80758
82305
  * Service for OI (Operations Intelligence) read operations: services, situations,
@@ -80760,9 +82307,11 @@ var DEFAULT_SITUATIONS_REQUEST_BODY = exports.OIAlarm.DEFAULT_SITUATIONS_REQUEST
80760
82307
  */
80761
82308
  class DxoiService {
80762
82309
  dxSaaSService;
82310
+ alarms;
80763
82311
  /** @param dxSaaSService - DX SaaS HTTP client for OI endpoints */
80764
82312
  constructor(dxSaaSService) {
80765
82313
  this.dxSaaSService = dxSaaSService;
82314
+ this.alarms = new AlarmService(dxSaaSService);
80766
82315
  }
80767
82316
  /** Returns top-level OI services using the default service request body. */
80768
82317
  getServices() {
@@ -80771,9 +82320,11 @@ class DxoiService {
80771
82320
  }
80772
82321
  /** Returns cluster alarms (situations) within the given time range. */
80773
82322
  async getSituations(startTime, endTime) {
80774
- const alarmRequestBody = DEFAULT_SITUATIONS_REQUEST_BODY;
80775
- alarmRequestBody.timeFrom = startTime.toMillis();
80776
- alarmRequestBody.timeTo = endTime.toMillis();
82323
+ const alarmRequestBody = {
82324
+ ...DEFAULT_SITUATIONS_REQUEST_BODY,
82325
+ timeFrom: startTime.toMillis(),
82326
+ timeTo: endTime.toMillis(),
82327
+ };
80777
82328
  return this.dxSaaSService.oiPost('oi/v2/api/clusteralarms/_search', alarmRequestBody);
80778
82329
  }
80779
82330
  /** Returns the entity-detail attributes for a given entity external ID. */
@@ -80782,51 +82333,28 @@ class DxoiService {
80782
82333
  externalId: entityExternalId,
80783
82334
  });
80784
82335
  }
80785
- /** Returns a single alarm by its ID. */
82336
+ /**
82337
+ * Returns a single alarm by its ID.
82338
+ * @deprecated Use `AlarmService.getAlarm` (`ServiceMonolith.dxAlarmService`).
82339
+ */
80786
82340
  async getAlarm(alarmId) {
80787
- return this.dxSaaSService.oiGet('oi/v2/api/alarms/_search', {
80788
- alarmId: alarmId,
80789
- });
82341
+ return this.alarms.getAlarm(alarmId);
80790
82342
  }
80791
- /** Returns the lifecycle event history for a given alarm ID. */
82343
+ /**
82344
+ * Returns the lifecycle event history for a given alarm ID.
82345
+ * @deprecated Use `AlarmService.getAlarmLifeCycle` (`ServiceMonolith.dxAlarmService`).
82346
+ */
80792
82347
  async getAlarmLifeCycle(alarmId) {
80793
- const alarmLifeCycleRequestBody = {
80794
- alarmId: alarmId,
80795
- pageSize: '20',
80796
- pageNumber: '0',
80797
- sortCol: 'timestamp:desc',
80798
- excludeFields: [
80799
- 'isolation_view_link',
80800
- 'metric_view_link',
80801
- 'alert_definition_link',
80802
- 'occurrence',
80803
- ],
80804
- };
80805
- return this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', alarmLifeCycleRequestBody);
82348
+ return this.alarms.getAlarmLifeCycle(alarmId);
80806
82349
  }
80807
- /** Returns all alarms in a time range, paginating until the full count is fetched. */
82350
+ /**
82351
+ * Returns every open alarm in a time range.
82352
+ * @deprecated Use `AlarmService.getAlarms`, which this now calls: it reads
82353
+ * ranges over 1000 alarms in windows and throws `IncompleteAlarmSearchError`
82354
+ * instead of returning a partial set (the old page loop could not end).
82355
+ */
80808
82356
  async getAlarms(startTime, endTime) {
80809
- const alarmRequestBody = DEFAULT_ALARMS_REQUEST_BODY;
80810
- alarmRequestBody.timeFrom = startTime.toMillis();
80811
- alarmRequestBody.timeTo = endTime.toMillis();
80812
- const alarmIdMap = new Map();
80813
- const alarmFirstPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
80814
- function mapAlarms(alarms) {
80815
- alarms.forEach((alarm) => {
80816
- if (!alarmIdMap.has(alarm.alarmId)) {
80817
- alarmIdMap.set(alarm.alarmId, alarm);
80818
- }
80819
- });
80820
- }
80821
- mapAlarms(alarmFirstPage.alarms);
80822
- let currentAlarmPage = 1;
80823
- while (alarmIdMap.size < Number.parseInt(alarmFirstPage.alarmCount)) {
80824
- alarmRequestBody.pageNumber = currentAlarmPage;
80825
- const alarmNextPage = await this.dxSaaSService.oiPost('oi/v2/api/alarms/_search', alarmRequestBody);
80826
- mapAlarms(alarmNextPage.alarms);
80827
- currentAlarmPage++;
80828
- }
80829
- return alarmIdMap;
82357
+ return this.alarms.getAlarms(startTime, endTime);
80830
82358
  }
80831
82359
  }
80832
82360
 
@@ -83065,6 +84593,92 @@ chain.gen = gen;
83065
84593
  chain.fun = fun;
83066
84594
  chain.dataSource = dataSource;
83067
84595
 
84596
+ // @ts-self-types="./path-matcher.d.ts"
84597
+
84598
+ const DIVERGED = -1,
84599
+ MATCHED = -2;
84600
+
84601
+ const defaultFilter$1 = () => true;
84602
+
84603
+ // Array.prototype.join semantics
84604
+ const toPart = key => (key == null ? '' : '' + key);
84605
+
84606
+ class PathMatcher {
84607
+ constructor(filter, separator = '.') {
84608
+ this.filter = filter;
84609
+ this.separator = separator;
84610
+ this.stateful = true;
84611
+ if (typeof filter == 'string') {
84612
+ this.filterWithSeparator = filter + separator;
84613
+ this.states = [0];
84614
+ return;
84615
+ }
84616
+ if (filter instanceof RegExp) {
84617
+ this.paths = [''];
84618
+ this.extend = this._extendRegExp;
84619
+ this.test = this._testRegExp;
84620
+ this.testRecorded = this._testRecordedRegExp;
84621
+ return;
84622
+ }
84623
+ this.stateful = false;
84624
+ this.extend = this._extendNothing;
84625
+ this.test = this.testRecorded = typeof filter == 'function' ? filter : defaultFilter$1;
84626
+ }
84627
+
84628
+ extend(stack) {
84629
+ const length = stack.length;
84630
+ if (length) this.states[length] = this._step(this.states[length - 1], stack[length - 1], length === 1);
84631
+ }
84632
+
84633
+ test(stack, _chunk) {
84634
+ const length = stack.length;
84635
+ return this._isMatch(length ? this._step(this.states[length - 1], stack[length - 1], length === 1) : 0);
84636
+ }
84637
+
84638
+ testRecorded(stack) {
84639
+ return this._isMatch(this.states[stack.length]);
84640
+ }
84641
+
84642
+ _isMatch(state) {
84643
+ return state === MATCHED || state === this.filter.length;
84644
+ }
84645
+
84646
+ // state: a position when the path is a proper prefix of filter + separator
84647
+ _step(state, key, isRoot) {
84648
+ if (!isRoot) state = this._append(state, this.separator);
84649
+ return this._append(state, toPart(key));
84650
+ }
84651
+
84652
+ _append(state, part) {
84653
+ if (state < 0) return state;
84654
+ const filterWithSeparator = this.filterWithSeparator;
84655
+ if (part.length < filterWithSeparator.length - state) return filterWithSeparator.startsWith(part, state) ? state + part.length : DIVERGED;
84656
+ return part.startsWith(filterWithSeparator.slice(state)) ? MATCHED : DIVERGED;
84657
+ }
84658
+
84659
+ _extendRegExp(stack) {
84660
+ const length = stack.length;
84661
+ // kept flat: a test against a concatenated parent costs ~34x more at depth 1000 (nano-bench)
84662
+ if (length) this.paths[length] = length === 1 ? toPart(stack[0]) : [this.paths[length - 1], this.separator, toPart(stack[length - 1])].join('');
84663
+ }
84664
+
84665
+ _testRegExp(stack, _chunk) {
84666
+ const length = stack.length,
84667
+ filter = this.filter;
84668
+ filter.lastIndex = 0;
84669
+ if (!length) return filter.test('');
84670
+ return filter.test(length === 1 ? toPart(stack[0]) : this.paths[length - 1] + this.separator + toPart(stack[length - 1]));
84671
+ }
84672
+
84673
+ _testRecordedRegExp(stack) {
84674
+ const filter = this.filter;
84675
+ filter.lastIndex = 0;
84676
+ return filter.test(this.paths[stack.length]);
84677
+ }
84678
+
84679
+ _extendNothing(_stack) {}
84680
+ }
84681
+
83068
84682
  // @ts-self-types="./filter-base.d.ts"
83069
84683
 
83070
84684
 
@@ -83091,21 +84705,6 @@ const defaultFilter = () => true;
83091
84705
 
83092
84706
  const DEFAULT_MAX_DEPTH = 1024;
83093
84707
 
83094
- const stringFilter = (string, separator) => {
83095
- const stringWithSeparator = string + separator;
83096
- return stack => {
83097
- const path = stack.join(separator);
83098
- return path === string || path.startsWith(stringWithSeparator);
83099
- };
83100
- };
83101
-
83102
- const regExpFilter = (regExp, separator) => {
83103
- return stack => {
83104
- regExp.lastIndex = 0;
83105
- return regExp.test(stack.join(separator));
83106
- };
83107
- };
83108
-
83109
84708
  /** @type {any} */
83110
84709
  const filterBase =
83111
84710
  (
@@ -83120,17 +84719,14 @@ const filterBase =
83120
84719
  const once = options?.once,
83121
84720
  separator = options?.pathSeparator || '.',
83122
84721
  maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;
83123
- /** @type {(stack: any[], chunk?: any) => boolean} */
84722
+ // the filter as authored: a string or a RegExp is matched by PathMatcher, never called
84723
+ /** @type {((stack: any[], chunk?: any) => boolean) | string | RegExp} */
83124
84724
  let filter = defaultFilter;
83125
84725
  let streamKeys = false,
83126
84726
  mirrorStreamKeys = true;
83127
84727
  if (options) {
83128
- if (typeof options.filter == 'function') {
84728
+ if (typeof options.filter == 'function' || typeof options.filter == 'string' || options.filter instanceof RegExp) {
83129
84729
  filter = options.filter;
83130
- } else if (typeof options.filter == 'string') {
83131
- filter = stringFilter(options.filter, separator);
83132
- } else if (options.filter instanceof RegExp) {
83133
- filter = regExpFilter(options.filter, separator);
83134
84730
  }
83135
84731
  if ('streamValues' in options) {
83136
84732
  streamKeys = options.streamValues;
@@ -83141,7 +84737,8 @@ const filterBase =
83141
84737
  mirrorStreamKeys = false;
83142
84738
  }
83143
84739
  }
83144
- const sanitizedOptions = {...options, filter, streamKeys, separator};
84740
+ const sanitizedOptions = {...options, filter, streamKeys, separator},
84741
+ matcher = new PathMatcher(options?.filter, separator);
83145
84742
  let state = 'check',
83146
84743
  stack = [],
83147
84744
  depth = 0,
@@ -83270,7 +84867,7 @@ const filterBase =
83270
84867
  let action = nonCheckableAction;
83271
84868
  if (checkableTokens[chunk.name] === 1) {
83272
84869
  if (stack.length > maxDepth) throw new RangeError(`filter: JSON nesting depth exceeds maxDepth (${maxDepth})`);
83273
- action = filter(stack, chunk) ? specialAction : defaultAction;
84870
+ action = matcher.test(stack, chunk) ? specialAction : defaultAction;
83274
84871
  }
83275
84872
 
83276
84873
  endToken = stopTokens[chunk.name] || '';
@@ -83319,9 +84916,11 @@ const filterBase =
83319
84916
  // update the stack
83320
84917
  switch (chunk.name) {
83321
84918
  case 'startObject':
84919
+ matcher.extend(stack);
83322
84920
  stack.push(null);
83323
84921
  break;
83324
84922
  case 'startArray':
84923
+ matcher.extend(stack);
83325
84924
  stack.push(-1);
83326
84925
  break;
83327
84926
  case 'endObject':
@@ -87540,36 +89139,206 @@ class ServiceService {
87540
89139
  return this.dxSaaSService.oiPost('oi/v2/sa/saTopologyGraph', { serviceName, startTime: Date.now(), endTime: Date.now() });
87541
89140
  }
87542
89141
  /**
87543
- * Builds a faithful, re-postable store body for a service's entire subtree:
87544
- * topology for structure + a per-vertex {@link getService} for full attributes
87545
- * (serviceContent, tags, customProperties, metrics). Shared by
87546
- * `export-hierarchy`, `associate`, and `dissociate`.
89142
+ * Builds a faithful, re-postable store body for a service's entire subtree
89143
+ * (full attributes + association edges) from one hierarchy read. Shared by
89144
+ * `export-hierarchy`, `associate`, `dissociate` and `update-service`.
87547
89145
  *
87548
- * @remarks One GET per vertex — fine for typical (small) hierarchies; reads
87549
- * are not throttled like saves.
89146
+ * @throws Error if the service does not exist.
87550
89147
  */
87551
89148
  async buildHierarchyBody(rootName) {
87552
- const topo = await this.getServiceTopology(rootName);
87553
- const names = new Set([rootName]);
87554
- topo.vertices.forEach((v) => names.add(v.attributes.name));
87555
- const vertices = [];
87556
- const seen = new Set();
89149
+ const graph = await this.readServiceGraph([rootName]);
89150
+ return exports.ServiceBulk.subtreeBody(graph, rootName);
89151
+ }
89152
+ /**
89153
+ * Reads every hierarchy that contains the named services into one name-keyed
89154
+ * graph: one `GET oi/v2/sa/services/{name}?subservices=true` per service not
89155
+ * already covered by an earlier read (the endpoint returns whole hierarchies
89156
+ * from their top-level services down, full attributes included).
89157
+ *
89158
+ * @param opts.allowMissing - skip services that do not exist instead of throwing.
89159
+ * @throws Error if a service does not exist, or a read is paged.
89160
+ */
89161
+ async readServiceGraph(names, opts = {}) {
89162
+ let graph = { vertices: {}, edges: [] };
87557
89163
  for (const name of names) {
87558
- const full = await this.getService(name, false);
87559
- const fv = full.vertices[0];
87560
- if (fv && !seen.has(fv.externalId)) {
87561
- seen.add(fv.externalId);
87562
- vertices.push(exports.ServiceTransform.retrievedToServiceVertex(fv));
89164
+ if (graph.vertices[name])
89165
+ continue;
89166
+ let read;
89167
+ try {
89168
+ read = await this.getService(name, true);
89169
+ }
89170
+ catch (e) {
89171
+ if (e.httpCode !== 404)
89172
+ throw e;
89173
+ if (opts.allowMissing)
89174
+ continue;
89175
+ throw new Error(`No service with name '${name}' found`);
87563
89176
  }
89177
+ graph = exports.ServiceBulk.mergeGraphs(graph, exports.ServiceBulk.graphFromRead(read));
87564
89178
  }
87565
- // Drop edges that reference vertices outside this subtree (e.g. the incoming
87566
- // edge from the root's parent, which saTopologyGraph returns without the
87567
- // parent vertex). Re-posting such a dangling edge is rejected by the server.
87568
- const presentIds = new Set(vertices
87569
- .map((v) => v.externalId)
87570
- .filter((id) => id !== undefined));
87571
- const edges = exports.ServiceTransform.filterEdgesToVertices(exports.ServiceTransform.edgesFromTopology(topo), presentIds);
87572
- return { vertices, edges };
89179
+ return graph;
89180
+ }
89181
+ /**
89182
+ * Plans changes to any number of services, in any hierarchies, without
89183
+ * saving: reads what the changes name, applies them, and returns the
89184
+ * per-service diff, the services the save would carry, and the store body.
89185
+ *
89186
+ * @throws ZodError for malformed changes; Error for an invalid change or
89187
+ * weights over 100 %.
89188
+ */
89189
+ async planServiceChanges(changes) {
89190
+ const parsed = exports.ServiceBulk.parseChanges(changes);
89191
+ const targets = exports.ServiceBulk.targetsOf(parsed);
89192
+ const graph = await this.readServiceGraph(targets);
89193
+ return exports.ServiceBulk.planChanges(graph, targets, parsed);
89194
+ }
89195
+ /**
89196
+ * Previews one set of edits applied to every service a selector picks, saving
89197
+ * nothing. Candidates come from `services` / `root` when given, otherwise from
89198
+ * the services list; every criterion is then re-checked against the fresh
89199
+ * hierarchy read the save would be built from. Edits that would change
89200
+ * nothing on a service are reported, not emitted.
89201
+ *
89202
+ * @param opts.max - more services to change than this is a blocker (default 25).
89203
+ * @throws ZodError for a malformed selector or edits; Error when nothing matches
89204
+ * or a named service does not exist.
89205
+ */
89206
+ async planBulkUpdate(selector, edits, opts = {}) {
89207
+ const sel = exports.ServiceBulkSelect.ServiceSelectorSchema.parse(selector);
89208
+ const edit = exports.ServiceBulkSelect.BulkEditSchema.parse(edits);
89209
+ const max = opts.max ?? 25;
89210
+ let graph = { vertices: {}, edges: [] };
89211
+ let candidates;
89212
+ if (sel.services) {
89213
+ graph = await this.readServiceGraph(sel.services, { allowMissing: true });
89214
+ const missing = sel.services.filter((n) => !graph.vertices[n]);
89215
+ if (missing.length)
89216
+ throw new Error(await this.unknownServicesMessage(missing));
89217
+ candidates = [...new Set(sel.services)];
89218
+ }
89219
+ if (sel.root) {
89220
+ graph = exports.ServiceBulk.mergeGraphs(graph, await this.readServiceGraph([sel.root]));
89221
+ const scope = exports.ServiceBulkSelect.withinDepth(graph, sel.root, sel.depth);
89222
+ candidates = candidates ? candidates.filter((n) => scope.includes(n)) : scope;
89223
+ }
89224
+ let checked = candidates?.length ?? 0;
89225
+ if (!candidates) {
89226
+ const rows = await this.getAllServices(100);
89227
+ checked = rows.length;
89228
+ candidates = rows
89229
+ .filter((r) => exports.ServiceBulkSelect.matchesFilters(exports.ServiceBulkSelect.subjectFromListRow(r), sel))
89230
+ .map((r) => r.name);
89231
+ graph = await this.readServiceGraph(candidates, { allowMissing: true });
89232
+ }
89233
+ const excluded = [];
89234
+ const matched = candidates.filter((name) => {
89235
+ const v = graph.vertices[name];
89236
+ if (!v) {
89237
+ excluded.push({ service: name, reason: 'no longer exists' });
89238
+ return false;
89239
+ }
89240
+ if (exports.ServiceBulkSelect.matchesFilters(exports.ServiceBulkSelect.subjectFromVertex(v), sel))
89241
+ return true;
89242
+ if (sel.services) {
89243
+ excluded.push({ service: name, reason: 'does not match the other criteria' });
89244
+ }
89245
+ else if (!sel.root) {
89246
+ excluded.push({ service: name, reason: 'no longer matches' });
89247
+ }
89248
+ return false;
89249
+ });
89250
+ if (!matched.length) {
89251
+ throw new Error(`0 of ${checked} services match ${exports.ServiceBulkSelect.describeSelector(sel)}`);
89252
+ }
89253
+ const { changes, outcomes, warnings } = exports.ServiceBulkSelect.expandEdits(graph, matched, edit);
89254
+ const blockers = exports.ServiceBulkSelect.editBlockers(edit);
89255
+ const changing = outcomes.filter((o) => o.will.length).length;
89256
+ if (changing > max) {
89257
+ blockers.push(`${changing} services would change, more than max=${max}; narrow the selector or raise max`);
89258
+ }
89259
+ const planned = changes.length
89260
+ ? exports.ServiceBulk.planChanges(graph, exports.ServiceBulk.targetsOf(changes), changes).plan
89261
+ : { targets: [], changes: [], diff: [], save: [] };
89262
+ const changed = new Set(planned.diff.map((d) => d.service));
89263
+ return {
89264
+ selector: exports.ServiceBulkSelect.describeSelector(sel),
89265
+ checked,
89266
+ matched,
89267
+ outcomes,
89268
+ excluded,
89269
+ warnings,
89270
+ blockers,
89271
+ plan: planned,
89272
+ before: planned.save.length ? exports.ServiceBulk.bodyFor(graph, planned.save) : { vertices: [], edges: [] },
89273
+ carried: planned.save.filter((n) => !changed.has(n)),
89274
+ confirm: exports.ServiceBulkSelect.planToken(planned),
89275
+ };
89276
+ }
89277
+ /** "No service named …", with case-insensitive suggestions from the services list. */
89278
+ async unknownServicesMessage(missing) {
89279
+ const all = (await this.getAllServices(100)).map((s) => s.name);
89280
+ const lines = missing.map((m) => {
89281
+ const near = all.filter((n) => n.toLowerCase() === m.toLowerCase());
89282
+ return near.length ? `'${m}' (did you mean '${near.join("', '")}'?)` : `'${m}'`;
89283
+ });
89284
+ return `No service with name ${lines.join(', ')} found (names are case-sensitive)`;
89285
+ }
89286
+ /**
89287
+ * The tenant's service cap and how many services count against it
89288
+ * (`GET oi/v2/sa/serviceLimitExceeded`).
89289
+ *
89290
+ * @remarks `limitExceeded` is already true when the count equals the limit (the tenant is
89291
+ * full). The count lags deletes by one to three minutes.
89292
+ */
89293
+ async getServiceLimit() {
89294
+ return this.dxSaaSService.oiGet('oi/v2/sa/serviceLimitExceeded');
89295
+ }
89296
+ /**
89297
+ * Plans importing a store body (an export file) into this tenant, saving nothing:
89298
+ * reads the target's current state for every name in the file, takes each service's
89299
+ * metrics from the target ({@link ServiceImport.planImport}), and checks the service cap.
89300
+ *
89301
+ * @param opts.prefix - rename every service in the file first (cloning).
89302
+ */
89303
+ async planImport(file, opts = {}) {
89304
+ const body = opts.prefix ? exports.ServiceImport.renameBody(file, opts.prefix) : file;
89305
+ // Read only names the services list knows, so new ones aren't probed one 404 at a time.
89306
+ const listed = new Set((await this.getAllServices(100)).map((s) => s.name));
89307
+ const names = body.vertices.map((v) => v.attributes.name).filter((n) => listed.has(n));
89308
+ const target = await this.readServiceGraph(names, { allowMissing: true });
89309
+ const plan = exports.ServiceImport.planImport(body, target);
89310
+ const cap = await this.getServiceLimit();
89311
+ const headroom = cap.limit - cap.totalServiceCnt;
89312
+ if (plan.created.length > headroom) {
89313
+ plan.blockers.push(`${plan.created.length} new services but only ${headroom} of ${cap.limit} left under the tenant's service cap`);
89314
+ }
89315
+ return { ...plan, headroom, limit: cap.limit };
89316
+ }
89317
+ /**
89318
+ * Commits a plan in ONE save. Re-reads the plan's services and refuses when a
89319
+ * value the plan replaces has moved; otherwise re-applies the changes onto the
89320
+ * fresh read (so concurrent edits elsewhere are kept) and saves. A plan whose
89321
+ * changes are already in place saves nothing (`response` is absent).
89322
+ *
89323
+ * @param opts.force - skip the conflict check and apply onto whatever is there now.
89324
+ * @throws ServiceBulk.ServiceConflictError listing what moved.
89325
+ * @remarks The server rejects an invalid payload whole — nothing is applied.
89326
+ */
89327
+ async commitServicePlan(plan, opts = {}) {
89328
+ const checked = exports.ServiceBulk.parsePlan(plan);
89329
+ const fresh = await this.readServiceGraph(checked.targets, {
89330
+ allowMissing: true,
89331
+ });
89332
+ if (!opts.force) {
89333
+ const conflicts = exports.ServiceBulk.findConflicts(checked, fresh);
89334
+ if (conflicts.length)
89335
+ throw new exports.ServiceBulk.ServiceConflictError(conflicts);
89336
+ }
89337
+ const rebased = exports.ServiceBulk.planChanges(fresh, checked.targets, checked.changes);
89338
+ if (!rebased.plan.diff.length)
89339
+ return rebased;
89340
+ const response = await this.createService(rebased.body, { replace: true });
89341
+ return { ...rebased, response };
87573
89342
  }
87574
89343
  /** Builds a single-service store body (no edges) for `service export`. */
87575
89344
  async exportServiceBody(serviceName) {
@@ -87601,55 +89370,48 @@ class ServiceService {
87601
89370
  }
87602
89371
  throw new Error(`No Service with name '${serviceName}' Found`);
87603
89372
  }
87604
- /** Returns paginated top-level (grouped) services up to `maxRequests` pages. */
87605
- async getTopLevelServices(pageSize = 100, maxRequests = 20) {
87606
- const returnServices = new Array();
87607
- let totalRequests = 0;
87608
- this.log.info(`Making initial request with pageSize=${pageSize}`);
87609
- const currentRequestBody = this.createParentServiceRequestBody(pageSize);
87610
- return this.dxSaaSService
87611
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87612
- .then(async (response) => {
87613
- totalRequests = 1;
87614
- returnServices.push(...response.services);
87615
- while (response.groupedCnt > returnServices.length ||
87616
- totalRequests > maxRequests) {
87617
- totalRequests++;
87618
- currentRequestBody.pageNum++;
87619
- this.log.info('Retrieving Page initial request with pageSize=100');
87620
- await this.dxSaaSService
87621
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87622
- .then(async (response) => {
87623
- returnServices.push(...response.services);
87624
- });
87625
- }
87626
- return returnServices;
87627
- });
89373
+ /**
89374
+ * Returns the top-level (grouped) services, every page of them.
89375
+ *
89376
+ * @param pageSize - Services per request.
89377
+ * @param maxRequests - Optional cap on the number of requests; omitted = until `groupedCnt` is reached.
89378
+ * @remarks Stops early on an empty page; a short result (cap or empty page) is logged as a warning.
89379
+ */
89380
+ async getTopLevelServices(pageSize = 100, maxRequests) {
89381
+ return this.fetchServicePages(this.createParentServiceRequestBody(pageSize), (response) => response.groupedCnt, maxRequests);
87628
89382
  }
87629
- /** Returns all services (ungrouped) paginating up to `maxRequests` pages. */
87630
- async getAllServices(pageSize = 100, maxRequests = 10) {
87631
- const returnServices = new Array();
87632
- let totalRequests = 0;
87633
- this.log.info(`Making initial request with pageSize=${pageSize}`);
87634
- const currentRequestBody = this.createAllServiceRequestBody(pageSize);
87635
- return this.dxSaaSService
87636
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87637
- .then(async (response) => {
87638
- totalRequests = 1;
87639
- returnServices.push(...response.services);
87640
- while (response.totalCnt > returnServices.length ||
87641
- totalRequests > maxRequests) {
87642
- totalRequests++;
87643
- currentRequestBody.pageNum++;
87644
- this.log.info('Retrieving Page initial request with pageSize=100');
87645
- await this.dxSaaSService
87646
- .oiPost('oi/v2/servicerepo/services', currentRequestBody)
87647
- .then(async (response) => {
87648
- returnServices.push(...response.services);
87649
- });
89383
+ /**
89384
+ * Returns all services (ungrouped), every page of them.
89385
+ *
89386
+ * @param pageSize - Services per request.
89387
+ * @param maxRequests - Optional cap on the number of requests; omitted = until `totalCnt` is reached.
89388
+ * @remarks Stops early on an empty page; a short result (cap or empty page) is logged as a warning.
89389
+ */
89390
+ async getAllServices(pageSize = 100, maxRequests) {
89391
+ return this.fetchServicePages(this.createAllServiceRequestBody(pageSize), (response) => response.totalCnt, maxRequests);
89392
+ }
89393
+ async fetchServicePages(body, expectedCount, maxRequests) {
89394
+ this.log.info(`Requesting services with pageSize=${body.pageSize}`);
89395
+ const first = await this.dxSaaSService.oiPost('oi/v2/servicerepo/services', body);
89396
+ const services = [...first.services];
89397
+ const expected = expectedCount(first);
89398
+ let requests = 1;
89399
+ while (services.length < expected) {
89400
+ if (maxRequests !== undefined && requests >= maxRequests) {
89401
+ this.log.warn(`Service list truncated at ${services.length} of ${expected}: maxRequests=${maxRequests} reached`);
89402
+ break;
87650
89403
  }
87651
- return returnServices;
87652
- });
89404
+ body.pageNum++;
89405
+ requests++;
89406
+ this.log.info(`Requesting services page ${body.pageNum}`);
89407
+ const page = await this.dxSaaSService.oiPost('oi/v2/servicerepo/services', body);
89408
+ if (page.services.length === 0) {
89409
+ this.log.warn(`Service list stopped at ${services.length} of ${expected}: page ${body.pageNum} was empty`);
89410
+ break;
89411
+ }
89412
+ services.push(...page.services);
89413
+ }
89414
+ return services;
87653
89415
  }
87654
89416
  /** Builds a services request body scoped to parent (top-level) services. */
87655
89417
  createParentServiceRequestBody(pageSize) {
@@ -88059,15 +89821,21 @@ class SituationService {
88059
89821
  async getSituationOverview(situationId) {
88060
89822
  return this.dxSaaSService.oiGet(`oi/v2/api/groupalarms/_search/${situationId}/overview`, { type: 'cluster' });
88061
89823
  }
88062
- /** Returns lifecycle (state change) events for a situation. */
89824
+ /**
89825
+ * Returns a situation's whole lifecycle (state change) history, newest first.
89826
+ *
89827
+ * @remarks Reads every page until the server's `totalCount` (it used to
89828
+ * stop at 50; a demo-dev situation had 69). A short read keeps the server's
89829
+ * `totalCount` and logs a warning.
89830
+ */
88063
89831
  async getSituationLifecycleEvents(situationId) {
88064
- return this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', {
89832
+ return readLifecyclePages((pageNumber, pageSize) => this.dxSaaSService.oiPost('oi/v2/api/alarms/lifecycle/_search', {
88065
89833
  alarmId: situationId,
88066
- pageSize: 50,
88067
- pageNumber: 0,
89834
+ pageSize,
89835
+ pageNumber,
88068
89836
  sortCol: 'timestamp:desc',
88069
89837
  lifeCycleType: 'SITUATION',
88070
- });
89838
+ }), `situation ${situationId}`, this.log);
88071
89839
  }
88072
89840
  /** Returns the inspector inspection result for a situation (related alarms, topology). */
88073
89841
  async getSituationInspection(situationId) {
@@ -89893,6 +91661,9 @@ exports.ALARM_QUEUE_DEFAULT_VISIBLE_COLUMNS = ALARM_QUEUE_DEFAULT_VISIBLE_COLUMN
89893
91661
  exports.ALARM_QUEUE_DISPLAY_COLUMN_KEYS = ALARM_QUEUE_DISPLAY_COLUMN_KEYS;
89894
91662
  exports.ALARM_QUEUE_FILTER_CONDITIONS = ALARM_QUEUE_FILTER_CONDITIONS;
89895
91663
  exports.ALARM_QUEUE_FILTER_SETTING_KEYS = ALARM_QUEUE_FILTER_SETTING_KEYS;
91664
+ exports.ALARM_RECORD_PAGE_SIZE = ALARM_RECORD_PAGE_SIZE;
91665
+ exports.ALARM_RECORD_WINDOW_CAP = ALARM_RECORD_WINDOW_CAP;
91666
+ exports.ALARM_SEARCH_PAGE_CAP = ALARM_SEARCH_PAGE_CAP;
89896
91667
  exports.ALARM_VIEW_CATEGORIES = ALARM_VIEW_CATEGORIES;
89897
91668
  exports.ALARM_VIEW_FIELD_PATHS = ALARM_VIEW_FIELD_PATHS;
89898
91669
  exports.ALARM_VIEW_SEARCH_PATHS = ALARM_VIEW_SEARCH_PATHS;
@@ -89916,6 +91687,8 @@ exports.AlarmQueuePreferencesSchema = AlarmQueuePreferencesSchema;
89916
91687
  exports.AlarmQueueSchema = AlarmQueueSchema;
89917
91688
  exports.AlarmQueueWriteBodySchema = AlarmQueueWriteBodySchema;
89918
91689
  exports.AlarmQueueWriteResponseSchema = AlarmQueueWriteResponseSchema;
91690
+ exports.AlarmRecordSchema = AlarmRecordSchema;
91691
+ exports.AlarmRecordSearchResponseSchema = AlarmRecordSearchResponseSchema;
89919
91692
  exports.AlarmService = AlarmService;
89920
91693
  exports.AlertService = AlertService;
89921
91694
  exports.AlignmentSchema = AlignmentSchema;
@@ -90110,6 +91883,7 @@ exports.INVENTORY_QUEUE_NO_GROUP = INVENTORY_QUEUE_NO_GROUP;
90110
91883
  exports.ITSM_DEFAULT_TICKET_TEMPLATE = ITSM_DEFAULT_TICKET_TEMPLATE;
90111
91884
  exports.ITSM_SECRET_KEYS = ITSM_SECRET_KEYS;
90112
91885
  exports.ImportTokenRequestSchema = ImportTokenRequestSchema;
91886
+ exports.IncompleteAlarmSearchError = IncompleteAlarmSearchError;
90113
91887
  exports.InventorizeDeleteResponseSchema = InventorizeDeleteResponseSchema;
90114
91888
  exports.InventorizeDraftSchema = InventorizeDraftSchema;
90115
91889
  exports.InventorizeLayerSchema = InventorizeLayerSchema;
@@ -90143,6 +91917,7 @@ exports.JexlEvalError = JexlEvalError;
90143
91917
  exports.JexlSyntaxError = JexlSyntaxError;
90144
91918
  exports.JoinTypeSchema = JoinTypeSchema;
90145
91919
  exports.JsExtensionService = JsExtensionService;
91920
+ exports.LIFECYCLE_PAGE_SIZE = LIFECYCLE_PAGE_SIZE;
90146
91921
  exports.LOG_ANALYTICS_PRODUCT = LOG_ANALYTICS_PRODUCT;
90147
91922
  exports.LogsService = LogsService;
90148
91923
  exports.MAX_SLIS_PER_GROUP = MAX_SLIS_PER_GROUP;
@@ -90245,6 +92020,7 @@ exports.REDACTED_SECRET = REDACTED_SECRET;
90245
92020
  exports.RecurrencePattern = RecurrencePattern;
90246
92021
  exports.RevokeTokenRequestSchema = RevokeTokenRequestSchema;
90247
92022
  exports.RevokeTokensResponseSchema = RevokeTokensResponseSchema;
92023
+ exports.SERVICE_METRIC_PRESENCE_WINDOW_MS = SERVICE_METRIC_PRESENCE_WINDOW_MS;
90248
92024
  exports.SLIService = SLIService;
90249
92025
  exports.SLI_DERIVED_METRIC_SOURCE = SLI_DERIVED_METRIC_SOURCE;
90250
92026
  exports.SMTP_DEFAULT_TEMPLATES = SMTP_DEFAULT_TEMPLATES;
@@ -90493,6 +92269,7 @@ exports.WebhookTestResponseSchema = WebhookTestResponseSchema;
90493
92269
  exports.ags = ags;
90494
92270
  exports.agsresponse = agsresponse;
90495
92271
  exports.alarmFilterDisplayColumnsFor = alarmFilterDisplayColumnsFor;
92272
+ exports.alarmRecordTime = alarmRecordTime;
90496
92273
  exports.alertsForSliIndex = alertsForSliIndex;
90497
92274
  exports.algorithmicSituationsEnabled = algorithmicSituationsEnabled;
90498
92275
  exports.allAlarmQueues = allAlarmQueues;
@@ -90559,6 +92336,7 @@ exports.evaluate = evaluate;
90559
92336
  exports.evaluateTemplate = evaluateTemplate;
90560
92337
  exports.example = example;
90561
92338
  exports.excludedAttributes = excludedAttributes;
92339
+ exports.exportAlarmRecords = exportAlarmRecords;
90562
92340
  exports.exportFileLabel = exportFileLabel;
90563
92341
  exports.exportIncludesToken = exportIncludesToken;
90564
92342
  exports.expressionPipelineNames = expressionPipelineNames;
@@ -90614,6 +92392,7 @@ exports.javaReplaceFirst = javaReplaceFirst;
90614
92392
  exports.javaSplit = javaSplit;
90615
92393
  exports.lintSourceName = lintSourceName;
90616
92394
  exports.listDataStoreSchemaOps = listDataStoreSchemaOps;
92395
+ exports.listNameSpecifierOps = listNameSpecifierOps;
90617
92396
  exports.listSlis = listSlis;
90618
92397
  exports.locationsCreate = locationsCreate;
90619
92398
  exports.locationsDelete = locationsDelete;
@@ -90638,6 +92417,7 @@ exports.maintenancesImmediateDelete = maintenancesImmediateDelete;
90638
92417
  exports.maintenancesImmediatePut = maintenancesImmediatePut;
90639
92418
  exports.maintenancesPostWindows = maintenancesPostWindows;
90640
92419
  exports.maintenancesUpdate = maintenancesUpdate;
92420
+ exports.markServiceMetricPresence = markServiceMetricPresence;
90641
92421
  exports.measureBytes = measureBytes;
90642
92422
  exports.messageGet = messageGet;
90643
92423
  exports.messageTemplateVariables = messageTemplateVariables;
@@ -90664,6 +92444,7 @@ exports.oauthTokenCognateDeleteCurrent = oauthTokenCognateDeleteCurrent;
90664
92444
  exports.oauthTokenDelete = oauthTokenDelete;
90665
92445
  exports.oauthTokenDeleteCurrent = oauthTokenDeleteCurrent;
90666
92446
  exports.orBlocksByField = orBlocksByField;
92447
+ exports.parseAlarmRecordTime = parseAlarmRecordTime;
90667
92448
  exports.parseExpression = parseExpression;
90668
92449
  exports.parseExternalIdFormat = parseExternalIdFormat;
90669
92450
  exports.parseFilter = parseFilter;
@@ -90678,6 +92459,7 @@ exports.producedMetricName = producedMetricName;
90678
92459
  exports.projectCustomAttributes = projectCustomAttributes;
90679
92460
  exports.projectRule = projectRule;
90680
92461
  exports.pruneOrphanSloFunctions = pruneOrphanSloFunctions;
92462
+ exports.readLifecyclePages = readLifecyclePages;
90681
92463
  exports.redactChannelSecrets = redactChannelSecrets;
90682
92464
  exports.reencodeItsmForWrite = reencodeItsmForWrite;
90683
92465
  exports.removeAlert = removeAlert;
@@ -90687,6 +92469,7 @@ exports.resolveAnomalyDetectionProduct = resolveAnomalyDetectionProduct;
90687
92469
  exports.resolveEnrichmentMappings = resolveEnrichmentMappings;
90688
92470
  exports.resolveWebhookPayload = resolveWebhookPayload;
90689
92471
  exports.sampleServiceDetailRequestBody = sampleServiceDetailRequestBody;
92472
+ exports.searchAlarmWindows = searchAlarmWindows;
90690
92473
  exports.searchUniverse = searchUniverse;
90691
92474
  exports.sendWithRetry = sendWithRetry;
90692
92475
  exports.serviceDetailResponseBody = serviceDetailResponseBody;