@adobe-commerce/aio-toolkit 1.0.9 → 1.0.10

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,6 @@ 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;
9
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
9
  var __esm = (fn, res) => function __init() {
11
10
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
@@ -31,427 +30,610 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
30
  mod
32
31
  ));
33
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
35
33
 
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"() {
34
+ // node_modules/tsup/assets/cjs_shims.js
35
+ var init_cjs_shims = __esm({
36
+ "node_modules/tsup/assets/cjs_shims.js"() {
40
37
  "use strict";
41
- _globalThis = typeof globalThis === "object" ? globalThis : global;
42
38
  }
43
39
  });
44
40
 
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"() {
41
+ // src/framework/telemetry/helpers/input-error/index.ts
42
+ var _TelemetryInputError, TelemetryInputError;
43
+ var init_input_error = __esm({
44
+ "src/framework/telemetry/helpers/input-error/index.ts"() {
65
45
  "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);
46
+ init_cjs_shims();
47
+ _TelemetryInputError = class _TelemetryInputError extends Error {
48
+ /**
49
+ * Creates a new TelemetryInputError
50
+ *
51
+ * @param message - Descriptive error message explaining the validation failure
52
+ */
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = "TelemetryInputError";
56
+ if (Error.captureStackTrace) {
57
+ Error.captureStackTrace(this, _TelemetryInputError);
58
+ }
127
59
  }
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);
60
+ };
61
+ __name(_TelemetryInputError, "TelemetryInputError");
62
+ TelemetryInputError = _TelemetryInputError;
144
63
  }
145
64
  });
146
65
 
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"() {
66
+ // src/framework/telemetry/new-relic/validator/index.ts
67
+ var _NewRelicTelemetryValidator, NewRelicTelemetryValidator;
68
+ var init_validator = __esm({
69
+ "src/framework/telemetry/new-relic/validator/index.ts"() {
188
70
  "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");
71
+ init_cjs_shims();
72
+ init_input_error();
73
+ _NewRelicTelemetryValidator = class _NewRelicTelemetryValidator {
74
+ /**
75
+ * Checks if New Relic telemetry is configured
76
+ *
77
+ * Returns true if:
78
+ * - ENABLE_TELEMETRY is explicitly set to true
79
+ * - NEW_RELIC_TELEMETRY is explicitly set to true
80
+ *
81
+ * This method does NOT validate the completeness of configuration,
82
+ * it only checks if the provider is enabled.
83
+ *
84
+ * @param params - Runtime parameters to check
85
+ * @returns true if New Relic telemetry is enabled, false otherwise
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const validator = new NewRelicTelemetryValidator();
90
+ * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };
91
+ * if (validator.isConfigured(params)) {
92
+ * // New Relic is enabled, proceed with initialization
93
+ * }
94
+ * ```
95
+ */
96
+ isConfigured(params) {
97
+ return params.ENABLE_TELEMETRY === true && params.NEW_RELIC_TELEMETRY === true;
98
+ }
99
+ /**
100
+ * Validates New Relic specific parameters
101
+ *
102
+ * IMPORTANT: Only call this method after checking isConfigured() returns true.
103
+ * This method assumes New Relic telemetry is enabled and validates that
104
+ * all required parameters are present.
105
+ *
106
+ * Required parameters when New Relic is enabled:
107
+ * - NEW_RELIC_SERVICE_NAME must be provided
108
+ * - NEW_RELIC_LICENSE_KEY must be provided
109
+ *
110
+ * @param params - Runtime parameters to validate
111
+ * @throws {TelemetryInputError} If NEW_RELIC_SERVICE_NAME is missing
112
+ * @throws {TelemetryInputError} If NEW_RELIC_LICENSE_KEY is missing
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * const validator = new NewRelicTelemetryValidator();
117
+ * const params = {
118
+ * ENABLE_TELEMETRY: true,
119
+ * NEW_RELIC_TELEMETRY: true,
120
+ * NEW_RELIC_SERVICE_NAME: "my-service",
121
+ * NEW_RELIC_LICENSE_KEY: "license-key"
122
+ * };
123
+ *
124
+ * if (validator.isConfigured(params)) {
125
+ * validator.validateConfiguration(params); // Validates required fields
126
+ * }
127
+ * ```
128
+ */
129
+ validateConfiguration(params) {
130
+ if (params.NEW_RELIC_SERVICE_NAME === void 0 || params.NEW_RELIC_SERVICE_NAME === null || params.NEW_RELIC_SERVICE_NAME === "") {
131
+ throw new TelemetryInputError("NEW_RELIC_SERVICE_NAME is required");
132
+ }
133
+ if (params.NEW_RELIC_LICENSE_KEY === void 0 || params.NEW_RELIC_LICENSE_KEY === null || params.NEW_RELIC_LICENSE_KEY === "") {
134
+ throw new TelemetryInputError("NEW_RELIC_LICENSE_KEY is required");
135
+ }
136
+ }
137
+ };
138
+ __name(_NewRelicTelemetryValidator, "NewRelicTelemetryValidator");
139
+ NewRelicTelemetryValidator = _NewRelicTelemetryValidator;
198
140
  }
199
141
  });
200
142
 
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"() {
143
+ // src/framework/telemetry/helpers/resource-factory/index.ts
144
+ var import_aio_lib_telemetry, import_resources, _ResourceFactory, ResourceFactory;
145
+ var init_resource_factory = __esm({
146
+ "src/framework/telemetry/helpers/resource-factory/index.ts"() {
213
147
  "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;
148
+ init_cjs_shims();
149
+ import_aio_lib_telemetry = require("@adobe/aio-lib-telemetry");
150
+ import_resources = require("@opentelemetry/resources");
151
+ _ResourceFactory = class _ResourceFactory {
152
+ /**
153
+ * Creates a resource with custom environment attributes
154
+ *
155
+ * Starts with the base Adobe I/O Runtime resource and optionally
156
+ * merges environment attributes. These attributes are useful for
157
+ * filtering and correlating telemetry data by deployment environment.
158
+ *
159
+ * Note: Request-specific data (like request IDs) should NOT be added to
160
+ * Resources as they are created once and reused across all requests.
161
+ * Use log attributes or span attributes for request-specific data.
162
+ *
163
+ * @param params - Runtime parameters containing optional ENVIRONMENT
164
+ * @param params.ENVIRONMENT - Environment name (e.g., "dev", "stage", "prod")
165
+ * @returns OpenTelemetry Resource with custom attributes if provided
166
+ *
167
+ * @example Without custom attributes
168
+ * ```typescript
169
+ * const factory = new ResourceFactory();
170
+ * const resource = factory.createWithEnvironment({});
171
+ * // Returns base Adobe I/O Runtime resource
172
+ * ```
173
+ *
174
+ * @example With environment
175
+ * ```typescript
176
+ * const factory = new ResourceFactory();
177
+ * const params = { ENVIRONMENT: "production" };
178
+ * const resource = factory.createWithEnvironment(params);
179
+ * // Returns resource with environment="production" attribute
180
+ * ```
181
+ */
182
+ createWithEnvironment(params) {
183
+ const baseResource = (0, import_aio_lib_telemetry.getAioRuntimeResource)();
184
+ const customAttributes = {};
185
+ if (params.ENVIRONMENT) {
186
+ customAttributes.environment = params.ENVIRONMENT;
228
187
  }
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];
188
+ if (Object.keys(customAttributes).length === 0) {
189
+ return baseResource;
237
190
  }
191
+ const customResource = (0, import_resources.resourceFromAttributes)(
192
+ customAttributes
193
+ );
194
+ return baseResource.merge(customResource);
238
195
  }
239
- return to.concat(ar || Array.prototype.slice.call(from));
240
196
  };
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");
197
+ __name(_ResourceFactory, "ResourceFactory");
198
+ ResourceFactory = _ResourceFactory;
285
199
  }
286
200
  });
