@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.mjs CHANGED
@@ -1,435 +1,646 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
5
4
  var __esm = (fn, res) => function __init() {
6
5
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
6
  };
8
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
9
11
 
10
- // node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
11
- var _globalThis;
12
- var init_globalThis = __esm({
13
- "node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js"() {
12
+ // node_modules/tsup/assets/esm_shims.js
13
+ import path from "path";
14
+ import { fileURLToPath } from "url";
15
+ var init_esm_shims = __esm({
16
+ "node_modules/tsup/assets/esm_shims.js"() {
14
17
  "use strict";
15
- _globalThis = typeof globalThis === "object" ? globalThis : global;
16
18
  }
17
19
  });
18
20
 
19
- // node_modules/@opentelemetry/api/build/esm/platform/node/index.js
20
- var init_node = __esm({
21
- "node_modules/@opentelemetry/api/build/esm/platform/node/index.js"() {
21
+ // src/framework/telemetry/helpers/input-error/index.ts
22
+ var _TelemetryInputError, TelemetryInputError;
23
+ var init_input_error = __esm({
24
+ "src/framework/telemetry/helpers/input-error/index.ts"() {
22
25
  "use strict";
23
- init_globalThis();
26
+ init_esm_shims();
27
+ _TelemetryInputError = class _TelemetryInputError extends Error {
28
+ /**
29
+ * Creates a new TelemetryInputError
30
+ *
31
+ * @param message - Descriptive error message explaining the validation failure
32
+ */
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "TelemetryInputError";
36
+ if (Error.captureStackTrace) {
37
+ Error.captureStackTrace(this, _TelemetryInputError);
38
+ }
39
+ }
40
+ };
41
+ __name(_TelemetryInputError, "TelemetryInputError");
42
+ TelemetryInputError = _TelemetryInputError;
24
43
  }
25
44
  });
26
45
 
27
- // node_modules/@opentelemetry/api/build/esm/platform/index.js
28
- var init_platform = __esm({
29
- "node_modules/@opentelemetry/api/build/esm/platform/index.js"() {
46
+ // src/framework/telemetry/new-relic/validator/index.ts
47
+ var _NewRelicTelemetryValidator, NewRelicTelemetryValidator;
48
+ var init_validator = __esm({
49
+ "src/framework/telemetry/new-relic/validator/index.ts"() {
30
50
  "use strict";
31
- init_node();
51
+ init_esm_shims();
52
+ init_input_error();
53
+ _NewRelicTelemetryValidator = class _NewRelicTelemetryValidator {
54
+ /**
55
+ * Checks if New Relic telemetry is configured
56
+ *
57
+ * Returns true if:
58
+ * - ENABLE_TELEMETRY is explicitly set to true
59
+ * - NEW_RELIC_TELEMETRY is explicitly set to true
60
+ *
61
+ * This method does NOT validate the completeness of configuration,
62
+ * it only checks if the provider is enabled.
63
+ *
64
+ * @param params - Runtime parameters to check
65
+ * @returns true if New Relic telemetry is enabled, false otherwise
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * const validator = new NewRelicTelemetryValidator();
70
+ * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };
71
+ * if (validator.isConfigured(params)) {
72
+ * // New Relic is enabled, proceed with initialization
73
+ * }
74
+ * ```
75
+ */
76
+ isConfigured(params) {
77
+ return params.ENABLE_TELEMETRY === true && params.NEW_RELIC_TELEMETRY === true;
78
+ }
79
+ /**
80
+ * Validates New Relic specific parameters
81
+ *
82
+ * IMPORTANT: Only call this method after checking isConfigured() returns true.
83
+ * This method assumes New Relic telemetry is enabled and validates that
84
+ * all required parameters are present.
85
+ *
86
+ * Required parameters when New Relic is enabled:
87
+ * - NEW_RELIC_SERVICE_NAME must be provided
88
+ * - NEW_RELIC_LICENSE_KEY must be provided
89
+ *
90
+ * @param params - Runtime parameters to validate
91
+ * @throws {TelemetryInputError} If NEW_RELIC_SERVICE_NAME is missing
92
+ * @throws {TelemetryInputError} If NEW_RELIC_LICENSE_KEY is missing
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * const validator = new NewRelicTelemetryValidator();
97
+ * const params = {
98
+ * ENABLE_TELEMETRY: true,
99
+ * NEW_RELIC_TELEMETRY: true,
100
+ * NEW_RELIC_SERVICE_NAME: "my-service",
101
+ * NEW_RELIC_LICENSE_KEY: "license-key"
102
+ * };
103
+ *
104
+ * if (validator.isConfigured(params)) {
105
+ * validator.validateConfiguration(params); // Validates required fields
106
+ * }
107
+ * ```
108
+ */
109
+ validateConfiguration(params) {
110
+ if (params.NEW_RELIC_SERVICE_NAME === void 0 || params.NEW_RELIC_SERVICE_NAME === null || params.NEW_RELIC_SERVICE_NAME === "") {
111
+ throw new TelemetryInputError("NEW_RELIC_SERVICE_NAME is required");
112
+ }
113
+ if (params.NEW_RELIC_LICENSE_KEY === void 0 || params.NEW_RELIC_LICENSE_KEY === null || params.NEW_RELIC_LICENSE_KEY === "") {
114
+ throw new TelemetryInputError("NEW_RELIC_LICENSE_KEY is required");
115
+ }
116
+ }
117
+ };
118
+ __name(_NewRelicTelemetryValidator, "NewRelicTelemetryValidator");
119
+ NewRelicTelemetryValidator = _NewRelicTelemetryValidator;
32
120
  }
33
121
  });
34
122
 
35
- // node_modules/@opentelemetry/api/build/esm/version.js
36
- var VERSION;
37
- var init_version = __esm({
38
- "node_modules/@opentelemetry/api/build/esm/version.js"() {
123
+ // src/framework/telemetry/helpers/resource-factory/index.ts
124
+ import { getAioRuntimeResource } from "@adobe/aio-lib-telemetry";
125
+ import { resourceFromAttributes } from "@opentelemetry/resources";
126
+ var _ResourceFactory, ResourceFactory;
127
+ var init_resource_factory = __esm({
128
+ "src/framework/telemetry/helpers/resource-factory/index.ts"() {
39
129
  "use strict";
40
- VERSION = "1.9.0";
41
- }
42
- });
43
-
44
- // node_modules/@opentelemetry/api/build/esm/internal/semver.js
45
- function _makeCompatibilityCheck(ownVersion) {
46
- var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
47
- var rejectedVersions = /* @__PURE__ */ new Set();
48
- var myVersionMatch = ownVersion.match(re);
49
- if (!myVersionMatch) {
50
- return function() {
51
- return false;
52
- };
53
- }
54
- var ownVersionParsed = {
55
- major: +myVersionMatch[1],
56
- minor: +myVersionMatch[2],
57
- patch: +myVersionMatch[3],
58
- prerelease: myVersionMatch[4]
59
- };
60
- if (ownVersionParsed.prerelease != null) {
61
- return /* @__PURE__ */ __name(function isExactmatch(globalVersion) {
62
- return globalVersion === ownVersion;
63
- }, "isExactmatch");
64
- }
65
- function _reject(v) {
66
- rejectedVersions.add(v);
67
- return false;
68
- }
69
- __name(_reject, "_reject");
70
- function _accept(v) {
71
- acceptedVersions.add(v);
72
- return true;
73
- }
74
- __name(_accept, "_accept");
75
- return /* @__PURE__ */ __name(function isCompatible2(globalVersion) {
76
- if (acceptedVersions.has(globalVersion)) {
77
- return true;
78
- }
79
- if (rejectedVersions.has(globalVersion)) {
80
- return false;
81
- }
82
- var globalVersionMatch = globalVersion.match(re);
83
- if (!globalVersionMatch) {
84
- return _reject(globalVersion);
85
- }
86
- var globalVersionParsed = {
87
- major: +globalVersionMatch[1],
88
- minor: +globalVersionMatch[2],
89
- patch: +globalVersionMatch[3],
90
- prerelease: globalVersionMatch[4]
91
- };
92
- if (globalVersionParsed.prerelease != null) {
93
- return _reject(globalVersion);
94
- }
95
- if (ownVersionParsed.major !== globalVersionParsed.major) {
96
- return _reject(globalVersion);
97
- }
98
- if (ownVersionParsed.major === 0) {
99
- if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
100
- return _accept(globalVersion);
130
+ init_esm_shims();
131
+ _ResourceFactory = class _ResourceFactory {
132
+ /**
133
+ * Creates a resource with custom environment attributes
134
+ *
135
+ * Starts with the base Adobe I/O Runtime resource and optionally
136
+ * merges environment attributes. These attributes are useful for
137
+ * filtering and correlating telemetry data by deployment environment.
138
+ *
139
+ * Note: Request-specific data (like request IDs) should NOT be added to
140
+ * Resources as they are created once and reused across all requests.
141
+ * Use log attributes or span attributes for request-specific data.
142
+ *
143
+ * @param params - Runtime parameters containing optional ENVIRONMENT
144
+ * @param params.ENVIRONMENT - Environment name (e.g., "dev", "stage", "prod")
145
+ * @returns OpenTelemetry Resource with custom attributes if provided
146
+ *
147
+ * @example Without custom attributes
148
+ * ```typescript
149
+ * const factory = new ResourceFactory();
150
+ * const resource = factory.createWithEnvironment({});
151
+ * // Returns base Adobe I/O Runtime resource
152
+ * ```
153
+ *
154
+ * @example With environment
155
+ * ```typescript
156
+ * const factory = new ResourceFactory();
157
+ * const params = { ENVIRONMENT: "production" };
158
+ * const resource = factory.createWithEnvironment(params);
159
+ * // Returns resource with environment="production" attribute
160
+ * ```
161
+ */
162
+ createWithEnvironment(params) {
163
+ const baseResource = getAioRuntimeResource();
164
+ const customAttributes = {};
165
+ if (params.ENVIRONMENT) {
166
+ customAttributes.environment = params.ENVIRONMENT;
167
+ }
168
+ if (Object.keys(customAttributes).length === 0) {
169
+ return baseResource;
170
+ }
171
+ const customResource = resourceFromAttributes(
172
+ customAttributes
173
+ );
174
+ return baseResource.merge(customResource);
101
175
  }
102
- return _reject(globalVersion);
103
- }
104
- if (ownVersionParsed.minor <= globalVersionParsed.minor) {
105
- return _accept(globalVersion);
106
- }
107
- return _reject(globalVersion);
108
- }, "isCompatible");
109
- }
110
- var re, isCompatible;
111
- var init_semver = __esm({
112
- "node_modules/@opentelemetry/api/build/esm/internal/semver.js"() {
113
- "use strict";
114
- init_version();
115
- re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
116
- __name(_makeCompatibilityCheck, "_makeCompatibilityCheck");
117
- isCompatible = _makeCompatibilityCheck(VERSION);
176
+ };
177
+ __name(_ResourceFactory, "ResourceFactory");
178
+ ResourceFactory = _ResourceFactory;
118
179
  }
119
180
  });
120
181
 
121
- // node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
122
- function registerGlobal(type, instance, diag2, allowOverride) {
123
- var _a;
124
- if (allowOverride === void 0) {
125
- allowOverride = false;
126
- }
127
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
128
- version: VERSION
129
- };
130
- if (!allowOverride && api[type]) {
131
- var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
132
- diag2.error(err.stack || err.message);
133
- return false;
134
- }
135
- if (api.version !== VERSION) {
136
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
137
- diag2.error(err.stack || err.message);
138
- return false;
139
- }
140
- api[type] = instance;
141
- diag2.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
142
- return true;
143
- }
144
- function getGlobal(type) {
145
- var _a, _b;
146
- var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
147
- if (!globalVersion || !isCompatible(globalVersion)) {
148
- return;
149
- }
150
- return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
151
- }
152
- function unregisterGlobal(type, diag2) {
153
- diag2.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
154
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
155
- if (api) {
156
- delete api[type];
157
- }
158
- }
159
- var major, GLOBAL_OPENTELEMETRY_API_KEY, _global;
160
- var init_global_utils = __esm({
161
- "node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() {
182
+ // src/framework/telemetry/helpers/success-checker/index.ts
183
+ var _SuccessChecker, SuccessChecker;
184
+ var init_success_checker = __esm({
185
+ "src/framework/telemetry/helpers/success-checker/index.ts"() {
162
186
  "use strict";
163
- init_platform();
164
- init_version();
165
- init_semver();
166
- major = VERSION.split(".")[0];
167
- GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
168
- _global = _globalThis;
169
- __name(registerGlobal, "registerGlobal");
170
- __name(getGlobal, "getGlobal");
171
- __name(unregisterGlobal, "unregisterGlobal");
187
+ init_esm_shims();
188
+ _SuccessChecker = class _SuccessChecker {
189
+ /**
190
+ * Determines if an action execution was successful
191
+ *
192
+ * Success criteria:
193
+ * - Response has statusCode 200
194
+ * - Body does not contain an exception operation
195
+ *
196
+ * @param result - The action execution result
197
+ * @returns true if successful, false otherwise
198
+ *
199
+ * @example Success case
200
+ * ```typescript
201
+ * const checker = new SuccessChecker();
202
+ * const result = { statusCode: 200, body: { data: 'success' } };
203
+ * checker.execute(result); // true
204
+ * ```
205
+ *
206
+ * @example Failure case - wrong status code
207
+ * ```typescript
208
+ * const checker = new SuccessChecker();
209
+ * const result = { statusCode: 500, body: { error: 'Internal error' } };
210
+ * checker.execute(result); // false
211
+ * ```
212
+ *
213
+ * @example Failure case - exception in body
214
+ * ```typescript
215
+ * const checker = new SuccessChecker();
216
+ * const result = { statusCode: 200, body: { op: 'exception', message: 'Error' } };
217
+ * checker.execute(result); // false
218
+ * ```
219
+ */
220
+ execute(result) {
221
+ if (!result || typeof result !== "object") {
222
+ return false;
223
+ }
224
+ const actionResult = result;
225
+ if (actionResult.statusCode !== 200) {
226
+ return false;
227
+ }
228
+ if (actionResult.body && typeof actionResult.body === "object") {
229
+ return actionResult.body.op !== "exception";
230
+ }
231
+ return true;
232
+ }
233
+ };
234
+ __name(_SuccessChecker, "SuccessChecker");
235
+ SuccessChecker = _SuccessChecker;
172
236
  }
173
237
  });
174
238
 
175
- // node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
176
- function logProxy(funcName, namespace, args) {
177
- var logger = getGlobal("diag");
178
- if (!logger) {
179
- return;
180
- }
181
- args.unshift(namespace);
182
- return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
183
- }
184
- var __read, __spreadArray, DiagComponentLogger;
185
- var init_ComponentLogger = __esm({
186
- "node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() {
239
+ // src/framework/telemetry/helpers/json-message-processor/index.ts
240
+ var _JsonMessageProcessor, JsonMessageProcessor;
241
+ var init_json_message_processor = __esm({
242
+ "src/framework/telemetry/helpers/json-message-processor/index.ts"() {
187
243
  "use strict";
188
- init_global_utils();
189
- __read = function(o, n) {
190
- var m = typeof Symbol === "function" && o[Symbol.iterator];
191
- if (!m) return o;
192
- var i = m.call(o), r, ar = [], e;
193
- try {
194
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
195
- } catch (error) {
196
- e = { error };
197
- } finally {
198
- try {
199
- if (r && !r.done && (m = i["return"])) m.call(i);
200
- } finally {
201
- if (e) throw e.error;
244
+ init_esm_shims();
245
+ _JsonMessageProcessor = class _JsonMessageProcessor {
246
+ /**
247
+ * Creates a new JsonMessageProcessor
248
+ *
249
+ * @param wrappedProcessor - The log processor to wrap and enhance
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * const exporter = new OTLPLogExporterProto({
254
+ * url: "https://otlp.nr-data.net/v1/logs",
255
+ * headers: { "api-key": licenseKey }
256
+ * });
257
+ * const baseProcessor = new SimpleLogRecordProcessor(exporter);
258
+ * const processor = new JsonMessageProcessor(baseProcessor);
259
+ * ```
260
+ */
261
+ constructor(wrappedProcessor) {
262
+ this.wrappedProcessor = wrappedProcessor;
263
+ }
264
+ /**
265
+ * Parse JavaScript object notation and convert to proper object
266
+ *
267
+ * Handles Winston's util.inspect format which produces JavaScript
268
+ * object literals instead of JSON strings.
269
+ *
270
+ * Examples:
271
+ * - { key: 'value' } → {"key":"value"}
272
+ * - { 'accept-encoding': 'gzip' } → {"accept-encoding":"gzip"}
273
+ *
274
+ * @param str - JavaScript object notation string
275
+ * @returns Parsed object
276
+ * @throws Error if parsing fails
277
+ * @private
278
+ */
279
+ parseJavaScriptObjectNotation(str) {
280
+ const func = new Function("return (" + str + ")");
281
+ return func();
282
+ }
283
+ /**
284
+ * Flatten nested objects into dot-notation keys
285
+ *
286
+ * Converts nested structures like:
287
+ * { headers: { accept: '*' } }
288
+ *
289
+ * Into flat structure:
290
+ * { 'headers.accept': '*' }
291
+ *
292
+ * This makes all attributes searchable in observability platforms.
293
+ *
294
+ * @param obj - Object to flatten
295
+ * @param prefix - Current key prefix (used in recursion)
296
+ * @returns Flattened object with dot-notation keys
297
+ * @private
298
+ */
299
+ flattenObject(obj, prefix = "") {
300
+ const flattened = {};
301
+ for (const [key, value] of Object.entries(obj)) {
302
+ const newKey = prefix ? `${prefix}.${key}` : key;
303
+ if (value === null || value === void 0) {
304
+ flattened[newKey] = value;
305
+ } else if (Array.isArray(value)) {
306
+ flattened[newKey] = JSON.stringify(value);
307
+ } else if (typeof value === "object") {
308
+ if (Object.keys(value).length === 0) {
309
+ continue;
310
+ }
311
+ const nested = this.flattenObject(value, newKey);
312
+ Object.assign(flattened, nested);
313
+ } else {
314
+ flattened[newKey] = value;
315
+ }
202
316
  }
317
+ return flattened;
203
318
  }
204
- return ar;
205
- };
206
- __spreadArray = function(to, from, pack) {
207
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
208
- if (ar || !(i in from)) {
209
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
210
- ar[i] = from[i];
319
+ /**
320
+ * Processes a log record by parsing JSON messages and extracting attributes
321
+ *
322
+ * This method intercepts log records, attempts to parse structured data
323
+ * from the message body, and merges extracted properties as attributes.
324
+ * Additionally, it extracts the log level from the severity information
325
+ * and adds it as a 'level' attribute for easier querying.
326
+ *
327
+ * The enhanced log record is then passed to the wrapped processor.
328
+ *
329
+ * @param logRecord - The log record to process
330
+ *
331
+ * @remarks
332
+ * Processing steps:
333
+ * 1. Extract log level from severityText or severityNumber
334
+ * 2. Add 'level' attribute (debug, info, warn, error, etc.)
335
+ * 3. Parse JSON bodies that start with '{'
336
+ * 4. Extract properties as individual attributes
337
+ * 5. Preserve 'message' field as primary log body
338
+ *
339
+ * Error handling:
340
+ * - Silently handles parsing errors to avoid breaking the logging pipeline
341
+ * - Failed parsing results in unmodified log record
342
+ */
343
+ onEmit(logRecord) {
344
+ try {
345
+ if (logRecord.severityText) {
346
+ logRecord.setAttribute("level", logRecord.severityText.toLowerCase());
347
+ } else if (logRecord.severityNumber !== void 0) {
348
+ const levelName = this.mapSeverityNumberToLevel(logRecord.severityNumber);
349
+ if (levelName) {
350
+ logRecord.setAttribute("level", levelName);
351
+ }
352
+ }
353
+ const body = logRecord.body;
354
+ if (typeof body === "string" && body.trim().startsWith("{")) {
355
+ let parsed = null;
356
+ try {
357
+ parsed = JSON.parse(body);
358
+ } catch {
359
+ try {
360
+ parsed = this.parseJavaScriptObjectNotation(body);
361
+ } catch {
362
+ }
363
+ }
364
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
365
+ const messageValue = parsed.message;
366
+ const { message, ...attributesObj } = parsed;
367
+ const flattenedAttributes = this.flattenObject(attributesObj);
368
+ Object.entries(flattenedAttributes).forEach(([key, value]) => {
369
+ if (value !== void 0 && value !== null) {
370
+ logRecord.setAttribute(key, value);
371
+ }
372
+ });
373
+ if (messageValue) {
374
+ logRecord.body = messageValue;
375
+ }
376
+ }
377
+ }
378
+ } catch {
211
379
  }
380
+ this.wrappedProcessor.onEmit(logRecord);
212
381
  }
213
- return to.concat(ar || Array.prototype.slice.call(from));
214
- };
215
- DiagComponentLogger = /** @class */
216
- (function() {
217
- function DiagComponentLogger2(props) {
218
- this._namespace = props.namespace || "DiagComponentLogger";
382
+ /**
383
+ * Maps OpenTelemetry severity number to log level name
384
+ *
385
+ * OpenTelemetry defines severity numbers from 1-24:
386
+ * - 1-4: TRACE
387
+ * - 5-8: DEBUG
388
+ * - 9-12: INFO
389
+ * - 13-16: WARN
390
+ * - 17-20: ERROR
391
+ * - 21-24: FATAL
392
+ *
393
+ * @param severityNumber - OpenTelemetry severity number
394
+ * @returns Log level name (trace, debug, info, warn, error, fatal) or null
395
+ * @private
396
+ */
397
+ mapSeverityNumberToLevel(severityNumber) {
398
+ if (severityNumber >= 1 && severityNumber <= 4) return "trace";
399
+ if (severityNumber >= 5 && severityNumber <= 8) return "debug";
400
+ if (severityNumber >= 9 && severityNumber <= 12) return "info";
401
+ if (severityNumber >= 13 && severityNumber <= 16) return "warn";
402
+ if (severityNumber >= 17 && severityNumber <= 20) return "error";
403
+ if (severityNumber >= 21 && severityNumber <= 24) return "fatal";
404
+ return null;
405
+ }
406
+ /**
407
+ * Forces the processor to flush any pending log records
408
+ *
409
+ * Delegates to the wrapped processor's forceFlush method.
410
+ * Useful for ensuring logs are sent before application shutdown.
411
+ *
412
+ * @returns Promise that resolves when flush is complete
413
+ *
414
+ * @example
415
+ * ```typescript
416
+ * await processor.forceFlush();
417
+ * console.log("All logs have been sent");
418
+ * ```
419
+ */
420
+ async forceFlush() {
421
+ return this.wrappedProcessor.forceFlush();
422
+ }
423
+ /**
424
+ * Shuts down the processor and releases resources
425
+ *
426
+ * Delegates to the wrapped processor's shutdown method.
427
+ * Should be called when the application is terminating.
428
+ *
429
+ * @returns Promise that resolves when shutdown is complete
430
+ *
431
+ * @example
432
+ * ```typescript
433
+ * await processor.shutdown();
434
+ * console.log("Processor has been shut down");
435
+ * ```
436
+ */
437
+ async shutdown() {
438
+ return this.wrappedProcessor.shutdown();
219
439
  }
220
- __name(DiagComponentLogger2, "DiagComponentLogger");
221
- DiagComponentLogger2.prototype.debug = function() {
222
- var args = [];
223
- for (var _i = 0; _i < arguments.length; _i++) {
224
- args[_i] = arguments[_i];
225
- }
226
- return logProxy("debug", this._namespace, args);
227
- };
228
- DiagComponentLogger2.prototype.error = function() {
229
- var args = [];
230
- for (var _i = 0; _i < arguments.length; _i++) {
231
- args[_i] = arguments[_i];
232
- }
233
- return logProxy("error", this._namespace, args);
234
- };
235
- DiagComponentLogger2.prototype.info = function() {
236
- var args = [];
237
- for (var _i = 0; _i < arguments.length; _i++) {
238
- args[_i] = arguments[_i];
239
- }
240
- return logProxy("info", this._namespace, args);
241
- };
242
- DiagComponentLogger2.prototype.warn = function() {
243
- var args = [];
244
- for (var _i = 0; _i < arguments.length; _i++) {
245
- args[_i] = arguments[_i];
246
- }
247
- return logProxy("warn", this._namespace, args);
248
- };
249
- DiagComponentLogger2.prototype.verbose = function() {
250
- var args = [];
251
- for (var _i = 0; _i < arguments.length; _i++) {
252
- args[_i] = arguments[_i];
253
- }
254
- return logProxy("verbose", this._namespace, args);
255
- };
256
- return DiagComponentLogger2;
257
- })();
258
- __name(logProxy, "logProxy");
259
- }
260
- });
261
-
262
- // node_modules/@opentelemetry/api/build/esm/diag/types.js
263
- var DiagLogLevel;
264
- var init_types = __esm({
265
- "node_modules/@opentelemetry/api/build/esm/diag/types.js"() {
266
- "use strict";
267
- (function(DiagLogLevel2) {
268
- DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
269
- DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
270
- DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
271
- DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
272
- DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
273
- DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
274
- DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
275
- })(DiagLogLevel || (DiagLogLevel = {}));
276
- }
277
- });
278
-
279
- // node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
280
- function createLogLevelDiagLogger(maxLevel, logger) {
281
- if (maxLevel < DiagLogLevel.NONE) {
282
- maxLevel = DiagLogLevel.NONE;
283
- } else if (maxLevel > DiagLogLevel.ALL) {
284
- maxLevel = DiagLogLevel.ALL;
285
- }
286
- logger = logger || {};
287
- function _filterFunc(funcName, theLevel) {
288
- var theFunc = logger[funcName];
289
- if (typeof theFunc === "function" && maxLevel >= theLevel) {
290
- return theFunc.bind(logger);
291
- }
292
- return function() {
293
440
  };
294
- }
295
- __name(_filterFunc, "_filterFunc");
296
- return {
297
- error: _filterFunc("error", DiagLogLevel.ERROR),
298
- warn: _filterFunc("warn", DiagLogLevel.WARN),
299
- info: _filterFunc("info", DiagLogLevel.INFO),
300
- debug: _filterFunc("debug", DiagLogLevel.DEBUG),
301
- verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
302
- };
303
- }
304
- var init_logLevelLogger = __esm({
305
- "node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() {
306
- "use strict";
307
- init_types();
308
- __name(createLogLevelDiagLogger, "createLogLevelDiagLogger");
441
+ __name(_JsonMessageProcessor, "JsonMessageProcessor");
442
+ JsonMessageProcessor = _JsonMessageProcessor;
309
443
  }
310
444
  });
311
445
 
312
- // node_modules/@opentelemetry/api/build/esm/api/diag.js
313
- var __read2, __spreadArray2, API_NAME, DiagAPI;
314
- var init_diag = __esm({
315
- "node_modules/@opentelemetry/api/build/esm/api/diag.js"() {
446
+ // src/framework/telemetry/new-relic/index.ts
447
+ var new_relic_exports = {};
448
+ __export(new_relic_exports, {
449
+ default: () => new_relic_default
450
+ });
451
+ import {
452
+ defineTelemetryConfig,
453
+ getPresetInstrumentations,
454
+ instrumentEntrypoint
455
+ } from "@adobe/aio-lib-telemetry";
456
+ import {
457
+ OTLPLogExporterProto,
458
+ OTLPMetricExporterProto,
459
+ OTLPTraceExporterProto,
460
+ PeriodicExportingMetricReader,
461
+ SimpleLogRecordProcessor
462
+ } from "@adobe/aio-lib-telemetry/otel";
463
+ var _NewRelicTelemetry, NewRelicTelemetry, new_relic_default;
464
+ var init_new_relic = __esm({
465
+ "src/framework/telemetry/new-relic/index.ts"() {
316
466
  "use strict";
317
- init_ComponentLogger();
318
- init_logLevelLogger();
319
- init_types();
320
- init_global_utils();
321
- __read2 = function(o, n) {
322
- var m = typeof Symbol === "function" && o[Symbol.iterator];
323
- if (!m) return o;
324
- var i = m.call(o), r, ar = [], e;
325
- try {
326
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
327
- } catch (error) {
328
- e = { error };
329
- } finally {
330
- try {
331
- if (r && !r.done && (m = i["return"])) m.call(i);
332
- } finally {
333
- if (e) throw e.error;
334
- }
467
+ init_esm_shims();
468
+ init_validator();
469
+ init_resource_factory();
470
+ init_success_checker();
471
+ init_json_message_processor();
472
+ _NewRelicTelemetry = class _NewRelicTelemetry {
473
+ /**
474
+ * Constructor for New Relic telemetry
475
+ *
476
+ * @description Constructor for New Relic telemetry
477
+ * @example
478
+ * ```typescript
479
+ * const telemetry = new NewRelicTelemetry();
480
+ * ```
481
+ */
482
+ constructor() {
483
+ this.validator = new NewRelicTelemetryValidator();
484
+ this.successChecker = new SuccessChecker();
485
+ this.resourceFactory = new ResourceFactory();
335
486
  }
336
- return ar;
337
- };
338
- __spreadArray2 = function(to, from, pack) {
339
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
340
- if (ar || !(i in from)) {
341
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
342
- ar[i] = from[i];
343
- }
487
+ /**
488
+ * Checks if New Relic telemetry can be initialized
489
+ *
490
+ * Determines if New Relic telemetry is properly configured without actually
491
+ * attempting initialization. Useful for provider chain fallback logic.
492
+ *
493
+ * @param params - Runtime parameters to check
494
+ * @returns true if New Relic is configured and can be initialized
495
+ *
496
+ * @example
497
+ * ```typescript
498
+ * const telemetry = new NewRelicTelemetry();
499
+ * if (telemetry.canInitialize(params)) {
500
+ * // New Relic is configured, use it
501
+ * } else {
502
+ * // Try next provider
503
+ * }
504
+ * ```
505
+ */
506
+ canInitialize(params) {
507
+ return this.validator.isConfigured(params);
344
508
  }
345
- return to.concat(ar || Array.prototype.slice.call(from));
346
- };
347
- API_NAME = "diag";
348
- DiagAPI = /** @class */
349
- (function() {
350
- function DiagAPI2() {
351
- function _logProxy(funcName) {
352
- return function() {
353
- var args = [];
354
- for (var _i = 0; _i < arguments.length; _i++) {
355
- args[_i] = arguments[_i];
509
+ /**
510
+ * Get the OpenTelemetry instrumentation configuration for New Relic
511
+ *
512
+ * Builds and returns the complete instrumentation configuration including:
513
+ * - Service name and preset instrumentations
514
+ * - Custom resource attributes (environment)
515
+ * - OTLP exporters for traces, metrics, and logs
516
+ * - Success/failure detection for actions
517
+ *
518
+ * This method is called internally by `instrumentEntrypoint` to configure
519
+ * telemetry before wrapping the action.
520
+ *
521
+ * @returns Complete entrypoint instrumentation configuration
522
+ * @throws {TelemetryInputError} If required parameters are missing (service name, license key)
523
+ *
524
+ * @example
525
+ * ```typescript
526
+ * const telemetry = new NewRelicTelemetry();
527
+ * const config = telemetry.getConfig();
528
+ * // Returns configuration with exporters, instrumentations, and resource attributes
529
+ * ```
530
+ */
531
+ getConfig() {
532
+ return {
533
+ ...defineTelemetryConfig((params) => {
534
+ if (!this.validator.isConfigured(params)) {
535
+ throw new Error("New Relic telemetry is not configured");
356
536
  }
357
- var logger = getGlobal("diag");
358
- if (!logger)
359
- return;
360
- return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
361
- };
362
- }
363
- __name(_logProxy, "_logProxy");
364
- var self = this;
365
- var setLogger = /* @__PURE__ */ __name(function(logger, optionsOrLogLevel) {
366
- var _a, _b, _c;
367
- if (optionsOrLogLevel === void 0) {
368
- optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
369
- }
370
- if (logger === self) {
371
- var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
372
- self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
373
- return false;
374
- }
375
- if (typeof optionsOrLogLevel === "number") {
376
- optionsOrLogLevel = {
377
- logLevel: optionsOrLogLevel
537
+ this.validator.validateConfiguration(params);
538
+ const serviceName = params.NEW_RELIC_SERVICE_NAME;
539
+ return {
540
+ sdkConfig: {
541
+ serviceName,
542
+ instrumentations: getPresetInstrumentations("simple"),
543
+ resource: this.resourceFactory.createWithEnvironment(params),
544
+ ...this.getExportersConfig(params)
545
+ }
378
546
  };
379
- }
380
- var oldLogger = getGlobal("diag");
381
- var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
382
- if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
383
- var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
384
- oldLogger.warn("Current logger will be overwritten from " + stack);
385
- newLogger.warn("Current logger will overwrite one already registered from " + stack);
386
- }
387
- return registerGlobal("diag", newLogger, self, true);
388
- }, "setLogger");
389
- self.setLogger = setLogger;
390
- self.disable = function() {
391
- unregisterGlobal(API_NAME, self);
547
+ }),
548
+ isSuccessful: this.successChecker.execute.bind(this.successChecker)
392
549
  };
393
- self.createComponentLogger = function(options) {
394
- return new DiagComponentLogger(options);
550
+ }
551
+ /**
552
+ * Configure New Relic exporters for traces, metrics, and logs
553
+ *
554
+ * Creates OTLP exporters for all three signal types (traces, metrics, logs)
555
+ * and configures them to send data to New Relic. Log processors are wrapped
556
+ * with JsonMessageProcessor for better attribute extraction.
557
+ *
558
+ * @param params - Runtime parameters containing NEW_RELIC_LICENSE_KEY and optional NEW_RELIC_URL
559
+ * @returns Configuration object with traceExporter, metricReaders, and logRecordProcessors
560
+ * @private
561
+ */
562
+ getExportersConfig(params) {
563
+ const licenseKey = params.NEW_RELIC_LICENSE_KEY;
564
+ const newRelicUrl = params.NEW_RELIC_URL || "https://otlp.nr-data.net";
565
+ const makeExporterConfig = /* @__PURE__ */ __name((endpoint) => {
566
+ return {
567
+ url: `${newRelicUrl}/${endpoint}`,
568
+ headers: {
569
+ "api-key": licenseKey
570
+ }
571
+ };
572
+ }, "makeExporterConfig");
573
+ return {
574
+ traceExporter: new OTLPTraceExporterProto(makeExporterConfig("v1/traces")),
575
+ metricReaders: [
576
+ new PeriodicExportingMetricReader({
577
+ exporter: new OTLPMetricExporterProto(makeExporterConfig("v1/metrics"))
578
+ })
579
+ ],
580
+ logRecordProcessors: [
581
+ new JsonMessageProcessor(
582
+ new SimpleLogRecordProcessor(new OTLPLogExporterProto(makeExporterConfig("v1/logs")))
583
+ )
584
+ ]
395
585
  };
396
- self.verbose = _logProxy("verbose");
397
- self.debug = _logProxy("debug");
398
- self.info = _logProxy("info");
399
- self.warn = _logProxy("warn");
400
- self.error = _logProxy("error");
401
586
  }
402
- __name(DiagAPI2, "DiagAPI");
403
- DiagAPI2.instance = function() {
404
- if (!this._instance) {
405
- this._instance = new DiagAPI2();
406
- }
407
- return this._instance;
408
- };
409
- return DiagAPI2;
410
- })();
587
+ /**
588
+ * Initialize telemetry instrumentation for a runtime action
589
+ *
590
+ * Wraps the provided action with OpenTelemetry instrumentation using
591
+ * New Relic as the backend. The instrumented action will automatically:
592
+ * - Create spans for the action execution
593
+ * - Export metrics during runtime
594
+ * - Forward logs to New Relic
595
+ * - Track success/failure status
596
+ *
597
+ * This method delegates to `instrumentEntrypoint` from `@adobe/aio-lib-telemetry`,
598
+ * passing the action and New Relic specific configuration.
599
+ *
600
+ * @param action - The runtime action function to instrument
601
+ * @returns The instrumented action function with telemetry enabled
602
+ * @throws {TelemetryInputError} If required configuration is missing
603
+ *
604
+ * @example
605
+ * ```typescript
606
+ * async function myAction(params: Record<string, unknown>) {
607
+ * const logger = Telemetry.createLogger("my-action", params);
608
+ * logger.info("Processing request");
609
+ *
610
+ * return { statusCode: 200, body: { success: true } };
611
+ * }
612
+ *
613
+ * const telemetry = new NewRelicTelemetry();
614
+ * const instrumentedAction = telemetry.initialize(myAction);
615
+ *
616
+ * // instrumentedAction now sends traces, metrics, and logs to New Relic
617
+ * export const main = instrumentedAction;
618
+ * ```
619
+ */
620
+ initialize(action) {
621
+ return instrumentEntrypoint(action, this.getConfig());
622
+ }
623
+ };
624
+ __name(_NewRelicTelemetry, "NewRelicTelemetry");
625
+ NewRelicTelemetry = _NewRelicTelemetry;
626
+ new_relic_default = NewRelicTelemetry;
411
627
  }
412
628
  });
413
629
 
414
- // node_modules/@opentelemetry/api/build/esm/diag-api.js
415
- var diag;
416
- var init_diag_api = __esm({
417
- "node_modules/@opentelemetry/api/build/esm/diag-api.js"() {
418
- "use strict";
419
- init_diag();
420
- diag = DiagAPI.instance();
421
- }
422
- });
630
+ // src/index.ts
631
+ init_esm_shims();
423
632
 
424
- // node_modules/@opentelemetry/api/build/esm/index.js
425
- var init_esm = __esm({
426
- "node_modules/@opentelemetry/api/build/esm/index.js"() {
427
- "use strict";
428
- init_diag_api();
429
- }
430
- });
633
+ // src/framework/index.ts
634
+ init_esm_shims();
635
+
636
+ // src/framework/runtime-action/index.ts
637
+ init_esm_shims();
638
+
639
+ // src/framework/runtime-action/response/index.ts
640
+ init_esm_shims();
431
641
 
432
642
  // src/framework/runtime-action/types.ts
643
+ init_esm_shims();
433
644
  var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
434
645
  HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
435
646
  HttpStatus2[HttpStatus2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
@@ -492,6 +703,7 @@ var RuntimeActionResponse = _RuntimeActionResponse;
492
703
  var response_default = RuntimeActionResponse;
493
704
 
494
705
  // src/framework/runtime-action/validator/index.ts
706
+ init_esm_shims();
495
707
  var _Validator = class _Validator {
496
708
  /**
497
709
  * Returns the list of missing keys given an object and its required keys.
@@ -557,701 +769,8 @@ var Validator = _Validator;
557
769
  var validator_default = Validator;
558
770
 
559
771
  // src/framework/telemetry/index.ts
772
+ init_esm_shims();
560
773
  import { Core } from "@adobe/aio-sdk";
561
- import { getLogger } from "@adobe/aio-lib-telemetry";
562
-
563
- // src/framework/telemetry/new-relic/index.ts
564
- import {
565
- defineTelemetryConfig,
566
- getPresetInstrumentations,
567
- instrumentEntrypoint
568
- } from "@adobe/aio-lib-telemetry";
569
-
570
- // src/framework/telemetry/helpers/input-error/index.ts
571
- var _TelemetryInputError = class _TelemetryInputError extends Error {
572
- /**
573
- * Creates a new TelemetryInputError
574
- *
575
- * @param message - Descriptive error message explaining the validation failure
576
- */
577
- constructor(message) {
578
- super(message);
579
- this.name = "TelemetryInputError";
580
- if (Error.captureStackTrace) {
581
- Error.captureStackTrace(this, _TelemetryInputError);
582
- }
583
- }
584
- };
585
- __name(_TelemetryInputError, "TelemetryInputError");
586
- var TelemetryInputError = _TelemetryInputError;
587
-
588
- // src/framework/telemetry/new-relic/validator/index.ts
589
- var _NewRelicTelemetryValidator = class _NewRelicTelemetryValidator {
590
- /**
591
- * Checks if New Relic telemetry is configured
592
- *
593
- * Returns true if:
594
- * - ENABLE_TELEMETRY is explicitly set to true
595
- * - NEW_RELIC_TELEMETRY is explicitly set to true
596
- *
597
- * This method does NOT validate the completeness of configuration,
598
- * it only checks if the provider is enabled.
599
- *
600
- * @param params - Runtime parameters to check
601
- * @returns true if New Relic telemetry is enabled, false otherwise
602
- *
603
- * @example
604
- * ```typescript
605
- * const validator = new NewRelicTelemetryValidator();
606
- * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };
607
- * if (validator.isConfigured(params)) {
608
- * // New Relic is enabled, proceed with initialization
609
- * }
610
- * ```
611
- */
612
- isConfigured(params) {
613
- return params.ENABLE_TELEMETRY === true && params.NEW_RELIC_TELEMETRY === true;
614
- }
615
- /**
616
- * Validates New Relic specific parameters
617
- *
618
- * IMPORTANT: Only call this method after checking isConfigured() returns true.
619
- * This method assumes New Relic telemetry is enabled and validates that
620
- * all required parameters are present.
621
- *
622
- * Required parameters when New Relic is enabled:
623
- * - NEW_RELIC_SERVICE_NAME must be provided
624
- * - NEW_RELIC_LICENSE_KEY must be provided
625
- *
626
- * @param params - Runtime parameters to validate
627
- * @throws {TelemetryInputError} If NEW_RELIC_SERVICE_NAME is missing
628
- * @throws {TelemetryInputError} If NEW_RELIC_LICENSE_KEY is missing
629
- *
630
- * @example
631
- * ```typescript
632
- * const validator = new NewRelicTelemetryValidator();
633
- * const params = {
634
- * ENABLE_TELEMETRY: true,
635
- * NEW_RELIC_TELEMETRY: true,
636
- * NEW_RELIC_SERVICE_NAME: "my-service",
637
- * NEW_RELIC_LICENSE_KEY: "license-key"
638
- * };
639
- *
640
- * if (validator.isConfigured(params)) {
641
- * validator.validateConfiguration(params); // Validates required fields
642
- * }
643
- * ```
644
- */
645
- validateConfiguration(params) {
646
- if (params.NEW_RELIC_SERVICE_NAME === void 0 || params.NEW_RELIC_SERVICE_NAME === null || params.NEW_RELIC_SERVICE_NAME === "") {
647
- throw new TelemetryInputError("NEW_RELIC_SERVICE_NAME is required");
648
- }
649
- if (params.NEW_RELIC_LICENSE_KEY === void 0 || params.NEW_RELIC_LICENSE_KEY === null || params.NEW_RELIC_LICENSE_KEY === "") {
650
- throw new TelemetryInputError("NEW_RELIC_LICENSE_KEY is required");
651
- }
652
- }
653
- };
654
- __name(_NewRelicTelemetryValidator, "NewRelicTelemetryValidator");
655
- var NewRelicTelemetryValidator = _NewRelicTelemetryValidator;
656
-
657
- // src/framework/telemetry/helpers/resource-factory/index.ts
658
- import { getAioRuntimeResource } from "@adobe/aio-lib-telemetry";
659
-
660
- // node_modules/@opentelemetry/resources/build/esm/ResourceImpl.js
661
- init_esm();
662
-
663
- // node_modules/@opentelemetry/resources/build/esm/utils.js
664
- var isPromiseLike = /* @__PURE__ */ __name((val) => {
665
- return val !== null && typeof val === "object" && typeof val.then === "function";
666
- }, "isPromiseLike");
667
-
668
- // node_modules/@opentelemetry/resources/build/esm/ResourceImpl.js
669
- var _ResourceImpl = class _ResourceImpl {
670
- constructor(resource, options) {
671
- __publicField(this, "_rawAttributes");
672
- __publicField(this, "_asyncAttributesPending", false);
673
- __publicField(this, "_schemaUrl");
674
- __publicField(this, "_memoizedAttributes");
675
- const attributes = resource.attributes ?? {};
676
- this._rawAttributes = Object.entries(attributes).map(([k, v]) => {
677
- if (isPromiseLike(v)) {
678
- this._asyncAttributesPending = true;
679
- }
680
- return [k, v];
681
- });
682
- this._rawAttributes = guardedRawAttributes(this._rawAttributes);
683
- this._schemaUrl = validateSchemaUrl(options?.schemaUrl);
684
- }
685
- static FromAttributeList(attributes, options) {
686
- const res = new _ResourceImpl({}, options);
687
- res._rawAttributes = guardedRawAttributes(attributes);
688
- res._asyncAttributesPending = attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;
689
- return res;
690
- }
691
- get asyncAttributesPending() {
692
- return this._asyncAttributesPending;
693
- }
694
- async waitForAsyncAttributes() {
695
- if (!this.asyncAttributesPending) {
696
- return;
697
- }
698
- for (let i = 0; i < this._rawAttributes.length; i++) {
699
- const [k, v] = this._rawAttributes[i];
700
- this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];
701
- }
702
- this._asyncAttributesPending = false;
703
- }
704
- get attributes() {
705
- if (this.asyncAttributesPending) {
706
- diag.error("Accessing resource attributes before async attributes settled");
707
- }
708
- if (this._memoizedAttributes) {
709
- return this._memoizedAttributes;
710
- }
711
- const attrs = {};
712
- for (const [k, v] of this._rawAttributes) {
713
- if (isPromiseLike(v)) {
714
- diag.debug(`Unsettled resource attribute ${k} skipped`);
715
- continue;
716
- }
717
- if (v != null) {
718
- attrs[k] ?? (attrs[k] = v);
719
- }
720
- }
721
- if (!this._asyncAttributesPending) {
722
- this._memoizedAttributes = attrs;
723
- }
724
- return attrs;
725
- }
726
- getRawAttributes() {
727
- return this._rawAttributes;
728
- }
729
- get schemaUrl() {
730
- return this._schemaUrl;
731
- }
732
- merge(resource) {
733
- if (resource == null)
734
- return this;
735
- const mergedSchemaUrl = mergeSchemaUrl(this, resource);
736
- const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : void 0;
737
- return _ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions);
738
- }
739
- };
740
- __name(_ResourceImpl, "ResourceImpl");
741
- var ResourceImpl = _ResourceImpl;
742
- function resourceFromAttributes(attributes, options) {
743
- return ResourceImpl.FromAttributeList(Object.entries(attributes), options);
744
- }
745
- __name(resourceFromAttributes, "resourceFromAttributes");
746
- function guardedRawAttributes(attributes) {
747
- return attributes.map(([k, v]) => {
748
- if (isPromiseLike(v)) {
749
- return [
750
- k,
751
- v.catch((err) => {
752
- diag.debug("promise rejection for resource attribute: %s - %s", k, err);
753
- return void 0;
754
- })
755
- ];
756
- }
757
- return [k, v];
758
- });
759
- }
760
- __name(guardedRawAttributes, "guardedRawAttributes");
761
- function validateSchemaUrl(schemaUrl) {
762
- if (typeof schemaUrl === "string" || schemaUrl === void 0) {
763
- return schemaUrl;
764
- }
765
- diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl);
766
- return void 0;
767
- }
768
- __name(validateSchemaUrl, "validateSchemaUrl");
769
- function mergeSchemaUrl(old, updating) {
770
- const oldSchemaUrl = old?.schemaUrl;
771
- const updatingSchemaUrl = updating?.schemaUrl;
772
- const isOldEmpty = oldSchemaUrl === void 0 || oldSchemaUrl === "";
773
- const isUpdatingEmpty = updatingSchemaUrl === void 0 || updatingSchemaUrl === "";
774
- if (isOldEmpty) {
775
- return updatingSchemaUrl;
776
- }
777
- if (isUpdatingEmpty) {
778
- return oldSchemaUrl;
779
- }
780
- if (oldSchemaUrl === updatingSchemaUrl) {
781
- return oldSchemaUrl;
782
- }
783
- diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl);
784
- return void 0;
785
- }
786
- __name(mergeSchemaUrl, "mergeSchemaUrl");
787
-
788
- // src/framework/telemetry/helpers/resource-factory/index.ts
789
- var _ResourceFactory = class _ResourceFactory {
790
- /**
791
- * Creates a resource with custom environment attributes
792
- *
793
- * Starts with the base Adobe I/O Runtime resource and optionally
794
- * merges environment attributes. These attributes are useful for
795
- * filtering and correlating telemetry data by deployment environment.
796
- *
797
- * Note: Request-specific data (like request IDs) should NOT be added to
798
- * Resources as they are created once and reused across all requests.
799
- * Use log attributes or span attributes for request-specific data.
800
- *
801
- * @param params - Runtime parameters containing optional ENVIRONMENT
802
- * @param params.ENVIRONMENT - Environment name (e.g., "dev", "stage", "prod")
803
- * @returns OpenTelemetry Resource with custom attributes if provided
804
- *
805
- * @example Without custom attributes
806
- * ```typescript
807
- * const factory = new ResourceFactory();
808
- * const resource = factory.createWithEnvironment({});
809
- * // Returns base Adobe I/O Runtime resource
810
- * ```
811
- *
812
- * @example With environment
813
- * ```typescript
814
- * const factory = new ResourceFactory();
815
- * const params = { ENVIRONMENT: "production" };
816
- * const resource = factory.createWithEnvironment(params);
817
- * // Returns resource with environment="production" attribute
818
- * ```
819
- */
820
- createWithEnvironment(params) {
821
- const baseResource = getAioRuntimeResource();
822
- const customAttributes = {};
823
- if (params.ENVIRONMENT) {
824
- customAttributes.environment = params.ENVIRONMENT;
825
- }
826
- if (Object.keys(customAttributes).length === 0) {
827
- return baseResource;
828
- }
829
- const customResource = resourceFromAttributes(
830
- customAttributes
831
- );
832
- return baseResource.merge(customResource);
833
- }
834
- };
835
- __name(_ResourceFactory, "ResourceFactory");
836
- var ResourceFactory = _ResourceFactory;
837
-
838
- // src/framework/telemetry/helpers/success-checker/index.ts
839
- var _SuccessChecker = class _SuccessChecker {
840
- /**
841
- * Determines if an action execution was successful
842
- *
843
- * Success criteria:
844
- * - Response has statusCode 200
845
- * - Body does not contain an exception operation
846
- *
847
- * @param result - The action execution result
848
- * @returns true if successful, false otherwise
849
- *
850
- * @example Success case
851
- * ```typescript
852
- * const checker = new SuccessChecker();
853
- * const result = { statusCode: 200, body: { data: 'success' } };
854
- * checker.execute(result); // true
855
- * ```
856
- *
857
- * @example Failure case - wrong status code
858
- * ```typescript
859
- * const checker = new SuccessChecker();
860
- * const result = { statusCode: 500, body: { error: 'Internal error' } };
861
- * checker.execute(result); // false
862
- * ```
863
- *
864
- * @example Failure case - exception in body
865
- * ```typescript
866
- * const checker = new SuccessChecker();
867
- * const result = { statusCode: 200, body: { op: 'exception', message: 'Error' } };
868
- * checker.execute(result); // false
869
- * ```
870
- */
871
- execute(result) {
872
- if (!result || typeof result !== "object") {
873
- return false;
874
- }
875
- const actionResult = result;
876
- if (actionResult.statusCode !== 200) {
877
- return false;
878
- }
879
- if (actionResult.body && typeof actionResult.body === "object") {
880
- return actionResult.body.op !== "exception";
881
- }
882
- return true;
883
- }
884
- };
885
- __name(_SuccessChecker, "SuccessChecker");
886
- var SuccessChecker = _SuccessChecker;
887
-
888
- // src/framework/telemetry/new-relic/index.ts
889
- import {
890
- OTLPLogExporterProto,
891
- OTLPMetricExporterProto,
892
- OTLPTraceExporterProto,
893
- PeriodicExportingMetricReader,
894
- SimpleLogRecordProcessor
895
- } from "@adobe/aio-lib-telemetry/otel";
896
-
897
- // src/framework/telemetry/helpers/json-message-processor/index.ts
898
- var _JsonMessageProcessor = class _JsonMessageProcessor {
899
- /**
900
- * Creates a new JsonMessageProcessor
901
- *
902
- * @param wrappedProcessor - The log processor to wrap and enhance
903
- *
904
- * @example
905
- * ```typescript
906
- * const exporter = new OTLPLogExporterProto({
907
- * url: "https://otlp.nr-data.net/v1/logs",
908
- * headers: { "api-key": licenseKey }
909
- * });
910
- * const baseProcessor = new SimpleLogRecordProcessor(exporter);
911
- * const processor = new JsonMessageProcessor(baseProcessor);
912
- * ```
913
- */
914
- constructor(wrappedProcessor) {
915
- this.wrappedProcessor = wrappedProcessor;
916
- }
917
- /**
918
- * Parse JavaScript object notation and convert to proper object
919
- *
920
- * Handles Winston's util.inspect format which produces JavaScript
921
- * object literals instead of JSON strings.
922
- *
923
- * Examples:
924
- * - { key: 'value' } → {"key":"value"}
925
- * - { 'accept-encoding': 'gzip' } → {"accept-encoding":"gzip"}
926
- *
927
- * @param str - JavaScript object notation string
928
- * @returns Parsed object
929
- * @throws Error if parsing fails
930
- * @private
931
- */
932
- parseJavaScriptObjectNotation(str) {
933
- const func = new Function("return (" + str + ")");
934
- return func();
935
- }
936
- /**
937
- * Flatten nested objects into dot-notation keys
938
- *
939
- * Converts nested structures like:
940
- * { headers: { accept: '*' } }
941
- *
942
- * Into flat structure:
943
- * { 'headers.accept': '*' }
944
- *
945
- * This makes all attributes searchable in observability platforms.
946
- *
947
- * @param obj - Object to flatten
948
- * @param prefix - Current key prefix (used in recursion)
949
- * @returns Flattened object with dot-notation keys
950
- * @private
951
- */
952
- flattenObject(obj, prefix = "") {
953
- const flattened = {};
954
- for (const [key, value] of Object.entries(obj)) {
955
- const newKey = prefix ? `${prefix}.${key}` : key;
956
- if (value === null || value === void 0) {
957
- flattened[newKey] = value;
958
- } else if (Array.isArray(value)) {
959
- flattened[newKey] = JSON.stringify(value);
960
- } else if (typeof value === "object") {
961
- if (Object.keys(value).length === 0) {
962
- continue;
963
- }
964
- const nested = this.flattenObject(value, newKey);
965
- Object.assign(flattened, nested);
966
- } else {
967
- flattened[newKey] = value;
968
- }
969
- }
970
- return flattened;
971
- }
972
- /**
973
- * Processes a log record by parsing JSON messages and extracting attributes
974
- *
975
- * This method intercepts log records, attempts to parse structured data
976
- * from the message body, and merges extracted properties as attributes.
977
- * Additionally, it extracts the log level from the severity information
978
- * and adds it as a 'level' attribute for easier querying.
979
- *
980
- * The enhanced log record is then passed to the wrapped processor.
981
- *
982
- * @param logRecord - The log record to process
983
- *
984
- * @remarks
985
- * Processing steps:
986
- * 1. Extract log level from severityText or severityNumber
987
- * 2. Add 'level' attribute (debug, info, warn, error, etc.)
988
- * 3. Parse JSON bodies that start with '{'
989
- * 4. Extract properties as individual attributes
990
- * 5. Preserve 'message' field as primary log body
991
- *
992
- * Error handling:
993
- * - Silently handles parsing errors to avoid breaking the logging pipeline
994
- * - Failed parsing results in unmodified log record
995
- */
996
- onEmit(logRecord) {
997
- try {
998
- if (logRecord.severityText) {
999
- logRecord.setAttribute("level", logRecord.severityText.toLowerCase());
1000
- } else if (logRecord.severityNumber !== void 0) {
1001
- const levelName = this.mapSeverityNumberToLevel(logRecord.severityNumber);
1002
- if (levelName) {
1003
- logRecord.setAttribute("level", levelName);
1004
- }
1005
- }
1006
- const body = logRecord.body;
1007
- if (typeof body === "string" && body.trim().startsWith("{")) {
1008
- let parsed = null;
1009
- try {
1010
- parsed = JSON.parse(body);
1011
- } catch {
1012
- try {
1013
- parsed = this.parseJavaScriptObjectNotation(body);
1014
- } catch {
1015
- }
1016
- }
1017
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1018
- const messageValue = parsed.message;
1019
- const { message, ...attributesObj } = parsed;
1020
- const flattenedAttributes = this.flattenObject(attributesObj);
1021
- Object.entries(flattenedAttributes).forEach(([key, value]) => {
1022
- if (value !== void 0 && value !== null) {
1023
- logRecord.setAttribute(key, value);
1024
- }
1025
- });
1026
- if (messageValue) {
1027
- logRecord.body = messageValue;
1028
- }
1029
- }
1030
- }
1031
- } catch {
1032
- }
1033
- this.wrappedProcessor.onEmit(logRecord);
1034
- }
1035
- /**
1036
- * Maps OpenTelemetry severity number to log level name
1037
- *
1038
- * OpenTelemetry defines severity numbers from 1-24:
1039
- * - 1-4: TRACE
1040
- * - 5-8: DEBUG
1041
- * - 9-12: INFO
1042
- * - 13-16: WARN
1043
- * - 17-20: ERROR
1044
- * - 21-24: FATAL
1045
- *
1046
- * @param severityNumber - OpenTelemetry severity number
1047
- * @returns Log level name (trace, debug, info, warn, error, fatal) or null
1048
- * @private
1049
- */
1050
- mapSeverityNumberToLevel(severityNumber) {
1051
- if (severityNumber >= 1 && severityNumber <= 4) return "trace";
1052
- if (severityNumber >= 5 && severityNumber <= 8) return "debug";
1053
- if (severityNumber >= 9 && severityNumber <= 12) return "info";
1054
- if (severityNumber >= 13 && severityNumber <= 16) return "warn";
1055
- if (severityNumber >= 17 && severityNumber <= 20) return "error";
1056
- if (severityNumber >= 21 && severityNumber <= 24) return "fatal";
1057
- return null;
1058
- }
1059
- /**
1060
- * Forces the processor to flush any pending log records
1061
- *
1062
- * Delegates to the wrapped processor's forceFlush method.
1063
- * Useful for ensuring logs are sent before application shutdown.
1064
- *
1065
- * @returns Promise that resolves when flush is complete
1066
- *
1067
- * @example
1068
- * ```typescript
1069
- * await processor.forceFlush();
1070
- * console.log("All logs have been sent");
1071
- * ```
1072
- */
1073
- async forceFlush() {
1074
- return this.wrappedProcessor.forceFlush();
1075
- }
1076
- /**
1077
- * Shuts down the processor and releases resources
1078
- *
1079
- * Delegates to the wrapped processor's shutdown method.
1080
- * Should be called when the application is terminating.
1081
- *
1082
- * @returns Promise that resolves when shutdown is complete
1083
- *
1084
- * @example
1085
- * ```typescript
1086
- * await processor.shutdown();
1087
- * console.log("Processor has been shut down");
1088
- * ```
1089
- */
1090
- async shutdown() {
1091
- return this.wrappedProcessor.shutdown();
1092
- }
1093
- };
1094
- __name(_JsonMessageProcessor, "JsonMessageProcessor");
1095
- var JsonMessageProcessor = _JsonMessageProcessor;
1096
-
1097
- // src/framework/telemetry/new-relic/index.ts
1098
- var _NewRelicTelemetry = class _NewRelicTelemetry {
1099
- /**
1100
- * Constructor for New Relic telemetry
1101
- *
1102
- * @description Constructor for New Relic telemetry
1103
- * @example
1104
- * ```typescript
1105
- * const telemetry = new NewRelicTelemetry();
1106
- * ```
1107
- */
1108
- constructor() {
1109
- this.validator = new NewRelicTelemetryValidator();
1110
- this.successChecker = new SuccessChecker();
1111
- this.resourceFactory = new ResourceFactory();
1112
- }
1113
- /**
1114
- * Checks if New Relic telemetry can be initialized
1115
- *
1116
- * Determines if New Relic telemetry is properly configured without actually
1117
- * attempting initialization. Useful for provider chain fallback logic.
1118
- *
1119
- * @param params - Runtime parameters to check
1120
- * @returns true if New Relic is configured and can be initialized
1121
- *
1122
- * @example
1123
- * ```typescript
1124
- * const telemetry = new NewRelicTelemetry();
1125
- * if (telemetry.canInitialize(params)) {
1126
- * // New Relic is configured, use it
1127
- * } else {
1128
- * // Try next provider
1129
- * }
1130
- * ```
1131
- */
1132
- canInitialize(params) {
1133
- return this.validator.isConfigured(params);
1134
- }
1135
- /**
1136
- * Get the OpenTelemetry instrumentation configuration for New Relic
1137
- *
1138
- * Builds and returns the complete instrumentation configuration including:
1139
- * - Service name and preset instrumentations
1140
- * - Custom resource attributes (environment)
1141
- * - OTLP exporters for traces, metrics, and logs
1142
- * - Success/failure detection for actions
1143
- *
1144
- * This method is called internally by `instrumentEntrypoint` to configure
1145
- * telemetry before wrapping the action.
1146
- *
1147
- * @returns Complete entrypoint instrumentation configuration
1148
- * @throws {TelemetryInputError} If required parameters are missing (service name, license key)
1149
- *
1150
- * @example
1151
- * ```typescript
1152
- * const telemetry = new NewRelicTelemetry();
1153
- * const config = telemetry.getConfig();
1154
- * // Returns configuration with exporters, instrumentations, and resource attributes
1155
- * ```
1156
- */
1157
- getConfig() {
1158
- return {
1159
- ...defineTelemetryConfig((params) => {
1160
- if (!this.validator.isConfigured(params)) {
1161
- throw new Error("New Relic telemetry is not configured");
1162
- }
1163
- this.validator.validateConfiguration(params);
1164
- const serviceName = params.NEW_RELIC_SERVICE_NAME;
1165
- return {
1166
- sdkConfig: {
1167
- serviceName,
1168
- instrumentations: getPresetInstrumentations("simple"),
1169
- resource: this.resourceFactory.createWithEnvironment(params),
1170
- ...this.getExportersConfig(params)
1171
- }
1172
- };
1173
- }),
1174
- isSuccessful: this.successChecker.execute.bind(this.successChecker)
1175
- };
1176
- }
1177
- /**
1178
- * Configure New Relic exporters for traces, metrics, and logs
1179
- *
1180
- * Creates OTLP exporters for all three signal types (traces, metrics, logs)
1181
- * and configures them to send data to New Relic. Log processors are wrapped
1182
- * with JsonMessageProcessor for better attribute extraction.
1183
- *
1184
- * @param params - Runtime parameters containing NEW_RELIC_LICENSE_KEY and optional NEW_RELIC_URL
1185
- * @returns Configuration object with traceExporter, metricReaders, and logRecordProcessors
1186
- * @private
1187
- */
1188
- getExportersConfig(params) {
1189
- const licenseKey = params.NEW_RELIC_LICENSE_KEY;
1190
- const newRelicUrl = params.NEW_RELIC_URL || "https://otlp.nr-data.net";
1191
- const makeExporterConfig = /* @__PURE__ */ __name((endpoint) => {
1192
- return {
1193
- url: `${newRelicUrl}/${endpoint}`,
1194
- headers: {
1195
- "api-key": licenseKey
1196
- }
1197
- };
1198
- }, "makeExporterConfig");
1199
- return {
1200
- traceExporter: new OTLPTraceExporterProto(makeExporterConfig("v1/traces")),
1201
- metricReaders: [
1202
- new PeriodicExportingMetricReader({
1203
- exporter: new OTLPMetricExporterProto(makeExporterConfig("v1/metrics"))
1204
- })
1205
- ],
1206
- logRecordProcessors: [
1207
- new JsonMessageProcessor(
1208
- new SimpleLogRecordProcessor(new OTLPLogExporterProto(makeExporterConfig("v1/logs")))
1209
- )
1210
- ]
1211
- };
1212
- }
1213
- /**
1214
- * Initialize telemetry instrumentation for a runtime action
1215
- *
1216
- * Wraps the provided action with OpenTelemetry instrumentation using
1217
- * New Relic as the backend. The instrumented action will automatically:
1218
- * - Create spans for the action execution
1219
- * - Export metrics during runtime
1220
- * - Forward logs to New Relic
1221
- * - Track success/failure status
1222
- *
1223
- * This method delegates to `instrumentEntrypoint` from `@adobe/aio-lib-telemetry`,
1224
- * passing the action and New Relic specific configuration.
1225
- *
1226
- * @param action - The runtime action function to instrument
1227
- * @returns The instrumented action function with telemetry enabled
1228
- * @throws {TelemetryInputError} If required configuration is missing
1229
- *
1230
- * @example
1231
- * ```typescript
1232
- * async function myAction(params: Record<string, unknown>) {
1233
- * const logger = Telemetry.createLogger("my-action", params);
1234
- * logger.info("Processing request");
1235
- *
1236
- * return { statusCode: 200, body: { success: true } };
1237
- * }
1238
- *
1239
- * const telemetry = new NewRelicTelemetry();
1240
- * const instrumentedAction = telemetry.initialize(myAction);
1241
- *
1242
- * // instrumentedAction now sends traces, metrics, and logs to New Relic
1243
- * export const main = instrumentedAction;
1244
- * ```
1245
- */
1246
- initialize(action) {
1247
- return instrumentEntrypoint(action, this.getConfig());
1248
- }
1249
- };
1250
- __name(_NewRelicTelemetry, "NewRelicTelemetry");
1251
- var NewRelicTelemetry = _NewRelicTelemetry;
1252
- var new_relic_default = NewRelicTelemetry;
1253
-
1254
- // src/framework/telemetry/index.ts
1255
774
  var _Telemetry = class _Telemetry {
1256
775
  /**
1257
776
  * Create a logger with standard configuration and automatic metadata injection.
@@ -1261,7 +780,7 @@ var _Telemetry = class _Telemetry {
1261
780
  * - `x-adobe-commerce-request-id`: Extracted from `__ow_headers` (when present)
1262
781
  * - `action.type`: Extracted from `params.action_type` (when present)
1263
782
  *
1264
- * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger; otherwise uses Core.Logger.
783
+ * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger (lazy-loaded); otherwise uses Core.Logger.
1265
784
  * The environment from params.ENVIRONMENT is set at the resource level and will
1266
785
  * automatically appear in all logs sent to New Relic if ENABLE_TELEMETRY is true.
1267
786
  *
@@ -1298,11 +817,59 @@ var _Telemetry = class _Telemetry {
1298
817
  * ```
1299
818
  */
1300
819
  static createLogger(name, params) {
1301
- const baseLogger = !params.ENABLE_TELEMETRY ? Core.Logger(name, {
1302
- level: params.LOG_LEVEL || "info"
1303
- }) : getLogger(name, {
1304
- level: params.LOG_LEVEL || "info"
820
+ const logLevel = params.LOG_LEVEL || "info";
821
+ if (!params.ENABLE_TELEMETRY) {
822
+ const baseLogger = Core.Logger(name, { level: logLevel });
823
+ return _Telemetry.wrapLogger(baseLogger, params);
824
+ }
825
+ let telemetryLogger = null;
826
+ let loadingPromise = null;
827
+ const fallbackLogger = Core.Logger(name, { level: logLevel });
828
+ const loadTelemetryLogger = /* @__PURE__ */ __name(async () => {
829
+ if (telemetryLogger || loadingPromise) {
830
+ return;
831
+ }
832
+ loadingPromise = (async () => {
833
+ try {
834
+ const { getLogger } = await import("@adobe/aio-lib-telemetry");
835
+ telemetryLogger = getLogger(name, { level: logLevel });
836
+ } catch (error) {
837
+ telemetryLogger = fallbackLogger;
838
+ }
839
+ })();
840
+ await loadingPromise;
841
+ }, "loadTelemetryLogger");
842
+ loadTelemetryLogger().catch(() => {
1305
843
  });
844
+ const proxyLogger = {
845
+ debug: /* @__PURE__ */ __name((message) => {
846
+ const logger = telemetryLogger || fallbackLogger;
847
+ logger.debug(message);
848
+ }, "debug"),
849
+ info: /* @__PURE__ */ __name((message) => {
850
+ const logger = telemetryLogger || fallbackLogger;
851
+ logger.info(message);
852
+ }, "info"),
853
+ warn: /* @__PURE__ */ __name((message) => {
854
+ const logger = telemetryLogger || fallbackLogger;
855
+ logger.warn(message);
856
+ }, "warn"),
857
+ error: /* @__PURE__ */ __name((message) => {
858
+ const logger = telemetryLogger || fallbackLogger;
859
+ logger.error(message);
860
+ }, "error")
861
+ };
862
+ return _Telemetry.wrapLogger(proxyLogger, params);
863
+ }
864
+ /**
865
+ * Wrap a logger with automatic metadata injection
866
+ *
867
+ * @private
868
+ * @param baseLogger - The base logger to wrap
869
+ * @param params - Runtime parameters containing optional metadata
870
+ * @returns Wrapped logger with metadata injection
871
+ */
872
+ static wrapLogger(baseLogger, params) {
1306
873
  const metadata = {};
1307
874
  const headers = params.__ow_headers;
1308
875
  const requestId = headers?.["x-adobe-commerce-request-id"];
@@ -1450,16 +1017,27 @@ var _Telemetry = class _Telemetry {
1450
1017
  */
1451
1018
  static initialize(action) {
1452
1019
  return async (params) => {
1453
- const newRelicTelemetry = new new_relic_default();
1454
- if (newRelicTelemetry.canInitialize(params)) {
1020
+ if (params.ENABLE_TELEMETRY && params.NEW_RELIC_TELEMETRY) {
1455
1021
  try {
1456
- const instrumentedAction = newRelicTelemetry.initialize(action);
1457
- return await instrumentedAction(params);
1022
+ const { default: NewRelicTelemetry2 } = await Promise.resolve().then(() => (init_new_relic(), new_relic_exports));
1023
+ const newRelicTelemetry = new NewRelicTelemetry2();
1024
+ if (newRelicTelemetry.canInitialize(params)) {
1025
+ try {
1026
+ const instrumentedAction = newRelicTelemetry.initialize(action);
1027
+ return await instrumentedAction(params);
1028
+ } catch (error) {
1029
+ const errorMessage = error instanceof Error ? error.message : "Telemetry initialization failed";
1030
+ return response_default.error(
1031
+ 500 /* INTERNAL_ERROR */,
1032
+ `Telemetry configuration error: ${errorMessage}`
1033
+ );
1034
+ }
1035
+ }
1458
1036
  } catch (error) {
1459
- const errorMessage = error instanceof Error ? error.message : "Telemetry initialization failed";
1037
+ const errorMessage = error instanceof Error ? error.message : "Failed to load telemetry module";
1460
1038
  return response_default.error(
1461
1039
  500 /* INTERNAL_ERROR */,
1462
- `Telemetry configuration error: ${errorMessage}`
1040
+ `Telemetry module error: ${errorMessage}`
1463
1041
  );
1464
1042
  }
1465
1043
  }
@@ -1659,7 +1237,11 @@ _RuntimeAction.actionType = "runtime-action";
1659
1237
  var RuntimeAction = _RuntimeAction;
1660
1238
  var runtime_action_default = RuntimeAction;
1661
1239
 
1240
+ // src/framework/runtime-action/response/types.ts
1241
+ init_esm_shims();
1242
+
1662
1243
  // src/framework/runtime-action/parameters/index.ts
1244
+ init_esm_shims();
1663
1245
  var _Parameters = class _Parameters {
1664
1246
  /**
1665
1247
  * Returns a log-ready string of the action input parameters.
@@ -1682,6 +1264,7 @@ var Parameters = _Parameters;
1682
1264
  var parameters_default = Parameters;
1683
1265
 
1684
1266
  // src/framework/event-consumer-action/index.ts
1267
+ init_esm_shims();
1685
1268
  var _EventConsumerAction = class _EventConsumerAction {
1686
1269
  /**
1687
1270
  * Creates an event consumer action handler with telemetry integration
@@ -1768,6 +1351,7 @@ var EventConsumerAction = _EventConsumerAction;
1768
1351
  var event_consumer_action_default = EventConsumerAction;
1769
1352
 
1770
1353
  // src/framework/graphql-action/index.ts
1354
+ init_esm_shims();
1771
1355
  import { graphql, buildSchema, parse, validate } from "graphql";
1772
1356
  var _GraphQlAction = class _GraphQlAction {
1773
1357
  static execute(schema = `
@@ -1845,6 +1429,7 @@ var GraphQlAction = _GraphQlAction;
1845
1429
  var graphql_action_default = GraphQlAction;
1846
1430
 
1847
1431
  // src/framework/openwhisk/index.ts
1432
+ init_esm_shims();
1848
1433
  import openwhisk from "openwhisk";
1849
1434
  var _Openwhisk = class _Openwhisk {
1850
1435
  /**
@@ -1872,6 +1457,7 @@ var Openwhisk = _Openwhisk;
1872
1457
  var openwhisk_default = Openwhisk;
1873
1458
 
1874
1459
  // src/framework/openwhisk-action/index.ts
1460
+ init_esm_shims();
1875
1461
  var _OpenwhiskAction = class _OpenwhiskAction {
1876
1462
  /**
1877
1463
  * Creates an OpenWhisk webhook action handler with logging and telemetry
@@ -1956,6 +1542,7 @@ var OpenwhiskAction = _OpenwhiskAction;
1956
1542
  var openwhisk_action_default = OpenwhiskAction;
1957
1543
 
1958
1544
  // src/framework/repository/file-repository/index.ts
1545
+ init_esm_shims();
1959
1546
  import { Files } from "@adobe/aio-sdk";
1960
1547
  var _FileRepository = class _FileRepository {
1961
1548
  /**
@@ -2112,12 +1699,17 @@ __name(_FileRepository, "FileRepository");
2112
1699
  var FileRepository = _FileRepository;
2113
1700
  var file_repository_default = FileRepository;
2114
1701
 
1702
+ // src/framework/repository/file-repository/types.ts
1703
+ init_esm_shims();
1704
+
2115
1705
  // src/framework/publish-event/index.ts
1706
+ init_esm_shims();
2116
1707
  import { Events } from "@adobe/aio-sdk";
2117
1708
  import { CloudEvent } from "cloudevents";
2118
1709
  import { v4 as uuidv4 } from "uuid";
2119
1710
 
2120
1711
  // src/framework/custom-logger/index.ts
1712
+ init_esm_shims();
2121
1713
  var _CustomLogger = class _CustomLogger {
2122
1714
  /**
2123
1715
  * @param logger - External logger instance (can be null)
@@ -2252,7 +1844,17 @@ __name(_PublishEvent, "PublishEvent");
2252
1844
  var PublishEvent = _PublishEvent;
2253
1845
  var publish_event_default = PublishEvent;
2254
1846
 
1847
+ // src/framework/publish-event/types.ts
1848
+ init_esm_shims();
1849
+
1850
+ // src/framework/webhook-action/index.ts
1851
+ init_esm_shims();
1852
+
1853
+ // src/framework/webhook-action/response/index.ts
1854
+ init_esm_shims();
1855
+
2255
1856
  // src/framework/webhook-action/response/types.ts
1857
+ init_esm_shims();
2256
1858
  var WebhookActionOperation = /* @__PURE__ */ ((WebhookActionOperation2) => {
2257
1859
  WebhookActionOperation2["SUCCESS"] = "success";
2258
1860
  WebhookActionOperation2["EXCEPTION"] = "exception";
@@ -2359,10 +1961,10 @@ var _WebhookActionResponse = class _WebhookActionResponse {
2359
1961
  * });
2360
1962
  * ```
2361
1963
  */
2362
- static add(path, value, instance) {
1964
+ static add(path2, value, instance) {
2363
1965
  const response = {
2364
1966
  op: "add" /* ADD */,
2365
- path,
1967
+ path: path2,
2366
1968
  value
2367
1969
  };
2368
1970
  if (instance !== void 0) {
@@ -2398,10 +2000,10 @@ var _WebhookActionResponse = class _WebhookActionResponse {
2398
2000
  * });
2399
2001
  * ```
2400
2002
  */
2401
- static replace(path, value, instance) {
2003
+ static replace(path2, value, instance) {
2402
2004
  const response = {
2403
2005
  op: "replace" /* REPLACE */,
2404
- path,
2006
+ path: path2,
2405
2007
  value
2406
2008
  };
2407
2009
  if (instance !== void 0) {
@@ -2439,10 +2041,10 @@ var _WebhookActionResponse = class _WebhookActionResponse {
2439
2041
  * };
2440
2042
  * ```
2441
2043
  */
2442
- static remove(path) {
2044
+ static remove(path2) {
2443
2045
  return {
2444
2046
  op: "remove" /* REMOVE */,
2445
- path
2047
+ path: path2
2446
2048
  };
2447
2049
  }
2448
2050
  };
@@ -2451,6 +2053,7 @@ var WebhookActionResponse = _WebhookActionResponse;
2451
2053
  var response_default2 = WebhookActionResponse;
2452
2054
 
2453
2055
  // src/framework/webhook-action/types.ts
2056
+ init_esm_shims();
2454
2057
  var SignatureVerification = /* @__PURE__ */ ((SignatureVerification2) => {
2455
2058
  SignatureVerification2["ENABLED"] = "enabled";
2456
2059
  SignatureVerification2["DISABLED"] = "disabled";
@@ -2538,10 +2141,12 @@ var WebhookAction = _WebhookAction;
2538
2141
  var webhook_action_default = WebhookAction;
2539
2142
 
2540
2143
  // src/framework/ims-token/index.ts
2144
+ init_esm_shims();
2541
2145
  import { State } from "@adobe/aio-sdk";
2542
2146
 
2543
2147
  // src/commerce/adobe-auth/index.ts
2544
- import { context, getToken } from "@adobe/aio-lib-ims";
2148
+ init_esm_shims();
2149
+ import * as aioLibIms from "@adobe/aio-lib-ims";
2545
2150
  var _AdobeAuth = class _AdobeAuth {
2546
2151
  /**
2547
2152
  * Retrieves an authentication token from Adobe IMS
@@ -2574,9 +2179,9 @@ var _AdobeAuth = class _AdobeAuth {
2574
2179
  ims_org_id: imsOrgId,
2575
2180
  scopes
2576
2181
  };
2577
- await context.setCurrent(currentContext);
2578
- await context.set(currentContext, config);
2579
- return await getToken();
2182
+ await aioLibIms.context.setCurrent(currentContext);
2183
+ await aioLibIms.context.set(currentContext, config);
2184
+ return await aioLibIms.getToken();
2580
2185
  }
2581
2186
  };
2582
2187
  __name(_AdobeAuth, "AdobeAuth");
@@ -2584,6 +2189,7 @@ var AdobeAuth = _AdobeAuth;
2584
2189
  var adobe_auth_default = AdobeAuth;
2585
2190
 
2586
2191
  // src/integration/bearer-token/index.ts
2192
+ init_esm_shims();
2587
2193
  var _BearerToken = class _BearerToken {
2588
2194
  /**
2589
2195
  * Extracts the Bearer token from HTTP request headers and returns detailed token information.
@@ -2940,7 +2546,14 @@ __name(_ImsToken, "ImsToken");
2940
2546
  var ImsToken = _ImsToken;
2941
2547
  var ims_token_default = ImsToken;
2942
2548
 
2549
+ // src/framework/ims-token/types.ts
2550
+ init_esm_shims();
2551
+
2552
+ // src/framework/runtime-api-gateway-service/index.ts
2553
+ init_esm_shims();
2554
+
2943
2555
  // src/integration/rest-client/index.ts
2556
+ init_esm_shims();
2944
2557
  import fetch from "node-fetch";
2945
2558
  var _RestClient = class _RestClient {
2946
2559
  /**
@@ -3299,10 +2912,35 @@ __name(_RuntimeApiGatewayService, "RuntimeApiGatewayService");
3299
2912
  _RuntimeApiGatewayService.BASE_URL = "https://adobeioruntime.net/apis";
3300
2913
  var RuntimeApiGatewayService = _RuntimeApiGatewayService;
3301
2914
 
2915
+ // src/framework/telemetry/types.ts
2916
+ init_esm_shims();
2917
+
2918
+ // src/framework/index.ts
2919
+ init_input_error();
2920
+ init_success_checker();
2921
+ init_json_message_processor();
2922
+
2923
+ // src/integration/index.ts
2924
+ init_esm_shims();
2925
+
3302
2926
  // src/integration/onboard-events/index.ts
2927
+ init_esm_shims();
3303
2928
  import { Core as Core2 } from "@adobe/aio-sdk";
3304
2929
 
2930
+ // src/integration/onboard-events/create-providers/index.ts
2931
+ init_esm_shims();
2932
+
2933
+ // src/io-events/index.ts
2934
+ init_esm_shims();
2935
+
2936
+ // src/io-events/provider/index.ts
2937
+ init_esm_shims();
2938
+
2939
+ // src/io-events/provider/list/index.ts
2940
+ init_esm_shims();
2941
+
3305
2942
  // src/io-events/types.ts
2943
+ init_esm_shims();
3306
2944
  var IoEventsGlobals = {
3307
2945
  BASE_URL: "https://api.adobe.io",
3308
2946
  STATUS_CODES: {
@@ -3539,6 +3177,7 @@ var List = _List;
3539
3177
  var list_default = List;
3540
3178
 
3541
3179
  // src/io-events/provider/get/index.ts
3180
+ init_esm_shims();
3542
3181
  var _Get = class _Get {
3543
3182
  /**
3544
3183
  * Constructor for Get provider service
@@ -3715,6 +3354,7 @@ var Get = _Get;
3715
3354
  var get_default = Get;
3716
3355
 
3717
3356
  // src/io-events/provider/create/index.ts
3357
+ init_esm_shims();
3718
3358
  var _Create = class _Create {
3719
3359
  /**
3720
3360
  * Constructor for Create provider service
@@ -3882,6 +3522,7 @@ var Create = _Create;
3882
3522
  var create_default = Create;
3883
3523
 
3884
3524
  // src/io-events/provider/delete/index.ts
3525
+ init_esm_shims();
3885
3526
  var _Delete = class _Delete {
3886
3527
  /**
3887
3528
  * Creates an instance of Delete service
@@ -4208,7 +3849,11 @@ __name(_ProviderManager, "ProviderManager");
4208
3849
  var ProviderManager = _ProviderManager;
4209
3850
  var provider_default = ProviderManager;
4210
3851
 
3852
+ // src/io-events/event-metadata/index.ts
3853
+ init_esm_shims();
3854
+
4211
3855
  // src/io-events/event-metadata/list/index.ts
3856
+ init_esm_shims();
4212
3857
  var _List2 = class _List2 {
4213
3858
  /**
4214
3859
  * Creates an instance of List service
@@ -4399,6 +4044,7 @@ __name(_List2, "List");
4399
4044
  var List2 = _List2;
4400
4045
 
4401
4046
  // src/io-events/event-metadata/get/index.ts
4047
+ init_esm_shims();
4402
4048
  var _Get2 = class _Get2 {
4403
4049
  /**
4404
4050
  * Creates an instance of Get service
@@ -4569,6 +4215,7 @@ __name(_Get2, "Get");
4569
4215
  var Get2 = _Get2;
4570
4216
 
4571
4217
  // src/io-events/event-metadata/create/index.ts
4218
+ init_esm_shims();
4572
4219
  var _Create2 = class _Create2 {
4573
4220
  /**
4574
4221
  * Constructor for Create event metadata service
@@ -4833,6 +4480,7 @@ var Create2 = _Create2;
4833
4480
  var create_default2 = Create2;
4834
4481
 
4835
4482
  // src/io-events/event-metadata/delete/index.ts
4483
+ init_esm_shims();
4836
4484
  var _Delete2 = class _Delete2 {
4837
4485
  /**
4838
4486
  * Constructor for Delete event metadata service
@@ -5142,7 +4790,11 @@ __name(_EventMetadataManager, "EventMetadataManager");
5142
4790
  var EventMetadataManager = _EventMetadataManager;
5143
4791
  var event_metadata_default = EventMetadataManager;
5144
4792
 
4793
+ // src/io-events/registration/index.ts
4794
+ init_esm_shims();
4795
+
5145
4796
  // src/io-events/registration/create/index.ts
4797
+ init_esm_shims();
5146
4798
  var _Create3 = class _Create3 {
5147
4799
  /**
5148
4800
  * Initialize the Create service
@@ -5327,6 +4979,7 @@ var Create3 = _Create3;
5327
4979
  var create_default3 = Create3;
5328
4980
 
5329
4981
  // src/io-events/registration/delete/index.ts
4982
+ init_esm_shims();
5330
4983
  var _Delete3 = class _Delete3 {
5331
4984
  /**
5332
4985
  * Initialize the Delete service
@@ -5445,6 +5098,7 @@ var Delete3 = _Delete3;
5445
5098
  var delete_default2 = Delete3;
5446
5099
 
5447
5100
  // src/io-events/registration/get/index.ts
5101
+ init_esm_shims();
5448
5102
  var _Get3 = class _Get3 {
5449
5103
  /**
5450
5104
  * Initialize the Get service
@@ -5564,6 +5218,7 @@ var Get3 = _Get3;
5564
5218
  var get_default2 = Get3;
5565
5219
 
5566
5220
  // src/io-events/registration/list/index.ts
5221
+ init_esm_shims();
5567
5222
  var _List3 = class _List3 {
5568
5223
  /**
5569
5224
  * Initialize the List service
@@ -6027,6 +5682,7 @@ var CreateProviders = _CreateProviders;
6027
5682
  var create_providers_default = CreateProviders;
6028
5683
 
6029
5684
  // src/integration/onboard-events/create-events/index.ts
5685
+ init_esm_shims();
6030
5686
  var _CreateEvents = class _CreateEvents {
6031
5687
  /**
6032
5688
  * Creates a new CreateEvents instance
@@ -6242,6 +5898,7 @@ var CreateEvents = _CreateEvents;
6242
5898
  var create_events_default = CreateEvents;
6243
5899
 
6244
5900
  // src/integration/onboard-events/create-registrations/index.ts
5901
+ init_esm_shims();
6245
5902
  var _CreateRegistrations = class _CreateRegistrations {
6246
5903
  /**
6247
5904
  * Creates a new CreateRegistrations instance
@@ -6515,6 +6172,7 @@ var CreateRegistrations = _CreateRegistrations;
6515
6172
  var create_registrations_default = CreateRegistrations;
6516
6173
 
6517
6174
  // src/integration/onboard-events/input-parser/index.ts
6175
+ init_esm_shims();
6518
6176
  var _InputParser = class _InputParser {
6519
6177
  constructor(input) {
6520
6178
  this.entities = {
@@ -6809,6 +6467,7 @@ var OnboardEvents = _OnboardEvents;
6809
6467
  var onboard_events_default = OnboardEvents;
6810
6468
 
6811
6469
  // src/integration/infinite-loop-breaker/index.ts
6470
+ init_esm_shims();
6812
6471
  import { Core as Core3, State as State2 } from "@adobe/aio-sdk";
6813
6472
  import crypto2 from "crypto";
6814
6473
  var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
@@ -6905,7 +6564,11 @@ _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60;
6905
6564
  var InfiniteLoopBreaker = _InfiniteLoopBreaker;
6906
6565
  var infinite_loop_breaker_default = InfiniteLoopBreaker;
6907
6566
 
6567
+ // src/integration/onboard-commerce/index.ts
6568
+ init_esm_shims();
6569
+
6908
6570
  // src/integration/onboard-commerce/configure-provider/index.ts
6571
+ init_esm_shims();
6909
6572
  import {
6910
6573
  EventConfigurationService,
6911
6574
  EventProviderService
@@ -7438,7 +7101,11 @@ __name(_OnboardCommerce, "OnboardCommerce");
7438
7101
  var OnboardCommerce = _OnboardCommerce;
7439
7102
  var onboard_commerce_default = OnboardCommerce;
7440
7103
 
7104
+ // src/commerce/index.ts
7105
+ init_esm_shims();
7106
+
7441
7107
  // src/commerce/adobe-commerce-client/index.ts
7108
+ init_esm_shims();
7442
7109
  import got from "got";
7443
7110
  var _AdobeCommerceClient = class _AdobeCommerceClient {
7444
7111
  /**
@@ -7577,7 +7244,11 @@ __name(_AdobeCommerceClient, "AdobeCommerceClient");
7577
7244
  var AdobeCommerceClient = _AdobeCommerceClient;
7578
7245
  var adobe_commerce_client_default = AdobeCommerceClient;
7579
7246
 
7247
+ // src/commerce/adobe-commerce-client/basic-auth-connection/index.ts
7248
+ init_esm_shims();
7249
+
7580
7250
  // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
7251
+ init_esm_shims();
7581
7252
  import { State as State3 } from "@adobe/aio-sdk";
7582
7253
  var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
7583
7254
  /**
@@ -7779,6 +7450,7 @@ var BasicAuthConnection = _BasicAuthConnection;
7779
7450
  var basic_auth_connection_default = BasicAuthConnection;
7780
7451
 
7781
7452
  // src/commerce/adobe-commerce-client/oauth1a-connection/index.ts
7453
+ init_esm_shims();
7782
7454
  import Oauth1a from "oauth-1.0a";
7783
7455
  import * as crypto3 from "crypto";
7784
7456
  var _Oauth1aConnection = class _Oauth1aConnection {
@@ -7838,6 +7510,7 @@ var Oauth1aConnection = _Oauth1aConnection;
7838
7510
  var oauth1a_connection_default = Oauth1aConnection;
7839
7511
 
7840
7512
  // src/commerce/adobe-commerce-client/ims-connection/index.ts
7513
+ init_esm_shims();
7841
7514
  var _ImsConnection = class _ImsConnection {
7842
7515
  /**
7843
7516
  * Creates an instance of ImsConnection
@@ -7880,7 +7553,11 @@ __name(_ImsConnection, "ImsConnection");
7880
7553
  var ImsConnection = _ImsConnection;
7881
7554
  var ims_connection_default = ImsConnection;
7882
7555
 
7556
+ // src/commerce/shipping-carrier/index.ts
7557
+ init_esm_shims();
7558
+
7883
7559
  // src/commerce/shipping-carrier/method/index.ts
7560
+ init_esm_shims();
7884
7561
  var _ShippingCarrierMethod = class _ShippingCarrierMethod {
7885
7562
  constructor(carrierCode, method) {
7886
7563
  this.methodData = { carrier_code: carrierCode, method, additional_data: [] };
@@ -8231,6 +7908,7 @@ var ShippingCarrier = _ShippingCarrier;
8231
7908
  var shipping_carrier_default = ShippingCarrier;
8232
7909
 
8233
7910
  // src/commerce/shipping-carrier/response/index.ts
7911
+ init_esm_shims();
8234
7912
  var _ShippingCarrierResponse = class _ShippingCarrierResponse {
8235
7913
  constructor(carrier) {
8236
7914
  this.carrier = carrier;
@@ -8264,7 +7942,11 @@ __name(_ShippingCarrierResponse, "ShippingCarrierResponse");
8264
7942
  var ShippingCarrierResponse = _ShippingCarrierResponse;
8265
7943
  var response_default3 = ShippingCarrierResponse;
8266
7944
 
7945
+ // src/experience/index.ts
7946
+ init_esm_shims();
7947
+
8267
7948
  // src/experience/admin-ui-sdk/index.ts
7949
+ init_esm_shims();
8268
7950
  var _AdminUiSdk = class _AdminUiSdk {
8269
7951
  /**
8270
7952
  * Creates a new AdminUiSdk instance