@interopio/browser 4.2.4 → 4.3.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.
@@ -2,56 +2,56 @@ function getDefaultExportFromCjs$1 (x) {
2
2
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3
3
  }
4
4
 
5
- var isMergeableObject = function isMergeableObject(value) {
6
- return isNonNullObject(value)
7
- && !isSpecial(value)
5
+ var isMergeableObject$1 = function isMergeableObject(value) {
6
+ return isNonNullObject$1(value)
7
+ && !isSpecial$1(value)
8
8
  };
9
9
 
10
- function isNonNullObject(value) {
10
+ function isNonNullObject$1(value) {
11
11
  return !!value && typeof value === 'object'
12
12
  }
13
13
 
14
- function isSpecial(value) {
14
+ function isSpecial$1(value) {
15
15
  var stringValue = Object.prototype.toString.call(value);
16
16
 
17
17
  return stringValue === '[object RegExp]'
18
18
  || stringValue === '[object Date]'
19
- || isReactElement(value)
19
+ || isReactElement$1(value)
20
20
  }
21
21
 
22
22
  // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
23
- var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
24
- var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
23
+ var canUseSymbol$1 = typeof Symbol === 'function' && Symbol.for;
24
+ var REACT_ELEMENT_TYPE$1 = canUseSymbol$1 ? Symbol.for('react.element') : 0xeac7;
25
25
 
26
- function isReactElement(value) {
27
- return value.$$typeof === REACT_ELEMENT_TYPE
26
+ function isReactElement$1(value) {
27
+ return value.$$typeof === REACT_ELEMENT_TYPE$1
28
28
  }
29
29
 
30
- function emptyTarget(val) {
30
+ function emptyTarget$1(val) {
31
31
  return Array.isArray(val) ? [] : {}
32
32
  }
33
33
 
34
- function cloneUnlessOtherwiseSpecified(value, options) {
34
+ function cloneUnlessOtherwiseSpecified$1(value, options) {
35
35
  return (options.clone !== false && options.isMergeableObject(value))
36
- ? deepmerge(emptyTarget(value), value, options)
36
+ ? deepmerge$1(emptyTarget$1(value), value, options)
37
37
  : value
38
38
  }
39
39
 
40
- function defaultArrayMerge(target, source, options) {
40
+ function defaultArrayMerge$1(target, source, options) {
41
41
  return target.concat(source).map(function(element) {
42
- return cloneUnlessOtherwiseSpecified(element, options)
42
+ return cloneUnlessOtherwiseSpecified$1(element, options)
43
43
  })
44
44
  }
45
45
 
46
- function getMergeFunction(key, options) {
46
+ function getMergeFunction$1(key, options) {
47
47
  if (!options.customMerge) {
48
- return deepmerge
48
+ return deepmerge$1
49
49
  }
50
50
  var customMerge = options.customMerge(key);
51
- return typeof customMerge === 'function' ? customMerge : deepmerge
51
+ return typeof customMerge === 'function' ? customMerge : deepmerge$1
52
52
  }
53
53
 
54
- function getEnumerableOwnPropertySymbols(target) {
54
+ function getEnumerableOwnPropertySymbols$1(target) {
55
55
  return Object.getOwnPropertySymbols
56
56
  ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
57
57
  return Object.propertyIsEnumerable.call(target, symbol)
@@ -59,11 +59,11 @@ function getEnumerableOwnPropertySymbols(target) {
59
59
  : []
60
60
  }
61
61
 
62
- function getKeys(target) {
63
- return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
62
+ function getKeys$1(target) {
63
+ return Object.keys(target).concat(getEnumerableOwnPropertySymbols$1(target))
64
64
  }
65
65
 
66
- function propertyIsOnObject(object, property) {
66
+ function propertyIsOnObject$1(object, property) {
67
67
  try {
68
68
  return property in object
69
69
  } catch(_) {
@@ -72,69 +72,69 @@ function propertyIsOnObject(object, property) {
72
72
  }
73
73
 
74
74
  // Protects from prototype poisoning and unexpected merging up the prototype chain.
75
- function propertyIsUnsafe(target, key) {
76
- return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
75
+ function propertyIsUnsafe$1(target, key) {
76
+ return propertyIsOnObject$1(target, key) // Properties are safe to merge if they don't exist in the target yet,
77
77
  && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
78
78
  && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
79
79
  }
80
80
 
81
- function mergeObject(target, source, options) {
81
+ function mergeObject$1(target, source, options) {
82
82
  var destination = {};
83
83
  if (options.isMergeableObject(target)) {
84
- getKeys(target).forEach(function(key) {
85
- destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
84
+ getKeys$1(target).forEach(function(key) {
85
+ destination[key] = cloneUnlessOtherwiseSpecified$1(target[key], options);
86
86
  });
87
87
  }
88
- getKeys(source).forEach(function(key) {
89
- if (propertyIsUnsafe(target, key)) {
88
+ getKeys$1(source).forEach(function(key) {
89
+ if (propertyIsUnsafe$1(target, key)) {
90
90
  return
91
91
  }
92
92
 
93
- if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
94
- destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
93
+ if (propertyIsOnObject$1(target, key) && options.isMergeableObject(source[key])) {
94
+ destination[key] = getMergeFunction$1(key, options)(target[key], source[key], options);
95
95
  } else {
96
- destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
96
+ destination[key] = cloneUnlessOtherwiseSpecified$1(source[key], options);
97
97
  }
98
98
  });
99
99
  return destination
100
100
  }
101
101
 
102
- function deepmerge(target, source, options) {
102
+ function deepmerge$1(target, source, options) {
103
103
  options = options || {};
104
- options.arrayMerge = options.arrayMerge || defaultArrayMerge;
105
- options.isMergeableObject = options.isMergeableObject || isMergeableObject;
104
+ options.arrayMerge = options.arrayMerge || defaultArrayMerge$1;
105
+ options.isMergeableObject = options.isMergeableObject || isMergeableObject$1;
106
106
  // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
107
107
  // implementations can use it. The caller may not replace it.
108
- options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
108
+ options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified$1;
109
109
 
110
110
  var sourceIsArray = Array.isArray(source);
111
111
  var targetIsArray = Array.isArray(target);
112
112
  var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
113
113
 
114
114
  if (!sourceAndTargetTypesMatch) {
115
- return cloneUnlessOtherwiseSpecified(source, options)
115
+ return cloneUnlessOtherwiseSpecified$1(source, options)
116
116
  } else if (sourceIsArray) {
117
117
  return options.arrayMerge(target, source, options)
118
118
  } else {
119
- return mergeObject(target, source, options)
119
+ return mergeObject$1(target, source, options)
120
120
  }
121
121
  }
122
122
 
123
- deepmerge.all = function deepmergeAll(array, options) {
123
+ deepmerge$1.all = function deepmergeAll(array, options) {
124
124
  if (!Array.isArray(array)) {
125
125
  throw new Error('first argument should be an array')
126
126
  }
127
127
 
128
128
  return array.reduce(function(prev, next) {
129
- return deepmerge(prev, next, options)
129
+ return deepmerge$1(prev, next, options)
130
130
  }, {})
131
131
  };
132
132
 
133
- var deepmerge_1 = deepmerge;
133
+ var deepmerge_1$1 = deepmerge$1;
134
134
 
135
- var cjs = deepmerge_1;
135
+ var cjs$1 = deepmerge_1$1;
136
136
 
137
- var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs);
137
+ var deepmerge$2 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs$1);
138
138
 
139
139
  /**
140
140
  * Wraps values in an `Ok` type.
@@ -1807,6 +1807,15 @@ const nonNegativeNumberDecoder$3 = number$1().where((num) => num >= 0, "Expected
1807
1807
  const regexDecoder = anyJson$1().andThen((value) => {
1808
1808
  return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`);
1809
1809
  });
1810
+ const urlDecoder = nonEmptyStringDecoder$3.andThen((url) => {
1811
+ try {
1812
+ new URL(url);
1813
+ return nonEmptyStringDecoder$3;
1814
+ }
1815
+ catch {
1816
+ return fail("Should be a valid URL");
1817
+ }
1818
+ });
1810
1819
 
1811
1820
  const intentDefinitionDecoder$1 = object$1({
1812
1821
  name: nonEmptyStringDecoder$3,
@@ -2134,7 +2143,8 @@ const decoders$1 = {
2134
2143
  common: {
2135
2144
  nonEmptyStringDecoder: nonEmptyStringDecoder$3,
2136
2145
  nonNegativeNumberDecoder: nonNegativeNumberDecoder$3,
2137
- regexDecoder
2146
+ regexDecoder,
2147
+ urlDecoder
2138
2148
  },
2139
2149
  fdc3: {
2140
2150
  allDefinitionsDecoder,
@@ -2338,7 +2348,8 @@ const applicationDataDecoder = object$2({
2338
2348
  title: optional$2(nonEmptyStringDecoder$2),
2339
2349
  version: optional$2(nonEmptyStringDecoder$2),
2340
2350
  icon: optional$2(string$2()),
2341
- caption: optional$2(nonEmptyStringDecoder$2)
2351
+ caption: optional$2(nonEmptyStringDecoder$2),
2352
+ fdc3: optional$2(anyJson$2())
2342
2353
  });
2343
2354
  const baseApplicationDataDecoder = object$2({
2344
2355
  name: nonEmptyStringDecoder$2,
@@ -2347,7 +2358,8 @@ const baseApplicationDataDecoder = object$2({
2347
2358
  title: optional$2(nonEmptyStringDecoder$2),
2348
2359
  version: optional$2(nonEmptyStringDecoder$2),
2349
2360
  icon: optional$2(string$2()),
2350
- caption: optional$2(nonEmptyStringDecoder$2)
2361
+ caption: optional$2(nonEmptyStringDecoder$2),
2362
+ fdc3: optional$2(anyJson$2())
2351
2363
  });
2352
2364
  const appDirectoryStateChangeDecoder = object$2({
2353
2365
  appsAdded: array$2(baseApplicationDataDecoder),
@@ -2397,7 +2409,8 @@ const windowLayoutItemDecoder = object$2({
2397
2409
  allowExtract: optional$2(boolean$2()),
2398
2410
  allowReorder: optional$2(boolean$2()),
2399
2411
  showCloseButton: optional$2(boolean$2()),
2400
- isMaximized: optional$2(boolean$2())
2412
+ isMaximized: optional$2(boolean$2()),
2413
+ instanceId: optional$2(nonEmptyStringDecoder$2)
2401
2414
  })
2402
2415
  });
2403
2416
  const groupLayoutItemDecoder = object$2({
@@ -3021,6 +3034,7 @@ const prefsHelloSuccessDecoder = object$2({
3021
3034
  app: nonEmptyStringDecoder$2,
3022
3035
  }),
3023
3036
  validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)),
3037
+ isAppValidationEnabled: optional$2(boolean$2()),
3024
3038
  });
3025
3039
  const clientErrorDataDecoder = object$2({
3026
3040
  message: nonEmptyStringDecoder$2
@@ -3257,9 +3271,9 @@ const parseConfig = (config = {}) => {
3257
3271
  isPlatformInternal,
3258
3272
  logger: config.systemLogger?.level ?? "info",
3259
3273
  customLogger: config.systemLogger?.customLogger,
3260
- widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}),
3261
- modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}),
3262
- intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}),
3274
+ widget: deepmerge$2(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}),
3275
+ modals: deepmerge$2(defaultModalsConfig, decodedModalsConfigResult.result ?? {}),
3276
+ intentResolver: deepmerge$2(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}),
3263
3277
  };
3264
3278
  return combined;
3265
3279
  };
@@ -4130,7 +4144,7 @@ class GlueBridge {
4130
4144
  return ioError.raiseError(error);
4131
4145
  }
4132
4146
  }
4133
- async createNotificationsSteam() {
4147
+ async createThemesSubscription() {
4134
4148
  const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream);
4135
4149
  if (!streamExists) {
4136
4150
  return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.");
@@ -4582,6 +4596,7 @@ class ApplicationModel {
4582
4596
  userProperties: this.data.userProperties,
4583
4597
  instances: this.instances,
4584
4598
  start: this.start.bind(this),
4599
+ getConfiguration: this.getConfiguration.bind(this),
4585
4600
  onInstanceStarted: this.onInstanceStarted.bind(this),
4586
4601
  onInstanceStopped: this.onInstanceStopped.bind(this)
4587
4602
  };
@@ -4613,6 +4628,30 @@ class ApplicationModel {
4613
4628
  const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options);
4614
4629
  return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions);
4615
4630
  }
4631
+ async getConfiguration() {
4632
+ const { details, intents, hidden, ...customProperties } = this.data.userProperties;
4633
+ const definition = {
4634
+ name: this.data.name,
4635
+ type: this.data.type,
4636
+ details,
4637
+ customProperties
4638
+ };
4639
+ const optionalProperties = {
4640
+ title: this.data.title,
4641
+ version: this.data.version,
4642
+ icon: this.data.icon,
4643
+ caption: this.data.caption,
4644
+ intents,
4645
+ hidden,
4646
+ fdc3: this.data.fdc3
4647
+ };
4648
+ for (const [key, value] of Object.entries(optionalProperties)) {
4649
+ if (value !== undefined) {
4650
+ definition[key] = value;
4651
+ }
4652
+ }
4653
+ return definition;
4654
+ }
4616
4655
  }
4617
4656
 
4618
4657
  const operations$8 = {
@@ -6856,18 +6895,18 @@ class ThemesController {
6856
6895
  bridge;
6857
6896
  registry = CallbackRegistryFactory$1();
6858
6897
  themesSubscription;
6859
- activeThemeSubs = 0;
6860
6898
  async start(coreGlue, ioc) {
6861
6899
  this.logger = coreGlue.logger.subLogger("themes.controller.web");
6862
6900
  this.logger.trace("starting the web themes controller");
6863
6901
  this.bridge = ioc.bridge;
6902
+ await this.setupSubscription();
6903
+ this.logger.trace("themes subscription is ready");
6864
6904
  const api = this.toApi();
6865
6905
  coreGlue.themes = api;
6866
6906
  this.logger.trace("themes are ready");
6867
6907
  }
6868
6908
  handlePlatformShutdown() {
6869
6909
  this.registry.clear();
6870
- this.activeThemeSubs = 0;
6871
6910
  this.themesSubscription?.close();
6872
6911
  delete this.themesSubscription;
6873
6912
  }
@@ -6894,47 +6933,30 @@ class ThemesController {
6894
6933
  runDecoderWithIOError(nonEmptyStringDecoder$2, name);
6895
6934
  await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true });
6896
6935
  }
6897
- async onChanged(callback) {
6936
+ onChanged(callback) {
6898
6937
  if (typeof callback !== "function") {
6899
6938
  return ioError.raiseError("onChanged requires a callback of type function");
6900
6939
  }
6901
- const subReady = this.themesSubscription ?
6902
- Promise.resolve() :
6903
- this.configureThemeSubscription();
6904
- await subReady;
6905
- ++this.activeThemeSubs;
6906
- const unsubFunc = this.registry.add("on-theme-change", callback);
6907
- return () => this.themeUnsub(unsubFunc);
6940
+ return this.registry.add("on-theme-change", callback);
6908
6941
  }
6909
- async configureThemeSubscription() {
6910
- if (this.themesSubscription) {
6911
- return;
6912
- }
6913
- this.themesSubscription = await this.bridge.createNotificationsSteam();
6914
- this.themesSubscription.onData((data) => {
6915
- const eventData = data.data;
6916
- const validation = simpleThemeResponseDecoder.run(eventData);
6917
- if (!validation.ok) {
6918
- this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`);
6919
- return;
6920
- }
6921
- const themeChanged = validation.result;
6922
- this.registry.execute("on-theme-change", themeChanged.theme);
6923
- });
6924
- this.themesSubscription.onClosed(() => {
6925
- this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received");
6926
- this.registry.clear();
6927
- this.activeThemeSubs = 0;
6928
- delete this.themesSubscription;
6929
- });
6942
+ async setupSubscription() {
6943
+ this.themesSubscription = await this.bridge.createThemesSubscription();
6944
+ this.themesSubscription.onData(this.handleStreamData.bind(this));
6945
+ this.themesSubscription.onClosed(this.handleStreamClosure.bind(this));
6930
6946
  }
6931
- themeUnsub(registryUnsub) {
6932
- registryUnsub();
6933
- --this.activeThemeSubs;
6934
- if (this.activeThemeSubs) {
6947
+ handleStreamData(data) {
6948
+ const eventData = data.data;
6949
+ const validation = simpleThemeResponseDecoder.run(eventData);
6950
+ if (!validation.ok) {
6951
+ this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`);
6935
6952
  return;
6936
6953
  }
6937
- this.themesSubscription?.close();
6954
+ const themeChanged = validation.result;
6955
+ this.registry.execute("on-theme-change", themeChanged.theme);
6956
+ }
6957
+ handleStreamClosure() {
6958
+ this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received");
6959
+ this.registry.clear();
6938
6960
  delete this.themesSubscription;
6939
6961
  }
6940
6962
  }
@@ -7044,6 +7066,7 @@ class PrefsController {
7044
7066
  validNonExistentApps;
7045
7067
  signaledSubscription = false;
7046
7068
  interopId;
7069
+ isAppValidationEnabled;
7047
7070
  handlePlatformShutdown() {
7048
7071
  this.registry.clear();
7049
7072
  }
@@ -7059,6 +7082,7 @@ class PrefsController {
7059
7082
  const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true });
7060
7083
  this.platformAppName = prefsHelloSuccess.platform.app;
7061
7084
  this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? [];
7085
+ this.isAppValidationEnabled = prefsHelloSuccess.isAppValidationEnabled ?? true;
7062
7086
  }
7063
7087
  catch (error) {
7064
7088
  this.logger.warn("The platform of this client is outdated and does not support Prefs API.");
@@ -7143,7 +7167,9 @@ class PrefsController {
7143
7167
  subscribeFor(app, callback) {
7144
7168
  const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app);
7145
7169
  const applications = this.appManagerController.getApplications();
7146
- const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp);
7170
+ const isValidApp = this.isAppValidationEnabled
7171
+ ? verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp)
7172
+ : true;
7147
7173
  if (!isValidApp) {
7148
7174
  return ioError.raiseError(`The provided app name "${app}" is not valid.`);
7149
7175
  }
@@ -7215,6 +7241,7 @@ class UIController {
7215
7241
  widgetResources;
7216
7242
  modalsResources;
7217
7243
  intentResolverResources;
7244
+ rootElements = [];
7218
7245
  modalsUiApi;
7219
7246
  isDialogOpen = false;
7220
7247
  intentResolverUiApi;
@@ -7252,6 +7279,7 @@ class UIController {
7252
7279
  const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve();
7253
7280
  const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve();
7254
7281
  const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve();
7282
+ this.subscribeForThemeChanges(io);
7255
7283
  await Promise.all([
7256
7284
  this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(),
7257
7285
  this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(),
@@ -7456,9 +7484,9 @@ class UIController {
7456
7484
  async initializeWidget(io, resources) {
7457
7485
  this.logger.trace("Initializing IOBrowserWidget.");
7458
7486
  const { rootElement } = this.appendWidgetResources(resources);
7459
- this.subscribeForThemeChanges(io, rootElement);
7487
+ this.rootElements.push(rootElement);
7460
7488
  const config = {
7461
- ...deepmerge$1(resources.config, this.config.widget),
7489
+ ...deepmerge$2(resources.config, this.config.widget),
7462
7490
  rootElement
7463
7491
  };
7464
7492
  return PromiseWrap(async () => {
@@ -7471,7 +7499,7 @@ class UIController {
7471
7499
  async initializeModalsUi(io, resources) {
7472
7500
  this.logger.trace("Initializing IOBrowserModalsUI.");
7473
7501
  const { rootElement } = this.appendModalsResources(resources);
7474
- this.subscribeForThemeChanges(io, rootElement);
7502
+ this.rootElements.push(rootElement);
7475
7503
  const config = {
7476
7504
  ...this.config.modals,
7477
7505
  rootElement
@@ -7486,7 +7514,7 @@ class UIController {
7486
7514
  async initializeIntentResolverUI(io, resources) {
7487
7515
  this.logger.trace("Initializing IOBrowserIntentResolverUI.");
7488
7516
  const { rootElement } = this.appendIntentResolverResources(resources);
7489
- this.subscribeForThemeChanges(io, rootElement);
7517
+ this.rootElements.push(rootElement);
7490
7518
  const config = {
7491
7519
  ...this.config.intentResolver,
7492
7520
  rootElement
@@ -7567,22 +7595,25 @@ class UIController {
7567
7595
  }
7568
7596
  this.intentResolverResources = resources;
7569
7597
  }
7570
- subscribeForThemeChanges(io, element) {
7598
+ subscribeForThemeChanges(io) {
7571
7599
  const themesApi = io.themes;
7572
7600
  if (!themesApi) {
7573
7601
  return;
7574
7602
  }
7575
7603
  const changeTheme = async (theme) => {
7576
- if (element.classList.contains(theme.name)) {
7577
- return;
7578
- }
7579
- const allThemes = await themesApi.list();
7580
- element.classList.remove(...allThemes.map(({ name }) => name));
7581
- element.classList.add(theme.name);
7604
+ await Promise.all(this.rootElements.map((element) => this.applyThemeToElement(element, themesApi, theme)));
7582
7605
  };
7583
7606
  themesApi.onChanged(changeTheme);
7584
7607
  themesApi.getCurrent().then(changeTheme);
7585
7608
  }
7609
+ async applyThemeToElement(element, themesApi, theme) {
7610
+ if (element.classList.contains(theme.name)) {
7611
+ return;
7612
+ }
7613
+ const allThemes = await themesApi.list();
7614
+ element.classList.remove(...allThemes.map(({ name }) => name));
7615
+ element.classList.add(theme.name);
7616
+ }
7586
7617
  }
7587
7618
 
7588
7619
  class IoC {
@@ -7745,7 +7776,7 @@ class IoC {
7745
7776
  }
7746
7777
  }
7747
7778
 
7748
- var version$1 = "4.2.4";
7779
+ var version$1 = "4.3.0";
7749
7780
 
7750
7781
  const setupGlobalSystem = (io, bridge) => {
7751
7782
  return {
@@ -8840,6 +8871,9 @@ class Utils {
8840
8871
  return Utils._isNode;
8841
8872
  }
8842
8873
  static _isNode;
8874
+ static getMethodName(method) {
8875
+ return typeof method === "string" ? method : method?.name;
8876
+ }
8843
8877
  }
8844
8878
 
8845
8879
  class PromiseWrapper {
@@ -10799,186 +10833,2201 @@ const ContextMessageReplaySpec = {
10799
10833
  }
10800
10834
  };
10801
10835
 
10802
- var version = "6.8.1";
10836
+ var version = "6.10.0";
10803
10837
 
10804
- function prepareConfig (configuration, ext, glue42gd) {
10805
- let nodeStartingContext;
10806
- if (Utils.isNode()) {
10807
- const startingContextString = process.env._GD_STARTING_CONTEXT_;
10808
- if (startingContextString) {
10809
- try {
10810
- nodeStartingContext = JSON.parse(startingContextString);
10811
- }
10812
- catch {
10813
- }
10814
- }
10815
- }
10816
- function getConnection() {
10817
- const gwConfig = configuration.gateway;
10818
- const protocolVersion = gwConfig?.protocolVersion ?? 3;
10819
- const reconnectInterval = gwConfig?.reconnectInterval;
10820
- const reconnectAttempts = gwConfig?.reconnectAttempts;
10821
- const defaultWs = "ws://localhost:8385";
10822
- let ws = gwConfig?.ws;
10823
- const sharedWorker = gwConfig?.sharedWorker;
10824
- const inproc = gwConfig?.inproc;
10825
- const webPlatform = gwConfig?.webPlatform ?? undefined;
10826
- if (glue42gd) {
10827
- ws = glue42gd.gwURL;
10828
- }
10829
- if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) {
10830
- ws = nodeStartingContext.gwURL;
10831
- }
10832
- if (!ws && !sharedWorker && !inproc) {
10833
- ws = defaultWs;
10834
- }
10835
- let instanceId;
10836
- let windowId;
10837
- let pid;
10838
- let environment;
10839
- let region;
10840
- const appName = getApplication();
10841
- let uniqueAppName = appName;
10842
- if (typeof glue42gd !== "undefined") {
10843
- windowId = glue42gd.windowId;
10844
- pid = glue42gd.pid;
10845
- if (glue42gd.env) {
10846
- environment = glue42gd.env.env;
10847
- region = glue42gd.env.region;
10848
- }
10849
- uniqueAppName = glue42gd.application ?? "glue-app";
10850
- instanceId = glue42gd.appInstanceId;
10851
- }
10852
- else if (Utils.isNode()) {
10853
- pid = process.pid;
10854
- if (nodeStartingContext) {
10855
- environment = nodeStartingContext.env;
10856
- region = nodeStartingContext.region;
10857
- instanceId = nodeStartingContext.instanceId;
10858
- }
10859
- }
10860
- else if (typeof window?.glue42electron !== "undefined") {
10861
- windowId = window?.glue42electron.instanceId;
10862
- pid = window?.glue42electron.pid;
10863
- environment = window?.glue42electron.env;
10864
- region = window?.glue42electron.region;
10865
- uniqueAppName = window?.glue42electron.application ?? "glue-app";
10866
- instanceId = window?.glue42electron.instanceId;
10867
- }
10868
- else ;
10869
- const replaySpecs = configuration.gateway?.replaySpecs ?? [];
10870
- replaySpecs.push(ContextMessageReplaySpec);
10871
- let identity = {
10872
- application: uniqueAppName,
10873
- applicationName: appName,
10874
- windowId,
10875
- instance: instanceId,
10876
- process: pid,
10877
- region,
10878
- environment,
10879
- api: ext.version || version
10880
- };
10881
- if (configuration.identity) {
10882
- identity = Object.assign(identity, configuration.identity);
10883
- }
10884
- return {
10885
- identity,
10886
- reconnectInterval,
10887
- ws,
10888
- sharedWorker,
10889
- webPlatform,
10890
- inproc,
10891
- protocolVersion,
10892
- reconnectAttempts,
10893
- replaySpecs,
10894
- };
10895
- }
10896
- function getContexts() {
10897
- const defaultConfig = {
10898
- reAnnounceKnownContexts: true,
10899
- subscribeOnUpdate: true,
10900
- subscribeOnGet: true,
10901
- onlyReAnnounceSubscribedContexts: true
10902
- };
10903
- if (typeof configuration.contexts === "undefined") {
10904
- return defaultConfig;
10905
- }
10906
- if (typeof configuration.contexts === "boolean" && configuration.contexts) {
10907
- return defaultConfig;
10908
- }
10909
- if (typeof configuration.contexts === "object") {
10910
- return { ...defaultConfig, ...configuration.contexts };
10911
- }
10838
+ /*!
10839
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
10840
+ *
10841
+ * Copyright (c) 2014-2017, Jon Schlinkert.
10842
+ * Released under the MIT License.
10843
+ */
10844
+ function isObject$1(o) {
10845
+ return Object.prototype.toString.call(o) === '[object Object]';
10846
+ }
10847
+ function isPlainObject$2(o) {
10848
+ let ctor;
10849
+ let prot;
10850
+ if (isObject$1(o) === false)
10851
+ return false;
10852
+ ctor = o.constructor;
10853
+ if (ctor === undefined)
10854
+ return true;
10855
+ prot = ctor.prototype;
10856
+ if (isObject$1(prot) === false)
10857
+ return false;
10858
+ if (prot.hasOwnProperty('isPrototypeOf') === false) {
10912
10859
  return false;
10913
10860
  }
10914
- function getApplication() {
10915
- if (configuration.application) {
10916
- return configuration.application;
10917
- }
10918
- if (glue42gd) {
10919
- return glue42gd.applicationName;
10920
- }
10921
- if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") {
10922
- return window.glue42electron.application;
10923
- }
10924
- const uid = nanoid(10);
10925
- if (Utils.isNode()) {
10926
- if (nodeStartingContext) {
10927
- return nodeStartingContext.applicationConfig.name;
10928
- }
10929
- return "NodeJS" + uid;
10930
- }
10931
- if (typeof window !== "undefined" && typeof document !== "undefined") {
10932
- return document.title + ` (${uid})`;
10933
- }
10934
- return uid;
10935
- }
10936
- function getAuth() {
10937
- if (typeof configuration.auth === "string") {
10938
- return {
10939
- token: configuration.auth
10940
- };
10941
- }
10942
- if (configuration.auth) {
10943
- return configuration.auth;
10944
- }
10945
- if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) {
10946
- return {
10947
- gatewayToken: nodeStartingContext.gwToken
10948
- };
10949
- }
10950
- if (configuration.gateway?.webPlatform) {
10951
- return {
10952
- username: "glue42",
10953
- password: ""
10954
- };
10955
- }
10956
- }
10957
- function getLogger() {
10958
- let config = configuration.logger;
10959
- const defaultLevel = "warn";
10960
- if (!config) {
10961
- config = defaultLevel;
10962
- }
10963
- let gdConsoleLevel;
10964
- if (glue42gd) {
10965
- gdConsoleLevel = glue42gd.consoleLogLevel;
10966
- }
10967
- if (typeof config === "string") {
10968
- return { console: gdConsoleLevel ?? config, publish: defaultLevel };
10969
- }
10970
- return {
10971
- console: gdConsoleLevel ?? config.console ?? defaultLevel,
10972
- publish: config.publish ?? defaultLevel
10973
- };
10974
- }
10975
- const connection = getConnection();
10976
- let application = getApplication();
10977
- if (typeof window !== "undefined") {
10978
- const windowAsAny = window;
10979
- const containerApplication = windowAsAny.htmlContainer ?
10980
- `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` :
10981
- windowAsAny?.glue42gd?.application;
10861
+ return true;
10862
+ }
10863
+
10864
+ var isMergeableObject = function isMergeableObject(value) {
10865
+ return isNonNullObject(value)
10866
+ && !isSpecial(value)
10867
+ };
10868
+
10869
+ function isNonNullObject(value) {
10870
+ return !!value && typeof value === 'object'
10871
+ }
10872
+
10873
+ function isSpecial(value) {
10874
+ var stringValue = Object.prototype.toString.call(value);
10875
+
10876
+ return stringValue === '[object RegExp]'
10877
+ || stringValue === '[object Date]'
10878
+ || isReactElement(value)
10879
+ }
10880
+
10881
+ // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
10882
+ var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
10883
+ var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
10884
+
10885
+ function isReactElement(value) {
10886
+ return value.$$typeof === REACT_ELEMENT_TYPE
10887
+ }
10888
+
10889
+ function emptyTarget(val) {
10890
+ return Array.isArray(val) ? [] : {}
10891
+ }
10892
+
10893
+ function cloneUnlessOtherwiseSpecified(value, options) {
10894
+ return (options.clone !== false && options.isMergeableObject(value))
10895
+ ? deepmerge(emptyTarget(value), value, options)
10896
+ : value
10897
+ }
10898
+
10899
+ function defaultArrayMerge(target, source, options) {
10900
+ return target.concat(source).map(function(element) {
10901
+ return cloneUnlessOtherwiseSpecified(element, options)
10902
+ })
10903
+ }
10904
+
10905
+ function getMergeFunction(key, options) {
10906
+ if (!options.customMerge) {
10907
+ return deepmerge
10908
+ }
10909
+ var customMerge = options.customMerge(key);
10910
+ return typeof customMerge === 'function' ? customMerge : deepmerge
10911
+ }
10912
+
10913
+ function getEnumerableOwnPropertySymbols(target) {
10914
+ return Object.getOwnPropertySymbols
10915
+ ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
10916
+ return Object.propertyIsEnumerable.call(target, symbol)
10917
+ })
10918
+ : []
10919
+ }
10920
+
10921
+ function getKeys(target) {
10922
+ return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
10923
+ }
10924
+
10925
+ function propertyIsOnObject(object, property) {
10926
+ try {
10927
+ return property in object
10928
+ } catch(_) {
10929
+ return false
10930
+ }
10931
+ }
10932
+
10933
+ // Protects from prototype poisoning and unexpected merging up the prototype chain.
10934
+ function propertyIsUnsafe(target, key) {
10935
+ return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
10936
+ && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
10937
+ && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
10938
+ }
10939
+
10940
+ function mergeObject(target, source, options) {
10941
+ var destination = {};
10942
+ if (options.isMergeableObject(target)) {
10943
+ getKeys(target).forEach(function(key) {
10944
+ destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
10945
+ });
10946
+ }
10947
+ getKeys(source).forEach(function(key) {
10948
+ if (propertyIsUnsafe(target, key)) {
10949
+ return
10950
+ }
10951
+
10952
+ if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
10953
+ destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
10954
+ } else {
10955
+ destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
10956
+ }
10957
+ });
10958
+ return destination
10959
+ }
10960
+
10961
+ function deepmerge(target, source, options) {
10962
+ options = options || {};
10963
+ options.arrayMerge = options.arrayMerge || defaultArrayMerge;
10964
+ options.isMergeableObject = options.isMergeableObject || isMergeableObject;
10965
+ // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
10966
+ // implementations can use it. The caller may not replace it.
10967
+ options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
10968
+
10969
+ var sourceIsArray = Array.isArray(source);
10970
+ var targetIsArray = Array.isArray(target);
10971
+ var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
10972
+
10973
+ if (!sourceAndTargetTypesMatch) {
10974
+ return cloneUnlessOtherwiseSpecified(source, options)
10975
+ } else if (sourceIsArray) {
10976
+ return options.arrayMerge(target, source, options)
10977
+ } else {
10978
+ return mergeObject(target, source, options)
10979
+ }
10980
+ }
10981
+
10982
+ deepmerge.all = function deepmergeAll(array, options) {
10983
+ if (!Array.isArray(array)) {
10984
+ throw new Error('first argument should be an array')
10985
+ }
10986
+
10987
+ return array.reduce(function(prev, next) {
10988
+ return deepmerge(prev, next, options)
10989
+ }, {})
10990
+ };
10991
+
10992
+ var deepmerge_1 = deepmerge;
10993
+
10994
+ var cjs = deepmerge_1;
10995
+
10996
+ var deepMerge = /*@__PURE__*/getDefaultExportFromCjs(cjs);
10997
+
10998
+ var dist = {};
10999
+
11000
+ var builder$3 = {};
11001
+
11002
+ var builder$2 = {};
11003
+
11004
+ var nullMetricsManager = {};
11005
+
11006
+ var nullManager$1 = {};
11007
+
11008
+ Object.defineProperty(nullManager$1, "__esModule", { value: true });
11009
+ nullManager$1.NullManager = void 0;
11010
+ class NullManager {
11011
+ constructor() {
11012
+ this.started = false;
11013
+ }
11014
+ waitForFinalExport(timeoutMs) {
11015
+ return Promise.resolve();
11016
+ }
11017
+ get settings() {
11018
+ return {};
11019
+ }
11020
+ start() {
11021
+ this.started = true;
11022
+ return Promise.resolve();
11023
+ }
11024
+ stop() {
11025
+ this.started = false;
11026
+ return Promise.resolve();
11027
+ }
11028
+ }
11029
+ nullManager$1.NullManager = NullManager;
11030
+
11031
+ var safeStringify$1 = {};
11032
+
11033
+ var isPlainObject$1 = {};
11034
+
11035
+ // https://github.com/jonschlinkert/is-plain-object/blob/master/is-plain-object.js
11036
+ // cf204a3
11037
+ Object.defineProperty(isPlainObject$1, "__esModule", { value: true });
11038
+ isPlainObject$1.isPlainObject = void 0;
11039
+ /*!
11040
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
11041
+ *
11042
+ * Copyright (c) 2014-2017, Jon Schlinkert.
11043
+ * Released under the MIT License.
11044
+ */
11045
+ function isObject(o) {
11046
+ return Object.prototype.toString.call(o) === '[object Object]';
11047
+ }
11048
+ function isPlainObject(o) {
11049
+ let ctor;
11050
+ let prot;
11051
+ if (isObject(o) === false)
11052
+ return false;
11053
+ // If has modified constructor
11054
+ ctor = o.constructor;
11055
+ if (ctor === undefined)
11056
+ return true;
11057
+ // If has modified prototype
11058
+ prot = ctor.prototype;
11059
+ if (isObject(prot) === false)
11060
+ return false;
11061
+ // If constructor does not have an Object-specific method
11062
+ if (prot.hasOwnProperty('isPrototypeOf') === false) {
11063
+ return false;
11064
+ }
11065
+ // Most likely a plain Object
11066
+ return true;
11067
+ }
11068
+ isPlainObject$1.isPlainObject = isPlainObject;
11069
+
11070
+ Object.defineProperty(safeStringify$1, "__esModule", { value: true });
11071
+ safeStringify$1.safeStringify = void 0;
11072
+ const is_plain_object_1 = isPlainObject$1;
11073
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11074
+ function safeStringify(obj) {
11075
+ if (!obj) {
11076
+ return JSON.stringify(obj);
11077
+ }
11078
+ return JSON.stringify(obj, (k, v) => {
11079
+ if (!v || typeof v !== "object")
11080
+ return v;
11081
+ if (!(0, is_plain_object_1.isPlainObject)(v))
11082
+ return Object.prototype.toString.call(v);
11083
+ return v;
11084
+ });
11085
+ }
11086
+ safeStringify$1.safeStringify = safeStringify;
11087
+
11088
+ var _null$1 = {};
11089
+
11090
+ Object.defineProperty(_null$1, "__esModule", { value: true });
11091
+ _null$1.NullMetric = void 0;
11092
+ class NullMetric {
11093
+ constructor(settings, logger) {
11094
+ this.settings = settings;
11095
+ this.logger = logger;
11096
+ this.started = false;
11097
+ }
11098
+ start() {
11099
+ var _a;
11100
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`null metric has been started instead of ${this.settings.type} one`);
11101
+ this.started = true;
11102
+ return Promise.resolve();
11103
+ }
11104
+ stop() {
11105
+ var _a;
11106
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`null metric has been stopped instead of ${this.settings.type} one`);
11107
+ this.started = false;
11108
+ return Promise.resolve();
11109
+ }
11110
+ add() { }
11111
+ record() { }
11112
+ }
11113
+ _null$1.NullMetric = NullMetric;
11114
+
11115
+ Object.defineProperty(nullMetricsManager, "__esModule", { value: true });
11116
+ nullMetricsManager.NullMetricsManager = void 0;
11117
+ const nullManager_1$2 = nullManager$1;
11118
+ const safe_stringify_1$2 = safeStringify$1;
11119
+ const null_1 = _null$1;
11120
+ class NullMetricsManager extends nullManager_1$2.NullManager {
11121
+ constructor(settings, otelSettings, logger) {
11122
+ if ((otelSettings === null || otelSettings === void 0 ? void 0 : otelSettings.logSettingsOnStartup) !== false) {
11123
+ logger === null || logger === void 0 ? void 0 : logger.info(`Starting NullMetrcsManager with settings ${(0, safe_stringify_1$2.safeStringify)(settings)}`);
11124
+ }
11125
+ super();
11126
+ }
11127
+ waitForFinalExport(timeoutMs) {
11128
+ return Promise.resolve();
11129
+ }
11130
+ getFromSettings(settings) {
11131
+ return new null_1.NullMetric(settings);
11132
+ }
11133
+ get(type) {
11134
+ return new null_1.NullMetric({ name: type, type, enabled: false, description: type });
11135
+ }
11136
+ }
11137
+ nullMetricsManager.NullMetricsManager = NullMetricsManager;
11138
+
11139
+ var hasRequiredBuilder$3;
11140
+
11141
+ function requireBuilder$3 () {
11142
+ if (hasRequiredBuilder$3) return builder$2;
11143
+ hasRequiredBuilder$3 = 1;
11144
+ Object.defineProperty(builder$2, "__esModule", { value: true });
11145
+ builder$2.MetricsManagerBuilder = void 0;
11146
+ const nullMetricsManager_1 = nullMetricsManager;
11147
+ const __1 = requireDist();
11148
+ class MetricsManagerBuilder {
11149
+ withLogger(logger) {
11150
+ this.logger = logger;
11151
+ return this;
11152
+ }
11153
+ withSettings(settings) {
11154
+ this.settings = settings;
11155
+ return this;
11156
+ }
11157
+ withMeterProvider(meterProviderCreateFunc) {
11158
+ this.meterProviderCreateFunc = meterProviderCreateFunc;
11159
+ return this;
11160
+ }
11161
+ withDependencyContainer(container) {
11162
+ this.dependencyContainer = container;
11163
+ return this;
11164
+ }
11165
+ build() {
11166
+ var _a, _b, _c, _d;
11167
+ if (((_a = globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.metrics) &&
11168
+ ((_b = this.settings) === null || _b === void 0 ? void 0 : _b.definitiveInstance) !== true) {
11169
+ return globalThis.ioInsightsInternals.metrics;
11170
+ }
11171
+ const toReturn = this.buildCore();
11172
+ globalThis.ioInsightsInternals = (_c = globalThis.ioInsightsInternals) !== null && _c !== void 0 ? _c : {};
11173
+ if (!globalThis.ioInsightsInternals.metrics ||
11174
+ ((_d = this.settings) === null || _d === void 0 ? void 0 : _d.definitiveInstance)) {
11175
+ globalThis.ioInsightsInternals.metrics = toReturn;
11176
+ }
11177
+ return toReturn;
11178
+ }
11179
+ buildCore() {
11180
+ var _a, _b, _c, _d;
11181
+ let metricsPlugin;
11182
+ if (((_a = this.settings) === null || _a === void 0 ? void 0 : _a.enabled) !== true ||
11183
+ ((_c = (_b = this.settings) === null || _b === void 0 ? void 0 : _b.metrics) === null || _c === void 0 ? void 0 : _c.enabled) !== true ||
11184
+ !(metricsPlugin = (0, __1.loadInsightsPlugin)("metrics", this.logger))) {
11185
+ return new nullMetricsManager_1.NullMetricsManager((_d = this.settings) === null || _d === void 0 ? void 0 : _d.metrics, this.settings, this.logger);
11186
+ }
11187
+ const manager = metricsPlugin.newMetricsManager(this.settings, this.dependencyContainer, this.meterProviderCreateFunc, this.logger);
11188
+ return manager;
11189
+ }
11190
+ }
11191
+ builder$2.MetricsManagerBuilder = MetricsManagerBuilder;
11192
+
11193
+ return builder$2;
11194
+ }
11195
+
11196
+ var builder$1 = {};
11197
+
11198
+ var nullTracesManager = {};
11199
+
11200
+ var nullTracingState = {};
11201
+
11202
+ Object.defineProperty(nullTracingState, "__esModule", { value: true });
11203
+ class NullTracingState {
11204
+ constructor(source, propagationInfo, disablePropagation) {
11205
+ this.source = source;
11206
+ this.propagationInfo = propagationInfo;
11207
+ this.disablePropagation = disablePropagation;
11208
+ this.currentSpanStatus = { code: 0 /*SpanStatusCode.UNSET*/ };
11209
+ this.level = "OFF";
11210
+ }
11211
+ endSpan() {
11212
+ return Promise.resolve();
11213
+ }
11214
+ get enabled() {
11215
+ return false;
11216
+ }
11217
+ get id() {
11218
+ return undefined;
11219
+ }
11220
+ get traceId() {
11221
+ return undefined;
11222
+ }
11223
+ set status(status) {
11224
+ this.currentSpanStatus = Object.assign({}, status);
11225
+ }
11226
+ get status() {
11227
+ return this.currentSpanStatus;
11228
+ }
11229
+ addEvent(name, attributesOrStartTime, startTime) {
11230
+ return this;
11231
+ }
11232
+ recordException(exception, time) { }
11233
+ isRecording() {
11234
+ return false;
11235
+ }
11236
+ updateName(name) {
11237
+ return this;
11238
+ }
11239
+ spanContext() {
11240
+ return undefined;
11241
+ }
11242
+ addData(level, data) {
11243
+ }
11244
+ end() { }
11245
+ getPropagationInfo() {
11246
+ if (this.propagationInfo) {
11247
+ return this.propagationInfo;
11248
+ }
11249
+ return null;
11250
+ // // todo vnikolov: should we use otel's own context management at all?
11251
+ // const propagationInfo = { };
11252
+ // propagation.inject(context.active(), propagationInfo);
11253
+ // return propagationInfo;
11254
+ }
11255
+ injectPropagationInfo(carrier) {
11256
+ if (this.propagationInfo && !this.disablePropagation) {
11257
+ carrier.__interopIOTracePropagationInfo = this.propagationInfo;
11258
+ }
11259
+ }
11260
+ }
11261
+ nullTracingState.default = NullTracingState;
11262
+
11263
+ var traces = {};
11264
+
11265
+ var otelUtils = {};
11266
+
11267
+ var container = {};
11268
+
11269
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
11270
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11271
+ return new (P || (P = Promise))(function (resolve, reject) {
11272
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11273
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11274
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11275
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11276
+ });
11277
+ };
11278
+ Object.defineProperty(container, "__esModule", { value: true });
11279
+ container.Container = void 0;
11280
+ const safe_stringify_1$1 = safeStringify$1;
11281
+ class Container {
11282
+ static get instance() {
11283
+ var _a, _b;
11284
+ return (_a = Container._instance) !== null && _a !== void 0 ? _a : (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.instance;
11285
+ }
11286
+ static get settings() {
11287
+ var _a;
11288
+ return (_a = Container._settings) !== null && _a !== void 0 ? _a : Container.instance.settings;
11289
+ }
11290
+ static set settings(value) {
11291
+ Container._settings = value;
11292
+ }
11293
+ static errorless(callback, defaultValue) {
11294
+ try {
11295
+ if (typeof callback !== "function") {
11296
+ return callback;
11297
+ }
11298
+ // eslint-disable-next-line @typescript-eslint/ban-types
11299
+ const toReturn = callback();
11300
+ return toReturn;
11301
+ }
11302
+ catch (err) {
11303
+ return Container.handleErrorlessMode(err, defaultValue);
11304
+ }
11305
+ }
11306
+ static errorlessDefined(callback, defaultValue) {
11307
+ try {
11308
+ if (typeof callback !== "function") {
11309
+ return callback;
11310
+ }
11311
+ // eslint-disable-next-line @typescript-eslint/ban-types
11312
+ const toReturn = callback();
11313
+ return toReturn;
11314
+ }
11315
+ catch (err) {
11316
+ return Container.handleErrorlessMode(err, defaultValue);
11317
+ }
11318
+ }
11319
+ static errorlessAsync(callback, defaultValue) {
11320
+ return __awaiter(this, void 0, void 0, function* () {
11321
+ try {
11322
+ if (typeof callback !== "function") {
11323
+ return callback;
11324
+ }
11325
+ // eslint-disable-next-line @typescript-eslint/ban-types
11326
+ const toReturn = (yield callback)();
11327
+ return toReturn;
11328
+ }
11329
+ catch (err) {
11330
+ return Container.handleErrorlessMode(err, defaultValue);
11331
+ }
11332
+ });
11333
+ }
11334
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11335
+ static handleErrorlessMode(err, defaultValue) {
11336
+ var _a, _b, _c, _d, _e;
11337
+ let message = undefined;
11338
+ try {
11339
+ if (err === null || err === void 0 ? void 0 : err.message) {
11340
+ message = (err === null || err === void 0 ? void 0 : err.message) + " " + ((_a = err === null || err === void 0 ? void 0 : err.stack) !== null && _a !== void 0 ? _a : new Error().stack);
11341
+ }
11342
+ if (!message) {
11343
+ try {
11344
+ message = (0, safe_stringify_1$1.safeStringify)(err) + " " + new Error().stack;
11345
+ }
11346
+ catch ( /*silent catch*/_f) { /*silent catch*/ }
11347
+ }
11348
+ if (!message) {
11349
+ try {
11350
+ message = (err === null || err === void 0 ? void 0 : err.toString()) + " " + new Error().stack;
11351
+ }
11352
+ catch ( /*silent catch*/_g) { /*silent catch*/ }
11353
+ }
11354
+ }
11355
+ catch ( /*silent catch*/_h) { /*silent catch*/ }
11356
+ if (!message) {
11357
+ message = "unknown " + new Error().stack;
11358
+ }
11359
+ try {
11360
+ if (!((_c = (_b = Container.instance) === null || _b === void 0 ? void 0 : _b.settings) === null || _c === void 0 ? void 0 : _c.errorlessMode)) {
11361
+ (_d = Container.instance.logger) === null || _d === void 0 ? void 0 : _d.error("Observed error " + message);
11362
+ throw err;
11363
+ }
11364
+ }
11365
+ catch (_j) {
11366
+ throw err;
11367
+ }
11368
+ try {
11369
+ (_e = Container.instance.logger) === null || _e === void 0 ? void 0 : _e.warn("Caught error " + message);
11370
+ return defaultValue;
11371
+ }
11372
+ catch (_k) {
11373
+ return defaultValue;
11374
+ }
11375
+ }
11376
+ constructor(_settings, _traces, metrics, logs, logger) {
11377
+ var _a;
11378
+ this._settings = _settings;
11379
+ this._traces = _traces;
11380
+ this.metrics = metrics;
11381
+ this.logs = logs;
11382
+ this.logger = logger;
11383
+ this.started = false;
11384
+ Container._instance = this;
11385
+ globalThis.ioInsightsInternals = (_a = globalThis.ioInsightsInternals) !== null && _a !== void 0 ? _a : {};
11386
+ globalThis.ioInsightsInternals.instance = this;
11387
+ }
11388
+ get traces() {
11389
+ var _a, _b;
11390
+ if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.traces) {
11391
+ return (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.traces;
11392
+ }
11393
+ return this._traces;
11394
+ }
11395
+ waitForFinalExport(timeoutMs) {
11396
+ var _a, _b, _c;
11397
+ return Promise.allSettled([
11398
+ (_a = this.traces) === null || _a === void 0 ? void 0 : _a.waitForFinalExport(timeoutMs),
11399
+ (_b = this.metrics) === null || _b === void 0 ? void 0 : _b.waitForFinalExport(timeoutMs),
11400
+ (_c = this.logs) === null || _c === void 0 ? void 0 : _c.waitForFinalExport(timeoutMs)
11401
+ ]);
11402
+ }
11403
+ get settings() {
11404
+ return this._settings;
11405
+ }
11406
+ start() {
11407
+ return __awaiter(this, void 0, void 0, function* () {
11408
+ // vnikolov TODO: maybe log this? don't silently refuse to start
11409
+ const metricsPromise = this.metrics.settings.enabled ? this.metrics.start() : Promise.resolve();
11410
+ const tracesPromise = this.traces.settings.enabled ? this.traces.start() : Promise.resolve();
11411
+ const logsPromise = this.logs.settings.enabled ? this.logs.start() : Promise.resolve();
11412
+ yield Promise.all([metricsPromise, tracesPromise, logsPromise]);
11413
+ this.started = true;
11414
+ });
11415
+ }
11416
+ stop() {
11417
+ return __awaiter(this, void 0, void 0, function* () {
11418
+ const metricsPromise = this.metrics.started ? this.metrics.stop() : Promise.resolve();
11419
+ const tracesPromise = this.traces.started ? this.traces.stop() : Promise.resolve();
11420
+ const logsPromise = this.logs.started ? this.logs.stop() : Promise.resolve();
11421
+ yield Promise.all([metricsPromise, tracesPromise, logsPromise]);
11422
+ this.started = false;
11423
+ });
11424
+ }
11425
+ }
11426
+ container.Container = Container;
11427
+
11428
+ (function (exports$1) {
11429
+ Object.defineProperty(exports$1, "__esModule", { value: true });
11430
+ exports$1.extractFilteringContextFromArgs = exports$1.deep_value = exports$1.getOTELData = exports$1.flattenOtelAtributes = void 0;
11431
+ const container_1 = container;
11432
+ /* eslint-disable @typescript-eslint/no-explicit-any */
11433
+ const flattenOtelAtributes = (data, maxDepth) => {
11434
+ if (data === undefined ||
11435
+ data === null) {
11436
+ return {};
11437
+ }
11438
+ if (typeof data !== "object") {
11439
+ data = { unknownAttribute: data };
11440
+ }
11441
+ const toReturn = {};
11442
+ for (const [key, value] of Object.entries(data)) {
11443
+ const otelValues = (0, exports$1.getOTELData)(key, value, 0, maxDepth);
11444
+ for (const [otelKey, otelValue] of otelValues) {
11445
+ toReturn[otelKey] = otelValue;
11446
+ }
11447
+ }
11448
+ return toReturn;
11449
+ };
11450
+ exports$1.flattenOtelAtributes = flattenOtelAtributes;
11451
+ const getOTELData = (key, value, depth, maxDepth) => {
11452
+ depth += 1;
11453
+ if (depth > maxDepth) {
11454
+ return [[key, "<depth exceeded>"]];
11455
+ }
11456
+ const isObject = Boolean(value && typeof value === "object");
11457
+ const isValidPrimitiveValue = typeof value === "number" || typeof value === "string" || typeof value === "boolean";
11458
+ if (isValidPrimitiveValue) {
11459
+ return [[key, value]];
11460
+ }
11461
+ if (isAttributeArray(value)) {
11462
+ return [[key, value]].concat(flatten(key, value, depth, maxDepth));
11463
+ }
11464
+ else if (isObject) {
11465
+ return flatten(key, value, depth, maxDepth);
11466
+ }
11467
+ else if (typeof value === "function") {
11468
+ return [];
11469
+ }
11470
+ else if (value) {
11471
+ return [[key, value + ""]];
11472
+ }
11473
+ else {
11474
+ return [];
11475
+ }
11476
+ };
11477
+ exports$1.getOTELData = getOTELData;
11478
+ const flatten = (key, obj, depth, maxDepth) => {
11479
+ const toReturn = [];
11480
+ for (const [key2, val2] of Object.entries(obj)) {
11481
+ for (const [key3, val3] of (0, exports$1.getOTELData)(key2, val2, depth, maxDepth)) {
11482
+ toReturn.push([key + "." + key3, val3]);
11483
+ }
11484
+ }
11485
+ return toReturn;
11486
+ };
11487
+ const isAttributeArray = (value) => {
11488
+ if (!Array.isArray(value)) {
11489
+ return false;
11490
+ }
11491
+ return value.every((item) => item === null ||
11492
+ item === undefined ||
11493
+ typeof item === "string" ||
11494
+ typeof item === "number" ||
11495
+ typeof item === "boolean");
11496
+ };
11497
+ // todo vnikolov: document all the places where deep_value is used in the spec, as well
11498
+ // as the regex matches
11499
+ const deep_value = function (obj, path) {
11500
+ // eslint-disable-next-line no-var
11501
+ if (!path) {
11502
+ return null;
11503
+ }
11504
+ // eslint-disable-next-line no-var
11505
+ for (var i = 0, path = path.split("."), len = path.length; i < len; i++) {
11506
+ if (obj === null || obj === undefined) {
11507
+ return undefined;
11508
+ }
11509
+ obj = obj[path[i]];
11510
+ }
11511
+ return obj;
11512
+ };
11513
+ exports$1.deep_value = deep_value;
11514
+ // https://stackoverflow.com/a/8817473
11515
+ const extractFilteringContextFromArgs = (template, args, that) => {
11516
+ let filteringContext = {};
11517
+ if (typeof template.thisMapping === "function") {
11518
+ filteringContext = Object.assign(Object.assign({}, filteringContext), container_1.Container.errorless(() => template.thisMapping.apply(that, [that])));
11519
+ }
11520
+ else {
11521
+ Object.keys(template.thisMapping || {}).forEach((keyOrPath) => {
11522
+ if (!keyOrPath || !template.thisMapping) {
11523
+ return;
11524
+ }
11525
+ const filteringContextKey = template.thisMapping[keyOrPath];
11526
+ filteringContext[filteringContextKey] = (0, exports$1.deep_value)(that, keyOrPath);
11527
+ });
11528
+ }
11529
+ if (typeof template.argMapping === "function") {
11530
+ filteringContext = Object.assign(Object.assign({}, filteringContext), container_1.Container.errorless(() => template.argMapping.apply(that, args)));
11531
+ }
11532
+ else {
11533
+ Object.keys(template.argMapping || {}).forEach((keyOrPath) => {
11534
+ if (!keyOrPath || !template.argMapping) {
11535
+ return;
11536
+ }
11537
+ const filteringContextKey = template.argMapping[keyOrPath];
11538
+ const value = (0, exports$1.deep_value)(args, keyOrPath);
11539
+ if (typeof value === "string" ||
11540
+ typeof value === "number") {
11541
+ filteringContext[filteringContextKey] = value;
11542
+ }
11543
+ });
11544
+ }
11545
+ return filteringContext;
11546
+ };
11547
+ exports$1.extractFilteringContextFromArgs = extractFilteringContextFromArgs;
11548
+
11549
+ } (otelUtils));
11550
+
11551
+ var hasRequiredTraces;
11552
+
11553
+ function requireTraces () {
11554
+ if (hasRequiredTraces) return traces;
11555
+ hasRequiredTraces = 1;
11556
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
11557
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11558
+ return new (P || (P = Promise))(function (resolve, reject) {
11559
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11560
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11561
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11562
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11563
+ });
11564
+ };
11565
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
11566
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11567
+ };
11568
+ Object.defineProperty(traces, "__esModule", { value: true });
11569
+ traces.withSpan = void 0;
11570
+ const otelUtils_1 = otelUtils;
11571
+ const nullTracesManager_1 = requireNullTracesManager();
11572
+ const nullTracingState_1 = __importDefault(nullTracingState);
11573
+ /**
11574
+ * Null-safe singleton class that can be invoked even if you haven't initialized
11575
+ * the library (yet?), or if you don't have access to the current manager instance.
11576
+ */
11577
+ class Traces {
11578
+ static get instance() {
11579
+ var _a, _b;
11580
+ if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.traces) {
11581
+ return (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.traces;
11582
+ }
11583
+ if (!Traces._instance) {
11584
+ Traces._instance = new nullTracesManager_1.NullTracesManager(undefined, undefined, undefined);
11585
+ }
11586
+ return Traces._instance;
11587
+ }
11588
+ static set instance(value) {
11589
+ Traces._instance = value;
11590
+ }
11591
+ static get currentTracingState() {
11592
+ var _a;
11593
+ return ((_a = Traces.instance) === null || _a === void 0 ? void 0 : _a.currentTracingState) || new nullTracingState_1.default("unknown", null, true);
11594
+ }
11595
+ static set currentTracingState(value) {
11596
+ if (Traces.instance) {
11597
+ Traces.instance.currentTracingState = value;
11598
+ }
11599
+ }
11600
+ static removePropagationInfo(propagationInfoCarrier) {
11601
+ Traces.extractPropagationInfo(propagationInfoCarrier, true);
11602
+ return propagationInfoCarrier;
11603
+ }
11604
+ static extractPropagationInfo(propagationInfoCarrier, deleteProperty) {
11605
+ if (propagationInfoCarrier === null || propagationInfoCarrier === void 0 ? void 0 : propagationInfoCarrier.traceparent) {
11606
+ return propagationInfoCarrier;
11607
+ }
11608
+ const nestedPropagationInfo = propagationInfoCarrier === null || propagationInfoCarrier === void 0 ? void 0 : propagationInfoCarrier.__interopIOTracePropagationInfo;
11609
+ if (nestedPropagationInfo) {
11610
+ if (deleteProperty === true) {
11611
+ delete propagationInfoCarrier.__interopIOTracePropagationInfo;
11612
+ }
11613
+ return nestedPropagationInfo;
11614
+ }
11615
+ else {
11616
+ return null;
11617
+ }
11618
+ }
11619
+ withSequenceSpanEx(source, traceName, filteringContextOrCallback, optionsOrCallback, callback) {
11620
+ return __awaiter(this, void 0, void 0, function* () {
11621
+ return Traces.instance.withSequenceSpanEx(source, traceName, filteringContextOrCallback, optionsOrCallback, callback);
11622
+ });
11623
+ }
11624
+ withSequenceSpan(source, filteringContextOrCallback, optionsOrCallback, callback) {
11625
+ return __awaiter(this, void 0, void 0, function* () {
11626
+ return Traces.instance.withSequenceSpan(source, filteringContextOrCallback, optionsOrCallback, callback);
11627
+ });
11628
+ }
11629
+ static withSpan(source, filteringContextOrDecoratorOptionsOrCallback, propagationInfoOrCallback, optionsOrCallback, callback) {
11630
+ // decorator or wrapping a function
11631
+ if (!(filteringContextOrDecoratorOptionsOrCallback instanceof Function) &&
11632
+ (!filteringContextOrDecoratorOptionsOrCallback ||
11633
+ filteringContextOrDecoratorOptionsOrCallback.argMapping ||
11634
+ filteringContextOrDecoratorOptionsOrCallback.thisMapping ||
11635
+ filteringContextOrDecoratorOptionsOrCallback.defaults) &&
11636
+ !propagationInfoOrCallback &&
11637
+ !optionsOrCallback &&
11638
+ !callback) {
11639
+ return function (target, propertyKey, descriptor) {
11640
+ let originalFn;
11641
+ if (descriptor) {
11642
+ // decorator
11643
+ originalFn = descriptor.value;
11644
+ }
11645
+ else {
11646
+ // wrapping function directly
11647
+ originalFn = target;
11648
+ }
11649
+ let tracedFunction = function (...args) {
11650
+ return Traces.withSpan(source, filteringContextOrDecoratorOptionsOrCallback
11651
+ ? (0, otelUtils_1.extractFilteringContextFromArgs)(filteringContextOrDecoratorOptionsOrCallback, args, this)
11652
+ : {}, null, filteringContextOrDecoratorOptionsOrCallback, () => {
11653
+ return originalFn.apply(this, args);
11654
+ });
11655
+ };
11656
+ if (Traces.isAsyncFunction(originalFn)) {
11657
+ // fix for interception API using toString() to check for async functions
11658
+ const inner = tracedFunction;
11659
+ tracedFunction = function __insightsAsyncTracedFunction(...args) {
11660
+ return inner.apply(this, args);
11661
+ };
11662
+ Object.defineProperty(tracedFunction, Symbol.toStringTag, {
11663
+ value: "AsyncFunction",
11664
+ configurable: true,
11665
+ });
11666
+ }
11667
+ if (descriptor) {
11668
+ descriptor.value = tracedFunction;
11669
+ }
11670
+ else {
11671
+ return tracedFunction;
11672
+ }
11673
+ };
11674
+ }
11675
+ return Traces.instance.withSpan(source, filteringContextOrDecoratorOptionsOrCallback, propagationInfoOrCallback, optionsOrCallback, callback);
11676
+ }
11677
+ static isAsyncFunction(value) {
11678
+ return value && {}.toString.call(value) === '[object AsyncFunction]';
11679
+ }
11680
+ static withSpans(tracingMap, objectToTrace) {
11681
+ for (const tracingMapPropertyName in tracingMap) {
11682
+ if (typeof objectToTrace[tracingMapPropertyName] === "function") {
11683
+ const originalMethod = objectToTrace[tracingMapPropertyName];
11684
+ const tracingMapPropertyValue = tracingMap[tracingMapPropertyName];
11685
+ if (!tracingMapPropertyValue) {
11686
+ continue;
11687
+ }
11688
+ let wrapperMaker;
11689
+ if (typeof tracingMapPropertyValue === "string") {
11690
+ wrapperMaker = Traces.withSpan(tracingMapPropertyValue);
11691
+ }
11692
+ else {
11693
+ wrapperMaker = Traces.withSpan(tracingMapPropertyValue.source, tracingMapPropertyValue.decoratorOptions);
11694
+ }
11695
+ objectToTrace[tracingMapPropertyName] = wrapperMaker(originalMethod);
11696
+ }
11697
+ }
11698
+ return objectToTrace;
11699
+ }
11700
+ }
11701
+ traces.default = Traces;
11702
+ traces.withSpan = Traces.withSpan;
11703
+
11704
+ return traces;
11705
+ }
11706
+
11707
+ var hasRequiredNullTracesManager;
11708
+
11709
+ function requireNullTracesManager () {
11710
+ if (hasRequiredNullTracesManager) return nullTracesManager;
11711
+ hasRequiredNullTracesManager = 1;
11712
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
11713
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11714
+ return new (P || (P = Promise))(function (resolve, reject) {
11715
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11716
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11717
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11718
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11719
+ });
11720
+ };
11721
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
11722
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11723
+ };
11724
+ Object.defineProperty(nullTracesManager, "__esModule", { value: true });
11725
+ nullTracesManager.NullTracesManager = void 0;
11726
+ const nullTracingState_1 = __importDefault(nullTracingState);
11727
+ const traces_1 = __importDefault(requireTraces());
11728
+ const nullManager_1 = nullManager$1;
11729
+ const safe_stringify_1 = safeStringify$1;
11730
+ class NullTracesManager extends nullManager_1.NullManager {
11731
+ get settings() {
11732
+ return this._settings || {};
11733
+ }
11734
+ set settings(value) {
11735
+ this._settings = value;
11736
+ }
11737
+ constructor(_settings, otelSettings, logger) {
11738
+ if ((otelSettings === null || otelSettings === void 0 ? void 0 : otelSettings.logSettingsOnStartup) !== false) {
11739
+ logger === null || logger === void 0 ? void 0 : logger.info(`Starting NullTracesManager with settings ${(0, safe_stringify_1.safeStringify)(_settings)}`);
11740
+ }
11741
+ super();
11742
+ this._settings = _settings;
11743
+ this.logger = logger;
11744
+ }
11745
+ withSequenceSpan(source, filteringContextOrCallback, optionsOrCallback, callback) {
11746
+ return __awaiter(this, void 0, void 0, function* () {
11747
+ return this.withSequenceSpanEx(source, source + ".start", filteringContextOrCallback, optionsOrCallback, callback);
11748
+ });
11749
+ }
11750
+ withSequenceSpanEx(source, traceName, filteringContextOrCallback, optionsOrCallback, callback) {
11751
+ return __awaiter(this, void 0, void 0, function* () {
11752
+ return this.withSpan(source, filteringContextOrCallback, null, optionsOrCallback, callback);
11753
+ });
11754
+ }
11755
+ get currentTracingState() {
11756
+ return new nullTracingState_1.default("nullTracingState", null, true);
11757
+ }
11758
+ set currentTracingState(ts) {
11759
+ }
11760
+ waitForFinalExport(timeoutMs) {
11761
+ return Promise.resolve();
11762
+ }
11763
+ withSpan(source, filteringContextOrCallback, propagationInfoOrCallback, optionsOrCallback, callback) {
11764
+ const actualCallback =
11765
+ // eslint-disable-next-line no-nested-ternary
11766
+ typeof filteringContextOrCallback === "function"
11767
+ ? filteringContextOrCallback
11768
+ : typeof propagationInfoOrCallback === "function"
11769
+ ? propagationInfoOrCallback
11770
+ : typeof optionsOrCallback === "function"
11771
+ ? optionsOrCallback
11772
+ : callback;
11773
+ if (!actualCallback) {
11774
+ throw new Error("callback must be provided");
11775
+ }
11776
+ if (typeof actualCallback !== "function") {
11777
+ throw new Error("Callback must be a function, received " + typeof actualCallback);
11778
+ }
11779
+ // ! DO NOT log in this method, danger of infinite loop with
11780
+ // interop log publishing
11781
+ //
11782
+ // this.logger?.debug("nullTracesManager.withSpan: " + source);
11783
+ // ! a null manager means no propagation
11784
+ //
11785
+ // let extractedPI: PropagationInfo | null = null;
11786
+ // if (propagationInfoOrCallback) {
11787
+ // let propagationInfoCarrier = {};
11788
+ // if (!isFunctionType(propagationInfoOrCallback)) {
11789
+ // propagationInfoCarrier = { ...propagationInfoOrCallback };
11790
+ // }
11791
+ // extractedPI = Traces.extractPropagationInfo(propagationInfoCarrier);
11792
+ // } else {
11793
+ // extractedPI = Traces.currentTracingState?.getPropagationInfo() || null;
11794
+ // }
11795
+ // const nts = new NullTracingState(source, extractedPI);
11796
+ const nts = new nullTracingState_1.default(source, null, true);
11797
+ traces_1.default.currentTracingState = nts;
11798
+ try {
11799
+ return actualCallback(nts);
11800
+ }
11801
+ finally {
11802
+ traces_1.default.currentTracingState = null;
11803
+ }
11804
+ }
11805
+ setFilterConfig(filters) {
11806
+ }
11807
+ get startupTraceFinished() {
11808
+ return (() => { });
11809
+ }
11810
+ get userJourneyMarker() {
11811
+ return (() => { });
11812
+ }
11813
+ setUserJourneyMarker(userJourneyMarker) {
11814
+ }
11815
+ get clickstreamMarker() {
11816
+ return (() => { });
11817
+ }
11818
+ }
11819
+ nullTracesManager.NullTracesManager = NullTracesManager;
11820
+
11821
+ return nullTracesManager;
11822
+ }
11823
+
11824
+ var hasRequiredBuilder$2;
11825
+
11826
+ function requireBuilder$2 () {
11827
+ if (hasRequiredBuilder$2) return builder$1;
11828
+ hasRequiredBuilder$2 = 1;
11829
+ Object.defineProperty(builder$1, "__esModule", { value: true });
11830
+ builder$1.TracesManagerBuilder = void 0;
11831
+ const nullTracesManager_1 = requireNullTracesManager();
11832
+ const __1 = requireDist();
11833
+ class TracesManagerBuilder {
11834
+ constructor() {
11835
+ this.traceLogger = null;
11836
+ }
11837
+ withLogger(logger) {
11838
+ this.logger = logger;
11839
+ return this;
11840
+ }
11841
+ withTraceLogger(traceLogger) {
11842
+ this.traceLogger = traceLogger;
11843
+ return this;
11844
+ }
11845
+ withSettings(settings) {
11846
+ this.settings = settings;
11847
+ return this;
11848
+ }
11849
+ withMetrics(metrics) {
11850
+ this.metrics = metrics;
11851
+ return this;
11852
+ }
11853
+ withTracerProvider(tracerProvider) {
11854
+ this.tracerProvider = tracerProvider;
11855
+ return this;
11856
+ }
11857
+ withContextManager(contextManager) {
11858
+ var _a, _b;
11859
+ this.settings = (_a = this.settings) !== null && _a !== void 0 ? _a : { enabled: false };
11860
+ this.settings.traces = (_b = this.settings.traces) !== null && _b !== void 0 ? _b : { enabled: false };
11861
+ this.settings.traces.contextManager = () => contextManager;
11862
+ this.settings.traces.useOTELContextManager = true;
11863
+ return this;
11864
+ }
11865
+ withPropagationInfoStorage(store, read) {
11866
+ this.store = store;
11867
+ this.read = read;
11868
+ return this;
11869
+ }
11870
+ build() {
11871
+ var _a, _b, _c, _d;
11872
+ if (((_a = globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.traces) &&
11873
+ ((_b = this.settings) === null || _b === void 0 ? void 0 : _b.definitiveInstance) !== true) {
11874
+ return globalThis.ioInsightsInternals.traces;
11875
+ }
11876
+ const toReturn = this.buildCore();
11877
+ globalThis.ioInsightsInternals = (_c = globalThis.ioInsightsInternals) !== null && _c !== void 0 ? _c : {};
11878
+ if (!globalThis.ioInsightsInternals.traces ||
11879
+ ((_d = this.settings) === null || _d === void 0 ? void 0 : _d.definitiveInstance)) {
11880
+ globalThis.ioInsightsInternals.traces = toReturn;
11881
+ }
11882
+ return toReturn;
11883
+ }
11884
+ buildCore() {
11885
+ var _a, _b, _c, _d, _e, _f, _g, _h;
11886
+ this.settings.traces = (_a = this.settings.traces) !== null && _a !== void 0 ? _a : { enabled: false };
11887
+ this.settings.traces.otlpExporterConfig = (_b = this.settings.traces.exporterSettings) !== null && _b !== void 0 ? _b : this.settings.traces.otlpExporterConfig;
11888
+ this.settings.traces.exporterSettings = (_c = this.settings.traces.exporterSettings) !== null && _c !== void 0 ? _c : this.settings.traces.otlpExporterConfig;
11889
+ let tracePlugin;
11890
+ if (((_d = this.settings) === null || _d === void 0 ? void 0 : _d.enabled) !== true ||
11891
+ ((_f = (_e = this.settings) === null || _e === void 0 ? void 0 : _e.traces) === null || _f === void 0 ? void 0 : _f.enabled) !== true ||
11892
+ !(tracePlugin = (0, __1.loadInsightsPlugin)("traces", this.logger))) {
11893
+ return new nullTracesManager_1.NullTracesManager((_g = this.settings) === null || _g === void 0 ? void 0 : _g.traces, this.settings, this.logger);
11894
+ }
11895
+ const manager = tracePlugin.newTracesManager(this.logger, this.settings, (_h = this.traceLogger) !== null && _h !== void 0 ? _h : this.logger, this.metrics, this.store, this.read);
11896
+ return manager;
11897
+ }
11898
+ }
11899
+ builder$1.TracesManagerBuilder = TracesManagerBuilder;
11900
+
11901
+ return builder$1;
11902
+ }
11903
+
11904
+ var _null = {};
11905
+
11906
+ Object.defineProperty(_null, "__esModule", { value: true });
11907
+ _null.NullLogger = void 0;
11908
+ class NullLogger {
11909
+ get level() {
11910
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
11911
+ }
11912
+ error() {
11913
+ // do nothing
11914
+ }
11915
+ warn() {
11916
+ // do nothing
11917
+ }
11918
+ info() {
11919
+ // do nothing
11920
+ }
11921
+ debug() {
11922
+ // do nothing
11923
+ }
11924
+ verbose() {
11925
+ // do nothing
11926
+ }
11927
+ }
11928
+ _null.NullLogger = NullLogger;
11929
+
11930
+ var nullManager = {};
11931
+
11932
+ Object.defineProperty(nullManager, "__esModule", { value: true });
11933
+ nullManager.NullLogsManager = void 0;
11934
+ const nullManager_1$1 = nullManager$1;
11935
+ const safe_stringify_1 = safeStringify$1;
11936
+ class NullLogsManager extends nullManager_1$1.NullManager {
11937
+ constructor(settings, otelSettings, logger) {
11938
+ if ((otelSettings === null || otelSettings === void 0 ? void 0 : otelSettings.logSettingsOnStartup) !== false) {
11939
+ logger === null || logger === void 0 ? void 0 : logger.info(`Starting NullLogsManager with settings ${(0, safe_stringify_1.safeStringify)(settings)}`);
11940
+ }
11941
+ super();
11942
+ }
11943
+ emit(logRecord) {
11944
+ return null;
11945
+ }
11946
+ }
11947
+ nullManager.NullLogsManager = NullLogsManager;
11948
+
11949
+ var constants = {};
11950
+
11951
+ Object.defineProperty(constants, "__esModule", { value: true });
11952
+ constants.Defaults = void 0;
11953
+ constants.Defaults = {
11954
+ DEFAULT_USER: "unknown-user",
11955
+ DEFAULT_SERVICE_NAME: "unknown-service-name",
11956
+ DEFAULT_SERVICE_ID: "unknown-service-id",
11957
+ DEFAULT_SERVICE_VERSION: "unknown-service-version",
11958
+ DEFAULT_PLATFORM_VERSION: "unknown-platform-version",
11959
+ };
11960
+
11961
+ var logWrapper = {};
11962
+
11963
+ Object.defineProperty(logWrapper, "__esModule", { value: true });
11964
+ logWrapper.LogWrapper = void 0;
11965
+ // wraps an OTEL library logger into an OTEL library logger
11966
+ // allows filtering messages etc
11967
+ class LogWrapper {
11968
+ constructor(logger, dropLog) {
11969
+ this.logger = logger;
11970
+ this.dropLog = dropLog;
11971
+ }
11972
+ get level() {
11973
+ var _a;
11974
+ return (_a = this.logger.level) !== null && _a !== void 0 ? _a : 0 /* IOInsights.LoggerLogLevel.NONE */;
11975
+ }
11976
+ error(message, ...args) {
11977
+ var _a;
11978
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 50 /* IOInsights.LoggerLogLevel.WARN */, message)) {
11979
+ return;
11980
+ }
11981
+ // we log errors as warn because some of our clients stopped the platform if an log error is observed (they consider it as broken state)
11982
+ // we can do that since otel impl is not considered critical
11983
+ this.logger.warn(message, ...args);
11984
+ }
11985
+ warn(message, ...args) {
11986
+ var _a;
11987
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 50 /* IOInsights.LoggerLogLevel.WARN */, message)) {
11988
+ return;
11989
+ }
11990
+ this.logger.warn(message, ...args);
11991
+ }
11992
+ info(message, ...args) {
11993
+ var _a;
11994
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 60 /* IOInsights.LoggerLogLevel.INFO */, message)) {
11995
+ return;
11996
+ }
11997
+ this.logger.info(message, ...args);
11998
+ }
11999
+ debug(message, ...args) {
12000
+ var _a;
12001
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 70 /* IOInsights.LoggerLogLevel.DEBUG */, message)) {
12002
+ return;
12003
+ }
12004
+ this.logger.debug(message, ...args);
12005
+ }
12006
+ verbose(message, ...args) {
12007
+ var _a;
12008
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 80 /* IOInsights.LoggerLogLevel.VERBOSE */, message)) {
12009
+ return;
12010
+ }
12011
+ this.logger.verbose(message, ...args);
12012
+ }
12013
+ }
12014
+ logWrapper.LogWrapper = LogWrapper;
12015
+
12016
+ var builder = {};
12017
+
12018
+ var hasRequiredBuilder$1;
12019
+
12020
+ function requireBuilder$1 () {
12021
+ if (hasRequiredBuilder$1) return builder;
12022
+ hasRequiredBuilder$1 = 1;
12023
+ Object.defineProperty(builder, "__esModule", { value: true });
12024
+ builder.LogsManagerBuilder = void 0;
12025
+ const __1 = requireDist();
12026
+ const nullManager_1 = nullManager;
12027
+ class LogsManagerBuilder {
12028
+ withLogger(logger) {
12029
+ this.logger = logger;
12030
+ return this;
12031
+ }
12032
+ withSettings(settings) {
12033
+ this.settings = settings;
12034
+ return this;
12035
+ }
12036
+ build() {
12037
+ var _a, _b, _c, _d;
12038
+ if (((_a = globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.logs) &&
12039
+ ((_b = this.settings) === null || _b === void 0 ? void 0 : _b.definitiveInstance) !== true) {
12040
+ return globalThis.ioInsightsInternals.logs;
12041
+ }
12042
+ const toReturn = this.buildCore();
12043
+ globalThis.ioInsightsInternals = (_c = globalThis.ioInsightsInternals) !== null && _c !== void 0 ? _c : {};
12044
+ if (!globalThis.ioInsightsInternals.logs ||
12045
+ ((_d = this.settings) === null || _d === void 0 ? void 0 : _d.definitiveInstance)) {
12046
+ globalThis.ioInsightsInternals.logs = toReturn;
12047
+ }
12048
+ return toReturn;
12049
+ }
12050
+ buildCore() {
12051
+ var _a, _b, _c, _d;
12052
+ let logsPlugin;
12053
+ if (((_a = this.settings) === null || _a === void 0 ? void 0 : _a.enabled) !== true ||
12054
+ ((_c = (_b = this.settings) === null || _b === void 0 ? void 0 : _b.logs) === null || _c === void 0 ? void 0 : _c.enabled) !== true ||
12055
+ !(logsPlugin = (0, __1.loadInsightsPlugin)("logs", this.logger))) {
12056
+ return new nullManager_1.NullLogsManager((_d = this.settings) === null || _d === void 0 ? void 0 : _d.logs, this.settings, this.logger);
12057
+ }
12058
+ const logs = logsPlugin.newLogsManager(this.logger, this.settings.logs, this.settings);
12059
+ return logs;
12060
+ }
12061
+ }
12062
+ builder.LogsManagerBuilder = LogsManagerBuilder;
12063
+
12064
+ return builder;
12065
+ }
12066
+
12067
+ var hasRequiredBuilder;
12068
+
12069
+ function requireBuilder () {
12070
+ if (hasRequiredBuilder) return builder$3;
12071
+ hasRequiredBuilder = 1;
12072
+ Object.defineProperty(builder$3, "__esModule", { value: true });
12073
+ builder$3.Builder = void 0;
12074
+ const builder_1 = requireBuilder$3();
12075
+ const builder_2 = requireBuilder$2();
12076
+ const null_1 = _null;
12077
+ const container_1 = container;
12078
+ const nullMetricsManager_1 = nullMetricsManager;
12079
+ const nullTracesManager_1 = requireNullTracesManager();
12080
+ const nullManager_1 = nullManager;
12081
+ const constants_1 = constants;
12082
+ const logWrapper_1 = logWrapper;
12083
+ const _1 = requireDist();
12084
+ const safe_stringify_1 = safeStringify$1;
12085
+ const builder_3 = requireBuilder$1();
12086
+ class Builder {
12087
+ constructor() {
12088
+ this.logger = new null_1.NullLogger();
12089
+ }
12090
+ // these methods must be invoked...
12091
+ withLogger(loggerArg) {
12092
+ var _a;
12093
+ if (loggerArg) {
12094
+ this.logger = new logWrapper_1.LogWrapper(loggerArg, (_, msg) => {
12095
+ var _a, _b, _c;
12096
+ if (((_a = this.settings) === null || _a === void 0 ? void 0 : _a.suppressDoubleInitializationWarnings) &&
12097
+ ~(msg + "").indexOf("@opentelemetry/api: Attempted duplicate registration of API")) {
12098
+ return true;
12099
+ }
12100
+ if (((_b = this.settings) === null || _b === void 0 ? void 0 : _b.suppressDoubleInitializationWarnings) &&
12101
+ ~(msg + "").indexOf("Current logger will overwrite one already registered")) {
12102
+ return true;
12103
+ }
12104
+ if (((_c = this.settings) === null || _c === void 0 ? void 0 : _c.suppressDoubleInitializationWarnings) &&
12105
+ ~(msg + "").indexOf("Current logger will be overwritten")) {
12106
+ return true;
12107
+ }
12108
+ return false;
12109
+ });
12110
+ }
12111
+ const basePlugin = (0, _1.loadInsightsPlugin)("base", this.logger);
12112
+ if (basePlugin) {
12113
+ if (this.logger.level) {
12114
+ const level = (_a = this.logger.level) === null || _a === void 0 ? void 0 : _a.valueOf();
12115
+ basePlugin.diag.setLogger(this.logger, level);
12116
+ }
12117
+ else {
12118
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
12119
+ basePlugin.diag.setLogger(this.logger, 70 /* IOInsights.LoggerLogLevel.DEBUG */);
12120
+ }
12121
+ }
12122
+ return this;
12123
+ }
12124
+ withSettings(settings) {
12125
+ this.settings = settings;
12126
+ container_1.Container.settings = settings;
12127
+ return this;
12128
+ }
12129
+ // ...before these methods
12130
+ withMetrics() {
12131
+ this.metricsBuilder = new builder_1.MetricsManagerBuilder();
12132
+ this.metricsBuilder.withLogger(this.logger);
12133
+ this.metricsBuilder.withSettings(Object.assign({ enabled: false }, this.settings));
12134
+ return this.metricsBuilder;
12135
+ }
12136
+ withTraces() {
12137
+ this.tracesBuilder = new builder_2.TracesManagerBuilder();
12138
+ this.tracesBuilder.withLogger(this.logger);
12139
+ this.tracesBuilder.withSettings(Object.assign({ enabled: false }, this.settings));
12140
+ return this.tracesBuilder;
12141
+ }
12142
+ withLogs() {
12143
+ this.logsBuilder = new builder_3.LogsManagerBuilder();
12144
+ this.logsBuilder.withLogger(this.logger);
12145
+ this.logsBuilder.withSettings(Object.assign({ enabled: false }, this.settings));
12146
+ return this.logsBuilder;
12147
+ }
12148
+ build() {
12149
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
12150
+ this.settings = (_a = this.settings) !== null && _a !== void 0 ? _a : { enabled: false };
12151
+ const nonPartialSettings = Object.assign({ enabled: false }, this.settings);
12152
+ if (((_b = this.settings) === null || _b === void 0 ? void 0 : _b.logSettingsOnStartup) !== false) {
12153
+ this.logger.info(`Starting interop.io OTEL with settings ${(0, safe_stringify_1.safeStringify)(this.settings)}`);
12154
+ }
12155
+ if (((_c = this.settings) === null || _c === void 0 ? void 0 : _c.enabled) == false ||
12156
+ !((0, _1.loadInsightsPlugin)("base", this.logger))) {
12157
+ return new container_1.Container(nonPartialSettings, new nullTracesManager_1.NullTracesManager(this.settings.traces, nonPartialSettings, this.logger), new nullMetricsManager_1.NullMetricsManager(this.settings.metrics, nonPartialSettings, this.logger), new nullManager_1.NullLogsManager(this.settings.logs, nonPartialSettings, this.logger), this.logger);
12158
+ }
12159
+ if (((_e = (_d = this.settings) === null || _d === void 0 ? void 0 : _d.metrics) === null || _e === void 0 ? void 0 : _e.enabled) &&
12160
+ ((_f = this.settings) === null || _f === void 0 ? void 0 : _f.metrics.platformMetricsEnabled) &&
12161
+ !this.metricsBuilder) {
12162
+ throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");
12163
+ }
12164
+ const providedAdditionalResourceAttributes = this.settings.additionalResourceAttributes;
12165
+ this.settings.additionalResourceAttributes = () => {
12166
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
12167
+ const evaluatedAdditionalResourceAttributes = (_a = container_1.Container.errorlessDefined(providedAdditionalResourceAttributes, {})) !== null && _a !== void 0 ? _a : {};
12168
+ return Object.assign(Object.assign({}, evaluatedAdditionalResourceAttributes), { user: (_e = (_d = (_b = evaluatedAdditionalResourceAttributes.userId) !== null && _b !== void 0 ? _b : (_c = this.settings) === null || _c === void 0 ? void 0 : _c.userId) !== null && _d !== void 0 ? _d : evaluatedAdditionalResourceAttributes["user.id"]) !== null && _e !== void 0 ? _e : constants_1.Defaults.DEFAULT_USER, "user.id": (_j = (_h = (_f = evaluatedAdditionalResourceAttributes.userId) !== null && _f !== void 0 ? _f : (_g = this.settings) === null || _g === void 0 ? void 0 : _g.userId) !== null && _h !== void 0 ? _h : evaluatedAdditionalResourceAttributes["user.id"]) !== null && _j !== void 0 ? _j : constants_1.Defaults.DEFAULT_USER, "service.name": (_o = (_m = (_k = evaluatedAdditionalResourceAttributes.serviceName) !== null && _k !== void 0 ? _k : (_l = this.settings) === null || _l === void 0 ? void 0 : _l.serviceName) !== null && _m !== void 0 ? _m : evaluatedAdditionalResourceAttributes["service.name"]) !== null && _o !== void 0 ? _o : constants_1.Defaults.DEFAULT_SERVICE_NAME, "service.instance.id": (_s = (_r = (_p = evaluatedAdditionalResourceAttributes.serviceId) !== null && _p !== void 0 ? _p : (_q = this.settings) === null || _q === void 0 ? void 0 : _q.serviceId) !== null && _r !== void 0 ? _r : evaluatedAdditionalResourceAttributes["service.instance.id"]) !== null && _s !== void 0 ? _s : constants_1.Defaults.DEFAULT_SERVICE_ID, "service.version": (_w = (_v = (_t = evaluatedAdditionalResourceAttributes.serviceVersion) !== null && _t !== void 0 ? _t : (_u = this.settings) === null || _u === void 0 ? void 0 : _u.serviceVersion) !== null && _v !== void 0 ? _v : evaluatedAdditionalResourceAttributes["service.version"]) !== null && _w !== void 0 ? _w : constants_1.Defaults.DEFAULT_SERVICE_VERSION, platformVersion: (_z = (_x = evaluatedAdditionalResourceAttributes.platformVersion) !== null && _x !== void 0 ? _x : (_y = this.settings) === null || _y === void 0 ? void 0 : _y.platformVersion) !== null && _z !== void 0 ? _z : constants_1.Defaults.DEFAULT_PLATFORM_VERSION });
12169
+ };
12170
+ Builder.maybeAddResourceAttributesToAttributes(this.settings);
12171
+ Builder.maybeAddResourceAttributesToAttributes(this.settings.logs);
12172
+ Builder.maybeAddResourceAttributesToAttributes(this.settings.metrics);
12173
+ Builder.maybeAddResourceAttributesToAttributes(this.settings.traces);
12174
+ Builder.propagateAttributeDown("useSSOAuth", this.settings, this.settings.logs);
12175
+ Builder.propagateAttributeDown("useSSOAuth", this.settings, this.settings.metrics);
12176
+ Builder.propagateAttributeDown("useSSOAuth", this.settings, this.settings.traces);
12177
+ Builder.propagateAttributeDown("useSSOAuthRawToken", this.settings, this.settings.logs);
12178
+ Builder.propagateAttributeDown("useSSOAuthRawToken", this.settings, this.settings.metrics);
12179
+ Builder.propagateAttributeDown("useSSOAuthRawToken", this.settings, this.settings.traces);
12180
+ Builder.propagateAttributesDown("headers", this.settings, this.settings.logs);
12181
+ Builder.propagateAttributesDown("headers", this.settings, this.settings.metrics);
12182
+ Builder.propagateAttributesDown("headers", this.settings, this.settings.traces);
12183
+ Builder.propagateAttributesDown("additionalAttributes", this.settings, this.settings.logs);
12184
+ Builder.propagateAttributesDown("additionalResourceAttributes", this.settings, this.settings.logs);
12185
+ Builder.propagateAttributesDown("additionalAttributes", this.settings, this.settings.metrics);
12186
+ Builder.propagateAttributesDown("additionalResourceAttributes", this.settings, this.settings.metrics);
12187
+ Builder.propagateAttributesDown("additionalAttributes", this.settings, this.settings.traces);
12188
+ Builder.propagateAttributesDown("additionalResourceAttributes", this.settings, this.settings.traces);
12189
+ const metricsBuilder = (_g = this.metricsBuilder) !== null && _g !== void 0 ? _g : this.withMetrics();
12190
+ const metrics = metricsBuilder
12191
+ .withLogger(this.logger)
12192
+ .withSettings(this.settings)
12193
+ .build();
12194
+ const tracesBuilder = (_h = this.tracesBuilder) !== null && _h !== void 0 ? _h : this.withTraces();
12195
+ const traces = tracesBuilder
12196
+ .withLogger(this.logger)
12197
+ .withSettings(this.settings)
12198
+ .withMetrics(metrics)
12199
+ .build();
12200
+ _1.Traces.instance = traces;
12201
+ const logsBuilder = (_j = this.logsBuilder) !== null && _j !== void 0 ? _j : this.withLogs();
12202
+ const logs = logsBuilder
12203
+ .withLogger(this.logger)
12204
+ .withSettings(this.settings)
12205
+ .build();
12206
+ _1.Logs.instance = logs;
12207
+ return new container_1.Container(nonPartialSettings, traces, metrics, logs, this.logger);
12208
+ }
12209
+ static propagateAttributeDown(k, otelSettings, settings) {
12210
+ var _a;
12211
+ if (!settings) {
12212
+ return;
12213
+ }
12214
+ settings[k] = (_a = settings[k]) !== null && _a !== void 0 ? _a : otelSettings[k];
12215
+ }
12216
+ static propagateAttributesDown(k, otelSettings, settings) {
12217
+ var _a, _b;
12218
+ if (!settings) {
12219
+ return;
12220
+ }
12221
+ const providedOtel = (_a = otelSettings[k]) !== null && _a !== void 0 ? _a : {};
12222
+ const provided = (_b = settings[k]) !== null && _b !== void 0 ? _b : {};
12223
+ settings[k] = () => (Object.assign(Object.assign({}, container_1.Container.errorless(providedOtel)), container_1.Container.errorless(provided)));
12224
+ }
12225
+ static maybeAddResourceAttributesToAttributes(settings) {
12226
+ if (settings === null || settings === void 0 ? void 0 : settings.addResourceAttributesToAttributes) {
12227
+ const providedAdditionalResourceAttributes = settings.additionalResourceAttributes;
12228
+ const providedAdditionalAttributes = settings.additionalAttributes;
12229
+ settings.additionalAttributes = () => (Object.assign(Object.assign({}, container_1.Container.errorless(providedAdditionalResourceAttributes)), container_1.Container.errorless(providedAdditionalAttributes)));
12230
+ }
12231
+ }
12232
+ }
12233
+ builder$3.Builder = Builder;
12234
+
12235
+ return builder$3;
12236
+ }
12237
+
12238
+ var log4jsWrapper = {};
12239
+
12240
+ Object.defineProperty(log4jsWrapper, "__esModule", { value: true });
12241
+ log4jsWrapper.Log4jsWrapper = void 0;
12242
+ // wraps a log4js wrapper into an OTEL library logger
12243
+ class Log4jsWrapper {
12244
+ constructor(logger) {
12245
+ this.logger = logger;
12246
+ }
12247
+ get level() {
12248
+ return this.convert("level" in this.logger ? this.logger.level : this.logger.publishLevel());
12249
+ }
12250
+ error(message, ...args) {
12251
+ // we log errors as warn because some of our clients stopped the platform if an log error is observed (they consider it as broken state)
12252
+ // we can do that since otel impl is not considered critical
12253
+ this.logger.warn(message, ...args);
12254
+ }
12255
+ warn(message, ...args) {
12256
+ this.logger.warn(message, ...args);
12257
+ }
12258
+ info(message, ...args) {
12259
+ this.logger.info(message, ...args);
12260
+ }
12261
+ debug(message, ...args) {
12262
+ this.logger.debug(message, ...args);
12263
+ }
12264
+ verbose(message, ...args) {
12265
+ this.logger.trace(message, ...args);
12266
+ }
12267
+ convert(level) {
12268
+ if (level === undefined) {
12269
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
12270
+ }
12271
+ const currentLevel = typeof level !== "string" ? level.levelStr.toLowerCase() : level.toLowerCase();
12272
+ switch (currentLevel) {
12273
+ case "off": {
12274
+ return 0 /* IOInsights.LoggerLogLevel.NONE */;
12275
+ }
12276
+ case "error": {
12277
+ return 30 /* IOInsights.LoggerLogLevel.ERROR */;
12278
+ }
12279
+ case "warn": {
12280
+ return 50 /* IOInsights.LoggerLogLevel.WARN */;
12281
+ }
12282
+ case "info": {
12283
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
12284
+ }
12285
+ case "debug": {
12286
+ return 70 /* IOInsights.LoggerLogLevel.DEBUG */;
12287
+ }
12288
+ case "trace": {
12289
+ return 80 /* IOInsights.LoggerLogLevel.VERBOSE */;
12290
+ }
12291
+ default: {
12292
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
12293
+ }
12294
+ }
12295
+ }
12296
+ }
12297
+ log4jsWrapper.Log4jsWrapper = Log4jsWrapper;
12298
+
12299
+ var metricsDependencyBuilder = {};
12300
+
12301
+ var nullPerfProvider = {};
12302
+
12303
+ Object.defineProperty(nullPerfProvider, "__esModule", { value: true });
12304
+ nullPerfProvider.NullPerformanceProvider = void 0;
12305
+ class NullPerformanceProvider {
12306
+ getAppsCPU() {
12307
+ return Promise.resolve(undefined);
12308
+ }
12309
+ getAppsMemory() {
12310
+ return Promise.resolve(undefined);
12311
+ }
12312
+ getSystemCPU() {
12313
+ return Promise.resolve(undefined);
12314
+ }
12315
+ getSystemMemory() {
12316
+ return Promise.resolve(undefined);
12317
+ }
12318
+ }
12319
+ nullPerfProvider.NullPerformanceProvider = NullPerformanceProvider;
12320
+
12321
+ Object.defineProperty(metricsDependencyBuilder, "__esModule", { value: true });
12322
+ metricsDependencyBuilder.MetricsDependencyBuilder = void 0;
12323
+ const nullPerfProvider_1 = nullPerfProvider;
12324
+ class MetricsDependencyBuilder {
12325
+ constructor() {
12326
+ this.performanceProvider = new nullPerfProvider_1.NullPerformanceProvider();
12327
+ this.instanceFocusedHandler = () => () => { };
12328
+ this.instanceStartedHandler = () => () => { };
12329
+ this.instanceStoppedHandler = () => () => { };
12330
+ this.instanceReadyHandler = () => () => { };
12331
+ this.instanceErrorHandler = () => () => { };
12332
+ this.instanceCrashHandler = () => () => { };
12333
+ this.layoutRestoredHandler = () => () => { };
12334
+ this.platformStartedHandler = () => () => { };
12335
+ this.platformErrorHandler = () => () => { };
12336
+ this.workspaceLoadedHandler = () => () => { };
12337
+ this.workspaceRestoredHandler = () => () => { };
12338
+ this.workspaceSavedHandler = () => () => { };
12339
+ this.workspaceStoppedHandler = () => () => { };
12340
+ this.workspaceSelectedHandler = () => () => { };
12341
+ this.workspaceStartedHandler = () => () => { };
12342
+ this.workspaceFrameCreatedHandler = () => () => { };
12343
+ this.workspaceFrameInitHandler = () => () => { };
12344
+ this.workspaceFramePageLoadHandler = () => () => { };
12345
+ this.workspaceFrameWorkspaceRenderHandler = () => () => { };
12346
+ this.workspaceComponentCreatedHandler = () => () => { };
12347
+ this.workspaceAppsStartedHandler = () => () => { };
12348
+ this.workspaceStartupHandler = () => () => { };
12349
+ }
12350
+ build() {
12351
+ const container = {
12352
+ performanceProvider: this.performanceProvider,
12353
+ instanceStartedHandler: this.instanceStartedHandler,
12354
+ instanceStoppedHandler: this.instanceStoppedHandler,
12355
+ instanceReadyHandler: this.instanceReadyHandler,
12356
+ instanceFocusedHandler: this.instanceFocusedHandler,
12357
+ instanceErrorHandler: this.instanceErrorHandler,
12358
+ instanceCrashHandler: this.instanceCrashHandler,
12359
+ layoutRestoredHandler: this.layoutRestoredHandler,
12360
+ platformStartedHandler: this.platformStartedHandler,
12361
+ platformErrorHandler: this.platformErrorHandler,
12362
+ workspaceLoadedHandler: this.workspaceLoadedHandler,
12363
+ workspaceSavedHandler: this.workspaceSavedHandler,
12364
+ workspaceStoppedHandler: this.workspaceStoppedHandler,
12365
+ workspaceSelectedHandler: this.workspaceSelectedHandler,
12366
+ workspaceRestoredHandler: this.workspaceRestoredHandler,
12367
+ workspaceStartedHandler: this.workspaceStartedHandler,
12368
+ workspaceStartupHandler: this.workspaceStartupHandler,
12369
+ workspaceFrameCreatedHandler: this.workspaceFrameCreatedHandler,
12370
+ workspaceFrameInitHandler: this.workspaceFrameInitHandler,
12371
+ workspaceFramePageLoadHandler: this.workspaceFramePageLoadHandler,
12372
+ workspaceFrameWorkspaceRenderHandler: this.workspaceFrameWorkspaceRenderHandler,
12373
+ workspaceComponentCreatedHandler: this.workspaceComponentCreatedHandler,
12374
+ workspaceAppsStartedHandler: this.workspaceAppsStartedHandler,
12375
+ };
12376
+ return container;
12377
+ }
12378
+ withInstanceStartedHandler(instanceStartedHandler) {
12379
+ this.instanceStartedHandler = instanceStartedHandler;
12380
+ return this;
12381
+ }
12382
+ withInstanceStoppedHandler(instanceStoppedHandler) {
12383
+ this.instanceStoppedHandler = instanceStoppedHandler;
12384
+ return this;
12385
+ }
12386
+ withInstanceReadyHandler(instanceReadyHandler) {
12387
+ this.instanceReadyHandler = instanceReadyHandler;
12388
+ return this;
12389
+ }
12390
+ withInstanceFocusedHandler(instanceFocusedHandler) {
12391
+ this.instanceFocusedHandler = instanceFocusedHandler;
12392
+ return this;
12393
+ }
12394
+ withInstanceErrorHandler(instanceErrorHandler) {
12395
+ this.instanceErrorHandler = instanceErrorHandler;
12396
+ return this;
12397
+ }
12398
+ withInstanceCrashHandler(instanceCrashHandler) {
12399
+ this.instanceCrashHandler = instanceCrashHandler;
12400
+ return this;
12401
+ }
12402
+ withLayoutRestoredHandler(layoutRestoredHandler) {
12403
+ this.layoutRestoredHandler = layoutRestoredHandler;
12404
+ return this;
12405
+ }
12406
+ withWorkspaceLoadedHandler(workspaceLoadedHandler) {
12407
+ this.workspaceLoadedHandler = workspaceLoadedHandler;
12408
+ return this;
12409
+ }
12410
+ withWorkspaceSavedHandler(workspaceSavedHandler) {
12411
+ this.workspaceSavedHandler = workspaceSavedHandler;
12412
+ return this;
12413
+ }
12414
+ withWorkspaceStartedHandler(workspaceStartedHandler) {
12415
+ this.workspaceRestoredHandler = () => () => { };
12416
+ this.workspaceStartedHandler = workspaceStartedHandler;
12417
+ return this;
12418
+ }
12419
+ withWorkspaceStoppedHandler(workspaceStoppedHandler) {
12420
+ this.workspaceStoppedHandler = workspaceStoppedHandler;
12421
+ return this;
12422
+ }
12423
+ withWorkspaceSelectedHandler(workspaceSelectedHandler) {
12424
+ this.workspaceSelectedHandler = workspaceSelectedHandler;
12425
+ return this;
12426
+ }
12427
+ withPlatformStartedHandler(platformStartedHandler) {
12428
+ this.platformStartedHandler = platformStartedHandler;
12429
+ return this;
12430
+ }
12431
+ withPlatformErrorHandler(platformErrorHandler) {
12432
+ this.platformErrorHandler = platformErrorHandler;
12433
+ return this;
12434
+ }
12435
+ withPerfProvider(perfProvider) {
12436
+ this.performanceProvider = perfProvider;
12437
+ return this;
12438
+ }
12439
+ withWorkspaceRestoredHandler(workspaceRestoredHandler) {
12440
+ this.workspaceRestoredHandler = workspaceRestoredHandler;
12441
+ this.workspaceStartedHandler = () => () => { };
12442
+ return this;
12443
+ }
12444
+ withWorkspaceStartupHandler(workspaceStartupHandler) {
12445
+ this.workspaceStartupHandler = workspaceStartupHandler;
12446
+ return this;
12447
+ }
12448
+ withWorkspaceFrameCreatedHandler(workspaceFrameCreatedHandler) {
12449
+ this.workspaceFrameCreatedHandler = workspaceFrameCreatedHandler;
12450
+ return this;
12451
+ }
12452
+ withWorkspaceFrameInitHandler(workspaceFrameInitHandler) {
12453
+ this.workspaceFrameInitHandler = workspaceFrameInitHandler;
12454
+ return this;
12455
+ }
12456
+ withWorkspaceFramePageLoadHandler(workspaceFramePageLoadHandler) {
12457
+ this.workspaceFramePageLoadHandler = workspaceFramePageLoadHandler;
12458
+ return this;
12459
+ }
12460
+ withWorkspaceFrameWorkspaceRenderHandler(workspaceFrameWorkspaceRenderHandler) {
12461
+ this.workspaceFrameWorkspaceRenderHandler = workspaceFrameWorkspaceRenderHandler;
12462
+ return this;
12463
+ }
12464
+ withWorkspaceComponentCreatedHandler(workspaceComponentCreatedHandler) {
12465
+ this.workspaceComponentCreatedHandler = workspaceComponentCreatedHandler;
12466
+ return this;
12467
+ }
12468
+ withWorkspaceAppsStartedHandler(workspaceAppsStartedHandler) {
12469
+ this.workspaceAppsStartedHandler = workspaceAppsStartedHandler;
12470
+ return this;
12471
+ }
12472
+ }
12473
+ metricsDependencyBuilder.MetricsDependencyBuilder = MetricsDependencyBuilder;
12474
+
12475
+ var logs = {};
12476
+
12477
+ Object.defineProperty(logs, "__esModule", { value: true });
12478
+ logs.Logs = void 0;
12479
+ const nullManager_1 = nullManager;
12480
+ class Logs {
12481
+ static get instance() {
12482
+ var _a, _b;
12483
+ if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.logs) {
12484
+ return (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.logs;
12485
+ }
12486
+ if (!Logs._instance) {
12487
+ Logs._instance = new nullManager_1.NullLogsManager(undefined, undefined, undefined);
12488
+ }
12489
+ return Logs._instance;
12490
+ }
12491
+ static set instance(value) {
12492
+ Logs._instance = value;
12493
+ }
12494
+ static emit(record) {
12495
+ return Logs.instance.emit(record);
12496
+ }
12497
+ }
12498
+ logs.Logs = Logs;
12499
+
12500
+ var pluginLoader = {};
12501
+
12502
+ Object.defineProperty(pluginLoader, "__esModule", { value: true });
12503
+ pluginLoader.registerInsightsPlugin = pluginLoader.loadInsightsPlugin = void 0;
12504
+ const returnedPlugins = new Map();
12505
+ function loadInsightsPlugin(name, logger) {
12506
+ if (returnedPlugins.get(name) !== undefined) {
12507
+ return returnedPlugins.get(name);
12508
+ }
12509
+ if (typeof globalThis.ioInsightsPlugins === "undefined") {
12510
+ return null;
12511
+ }
12512
+ let plugin = globalThis.ioInsightsPlugins[name];
12513
+ if (!plugin) {
12514
+ return null;
12515
+ }
12516
+ if (typeof plugin === "function") {
12517
+ try {
12518
+ plugin = plugin();
12519
+ }
12520
+ catch (err) {
12521
+ logger === null || logger === void 0 ? void 0 : logger.error(`Error loading io.Insights plugin ${name}`, err);
12522
+ returnedPlugins.set(name, null);
12523
+ return null;
12524
+ }
12525
+ }
12526
+ returnedPlugins.set(name, plugin);
12527
+ return plugin;
12528
+ }
12529
+ pluginLoader.loadInsightsPlugin = loadInsightsPlugin;
12530
+ function registerInsightsPlugin(name, pluginOrFactoryFunc) {
12531
+ if (typeof globalThis.ioInsightsPlugins === "undefined") {
12532
+ globalThis.ioInsightsPlugins = {};
12533
+ }
12534
+ globalThis.ioInsightsPlugins[name] = pluginOrFactoryFunc;
12535
+ }
12536
+ pluginLoader.registerInsightsPlugin = registerInsightsPlugin;
12537
+
12538
+ var isNode$1 = {};
12539
+
12540
+ Object.defineProperty(isNode$1, "__esModule", { value: true });
12541
+ isNode$1.isNode = void 0;
12542
+ let _isNode;
12543
+ function isNode() {
12544
+ if (typeof _isNode !== "undefined") {
12545
+ return _isNode;
12546
+ }
12547
+ if (typeof window !== "undefined") {
12548
+ _isNode = false;
12549
+ return false;
12550
+ }
12551
+ // Only Node.JS has a process variable that is of [[Class]] process
12552
+ try {
12553
+ _isNode = Object.prototype.toString.call(commonjsGlobal.process) === "[object process]";
12554
+ }
12555
+ catch (e) {
12556
+ _isNode = false;
12557
+ }
12558
+ return _isNode;
12559
+ }
12560
+ isNode$1.isNode = isNode;
12561
+
12562
+ var hasRequiredDist;
12563
+
12564
+ function requireDist () {
12565
+ if (hasRequiredDist) return dist;
12566
+ hasRequiredDist = 1;
12567
+ (function (exports$1) {
12568
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12569
+ if (k2 === undefined) k2 = k;
12570
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12571
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12572
+ desc = { enumerable: true, get: function() { return m[k]; } };
12573
+ }
12574
+ Object.defineProperty(o, k2, desc);
12575
+ }) : (function(o, m, k, k2) {
12576
+ if (k2 === undefined) k2 = k;
12577
+ o[k2] = m[k];
12578
+ }));
12579
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
12580
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
12581
+ }) : function(o, v) {
12582
+ o["default"] = v;
12583
+ });
12584
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
12585
+ if (mod && mod.__esModule) return mod;
12586
+ var result = {};
12587
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
12588
+ __setModuleDefault(result, mod);
12589
+ return result;
12590
+ };
12591
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
12592
+ return (mod && mod.__esModule) ? mod : { "default": mod };
12593
+ };
12594
+ Object.defineProperty(exports$1, "__esModule", { value: true });
12595
+ exports$1.SpanStatusCode = exports$1.deep_value = exports$1.extractFilteringContextFromArgs = exports$1.getOTELData = exports$1.flattenOtelAtributes = exports$1.safeStringify = exports$1.isNode = exports$1.loadInsightsPlugin = exports$1.registerInsightsPlugin = exports$1.Logs = exports$1.NullTracingState = exports$1.OTEL_PI_KEY = exports$1.withSpan = exports$1.Traces = exports$1.MetricsDependencyBuilder = exports$1.NullMetric = exports$1.Container = exports$1.Log4jsWrapper = exports$1.Builder = void 0;
12596
+ var builder_1 = requireBuilder();
12597
+ Object.defineProperty(exports$1, "Builder", { enumerable: true, get: function () { return builder_1.Builder; } });
12598
+ var log4jsWrapper_1 = log4jsWrapper;
12599
+ Object.defineProperty(exports$1, "Log4jsWrapper", { enumerable: true, get: function () { return log4jsWrapper_1.Log4jsWrapper; } });
12600
+ var container_1 = container;
12601
+ Object.defineProperty(exports$1, "Container", { enumerable: true, get: function () { return container_1.Container; } });
12602
+ var null_1 = _null$1;
12603
+ Object.defineProperty(exports$1, "NullMetric", { enumerable: true, get: function () { return null_1.NullMetric; } });
12604
+ var metricsDependencyBuilder_1 = metricsDependencyBuilder;
12605
+ Object.defineProperty(exports$1, "MetricsDependencyBuilder", { enumerable: true, get: function () { return metricsDependencyBuilder_1.MetricsDependencyBuilder; } });
12606
+ const traces_1 = __importStar(requireTraces());
12607
+ exports$1.Traces = traces_1.default;
12608
+ Object.defineProperty(exports$1, "withSpan", { enumerable: true, get: function () { return traces_1.withSpan; } });
12609
+ exports$1.OTEL_PI_KEY = "__interopIOTracePropagationInfo";
12610
+ const nullTracingState_1 = __importDefault(nullTracingState);
12611
+ exports$1.NullTracingState = nullTracingState_1.default;
12612
+ var logs_1 = logs;
12613
+ Object.defineProperty(exports$1, "Logs", { enumerable: true, get: function () { return logs_1.Logs; } });
12614
+ const pluginLoader_1 = pluginLoader;
12615
+ Object.defineProperty(exports$1, "registerInsightsPlugin", { enumerable: true, get: function () { return pluginLoader_1.registerInsightsPlugin; } });
12616
+ Object.defineProperty(exports$1, "loadInsightsPlugin", { enumerable: true, get: function () { return pluginLoader_1.loadInsightsPlugin; } });
12617
+ const isNode_1 = isNode$1;
12618
+ Object.defineProperty(exports$1, "isNode", { enumerable: true, get: function () { return isNode_1.isNode; } });
12619
+ const safe_stringify_1 = safeStringify$1;
12620
+ Object.defineProperty(exports$1, "safeStringify", { enumerable: true, get: function () { return safe_stringify_1.safeStringify; } });
12621
+ const otelUtils_1 = otelUtils;
12622
+ Object.defineProperty(exports$1, "getOTELData", { enumerable: true, get: function () { return otelUtils_1.getOTELData; } });
12623
+ Object.defineProperty(exports$1, "flattenOtelAtributes", { enumerable: true, get: function () { return otelUtils_1.flattenOtelAtributes; } });
12624
+ Object.defineProperty(exports$1, "extractFilteringContextFromArgs", { enumerable: true, get: function () { return otelUtils_1.extractFilteringContextFromArgs; } });
12625
+ Object.defineProperty(exports$1, "deep_value", { enumerable: true, get: function () { return otelUtils_1.deep_value; } });
12626
+ if (typeof Promise !== "undefined") {
12627
+ Promise.allSettled = Promise.allSettled || ((promises) => Promise.all(promises.map((p) => p
12628
+ .then((value) => ({
12629
+ status: "fulfilled",
12630
+ value
12631
+ }))
12632
+ .catch((reason) => ({
12633
+ status: "rejected",
12634
+ reason
12635
+ })))));
12636
+ }
12637
+ var SpanStatusCode;
12638
+ (function (SpanStatusCode) {
12639
+ /**
12640
+ * The default status.
12641
+ */
12642
+ SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET";
12643
+ /**
12644
+ * The operation has been validated by an Application developer or
12645
+ * Operator to have completed successfully.
12646
+ */
12647
+ SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK";
12648
+ /**
12649
+ * The operation contains an error.
12650
+ */
12651
+ SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
12652
+ })(SpanStatusCode || (SpanStatusCode = {}));
12653
+ exports$1.SpanStatusCode = SpanStatusCode;
12654
+
12655
+ } (dist));
12656
+ return dist;
12657
+ }
12658
+
12659
+ var distExports = requireDist();
12660
+
12661
+ function setInsightsAttributes(settings, ext, glue42gd, nodeStartingContext) {
12662
+ let applicationName = settings.applicationName ?? "unknown-app";
12663
+ if (glue42gd) {
12664
+ applicationName = settings.applicationName ?? glue42gd?.appName ?? applicationName;
12665
+ }
12666
+ if (nodeStartingContext) {
12667
+ applicationName = settings.applicationName ?? nodeStartingContext.applicationConfig.name ?? applicationName;
12668
+ }
12669
+ settings.applicationName = applicationName;
12670
+ if (settings.traces?.closeTrace) {
12671
+ glue42gd?.addCloseHandler(() => distExports.Traces.withSpan("interopio.api.application.close", () => { }));
12672
+ }
12673
+ const sid = glue42gd?.sid;
12674
+ const user = glue42gd?.user;
12675
+ const osUser = (Utils.isNode() && process?.env?.USERNAME) ?? glue42gd?.env?.windowsUserName;
12676
+ const machine = (Utils.isNode() && process?.env?.COMPUTERNAME) ?? glue42gd?.env?.machineName;
12677
+ const env = nodeStartingContext?.env ?? glue42gd?.env?.env;
12678
+ const region = nodeStartingContext?.region ?? glue42gd?.env?.region;
12679
+ const appInstanceId = nodeStartingContext?.instanceId ?? glue42gd?.appInstanceId ?? "";
12680
+ const windowId = glue42gd?.windowId;
12681
+ const extraInsightsContext = {
12682
+ interopioCoreVersion: version,
12683
+ interopioLibVersion: ext.version || version,
12684
+ host: "io.api",
12685
+ tracingAppName: applicationName,
12686
+ tracingAppInstanceId: appInstanceId,
12687
+ user,
12688
+ osUser,
12689
+ machine,
12690
+ env,
12691
+ region,
12692
+ windowId,
12693
+ sid
12694
+ };
12695
+ let providedAdditionalResourceAttributesFunc = settings.additionalResourceAttributes;
12696
+ if (typeof providedAdditionalResourceAttributesFunc !== "function") {
12697
+ const providedAdditionalResourceAttributes = settings.additionalResourceAttributes;
12698
+ providedAdditionalResourceAttributesFunc = () => providedAdditionalResourceAttributes;
12699
+ }
12700
+ settings.additionalResourceAttributes = () => ({
12701
+ ...extraInsightsContext,
12702
+ ...providedAdditionalResourceAttributesFunc(),
12703
+ });
12704
+ }
12705
+ function setDefaultTraceFilters(settings) {
12706
+ if (!settings.traces) {
12707
+ return;
12708
+ }
12709
+ settings.traces.defaultFilters ??= [];
12710
+ settings.traces.defaultFilters.push({
12711
+ "source": "interopio.api.instrumentation.fetch",
12712
+ "canBeRoot": false
12713
+ });
12714
+ settings.traces.defaultFilters.push({
12715
+ "source": "interopio.api.instrumentation.xhr",
12716
+ "canBeRoot": false
12717
+ });
12718
+ settings.traces.defaultFilters.push({
12719
+ "source": "interopio.api.prefs",
12720
+ "canBeRoot": false
12721
+ });
12722
+ settings.traces.defaultFilters.push({
12723
+ "source": "interopio.api.layouts",
12724
+ "canBeRoot": false
12725
+ });
12726
+ settings.traces.defaultFilters.push({
12727
+ "source": "interopio.api.windows",
12728
+ "canBeRoot": false
12729
+ });
12730
+ settings.traces.defaultFilters.push({
12731
+ "source": "interopio.api.interop",
12732
+ "context": {
12733
+ "stream": "#^t42[.].*"
12734
+ },
12735
+ "canBeRoot": false,
12736
+ "enabled": false
12737
+ });
12738
+ settings.traces.defaultFilters.push({
12739
+ "source": "interopio.api.interop",
12740
+ "context": {
12741
+ "stream": "apps.event"
12742
+ },
12743
+ "canBeRoot": false,
12744
+ "enabled": false
12745
+ });
12746
+ settings.traces.defaultFilters.push({
12747
+ "source": "interopio.api.interop",
12748
+ "context": {
12749
+ "name": "#^t42[.].*"
12750
+ },
12751
+ "canBeRoot": false,
12752
+ "enabled": false
12753
+ });
12754
+ settings.traces.defaultFilters.push({
12755
+ "source": "interopio.api.interop",
12756
+ "context": {
12757
+ "name": "apps.event"
12758
+ },
12759
+ "canBeRoot": false,
12760
+ "enabled": false
12761
+ });
12762
+ settings.traces.defaultFilters.push({
12763
+ "source": "interopio.api.interop",
12764
+ "context": {
12765
+ "method": "apps.command"
12766
+ },
12767
+ "canBeRoot": false
12768
+ });
12769
+ settings.traces.defaultFilters.push({
12770
+ "source": "interopio.api.interop",
12771
+ "context": {
12772
+ "method": "#^t42[.].*"
12773
+ },
12774
+ "canBeRoot": false
12775
+ });
12776
+ settings.traces.defaultFilters.push({
12777
+ "source": "interopio.api.contexts",
12778
+ "context": {
12779
+ "context": "___insights_pi_storage___"
12780
+ },
12781
+ "enabled": false
12782
+ });
12783
+ settings.traces.defaultFilters.push({
12784
+ "source": "interopio.api.contexts",
12785
+ "context": {
12786
+ "context": "#^t42[.].*"
12787
+ },
12788
+ "canBeRoot": false
12789
+ });
12790
+ settings.traces.defaultFilters.push({
12791
+ "source": "interopio.api.contexts",
12792
+ "context": {
12793
+ "context": "#^__.*"
12794
+ },
12795
+ "canBeRoot": false
12796
+ });
12797
+ settings.traces.defaultFilters.push({
12798
+ "source": "interopio.api.appManager",
12799
+ "canBeRoot": false
12800
+ });
12801
+ settings.traces.defaultFilters.push({
12802
+ "source": "interopio.api.notifications",
12803
+ "canBeRoot": false
12804
+ });
12805
+ }
12806
+
12807
+ function prepareConfig (configuration, ext, glue42gd) {
12808
+ let nodeStartingContext;
12809
+ if (Utils.isNode()) {
12810
+ const startingContextString = process.env._GD_STARTING_CONTEXT_;
12811
+ if (startingContextString) {
12812
+ try {
12813
+ nodeStartingContext = JSON.parse(startingContextString);
12814
+ }
12815
+ catch {
12816
+ }
12817
+ }
12818
+ }
12819
+ function getConnection() {
12820
+ const gwConfig = configuration.gateway;
12821
+ const protocolVersion = gwConfig?.protocolVersion ?? 3;
12822
+ const reconnectInterval = gwConfig?.reconnectInterval;
12823
+ const reconnectAttempts = gwConfig?.reconnectAttempts;
12824
+ const defaultWs = "ws://localhost:8385";
12825
+ let ws = gwConfig?.ws;
12826
+ const sharedWorker = gwConfig?.sharedWorker;
12827
+ const inproc = gwConfig?.inproc;
12828
+ const webPlatform = gwConfig?.webPlatform ?? undefined;
12829
+ if (glue42gd) {
12830
+ ws = glue42gd.gwURL;
12831
+ }
12832
+ if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) {
12833
+ ws = nodeStartingContext.gwURL;
12834
+ }
12835
+ if (!ws && !sharedWorker && !inproc) {
12836
+ ws = defaultWs;
12837
+ }
12838
+ let instanceId;
12839
+ let windowId;
12840
+ let pid;
12841
+ let environment;
12842
+ let region;
12843
+ const appName = getApplication();
12844
+ let uniqueAppName = appName;
12845
+ if (typeof glue42gd !== "undefined") {
12846
+ windowId = glue42gd.windowId;
12847
+ pid = glue42gd.pid;
12848
+ if (glue42gd.env) {
12849
+ environment = glue42gd.env.env;
12850
+ region = glue42gd.env.region;
12851
+ }
12852
+ uniqueAppName = glue42gd.application ?? "glue-app";
12853
+ instanceId = glue42gd.appInstanceId;
12854
+ }
12855
+ else if (Utils.isNode()) {
12856
+ pid = process.pid;
12857
+ if (nodeStartingContext) {
12858
+ environment = nodeStartingContext.env;
12859
+ region = nodeStartingContext.region;
12860
+ instanceId = nodeStartingContext.instanceId;
12861
+ }
12862
+ }
12863
+ else if (typeof window?.glue42electron !== "undefined") {
12864
+ windowId = window?.glue42electron.instanceId;
12865
+ pid = window?.glue42electron.pid;
12866
+ environment = window?.glue42electron.env;
12867
+ region = window?.glue42electron.region;
12868
+ uniqueAppName = window?.glue42electron.application ?? "glue-app";
12869
+ instanceId = window?.glue42electron.instanceId;
12870
+ }
12871
+ else ;
12872
+ const replaySpecs = configuration.gateway?.replaySpecs ?? [];
12873
+ replaySpecs.push(ContextMessageReplaySpec);
12874
+ let identity = {
12875
+ application: uniqueAppName,
12876
+ applicationName: appName,
12877
+ windowId,
12878
+ instance: instanceId,
12879
+ process: pid,
12880
+ region,
12881
+ environment,
12882
+ api: ext.version || version
12883
+ };
12884
+ if (configuration.identity) {
12885
+ identity = Object.assign(identity, configuration.identity);
12886
+ }
12887
+ return {
12888
+ identity,
12889
+ reconnectInterval,
12890
+ ws,
12891
+ sharedWorker,
12892
+ webPlatform,
12893
+ inproc,
12894
+ protocolVersion,
12895
+ reconnectAttempts,
12896
+ replaySpecs,
12897
+ };
12898
+ }
12899
+ function getContexts() {
12900
+ const defaultConfig = {
12901
+ reAnnounceKnownContexts: true,
12902
+ subscribeOnUpdate: true,
12903
+ subscribeOnGet: true,
12904
+ onlyReAnnounceSubscribedContexts: true
12905
+ };
12906
+ if (typeof configuration.contexts === "undefined") {
12907
+ return defaultConfig;
12908
+ }
12909
+ if (typeof configuration.contexts === "boolean" && configuration.contexts) {
12910
+ return defaultConfig;
12911
+ }
12912
+ if (typeof configuration.contexts === "object") {
12913
+ return { ...defaultConfig, ...configuration.contexts };
12914
+ }
12915
+ return false;
12916
+ }
12917
+ function getApplication() {
12918
+ if (configuration.application) {
12919
+ return configuration.application;
12920
+ }
12921
+ if (glue42gd) {
12922
+ return glue42gd.applicationName;
12923
+ }
12924
+ if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") {
12925
+ return window.glue42electron.application;
12926
+ }
12927
+ const uid = nanoid(10);
12928
+ if (Utils.isNode()) {
12929
+ if (nodeStartingContext) {
12930
+ return nodeStartingContext.applicationConfig.name;
12931
+ }
12932
+ return "NodeJS" + uid;
12933
+ }
12934
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
12935
+ return document.title + ` (${uid})`;
12936
+ }
12937
+ return uid;
12938
+ }
12939
+ async function getInsights(iodesktop, interop, logger) {
12940
+ const configProp = configuration.insights;
12941
+ if (typeof configProp !== "object" && typeof configProp !== "boolean" && typeof configProp !== "undefined") {
12942
+ throw new Error("insights/otel property should be boolean, object or unspecified");
12943
+ }
12944
+ if (configProp === false) {
12945
+ return { enabled: false };
12946
+ }
12947
+ let gdConfig;
12948
+ if (iodesktop) {
12949
+ gdConfig = iodesktop.insights;
12950
+ }
12951
+ else if (Utils.isNode() && (configuration?.insights !== false &&
12952
+ configuration?.insights?.enabled !== false &&
12953
+ configuration?.insights?.requestSettings !== false)) {
12954
+ gdConfig = (await interop?.invoke("T42.Otel.GetConfig", undefined, nodeStartingContext ? { environment: nodeStartingContext.env, region: nodeStartingContext.region } : undefined, { waitTimeoutMs: 0 })
12955
+ .then(result => result.returned)
12956
+ .catch(err => logger?.warn("Unable to retrieve base io.Insights settings: " +
12957
+ (err?.message ?? err))));
12958
+ }
12959
+ if (gdConfig &&
12960
+ (iodesktop ||
12961
+ nodeStartingContext ||
12962
+ (Utils.isNode() && (typeof configProp === "boolean" || !configProp?.platformInstance)))) {
12963
+ gdConfig = {
12964
+ ...gdConfig,
12965
+ metrics: {
12966
+ ...gdConfig?.metrics,
12967
+ enabled: !!gdConfig?.metrics?.enabled,
12968
+ platformMetricsEnabled: false
12969
+ }
12970
+ };
12971
+ }
12972
+ let settings;
12973
+ if (configProp === true || typeof configProp === "undefined") {
12974
+ settings = gdConfig ?? { enabled: false };
12975
+ }
12976
+ else {
12977
+ settings = deepMerge(gdConfig || {}, configProp, { isMergeableObject: isPlainObject$2 });
12978
+ }
12979
+ setInsightsAttributes(settings, ext, glue42gd, nodeStartingContext);
12980
+ if (settings.traces?.enabled) {
12981
+ setDefaultTraceFilters(settings);
12982
+ }
12983
+ return settings;
12984
+ }
12985
+ function getAuth() {
12986
+ if (typeof configuration.auth === "string") {
12987
+ return {
12988
+ token: configuration.auth
12989
+ };
12990
+ }
12991
+ if (configuration.auth) {
12992
+ return configuration.auth;
12993
+ }
12994
+ if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) {
12995
+ return {
12996
+ gatewayToken: nodeStartingContext.gwToken
12997
+ };
12998
+ }
12999
+ if (configuration.gateway?.webPlatform) {
13000
+ return {
13001
+ username: "glue42",
13002
+ password: ""
13003
+ };
13004
+ }
13005
+ }
13006
+ function getLogger() {
13007
+ let config = configuration.logger;
13008
+ const defaultLevel = "warn";
13009
+ if (!config) {
13010
+ config = defaultLevel;
13011
+ }
13012
+ let gdConsoleLevel;
13013
+ if (glue42gd) {
13014
+ gdConsoleLevel = glue42gd.consoleLogLevel;
13015
+ }
13016
+ if (typeof config === "string") {
13017
+ return { console: gdConsoleLevel ?? config, publish: defaultLevel };
13018
+ }
13019
+ return {
13020
+ console: gdConsoleLevel ?? config.console ?? defaultLevel,
13021
+ publish: config.publish ?? defaultLevel
13022
+ };
13023
+ }
13024
+ const connection = getConnection();
13025
+ let application = getApplication();
13026
+ if (typeof window !== "undefined") {
13027
+ const windowAsAny = window;
13028
+ const containerApplication = windowAsAny.htmlContainer ?
13029
+ `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` :
13030
+ windowAsAny?.glue42gd?.application;
10982
13031
  if (containerApplication) {
10983
13032
  application = containerApplication;
10984
13033
  }
@@ -10993,10 +13042,40 @@ function prepareConfig (configuration, ext, glue42gd) {
10993
13042
  contexts: getContexts(),
10994
13043
  version: ext.version || version,
10995
13044
  libs: ext.libs ?? [],
10996
- customLogger: configuration.customLogger
13045
+ customLogger: configuration.customLogger,
13046
+ getInsights
10997
13047
  };
10998
13048
  }