287
201
 
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"() {
202
+ // src/framework/telemetry/helpers/success-checker/index.ts
203
+ var _SuccessChecker, SuccessChecker;
204
+ var init_success_checker = __esm({
205
+ "src/framework/telemetry/helpers/success-checker/index.ts"() {
292
206
  "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() {
207
+ init_cjs_shims();
208
+ _SuccessChecker = class _SuccessChecker {
209
+ /**
210
+ * Determines if an action execution was successful
211
+ *
212
+ * Success criteria:
213
+ * - Response has statusCode 200
214
+ * - Body does not contain an exception operation
215
+ *
216
+ * @param result - The action execution result
217
+ * @returns true if successful, false otherwise
218
+ *
219
+ * @example Success case
220
+ * ```typescript
221
+ * const checker = new SuccessChecker();
222
+ * const result = { statusCode: 200, body: { data: 'success' } };
223
+ * checker.execute(result); // true
224
+ * ```
225
+ *
226
+ * @example Failure case - wrong status code
227
+ * ```typescript
228
+ * const checker = new SuccessChecker();
229
+ * const result = { statusCode: 500, body: { error: 'Internal error' } };
230
+ * checker.execute(result); // false
231
+ * ```
232
+ *
233
+ * @example Failure case - exception in body
234
+ * ```typescript
235
+ * const checker = new SuccessChecker();
236
+ * const result = { statusCode: 200, body: { op: 'exception', message: 'Error' } };
237
+ * checker.execute(result); // false
238
+ * ```
239
+ */
240
+ execute(result) {
241
+ if (!result || typeof result !== "object") {
242
+ return false;
243
+ }
244
+ const actionResult = result;
245
+ if (actionResult.statusCode !== 200) {
246
+ return false;
247
+ }
248
+ if (actionResult.body && typeof actionResult.body === "object") {
249
+ return actionResult.body.op !== "exception";
250
+ }
251
+ return true;
252
+ }
319
253
  };
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");
254
+ __name(_SuccessChecker, "SuccessChecker");
255
+ SuccessChecker = _SuccessChecker;
335
256
  }
336
257
  });
