@adobe-commerce/aio-toolkit 1.0.7 → 1.0.9

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.
package/dist/index.js CHANGED
@@ -5,7 +5,11 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
9
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __esm = (fn, res) => function __init() {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ };
9
13
  var __export = (target, all) => {
10
14
  for (var name in all)
11
15
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,6 +31,429 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
31
  mod
28
32
  ));
29
33
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
35
+
36
+ // node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
37
+ var _globalThis;
38
+ var init_globalThis = __esm({
39
+ "node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js"() {
40
+ "use strict";
41
+ _globalThis = typeof globalThis === "object" ? globalThis : global;
42
+ }
43
+ });
44
+
45
+ // node_modules/@opentelemetry/api/build/esm/platform/node/index.js
46
+ var init_node = __esm({
47
+ "node_modules/@opentelemetry/api/build/esm/platform/node/index.js"() {
48
+ "use strict";
49
+ init_globalThis();
50
+ }
51
+ });
52
+
53
+ // node_modules/@opentelemetry/api/build/esm/platform/index.js
54
+ var init_platform = __esm({
55
+ "node_modules/@opentelemetry/api/build/esm/platform/index.js"() {
56
+ "use strict";
57
+ init_node();
58
+ }
59
+ });
60
+
61
+ // node_modules/@opentelemetry/api/build/esm/version.js
62
+ var VERSION;
63
+ var init_version = __esm({
64
+ "node_modules/@opentelemetry/api/build/esm/version.js"() {
65
+ "use strict";
66
+ VERSION = "1.9.0";
67
+ }
68
+ });
69
+
70
+ // node_modules/@opentelemetry/api/build/esm/internal/semver.js
71
+ function _makeCompatibilityCheck(ownVersion) {
72
+ var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
73
+ var rejectedVersions = /* @__PURE__ */ new Set();
74
+ var myVersionMatch = ownVersion.match(re);
75
+ if (!myVersionMatch) {
76
+ return function() {
77
+ return false;
78
+ };
79
+ }
80
+ var ownVersionParsed = {
81
+ major: +myVersionMatch[1],
82
+ minor: +myVersionMatch[2],
83
+ patch: +myVersionMatch[3],
84
+ prerelease: myVersionMatch[4]
85
+ };
86
+ if (ownVersionParsed.prerelease != null) {
87
+ return /* @__PURE__ */ __name(function isExactmatch(globalVersion) {
88
+ return globalVersion === ownVersion;
89
+ }, "isExactmatch");
90
+ }
91
+ function _reject(v) {
92
+ rejectedVersions.add(v);
93
+ return false;
94
+ }
95
+ __name(_reject, "_reject");
96
+ function _accept(v) {
97
+ acceptedVersions.add(v);
98
+ return true;
99
+ }
100
+ __name(_accept, "_accept");
101
+ return /* @__PURE__ */ __name(function isCompatible2(globalVersion) {
102
+ if (acceptedVersions.has(globalVersion)) {
103
+ return true;
104
+ }
105
+ if (rejectedVersions.has(globalVersion)) {
106
+ return false;
107
+ }
108
+ var globalVersionMatch = globalVersion.match(re);
109
+ if (!globalVersionMatch) {
110
+ return _reject(globalVersion);
111
+ }
112
+ var globalVersionParsed = {
113
+ major: +globalVersionMatch[1],
114
+ minor: +globalVersionMatch[2],
115
+ patch: +globalVersionMatch[3],
116
+ prerelease: globalVersionMatch[4]
117
+ };
118
+ if (globalVersionParsed.prerelease != null) {
119
+ return _reject(globalVersion);
120
+ }
121
+ if (ownVersionParsed.major !== globalVersionParsed.major) {
122
+ return _reject(globalVersion);
123
+ }
124
+ if (ownVersionParsed.major === 0) {
125
+ if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
126
+ return _accept(globalVersion);
127
+ }
128
+ return _reject(globalVersion);
129
+ }
130
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
131
+ return _accept(globalVersion);
132
+ }
133
+ return _reject(globalVersion);
134
+ }, "isCompatible");
135
+ }
136
+ var re, isCompatible;
137
+ var init_semver = __esm({
138
+ "node_modules/@opentelemetry/api/build/esm/internal/semver.js"() {
139
+ "use strict";
140
+ init_version();
141
+ re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
142
+ __name(_makeCompatibilityCheck, "_makeCompatibilityCheck");
143
+ isCompatible = _makeCompatibilityCheck(VERSION);
144
+ }
145
+ });
146
+
147
+ // node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
148
+ function registerGlobal(type, instance, diag2, allowOverride) {
149
+ var _a;
150
+ if (allowOverride === void 0) {
151
+ allowOverride = false;
152
+ }
153
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
154
+ version: VERSION
155
+ };
156
+ if (!allowOverride && api[type]) {
157
+ var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
158
+ diag2.error(err.stack || err.message);
159
+ return false;
160
+ }
161
+ if (api.version !== VERSION) {
162
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
163
+ diag2.error(err.stack || err.message);
164
+ return false;
165
+ }
166
+ api[type] = instance;
167
+ diag2.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
168
+ return true;
169
+ }
170
+ function getGlobal(type) {
171
+ var _a, _b;
172
+ var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
173
+ if (!globalVersion || !isCompatible(globalVersion)) {
174
+ return;
175
+ }
176
+ return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
177
+ }
178
+ function unregisterGlobal(type, diag2) {
179
+ diag2.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
180
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
181
+ if (api) {
182
+ delete api[type];
183
+ }
184
+ }
185
+ var major, GLOBAL_OPENTELEMETRY_API_KEY, _global;
186
+ var init_global_utils = __esm({
187
+ "node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() {
188
+ "use strict";
189
+ init_platform();
190
+ init_version();
191
+ init_semver();
192
+ major = VERSION.split(".")[0];
193
+ GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
194
+ _global = _globalThis;
195
+ __name(registerGlobal, "registerGlobal");
196
+ __name(getGlobal, "getGlobal");
197
+ __name(unregisterGlobal, "unregisterGlobal");
198
+ }
199
+ });
200
+
201
+ // node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
202
+ function logProxy(funcName, namespace, args) {
203
+ var logger = getGlobal("diag");
204
+ if (!logger) {
205
+ return;
206
+ }
207
+ args.unshift(namespace);
208
+ return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
209
+ }
210
+ var __read, __spreadArray, DiagComponentLogger;
211
+ var init_ComponentLogger = __esm({
212
+ "node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() {
213
+ "use strict";
214
+ init_global_utils();
215
+ __read = function(o, n) {
216
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
217
+ if (!m) return o;
218
+ var i = m.call(o), r, ar = [], e;
219
+ try {
220
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
221
+ } catch (error) {
222
+ e = { error };
223
+ } finally {
224
+ try {
225
+ if (r && !r.done && (m = i["return"])) m.call(i);
226
+ } finally {
227
+ if (e) throw e.error;
228
+ }
229
+ }
230
+ return ar;
231
+ };
232
+ __spreadArray = function(to, from, pack) {
233
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
234
+ if (ar || !(i in from)) {
235
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
236
+ ar[i] = from[i];
237
+ }
238
+ }
239
+ return to.concat(ar || Array.prototype.slice.call(from));
240
+ };
241
+ DiagComponentLogger = /** @class */
242
+ (function() {
243
+ function DiagComponentLogger2(props) {
244
+ this._namespace = props.namespace || "DiagComponentLogger";
245
+ }
246
+ __name(DiagComponentLogger2, "DiagComponentLogger");
247
+ DiagComponentLogger2.prototype.debug = function() {
248
+ var args = [];
249
+ for (var _i = 0; _i < arguments.length; _i++) {
250
+ args[_i] = arguments[_i];
251
+ }
252
+ return logProxy("debug", this._namespace, args);
253
+ };
254
+ DiagComponentLogger2.prototype.error = function() {
255
+ var args = [];
256
+ for (var _i = 0; _i < arguments.length; _i++) {
257
+ args[_i] = arguments[_i];
258
+ }
259
+ return logProxy("error", this._namespace, args);
260
+ };
261
+ DiagComponentLogger2.prototype.info = function() {
262
+ var args = [];
263
+ for (var _i = 0; _i < arguments.length; _i++) {
264
+ args[_i] = arguments[_i];
265
+ }
266
+ return logProxy("info", this._namespace, args);
267
+ };
268
+ DiagComponentLogger2.prototype.warn = function() {
269
+ var args = [];
270
+ for (var _i = 0; _i < arguments.length; _i++) {
271
+ args[_i] = arguments[_i];
272
+ }
273
+ return logProxy("warn", this._namespace, args);
274
+ };
275
+ DiagComponentLogger2.prototype.verbose = function() {
276
+ var args = [];
277
+ for (var _i = 0; _i < arguments.length; _i++) {
278
+ args[_i] = arguments[_i];
279
+ }
280
+ return logProxy("verbose", this._namespace, args);
281
+ };
282
+ return DiagComponentLogger2;
283
+ })();
284
+ __name(logProxy, "logProxy");
285
+ }
286
+ });
287
+
288
+ // node_modules/@opentelemetry/api/build/esm/diag/types.js
289
+ var DiagLogLevel;
290
+ var init_types = __esm({
291
+ "node_modules/@opentelemetry/api/build/esm/diag/types.js"() {
292
+ "use strict";
293
+ (function(DiagLogLevel2) {
294
+ DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
295
+ DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
296
+ DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
297
+ DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
298
+ DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
299
+ DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
300
+ DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
301
+ })(DiagLogLevel || (DiagLogLevel = {}));
302
+ }
303
+ });
304
+
305
+ // node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
306
+ function createLogLevelDiagLogger(maxLevel, logger) {
307
+ if (maxLevel < DiagLogLevel.NONE) {
308
+ maxLevel = DiagLogLevel.NONE;
309
+ } else if (maxLevel > DiagLogLevel.ALL) {
310
+ maxLevel = DiagLogLevel.ALL;
311
+ }
312
+ logger = logger || {};
313
+ function _filterFunc(funcName, theLevel) {
314
+ var theFunc = logger[funcName];
315
+ if (typeof theFunc === "function" && maxLevel >= theLevel) {
316
+ return theFunc.bind(logger);
317
+ }
318
+ return function() {
319
+ };
320
+ }
321
+ __name(_filterFunc, "_filterFunc");
322
+ return {
323
+ error: _filterFunc("error", DiagLogLevel.ERROR),
324
+ warn: _filterFunc("warn", DiagLogLevel.WARN),
325
+ info: _filterFunc("info", DiagLogLevel.INFO),
326
+ debug: _filterFunc("debug", DiagLogLevel.DEBUG),
327
+ verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
328
+ };
329
+ }
330
+ var init_logLevelLogger = __esm({
331
+ "node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() {
332
+ "use strict";
333
+ init_types();
334
+ __name(createLogLevelDiagLogger, "createLogLevelDiagLogger");
335
+ }
336
+ });
337
+
338
+ // node_modules/@opentelemetry/api/build/esm/api/diag.js
339
+ var __read2, __spreadArray2, API_NAME, DiagAPI;
340
+ var init_diag = __esm({
341
+ "node_modules/@opentelemetry/api/build/esm/api/diag.js"() {
342
+ "use strict";
343
+ init_ComponentLogger();
344
+ init_logLevelLogger();
345
+ init_types();
346
+ init_global_utils();
347
+ __read2 = function(o, n) {
348
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
349
+ if (!m) return o;
350
+ var i = m.call(o), r, ar = [], e;
351
+ try {
352
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
353
+ } catch (error) {
354
+ e = { error };
355
+ } finally {
356
+ try {
357
+ if (r && !r.done && (m = i["return"])) m.call(i);
358
+ } finally {
359
+ if (e) throw e.error;
360
+ }
361
+ }
362
+ return ar;
363
+ };
364
+ __spreadArray2 = function(to, from, pack) {
365
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
366
+ if (ar || !(i in from)) {
367
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
368
+ ar[i] = from[i];
369
+ }
370
+ }
371
+ return to.concat(ar || Array.prototype.slice.call(from));
372
+ };
373
+ API_NAME = "diag";
374
+ DiagAPI = /** @class */
375
+ (function() {
376
+ function DiagAPI2() {
377
+ function _logProxy(funcName) {
378
+ return function() {
379
+ var args = [];
380
+ for (var _i = 0; _i < arguments.length; _i++) {
381
+ args[_i] = arguments[_i];
382
+ }
383
+ var logger = getGlobal("diag");
384
+ if (!logger)
385
+ return;
386
+ return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
387
+ };
388
+ }
389
+ __name(_logProxy, "_logProxy");
390
+ var self = this;
391
+ var setLogger = /* @__PURE__ */ __name(function(logger, optionsOrLogLevel) {
392
+ var _a, _b, _c;
393
+ if (optionsOrLogLevel === void 0) {
394
+ optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
395
+ }
396
+ if (logger === self) {
397
+ var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
398
+ self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
399
+ return false;
400
+ }
401
+ if (typeof optionsOrLogLevel === "number") {
402
+ optionsOrLogLevel = {
403
+ logLevel: optionsOrLogLevel
404
+ };
405
+ }
406
+ var oldLogger = getGlobal("diag");
407
+ var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
408
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
409
+ var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
410
+ oldLogger.warn("Current logger will be overwritten from " + stack);
411
+ newLogger.warn("Current logger will overwrite one already registered from " + stack);
412
+ }
413
+ return registerGlobal("diag", newLogger, self, true);
414
+ }, "setLogger");
415
+ self.setLogger = setLogger;
416
+ self.disable = function() {
417
+ unregisterGlobal(API_NAME, self);
418
+ };
419
+ self.createComponentLogger = function(options) {
420
+ return new DiagComponentLogger(options);
421
+ };
422
+ self.verbose = _logProxy("verbose");
423
+ self.debug = _logProxy("debug");
424
+ self.info = _logProxy("info");
425
+ self.warn = _logProxy("warn");
426
+ self.error = _logProxy("error");
427
+ }
428
+ __name(DiagAPI2, "DiagAPI");
429
+ DiagAPI2.instance = function() {
430
+ if (!this._instance) {
431
+ this._instance = new DiagAPI2();
432
+ }
433
+ return this._instance;
434
+ };
435
+ return DiagAPI2;
436
+ })();
437
+ }
438
+ });
439
+
440
+ // node_modules/@opentelemetry/api/build/esm/diag-api.js
441
+ var diag;
442
+ var init_diag_api = __esm({
443
+ "node_modules/@opentelemetry/api/build/esm/diag-api.js"() {
444
+ "use strict";
445
+ init_diag();
446
+ diag = DiagAPI.instance();
447
+ }
448
+ });
449
+
450
+ // node_modules/@opentelemetry/api/build/esm/index.js
451
+ var init_esm = __esm({
452
+ "node_modules/@opentelemetry/api/build/esm/index.js"() {
453
+ "use strict";
454
+ init_diag_api();
455
+ }
456
+ });
30
457
 