10999
13049
 
13050
+ /******************************************************************************
13051
+ Copyright (c) Microsoft Corporation.
13052
+
13053
+ Permission to use, copy, modify, and/or distribute this software for any
13054
+ purpose with or without fee is hereby granted.
13055
+
13056
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13057
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13058
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13059
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13060
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13061
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13062
+ PERFORMANCE OF THIS SOFTWARE.
13063
+ ***************************************************************************** */
13064
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
13065
+
13066
+
13067
+ function __decorate(decorators, target, key, desc) {
13068
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13069
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
13070
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13071
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
13072
+ }
13073
+
13074
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
13075
+ var e = new Error(message);
13076
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
13077
+ };
13078
+
11000
13079
  class GW3ContextData {
11001
13080
  name;
11002
13081
  contextId;
@@ -11059,7 +13138,7 @@ var lodash_clonedeep = {exports: {}};
11059
13138
  */
11060
13139
  lodash_clonedeep.exports;
11061
13140
 
11062
- (function (module, exports) {
13141
+ (function (module, exports$1) {
11063
13142
  /** Used as the size to enable large array optimizations. */
11064
13143
  var LARGE_ARRAY_SIZE = 200;
11065
13144
 
@@ -11140,7 +13219,7 @@ lodash_clonedeep.exports;
11140
13219
  var root = freeGlobal || freeSelf || Function('return this')();
11141
13220
 
11142
13221
  /** Detect free variable `exports`. */
11143
- var freeExports = exports && !exports.nodeType && exports;
13222
+ var freeExports = exports$1 && !exports$1.nodeType && exports$1;
11144
13223
 
11145
13224
  /** Detect free variable `module`. */
11146
13225
  var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
@@ -12840,6 +14919,7 @@ function applyContextDelta(context, delta, logger) {
12840
14919
  delete context[key];
12841
14920
  });
12842
14921
  }
14922
+ distExports.Traces.removePropagationInfo(context);
12843
14923
  return context;
12844
14924
  }
12845
14925
  catch (e) {
@@ -13046,6 +15126,11 @@ class GW3Bridge {
13046
15126
  if (name in this._creationPromises) {
13047
15127
  return this._creationPromises[name];
13048
15128
  }
15129
+ const ts = distExports.Traces.currentTracingState;
15130
+ ts.addData("INFO", { context: name });
15131
+ ts.addData("DIAGNOSTIC", { data });
15132
+ data = deepClone(data);
15133
+ ts.injectPropagationInfo(data);
13049
15134
  this._creationPromises[name] =
13050
15135
  this._gw3Session
13051
15136
  .send({
@@ -13081,15 +15166,21 @@ class GW3Bridge {
13081
15166
  if (delta) {
13082
15167
  delta = deepClone(delta);
13083
15168
  }
15169
+ const ts = distExports.Traces.currentTracingState;
13084
15170
  if (name in this._creationPromises) {
13085
15171
  await this._creationPromises[name];
15172
+ distExports.Traces.currentTracingState = ts;
13086
15173
  }
13087
15174
  const contextData = this._contextNameToData[name];
15175
+ ts.addData("DIAGNOSTIC", { data: contextData });
15176
+ ts.addData("DEBUG", { delta });
13088
15177
  if (!contextData || !contextData.isAnnounced) {
13089
15178
  await this.createContext(name, delta);
13090
15179
  return;
13091
15180
  }
13092
15181
  const currentContext = await this.get(contextData.name);
15182
+ distExports.Traces.currentTracingState = ts;
15183
+ distExports.Traces.removePropagationInfo(currentContext);
13093
15184
  const calculatedDelta = this.setPathSupported ?
13094
15185
  this.calculateContextDeltaV2(currentContext, delta) :
13095
15186
  this.calculateContextDeltaV1(currentContext, delta);
@@ -13099,13 +15190,16 @@ class GW3Bridge {
13099
15190
  && !calculatedDelta.commands?.length) {
13100
15191
  return Promise.resolve();
13101
15192
  }
15193
+ const calculatedDeltaWithPropagationInfo = deepClone(calculatedDelta);
15194
+ ts.injectPropagationInfo(calculatedDeltaWithPropagationInfo);
13102
15195
  const gwResponse = await this._gw3Session
13103
15196
  .send({
13104
15197
  type: GW_MESSAGE_UPDATE_CONTEXT,
13105
15198
  domain: "global",
13106
15199
  context_id: contextData.contextId,
13107
- delta: calculatedDelta,
15200
+ delta: calculatedDeltaWithPropagationInfo,
13108
15201
  }, {}, { skipPeerId: false });
15202
+ distExports.Traces.currentTracingState = ts;
13109
15203
  if (this._subscribeOnUpdate &&
13110
15204
  !contextData.sentExplicitSubscription &&
13111
15205
  !contextData.activityId) {
@@ -13115,6 +15209,7 @@ class GW3Bridge {
13115
15209
  contextData.sentExplicitSubscription ||
13116
15210
  contextData.activityId) {
13117
15211
  await contextData.snapshotPromise;
15212
+ distExports.Traces.currentTracingState = ts;
13118
15213
  this.handleUpdated(contextData, calculatedDelta, {
13119
15214
  updaterId: gwResponse.peer_id
13120
15215
  });
@@ -13124,10 +15219,14 @@ class GW3Bridge {
13124
15219
  if (data) {
13125
15220
  data = deepClone(data);
13126
15221
  }
15222
+ const ts = distExports.Traces.currentTracingState;
13127
15223
  if (name in this._creationPromises) {
13128
15224
  await this._creationPromises[name];
15225
+ distExports.Traces.currentTracingState = ts;
13129
15226
  }
13130
15227
  const contextData = this._contextNameToData[name];
15228
+ ts.addData("DIAGNOSTIC", { data: contextData });
15229
+ ts.injectPropagationInfo(data);
13131
15230
  if (!contextData || !contextData.isAnnounced) {
13132
15231
  return this.createContext(name, data);
13133
15232
  }
@@ -13138,6 +15237,7 @@ class GW3Bridge {
13138
15237
  context_id: contextData.contextId,
13139
15238
  delta: { reset: data },
13140
15239
  }, {}, { skipPeerId: false });
15240
+ distExports.Traces.currentTracingState = ts;
13141
15241
  if (this._subscribeOnUpdate &&
13142
15242
  !contextData.sentExplicitSubscription &&
13143
15243
  !contextData.activityId) {
@@ -13158,21 +15258,30 @@ class GW3Bridge {
13158
15258
  }
13159
15259
  setPath(name, path, value) {
13160
15260
  if (!this.setPathSupported) {
13161
- return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later");
15261
+ return Promise.reject(new Error("contexts.setPath operation is not supported, use version 3.10 or later"));
13162
15262
  }
13163
15263
  return this.setPaths(name, [{ path, value }]);
13164
15264
  }
13165
15265
  async setPaths(name, pathValues) {
13166
15266
  if (!this.setPathSupported) {
13167
- return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");
15267
+ return Promise.reject(new Error("contexts.setPaths operation is not supported, use version 3.10 or later"));
13168
15268
  }
13169
15269
  if (pathValues) {
13170
15270
  pathValues = deepClone(pathValues);
13171
15271
  }
15272
+ const ts = distExports.Traces.currentTracingState;
13172
15273
  if (name in this._creationPromises) {
13173
15274
  await this._creationPromises[name];
15275
+ distExports.Traces.currentTracingState = ts;
13174
15276
  }
13175
15277
  const contextData = this._contextNameToData[name];
15278
+ ts.addData("DIAGNOSTIC", { data: contextData });
15279
+ ts.addData("DEBUG", { pathValues });
15280
+ const injectionCarrier = { [distExports.OTEL_PI_KEY]: undefined };
15281
+ ts.injectPropagationInfo(injectionCarrier);
15282
+ if (injectionCarrier[distExports.OTEL_PI_KEY]) {
15283
+ pathValues.push({ path: distExports.OTEL_PI_KEY, value: injectionCarrier[distExports.OTEL_PI_KEY] });
15284
+ }
13176
15285
  if (!contextData || !contextData.isAnnounced) {
13177
15286
  const obj = {};
13178
15287
  for (const pathValue of pathValues) {
@@ -13196,6 +15305,7 @@ class GW3Bridge {
13196
15305
  context_id: contextData.contextId,
13197
15306
  delta: { commands }
13198
15307
  }, {}, { skipPeerId: false });
15308
+ distExports.Traces.currentTracingState = ts;
13199
15309
  if (this._subscribeOnUpdate &&
13200
15310
  !contextData.sentExplicitSubscription &&
13201
15311
  !contextData.activityId) {
@@ -13205,6 +15315,7 @@ class GW3Bridge {
13205
15315
  contextData.sentExplicitSubscription ||
13206
15316
  contextData.activityId) {
13207
15317
  await contextData.snapshotPromise;
15318
+ distExports.Traces.currentTracingState = ts;
13208
15319
  this.handleUpdated(contextData, {
13209
15320
  added: {},
13210
15321
  removed: [],
@@ -13216,19 +15327,23 @@ class GW3Bridge {
13216
15327
  }
13217
15328
  }
13218
15329
  async get(name) {
15330
+ const ts = distExports.Traces.currentTracingState;
15331
+ ts.addData("INFO", { context: name });
13219
15332
  if (name in this._creationPromises) {
13220
15333
  await this._creationPromises[name];
15334
+ distExports.Traces.currentTracingState = ts;
13221
15335
  }
13222
15336
  const contextData = this._contextNameToData[name];
13223
15337
  if (!contextData || !contextData.isAnnounced) {
13224
15338
  if (!contextData && this._subscribeOnGet) {
13225
- this.subscribe(name, () => { });
15339
+ this.subscribeInner(name, () => { });
13226
15340
  }
13227
15341
  return Promise.resolve({});
13228
15342
  }
13229
15343
  if (contextData && !contextData.sentExplicitSubscription) {
13230
15344
  return new Promise((resolve, reject) => {
13231
- this.subscribe(name, (data, _d, _r, un) => {
15345
+ this.subscribeInner(name, (data, _d, _r, un) => {
15346
+ distExports.Traces.removePropagationInfo(data);
13232
15347
  if (!this._subscribeOnGet) {
13233
15348
  this.unsubscribe(un);
13234
15349
  }
@@ -13244,15 +15359,18 @@ class GW3Bridge {
13244
15359
  }
13245
15360
  await contextData.snapshotPromise;
13246
15361
  const context = contextData?.context ?? {};
15362
+ distExports.Traces.removePropagationInfo(context);
13247
15363
  return Promise.resolve(deepClone(context));
13248
15364
  }
13249
15365
  isInvalidContextError(e) {
13250
15366
  return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT
13251
15367
  || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id"));
13252
15368
  }
13253
- async subscribe(name, callback, subscriptionKey) {
15369
+ async subscribeInner(name, callback, subscriptionKey) {
15370
+ const ts = distExports.Traces.currentTracingState;
13254
15371
  if (name in this._creationPromises) {
13255
15372
  await this._creationPromises[name];
15373
+ distExports.Traces.currentTracingState = ts;
13256
15374
  }
13257
15375
  const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey;
13258
15376
  if (typeof subscriptionKey === "undefined") {
@@ -13300,6 +15418,23 @@ class GW3Bridge {
13300
15418
  return Promise.resolve(thisCallbackSubscriptionNumber);
13301
15419
  }
13302
15420
  }
15421
+ async subscribe(name, callback, subscriptionKey) {
15422
+ const contextExists = this.all().includes(name);
15423
+ const ts = distExports.Traces.currentTracingState;
15424
+ ts.addData("INFO", { context: name, contextExists });
15425
+ const wrappedCallback = async (...args) => {
15426
+ return distExports.withSpan("interopio.api.contexts.bridge.subscribe.callback", { context: name }, args?.[5], (cbts) => {
15427
+ distExports.Traces.removePropagationInfo(args?.[0]);
15428
+ distExports.Traces.removePropagationInfo(args?.[1]);
15429
+ cbts.addData("INFO", { context: name });
15430
+ cbts.addData("DEBUG", { delta: args?.[1] });
15431
+ cbts.addData("DEBUG", { removed: args?.[2] });
15432
+ cbts.addData("DIAGNOSTIC", { data: args?.[0] });
15433
+ return callback(args?.[0], args?.[1], args?.[2], args?.[3], args?.[4]);
15434
+ });
15435
+ };
15436
+ return this.subscribeInner(name, wrappedCallback, subscriptionKey);
15437
+ }
13303
15438
  unsubscribe(subscriptionKey, keepInSubscriptionsCache) {
13304
15439
  if (!keepInSubscriptionsCache) {
13305
15440
  this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey);
@@ -13330,8 +15465,11 @@ class GW3Bridge {
13330
15465
  }
13331
15466
  }
13332
15467
  async destroy(name) {
15468
+ const ts = distExports.Traces.currentTracingState;
15469
+ ts.addData("INFO", { context: name });
13333
15470
  if (name in this._creationPromises) {
13334
15471
  await this._creationPromises[name];
15472
+ distExports.Traces.currentTracingState = ts;
13335
15473
  }
13336
15474
  const contextData = this._contextNameToData[name];
13337
15475
  const contextId = contextData?.contextId;
@@ -13469,7 +15607,7 @@ class GW3Bridge {
13469
15607
  if (justSeen ||
13470
15608
  !deepEqual(contextData.context, oldContext) ||
13471
15609
  updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) {
13472
- this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id });
15610
+ this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta ?? contextUpdatedMsg.data, { updaterId: contextUpdatedMsg.updater_id });
13473
15611
  }
13474
15612
  }
13475
15613
  invokeUpdateCallbacks(contextData, delta, extraData) {
@@ -13493,7 +15631,12 @@ class GW3Bridge {
13493
15631
  if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) {
13494
15632
  try {
13495
15633
  const updateCallback = contextData.updateCallbacks[updateCallbackIndex];
13496
- updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData);
15634
+ const deltaArg = deepClone({
15635
+ ...delta.added,
15636
+ ...delta.updated,
15637
+ ...delta.reset
15638
+ });
15639
+ updateCallback(deepClone(contextData.context), deltaArg, delta.removed, parseInt(updateCallbackIndex, 10), extraData, distExports.Traces.extractPropagationInfo(delta));
13497
15640
  }
13498
15641
  catch (err) {
13499
15642
  this._logger.debug("callback error: " + JSON.stringify(err));
@@ -13673,6 +15816,27 @@ class GW3Bridge {
13673
15816
  return new Promise((resolve) => setTimeout(() => resolve(), 0));
13674
15817
  }
13675
15818
  }
15819
+ __decorate([
15820
+ distExports.withSpan("interopio.api.contexts.bridge.create", { argMapping: ["context"] })
15821
+ ], GW3Bridge.prototype, "createContext", null);
15822
+ __decorate([
15823
+ distExports.withSpan("interopio.api.contexts.bridge.update", { argMapping: ["context"] })
15824
+ ], GW3Bridge.prototype, "update", null);
15825
+ __decorate([
15826
+ distExports.withSpan("interopio.api.contexts.bridge.set", { argMapping: ["context"] })
15827
+ ], GW3Bridge.prototype, "set", null);
15828
+ __decorate([
15829
+ distExports.withSpan("interopio.api.contexts.bridge.setPaths", { argMapping: ["context"] })
15830
+ ], GW3Bridge.prototype, "setPaths", null);
15831
+ __decorate([
15832
+ distExports.withSpan("interopio.api.contexts.bridge.get", { argMapping: ["context"] })
15833
+ ], GW3Bridge.prototype, "get", null);
15834
+ __decorate([
15835
+ distExports.withSpan("interopio.api.contexts.bridge.subscribe", { argMapping: ["context"] })
15836
+ ], GW3Bridge.prototype, "subscribe", null);
15837
+ __decorate([
15838
+ distExports.withSpan("interopio.api.contexts.bridge.destroy", { argMapping: ["context"] })
15839
+ ], GW3Bridge.prototype, "destroy", null);
13676
15840
 
13677
15841
  class ContextsModule {
13678
15842
  initTime;
@@ -13760,6 +15924,21 @@ class ContextsModule {
13760
15924
  }
13761
15925
  }
13762
15926
  }
15927
+ __decorate([
15928
+ distExports.withSpan("interopio.api.contexts.module.update", { argMapping: ["context"] })
15929
+ ], ContextsModule.prototype, "update", null);
15930
+ __decorate([
15931
+ distExports.withSpan("interopio.api.contexts.module.set", { argMapping: ["context"] })
15932
+ ], ContextsModule.prototype, "set", null);
15933
+ __decorate([
15934
+ distExports.withSpan("interopio.api.contexts.module.setPaths", { argMapping: ["context"] })
15935
+ ], ContextsModule.prototype, "setPaths", null);
15936
+ __decorate([
15937
+ distExports.withSpan("interopio.api.contexts.module.subscribe", { argMapping: ["context"] })
15938
+ ], ContextsModule.prototype, "subscribe", null);
15939
+ __decorate([
15940
+ distExports.withSpan("interopio.api.contexts.module.destroy", { argMapping: ["context"] })
15941
+ ], ContextsModule.prototype, "destroy", null);
13763
15942
 
13764
15943
  function promisify (promise, successCallback, errorCallback) {
13765
15944
  if (typeof successCallback !== "function" && typeof errorCallback !== "function") {
@@ -14578,7 +16757,7 @@ const functionCheck = (input, propDescription) => {
14578
16757
  const providedType = typeof input;
14579
16758
  return providedType === "function" ?
14580
16759
  anyJson() :
14581
- fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`);
16760
+ fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${providedType}`);
14582
16761
  };
14583
16762
  const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
14584
16763
  const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0");
@@ -14635,6 +16814,9 @@ class Client {
14635
16814
  this.configuration = configuration;
14636
16815
  }
14637
16816
  subscribe(method, options, successCallback, errorCallback, existingSub) {
16817
+ const ts = distExports.Traces.currentTracingState;
16818
+ ts.addData("INFO", { stream: Utils.getMethodName(method) });
16819
+ ts.addData("INFO", { options });
14638
16820
  const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => {
14639
16821
  options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs;
14640
16822
  this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub);
@@ -14759,6 +16941,10 @@ class Client {
14759
16941
  });
14760
16942
  }
14761
16943
  async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) {
16944
+ const ts = distExports.Traces.currentTracingState;
16945
+ ts.addData("INFO", { method: Utils.getMethodName(methodFilter) });
16946
+ ts.addData("INFO", { target, additionalOptions });
16947
+ ts.addData("DIAGNOSTIC", { arguments: argumentObj });
14762
16948
  const getInvokePromise = async () => {
14763
16949
  const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter };
14764
16950
  if (!argumentObj) {
@@ -14819,23 +17005,10 @@ class Client {
14819
17005
  return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj));
14820
17006
  }
14821
17007
  }
14822
- const timeout = additionalOptions.methodResponseTimeoutMs;
17008
+ const timeout = additionalOptions.methodResponseTimeoutMs ?? 30000;
14823
17009
  const additionalOptionsCopy = additionalOptions;
14824
- const invokePromises = serversMethodMap.map((serversMethodPair) => {
14825
- const invId = nanoid(10);
14826
- const method = serversMethodPair.methods[0];
14827
- const server = serversMethodPair.server;
14828
- const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy);
14829
- return Promise.race([
14830
- invokePromise,
14831
- rejectAfter(timeout, invokePromise, {
14832
- invocationId: invId,
14833
- message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`,
14834
- status: InvokeStatus.Error,
14835
- })
14836
- ]);
14837
- });
14838
- const invocationMessages = await Promise.all(invokePromises);
17010
+ const serverInvokePromises = serversMethodMap.map((smp) => this.getServerInvokePromise(smp.methods[0], smp.server, argumentObj, additionalOptionsCopy, timeout));
17011
+ const invocationMessages = await Promise.all(serverInvokePromises);
14839
17012
  const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj);
14840
17013
  const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error);
14841
17014
  if (allRejected) {
@@ -14845,6 +17018,27 @@ class Client {
14845
17018
  };
14846
17019
  return promisify(getInvokePromise(), success, error);
14847
17020
  }
17021
+ async getServerInvokePromise(method, server, argumentObj, additionalOptionsCopy, timeout) {
17022
+ const invId = nanoid(10);
17023
+ const ts = distExports.Traces.currentTracingState;
17024
+ if (argumentObj) {
17025
+ argumentObj = deepClone(argumentObj);
17026
+ ts.injectPropagationInfo(argumentObj);
17027
+ }
17028
+ ts.addData("INFO", { "server": server?.id, instance: server?.instance });
17029
+ ts.addData("INFO", { "invocationId": invId });
17030
+ const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy);
17031
+ const returnValue = await Promise.race([
17032
+ invokePromise,
17033
+ rejectAfter(timeout, invokePromise, {
17034
+ invocationId: invId,
17035
+ message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`,
17036
+ status: InvokeStatus.Error,
17037
+ })
17038
+ ]);
17039
+ ts.addData("DIAGNOSTIC", { returnValue });
17040
+ return returnValue;
17041
+ }
14848
17042
  generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) {
14849
17043
  const method = {
14850
17044
  ...methodDefinition,
@@ -14861,6 +17055,7 @@ class Client {
14861
17055
  return this.getInvocationResultObj([invokeResultMessage], method, argumentObj);
14862
17056
  }
14863
17057
  getInvocationResultObj(invocationResults, method, calledWith) {
17058
+ distExports.Traces.removePropagationInfo(calledWith);
14864
17059
  const all_return_values = invocationResults
14865
17060
  .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success)
14866
17061
  .reduce((allValues, currentValue) => {
@@ -15064,6 +17259,15 @@ class Client {
15064
17259
  return this.filterByTarget(target, serversMethodMap);
15065
17260
  }
15066
17261
  }
17262
+ __decorate([
17263
+ distExports.withSpan("interopio.api.interop.stream.subscribe", { argMapping: (methodDefinition) => ({ stream: Utils.getMethodName(methodDefinition) }) })
17264
+ ], Client.prototype, "subscribe", null);
17265
+ __decorate([
17266
+ distExports.withSpan("interopio.api.interop.invoke", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17267
+ ], Client.prototype, "invoke", null);
17268
+ __decorate([
17269
+ distExports.withSpan("interopio.api.interop.invoke.server", { argMapping: { "0.name": "method" } })
17270
+ ], Client.prototype, "getServerInvokePromise", null);
15067
17271
 
15068
17272
  class ServerSubscription {
15069
17273
  protocol;
@@ -15229,9 +17433,9 @@ class ServerStream {
15229
17433
  flags: def2.flags?.metadata,
15230
17434
  };
15231
17435
  }
15232
- close() {
17436
+ async close() {
15233
17437
  this._protocol.server.closeAllSubscriptions(this._repoMethod);
15234
- this._server.unregister(this._repoMethod.definition, true);
17438
+ return this._server.unregister(this._repoMethod.definition, true);
15235
17439
  }
15236
17440
  push(data, branches) {
15237
17441
  if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) {
@@ -15240,12 +17444,23 @@ class ServerStream {
15240
17444
  if (typeof data !== "object") {
15241
17445
  throw new Error("Invalid arguments. Data must be an object.");
15242
17446
  }
17447
+ const ts = distExports.Traces.currentTracingState;
17448
+ ts.addData("INFO", { stream: this?.name, branches });
17449
+ ts.addData("DIAGNOSTIC", { data });
17450
+ data = deepClone(data);
17451
+ ts.injectPropagationInfo(data);
15243
17452
  this._protocol.server.pushData(this._repoMethod, data, branches);
15244
17453
  }
15245
17454
  updateRepoMethod(repoMethod) {
15246
17455
  this._repoMethod = repoMethod;
15247
17456
  }
15248
17457
  }
17458
+ __decorate([
17459
+ distExports.withSpan("interopio.api.interop.stream.close", { thisMapping: { name: "stream" } })
17460
+ ], ServerStream.prototype, "close", null);
17461
+ __decorate([
17462
+ distExports.withSpan("interopio.api.interop.stream.push", { thisMapping: { name: "stream" } })
17463
+ ], ServerStream.prototype, "push", null);
15249
17464
 
15250
17465
  class Server {
15251
17466
  protocol;
@@ -15320,14 +17535,18 @@ class Server {
15320
17535
  if (!methodDefinition) {
15321
17536
  return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");
15322
17537
  }
17538
+ const ts = distExports.Traces.currentTracingState;
17539
+ ts.addData("INFO", { method: Utils.getMethodName(methodDefinition) });
15323
17540
  if (typeof callback !== "function") {
15324
- return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`);
17541
+ return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(methodDefinition)}`);
15325
17542
  }
15326
17543
  const wrappedCallbackFunction = async (context, resultCallback) => {
15327
17544
  try {
15328
17545
  const result = callback(context.args, context.instance);
15329
17546
  if (result && typeof result.then === "function") {
17547
+ const cbts = distExports.Traces.currentTracingState;
15330
17548
  const resultValue = await result;
17549
+ distExports.Traces.currentTracingState = cbts;
15331
17550
  resultCallback(undefined, resultValue);
15332
17551
  }
15333
17552
  else {
@@ -15345,8 +17564,10 @@ class Server {
15345
17564
  if (!methodDefinition) {
15346
17565
  return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");
15347
17566
  }
17567
+ const ts = distExports.Traces.currentTracingState;
17568
+ ts.addData("INFO", { method: Utils.getMethodName(methodDefinition) });
15348
17569
  if (typeof callback !== "function") {
15349
- return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`);
17570
+ return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(methodDefinition)}`);
15350
17571
  }
15351
17572
  const wrappedCallback = async (context, resultCallback) => {
15352
17573
  try {
@@ -15384,6 +17605,8 @@ class Server {
15384
17605
  if (methodFilter === undefined) {
15385
17606
  return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");
15386
17607
  }
17608
+ const ts = distExports.Traces.currentTracingState;
17609
+ ts.addData("INFO", { method: Utils.getMethodName(methodFilter) });
15387
17610
  if (typeof methodFilter === "function") {
15388
17611
  await this.unregisterWithPredicate(methodFilter, forStream);
15389
17612
  return;
@@ -15473,33 +17696,62 @@ class Server {
15473
17696
  });
15474
17697
  }
15475
17698
  onMethodInvoked(methodToExecute, invocationId, invocationArgs) {
15476
- if (!methodToExecute || !methodToExecute.theFunction) {
15477
- return;
15478
- }
15479
- methodToExecute.theFunction(invocationArgs, (err, result) => {
15480
- if (err !== undefined && err !== null) {
15481
- if (err.message && typeof err.message === "string") {
15482
- err = err.message;
15483
- }
15484
- else if (typeof err !== "string") {
15485
- try {
15486
- err = JSON.stringify(err);
17699
+ const propagationInfo = distExports.Traces.extractPropagationInfo(invocationArgs.args, true);
17700
+ distExports.withSpan("interopio.api.interop.register.callback", { method: methodToExecute?.definition?.name }, propagationInfo, (ts) => {
17701
+ ts.addData("INFO", { method: methodToExecute?.definition?.name });
17702
+ ts.addData("INFO", { invocationId });
17703
+ ts.addData("INFO", { invoker: invocationArgs?.instance });
17704
+ ts.addData("DIAGNOSTIC", { arguments: invocationArgs?.args });
17705
+ if (!methodToExecute || !methodToExecute.theFunction) {
17706
+ ts.status = { code: distExports.SpanStatusCode.ERROR, message: "Required argument 'methodToExecute' is missing." };
17707
+ return;
17708
+ }
17709
+ let resolveWithSpanCallback;
17710
+ const withSpanCallbackPromise = new Promise(resolve => {
17711
+ resolveWithSpanCallback = resolve;
17712
+ });
17713
+ methodToExecute.theFunction(invocationArgs, (err, result) => {
17714
+ if (err !== undefined && err !== null) {
17715
+ if (err.message && typeof err.message === "string") {
17716
+ err = err.message;
15487
17717
  }
15488
- catch (unStrException) {
15489
- err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`;
17718
+ else if (typeof err !== "string") {
17719
+ try {
17720
+ err = JSON.stringify(err);
17721
+ }
17722
+ catch (unStrException) {
17723
+ err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`;
17724
+ }
15490
17725
  }
17726
+ ts.status = { code: distExports.SpanStatusCode.ERROR, message: err };
17727
+ ts.recordException(err);
15491
17728
  }
15492
- }
15493
- if (!result) {
15494
- result = {};
15495
- }
15496
- else if (typeof result !== "object" || Array.isArray(result)) {
15497
- result = { _value: result };
15498
- }
15499
- this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result);
17729
+ if (!result) {
17730
+ result = {};
17731
+ }
17732
+ else if (typeof result !== "object" || Array.isArray(result)) {
17733
+ result = { _value: result };
17734
+ }
17735
+ ts.addData("DIAGNOSTIC", { returnValue: result });
17736
+ this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result);
17737
+ resolveWithSpanCallback();
17738
+ });
17739
+ return withSpanCallbackPromise;
15500
17740
  });
15501
17741
  }
15502
17742
  }
17743
+ __decorate([
17744
+ distExports.withSpan("interopio.api.interop.stream.create", { argMapping: (methodDefinition) => ({ stream: Utils.getMethodName(methodDefinition) }) })
17745
+ ], Server.prototype, "createStream", null);
17746
+ __decorate([
17747
+ distExports.withSpan("interopio.api.interop.register", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17748
+ ], Server.prototype, "register", null);
17749
+ __decorate([
17750
+ distExports.withSpan("interopio.api.interop.register.async", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17751
+ ], Server.prototype, "registerAsync", null);
17752
+ __decorate([
17753
+ distExports.withSpan("interopio.api.interop.unregister", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17754
+ ], Server.prototype, "unregister", null);
15503
17755
 
15504
17756
  class InstanceWrapper {
15505
17757
  wrapped = {};
@@ -16336,6 +18588,7 @@ class ClientStreaming {
16336
18588
  session.on("subscription-cancelled", this.handleSubscriptionCancelled);
16337
18589
  }
16338
18590
  subscribe(streamingMethod, params, targetServers, success, error, existingSub) {
18591
+ distExports.Traces.removePropagationInfo(params.arguments);
16339
18592
  if (targetServers.length === 0) {
16340
18593
  error({
16341
18594
  method: streamingMethod,
@@ -16471,7 +18724,7 @@ class ClientStreaming {
16471
18724
  "{}";
16472
18725
  pendingSub.error({
16473
18726
  message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs,
16474
- called_with: pendingSub.params.arguments,
18727
+ called_with: distExports.Traces.removePropagationInfo(pendingSub.params.arguments),
16475
18728
  method: pendingSub.method,
16476
18729
  });
16477
18730
  }
@@ -16539,7 +18792,7 @@ class ClientStreaming {
16539
18792
  const isPrivateData = msg.oob;
16540
18793
  const sendingServerId = trackedServersFound[0].serverId;
16541
18794
  const server = this.repository.getServerById(sendingServerId);
16542
- const receivedStreamData = () => {
18795
+ const getReceivedStreamData = () => {
16543
18796
  return {
16544
18797
  data: msg.data,
16545
18798
  server: server?.instance ?? {},
@@ -16550,16 +18803,29 @@ class ClientStreaming {
16550
18803
  };
16551
18804
  const onDataHandlers = subscription.handlers.onData;
16552
18805
  const queuedData = subscription.queued.data;
16553
- if (onDataHandlers.length > 0) {
16554
- onDataHandlers.forEach((callback) => {
16555
- if (typeof callback === "function") {
16556
- callback(receivedStreamData());
16557
- }
16558
- });
16559
- }
16560
- else {
16561
- queuedData.push(receivedStreamData());
16562
- }
18806
+ const rsd = getReceivedStreamData();
18807
+ const pi = distExports.Traces.extractPropagationInfo(rsd.data, true);
18808
+ const methodName = subscription?.method?.name;
18809
+ distExports.withSpan("interopio.api.interop.stream.onData", {
18810
+ method: methodName,
18811
+ stream: methodName
18812
+ }, pi, () => {
18813
+ const ts = distExports.Traces.currentTracingState;
18814
+ ts.addData("INFO", { method: methodName });
18815
+ ts.addData("INFO", { stream: methodName });
18816
+ ts.addData("INFO", { handlerCount: onDataHandlers?.length });
18817
+ ts.addData("DIAGNOSTIC", { data: rsd });
18818
+ if (onDataHandlers.length > 0) {
18819
+ onDataHandlers.forEach((callback) => {
18820
+ if (typeof callback === "function") {
18821
+ callback(deepClone(rsd));
18822
+ }
18823
+ });
18824
+ }
18825
+ else {
18826
+ queuedData.push(deepClone(rsd));
18827
+ }
18828
+ });
16563
18829
  };
16564
18830
  handleSubscriptionCancelled = (msg) => {
16565
18831
  const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id];
@@ -16957,7 +19223,16 @@ class MessageBus {
16957
19223
  return this.readyPromise;
16958
19224
  }
16959
19225
  publish = (topic, data, options) => {
19226
+ this.publishCore(topic, data, options);
19227
+ };
19228
+ publishCore(topic, data, options) {
16960
19229
  const { routingKey, target } = options || {};
19230
+ const ts = distExports.Traces.currentTracingState;
19231
+ ts.addData("INFO", { topic });
19232
+ ts.addData("DIAGNOSTIC", { data });
19233
+ ts.addData("INFO", { routingKey, target });
19234
+ data = deepClone(data);
19235
+ ts.injectPropagationInfo(data);
16961
19236
  const args = this.removeEmptyValues({
16962
19237
  type: "publish",
16963
19238
  topic,
@@ -16970,10 +19245,17 @@ class MessageBus {
16970
19245
  .catch((err) => {
16971
19246
  this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`);
16972
19247
  });
16973
- };
19248
+ }
19249
+ ;
16974
19250
  subscribe = (topic, callback, options) => {
19251
+ return this.subscribeCore(topic, callback, options);
19252
+ };
19253
+ subscribeCore(topic, callback, options) {
16975
19254
  return new Promise((resolve, reject) => {
16976
19255
  const { routingKey, target } = options || {};
19256
+ const ts = distExports.Traces.currentTracingState;
19257
+ ts.addData("INFO", { topic });
19258
+ ts.addData("INFO", { routingKey, target });
16977
19259
  const args = this.removeEmptyValues({
16978
19260
  type: "subscribe",
16979
19261
  topic,
@@ -16984,7 +19266,16 @@ class MessageBus {
16984
19266
  this.session.send(args)
16985
19267
  .then((response) => {
16986
19268
  const { subscription_id } = response;
16987
- this.subscriptions.push({ subscription_id, topic, callback, source: target });
19269
+ ts.addData("INFO", { subscription_id });
19270
+ const tracedCallback = function (...tracedCallbackArgs) {
19271
+ const propagationInfo = distExports.Traces.extractPropagationInfo(tracedCallbackArgs?.[0], true);
19272
+ distExports.withSpan("interopio.api.bus.subscribe.callback", { topic }, propagationInfo, (cbts) => {
19273
+ cbts.addData("INFO", { topic, subscription_id });
19274
+ cbts.addData("DIAGNOSTIC", { data: tracedCallbackArgs?.[0] });
19275
+ callback.apply(this, tracedCallbackArgs);
19276
+ });
19277
+ };
19278
+ this.subscriptions.push({ subscription_id, topic, callback: tracedCallback, source: target });
16988
19279
  resolve({
16989
19280
  unsubscribe: () => {
16990
19281
  this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId })
@@ -16999,7 +19290,8 @@ class MessageBus {
16999
19290
  })
17000
19291
  .catch((error) => reject(error));
17001
19292
  });
17002
- };
19293
+ }
19294
+ ;
17003
19295
  watchOnEvent = () => {
17004
19296
  this.session.on("event", (args) => {
17005
19297
  const { data, subscription_id } = args;
@@ -17037,10 +19329,74 @@ class MessageBus {
17037
19329
  return allMatch;
17038
19330
  }
17039
19331
  }
19332
+ __decorate([
19333
+ distExports.withSpan("interopio.api.bus.publish", { argMapping: ["topic"] })
19334
+ ], MessageBus.prototype, "publishCore", null);
19335
+ __decorate([
19336
+ distExports.withSpan("interopio.api.bus.subscribe", { argMapping: ["topic"] })
19337
+ ], MessageBus.prototype, "subscribeCore", null);
19338
+
19339
+ function replaceComplexProperties(obj) {
19340
+ if (isPrimitiveOrFunction(obj)) {
19341
+ return;
19342
+ }
19343
+ for (const prop in obj) {
19344
+ if (!obj.hasOwnProperty(prop)) {
19345
+ continue;
19346
+ }
19347
+ const value = obj[prop];
19348
+ if (isPrimitiveOrFunction(value)) {
19349
+ continue;
19350
+ }
19351
+ if (isPlainObject$2(value) || Array.isArray(value)) {
19352
+ replaceComplexProperties(value);
19353
+ continue;
19354
+ }
19355
+ obj[prop] = value?.constructor?.name || value.toString();
19356
+ }
19357
+ }
19358
+ function isPrimitiveOrFunction(obj) {
19359
+ if (!obj) {
19360
+ return true;
19361
+ }
19362
+ if (obj !== Object(obj)) {
19363
+ return true;
19364
+ }
19365
+ if (typeof obj === "function") {
19366
+ return true;
19367
+ }
19368
+ return false;
19369
+ }
19370
+
19371
+ async function loadInsightsPlugins(logger, settings) {
19372
+ try {
19373
+ (await import('@interopio/insights-base')).init();
19374
+ }
19375
+ catch {
19376
+ logger.warn("@interopio/insights-base plugin failed to load, insights will be disabled");
19377
+ }
19378
+ if (settings.metrics?.enabled) {
19379
+ try {
19380
+ (await import('@interopio/insights-metrics')).init();
19381
+ }
19382
+ catch {
19383
+ logger.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled");
19384
+ }
19385
+ }
19386
+ if (settings.traces?.enabled) {
19387
+ try {
19388
+ (await import('@interopio/insights-traces')).init();
19389
+ }
19390
+ catch {
19391
+ logger.warn("@interopio/insights-traces plugin failed to load, insights traces functionality will be disabled");
19392
+ }
19393
+ }
19394
+ }
17040
19395
 
17041
19396
  const IOConnectCoreFactory = (userConfig, ext) => {
17042
19397
  const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined;
17043
19398
  const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve();
19399
+ const glueReadyPromiseWrapper = new PromiseWrapper();
17044
19400
  const glueInitTimer = timer("glue");
17045
19401
  userConfig = userConfig || {};
17046
19402
  ext = ext || {};
@@ -17051,6 +19407,7 @@ const IOConnectCoreFactory = (userConfig, ext) => {
17051
19407
  let _metrics;
17052
19408
  let _contexts;
17053
19409
  let _bus;
19410
+ let _insights;
17054
19411
  let _allowTrace;
17055
19412
  const libs = {};
17056
19413
  function registerLib(name, inner, t) {
@@ -17214,6 +19571,43 @@ const IOConnectCoreFactory = (userConfig, ext) => {
17214
19571
  registerLib("bus", _bus, initTimer);
17215
19572
  return Promise.resolve();
17216
19573
  }
19574
+ async function setupInsights(interop) {
19575
+ const initTimer = timer("insights");
19576
+ const settings = await internalConfig.getInsights(iodesktop, interop, _logger);
19577
+ internalConfig.insights = settings;
19578
+ try {
19579
+ const builder = new distExports.Builder();
19580
+ const insightsLogger = _logger.subLogger("insights");
19581
+ if (settings.enabled) {
19582
+ await loadInsightsPlugins(insightsLogger, settings);
19583
+ }
19584
+ builder.withSettings(settings);
19585
+ builder.withLogger(new distExports.Log4jsWrapper(insightsLogger));
19586
+ builder.withMetrics();
19587
+ const INSIGHTS_PI_STORAGE = "___insights_pi_storage___";
19588
+ builder.withTraces()
19589
+ .withTraceLogger(new distExports.Log4jsWrapper(insightsLogger.subLogger("traces")))
19590
+ .withPropagationInfoStorage((source, pi) => _contexts?.update(INSIGHTS_PI_STORAGE, { [source.replace(/[.]/g, "_!_")]: { pi } }), (source) => _contexts?.get(INSIGHTS_PI_STORAGE)?.then(x => x[source.replace(/[.]/g, "_!_")]?.pi) ?? Promise.resolve(null));
19591
+ const container = builder.build();
19592
+ await container.start();
19593
+ registerLib("insights", container, initTimer);
19594
+ distExports.Traces.withSpan("interopio.api.startup", () => glueReadyPromiseWrapper.promise);
19595
+ _insights = container;
19596
+ return Promise.resolve();
19597
+ }
19598
+ catch (e) {
19599
+ initTimer.stop();
19600
+ _logger?.error("Error initializing insights", e);
19601
+ if (settings.failOnInitError) {
19602
+ throw e;
19603
+ }
19604
+ return Promise.resolve();
19605
+ }
19606
+ finally {
19607
+ replaceComplexProperties(internalConfig?.insights);
19608
+ replaceComplexProperties(userConfig?.insights);
19609
+ }
19610
+ }
17217
19611
  function setupExternalLibs(externalLibs) {
17218
19612
  try {
17219
19613
  externalLibs.forEach((lib) => {
@@ -17261,6 +19655,7 @@ const IOConnectCoreFactory = (userConfig, ext) => {
17261
19655
  connection: _connection,
17262
19656
  metrics: _metrics,
17263
19657
  contexts: _contexts,
19658
+ insights: _insights,
17264
19659
  bus: _bus,
17265
19660
  version: internalConfig.version,
17266
19661
  userConfig,
@@ -17329,6 +19724,7 @@ const IOConnectCoreFactory = (userConfig, ext) => {
17329
19724
  agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded");
17330
19725
  agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved");
17331
19726
  }
19727
+ glueReadyPromiseWrapper.resolve();
17332
19728
  return glue;
17333
19729
  }
17334
19730
  async function registerInstanceIfNeeded() {
@@ -17352,12 +19748,14 @@ const IOConnectCoreFactory = (userConfig, ext) => {
17352
19748
  .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()]))
17353
19749
  .then(() => _interop.readyPromise)
17354
19750
  .then(() => registerInstanceIfNeeded())
19751
+ .then(() => setupInsights(_interop))
17355
19752
  .then(() => {
17356
19753
  return setupExternalLibs(internalConfig.libs || []);
17357
19754
  })
17358
19755
  .then(waitForLibs)
17359
19756
  .then(constructGlueObject)
17360
19757
  .catch((err) => {
19758
+ glueReadyPromiseWrapper.reject({ err });
17361
19759
  return Promise.reject({
17362
19760
  err,
17363
19761
  libs