337
258
 
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"() {
259
+ // src/framework/telemetry/helpers/json-message-processor/index.ts
260
+ var _JsonMessageProcessor, JsonMessageProcessor;
261
+ var init_json_message_processor = __esm({
262
+ "src/framework/telemetry/helpers/json-message-processor/index.ts"() {
342
263
  "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
- }
264
+ init_cjs_shims();
265
+ _JsonMessageProcessor = class _JsonMessageProcessor {
266
+ /**
267
+ * Creates a new JsonMessageProcessor
268
+ *
269
+ * @param wrappedProcessor - The log processor to wrap and enhance
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * const exporter = new OTLPLogExporterProto({
274
+ * url: "https://otlp.nr-data.net/v1/logs",
275
+ * headers: { "api-key": licenseKey }
276
+ * });
277
+ * const baseProcessor = new SimpleLogRecordProcessor(exporter);
278
+ * const processor = new JsonMessageProcessor(baseProcessor);
279
+ * ```
280
+ */
281
+ constructor(wrappedProcessor) {
282
+ this.wrappedProcessor = wrappedProcessor;
361
283
  }
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
- }
284
+ /**
285
+ * Parse JavaScript object notation and convert to proper object
286
+ *
287
+ * Handles Winston's util.inspect format which produces JavaScript
288
+ * object literals instead of JSON strings.
289
+ *
290
+ * Examples:
291
+ * - { key: 'value' } → {"key":"value"}
292
+ * - { 'accept-encoding': 'gzip' } → {"accept-encoding":"gzip"}
293
+ *
294
+ * @param str - JavaScript object notation string
295
+ * @returns Parsed object
296
+ * @throws Error if parsing fails
297
+ * @private
298
+ */
299
+ parseJavaScriptObjectNotation(str) {
300
+ const func = new Function("return (" + str + ")");
301
+ return func();
370
302
  }
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];
303
+ /**
304
+ * Flatten nested objects into dot-notation keys
305
+ *
306
+ * Converts nested structures like:
307
+ * { headers: { accept: '*' } }
308
+ *
309
+ * Into flat structure:
310
+ * { 'headers.accept': '*' }
311
+ *
312
+ * This makes all attributes searchable in observability platforms.
313
+ *
314
+ * @param obj - Object to flatten
315
+ * @param prefix - Current key prefix (used in recursion)
316
+ * @returns Flattened object with dot-notation keys
317
+ * @private
318
+ */
319
+ flattenObject(obj, prefix = "") {
320
+ const flattened = {};
321
+ for (const [key, value] of Object.entries(obj)) {
322
+ const newKey = prefix ? `${prefix}.${key}` : key;
323
+ if (value === null || value === void 0) {
324
+ flattened[newKey] = value;
325
+ } else if (Array.isArray(value)) {
326
+ flattened[newKey] = JSON.stringify(value);
327
+ } else if (typeof value === "object") {
328
+ if (Object.keys(value).length === 0) {
329
+ continue;
382
330
  }
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;
331
+ const nested = this.flattenObject(value, newKey);
332
+ Object.assign(flattened, nested);
333
+ } else {
334
+ flattened[newKey] = value;
400
335
  }
401
- if (typeof optionsOrLogLevel === "number") {
402
- optionsOrLogLevel = {
403
- logLevel: optionsOrLogLevel
404
- };
336
+ }
337
+ return flattened;
338
+ }
339
+ /**
340
+ * Processes a log record by parsing JSON messages and extracting attributes
341
+ *
342
+ * This method intercepts log records, attempts to parse structured data
343
+ * from the message body, and merges extracted properties as attributes.
344
+ * Additionally, it extracts the log level from the severity information
345
+ * and adds it as a 'level' attribute for easier querying.
346
+ *
347
+ * The enhanced log record is then passed to the wrapped processor.
348
+ *
349
+ * @param logRecord - The log record to process
350
+ *
351
+ * @remarks
352
+ * Processing steps:
353
+ * 1. Extract log level from severityText or severityNumber
354
+ * 2. Add 'level' attribute (debug, info, warn, error, etc.)
355
+ * 3. Parse JSON bodies that start with '{'
356
+ * 4. Extract properties as individual attributes
357
+ * 5. Preserve 'message' field as primary log body
358
+ *
359
+ * Error handling:
360
+ * - Silently handles parsing errors to avoid breaking the logging pipeline
361
+ * - Failed parsing results in unmodified log record
362
+ */
363
+ onEmit(logRecord) {
364
+ try {
365
+ if (logRecord.severityText) {
366
+ logRecord.setAttribute("level", logRecord.severityText.toLowerCase());
367
+ } else if (logRecord.severityNumber !== void 0) {
368
+ const levelName = this.mapSeverityNumberToLevel(logRecord.severityNumber);
369
+ if (levelName) {
370
+ logRecord.setAttribute("level", levelName);
371
+ }
405
372
  }
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);
373
+ const body = logRecord.body;
374
+ if (typeof body === "string" && body.trim().startsWith("{")) {
375
+ let parsed = null;
376
+ try {
377
+ parsed = JSON.parse(body);
378
+ } catch {
379
+ try {
380
+ parsed = this.parseJavaScriptObjectNotation(body);
381
+ } catch {
382
+ }
383
+ }
384
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
385
+ const messageValue = parsed.message;
386
+ const { message, ...attributesObj } = parsed;
387
+ const flattenedAttributes = this.flattenObject(attributesObj);
388
+ Object.entries(flattenedAttributes).forEach(([key, value]) => {
389
+ if (value !== void 0 && value !== null) {
390
+ logRecord.setAttribute(key, value);
391
+ }
392
+ });
393
+ if (messageValue) {
394
+ logRecord.body = messageValue;
395
+ }
396
+ }
412
397
  }
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();
398
+ } catch {
432
399
  }
433
- return this._instance;
434
- };
435
- return DiagAPI2;
436
- })();
400
+ this.wrappedProcessor.onEmit(logRecord);
401
+ }
402
+ /**
403
+ * Maps OpenTelemetry severity number to log level name
404
+ *
405
+ * OpenTelemetry defines severity numbers from 1-24:
406
+ * - 1-4: TRACE
407
+ * - 5-8: DEBUG
408
+ * - 9-12: INFO
409
+ * - 13-16: WARN
410
+ * - 17-20: ERROR
411
+ * - 21-24: FATAL
412
+ *
413
+ * @param severityNumber - OpenTelemetry severity number
414
+ * @returns Log level name (trace, debug, info, warn, error, fatal) or null
415
+ * @private
416
+ */
417
+ mapSeverityNumberToLevel(severityNumber) {
418
+ if (severityNumber >= 1 && severityNumber <= 4) return "trace";
419
+ if (severityNumber >= 5 && severityNumber <= 8) return "debug";
420
+ if (severityNumber >= 9 && severityNumber <= 12) return "info";
421
+ if (severityNumber >= 13 && severityNumber <= 16) return "warn";
422
+ if (severityNumber >= 17 && severityNumber <= 20) return "error";
423
+ if (severityNumber >= 21 && severityNumber <= 24) return "fatal";
424
+ return null;
425
+ }
426
+ /**
427
+ * Forces the processor to flush any pending log records
428
+ *
429
+ * Delegates to the wrapped processor's forceFlush method.
430
+ * Useful for ensuring logs are sent before application shutdown.
431
+ *
432
+ * @returns Promise that resolves when flush is complete
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * await processor.forceFlush();
437
+ * console.log("All logs have been sent");
438
+ * ```
439
+ */
440
+ async forceFlush() {
441
+ return this.wrappedProcessor.forceFlush();
442
+ }
443
+ /**
444
+ * Shuts down the processor and releases resources
445
+ *
446
+ * Delegates to the wrapped processor's shutdown method.
447
+ * Should be called when the application is terminating.
448
+ *
449
+ * @returns Promise that resolves when shutdown is complete
450
+ *
451
+ * @example
452
+ * ```typescript
453
+ * await processor.shutdown();
454
+ * console.log("Processor has been shut down");
455
+ * ```
456
+ */
457
+ async shutdown() {
458
+ return this.wrappedProcessor.shutdown();
459
+ }
460
+ };
461
+ __name(_JsonMessageProcessor, "JsonMessageProcessor");
462
+ JsonMessageProcessor = _JsonMessageProcessor;
437
463
  }
438
464
  });
439
465
 
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
- }
466
+ // src/framework/telemetry/new-relic/index.ts
467
+ var new_relic_exports = {};
468
+ __export(new_relic_exports, {
469
+ default: () => new_relic_default
448
470
  });