31
458
  // src/index.ts
32
459
  var index_exports = {};
@@ -50,6 +477,7 @@ __export(index_exports, {
50
477
  ImsToken: () => ims_token_default,
51
478
  InfiniteLoopBreaker: () => infinite_loop_breaker_default,
52
479
  IoEventsGlobals: () => IoEventsGlobals,
480
+ JsonMessageProcessor: () => JsonMessageProcessor,
53
481
  Oauth1aConnection: () => oauth1a_connection_default,
54
482
  OnboardCommerce: () => onboard_commerce_default,
55
483
  OnboardEvents: () => onboard_events_default,
@@ -68,6 +496,9 @@ __export(index_exports, {
68
496
  ShippingCarrierMethod: () => method_default,
69
497
  ShippingCarrierResponse: () => response_default3,
70
498
  SignatureVerification: () => SignatureVerification,
499
+ SuccessChecker: () => SuccessChecker,
500
+ Telemetry: () => telemetry_default,
501
+ TelemetryInputError: () => TelemetryInputError,
71
502
  Validator: () => validator_default,
72
503
  WebhookAction: () => webhook_action_default,
73
504
  WebhookActionOperation: () => WebhookActionOperation,
@@ -75,9 +506,6 @@ __export(index_exports, {
75
506
  });
76
507
  module.exports = __toCommonJS(index_exports);
77
508
 
78
- // src/framework/runtime-action/index.ts
79
- var import_aio_sdk = require("@adobe/aio-sdk");
80
-
81
509
  // src/framework/runtime-action/types.ts
82
510
  var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
83
511
  HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
@@ -140,178 +568,1266 @@ __name(_RuntimeActionResponse, "RuntimeActionResponse");
140
568
  var RuntimeActionResponse = _RuntimeActionResponse;
141
569
  var response_default = RuntimeActionResponse;
142
570
 
143
- // src/framework/runtime-action/parameters/index.ts
144
- var _Parameters = class _Parameters {
571
+ // src/framework/runtime-action/validator/index.ts
572
+ var _Validator = class _Validator {
145
573
  /**
146
- * Returns a log-ready string of the action input parameters.
147
- * The `Authorization` header content will be replaced by '<hidden>'.
574
+ * Returns the list of missing keys given an object and its required keys.
575
+ * A parameter is missing if its value is undefined or ''.
576
+ * A value of 0 or null is not considered as missing.
577
+ *
578
+ * @param obj object to check.
579
+ * @param required list of required keys.
580
+ * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'
581
+ *
582
+ * @returns array
583
+ * @private
584
+ */
585
+ static getMissingKeys(obj, required) {
586
+ return required.filter((r) => {
587
+ const splits = r.split(".");
588
+ const last = splits[splits.length - 1];
589
+ const traverse = splits.slice(0, -1).reduce((tObj, split) => tObj[split] || {}, obj);
590
+ return last && (traverse[last] === void 0 || traverse[last] === "");
591
+ });
592
+ }
593
+ /**
594
+ * Returns the list of missing keys given an object and its required keys.
595
+ * A parameter is missing if its value is undefined or ''.
596
+ * A value of 0 or null is not considered as missing.
597
+ *
598
+ * @param params action input parameters.
599
+ * @param requiredHeaders list of required input headers.
600
+ * @param requiredParams list of required input parameters.
601
+ * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'.
602
+ *
603
+ * @returns string|null if the return value is not null, then it holds an error message describing the missing inputs.
604
+ *
605
+ */
606
+ static checkMissingRequestInputs(params, requiredParams = [], requiredHeaders = []) {
607
+ let errorMessage = null;
608
+ requiredHeaders = requiredHeaders.map((h) => h.toLowerCase());
609
+ const normalizedHeaders = Object.keys(params.__ow_headers || {}).reduce(
610
+ (acc, key) => {
611
+ acc[key.toLowerCase()] = params.__ow_headers?.[key];
612
+ return acc;
613
+ },
614
+ {}
615
+ );
616
+ const missingHeaders = _Validator.getMissingKeys(normalizedHeaders, requiredHeaders);
617
+ if (missingHeaders.length > 0) {
618
+ errorMessage = `missing header(s) '${missingHeaders.join(", ")}'`;
619
+ }
620
+ const missingParams = _Validator.getMissingKeys(params, requiredParams);
621
+ if (missingParams.length > 0) {
622
+ if (errorMessage) {
623
+ errorMessage += " and ";
624
+ } else {
625
+ errorMessage = "";
626
+ }
627
+ errorMessage += `missing parameter(s) '${missingParams.join(", ")}'`;
628
+ }
629
+ return errorMessage;
630
+ }
631
+ };
632
+ __name(_Validator, "Validator");
633
+ var Validator = _Validator;
634
+ var validator_default = Validator;
635
+
636
+ // src/framework/telemetry/index.ts
637
+ var import_aio_sdk = require("@adobe/aio-sdk");
638
+ var import_aio_lib_telemetry3 = require("@adobe/aio-lib-telemetry");
639
+
640
+ // src/framework/telemetry/new-relic/index.ts
641
+ var import_aio_lib_telemetry2 = require("@adobe/aio-lib-telemetry");
642
+
643
+ // src/framework/telemetry/helpers/input-error/index.ts
644
+ var _TelemetryInputError = class _TelemetryInputError extends Error {
645
+ /**
646
+ * Creates a new TelemetryInputError
647
+ *
648
+ * @param message - Descriptive error message explaining the validation failure
649
+ */
650
+ constructor(message) {
651
+ super(message);
652
+ this.name = "TelemetryInputError";
653
+ if (Error.captureStackTrace) {
654
+ Error.captureStackTrace(this, _TelemetryInputError);
655
+ }
656
+ }
657
+ };
658
+ __name(_TelemetryInputError, "TelemetryInputError");
659
+ var TelemetryInputError = _TelemetryInputError;
660
+
661
+ // src/framework/telemetry/new-relic/validator/index.ts
662
+ var _NewRelicTelemetryValidator = class _NewRelicTelemetryValidator {
663
+ /**
664
+ * Checks if New Relic telemetry is configured
665
+ *
666
+ * Returns true if:
667
+ * - ENABLE_TELEMETRY is explicitly set to true
668
+ * - NEW_RELIC_TELEMETRY is explicitly set to true
669
+ *
670
+ * This method does NOT validate the completeness of configuration,
671
+ * it only checks if the provider is enabled.
672
+ *
673
+ * @param params - Runtime parameters to check
674
+ * @returns true if New Relic telemetry is enabled, false otherwise
675
+ *
676
+ * @example
677
+ * ```typescript
678
+ * const validator = new NewRelicTelemetryValidator();
679
+ * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };
680
+ * if (validator.isConfigured(params)) {
681
+ * // New Relic is enabled, proceed with initialization
682
+ * }
683
+ * ```
684
+ */
685
+ isConfigured(params) {
686
+ return params.ENABLE_TELEMETRY === true && params.NEW_RELIC_TELEMETRY === true;
687
+ }
688
+ /**
689
+ * Validates New Relic specific parameters
690
+ *
691
+ * IMPORTANT: Only call this method after checking isConfigured() returns true.
692
+ * This method assumes New Relic telemetry is enabled and validates that
693
+ * all required parameters are present.
694
+ *
695
+ * Required parameters when New Relic is enabled:
696
+ * - NEW_RELIC_SERVICE_NAME must be provided
697
+ * - NEW_RELIC_LICENSE_KEY must be provided
698
+ *
699
+ * @param params - Runtime parameters to validate
700
+ * @throws {TelemetryInputError} If NEW_RELIC_SERVICE_NAME is missing
701
+ * @throws {TelemetryInputError} If NEW_RELIC_LICENSE_KEY is missing
702
+ *
703
+ * @example
704
+ * ```typescript
705
+ * const validator = new NewRelicTelemetryValidator();
706
+ * const params = {
707
+ * ENABLE_TELEMETRY: true,
708
+ * NEW_RELIC_TELEMETRY: true,
709
+ * NEW_RELIC_SERVICE_NAME: "my-service",
710
+ * NEW_RELIC_LICENSE_KEY: "license-key"
711
+ * };
712
+ *
713
+ * if (validator.isConfigured(params)) {
714
+ * validator.validateConfiguration(params); // Validates required fields
715
+ * }
716
+ * ```
717
+ */
718
+ validateConfiguration(params) {
719
+ if (params.NEW_RELIC_SERVICE_NAME === void 0 || params.NEW_RELIC_SERVICE_NAME === null || params.NEW_RELIC_SERVICE_NAME === "") {
720
+ throw new TelemetryInputError("NEW_RELIC_SERVICE_NAME is required");
721
+ }
722
+ if (params.NEW_RELIC_LICENSE_KEY === void 0 || params.NEW_RELIC_LICENSE_KEY === null || params.NEW_RELIC_LICENSE_KEY === "") {
723
+ throw new TelemetryInputError("NEW_RELIC_LICENSE_KEY is required");
724
+ }
725
+ }
726
+ };
727
+ __name(_NewRelicTelemetryValidator, "NewRelicTelemetryValidator");
728
+ var NewRelicTelemetryValidator = _NewRelicTelemetryValidator;
729
+
730
+ // src/framework/telemetry/helpers/resource-factory/index.ts
731
+ var import_aio_lib_telemetry = require("@adobe/aio-lib-telemetry");
732
+
733
+ // node_modules/@opentelemetry/resources/build/esm/ResourceImpl.js
734
+ init_esm();
735
+
736
+ // node_modules/@opentelemetry/resources/build/esm/utils.js
737
+ var isPromiseLike = /* @__PURE__ */ __name((val) => {
738
+ return val !== null && typeof val === "object" && typeof val.then === "function";
739
+ }, "isPromiseLike");
740
+
741
+ // node_modules/@opentelemetry/resources/build/esm/ResourceImpl.js
742
+ var _ResourceImpl = class _ResourceImpl {
743
+ constructor(resource, options) {
744
+ __publicField(this, "_rawAttributes");
745
+ __publicField(this, "_asyncAttributesPending", false);
746
+ __publicField(this, "_schemaUrl");
747
+ __publicField(this, "_memoizedAttributes");
748
+ const attributes = resource.attributes ?? {};
749
+ this._rawAttributes = Object.entries(attributes).map(([k, v]) => {
750
+ if (isPromiseLike(v)) {
751
+ this._asyncAttributesPending = true;
752
+ }
753
+ return [k, v];
754
+ });
755
+ this._rawAttributes = guardedRawAttributes(this._rawAttributes);
756
+ this._schemaUrl = validateSchemaUrl(options?.schemaUrl);
757
+ }
758
+ static FromAttributeList(attributes, options) {
759
+ const res = new _ResourceImpl({}, options);
760
+ res._rawAttributes = guardedRawAttributes(attributes);
761
+ res._asyncAttributesPending = attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;
762
+ return res;
763
+ }
764
+ get asyncAttributesPending() {
765
+ return this._asyncAttributesPending;
766
+ }
767
+ async waitForAsyncAttributes() {
768
+ if (!this.asyncAttributesPending) {
769
+ return;
770
+ }
771
+ for (let i = 0; i < this._rawAttributes.length; i++) {
772
+ const [k, v] = this._rawAttributes[i];
773
+ this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];
774
+ }
775
+ this._asyncAttributesPending = false;
776
+ }
777
+ get attributes() {
778
+ if (this.asyncAttributesPending) {
779
+ diag.error("Accessing resource attributes before async attributes settled");
780
+ }
781
+ if (this._memoizedAttributes) {
782
+ return this._memoizedAttributes;
783
+ }
784
+ const attrs = {};
785
+ for (const [k, v] of this._rawAttributes) {
786
+ if (isPromiseLike(v)) {
787
+ diag.debug(`Unsettled resource attribute ${k} skipped`);
788
+ continue;
789
+ }
790
+ if (v != null) {
791
+ attrs[k] ?? (attrs[k] = v);
792
+ }
793
+ }
794
+ if (!this._asyncAttributesPending) {
795
+ this._memoizedAttributes = attrs;
796
+ }
797
+ return attrs;
798
+ }
799
+ getRawAttributes() {
800
+ return this._rawAttributes;
801
+ }
802
+ get schemaUrl() {
803
+ return this._schemaUrl;
804
+ }
805
+ merge(resource) {
806
+ if (resource == null)
807
+ return this;
808
+ const mergedSchemaUrl = mergeSchemaUrl(this, resource);
809
+ const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : void 0;
810
+ return _ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions);
811
+ }
812
+ };
813
+ __name(_ResourceImpl, "ResourceImpl");
814
+ var ResourceImpl = _ResourceImpl;
815
+ function resourceFromAttributes(attributes, options) {
816
+ return ResourceImpl.FromAttributeList(Object.entries(attributes), options);
817
+ }
818
+ __name(resourceFromAttributes, "resourceFromAttributes");
819
+ function guardedRawAttributes(attributes) {
820
+ return attributes.map(([k, v]) => {
821
+ if (isPromiseLike(v)) {
822
+ return [
823
+ k,
824
+ v.catch((err) => {
825
+ diag.debug("promise rejection for resource attribute: %s - %s", k, err);
826
+ return void 0;
827
+ })
828
+ ];
829
+ }
830
+ return [k, v];
831
+ });
832
+ }
833
+ __name(guardedRawAttributes, "guardedRawAttributes");
834
+ function validateSchemaUrl(schemaUrl) {
835
+ if (typeof schemaUrl === "string" || schemaUrl === void 0) {
836
+ return schemaUrl;
837
+ }
838
+ diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl);
839
+ return void 0;
840
+ }
841
+ __name(validateSchemaUrl, "validateSchemaUrl");
842
+ function mergeSchemaUrl(old, updating) {
843
+ const oldSchemaUrl = old?.schemaUrl;
844
+ const updatingSchemaUrl = updating?.schemaUrl;
845
+ const isOldEmpty = oldSchemaUrl === void 0 || oldSchemaUrl === "";
846
+ const isUpdatingEmpty = updatingSchemaUrl === void 0 || updatingSchemaUrl === "";
847
+ if (isOldEmpty) {
848
+ return updatingSchemaUrl;
849
+ }
850
+ if (isUpdatingEmpty) {
851
+ return oldSchemaUrl;
852
+ }
853
+ if (oldSchemaUrl === updatingSchemaUrl) {
854
+ return oldSchemaUrl;
855
+ }
856
+ diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl);
857
+ return void 0;
858
+ }
859
+ __name(mergeSchemaUrl, "mergeSchemaUrl");
860
+
861
+ // src/framework/telemetry/helpers/resource-factory/index.ts
862
+ var _ResourceFactory = class _ResourceFactory {
863
+ /**
864
+ * Creates a resource with custom environment attributes
865
+ *
866
+ * Starts with the base Adobe I/O Runtime resource and optionally
867
+ * merges environment attributes. These attributes are useful for
868
+ * filtering and correlating telemetry data by deployment environment.
869
+ *
870
+ * Note: Request-specific data (like request IDs) should NOT be added to
871
+ * Resources as they are created once and reused across all requests.
872
+ * Use log attributes or span attributes for request-specific data.
873
+ *
874
+ * @param params - Runtime parameters containing optional ENVIRONMENT
875
+ * @param params.ENVIRONMENT - Environment name (e.g., "dev", "stage", "prod")
876
+ * @returns OpenTelemetry Resource with custom attributes if provided
877
+ *
878
+ * @example Without custom attributes
879
+ * ```typescript
880
+ * const factory = new ResourceFactory();
881
+ * const resource = factory.createWithEnvironment({});
882
+ * // Returns base Adobe I/O Runtime resource
883
+ * ```
884
+ *
885
+ * @example With environment
886
+ * ```typescript
887
+ * const factory = new ResourceFactory();
888
+ * const params = { ENVIRONMENT: "production" };
889
+ * const resource = factory.createWithEnvironment(params);
890
+ * // Returns resource with environment="production" attribute
891
+ * ```
892
+ */
893
+ createWithEnvironment(params) {
894
+ const baseResource = (0, import_aio_lib_telemetry.getAioRuntimeResource)();
895
+ const customAttributes = {};
896
+ if (params.ENVIRONMENT) {
897
+ customAttributes.environment = params.ENVIRONMENT;
898
+ }
899
+ if (Object.keys(customAttributes).length === 0) {
900
+ return baseResource;
901
+ }
902
+ const customResource = resourceFromAttributes(
903
+ customAttributes
904
+ );
905
+ return baseResource.merge(customResource);
906
+ }
907
+ };
908
+ __name(_ResourceFactory, "ResourceFactory");
909
+ var ResourceFactory = _ResourceFactory;
910
+
911
+ // src/framework/telemetry/helpers/success-checker/index.ts
912
+ var _SuccessChecker = class _SuccessChecker {
913
+ /**
914
+ * Determines if an action execution was successful
915
+ *
916
+ * Success criteria:
917
+ * - Response has statusCode 200
918
+ * - Body does not contain an exception operation
919
+ *
920
+ * @param result - The action execution result
921
+ * @returns true if successful, false otherwise
922
+ *
923
+ * @example Success case
924
+ * ```typescript
925
+ * const checker = new SuccessChecker();
926
+ * const result = { statusCode: 200, body: { data: 'success' } };
927
+ * checker.execute(result); // true
928
+ * ```
929
+ *
930
+ * @example Failure case - wrong status code
931
+ * ```typescript
932
+ * const checker = new SuccessChecker();
933
+ * const result = { statusCode: 500, body: { error: 'Internal error' } };
934
+ * checker.execute(result); // false
935
+ * ```
936
+ *
937
+ * @example Failure case - exception in body
938
+ * ```typescript
939
+ * const checker = new SuccessChecker();
940
+ * const result = { statusCode: 200, body: { op: 'exception', message: 'Error' } };
941
+ * checker.execute(result); // false
942
+ * ```
943
+ */
944
+ execute(result) {
945
+ if (!result || typeof result !== "object") {
946
+ return false;
947
+ }
948
+ const actionResult = result;
949
+ if (actionResult.statusCode !== 200) {
950
+ return false;
951
+ }
952
+ if (actionResult.body && typeof actionResult.body === "object") {
953
+ return actionResult.body.op !== "exception";
954
+ }
955
+ return true;
956
+ }
957
+ };
958
+ __name(_SuccessChecker, "SuccessChecker");
959
+ var SuccessChecker = _SuccessChecker;
960
+
961
+ // src/framework/telemetry/new-relic/index.ts
962
+ var import_otel = require("@adobe/aio-lib-telemetry/otel");
963
+
964
+ // src/framework/telemetry/helpers/json-message-processor/index.ts
965
+ var _JsonMessageProcessor = class _JsonMessageProcessor {
966
+ /**
967
+ * Creates a new JsonMessageProcessor
968
+ *
969
+ * @param wrappedProcessor - The log processor to wrap and enhance
970
+ *
971
+ * @example
972
+ * ```typescript
973
+ * const exporter = new OTLPLogExporterProto({
974
+ * url: "https://otlp.nr-data.net/v1/logs",
975
+ * headers: { "api-key": licenseKey }
976
+ * });
977
+ * const baseProcessor = new SimpleLogRecordProcessor(exporter);
978
+ * const processor = new JsonMessageProcessor(baseProcessor);
979
+ * ```
980
+ */
981
+ constructor(wrappedProcessor) {
982
+ this.wrappedProcessor = wrappedProcessor;
983
+ }
984
+ /**
985
+ * Parse JavaScript object notation and convert to proper object
986
+ *
987
+ * Handles Winston's util.inspect format which produces JavaScript
988
+ * object literals instead of JSON strings.
989
+ *
990
+ * Examples:
991
+ * - { key: 'value' } → {"key":"value"}
992
+ * - { 'accept-encoding': 'gzip' } → {"accept-encoding":"gzip"}
993
+ *
994
+ * @param str - JavaScript object notation string
995
+ * @returns Parsed object
996
+ * @throws Error if parsing fails
997
+ * @private
998
+ */
999
+ parseJavaScriptObjectNotation(str) {
1000
+ const func = new Function("return (" + str + ")");
1001
+ return func();
1002
+ }
1003
+ /**
1004
+ * Flatten nested objects into dot-notation keys
1005
+ *
1006
+ * Converts nested structures like:
1007
+ * { headers: { accept: '*' } }
1008
+ *
1009
+ * Into flat structure:
1010
+ * { 'headers.accept': '*' }
1011
+ *
1012
+ * This makes all attributes searchable in observability platforms.
1013
+ *
1014
+ * @param obj - Object to flatten
1015
+ * @param prefix - Current key prefix (used in recursion)
1016
+ * @returns Flattened object with dot-notation keys
1017
+ * @private
1018
+ */
1019
+ flattenObject(obj, prefix = "") {
1020
+ const flattened = {};
1021
+ for (const [key, value] of Object.entries(obj)) {
1022
+ const newKey = prefix ? `${prefix}.${key}` : key;
1023
+ if (value === null || value === void 0) {
1024
+ flattened[newKey] = value;
1025
+ } else if (Array.isArray(value)) {
1026
+ flattened[newKey] = JSON.stringify(value);
1027
+ } else if (typeof value === "object") {
1028
+ if (Object.keys(value).length === 0) {
1029
+ continue;
1030
+ }
1031
+ const nested = this.flattenObject(value, newKey);
1032
+ Object.assign(flattened, nested);
1033
+ } else {
1034
+ flattened[newKey] = value;
1035
+ }
1036
+ }
1037
+ return flattened;
1038
+ }
1039
+ /**
1040
+ * Processes a log record by parsing JSON messages and extracting attributes
1041
+ *
1042
+ * This method intercepts log records, attempts to parse structured data
1043
+ * from the message body, and merges extracted properties as attributes.
1044
+ * Additionally, it extracts the log level from the severity information
1045
+ * and adds it as a 'level' attribute for easier querying.
1046
+ *
1047
+ * The enhanced log record is then passed to the wrapped processor.
1048
+ *
1049
+ * @param logRecord - The log record to process
1050
+ *
1051
+ * @remarks
1052
+ * Processing steps:
1053
+ * 1. Extract log level from severityText or severityNumber
1054
+ * 2. Add 'level' attribute (debug, info, warn, error, etc.)
1055
+ * 3. Parse JSON bodies that start with '{'
1056
+ * 4. Extract properties as individual attributes
1057
+ * 5. Preserve 'message' field as primary log body
1058
+ *
1059
+ * Error handling:
1060
+ * - Silently handles parsing errors to avoid breaking the logging pipeline
1061
+ * - Failed parsing results in unmodified log record
1062
+ */
1063
+ onEmit(logRecord) {
1064
+ try {
1065
+ if (logRecord.severityText) {
1066
+ logRecord.setAttribute("level", logRecord.severityText.toLowerCase());
1067
+ } else if (logRecord.severityNumber !== void 0) {
1068
+ const levelName = this.mapSeverityNumberToLevel(logRecord.severityNumber);
1069
+ if (levelName) {
1070
+ logRecord.setAttribute("level", levelName);
1071
+ }
1072
+ }
1073
+ const body = logRecord.body;
1074
+ if (typeof body === "string" && body.trim().startsWith("{")) {
1075
+ let parsed = null;
1076
+ try {
1077
+ parsed = JSON.parse(body);
1078
+ } catch {
1079
+ try {
1080
+ parsed = this.parseJavaScriptObjectNotation(body);
1081
+ } catch {
1082
+ }
1083
+ }
1084
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1085
+ const messageValue = parsed.message;
1086
+ const { message, ...attributesObj } = parsed;
1087
+ const flattenedAttributes = this.flattenObject(attributesObj);
1088
+ Object.entries(flattenedAttributes).forEach(([key, value]) => {
1089
+ if (value !== void 0 && value !== null) {
1090
+ logRecord.setAttribute(key, value);
1091
+ }
1092
+ });
1093
+ if (messageValue) {
1094
+ logRecord.body = messageValue;
1095
+ }
1096
+ }
1097
+ }
1098
+ } catch {
1099
+ }
1100
+ this.wrappedProcessor.onEmit(logRecord);
1101
+ }
1102
+ /**
1103
+ * Maps OpenTelemetry severity number to log level name
1104
+ *
1105
+ * OpenTelemetry defines severity numbers from 1-24:
1106
+ * - 1-4: TRACE
1107
+ * - 5-8: DEBUG
1108
+ * - 9-12: INFO
1109
+ * - 13-16: WARN
1110
+ * - 17-20: ERROR
1111
+ * - 21-24: FATAL
1112
+ *
1113
+ * @param severityNumber - OpenTelemetry severity number
1114
+ * @returns Log level name (trace, debug, info, warn, error, fatal) or null
1115
+ * @private
1116
+ */
1117
+ mapSeverityNumberToLevel(severityNumber) {
1118
+ if (severityNumber >= 1 && severityNumber <= 4) return "trace";
1119
+ if (severityNumber >= 5 && severityNumber <= 8) return "debug";
1120
+ if (severityNumber >= 9 && severityNumber <= 12) return "info";
1121
+ if (severityNumber >= 13 && severityNumber <= 16) return "warn";
1122
+ if (severityNumber >= 17 && severityNumber <= 20) return "error";
1123
+ if (severityNumber >= 21 && severityNumber <= 24) return "fatal";
1124
+ return null;
1125
+ }
1126
+ /**
1127
+ * Forces the processor to flush any pending log records
1128
+ *
1129
+ * Delegates to the wrapped processor's forceFlush method.
1130
+ * Useful for ensuring logs are sent before application shutdown.
1131
+ *
1132
+ * @returns Promise that resolves when flush is complete
1133
+ *
1134
+ * @example
1135
+ * ```typescript
1136
+ * await processor.forceFlush();
1137
+ * console.log("All logs have been sent");
1138
+ * ```
1139
+ */
1140
+ async forceFlush() {
1141
+ return this.wrappedProcessor.forceFlush();
1142
+ }
1143
+ /**
1144
+ * Shuts down the processor and releases resources
1145
+ *
1146
+ * Delegates to the wrapped processor's shutdown method.
1147
+ * Should be called when the application is terminating.
1148
+ *
1149
+ * @returns Promise that resolves when shutdown is complete
1150
+ *
1151
+ * @example
1152
+ * ```typescript
1153
+ * await processor.shutdown();
1154
+ * console.log("Processor has been shut down");
1155
+ * ```
1156
+ */
1157
+ async shutdown() {
1158
+ return this.wrappedProcessor.shutdown();
1159
+ }
1160
+ };
1161
+ __name(_JsonMessageProcessor, "JsonMessageProcessor");
1162
+ var JsonMessageProcessor = _JsonMessageProcessor;
1163
+
1164
+ // src/framework/telemetry/new-relic/index.ts
1165
+ var _NewRelicTelemetry = class _NewRelicTelemetry {
1166
+ /**
1167
+ * Constructor for New Relic telemetry
1168
+ *
1169
+ * @description Constructor for New Relic telemetry
1170
+ * @example
1171
+ * ```typescript
1172
+ * const telemetry = new NewRelicTelemetry();
1173
+ * ```
1174
+ */
1175
+ constructor() {
1176
+ this.validator = new NewRelicTelemetryValidator();
1177
+ this.successChecker = new SuccessChecker();
1178
+ this.resourceFactory = new ResourceFactory();
1179
+ }
1180
+ /**
1181
+ * Checks if New Relic telemetry can be initialized
1182
+ *
1183
+ * Determines if New Relic telemetry is properly configured without actually
1184
+ * attempting initialization. Useful for provider chain fallback logic.
1185
+ *
1186
+ * @param params - Runtime parameters to check
1187
+ * @returns true if New Relic is configured and can be initialized
1188
+ *
1189
+ * @example
1190
+ * ```typescript
1191
+ * const telemetry = new NewRelicTelemetry();
1192
+ * if (telemetry.canInitialize(params)) {
1193
+ * // New Relic is configured, use it
1194
+ * } else {
1195
+ * // Try next provider
1196
+ * }
1197
+ * ```
1198
+ */
1199
+ canInitialize(params) {
1200
+ return this.validator.isConfigured(params);
1201
+ }
1202
+ /**
1203
+ * Get the OpenTelemetry instrumentation configuration for New Relic
1204
+ *
1205
+ * Builds and returns the complete instrumentation configuration including:
1206
+ * - Service name and preset instrumentations
1207
+ * - Custom resource attributes (environment)
1208
+ * - OTLP exporters for traces, metrics, and logs
1209
+ * - Success/failure detection for actions
1210
+ *
1211
+ * This method is called internally by `instrumentEntrypoint` to configure
1212
+ * telemetry before wrapping the action.
1213
+ *
1214
+ * @returns Complete entrypoint instrumentation configuration
1215
+ * @throws {TelemetryInputError} If required parameters are missing (service name, license key)
1216
+ *
1217
+ * @example
1218
+ * ```typescript
1219
+ * const telemetry = new NewRelicTelemetry();
1220
+ * const config = telemetry.getConfig();
1221
+ * // Returns configuration with exporters, instrumentations, and resource attributes
1222
+ * ```
1223
+ */
1224
+ getConfig() {
1225
+ return {
1226
+ ...(0, import_aio_lib_telemetry2.defineTelemetryConfig)((params) => {
1227
+ if (!this.validator.isConfigured(params)) {
1228
+ throw new Error("New Relic telemetry is not configured");
1229
+ }
1230
+ this.validator.validateConfiguration(params);
1231
+ const serviceName = params.NEW_RELIC_SERVICE_NAME;
1232
+ return {
1233
+ sdkConfig: {
1234
+ serviceName,
1235
+ instrumentations: (0, import_aio_lib_telemetry2.getPresetInstrumentations)("simple"),
1236
+ resource: this.resourceFactory.createWithEnvironment(params),
1237
+ ...this.getExportersConfig(params)
1238
+ }
1239
+ };
1240
+ }),
1241
+ isSuccessful: this.successChecker.execute.bind(this.successChecker)
1242
+ };
1243
+ }
1244
+ /**
1245
+ * Configure New Relic exporters for traces, metrics, and logs
1246
+ *
1247
+ * Creates OTLP exporters for all three signal types (traces, metrics, logs)
1248
+ * and configures them to send data to New Relic. Log processors are wrapped
1249
+ * with JsonMessageProcessor for better attribute extraction.
1250
+ *
1251
+ * @param params - Runtime parameters containing NEW_RELIC_LICENSE_KEY and optional NEW_RELIC_URL
1252
+ * @returns Configuration object with traceExporter, metricReaders, and logRecordProcessors
1253
+ * @private
1254
+ */
1255
+ getExportersConfig(params) {
1256
+ const licenseKey = params.NEW_RELIC_LICENSE_KEY;
1257
+ const newRelicUrl = params.NEW_RELIC_URL || "https://otlp.nr-data.net";
1258
+ const makeExporterConfig = /* @__PURE__ */ __name((endpoint) => {
1259
+ return {
1260
+ url: `${newRelicUrl}/${endpoint}`,
1261
+ headers: {
1262
+ "api-key": licenseKey
1263
+ }
1264
+ };
1265
+ }, "makeExporterConfig");
1266
+ return {
1267
+ traceExporter: new import_otel.OTLPTraceExporterProto(makeExporterConfig("v1/traces")),
1268
+ metricReaders: [
1269
+ new import_otel.PeriodicExportingMetricReader({
1270
+ exporter: new import_otel.OTLPMetricExporterProto(makeExporterConfig("v1/metrics"))
1271
+ })
1272
+ ],
1273
+ logRecordProcessors: [
1274
+ new JsonMessageProcessor(
1275
+ new import_otel.SimpleLogRecordProcessor(new import_otel.OTLPLogExporterProto(makeExporterConfig("v1/logs")))
1276
+ )
1277
+ ]
1278
+ };
1279
+ }
1280
+ /**
1281
+ * Initialize telemetry instrumentation for a runtime action
1282
+ *
1283
+ * Wraps the provided action with OpenTelemetry instrumentation using
1284
+ * New Relic as the backend. The instrumented action will automatically:
1285
+ * - Create spans for the action execution
1286
+ * - Export metrics during runtime
1287
+ * - Forward logs to New Relic
1288
+ * - Track success/failure status
1289
+ *
1290
+ * This method delegates to `instrumentEntrypoint` from `@adobe/aio-lib-telemetry`,
1291
+ * passing the action and New Relic specific configuration.
1292
+ *
1293
+ * @param action - The runtime action function to instrument
1294
+ * @returns The instrumented action function with telemetry enabled
1295
+ * @throws {TelemetryInputError} If required configuration is missing
1296
+ *
1297
+ * @example
1298
+ * ```typescript
1299
+ * async function myAction(params: Record<string, unknown>) {
1300
+ * const logger = Telemetry.createLogger("my-action", params);
1301
+ * logger.info("Processing request");
1302
+ *
1303
+ * return { statusCode: 200, body: { success: true } };
1304
+ * }
1305
+ *
1306
+ * const telemetry = new NewRelicTelemetry();
1307
+ * const instrumentedAction = telemetry.initialize(myAction);
1308
+ *
1309
+ * // instrumentedAction now sends traces, metrics, and logs to New Relic
1310
+ * export const main = instrumentedAction;
1311
+ * ```
1312
+ */
1313
+ initialize(action) {
1314
+ return (0, import_aio_lib_telemetry2.instrumentEntrypoint)(action, this.getConfig());
1315
+ }
1316
+ };
1317
+ __name(_NewRelicTelemetry, "NewRelicTelemetry");
1318
+ var NewRelicTelemetry = _NewRelicTelemetry;
1319
+ var new_relic_default = NewRelicTelemetry;
1320
+
1321
+ // src/framework/telemetry/index.ts
1322
+ var _Telemetry = class _Telemetry {
1323
+ /**
1324
+ * Create a logger with standard configuration and automatic metadata injection.
1325
+ *
1326
+ * This method creates a structured logger and wraps it to automatically add
1327
+ * contextual metadata to all log calls:
1328
+ * - `x-adobe-commerce-request-id`: Extracted from `__ow_headers` (when present)
1329
+ * - `action.type`: Extracted from `params.action_type` (when present)
1330
+ *
1331
+ * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger; otherwise uses Core.Logger.
1332
+ * The environment from params.ENVIRONMENT is set at the resource level and will
1333
+ * automatically appear in all logs sent to New Relic if ENABLE_TELEMETRY is true.
1334
+ *
1335
+ * @param name - Logger name (typically action name)
1336
+ * @param params - Runtime parameters containing LOG_LEVEL, optional ENABLE_TELEMETRY, ENVIRONMENT, action_type, and __ow_headers
1337
+ * @returns Configured logger instance with automatic metadata injection
1338
+ *
1339
+ * @example Basic string message
1340
+ * ```typescript
1341
+ * const logger = Telemetry.createLogger("my-action", params);
1342
+ * logger.info("Processing started");
1343
+ * // Logs: "Processing started"
1344
+ * ```
1345
+ *
1346
+ * @example JSON object message with automatic metadata
1347
+ * ```typescript
1348
+ * const logger = Telemetry.createLogger("my-action", {
1349
+ * ...params,
1350
+ * action_type: "webhook",
1351
+ * __ow_headers: { 'x-adobe-commerce-request-id': 'req-123' }
1352
+ * });
1353
+ * logger.info({
1354
+ * message: "User action completed",
1355
+ * user_id: "123"
1356
+ * });
1357
+ * // In New Relic: {
1358
+ * // message: "User action completed",
1359
+ * // user_id: "123",
1360
+ * // "x-adobe-commerce-request-id": "req-123",
1361
+ * // "action.type": "webhook",
1362
+ * // environment: "development",
1363
+ * // ...
1364
+ * // }
1365
+ * ```
1366
+ */
1367
+ static createLogger(name, params) {
1368
+ const baseLogger = !params.ENABLE_TELEMETRY ? import_aio_sdk.Core.Logger(name, {
1369
+ level: params.LOG_LEVEL || "info"
1370
+ }) : (0, import_aio_lib_telemetry3.getLogger)(name, {
1371
+ level: params.LOG_LEVEL || "info"
1372
+ });
1373
+ const metadata = {};
1374
+ const headers = params.__ow_headers;
1375
+ const requestId = headers?.["x-adobe-commerce-request-id"];
1376
+ if (requestId && requestId !== "") {
1377
+ metadata["x-adobe-commerce-request-id"] = requestId;
1378
+ }
1379
+ const actionType = params.action_type;
1380
+ if (actionType && actionType !== "") {
1381
+ metadata["action.type"] = actionType;
1382
+ }
1383
+ if (Object.keys(metadata).length === 0) {
1384
+ return baseLogger;
1385
+ }
1386
+ const wrapper = {
1387
+ debug: /* @__PURE__ */ __name((message) => {
1388
+ if (typeof message === "object" && message !== null) {
1389
+ baseLogger.debug({ ...metadata, ...message });
1390
+ } else {
1391
+ baseLogger.debug(message);
1392
+ }
1393
+ }, "debug"),
1394
+ info: /* @__PURE__ */ __name((message) => {
1395
+ if (typeof message === "object" && message !== null) {
1396
+ baseLogger.info({ ...metadata, ...message });
1397
+ } else {
1398
+ baseLogger.info(message);
1399
+ }
1400
+ }, "info"),
1401
+ warn: /* @__PURE__ */ __name((message) => {
1402
+ if (typeof message === "object" && message !== null) {
1403
+ baseLogger.warn({ ...metadata, ...message });
1404
+ } else {
1405
+ baseLogger.warn(message);
1406
+ }
1407
+ }, "warn"),
1408
+ error: /* @__PURE__ */ __name((message) => {
1409
+ if (typeof message === "object" && message !== null) {
1410
+ baseLogger.error({ ...metadata, ...message });
1411
+ } else {
1412
+ baseLogger.error(message);
1413
+ }
1414
+ }, "error")
1415
+ };
1416
+ return {
1417
+ ...baseLogger,
1418
+ ...wrapper
1419
+ };
1420
+ }
1421
+ /**
1422
+ * Extract structured error information for logging
1423
+ *
1424
+ * Converts Error objects into a structured format suitable for logging
1425
+ * and telemetry systems like New Relic.
148
1426
  *
149
- * @param params action input parameters.
1427
+ * @param error - Error object or unknown error value
1428
+ * @returns Structured error object with name, message, and stack trace
150
1429
  *
151
- * @returns string
1430
+ * @example
1431
+ * ```typescript
1432
+ * try {
1433
+ * // some operation
1434
+ * } catch (error) {
1435
+ * logger.error("Operation failed", Telemetry.formatError(error));
1436
+ * }
1437
+ * ```
152
1438
  */
153
- static stringify(params) {
154
- let headers = params.__ow_headers || {};
155
- if (headers.authorization) {
156
- headers = { ...headers, authorization: "<hidden>" };
1439
+ static formatError(error) {
1440
+ if (error instanceof Error) {
1441
+ return {
1442
+ error_name: error.name,
1443
+ error_message: error.message,
1444
+ error_stack: error.stack
1445
+ };
157
1446
  }
158
- return JSON.stringify({ ...params, __ow_headers: headers });
1447
+ return { error: String(error) };
159
1448
  }
160
- };
161
- __name(_Parameters, "Parameters");
162
- var Parameters = _Parameters;
163
- var parameters_default = Parameters;
164
-
165
- // src/framework/runtime-action/validator/index.ts
166
- var _Validator = class _Validator {
167
1449
  /**
168
- * Returns the list of missing keys given an object and its required keys.
169
- * A parameter is missing if its value is undefined or ''.
170
- * A value of 0 or null is not considered as missing.
1450
+ * Initialize telemetry for a runtime action with provider fallback chain
171
1451
  *
172
- * @param obj object to check.
173
- * @param required list of required keys.
174
- * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'
1452
+ * Attempts to initialize telemetry providers in the following order:
1453
+ * 1. New Relic (if NEW_RELIC_TELEMETRY=true)
1454
+ * 2. Grafana (if GRAFANA_TELEMETRY=true) - Future support
1455
+ * 3. Original action (no telemetry)
175
1456
  *
176
- * @returns array
177
- * @private
178
- */
179
- static getMissingKeys(obj, required) {
180
- return required.filter((r) => {
181
- const splits = r.split(".");
182
- const last = splits[splits.length - 1];
183
- const traverse = splits.slice(0, -1).reduce((tObj, split) => tObj[split] || {}, obj);
184
- return last && (traverse[last] === void 0 || traverse[last] === "");
185
- });
186
- }
187
- /**
188
- * Returns the list of missing keys given an object and its required keys.
189
- * A parameter is missing if its value is undefined or ''.
190
- * A value of 0 or null is not considered as missing.
1457
+ * Telemetry initialization is deferred to runtime when params are available.
1458
+ * This allows proper configuration detection and graceful fallback to the
1459
+ * next provider in the chain.
191
1460
  *
192
- * @param params action input parameters.
193
- * @param requiredHeaders list of required input headers.
194
- * @param requiredParams list of required input parameters.
195
- * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'.
1461
+ * **IMPORTANT**: If a provider is explicitly enabled (e.g., NEW_RELIC_TELEMETRY=true)
1462
+ * but has invalid configuration (missing API key, service name), a 500 error response
1463
+ * is returned to alert you of the misconfiguration. This prevents silently running
1464
+ * without telemetry when you expect it to be working.
196
1465
  *
197
- * @returns string|null if the return value is not null, then it holds an error message describing the missing inputs.
1466
+ * Environment Configuration:
1467
+ * Pass params.ENVIRONMENT to set the environment field in all logs.
1468
+ * This can be set via environment variables in your action configuration.
1469
+ *
1470
+ * @param action - The runtime action function to instrument
1471
+ * @returns The instrumented action ready for export
198
1472
  *
1473
+ * @example Single provider (New Relic) - Valid configuration
1474
+ * ```typescript
1475
+ * // Environment:
1476
+ * // ENABLE_TELEMETRY=true
1477
+ * // NEW_RELIC_TELEMETRY=true
1478
+ * // NEW_RELIC_SERVICE_NAME=my-service
1479
+ * // NEW_RELIC_LICENSE_KEY=xxxxx
1480
+ *
1481
+ * export const main = Telemetry.initialize(myAction);
1482
+ * // ✅ Uses New Relic telemetry
1483
+ * ```
1484
+ *
1485
+ * @example New Relic enabled but misconfigured - Returns error response
1486
+ * ```typescript
1487
+ * // Environment:
1488
+ * // ENABLE_TELEMETRY=true
1489
+ * // NEW_RELIC_TELEMETRY=true
1490
+ * // NEW_RELIC_SERVICE_NAME=my-service
1491
+ * // Missing NEW_RELIC_LICENSE_KEY!
1492
+ *
1493
+ * export const main = Telemetry.initialize(myAction);
1494
+ * // ❌ Returns { error: { statusCode: 500, body: { error: "Telemetry configuration error: NEW_RELIC_LICENSE_KEY is required" } } }
1495
+ * // This is intentional - you want to know your telemetry config is broken!
1496
+ * ```
1497
+ *
1498
+ * @example Multi-provider fallback
1499
+ * ```typescript
1500
+ * // Environment:
1501
+ * // ENABLE_TELEMETRY=true
1502
+ * // NEW_RELIC_TELEMETRY=false // Skip New Relic
1503
+ * // GRAFANA_TELEMETRY=true // Use Grafana instead
1504
+ *
1505
+ * export const main = Telemetry.initialize(myAction);
1506
+ * // ✅ Skips New Relic, tries Grafana (when implemented)
1507
+ * ```
1508
+ *
1509
+ * @example No telemetry
1510
+ * ```typescript
1511
+ * // Environment:
1512
+ * // ENABLE_TELEMETRY=false (or not set)
1513
+ *
1514
+ * export const main = Telemetry.initialize(myAction);
1515
+ * // ✅ Returns original action without instrumentation
1516
+ * ```
199
1517
  */
200
- static checkMissingRequestInputs(params, requiredParams = [], requiredHeaders = []) {
201
- let errorMessage = null;
202
- requiredHeaders = requiredHeaders.map((h) => h.toLowerCase());
203
- const normalizedHeaders = Object.keys(params.__ow_headers || {}).reduce(
204
- (acc, key) => {
205
- acc[key.toLowerCase()] = params.__ow_headers?.[key];
206
- return acc;
207
- },
208
- {}
209
- );
210
- const missingHeaders = _Validator.getMissingKeys(normalizedHeaders, requiredHeaders);
211
- if (missingHeaders.length > 0) {
212
- errorMessage = `missing header(s) '${missingHeaders.join(", ")}'`;
213
- }
214
- const missingParams = _Validator.getMissingKeys(params, requiredParams);
215
- if (missingParams.length > 0) {
216
- if (errorMessage) {
217
- errorMessage += " and ";
218
- } else {
219
- errorMessage = "";
1518
+ static initialize(action) {
1519
+ return async (params) => {
1520
+ const newRelicTelemetry = new new_relic_default();
1521
+ if (newRelicTelemetry.canInitialize(params)) {
1522
+ try {
1523
+ const instrumentedAction = newRelicTelemetry.initialize(action);
1524
+ return await instrumentedAction(params);
1525
+ } catch (error) {
1526
+ const errorMessage = error instanceof Error ? error.message : "Telemetry initialization failed";
1527
+ return response_default.error(
1528
+ 500 /* INTERNAL_ERROR */,
1529
+ `Telemetry configuration error: ${errorMessage}`
1530
+ );
1531
+ }
220
1532
  }
221
- errorMessage += `missing parameter(s) '${missingParams.join(", ")}'`;
222
- }
223
- return errorMessage;
1533
+ return action(params);
1534
+ };
224
1535
  }
225
1536
  };
226
- __name(_Validator, "Validator");
227
- var Validator = _Validator;
228
- var validator_default = Validator;
1537
+ __name(_Telemetry, "Telemetry");
1538
+ var Telemetry = _Telemetry;
1539
+ var telemetry_default = Telemetry;
229
1540
 
230
1541
  // src/framework/runtime-action/index.ts
231
1542
  var _RuntimeAction = class _RuntimeAction {
232
1543
  /**
233
- * @param name
234
- * @param httpMethods
235
- * @param requiredParams
236
- * @param requiredHeaders
237
- * @param action
238
- * @returns {(function(*): Promise<any>)|*}
1544
+ * Sets the action type for the next action execution
1545
+ * This is used for logging to identify different action types
1546
+ * (runtime-action, webhook-action, event-consumer-action, etc.)
1547
+ *
1548
+ * @param type - The action type identifier
1549
+ */
1550
+ static setActionType(type) {
1551
+ _RuntimeAction.actionType = type;
1552
+ }
1553
+ /**
1554
+ * Gets the current action type
1555
+ * @returns The current action type identifier
1556
+ */
1557
+ static getActionType() {
1558
+ return _RuntimeAction.actionType;
1559
+ }
1560
+ /**
1561
+ * Creates a runtime action handler with validation, logging, and telemetry
1562
+ *
1563
+ * Wraps a user-defined action function with standardized runtime functionality:
1564
+ * 1. Creates a structured logger with telemetry integration
1565
+ * 2. Logs action start, headers, and body at debug level
1566
+ * 3. Validates required parameters, headers, and HTTP methods
1567
+ * 4. Executes the user action with logger and headers context
1568
+ * 5. Logs the result and handles errors with appropriate status codes
1569
+ * 6. Integrates with OpenTelemetry for distributed tracing
1570
+ *
1571
+ * @param name - Action name used for logging and telemetry spans (default: 'main')
1572
+ * @param httpMethods - Allowed HTTP methods (GET, POST, etc.). Empty array allows all methods
1573
+ * @param requiredParams - Required parameter names in the request body
1574
+ * @param requiredHeaders - Required header names (case-insensitive)
1575
+ * @param action - User-defined action function that receives:
1576
+ * - params: All request parameters including __ow_* runtime parameters
1577
+ * - ctx: Context object with logger and headers
1578
+ * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint
1579
+ *
1580
+ * @example With All Options
1581
+ * ```typescript
1582
+ * const handler = RuntimeAction.execute(
1583
+ * 'processOrder',
1584
+ * [HttpMethod.POST],
1585
+ * ['orderId', 'customerId'],
1586
+ * ['authorization', 'x-api-key'],
1587
+ * async (params, { logger, headers }) => {
1588
+ * const { orderId, customerId } = params;
1589
+ * logger.info({ message: 'Processing order', orderId, customerId });
1590
+ *
1591
+ * // Your business logic here
1592
+ * const result = await processOrderLogic(orderId, customerId);
1593
+ *
1594
+ * return {
1595
+ * statusCode: 200,
1596
+ * body: { orderId, status: 'processed', result }
1597
+ * };
1598
+ * }
1599
+ * );
1600
+ * ```
1601
+ *
1602
+ * @example Minimal Configuration
1603
+ * ```typescript
1604
+ * const handler = RuntimeAction.execute('simpleAction', [], [], [], async (params, { logger }) => {
1605
+ * logger.info('Simple action executed');
1606
+ * return { statusCode: 200, body: { message: 'Success' } };
1607
+ * });
1608
+ * ```
239
1609
  */
240
1610
  static execute(name = "main", httpMethods = [], requiredParams = [], requiredHeaders = [], action = async (_params) => {
241
1611
  return { statusCode: 200 /* OK */, body: {} };
242
1612
  }) {
243
- return async (params) => {
244
- const logger = import_aio_sdk.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
1613
+ const runtimeAction = /* @__PURE__ */ __name(async (params) => {
1614
+ if (!params.action_type) {
1615
+ params.action_type = _RuntimeAction.getActionType();
1616
+ }
1617
+ const logger = telemetry_default.createLogger(name, params);
245
1618
  try {
246
- logger.info(`Calling the ${name} action`);
247
- logger.debug(parameters_default.stringify(params));
1619
+ logger.debug({
1620
+ message: `${name}-started`,
1621
+ action_name: name
1622
+ });
1623
+ logger.debug({
1624
+ message: `${name}-headers`,
1625
+ headers: params.__ow_headers || {}
1626
+ });
1627
+ logger.debug({
1628
+ message: `${name}-body`,
1629
+ body: params.__ow_body || {}
1630
+ });
248
1631
  const validationError = _RuntimeAction.validateRequest(
249
1632
  params,
250
1633
  requiredParams,
251
1634
  requiredHeaders,
252
1635
  httpMethods,
253
- logger
1636
+ logger,
1637
+ name
254
1638
  );
255
1639
  if (validationError) {
256
1640
  return validationError;
257
1641
  }
258
1642
  const result = await action(params, { logger, headers: params.__ow_headers || {} });
259
- logger.info(result);
1643
+ logger.debug({
1644
+ message: `${name}-completed`,
1645
+ result
1646
+ });
260
1647
  return result;
261
1648
  } catch (error) {
262
- logger.error(error);
1649
+ if (error instanceof Error) {
1650
+ logger.error({
1651
+ message: `${name}-failed`,
1652
+ error: error.message,
1653
+ stack: error.stack
1654
+ });
1655
+ } else {
1656
+ logger.error({
1657
+ message: `${name}-failed`,
1658
+ error
1659
+ });
1660
+ }
263
1661
  return response_default.error(500 /* INTERNAL_ERROR */, "server error");
264
1662
  }
265
- };
1663
+ }, "runtimeAction");
1664
+ return telemetry_default.initialize(runtimeAction);
266
1665
  }
267
- static validateRequest(params, requiredParams, requiredHeaders, httpMethods, logger) {
1666
+ /**
1667
+ * Validates incoming request against required parameters, headers, and HTTP methods
1668
+ *
1669
+ * This private method performs comprehensive request validation:
1670
+ * 1. Checks for missing required parameters in the request body
1671
+ * 2. Checks for missing required headers (case-insensitive)
1672
+ * 3. Validates the HTTP method against allowed methods list
1673
+ *
1674
+ * @param params - Request parameters including __ow_* runtime parameters
1675
+ * @param requiredParams - List of required parameter names to validate
1676
+ * @param requiredHeaders - List of required header names to validate (case-insensitive)
1677
+ * @param httpMethods - Allowed HTTP methods. Empty array skips HTTP method validation
1678
+ * @param logger - Logger instance for error logging (child logger with request ID if present)
1679
+ * @param name - Action name for logging
1680
+ * @returns RuntimeActionResponseType with error details if validation fails, null if valid
1681
+ *
1682
+ * @private
1683
+ *
1684
+ * @example Validation Error Response
1685
+ * ```typescript
1686
+ * // Missing parameter returns:
1687
+ * {
1688
+ * statusCode: 400,
1689
+ * body: { error: 'Missing required parameter: userId' }
1690
+ * }
1691
+ *
1692
+ * // Invalid HTTP method returns:
1693
+ * {
1694
+ * statusCode: 405,
1695
+ * body: { error: 'Invalid HTTP method: DELETE. Allowed methods are: GET, POST' }
1696
+ * }
1697
+ * ```
1698
+ */
1699
+ static validateRequest(params, requiredParams, requiredHeaders, httpMethods, logger, name) {
268
1700
  const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? "";
269
1701
  if (errorMessage) {
1702
+ logger.error({
1703
+ message: `${name}-validation-failed`,
1704
+ error: errorMessage
1705
+ });
270
1706
  return response_default.error(400 /* BAD_REQUEST */, errorMessage);
271
1707
  }
272
1708
  const requestMethod = params.__ow_method?.toUpperCase();
273
1709
  if (httpMethods.length > 0 && !httpMethods.includes(requestMethod)) {
274
1710
  const errorMessage2 = `Invalid HTTP method: ${params.__ow_method}. Allowed methods are: ${httpMethods.join(", ")}`;
275
- logger.error(errorMessage2);
1711
+ logger.error({
1712
+ message: `${name}-validation-failed`,
1713
+ error: errorMessage2
1714
+ });
276
1715
  return response_default.error(405 /* METHOD_NOT_ALLOWED */, errorMessage2);
277
1716
  }
278
1717
  return null;
279
1718
  }
280
1719
  };
281
1720
  __name(_RuntimeAction, "RuntimeAction");
1721
+ /**
1722
+ * Private static property to store the action type for logging
1723
+ * Can be set using setActionType() before calling execute()
1724
+ */
1725
+ _RuntimeAction.actionType = "runtime-action";
282
1726
  var RuntimeAction = _RuntimeAction;
283
1727
  var runtime_action_default = RuntimeAction;
284
1728
 
1729
+ // src/framework/runtime-action/parameters/index.ts
1730
+ var _Parameters = class _Parameters {
1731
+ /**
1732
+ * Returns a log-ready string of the action input parameters.
1733
+ * The `Authorization` header content will be replaced by '<hidden>'.
1734
+ *
1735
+ * @param params action input parameters.
1736
+ *
1737
+ * @returns string
1738
+ */
1739
+ static stringify(params) {
1740
+ let headers = params.__ow_headers || {};
1741
+ if (headers.authorization) {
1742
+ headers = { ...headers, authorization: "<hidden>" };
1743
+ }
1744
+ return JSON.stringify({ ...params, __ow_headers: headers });
1745
+ }
1746
+ };
1747
+ __name(_Parameters, "Parameters");
1748
+ var Parameters = _Parameters;
1749
+ var parameters_default = Parameters;
1750
+
285
1751
  // src/framework/event-consumer-action/index.ts
286
- var import_aio_sdk2 = require("@adobe/aio-sdk");
287
1752
  var _EventConsumerAction = class _EventConsumerAction {
288
1753
  /**
289
- * @param name
290
- * @param requiredParams
291
- * @param requiredHeaders
292
- * @param action
293
- * @returns {(function(*): Promise<any>)|*}
1754
+ * Creates an event consumer action handler with telemetry integration
1755
+ *
1756
+ * This method wraps a user-defined action with:
1757
+ * - Structured logging (all logs automatically include x-adobe-commerce-request-id if present)
1758
+ * - Request validation for required parameters and headers
1759
+ * - OpenTelemetry instrumentation
1760
+ * - Standardized error handling
1761
+ *
1762
+ * @param name - Action name for logging and observability
1763
+ * @param requiredParams - List of required parameter names to validate
1764
+ * @param requiredHeaders - List of required header names to validate (case-insensitive)
1765
+ * @param action - User's event consumer function that receives params and context
1766
+ * @returns Wrapped action handler ready for OpenWhisk runtime
1767
+ *
1768
+ * @example
1769
+ * ```typescript
1770
+ * const handler = EventConsumerAction.execute(
1771
+ * 'webhook-processor',
1772
+ * ['eventType', 'eventData'],
1773
+ * ['x-webhook-signature'],
1774
+ * async (params, { logger, headers }) => {
1775
+ * logger.info({
1776
+ * message: 'Processing webhook',
1777
+ * eventType: params.eventType
1778
+ * });
1779
+ * // Process event...
1780
+ * return { statusCode: 200, body: { processed: true } };
1781
+ * }
1782
+ * );
1783
+ * ```
294
1784
  */
295
1785
  static execute(name = "main", requiredParams = [], requiredHeaders = [], action = async (_params) => {
296
1786
  return { statusCode: 200 /* OK */, body: {} };
297
1787
  }) {
298
- return async (params) => {
299
- const logger = import_aio_sdk2.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
1788
+ const eventConsumerAction = /* @__PURE__ */ __name(async (params) => {
1789
+ params.action_type = "event-consumer-action";
1790
+ const logger = telemetry_default.createLogger(name, params);
300
1791
  try {
301
- logger.info(`Calling the ${name} action`);
302
- logger.debug(parameters_default.stringify(params));
1792
+ logger.debug({
1793
+ message: `${name}-started`,
1794
+ action_name: name
1795
+ });
1796
+ logger.debug({
1797
+ message: `${name}-headers`,
1798
+ headers: params.__ow_headers || {}
1799
+ });
1800
+ logger.debug({
1801
+ message: `${name}-parameters`,
1802
+ parameters: params
1803
+ });
303
1804
  const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) || "";
304
1805
  if (errorMessage) {
1806
+ logger.error({
1807
+ message: `${name}-validation-failed`,
1808
+ error: errorMessage
1809
+ });
305
1810
  return response_default.error(400 /* BAD_REQUEST */, errorMessage);
306
1811
  }
307
1812
  const result = await action(params, { logger, headers: params.__ow_headers || {} });
308
- logger.info(result);
1813
+ logger.debug({
1814
+ message: `${name}-completed`,
1815
+ result
1816
+ });
309
1817
  return result;
310
1818
  } catch (error) {
311
- logger.error(error);
1819
+ if (error instanceof Error) {
1820
+ logger.error({
1821
+ error: error.message,
1822
+ stack: error.stack
1823
+ });
1824
+ } else {
1825
+ logger.error({ error });
1826
+ }
312
1827
  return response_default.error(500 /* INTERNAL_ERROR */, "server error");
313
1828
  }
314
- };
1829
+ }, "eventConsumerAction");
1830
+ return telemetry_default.initialize(eventConsumerAction);
315
1831
  }
316
1832
  };
317
1833
  __name(_EventConsumerAction, "EventConsumerAction");
@@ -423,29 +1939,83 @@ var Openwhisk = _Openwhisk;
423
1939
  var openwhisk_default = Openwhisk;
424
1940
 
425
1941
  // src/framework/openwhisk-action/index.ts
426
- var import_aio_sdk3 = require("@adobe/aio-sdk");
427
1942
  var _OpenwhiskAction = class _OpenwhiskAction {
428
1943
  /**
429
- * @param name
430
- * @param action
431
- * @returns {(function(*): Promise<any>)|*}
1944
+ * Creates an OpenWhisk webhook action handler with logging and telemetry
1945
+ *
1946
+ * Wraps a user-defined action function with standardized runtime functionality:
1947
+ * 1. Creates a structured logger with telemetry integration
1948
+ * 2. Logs action start with structured data
1949
+ * 3. Logs request parameters at debug level
1950
+ * 4. Executes the user action with logger and headers context
1951
+ * 5. Logs the result and handles errors with appropriate status codes
1952
+ * 6. Integrates with OpenTelemetry for distributed tracing
1953
+ *
1954
+ * The logger automatically includes x-adobe-commerce-request-id and action.type
1955
+ * (if present) in all log messages.
1956
+ *
1957
+ * @param name - Action name used for logging and telemetry spans (default: 'main')
1958
+ * @param action - User-defined action function that receives:
1959
+ * - params: All request parameters including __ow_* runtime parameters
1960
+ * - ctx: Context object with logger and headers
1961
+ * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint
1962
+ *
1963
+ * @example Complete Example
1964
+ * ```typescript
1965
+ * const handler = OpenwhiskAction.execute(
1966
+ * 'processWebhook',
1967
+ * async (params, { logger, headers }) => {
1968
+ * logger.info({ message: 'Webhook received', event: params.event });
1969
+ *
1970
+ * // Your webhook processing logic here
1971
+ * const result = await processWebhookData(params);
1972
+ *
1973
+ * return {
1974
+ * statusCode: 200,
1975
+ * body: { status: 'processed', result }
1976
+ * };
1977
+ * }
1978
+ * );
1979
+ * ```
432
1980
  */
433
1981
  static execute(name = "main", action = async (_params) => {
434
1982
  return { statusCode: 200 /* OK */, body: {} };
435
1983
  }) {
436
- return async (params) => {
437
- const logger = import_aio_sdk3.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
1984
+ const openwhiskAction = /* @__PURE__ */ __name(async (params) => {
1985
+ params.action_type = "openwhisk-action";
1986
+ const logger = telemetry_default.createLogger(name, params);
438
1987
  try {
439
- logger.info(`Calling the ${name} webhook action`);
440
- logger.debug(parameters_default.stringify(params));
1988
+ logger.debug({
1989
+ message: `${name}-started`,
1990
+ action_name: name
1991
+ });
1992
+ logger.debug({
1993
+ message: `${name}-params`,
1994
+ params
1995
+ });
441
1996
  const result = await action(params, { logger, headers: params.__ow_headers || {} });
442
- logger.info(result);
1997
+ logger.debug({
1998
+ message: `${name}-completed`,
1999
+ result
2000
+ });
443
2001
  return result;
444
2002
  } catch (error) {
445
- logger.error(error);
2003
+ if (error instanceof Error) {
2004
+ logger.error({
2005
+ message: `${name}-failed`,
2006
+ error: error.message,
2007
+ stack: error.stack
2008
+ });
2009
+ } else {
2010
+ logger.error({
2011
+ message: `${name}-failed`,
2012
+ error
2013
+ });
2014
+ }
446
2015
  return response_default.error(500 /* INTERNAL_ERROR */, "server error");
447
2016
  }
448
- };
2017
+ }, "openwhiskAction");
2018
+ return telemetry_default.initialize(openwhiskAction);
449
2019
  }
450
2020
  };
451
2021
  __name(_OpenwhiskAction, "OpenwhiskAction");
@@ -453,7 +2023,7 @@ var OpenwhiskAction = _OpenwhiskAction;
453
2023
  var openwhisk_action_default = OpenwhiskAction;
454
2024
 
455
2025
  // src/framework/repository/file-repository/index.ts
456
- var import_aio_sdk4 = require("@adobe/aio-sdk");
2026
+ var import_aio_sdk2 = require("@adobe/aio-sdk");
457
2027
  var _FileRepository = class _FileRepository {
458
2028
  /**
459
2029
  * Creates a new FileRepository instance
@@ -553,7 +2123,6 @@ var _FileRepository = class _FileRepository {
553
2123
  const existingData = JSON.parse(buffer.toString());
554
2124
  payload = { ...existingData, ...payload };
555
2125
  }
556
- await filesLib.delete(filepath);
557
2126
  } else {
558
2127
  payload = {
559
2128
  id: fileId,
@@ -601,7 +2170,7 @@ var _FileRepository = class _FileRepository {
601
2170
  */
602
2171
  async getFiles() {
603
2172
  if (!this.files) {
604
- this.files = await import_aio_sdk4.Files.init();
2173
+ this.files = await import_aio_sdk2.Files.init();
605
2174
  }
606
2175
  return this.files;
607
2176
  }
@@ -611,7 +2180,7 @@ var FileRepository = _FileRepository;
611
2180
  var file_repository_default = FileRepository;
612
2181
 
613
2182
  // src/framework/publish-event/index.ts
614
- var import_aio_sdk5 = require("@adobe/aio-sdk");
2183
+ var import_aio_sdk3 = require("@adobe/aio-sdk");
615
2184
  var import_cloudevents = require("cloudevents");
616
2185
  var import_uuid = require("uuid");
617
2186
 
@@ -724,7 +2293,7 @@ var _PublishEvent = class _PublishEvent {
724
2293
  ...subject && { subject }
725
2294
  });
726
2295
  this.customLogger.debug(`Constructed CloudEvent with ID: ${eventId}`);
727
- const eventsClient = await import_aio_sdk5.Events.init(this.imsOrgId, this.apiKey, this.accessToken);
2296
+ const eventsClient = await import_aio_sdk3.Events.init(this.imsOrgId, this.apiKey, this.accessToken);
728
2297
  this.customLogger.debug("Adobe I/O Events client initialized successfully");
729
2298
  await eventsClient.publishEvent(cloudEvent);
730
2299
  const publishedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -999,9 +2568,14 @@ var _WebhookAction = class _WebhookAction {
999
2568
  return null;
1000
2569
  }, "verifySignature");
1001
2570
  const callback = /* @__PURE__ */ __name(async (params, ctx) => {
2571
+ const { logger } = ctx;
1002
2572
  if (signatureVerification === "enabled" /* ENABLED */) {
1003
2573
  const verificationErrorMessage = await verifySignature(params);
1004
2574
  if (verificationErrorMessage) {
2575
+ logger.error({
2576
+ message: `${name}-signature-verification-failed`,
2577
+ error: verificationErrorMessage
2578
+ });
1005
2579
  const verificationErrorResponse = response_default2.exception(verificationErrorMessage);
1006
2580
  return response_default.success(JSON.stringify(verificationErrorResponse));
1007
2581
  }
@@ -1012,12 +2586,17 @@ var _WebhookAction = class _WebhookAction {
1012
2586
  }
1013
2587
  const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? "";
1014
2588
  if (errorMessage) {
2589
+ logger.error({
2590
+ message: `${name}-validation-failed`,
2591
+ error: errorMessage
2592
+ });
1015
2593
  const errorMessageResponse = response_default2.exception(errorMessage);
1016
2594
  return response_default.success(JSON.stringify(errorMessageResponse));
1017
2595
  }
1018
2596
  const response = await action(params, ctx);
1019
2597
  return response_default.success(JSON.stringify(response));
1020
2598
  }, "callback");
2599
+ runtime_action_default.setActionType("webhook-action");
1021
2600
  return runtime_action_default.execute(name, httpMethods, [], [], callback);
1022
2601
  }
1023
2602
  };
@@ -1026,7 +2605,7 @@ var WebhookAction = _WebhookAction;
1026
2605
  var webhook_action_default = WebhookAction;
1027
2606
 
1028
2607
  // src/framework/ims-token/index.ts
1029
- var import_aio_sdk6 = require("@adobe/aio-sdk");
2608
+ var import_aio_sdk4 = require("@adobe/aio-sdk");
1030
2609
 
1031
2610
  // src/commerce/adobe-auth/index.ts
1032
2611
  var import_aio_lib_ims = require("@adobe/aio-lib-ims");
@@ -1220,6 +2799,9 @@ var _ImsToken = class _ImsToken {
1220
2799
  /**
1221
2800
  * Creates an instance of ImsToken
1222
2801
  *
2802
+ * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.
2803
+ * See class documentation for migration examples.
2804
+ *
1223
2805
  * @param clientId - OAuth client ID for Adobe IMS authentication
1224
2806
  * @param clientSecret - OAuth client secret for Adobe IMS authentication
1225
2807
  * @param technicalAccountId - Technical account ID for service-to-service authentication
@@ -1246,6 +2828,10 @@ var _ImsToken = class _ImsToken {
1246
2828
  /**
1247
2829
  * Executes IMS token generation or retrieves a cached token
1248
2830
  *
2831
+ * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.
2832
+ * The built-in caching mechanism has reliability issues with the State API.
2833
+ * See class documentation for migration examples.
2834
+ *
1249
2835
  * This method first checks for a cached token. If a valid cached token exists,
1250
2836
  * it returns that. Otherwise, it generates a new token, caches it, and returns it.
1251
2837
  *
@@ -1328,6 +2914,14 @@ var _ImsToken = class _ImsToken {
1328
2914
  /**
1329
2915
  * Caches the IMS token in the state store with TTL
1330
2916
  *
2917
+ * @deprecated This method has issues with State API reliability. Use application-level caching instead.
2918
+ *
2919
+ * **Known Issues:**
2920
+ * - State API may not be available in all runtime environments
2921
+ * - Hard-coded 10-minute buffer may not suit all use cases
2922
+ * - Minimum 60-minute TTL is opinionated and inflexible
2923
+ * - No retry mechanism for State API failures
2924
+ *
1331
2925
  * @param result - The token result containing the token and expiration time
1332
2926
  * @returns A promise that resolves to true if caching succeeded, false otherwise
1333
2927
  * @private
@@ -1353,6 +2947,13 @@ var _ImsToken = class _ImsToken {
1353
2947
  /**
1354
2948
  * Retrieves a cached IMS token from the state store
1355
2949
  *
2950
+ * @deprecated This method has issues with State API reliability. Use application-level caching instead.
2951
+ *
2952
+ * **Known Issues:**
2953
+ * - State API may not be available in all runtime environments
2954
+ * - No validation of cached token expiry
2955
+ * - Silent failures may return null without proper error context
2956
+ *
1356
2957
  * @returns A promise that resolves to the cached token string or null if not found
1357
2958
  * @private
1358
2959
  */
@@ -1378,6 +2979,14 @@ var _ImsToken = class _ImsToken {
1378
2979
  /**
1379
2980
  * Initializes and returns the state store instance
1380
2981
  *
2982
+ * @deprecated This method relies on State API which has reliability issues.
2983
+ * Use application-level caching instead.
2984
+ *
2985
+ * **Known Issues:**
2986
+ * - State API initialization may fail silently
2987
+ * - Not available outside Adobe I/O Runtime environments
2988
+ * - Caches the state instance which may become stale
2989
+ *
1381
2990
  * @returns A promise that resolves to the state instance or null if initialization fails
1382
2991
  * @private
1383
2992
  */
@@ -1385,7 +2994,7 @@ var _ImsToken = class _ImsToken {
1385
2994
  if (this.state === void 0) {
1386
2995
  try {
1387
2996
  this.customLogger.debug("Initializing State API for token caching");
1388
- this.state = await import_aio_sdk6.State.init();
2997
+ this.state = await import_aio_sdk4.State.init();
1389
2998
  } catch (error) {
1390
2999
  this.customLogger.error(`Failed to initialize State API: ${error.message}`);
1391
3000
  this.state = null;
@@ -1575,44 +3184,26 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1575
3184
  /**
1576
3185
  * Creates an instance of RuntimeApiGatewayService
1577
3186
  *
1578
- * @param clientId - OAuth client ID for Adobe IMS authentication
1579
- * @param clientSecret - OAuth client secret for Adobe IMS authentication
1580
- * @param technicalAccountId - Technical account ID for service-to-service authentication
1581
- * @param technicalAccountEmail - Technical account email for service-to-service authentication
1582
- * @param imsOrgId - IMS organization ID
1583
- * @param scopes - Array of scopes required for the token
1584
3187
  * @param namespace - The Adobe I/O Runtime namespace identifier
3188
+ * @param imsOrgId - IMS organization ID
3189
+ * @param imsToken - Bearer token string for authentication
1585
3190
  * @param logger - Optional logger instance for logging operations
1586
3191
  * @example
1587
3192
  * ```typescript
1588
3193
  * const service = new RuntimeApiGatewayService(
1589
- * 'client-id',
1590
- * 'client-secret',
1591
- * 'tech-account-id',
1592
- * 'tech@example.com',
1593
- * 'org-id',
1594
- * ['openid', 'AdobeID'],
1595
- * 'my-namespace-12345',
1596
- * logger // optional
3194
+ * 'test-namespace',
3195
+ * 'org-id@AdobeOrg',
3196
+ * 'bearer-token-string',
3197
+ * logger
1597
3198
  * );
1598
3199
  * ```
1599
3200
  */
1600
- constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, namespace, logger = null) {
3201
+ constructor(namespace, imsOrgId, imsToken, logger = null) {
1601
3202
  this.namespace = namespace;
1602
3203
  this.imsOrgId = imsOrgId;
1603
- this.customLogger = new custom_logger_default(logger);
1604
- this.imsToken = new ims_token_default(
1605
- clientId,
1606
- clientSecret,
1607
- technicalAccountId,
1608
- technicalAccountEmail,
1609
- imsOrgId,
1610
- scopes,
1611
- logger,
1612
- "runtime_api_gateway_token",
1613
- "runtime-api-gateway-context"
1614
- );
3204
+ this.imsToken = imsToken;
1615
3205
  this.restClient = new rest_client_default();
3206
+ this.customLogger = new custom_logger_default(logger);
1616
3207
  }
1617
3208
  /**
1618
3209
  * Builds the complete API endpoint URL
@@ -1627,21 +3218,13 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1627
3218
  /**
1628
3219
  * Gets the authenticated headers for API requests
1629
3220
  *
1630
- * @returns A promise that resolves with the headers object including authentication
1631
- * @throws {Error} If token generation fails
3221
+ * @returns Headers object including authentication
1632
3222
  * @private
1633
3223
  */
1634
- async getAuthenticatedHeaders() {
1635
- this.customLogger.debug("Generating authenticated headers for API request");
1636
- const token = await this.imsToken.execute();
1637
- if (!token) {
1638
- this.customLogger.error("Failed to generate IMS token for authenticated headers");
1639
- throw new Error("Failed to generate IMS token");
1640
- }
1641
- this.customLogger.debug("Successfully generated authenticated headers");
3224
+ getAuthenticatedHeaders() {
1642
3225
  return {
1643
3226
  "Content-Type": "application/json",
1644
- Authorization: `Bearer ${token}`,
3227
+ Authorization: `Bearer ${this.imsToken}`,
1645
3228
  "x-gw-ims-org-id": this.imsOrgId
1646
3229
  };
1647
3230
  }
@@ -1665,7 +3248,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1665
3248
  try {
1666
3249
  const url = this.buildEndpoint(endpoint);
1667
3250
  this.customLogger.info(`Performing GET request to: ${url}`);
1668
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
3251
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1669
3252
  this.customLogger.debug(`GET headers: ${JSON.stringify(headers)}`);
1670
3253
  const response = await this.restClient.get(url, headers, false);
1671
3254
  this.customLogger.debug(`GET response: ${JSON.stringify(response)}`);
@@ -1699,7 +3282,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1699
3282
  const url = this.buildEndpoint(endpoint);
1700
3283
  this.customLogger.info(`Performing POST request to: ${url}`);
1701
3284
  this.customLogger.debug(`POST payload: ${JSON.stringify(payload)}`);
1702
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
3285
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1703
3286
  this.customLogger.debug(`POST headers: ${JSON.stringify(headers)}`);
1704
3287
  const response = await this.restClient.post(url, headers, payload, false);
1705
3288
  this.customLogger.debug(`POST response: ${JSON.stringify(response)}`);
@@ -1733,7 +3316,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1733
3316
  const url = this.buildEndpoint(endpoint);
1734
3317
  this.customLogger.info(`Performing PUT request to: ${url}`);
1735
3318
  this.customLogger.debug(`PUT payload: ${JSON.stringify(payload)}`);
1736
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
3319
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1737
3320
  this.customLogger.debug(`PUT headers: ${JSON.stringify(headers)}`);
1738
3321
  const response = await this.restClient.put(url, headers, payload, false);
1739
3322
  this.customLogger.debug(`PUT response: ${JSON.stringify(response)}`);
@@ -1765,7 +3348,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1765
3348
  try {
1766
3349
  const url = this.buildEndpoint(endpoint);
1767
3350
  this.customLogger.info(`Performing DELETE request to: ${url}`);
1768
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
3351
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1769
3352
  this.customLogger.debug(`DELETE headers: ${JSON.stringify(headers)}`);
1770
3353
  const response = await this.restClient.delete(url, headers, false);
1771
3354
  this.customLogger.debug(`DELETE response: ${JSON.stringify(response)}`);
@@ -1784,7 +3367,7 @@ _RuntimeApiGatewayService.BASE_URL = "https://adobeioruntime.net/apis";
1784
3367
  var RuntimeApiGatewayService = _RuntimeApiGatewayService;
1785
3368
 
1786
3369
  // src/integration/onboard-events/index.ts
1787
- var import_aio_sdk7 = require("@adobe/aio-sdk");
3370
+ var import_aio_sdk5 = require("@adobe/aio-sdk");
1788
3371
 
1789
3372
  // src/io-events/types.ts
1790
3373
  var IoEventsGlobals = {
@@ -4434,9 +6017,7 @@ var _CreateProviders = class _CreateProviders {
4434
6017
  }
4435
6018
  try {
4436
6019
  const providerInput = this.preparePayload(providerData, enhancedLabel);
4437
- this.logger.debug(
4438
- `[NEW] Creating new provider with payload: ${JSON.stringify(providerInput)}`
4439
- );
6020
+ this.logger.debug(`[NEW] Creating new provider: ${enhancedLabel}`);
4440
6021
  const createdProvider = await this.getProviderManager().create(providerInput);
4441
6022
  this.logger.debug(
4442
6023
  `[INFO] Provider created successfully! ID: ${createdProvider.id}, Instance ID: ${createdProvider.instance_id}`
@@ -4955,7 +6536,7 @@ var _CreateRegistrations = class _CreateRegistrations {
4955
6536
  registrationName,
4956
6537
  firstEvent
4957
6538
  );
4958
- this.logger.debug(`[INFO] Registration input: ${JSON.stringify(registrationInput, null, 2)}`);
6539
+ this.logger.debug(`[INFO] Creating registration: ${registrationName}`);
4959
6540
  const registrationSDK = this.getRegistrationManager();
4960
6541
  const createdRegistration = await registrationSDK.create(registrationInput);
4961
6542
  this.logger.debug("[SUCCESS] Registration created successfully!");
@@ -5099,7 +6680,7 @@ var _OnboardEvents = class _OnboardEvents {
5099
6680
  throw new Error("Access token is required");
5100
6681
  }
5101
6682
  const loggerName = projectName.toLowerCase().replace(/[^a-z0-9\s-_]/g, "").replace(/\s+/g, "-").replace(/_{2,}/g, "_").replace(/-{2,}/g, "-").trim().concat("-onboard-events");
5102
- this.logger = import_aio_sdk7.Core.Logger(loggerName, { level: "debug" });
6683
+ this.logger = import_aio_sdk5.Core.Logger(loggerName, { level: "debug" });
5103
6684
  this.createProviders = new create_providers_default(
5104
6685
  consumerId,
5105
6686
  projectId,
@@ -5295,7 +6876,7 @@ var OnboardEvents = _OnboardEvents;
5295
6876
  var onboard_events_default = OnboardEvents;
5296
6877
 
5297
6878
  // src/integration/infinite-loop-breaker/index.ts
5298
- var import_aio_sdk8 = require("@adobe/aio-sdk");
6879
+ var import_aio_sdk6 = require("@adobe/aio-sdk");
5299
6880
  var import_crypto3 = __toESM(require("crypto"));
5300
6881
  var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5301
6882
  // seconds
@@ -5313,7 +6894,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5313
6894
  event
5314
6895
  }) {
5315
6896
  const logLevel = process.env.LOG_LEVEL || "info";
5316
- const logger = import_aio_sdk8.Core.Logger("infiniteLoopBreaker", { level: logLevel });
6897
+ const logger = import_aio_sdk6.Core.Logger("infiniteLoopBreaker", { level: logLevel });
5317
6898
  logger.debug(`Checking for potential infinite loop for event: ${event}`);
5318
6899
  if (!eventTypes.includes(event)) {
5319
6900
  logger.debug(`Event type ${event} is not in the infinite loop event types list`);
@@ -5321,7 +6902,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5321
6902
  }
5322
6903
  const key = typeof keyFn === "function" ? keyFn() : keyFn;
5323
6904
  const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
5324
- const state = await import_aio_sdk8.State.init();
6905
+ const state = await import_aio_sdk6.State.init();
5325
6906
  const persistedFingerPrint = await state.get(key);
5326
6907
  if (!persistedFingerPrint) {
5327
6908
  logger.debug(`No persisted fingerprint found for key ${key}`);
@@ -5342,7 +6923,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5342
6923
  static async storeFingerPrint(keyFn, fingerprintFn, ttl) {
5343
6924
  const key = typeof keyFn === "function" ? keyFn() : keyFn;
5344
6925
  const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
5345
- const state = await import_aio_sdk8.State.init();
6926
+ const state = await import_aio_sdk6.State.init();
5346
6927
  await state.put(key, _InfiniteLoopBreaker.fingerPrint(data), {
5347
6928
  ttl: ttl !== void 0 ? ttl : _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL
5348
6929
  });
@@ -5518,10 +7099,7 @@ var _ConfigureProvider = class _ConfigureProvider {
5518
7099
  description: provider.description,
5519
7100
  workspace_configuration: JSON.stringify(workspaceConfig)
5520
7101
  };
5521
- this.customLogger.debug(
5522
- `[DEBUG] Creating event provider:
5523
- ${JSON.stringify(providerData, null, 2)}`
5524
- );
7102
+ this.customLogger.debug(`[DEBUG] Creating event provider: ${provider.label} (${provider.id})`);
5525
7103
  const createResult = await this.eventProviderService.create(providerData);
5526
7104
  if (!createResult.success) {
5527
7105
  const errorMsg = `Failed to create event provider: ${createResult.error}`;
@@ -5559,8 +7137,7 @@ ${JSON.stringify(providerData, null, 2)}`
5559
7137
  workspace_configuration: JSON.stringify(workspaceConfig)
5560
7138
  };
5561
7139
  this.customLogger.debug(
5562
- `[DEBUG] Updating configuration with payload:
5563
- ${JSON.stringify(updateConfigPayload, null, 2)}`
7140
+ `[DEBUG] Updating workspace configuration for merchant: ${this.merchantId}`
5564
7141
  );
5565
7142
  const updateResult = await this.eventConfigurationService.update(updateConfigPayload);
5566
7143
  if (!updateResult.success) {
@@ -5735,10 +7312,7 @@ var _OnboardCommerce = class _OnboardCommerce {
5735
7312
  for (const commerceEvent of needsSubscription) {
5736
7313
  try {
5737
7314
  const preparedEvent = this.prepareEventPayload(commerceEvent, provider.id);
5738
- this.customLogger.debug(
5739
- `[DEBUG] Subscribing to event with payload:
5740
- ${JSON.stringify(preparedEvent.event, null, 2)}`
5741
- );
7315
+ this.customLogger.debug(`[DEBUG] Subscribing to event: ${commerceEvent.event.name}`);
5742
7316
  const eventSubscribeResult = await this.eventSubscriptionService.create(
5743
7317
  preparedEvent.event
5744
7318
  );
@@ -6065,7 +7639,7 @@ var AdobeCommerceClient = _AdobeCommerceClient;
6065
7639
  var adobe_commerce_client_default = AdobeCommerceClient;
6066
7640
 
6067
7641
  // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
6068
- var import_aio_sdk9 = require("@adobe/aio-sdk");
7642
+ var import_aio_sdk7 = require("@adobe/aio-sdk");
6069
7643
  var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
6070
7644
  /**
6071
7645
  * @param baseUrl
@@ -6215,7 +7789,7 @@ var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
6215
7789
  async getState() {
6216
7790
  if (this.state === void 0) {
6217
7791
  try {
6218
- this.state = await import_aio_sdk9.State.init();
7792
+ this.state = await import_aio_sdk7.State.init();
6219
7793
  } catch (error) {
6220
7794
  this.logger.debug("State API initialization failed, running without caching");
6221
7795
  this.state = null;
@@ -6327,49 +7901,38 @@ var oauth1a_connection_default = Oauth1aConnection;
6327
7901
  // src/commerce/adobe-commerce-client/ims-connection/index.ts
6328
7902
  var _ImsConnection = class _ImsConnection {
6329
7903
  /**
6330
- * @param clientId
6331
- * @param clientSecret
6332
- * @param technicalAccountId
6333
- * @param technicalAccountEmail
6334
- * @param imsOrgId
6335
- * @param scopes
6336
- * @param logger
7904
+ * Creates an instance of ImsConnection
7905
+ *
7906
+ * @param imsToken - Bearer token string for IMS authentication (generate using AdobeAuth)
7907
+ * @param logger - Optional logger instance for logging operations
7908
+ * @example
7909
+ * ```typescript
7910
+ * const token = await AdobeAuth.getToken(...);
7911
+ * const connection = new ImsConnection(token, logger);
7912
+ * ```
6337
7913
  */
6338
- constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, logger = null) {
6339
- this.clientId = clientId;
6340
- this.clientSecret = clientSecret;
6341
- this.technicalAccountId = technicalAccountId;
6342
- this.technicalAccountEmail = technicalAccountEmail;
6343
- this.imsOrgId = imsOrgId;
6344
- this.scopes = scopes;
7914
+ constructor(imsToken, logger = null) {
7915
+ this.imsToken = imsToken;
6345
7916
  this.customLogger = new custom_logger_default(logger);
6346
7917
  }
6347
7918
  /**
6348
- * @param commerceGot
7919
+ * Extends the Commerce Got client with IMS authentication headers
7920
+ *
7921
+ * @param commerceGot - The Got instance to extend with authentication
7922
+ * @returns Promise<any> - Extended Got instance with authentication headers
7923
+ * @throws {Error} If token is invalid or empty
6349
7924
  */
6350
7925
  async extend(commerceGot) {
6351
7926
  this.customLogger.info("Using Commerce client with IMS authentication");
6352
- const tokenGenerator = new ims_token_default(
6353
- this.clientId,
6354
- this.clientSecret,
6355
- this.technicalAccountId,
6356
- this.technicalAccountEmail,
6357
- this.imsOrgId,
6358
- this.scopes,
6359
- this.customLogger.getLogger(),
6360
- "adobe_commerce_ims_token",
6361
- // Use specific cache key for commerce client
6362
- "adobe-commerce-client"
6363
- // Use adobe-commerce-client context for backward compatibility
6364
- );
6365
- const token = await tokenGenerator.execute();
6366
- if (token === null) {
7927
+ if (!this.imsToken || this.imsToken.trim() === "") {
6367
7928
  throw new Error("Failed to generate or retrieve IMS token");
6368
7929
  }
6369
- this.customLogger.info(`IMS token being extended to header: ${token.substring(0, 10)}...`);
7930
+ this.customLogger.info(
7931
+ `IMS token being extended to header: ${this.imsToken.substring(0, 10)}...`
7932
+ );
6370
7933
  return commerceGot.extend({
6371
7934
  headers: {
6372
- Authorization: `Bearer ${token}`
7935
+ Authorization: `Bearer ${this.imsToken}`
6373
7936
  }
6374
7937
  });
6375
7938
  }
@@ -6942,6 +8505,7 @@ var AdminUiSdk = _AdminUiSdk;
6942
8505
  ImsToken,
6943
8506
  InfiniteLoopBreaker,
6944
8507
  IoEventsGlobals,
8508
+ JsonMessageProcessor,
6945
8509
  Oauth1aConnection,
6946
8510
  OnboardCommerce,
6947
8511
  OnboardEvents,
@@ -6960,6 +8524,9 @@ var AdminUiSdk = _AdminUiSdk;
6960
8524
  ShippingCarrierMethod,
6961
8525
  ShippingCarrierResponse,
6962
8526
  SignatureVerification,
8527
+ SuccessChecker,
8528
+ Telemetry,
8529
+ TelemetryInputError,
6963
8530
  Validator,
6964
8531
  WebhookAction,
6965
8532
  WebhookActionOperation,