449
-
450
- // node_modules/@opentelemetry/api/build/esm/index.js
451
- var init_esm = __esm({
452
- "node_modules/@opentelemetry/api/build/esm/index.js"() {
471
+ var import_aio_lib_telemetry2, import_otel, _NewRelicTelemetry, NewRelicTelemetry, new_relic_default;
472
+ var init_new_relic = __esm({
473
+ "src/framework/telemetry/new-relic/index.ts"() {
453
474
  "use strict";
454
- init_diag_api();
475
+ init_cjs_shims();
476
+ import_aio_lib_telemetry2 = require("@adobe/aio-lib-telemetry");
477
+ init_validator();
478
+ init_resource_factory();
479
+ init_success_checker();
480
+ import_otel = require("@adobe/aio-lib-telemetry/otel");
481
+ init_json_message_processor();
482
+ _NewRelicTelemetry = class _NewRelicTelemetry {
483
+ /**
484
+ * Constructor for New Relic telemetry
485
+ *
486
+ * @description Constructor for New Relic telemetry
487
+ * @example
488
+ * ```typescript
489
+ * const telemetry = new NewRelicTelemetry();
490
+ * ```
491
+ */
492
+ constructor() {
493
+ this.validator = new NewRelicTelemetryValidator();
494
+ this.successChecker = new SuccessChecker();
495
+ this.resourceFactory = new ResourceFactory();
496
+ }
497
+ /**
498
+ * Checks if New Relic telemetry can be initialized
499
+ *
500
+ * Determines if New Relic telemetry is properly configured without actually
501
+ * attempting initialization. Useful for provider chain fallback logic.
502
+ *
503
+ * @param params - Runtime parameters to check
504
+ * @returns true if New Relic is configured and can be initialized
505
+ *
506
+ * @example
507
+ * ```typescript
508
+ * const telemetry = new NewRelicTelemetry();
509
+ * if (telemetry.canInitialize(params)) {
510
+ * // New Relic is configured, use it
511
+ * } else {
512
+ * // Try next provider
513
+ * }
514
+ * ```
515
+ */
516
+ canInitialize(params) {
517
+ return this.validator.isConfigured(params);
518
+ }
519
+ /**
520
+ * Get the OpenTelemetry instrumentation configuration for New Relic
521
+ *
522
+ * Builds and returns the complete instrumentation configuration including:
523
+ * - Service name and preset instrumentations
524
+ * - Custom resource attributes (environment)
525
+ * - OTLP exporters for traces, metrics, and logs
526
+ * - Success/failure detection for actions
527
+ *
528
+ * This method is called internally by `instrumentEntrypoint` to configure
529
+ * telemetry before wrapping the action.
530
+ *
531
+ * @returns Complete entrypoint instrumentation configuration
532
+ * @throws {TelemetryInputError} If required parameters are missing (service name, license key)
533
+ *
534
+ * @example
535
+ * ```typescript
536
+ * const telemetry = new NewRelicTelemetry();
537
+ * const config = telemetry.getConfig();
538
+ * // Returns configuration with exporters, instrumentations, and resource attributes
539
+ * ```
540
+ */
541
+ getConfig() {
542
+ return {
543
+ ...(0, import_aio_lib_telemetry2.defineTelemetryConfig)((params) => {
544
+ if (!this.validator.isConfigured(params)) {
545
+ throw new Error("New Relic telemetry is not configured");
546
+ }
547
+ this.validator.validateConfiguration(params);
548
+ const serviceName = params.NEW_RELIC_SERVICE_NAME;
549
+ return {
550
+ sdkConfig: {
551
+ serviceName,
552
+ instrumentations: (0, import_aio_lib_telemetry2.getPresetInstrumentations)("simple"),
553
+ resource: this.resourceFactory.createWithEnvironment(params),
554
+ ...this.getExportersConfig(params)
555
+ }
556
+ };
557
+ }),
558
+ isSuccessful: this.successChecker.execute.bind(this.successChecker)
559
+ };
560
+ }
561
+ /**
562
+ * Configure New Relic exporters for traces, metrics, and logs
563
+ *
564
+ * Creates OTLP exporters for all three signal types (traces, metrics, logs)
565
+ * and configures them to send data to New Relic. Log processors are wrapped
566
+ * with JsonMessageProcessor for better attribute extraction.
567
+ *
568
+ * @param params - Runtime parameters containing NEW_RELIC_LICENSE_KEY and optional NEW_RELIC_URL
569
+ * @returns Configuration object with traceExporter, metricReaders, and logRecordProcessors
570
+ * @private
571
+ */
572
+ getExportersConfig(params) {
573
+ const licenseKey = params.NEW_RELIC_LICENSE_KEY;
574
+ const newRelicUrl = params.NEW_RELIC_URL || "https://otlp.nr-data.net";
575
+ const makeExporterConfig = /* @__PURE__ */ __name((endpoint) => {
576
+ return {
577
+ url: `${newRelicUrl}/${endpoint}`,
578
+ headers: {
579
+ "api-key": licenseKey
580
+ }
581
+ };
582
+ }, "makeExporterConfig");
583
+ return {
584
+ traceExporter: new import_otel.OTLPTraceExporterProto(makeExporterConfig("v1/traces")),
585
+ metricReaders: [
586
+ new import_otel.PeriodicExportingMetricReader({
587
+ exporter: new import_otel.OTLPMetricExporterProto(makeExporterConfig("v1/metrics"))
588
+ })
589
+ ],
590
+ logRecordProcessors: [
591
+ new JsonMessageProcessor(
592
+ new import_otel.SimpleLogRecordProcessor(new import_otel.OTLPLogExporterProto(makeExporterConfig("v1/logs")))
593
+ )
594
+ ]
595
+ };
596
+ }
597
+ /**
598
+ * Initialize telemetry instrumentation for a runtime action
599
+ *
600
+ * Wraps the provided action with OpenTelemetry instrumentation using
601
+ * New Relic as the backend. The instrumented action will automatically:
602
+ * - Create spans for the action execution
603
+ * - Export metrics during runtime
604
+ * - Forward logs to New Relic
605
+ * - Track success/failure status
606
+ *
607
+ * This method delegates to `instrumentEntrypoint` from `@adobe/aio-lib-telemetry`,
608
+ * passing the action and New Relic specific configuration.
609
+ *
610
+ * @param action - The runtime action function to instrument
611
+ * @returns The instrumented action function with telemetry enabled
612
+ * @throws {TelemetryInputError} If required configuration is missing
613
+ *
614
+ * @example
615
+ * ```typescript
616
+ * async function myAction(params: Record<string, unknown>) {
617
+ * const logger = Telemetry.createLogger("my-action", params);
618
+ * logger.info("Processing request");
619
+ *
620
+ * return { statusCode: 200, body: { success: true } };
621
+ * }
622
+ *
623
+ * const telemetry = new NewRelicTelemetry();
624
+ * const instrumentedAction = telemetry.initialize(myAction);
625
+ *
626
+ * // instrumentedAction now sends traces, metrics, and logs to New Relic
627
+ * export const main = instrumentedAction;
628
+ * ```
629
+ */
630
+ initialize(action) {
631
+ return (0, import_aio_lib_telemetry2.instrumentEntrypoint)(action, this.getConfig());
632
+ }
633
+ };
634
+ __name(_NewRelicTelemetry, "NewRelicTelemetry");
635
+ NewRelicTelemetry = _NewRelicTelemetry;
636
+ new_relic_default = NewRelicTelemetry;
455
637
  }
456
638
  });
457
639
 
@@ -505,8 +687,19 @@ __export(index_exports, {
505
687
  WebhookActionResponse: () => response_default2
506
688
  });
507
689
  module.exports = __toCommonJS(index_exports);
690
+ init_cjs_shims();
691
+
692
+ // src/framework/index.ts
693
+ init_cjs_shims();
694
+
695
+ // src/framework/runtime-action/index.ts
696
+ init_cjs_shims();
697
+
698
+ // src/framework/runtime-action/response/index.ts
699
+ init_cjs_shims();
508
700
 
509
701
  // src/framework/runtime-action/types.ts
702
+ init_cjs_shims();
510
703
  var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
511
704
  HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
512
705
  HttpStatus2[HttpStatus2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
@@ -569,6 +762,7 @@ var RuntimeActionResponse = _RuntimeActionResponse;
569
762
  var response_default = RuntimeActionResponse;
570
763
 
571
764
  // src/framework/runtime-action/validator/index.ts
765
+ init_cjs_shims();
572
766
  var _Validator = class _Validator {
573
767
  /**
574
768
  * Returns the list of missing keys given an object and its required keys.
@@ -634,691 +828,8 @@ var Validator = _Validator;
634
828
  var validator_default = Validator;
635
829
 
636
830
  // src/framework/telemetry/index.ts
831
+ init_cjs_shims();
637
832
  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
833
  var _Telemetry = class _Telemetry {
1323
834
  /**
1324
835
  * Create a logger with standard configuration and automatic metadata injection.
@@ -1328,7 +839,7 @@ var _Telemetry = class _Telemetry {
1328
839
  * - `x-adobe-commerce-request-id`: Extracted from `__ow_headers` (when present)
1329
840
  * - `action.type`: Extracted from `params.action_type` (when present)
1330
841
  *
1331
- * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger; otherwise uses Core.Logger.
842
+ * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger (lazy-loaded); otherwise uses Core.Logger.
1332
843
  * The environment from params.ENVIRONMENT is set at the resource level and will
1333
844
  * automatically appear in all logs sent to New Relic if ENABLE_TELEMETRY is true.
1334
845
  *
@@ -1365,11 +876,59 @@ var _Telemetry = class _Telemetry {
1365
876
  * ```
1366
877
  */
1367
878
  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"
879
+ const logLevel = params.LOG_LEVEL || "info";
880
+ if (!params.ENABLE_TELEMETRY) {
881
+ const baseLogger = import_aio_sdk.Core.Logger(name, { level: logLevel });
882
+ return _Telemetry.wrapLogger(baseLogger, params);
883
+ }
884
+ let telemetryLogger = null;
885
+ let loadingPromise = null;
886
+ const fallbackLogger = import_aio_sdk.Core.Logger(name, { level: logLevel });
887
+ const loadTelemetryLogger = /* @__PURE__ */ __name(async () => {
888
+ if (telemetryLogger || loadingPromise) {
889
+ return;
890
+ }
891
+ loadingPromise = (async () => {
892
+ try {
893
+ const { getLogger } = await import("@adobe/aio-lib-telemetry");
894
+ telemetryLogger = getLogger(name, { level: logLevel });
895
+ } catch (error) {
896
+ telemetryLogger = fallbackLogger;
897
+ }
898
+ })();
899
+ await loadingPromise;
900
+ }, "loadTelemetryLogger");
901
+ loadTelemetryLogger().catch(() => {
1372
902
  });
903
+ const proxyLogger = {
904
+ debug: /* @__PURE__ */ __name((message) => {
905
+ const logger = telemetryLogger || fallbackLogger;
906
+ logger.debug(message);
907
+ }, "debug"),
908
+ info: /* @__PURE__ */ __name((message) => {
909
+ const logger = telemetryLogger || fallbackLogger;
910
+ logger.info(message);
911
+ }, "info"),
912
+ warn: /* @__PURE__ */ __name((message) => {
913
+ const logger = telemetryLogger || fallbackLogger;
914
+ logger.warn(message);
915
+ }, "warn"),
916
+ error: /* @__PURE__ */ __name((message) => {
917
+ const logger = telemetryLogger || fallbackLogger;
918
+ logger.error(message);
919
+ }, "error")
920
+ };
921
+ return _Telemetry.wrapLogger(proxyLogger, params);
922
+ }
923
+ /**
924
+ * Wrap a logger with automatic metadata injection
925
+ *
926
+ * @private
927
+ * @param baseLogger - The base logger to wrap
928
+ * @param params - Runtime parameters containing optional metadata
929
+ * @returns Wrapped logger with metadata injection
930
+ */
931
+ static wrapLogger(baseLogger, params) {
1373
932
  const metadata = {};
1374
933
  const headers = params.__ow_headers;
1375
934
  const requestId = headers?.["x-adobe-commerce-request-id"];
@@ -1517,16 +1076,27 @@ var _Telemetry = class _Telemetry {
1517
1076
  */
1518
1077
  static initialize(action) {
1519
1078
  return async (params) => {
1520
- const newRelicTelemetry = new new_relic_default();
1521
- if (newRelicTelemetry.canInitialize(params)) {
1079
+ if (params.ENABLE_TELEMETRY && params.NEW_RELIC_TELEMETRY) {
1522
1080
  try {
1523
- const instrumentedAction = newRelicTelemetry.initialize(action);
1524
- return await instrumentedAction(params);
1081
+ const { default: NewRelicTelemetry2 } = await Promise.resolve().then(() => (init_new_relic(), new_relic_exports));
1082
+ const newRelicTelemetry = new NewRelicTelemetry2();
1083
+ if (newRelicTelemetry.canInitialize(params)) {
1084
+ try {
1085
+ const instrumentedAction = newRelicTelemetry.initialize(action);
1086
+ return await instrumentedAction(params);
1087
+ } catch (error) {
1088
+ const errorMessage = error instanceof Error ? error.message : "Telemetry initialization failed";
1089
+ return response_default.error(
1090
+ 500 /* INTERNAL_ERROR */,
1091
+ `Telemetry configuration error: ${errorMessage}`
1092
+ );
1093
+ }
1094
+ }
1525
1095
  } catch (error) {
1526
- const errorMessage = error instanceof Error ? error.message : "Telemetry initialization failed";
1096
+ const errorMessage = error instanceof Error ? error.message : "Failed to load telemetry module";
1527
1097
  return response_default.error(
1528
1098
  500 /* INTERNAL_ERROR */,
1529
- `Telemetry configuration error: ${errorMessage}`
1099
+ `Telemetry module error: ${errorMessage}`
1530
1100
  );
1531
1101
  }
1532
1102
  }
@@ -1726,7 +1296,11 @@ _RuntimeAction.actionType = "runtime-action";
1726
1296
  var RuntimeAction = _RuntimeAction;
1727
1297
  var runtime_action_default = RuntimeAction;
1728
1298
 
1299
+ // src/framework/runtime-action/response/types.ts
1300
+ init_cjs_shims();
1301
+
1729
1302
  // src/framework/runtime-action/parameters/index.ts
1303
+ init_cjs_shims();
1730
1304
  var _Parameters = class _Parameters {
1731
1305
  /**
1732
1306
  * Returns a log-ready string of the action input parameters.
@@ -1749,6 +1323,7 @@ var Parameters = _Parameters;
1749
1323
  var parameters_default = Parameters;
1750
1324
 
1751
1325
  // src/framework/event-consumer-action/index.ts
1326
+ init_cjs_shims();
1752
1327
  var _EventConsumerAction = class _EventConsumerAction {
1753
1328
  /**
1754
1329
  * Creates an event consumer action handler with telemetry integration
@@ -1835,6 +1410,7 @@ var EventConsumerAction = _EventConsumerAction;
1835
1410
  var event_consumer_action_default = EventConsumerAction;
1836
1411
 
1837
1412
  // src/framework/graphql-action/index.ts
1413
+ init_cjs_shims();
1838
1414
  var import_graphql = require("graphql");
1839
1415
  var _GraphQlAction = class _GraphQlAction {
1840
1416
  static execute(schema = `
@@ -1912,6 +1488,7 @@ var GraphQlAction = _GraphQlAction;
1912
1488
  var graphql_action_default = GraphQlAction;
1913
1489
 
1914
1490
  // src/framework/openwhisk/index.ts
1491
+ init_cjs_shims();
1915
1492
  var import_openwhisk = __toESM(require("openwhisk"));
1916
1493
  var _Openwhisk = class _Openwhisk {
1917
1494
  /**
@@ -1939,6 +1516,7 @@ var Openwhisk = _Openwhisk;
1939
1516
  var openwhisk_default = Openwhisk;
1940
1517
 
1941
1518
  // src/framework/openwhisk-action/index.ts
1519
+ init_cjs_shims();
1942
1520
  var _OpenwhiskAction = class _OpenwhiskAction {
1943
1521
  /**
1944
1522
  * Creates an OpenWhisk webhook action handler with logging and telemetry
@@ -2023,6 +1601,7 @@ var OpenwhiskAction = _OpenwhiskAction;
2023
1601
  var openwhisk_action_default = OpenwhiskAction;
2024
1602
 
2025
1603
  // src/framework/repository/file-repository/index.ts
1604
+ init_cjs_shims();
2026
1605
  var import_aio_sdk2 = require("@adobe/aio-sdk");
2027
1606
  var _FileRepository = class _FileRepository {
2028
1607
  /**
@@ -2179,12 +1758,17 @@ __name(_FileRepository, "FileRepository");
2179
1758
  var FileRepository = _FileRepository;
2180
1759
  var file_repository_default = FileRepository;
2181
1760
 
1761
+ // src/framework/repository/file-repository/types.ts
1762
+ init_cjs_shims();
1763
+
2182
1764
  // src/framework/publish-event/index.ts
1765
+ init_cjs_shims();
2183
1766
  var import_aio_sdk3 = require("@adobe/aio-sdk");
2184
1767
  var import_cloudevents = require("cloudevents");
2185
1768
  var import_uuid = require("uuid");
2186
1769
 
2187
1770
  // src/framework/custom-logger/index.ts
1771
+ init_cjs_shims();
2188
1772
  var _CustomLogger = class _CustomLogger {
2189
1773
  /**
2190
1774
  * @param logger - External logger instance (can be null)
@@ -2319,7 +1903,17 @@ __name(_PublishEvent, "PublishEvent");
2319
1903
  var PublishEvent = _PublishEvent;
2320
1904
  var publish_event_default = PublishEvent;
2321
1905
 
1906
+ // src/framework/publish-event/types.ts
1907
+ init_cjs_shims();
1908
+
1909
+ // src/framework/webhook-action/index.ts
1910
+ init_cjs_shims();
1911
+
1912
+ // src/framework/webhook-action/response/index.ts
1913
+ init_cjs_shims();
1914
+
2322
1915
  // src/framework/webhook-action/response/types.ts
1916
+ init_cjs_shims();
2323
1917
  var WebhookActionOperation = /* @__PURE__ */ ((WebhookActionOperation2) => {
2324
1918
  WebhookActionOperation2["SUCCESS"] = "success";
2325
1919
  WebhookActionOperation2["EXCEPTION"] = "exception";
@@ -2518,6 +2112,7 @@ var WebhookActionResponse = _WebhookActionResponse;
2518
2112
  var response_default2 = WebhookActionResponse;
2519
2113
 
2520
2114
  // src/framework/webhook-action/types.ts
2115
+ init_cjs_shims();
2521
2116
  var SignatureVerification = /* @__PURE__ */ ((SignatureVerification2) => {
2522
2117
  SignatureVerification2["ENABLED"] = "enabled";
2523
2118
  SignatureVerification2["DISABLED"] = "disabled";
@@ -2605,10 +2200,12 @@ var WebhookAction = _WebhookAction;
2605
2200
  var webhook_action_default = WebhookAction;
2606
2201
 
2607
2202
  // src/framework/ims-token/index.ts
2203
+ init_cjs_shims();
2608
2204
  var import_aio_sdk4 = require("@adobe/aio-sdk");
2609
2205
 
2610
2206
  // src/commerce/adobe-auth/index.ts
2611
- var import_aio_lib_ims = require("@adobe/aio-lib-ims");
2207
+ init_cjs_shims();
2208
+ var aioLibIms = __toESM(require("@adobe/aio-lib-ims"));
2612
2209
  var _AdobeAuth = class _AdobeAuth {
2613
2210
  /**
2614
2211
  * Retrieves an authentication token from Adobe IMS
@@ -2641,9 +2238,9 @@ var _AdobeAuth = class _AdobeAuth {
2641
2238
  ims_org_id: imsOrgId,
2642
2239
  scopes
2643
2240
  };
2644
- await import_aio_lib_ims.context.setCurrent(currentContext);
2645
- await import_aio_lib_ims.context.set(currentContext, config);
2646
- return await (0, import_aio_lib_ims.getToken)();
2241
+ await aioLibIms.context.setCurrent(currentContext);
2242
+ await aioLibIms.context.set(currentContext, config);
2243
+ return await aioLibIms.getToken();
2647
2244
  }
2648
2245
  };
2649
2246
  __name(_AdobeAuth, "AdobeAuth");
@@ -2651,6 +2248,7 @@ var AdobeAuth = _AdobeAuth;
2651
2248
  var adobe_auth_default = AdobeAuth;
2652
2249
 
2653
2250
  // src/integration/bearer-token/index.ts
2251
+ init_cjs_shims();
2654
2252
  var _BearerToken = class _BearerToken {
2655
2253
  /**
2656
2254
  * Extracts the Bearer token from HTTP request headers and returns detailed token information.
@@ -3007,7 +2605,14 @@ __name(_ImsToken, "ImsToken");
3007
2605
  var ImsToken = _ImsToken;
3008
2606
  var ims_token_default = ImsToken;
3009
2607
 
2608
+ // src/framework/ims-token/types.ts
2609
+ init_cjs_shims();
2610
+
2611
+ // src/framework/runtime-api-gateway-service/index.ts
2612
+ init_cjs_shims();
2613
+
3010
2614
  // src/integration/rest-client/index.ts
2615
+ init_cjs_shims();
3011
2616
  var import_node_fetch = __toESM(require("node-fetch"));
3012
2617
  var _RestClient = class _RestClient {
3013
2618
  /**
@@ -3366,10 +2971,35 @@ __name(_RuntimeApiGatewayService, "RuntimeApiGatewayService");
3366
2971
  _RuntimeApiGatewayService.BASE_URL = "https://adobeioruntime.net/apis";
3367
2972
  var RuntimeApiGatewayService = _RuntimeApiGatewayService;
3368
2973
 
2974
+ // src/framework/telemetry/types.ts
2975
+ init_cjs_shims();
2976
+
2977
+ // src/framework/index.ts
2978
+ init_input_error();
2979
+ init_success_checker();
2980
+ init_json_message_processor();
2981
+
2982
+ // src/integration/index.ts
2983
+ init_cjs_shims();
2984
+
3369
2985
  // src/integration/onboard-events/index.ts
2986
+ init_cjs_shims();
3370
2987
  var import_aio_sdk5 = require("@adobe/aio-sdk");
3371
2988
 
2989
+ // src/integration/onboard-events/create-providers/index.ts
2990
+ init_cjs_shims();
2991
+
2992
+ // src/io-events/index.ts
2993
+ init_cjs_shims();
2994
+
2995
+ // src/io-events/provider/index.ts
2996
+ init_cjs_shims();
2997
+
2998
+ // src/io-events/provider/list/index.ts
2999
+ init_cjs_shims();
3000
+
3372
3001
  // src/io-events/types.ts
3002
+ init_cjs_shims();
3373
3003
  var IoEventsGlobals = {
3374
3004
  BASE_URL: "https://api.adobe.io",
3375
3005
  STATUS_CODES: {
@@ -3606,6 +3236,7 @@ var List = _List;
3606
3236
  var list_default = List;
3607
3237
 
3608
3238
  // src/io-events/provider/get/index.ts
3239
+ init_cjs_shims();
3609
3240
  var _Get = class _Get {
3610
3241
  /**
3611
3242
  * Constructor for Get provider service
@@ -3782,6 +3413,7 @@ var Get = _Get;
3782
3413
  var get_default = Get;
3783
3414
 
3784
3415
  // src/io-events/provider/create/index.ts
3416
+ init_cjs_shims();
3785
3417
  var _Create = class _Create {
3786
3418
  /**
3787
3419
  * Constructor for Create provider service
@@ -3949,6 +3581,7 @@ var Create = _Create;
3949
3581
  var create_default = Create;
3950
3582
 
3951
3583
  // src/io-events/provider/delete/index.ts
3584
+ init_cjs_shims();
3952
3585
  var _Delete = class _Delete {
3953
3586
  /**
3954
3587
  * Creates an instance of Delete service
@@ -4275,7 +3908,11 @@ __name(_ProviderManager, "ProviderManager");
4275
3908
  var ProviderManager = _ProviderManager;
4276
3909
  var provider_default = ProviderManager;
4277
3910
 
3911
+ // src/io-events/event-metadata/index.ts
3912
+ init_cjs_shims();
3913
+
4278
3914
  // src/io-events/event-metadata/list/index.ts
3915
+ init_cjs_shims();
4279
3916
  var _List2 = class _List2 {
4280
3917
  /**
4281
3918
  * Creates an instance of List service
@@ -4466,6 +4103,7 @@ __name(_List2, "List");
4466
4103
  var List2 = _List2;
4467
4104
 
4468
4105
  // src/io-events/event-metadata/get/index.ts
4106
+ init_cjs_shims();
4469
4107
  var _Get2 = class _Get2 {
4470
4108
  /**
4471
4109
  * Creates an instance of Get service
@@ -4636,6 +4274,7 @@ __name(_Get2, "Get");
4636
4274
  var Get2 = _Get2;
4637
4275
 
4638
4276
  // src/io-events/event-metadata/create/index.ts
4277
+ init_cjs_shims();
4639
4278
  var _Create2 = class _Create2 {
4640
4279
  /**
4641
4280
  * Constructor for Create event metadata service
@@ -4900,6 +4539,7 @@ var Create2 = _Create2;
4900
4539
  var create_default2 = Create2;
4901
4540
 
4902
4541
  // src/io-events/event-metadata/delete/index.ts
4542
+ init_cjs_shims();
4903
4543
  var _Delete2 = class _Delete2 {
4904
4544
  /**
4905
4545
  * Constructor for Delete event metadata service
@@ -5209,7 +4849,11 @@ __name(_EventMetadataManager, "EventMetadataManager");
5209
4849
  var EventMetadataManager = _EventMetadataManager;
5210
4850
  var event_metadata_default = EventMetadataManager;
5211
4851
 
4852
+ // src/io-events/registration/index.ts
4853
+ init_cjs_shims();
4854
+
5212
4855
  // src/io-events/registration/create/index.ts
4856
+ init_cjs_shims();
5213
4857
  var _Create3 = class _Create3 {
5214
4858
  /**
5215
4859
  * Initialize the Create service
@@ -5394,6 +5038,7 @@ var Create3 = _Create3;
5394
5038
  var create_default3 = Create3;
5395
5039
 
5396
5040
  // src/io-events/registration/delete/index.ts
5041
+ init_cjs_shims();
5397
5042
  var _Delete3 = class _Delete3 {
5398
5043
  /**
5399
5044
  * Initialize the Delete service
@@ -5512,6 +5157,7 @@ var Delete3 = _Delete3;
5512
5157
  var delete_default2 = Delete3;
5513
5158
 
5514
5159
  // src/io-events/registration/get/index.ts
5160
+ init_cjs_shims();
5515
5161
  var _Get3 = class _Get3 {
5516
5162
  /**
5517
5163
  * Initialize the Get service
@@ -5631,6 +5277,7 @@ var Get3 = _Get3;
5631
5277
  var get_default2 = Get3;
5632
5278
 
5633
5279
  // src/io-events/registration/list/index.ts
5280
+ init_cjs_shims();
5634
5281
  var _List3 = class _List3 {
5635
5282
  /**
5636
5283
  * Initialize the List service
@@ -6094,6 +5741,7 @@ var CreateProviders = _CreateProviders;
6094
5741
  var create_providers_default = CreateProviders;
6095
5742
 
6096
5743
  // src/integration/onboard-events/create-events/index.ts
5744
+ init_cjs_shims();
6097
5745
  var _CreateEvents = class _CreateEvents {
6098
5746
  /**
6099
5747
  * Creates a new CreateEvents instance
@@ -6309,6 +5957,7 @@ var CreateEvents = _CreateEvents;
6309
5957
  var create_events_default = CreateEvents;
6310
5958
 
6311
5959
  // src/integration/onboard-events/create-registrations/index.ts
5960
+ init_cjs_shims();
6312
5961
  var _CreateRegistrations = class _CreateRegistrations {
6313
5962
  /**
6314
5963
  * Creates a new CreateRegistrations instance
@@ -6582,6 +6231,7 @@ var CreateRegistrations = _CreateRegistrations;
6582
6231
  var create_registrations_default = CreateRegistrations;
6583
6232
 
6584
6233
  // src/integration/onboard-events/input-parser/index.ts
6234
+ init_cjs_shims();
6585
6235
  var _InputParser = class _InputParser {
6586
6236
  constructor(input) {
6587
6237
  this.entities = {
@@ -6876,6 +6526,7 @@ var OnboardEvents = _OnboardEvents;
6876
6526
  var onboard_events_default = OnboardEvents;
6877
6527
 
6878
6528
  // src/integration/infinite-loop-breaker/index.ts
6529
+ init_cjs_shims();
6879
6530
  var import_aio_sdk6 = require("@adobe/aio-sdk");
6880
6531
  var import_crypto3 = __toESM(require("crypto"));
6881
6532
  var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
@@ -6972,7 +6623,11 @@ _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60;
6972
6623
  var InfiniteLoopBreaker = _InfiniteLoopBreaker;
6973
6624
  var infinite_loop_breaker_default = InfiniteLoopBreaker;
6974
6625
 
6626
+ // src/integration/onboard-commerce/index.ts
6627
+ init_cjs_shims();
6628
+
6975
6629
  // src/integration/onboard-commerce/configure-provider/index.ts
6630
+ init_cjs_shims();
6976
6631
  var import_aio_services_kit = require("@adobe-commerce/aio-services-kit");
6977
6632
  var _ConfigureProvider = class _ConfigureProvider {
6978
6633
  /**
@@ -7499,7 +7154,11 @@ __name(_OnboardCommerce, "OnboardCommerce");
7499
7154
  var OnboardCommerce = _OnboardCommerce;
7500
7155
  var onboard_commerce_default = OnboardCommerce;
7501
7156
 
7157
+ // src/commerce/index.ts
7158
+ init_cjs_shims();
7159
+
7502
7160
  // src/commerce/adobe-commerce-client/index.ts
7161
+ init_cjs_shims();
7503
7162
  var import_got = __toESM(require("got"));
7504
7163
  var _AdobeCommerceClient = class _AdobeCommerceClient {
7505
7164
  /**
@@ -7638,7 +7297,11 @@ __name(_AdobeCommerceClient, "AdobeCommerceClient");
7638
7297
  var AdobeCommerceClient = _AdobeCommerceClient;
7639
7298
  var adobe_commerce_client_default = AdobeCommerceClient;
7640
7299
 
7300
+ // src/commerce/adobe-commerce-client/basic-auth-connection/index.ts
7301
+ init_cjs_shims();
7302
+
7641
7303
  // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
7304
+ init_cjs_shims();
7642
7305
  var import_aio_sdk7 = require("@adobe/aio-sdk");
7643
7306
  var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
7644
7307
  /**
@@ -7840,6 +7503,7 @@ var BasicAuthConnection = _BasicAuthConnection;
7840
7503
  var basic_auth_connection_default = BasicAuthConnection;
7841
7504
 
7842
7505
  // src/commerce/adobe-commerce-client/oauth1a-connection/index.ts
7506
+ init_cjs_shims();
7843
7507
  var import_oauth_1 = __toESM(require("oauth-1.0a"));
7844
7508
  var crypto3 = __toESM(require("crypto"));
7845
7509
  var _Oauth1aConnection = class _Oauth1aConnection {
@@ -7899,6 +7563,7 @@ var Oauth1aConnection = _Oauth1aConnection;
7899
7563
  var oauth1a_connection_default = Oauth1aConnection;
7900
7564
 
7901
7565
  // src/commerce/adobe-commerce-client/ims-connection/index.ts
7566
+ init_cjs_shims();
7902
7567
  var _ImsConnection = class _ImsConnection {
7903
7568
  /**
7904
7569
  * Creates an instance of ImsConnection
@@ -7941,7 +7606,11 @@ __name(_ImsConnection, "ImsConnection");
7941
7606
  var ImsConnection = _ImsConnection;
7942
7607
  var ims_connection_default = ImsConnection;
7943
7608
 
7609
+ // src/commerce/shipping-carrier/index.ts
7610
+ init_cjs_shims();
7611
+
7944
7612
  // src/commerce/shipping-carrier/method/index.ts
7613
+ init_cjs_shims();
7945
7614
  var _ShippingCarrierMethod = class _ShippingCarrierMethod {
7946
7615
  constructor(carrierCode, method) {
7947
7616
  this.methodData = { carrier_code: carrierCode, method, additional_data: [] };
@@ -8292,6 +7961,7 @@ var ShippingCarrier = _ShippingCarrier;
8292
7961
  var shipping_carrier_default = ShippingCarrier;
8293
7962
 
8294
7963
  // src/commerce/shipping-carrier/response/index.ts
7964
+ init_cjs_shims();
8295
7965
  var _ShippingCarrierResponse = class _ShippingCarrierResponse {
8296
7966
  constructor(carrier) {
8297
7967
  this.carrier = carrier;
@@ -8325,7 +7995,11 @@ __name(_ShippingCarrierResponse, "ShippingCarrierResponse");
8325
7995
  var ShippingCarrierResponse = _ShippingCarrierResponse;
8326
7996
  var response_default3 = ShippingCarrierResponse;
8327
7997
 
7998
+ // src/experience/index.ts
7999
+ init_cjs_shims();
8000
+
8328
8001
  // src/experience/admin-ui-sdk/index.ts
8002
+ init_cjs_shims();
8329
8003
  var _AdminUiSdk = class _AdminUiSdk {
8330
8004
  /**
8331
8005
  * Creates a new AdminUiSdk instance