@adobe-commerce/aio-toolkit 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4891 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ AdobeAuth: () => adobe_auth_default,
35
+ AdobeCommerceClient: () => adobe_commerce_client_default,
36
+ BasicAuthConnection: () => basic_auth_connection_default,
37
+ BearerToken: () => bearer_token_default,
38
+ CreateEvents: () => create_events_default,
39
+ CreateRegistrations: () => create_registrations_default,
40
+ EventConsumerAction: () => event_consumer_action_default,
41
+ EventMetadataManager: () => event_metadata_default,
42
+ FileRepository: () => file_repository_default,
43
+ GenerateBasicAuthToken: () => generate_basic_auth_token_default,
44
+ GraphQlAction: () => graphql_action_default,
45
+ HttpMethod: () => HttpMethod,
46
+ HttpStatus: () => HttpStatus,
47
+ IOEventsApiError: () => IOEventsApiError,
48
+ ImsConnection: () => ims_connection_default,
49
+ InfiniteLoopBreaker: () => infinite_loop_breaker_default,
50
+ IoEventsGlobals: () => IoEventsGlobals,
51
+ Oauth1aConnection: () => oauth1a_connection_default,
52
+ OnboardEvents: () => onboard_events_default,
53
+ Openwhisk: () => openwhisk_default,
54
+ OpenwhiskAction: () => openwhisk_action_default,
55
+ Parameters: () => parameters_default,
56
+ ProviderManager: () => provider_default,
57
+ RegistrationManager: () => registration_default,
58
+ RestClient: () => rest_client_default,
59
+ RuntimeAction: () => runtime_action_default,
60
+ RuntimeActionResponse: () => response_default,
61
+ Validator: () => validator_default
62
+ });
63
+ module.exports = __toCommonJS(index_exports);
64
+
65
+ // src/framework/runtime-action/index.ts
66
+ var import_aio_sdk = require("@adobe/aio-sdk");
67
+
68
+ // src/framework/runtime-action/types.ts
69
+ var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
70
+ HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
71
+ HttpStatus2[HttpStatus2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
72
+ HttpStatus2[HttpStatus2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
73
+ HttpStatus2[HttpStatus2["NOT_FOUND"] = 404] = "NOT_FOUND";
74
+ HttpStatus2[HttpStatus2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
75
+ HttpStatus2[HttpStatus2["INTERNAL_ERROR"] = 500] = "INTERNAL_ERROR";
76
+ return HttpStatus2;
77
+ })(HttpStatus || {});
78
+ var HttpMethod = /* @__PURE__ */ ((HttpMethod3) => {
79
+ HttpMethod3["GET"] = "get";
80
+ HttpMethod3["POST"] = "post";
81
+ HttpMethod3["PUT"] = "put";
82
+ HttpMethod3["DELETE"] = "delete";
83
+ HttpMethod3["PATCH"] = "patch";
84
+ HttpMethod3["HEAD"] = "head";
85
+ HttpMethod3["OPTIONS"] = "options";
86
+ return HttpMethod3;
87
+ })(HttpMethod || {});
88
+
89
+ // src/framework/runtime-action/response/index.ts
90
+ var _RuntimeActionResponse = class _RuntimeActionResponse {
91
+ /**
92
+ * Returns a success response object, this method should be called on the handlers actions
93
+ *
94
+ * @param response a descriptive message of the result
95
+ * e.g. 'missing xyz parameter'
96
+ * @param headers optional headers to include in the response
97
+ * @returns the response object, ready to be returned from the action main's function.
98
+ */
99
+ static success(response, headers = {}) {
100
+ return {
101
+ statusCode: 200 /* OK */,
102
+ body: response,
103
+ headers
104
+ };
105
+ }
106
+ /**
107
+ * Returns an error response object, this method should be called on the handlers actions
108
+ *
109
+ * @param statusCode the status code.
110
+ * e.g. 400
111
+ * @param error a descriptive message of the result
112
+ * e.g. 'missing xyz parameter'
113
+ * @returns the response object, ready to be returned from the action main's function.
114
+ */
115
+ static error(statusCode, error) {
116
+ return {
117
+ error: {
118
+ statusCode,
119
+ body: {
120
+ error
121
+ }
122
+ }
123
+ };
124
+ }
125
+ };
126
+ __name(_RuntimeActionResponse, "RuntimeActionResponse");
127
+ var RuntimeActionResponse = _RuntimeActionResponse;
128
+ var response_default = RuntimeActionResponse;
129
+
130
+ // src/framework/runtime-action/parameters/index.ts
131
+ var _Parameters = class _Parameters {
132
+ /**
133
+ * Returns a log-ready string of the action input parameters.
134
+ * The `Authorization` header content will be replaced by '<hidden>'.
135
+ *
136
+ * @param params action input parameters.
137
+ *
138
+ * @returns string
139
+ */
140
+ static stringify(params) {
141
+ let headers = params.__ow_headers || {};
142
+ if (headers.authorization) {
143
+ headers = { ...headers, authorization: "<hidden>" };
144
+ }
145
+ return JSON.stringify({ ...params, __ow_headers: headers });
146
+ }
147
+ };
148
+ __name(_Parameters, "Parameters");
149
+ var Parameters = _Parameters;
150
+ var parameters_default = Parameters;
151
+
152
+ // src/framework/runtime-action/validator/index.ts
153
+ var _Validator = class _Validator {
154
+ /**
155
+ * Returns the list of missing keys given an object and its required keys.
156
+ * A parameter is missing if its value is undefined or ''.
157
+ * A value of 0 or null is not considered as missing.
158
+ *
159
+ * @param obj object to check.
160
+ * @param required list of required keys.
161
+ * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'
162
+ *
163
+ * @returns array
164
+ * @private
165
+ */
166
+ static getMissingKeys(obj, required) {
167
+ return required.filter((r) => {
168
+ const splits = r.split(".");
169
+ const last = splits[splits.length - 1];
170
+ const traverse = splits.slice(0, -1).reduce((tObj, split) => tObj[split] || {}, obj);
171
+ return last && (traverse[last] === void 0 || traverse[last] === "");
172
+ });
173
+ }
174
+ /**
175
+ * Returns the list of missing keys given an object and its required keys.
176
+ * A parameter is missing if its value is undefined or ''.
177
+ * A value of 0 or null is not considered as missing.
178
+ *
179
+ * @param params action input parameters.
180
+ * @param requiredHeaders list of required input headers.
181
+ * @param requiredParams list of required input parameters.
182
+ * Each element can be multi-level deep using a '.' separator e.g. 'myRequiredObj.myRequiredKey'.
183
+ *
184
+ * @returns string|null if the return value is not null, then it holds an error message describing the missing inputs.
185
+ *
186
+ */
187
+ static checkMissingRequestInputs(params, requiredParams = [], requiredHeaders = []) {
188
+ let errorMessage = null;
189
+ requiredHeaders = requiredHeaders.map((h) => h.toLowerCase());
190
+ const normalizedHeaders = Object.keys(params.__ow_headers || {}).reduce(
191
+ (acc, key) => {
192
+ acc[key.toLowerCase()] = params.__ow_headers?.[key];
193
+ return acc;
194
+ },
195
+ {}
196
+ );
197
+ const missingHeaders = _Validator.getMissingKeys(normalizedHeaders, requiredHeaders);
198
+ if (missingHeaders.length > 0) {
199
+ errorMessage = `missing header(s) '${missingHeaders.join(", ")}'`;
200
+ }
201
+ const missingParams = _Validator.getMissingKeys(params, requiredParams);
202
+ if (missingParams.length > 0) {
203
+ if (errorMessage) {
204
+ errorMessage += " and ";
205
+ } else {
206
+ errorMessage = "";
207
+ }
208
+ errorMessage += `missing parameter(s) '${missingParams.join(", ")}'`;
209
+ }
210
+ return errorMessage;
211
+ }
212
+ };
213
+ __name(_Validator, "Validator");
214
+ var Validator = _Validator;
215
+ var validator_default = Validator;
216
+
217
+ // src/framework/runtime-action/index.ts
218
+ var _RuntimeAction = class _RuntimeAction {
219
+ /**
220
+ * @param name
221
+ * @param httpMethods
222
+ * @param requiredParams
223
+ * @param requiredHeaders
224
+ * @param action
225
+ * @returns {(function(*): Promise<any>)|*}
226
+ */
227
+ static execute(name = "main", httpMethods = [], requiredParams = [], requiredHeaders = [], action = async (_params) => {
228
+ return { statusCode: 200 /* OK */, body: {} };
229
+ }) {
230
+ return async (params) => {
231
+ const logger = import_aio_sdk.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
232
+ try {
233
+ logger.info(`Calling the ${name} action`);
234
+ logger.debug(parameters_default.stringify(params));
235
+ const validationError = _RuntimeAction.validateRequest(
236
+ params,
237
+ requiredParams,
238
+ requiredHeaders,
239
+ httpMethods,
240
+ logger
241
+ );
242
+ if (validationError) {
243
+ return validationError;
244
+ }
245
+ const result = await action(params, { logger, headers: params.__ow_headers || {} });
246
+ logger.info(result);
247
+ return result;
248
+ } catch (error) {
249
+ logger.error(error);
250
+ return response_default.error(500 /* INTERNAL_ERROR */, "server error");
251
+ }
252
+ };
253
+ }
254
+ static validateRequest(params, requiredParams, requiredHeaders, httpMethods, logger) {
255
+ const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? "";
256
+ if (errorMessage) {
257
+ return response_default.error(400 /* BAD_REQUEST */, errorMessage);
258
+ }
259
+ const requestMethod = params.__ow_method;
260
+ if (httpMethods.length > 0 && !httpMethods.includes(requestMethod)) {
261
+ const errorMessage2 = `Invalid HTTP method: ${requestMethod}. Allowed methods are: ${httpMethods.join(", ")}`;
262
+ logger.error(errorMessage2);
263
+ return response_default.error(405 /* METHOD_NOT_ALLOWED */, errorMessage2);
264
+ }
265
+ return null;
266
+ }
267
+ };
268
+ __name(_RuntimeAction, "RuntimeAction");
269
+ var RuntimeAction = _RuntimeAction;
270
+ var runtime_action_default = RuntimeAction;
271
+
272
+ // src/framework/event-consumer-action/index.ts
273
+ var import_aio_sdk2 = require("@adobe/aio-sdk");
274
+ var _EventConsumerAction = class _EventConsumerAction {
275
+ /**
276
+ * @param name
277
+ * @param requiredParams
278
+ * @param requiredHeaders
279
+ * @param action
280
+ * @returns {(function(*): Promise<any>)|*}
281
+ */
282
+ static execute(name = "main", requiredParams = [], requiredHeaders = [], action = async (_params) => {
283
+ return { statusCode: 200 /* OK */, body: {} };
284
+ }) {
285
+ return async (params) => {
286
+ const logger = import_aio_sdk2.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
287
+ try {
288
+ logger.info(`Calling the ${name} action`);
289
+ logger.debug(parameters_default.stringify(params));
290
+ const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) || "";
291
+ if (errorMessage) {
292
+ return response_default.error(400 /* BAD_REQUEST */, errorMessage);
293
+ }
294
+ const result = await action(params, { logger, headers: params.__ow_headers || {} });
295
+ logger.info(result);
296
+ return result;
297
+ } catch (error) {
298
+ logger.error(error);
299
+ return response_default.error(500 /* INTERNAL_ERROR */, "server error");
300
+ }
301
+ };
302
+ }
303
+ };
304
+ __name(_EventConsumerAction, "EventConsumerAction");
305
+ var EventConsumerAction = _EventConsumerAction;
306
+ var event_consumer_action_default = EventConsumerAction;
307
+
308
+ // src/framework/graphql-action/index.ts
309
+ var import_graphql = require("graphql");
310
+ var _GraphQlAction = class _GraphQlAction {
311
+ static execute(schema = `
312
+ type Query {
313
+ hello: String
314
+ }
315
+ `, resolvers = async (_params) => {
316
+ return {
317
+ hello: /* @__PURE__ */ __name(() => "Hello World!", "hello")
318
+ };
319
+ }, name = "main", disableIntrospection = false) {
320
+ return runtime_action_default.execute(
321
+ `graphql-${name}`,
322
+ ["get" /* GET */, "post" /* POST */],
323
+ ["query"],
324
+ [],
325
+ async (params, ctx) => {
326
+ let graphqlSchema;
327
+ try {
328
+ graphqlSchema = (0, import_graphql.buildSchema)(schema);
329
+ } catch (error) {
330
+ return response_default.error(400 /* BAD_REQUEST */, error.message);
331
+ }
332
+ const graphqlResolvers = await resolvers({
333
+ ...ctx,
334
+ ...{
335
+ params
336
+ }
337
+ });
338
+ const context2 = {};
339
+ const query = params.query;
340
+ let parsedQuery;
341
+ try {
342
+ parsedQuery = (0, import_graphql.parse)(query);
343
+ } catch (error) {
344
+ return response_default.error(400 /* BAD_REQUEST */, error.message);
345
+ }
346
+ const validationErrors = (0, import_graphql.validate)(graphqlSchema, parsedQuery);
347
+ if (validationErrors.length) {
348
+ return response_default.error(
349
+ 400 /* BAD_REQUEST */,
350
+ validationErrors.map((err) => err.message).join(", ")
351
+ );
352
+ }
353
+ if (disableIntrospection) {
354
+ const isIntrospectionQuery = parsedQuery.definitions.some(
355
+ (definition) => definition.selectionSet.selections.some(
356
+ (selection) => selection.name.value.startsWith("__")
357
+ )
358
+ );
359
+ if (isIntrospectionQuery) {
360
+ return response_default.error(
361
+ 400 /* BAD_REQUEST */,
362
+ "Introspection is disabled for security reasons."
363
+ );
364
+ }
365
+ }
366
+ const variables = typeof params.variables === "string" ? JSON.parse(params.variables) : params.variables;
367
+ return response_default.success(
368
+ await (0, import_graphql.graphql)({
369
+ schema: graphqlSchema,
370
+ source: query,
371
+ rootValue: graphqlResolvers,
372
+ contextValue: context2,
373
+ variableValues: variables,
374
+ operationName: params.operationName
375
+ })
376
+ );
377
+ }
378
+ );
379
+ }
380
+ };
381
+ __name(_GraphQlAction, "GraphQlAction");
382
+ var GraphQlAction = _GraphQlAction;
383
+ var graphql_action_default = GraphQlAction;
384
+
385
+ // src/framework/openwhisk/index.ts
386
+ var import_openwhisk = __toESM(require("openwhisk"));
387
+ var _Openwhisk = class _Openwhisk {
388
+ /**
389
+ * @param host
390
+ * @param apiKey
391
+ */
392
+ constructor(host, apiKey) {
393
+ this.openwhiskClient = (0, import_openwhisk.default)({ apihost: host, api_key: apiKey });
394
+ }
395
+ /**
396
+ * @param action
397
+ * @param params
398
+ * @returns {Promise<Activation<Dict>>}
399
+ */
400
+ async execute(action, params) {
401
+ return await this.openwhiskClient.actions.invoke({
402
+ name: action,
403
+ blocking: true,
404
+ params
405
+ });
406
+ }
407
+ };
408
+ __name(_Openwhisk, "Openwhisk");
409
+ var Openwhisk = _Openwhisk;
410
+ var openwhisk_default = Openwhisk;
411
+
412
+ // src/framework/openwhisk-action/index.ts
413
+ var import_aio_sdk3 = require("@adobe/aio-sdk");
414
+ var _OpenwhiskAction = class _OpenwhiskAction {
415
+ /**
416
+ * @param name
417
+ * @param action
418
+ * @returns {(function(*): Promise<any>)|*}
419
+ */
420
+ static execute(name = "main", action = async (_params) => {
421
+ return { statusCode: 200 /* OK */, body: {} };
422
+ }) {
423
+ return async (params) => {
424
+ const logger = import_aio_sdk3.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
425
+ try {
426
+ logger.info(`Calling the ${name} webhook action`);
427
+ logger.debug(parameters_default.stringify(params));
428
+ const result = await action(params, { logger, headers: params.__ow_headers || {} });
429
+ logger.info(result);
430
+ return result;
431
+ } catch (error) {
432
+ logger.error(error);
433
+ return response_default.error(500 /* INTERNAL_ERROR */, "server error");
434
+ }
435
+ };
436
+ }
437
+ };
438
+ __name(_OpenwhiskAction, "OpenwhiskAction");
439
+ var OpenwhiskAction = _OpenwhiskAction;
440
+ var openwhisk_action_default = OpenwhiskAction;
441
+
442
+ // src/framework/repository/file-repository/index.ts
443
+ var import_aio_sdk4 = require("@adobe/aio-sdk");
444
+ var _FileRepository = class _FileRepository {
445
+ /**
446
+ * Creates a new FileRepository instance
447
+ * @param filepath - The base directory path for file operations
448
+ */
449
+ constructor(filepath) {
450
+ this.files = null;
451
+ this.filepath = filepath;
452
+ }
453
+ /**
454
+ * Lists all files in the repository directory
455
+ * @returns Promise<FileRecord[]> Array of file records
456
+ */
457
+ async list() {
458
+ const filesLib = await this.getFiles();
459
+ const results = [];
460
+ const existingFiles = await filesLib.list(`${this.filepath}/`);
461
+ if (existingFiles.length) {
462
+ for (const { name } of existingFiles) {
463
+ const buffer = await filesLib.read(`${name}`);
464
+ results.push(JSON.parse(buffer.toString()));
465
+ }
466
+ }
467
+ return results;
468
+ }
469
+ /**
470
+ * Loads a specific file by ID
471
+ * @param id - The ID of the file to load
472
+ * @returns Promise<FileRecord> The loaded file record or empty object if not found
473
+ */
474
+ async load(id = "") {
475
+ const filepath = `${this.filepath}/${id}.json`;
476
+ const filesLib = await this.getFiles();
477
+ const existingFile = await filesLib.list(filepath);
478
+ if (existingFile.length) {
479
+ const buffer = await filesLib.read(filepath);
480
+ return JSON.parse(buffer.toString());
481
+ }
482
+ return {};
483
+ }
484
+ /**
485
+ * Saves a file record to the repository
486
+ * @param payload - The data to save
487
+ * @returns Promise<boolean> True if save was successful, false otherwise
488
+ */
489
+ async save(payload = {}) {
490
+ try {
491
+ const filesLib = await this.getFiles();
492
+ let requestFileId = (/* @__PURE__ */ new Date()).getTime();
493
+ if ("id" in payload && payload.id !== void 0) {
494
+ requestFileId = Number(payload.id);
495
+ }
496
+ const filepath = `${this.filepath}/${requestFileId}.json`;
497
+ const existingFile = await filesLib.list(filepath);
498
+ if (existingFile.length) {
499
+ const buffer = await filesLib.read(filepath);
500
+ const existingData = JSON.parse(buffer.toString());
501
+ payload = {
502
+ ...payload,
503
+ updated_at: (/* @__PURE__ */ new Date()).toDateString()
504
+ };
505
+ payload = { ...existingData, ...payload };
506
+ await filesLib.delete(filepath);
507
+ } else {
508
+ payload = {
509
+ ...payload,
510
+ id: requestFileId,
511
+ created_at: (/* @__PURE__ */ new Date()).toDateString(),
512
+ updated_at: (/* @__PURE__ */ new Date()).toDateString()
513
+ };
514
+ }
515
+ await filesLib.write(filepath, JSON.stringify(payload));
516
+ return true;
517
+ } catch (error) {
518
+ console.error("Error saving file:", error);
519
+ return false;
520
+ }
521
+ }
522
+ /**
523
+ * Deletes files by their IDs
524
+ * @param ids - Array of file IDs to delete
525
+ * @returns Promise<FileRecord[]> Updated list of remaining files
526
+ */
527
+ async delete(ids = []) {
528
+ const filesLib = await this.getFiles();
529
+ for (const id of ids) {
530
+ await filesLib.delete(`${this.filepath}/${id}.json`);
531
+ }
532
+ return await this.list();
533
+ }
534
+ /**
535
+ * Initializes and returns the Files library instance
536
+ * @returns Promise<any> Initialized Files library instance
537
+ */
538
+ async getFiles() {
539
+ if (!this.files) {
540
+ this.files = await import_aio_sdk4.Files.init();
541
+ }
542
+ return this.files;
543
+ }
544
+ };
545
+ __name(_FileRepository, "FileRepository");
546
+ var FileRepository = _FileRepository;
547
+ var file_repository_default = FileRepository;
548
+
549
+ // src/integration/bearer-token/index.ts
550
+ var _BearerToken = class _BearerToken {
551
+ /**
552
+ * Extracts the Bearer token from OpenWhisk action parameters and returns detailed token information.
553
+ * Looks for the authorization header in __ow_headers and extracts the token value
554
+ * after the "Bearer " prefix.
555
+ *
556
+ * @param params - OpenWhisk action input parameters containing headers
557
+ * @returns Detailed token information object
558
+ *
559
+ * @example
560
+ * const params = {
561
+ * __ow_headers: {
562
+ * authorization: 'Bearer abc123token'
563
+ * }
564
+ * };
565
+ * const tokenInfo = BearerToken.extract(params);
566
+ * // returns: {
567
+ * // token: 'abc123token',
568
+ * // tokenLength: 11,
569
+ * // isValid: true,
570
+ * // expiry: '2024-01-01T12:00:00.000Z',
571
+ * // timeUntilExpiry: 3600000
572
+ * // }
573
+ */
574
+ static extract(params) {
575
+ let token = null;
576
+ if (params.__ow_headers?.authorization?.startsWith("Bearer ")) {
577
+ token = params.__ow_headers.authorization.substring("Bearer ".length);
578
+ }
579
+ return _BearerToken.info(token);
580
+ }
581
+ /**
582
+ * Gets detailed information about a Bearer token
583
+ * @param token - The Bearer token string (or null)
584
+ * @returns {BearerTokenInfo} Detailed token information including validity and expiry
585
+ *
586
+ * @example
587
+ * const tokenInfo = BearerToken.info('abc123token');
588
+ * // returns: {
589
+ * // token: 'abc123token',
590
+ * // tokenLength: 11,
591
+ * // isValid: true,
592
+ * // expiry: '2024-01-01T12:00:00.000Z',
593
+ * // timeUntilExpiry: 3600000
594
+ * // }
595
+ */
596
+ static info(token) {
597
+ const tokenExpiry = _BearerToken._calculateExpiry(token);
598
+ return {
599
+ token,
600
+ tokenLength: token ? token.length : 0,
601
+ isValid: _BearerToken._isTokenValid(token, tokenExpiry),
602
+ expiry: tokenExpiry ? tokenExpiry.toISOString() : null,
603
+ timeUntilExpiry: tokenExpiry ? Math.max(0, tokenExpiry.getTime() - Date.now()) : null
604
+ };
605
+ }
606
+ /**
607
+ * Checks if the given token is valid and not expired
608
+ * @private
609
+ * @param token - The bearer token string
610
+ * @param tokenExpiry - The token expiry date
611
+ * @returns {boolean} True if token is valid
612
+ */
613
+ static _isTokenValid(token, tokenExpiry) {
614
+ if (!token) {
615
+ return false;
616
+ }
617
+ if (tokenExpiry && Date.now() >= tokenExpiry.getTime()) {
618
+ console.log("\u23F0 Token has expired");
619
+ return false;
620
+ }
621
+ return true;
622
+ }
623
+ /**
624
+ * Calculates token expiry from JWT token or uses default for non-JWT tokens
625
+ * @private
626
+ * @param token - The token string (JWT or plain token)
627
+ * @returns Date object representing token expiry
628
+ */
629
+ static _calculateExpiry(token) {
630
+ if (!token) {
631
+ return null;
632
+ }
633
+ try {
634
+ const parts = token.split(".");
635
+ if (parts.length === 3) {
636
+ const payload = JSON.parse(Buffer.from(parts[1] || "", "base64").toString());
637
+ if (payload.expires_in) {
638
+ return new Date(Date.now() + parseInt(payload.expires_in));
639
+ }
640
+ if (payload.exp) {
641
+ return new Date(payload.exp * 1e3);
642
+ }
643
+ }
644
+ return new Date(Date.now() + 24 * 60 * 60 * 1e3);
645
+ } catch (error) {
646
+ console.warn("[WARN] Could not parse token expiry, using default 24h");
647
+ return new Date(Date.now() + 24 * 60 * 60 * 1e3);
648
+ }
649
+ }
650
+ };
651
+ __name(_BearerToken, "BearerToken");
652
+ var BearerToken = _BearerToken;
653
+ var bearer_token_default = BearerToken;
654
+
655
+ // src/integration/rest-client/index.ts
656
+ var import_node_fetch = __toESM(require("node-fetch"));
657
+ var _RestClient = class _RestClient {
658
+ /**
659
+ * A generic method to make GET rest call
660
+ *
661
+ * @param endpoint
662
+ * @param headers
663
+ * @returns {Promise<any>}
664
+ */
665
+ async get(endpoint, headers = {}) {
666
+ return await this.apiCall(endpoint, "GET", headers);
667
+ }
668
+ /**
669
+ * A generic method to make POST rest call
670
+ *
671
+ * @param endpoint
672
+ * @param headers
673
+ * @param payload
674
+ * @returns {Promise<any>}
675
+ */
676
+ async post(endpoint, headers = {}, payload = null) {
677
+ return await this.apiCall(endpoint, "POST", headers, payload);
678
+ }
679
+ /**
680
+ * A generic method to make PUT rest call
681
+ *
682
+ * @param endpoint
683
+ * @param headers
684
+ * @param payload
685
+ * @returns {Promise<any>}
686
+ */
687
+ async put(endpoint, headers = {}, payload = null) {
688
+ return await this.apiCall(endpoint, "PUT", headers, payload);
689
+ }
690
+ /**
691
+ * A generic method to make DELETE rest call
692
+ *
693
+ * @param endpoint
694
+ * @param headers
695
+ * @returns {Promise<any>}
696
+ */
697
+ async delete(endpoint, headers = {}) {
698
+ return await this.apiCall(endpoint, "DELETE", headers);
699
+ }
700
+ /**
701
+ * A generic method to make rest call
702
+ *
703
+ * @param endpoint
704
+ * @param method
705
+ * @param headers
706
+ * @param payload
707
+ * @returns {Promise<any>}
708
+ */
709
+ async apiCall(endpoint, method = "POST", headers = {}, payload = null) {
710
+ let options = {
711
+ method,
712
+ headers
713
+ };
714
+ if (payload !== null) {
715
+ options = {
716
+ ...options,
717
+ body: JSON.stringify(payload),
718
+ headers: {
719
+ ...headers,
720
+ "Content-Type": "application/json"
721
+ }
722
+ };
723
+ }
724
+ const response = await (0, import_node_fetch.default)(endpoint, options);
725
+ if (!response.ok) {
726
+ throw new Error(`HTTP error! status: ${response.status}`);
727
+ }
728
+ if (response.status === 204 || response.headers?.get("content-length") === "0") {
729
+ return null;
730
+ }
731
+ if (typeof response.json === "function") {
732
+ const contentType = response.headers?.get("content-type");
733
+ if (!contentType || contentType.includes("application/json") || contentType.includes("application/hal+json")) {
734
+ return await response.json();
735
+ }
736
+ }
737
+ if (typeof response.text === "function") {
738
+ const text = await response.text();
739
+ return text;
740
+ }
741
+ return null;
742
+ }
743
+ };
744
+ __name(_RestClient, "RestClient");
745
+ var RestClient = _RestClient;
746
+ var rest_client_default = RestClient;
747
+
748
+ // src/integration/onboard-events/index.ts
749
+ var import_aio_sdk5 = require("@adobe/aio-sdk");
750
+
751
+ // src/io-events/types.ts
752
+ var IoEventsGlobals = {
753
+ BASE_URL: "https://api.adobe.io",
754
+ STATUS_CODES: {
755
+ OK: 200,
756
+ BAD_REQUEST: 400,
757
+ UNAUTHORIZED: 401,
758
+ FORBIDDEN: 403,
759
+ NOT_FOUND: 404,
760
+ REQUEST_TIMEOUT: 408,
761
+ TIMEOUT: 408,
762
+ CONFLICT: 409,
763
+ INTERNAL_SERVER_ERROR: 500
764
+ },
765
+ HEADERS: {
766
+ CONFLICTING_ID: "x-conflicting-id"
767
+ }
768
+ };
769
+ var _IOEventsApiError = class _IOEventsApiError extends Error {
770
+ constructor(message, statusCode, errorCode, details) {
771
+ super(message);
772
+ this.name = "IOEventsApiError";
773
+ this.statusCode = statusCode;
774
+ this.errorCode = errorCode;
775
+ this.details = details;
776
+ }
777
+ };
778
+ __name(_IOEventsApiError, "IOEventsApiError");
779
+ var IOEventsApiError = _IOEventsApiError;
780
+
781
+ // src/io-events/provider/list/index.ts
782
+ var _List = class _List {
783
+ /**
784
+ * Constructor for List providers service
785
+ *
786
+ * @param clientId - Client ID from Adobe Developer Console (x-api-key header)
787
+ * @param consumerId - Project Organization ID from Adobe Developer Console
788
+ * @param projectId - Project ID from Adobe Developer Console
789
+ * @param workspaceId - Workspace ID from Adobe Developer Console
790
+ * @param accessToken - IMS token for authentication (Bearer token)
791
+ */
792
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
793
+ this.clientId = clientId;
794
+ this.consumerId = consumerId;
795
+ this.projectId = projectId;
796
+ this.workspaceId = workspaceId;
797
+ this.accessToken = accessToken;
798
+ this.endpoint = IoEventsGlobals.BASE_URL;
799
+ if (!clientId?.trim()) {
800
+ throw new Error("clientId is required and cannot be empty");
801
+ }
802
+ if (!consumerId?.trim()) {
803
+ throw new Error("consumerId is required and cannot be empty");
804
+ }
805
+ if (!projectId?.trim()) {
806
+ throw new Error("projectId is required and cannot be empty");
807
+ }
808
+ if (!workspaceId?.trim()) {
809
+ throw new Error("workspaceId is required and cannot be empty");
810
+ }
811
+ if (!accessToken?.trim()) {
812
+ throw new Error("accessToken is required and cannot be empty");
813
+ }
814
+ this.restClient = new rest_client_default();
815
+ }
816
+ /**
817
+ * Execute the list providers API call with automatic pagination
818
+ *
819
+ * This method automatically handles pagination by following the `_links.next.href` from the HAL+JSON response.
820
+ * It makes recursive API calls to fetch all pages and returns a complete array containing all providers
821
+ * across all pages.
822
+ *
823
+ * @param queryParams - Optional query parameters for filtering providers
824
+ * @param queryParams.providerMetadataId - Filter by provider metadata id
825
+ * @param queryParams.instanceId - Filter by instance id
826
+ * @param queryParams.providerMetadataIds - List of provider metadata ids to filter (mutually exclusive with providerMetadataId)
827
+ * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)
828
+ * @returns Promise<Provider[]> - Complete array of all providers across all pages
829
+ * @throws IOEventsApiError - When API call fails with specific error details
830
+ */
831
+ async execute(queryParams = {}) {
832
+ try {
833
+ if (queryParams.providerMetadataId && queryParams.providerMetadataIds) {
834
+ throw new Error("Cannot specify both providerMetadataId and providerMetadataIds");
835
+ }
836
+ const url = `${this.endpoint}/events/${this.consumerId}/providers`;
837
+ const queryString = this.buildQueryString(queryParams);
838
+ const fullUrl = queryString ? `${url}?${queryString}` : url;
839
+ const headers = {
840
+ Authorization: `Bearer ${this.accessToken}`,
841
+ "x-api-key": this.clientId,
842
+ Accept: "application/hal+json"
843
+ };
844
+ return await this.fetchAllPages(fullUrl, headers);
845
+ } catch (error) {
846
+ this.handleError(error);
847
+ }
848
+ }
849
+ /**
850
+ * Recursively fetches all pages of providers using pagination links
851
+ *
852
+ * @param url - The URL to fetch (either initial URL or next page URL)
853
+ * @param headers - Headers for the API request
854
+ * @param accumulatedResults - Array to accumulate results across pages
855
+ * @returns Promise<Provider[]> - Complete array of all providers
856
+ * @private
857
+ */
858
+ async fetchAllPages(url, headers, accumulatedResults = []) {
859
+ const response = await this.restClient.get(url, headers);
860
+ if (response === null || response === void 0) {
861
+ throw new Error("Invalid response format: Expected object");
862
+ }
863
+ if (typeof response !== "object") {
864
+ throw new Error("Invalid response format: Expected object");
865
+ }
866
+ const providers = response._embedded?.providers;
867
+ if (providers !== void 0 && !Array.isArray(providers)) {
868
+ throw new Error("Invalid response format: providers should be an array");
869
+ }
870
+ const currentPageResults = providers || [];
871
+ const allResults = [...accumulatedResults, ...currentPageResults];
872
+ const nextPageUrl = response._links?.next?.href;
873
+ if (nextPageUrl) {
874
+ return await this.fetchAllPages(nextPageUrl, headers, allResults);
875
+ }
876
+ return allResults;
877
+ }
878
+ /**
879
+ * Handle and transform errors from the API call
880
+ * @private
881
+ * @param error - The caught error
882
+ * @throws IOEventsApiError - Transformed error with proper details
883
+ */
884
+ handleError(error) {
885
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
886
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
887
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
888
+ throw new IOEventsApiError(errorMessage, statusCode);
889
+ }
890
+ if (error.response?.body) {
891
+ const errorBody = error.response.body;
892
+ const statusCode = error.response.statusCode || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
893
+ const message = errorBody.message || errorBody.error || this.getErrorMessageForStatus(statusCode);
894
+ throw new IOEventsApiError(message, statusCode, errorBody.error_code, errorBody.details);
895
+ }
896
+ if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
897
+ throw new IOEventsApiError(
898
+ "Network error: Unable to connect to Adobe I/O Events API. Please check your internet connection.",
899
+ 0,
900
+ "NETWORK_ERROR"
901
+ );
902
+ }
903
+ if (error.code === "ETIMEDOUT") {
904
+ throw new IOEventsApiError(
905
+ "Request timeout: Adobe I/O Events API did not respond in time.",
906
+ 0,
907
+ "TIMEOUT_ERROR"
908
+ );
909
+ }
910
+ if (error.message?.includes("JSON") || error.name === "SyntaxError") {
911
+ throw new IOEventsApiError(
912
+ "Invalid response format: Unable to parse API response.",
913
+ 0,
914
+ "PARSE_ERROR"
915
+ );
916
+ }
917
+ if (error.message?.includes("Cannot specify both") || error.message?.includes("Invalid response format")) {
918
+ throw new IOEventsApiError(
919
+ error.message,
920
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST,
921
+ "VALIDATION_ERROR"
922
+ );
923
+ }
924
+ throw new IOEventsApiError(
925
+ `Failed to list providers: ${error.message || "Unknown error occurred"}`,
926
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
927
+ "UNKNOWN_ERROR"
928
+ );
929
+ }
930
+ /**
931
+ * Extracts the status code from RestClient error message
932
+ *
933
+ * @param errorMessage - Error message like "HTTP error! status: 404"
934
+ * @returns The HTTP status code
935
+ */
936
+ extractStatusCodeFromMessage(errorMessage) {
937
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
938
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
939
+ }
940
+ /**
941
+ * Get user-friendly error message based on HTTP status code
942
+ * @private
943
+ * @param statusCode - HTTP status code
944
+ * @returns string - User-friendly error message
945
+ */
946
+ getErrorMessageForStatus(statusCode) {
947
+ switch (statusCode) {
948
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
949
+ return "Unauthorized: Invalid or expired access token";
950
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
951
+ return "Forbidden: Insufficient permissions or invalid API key";
952
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
953
+ return "Not Found: Provider associated with the consumerOrgId, providerMetadataId or instanceID does not exist";
954
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
955
+ return "Internal Server Error: Adobe I/O Events service is temporarily unavailable";
956
+ default:
957
+ return `API Error: HTTP ${statusCode}`;
958
+ }
959
+ }
960
+ /**
961
+ * Build query string from parameters
962
+ * @private
963
+ */
964
+ buildQueryString(params) {
965
+ const queryParts = [];
966
+ if (params.providerMetadataId) {
967
+ queryParts.push(`providerMetadataId=${encodeURIComponent(params.providerMetadataId)}`);
968
+ }
969
+ if (params.instanceId) {
970
+ queryParts.push(`instanceId=${encodeURIComponent(params.instanceId)}`);
971
+ }
972
+ if (params.providerMetadataIds && Array.isArray(params.providerMetadataIds)) {
973
+ params.providerMetadataIds.forEach((id) => {
974
+ queryParts.push(`providerMetadataIds=${encodeURIComponent(id)}`);
975
+ });
976
+ }
977
+ if (typeof params.eventmetadata === "boolean") {
978
+ queryParts.push(`eventmetadata=${params.eventmetadata}`);
979
+ }
980
+ return queryParts.join("&");
981
+ }
982
+ };
983
+ __name(_List, "List");
984
+ var List = _List;
985
+ var list_default = List;
986
+
987
+ // src/io-events/provider/get/index.ts
988
+ var _Get = class _Get {
989
+ /**
990
+ * Constructor for Get provider service
991
+ *
992
+ * @param clientId - Client ID from Adobe Developer Console (x-api-key header)
993
+ * @param consumerId - Project Organization ID from Adobe Developer Console
994
+ * @param projectId - Project ID from Adobe Developer Console
995
+ * @param workspaceId - Workspace ID from Adobe Developer Console
996
+ * @param accessToken - IMS token for authentication (Bearer token)
997
+ */
998
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
999
+ this.clientId = clientId;
1000
+ this.consumerId = consumerId;
1001
+ this.projectId = projectId;
1002
+ this.workspaceId = workspaceId;
1003
+ this.accessToken = accessToken;
1004
+ this.endpoint = IoEventsGlobals.BASE_URL;
1005
+ if (!clientId?.trim()) {
1006
+ throw new Error("clientId is required and cannot be empty");
1007
+ }
1008
+ if (!consumerId?.trim()) {
1009
+ throw new Error("consumerId is required and cannot be empty");
1010
+ }
1011
+ if (!projectId?.trim()) {
1012
+ throw new Error("projectId is required and cannot be empty");
1013
+ }
1014
+ if (!workspaceId?.trim()) {
1015
+ throw new Error("workspaceId is required and cannot be empty");
1016
+ }
1017
+ if (!accessToken?.trim()) {
1018
+ throw new Error("accessToken is required and cannot be empty");
1019
+ }
1020
+ this.restClient = new rest_client_default();
1021
+ }
1022
+ /**
1023
+ * Execute the get provider by ID API call
1024
+ *
1025
+ * @param providerId - The ID of the provider to retrieve
1026
+ * @param queryParams - Optional query parameters
1027
+ * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)
1028
+ * @returns Promise<Provider> - The provider details
1029
+ * @throws IOEventsApiError - When API call fails with specific error details
1030
+ *
1031
+ * @example
1032
+ * ```typescript
1033
+ * // Get basic provider details
1034
+ * const provider = await getService.execute('provider-123');
1035
+ *
1036
+ * // Get provider details with event metadata
1037
+ * const providerWithMetadata = await getService.execute('provider-123', {
1038
+ * eventmetadata: true
1039
+ * });
1040
+ * ```
1041
+ */
1042
+ async execute(providerId, queryParams = {}) {
1043
+ try {
1044
+ if (!providerId?.trim()) {
1045
+ throw new Error("Provider ID is required and cannot be empty");
1046
+ }
1047
+ const url = `${this.endpoint}/events/providers/${encodeURIComponent(providerId)}`;
1048
+ const queryString = this.buildQueryString(queryParams);
1049
+ const fullUrl = queryString ? `${url}?${queryString}` : url;
1050
+ const headers = {
1051
+ Authorization: `Bearer ${this.accessToken}`,
1052
+ "x-api-key": this.clientId,
1053
+ Accept: "application/hal+json"
1054
+ };
1055
+ const response = await this.restClient.get(fullUrl, headers);
1056
+ if (response === null || response === void 0) {
1057
+ throw new Error("Invalid response format: Expected provider object");
1058
+ }
1059
+ if (typeof response !== "object") {
1060
+ throw new Error("Invalid response format: Expected provider object");
1061
+ }
1062
+ return response;
1063
+ } catch (error) {
1064
+ this.handleError(error);
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Build query string from parameters
1069
+ */
1070
+ buildQueryString(queryParams) {
1071
+ const params = new URLSearchParams();
1072
+ if (queryParams.eventmetadata !== void 0) {
1073
+ params.append("eventmetadata", String(queryParams.eventmetadata));
1074
+ }
1075
+ return params.toString();
1076
+ }
1077
+ /**
1078
+ * Handle and transform errors into IOEventsApiError
1079
+ */
1080
+ handleError(error) {
1081
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
1082
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
1083
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
1084
+ throw new IOEventsApiError(errorMessage, statusCode);
1085
+ }
1086
+ if (error.response) {
1087
+ const status = this.extractStatusCode(error);
1088
+ const errorMessage = this.getErrorMessageForStatus(status);
1089
+ throw new IOEventsApiError(errorMessage, status, "API_ERROR");
1090
+ }
1091
+ if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
1092
+ throw new IOEventsApiError(
1093
+ "Network error: Unable to connect to Adobe I/O Events API",
1094
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1095
+ "NETWORK_ERROR"
1096
+ );
1097
+ }
1098
+ if (error.code === "ETIMEDOUT") {
1099
+ throw new IOEventsApiError(
1100
+ "Request timeout: Adobe I/O Events API did not respond in time",
1101
+ IoEventsGlobals.STATUS_CODES.TIMEOUT,
1102
+ "TIMEOUT_ERROR"
1103
+ );
1104
+ }
1105
+ if (error.message?.includes("JSON")) {
1106
+ throw new IOEventsApiError(
1107
+ "Invalid response format from Adobe I/O Events API",
1108
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1109
+ "PARSE_ERROR"
1110
+ );
1111
+ }
1112
+ if (error.message?.includes("Provider ID is required") || error.message?.includes("Invalid response format")) {
1113
+ throw new IOEventsApiError(
1114
+ error.message,
1115
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST,
1116
+ "VALIDATION_ERROR"
1117
+ );
1118
+ }
1119
+ throw new IOEventsApiError(
1120
+ `Unexpected error: ${error.message || "Unknown error occurred"}`,
1121
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1122
+ "UNKNOWN_ERROR"
1123
+ );
1124
+ }
1125
+ /**
1126
+ * Extract status code from error response
1127
+ */
1128
+ extractStatusCode(error) {
1129
+ return error.response?.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1130
+ }
1131
+ /**
1132
+ * Extracts the status code from RestClient error message
1133
+ *
1134
+ * @param errorMessage - Error message like "HTTP error! status: 404"
1135
+ * @returns The HTTP status code
1136
+ */
1137
+ extractStatusCodeFromMessage(errorMessage) {
1138
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
1139
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1140
+ }
1141
+ /**
1142
+ * Get specific error message based on HTTP status code
1143
+ */
1144
+ getErrorMessageForStatus(status) {
1145
+ switch (status) {
1146
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
1147
+ return "Unauthorized: Invalid or expired access token";
1148
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
1149
+ return "Forbidden: Insufficient permissions to access this provider";
1150
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
1151
+ return "Provider ID does not exist";
1152
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
1153
+ return "Internal server error occurred while fetching provider";
1154
+ default:
1155
+ return `HTTP ${status}: Provider request failed`;
1156
+ }
1157
+ }
1158
+ };
1159
+ __name(_Get, "Get");
1160
+ var Get = _Get;
1161
+ var get_default = Get;
1162
+
1163
+ // src/io-events/provider/create/index.ts
1164
+ var _Create = class _Create {
1165
+ /**
1166
+ * Constructor for Create provider service
1167
+ *
1168
+ * @param clientId - Client ID from Adobe Developer Console (x-api-key header)
1169
+ * @param consumerId - Project Organization ID from Adobe Developer Console
1170
+ * @param projectId - Project ID from Adobe Developer Console
1171
+ * @param workspaceId - Workspace ID from Adobe Developer Console
1172
+ * @param accessToken - IMS token for authentication (Bearer token)
1173
+ */
1174
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
1175
+ this.clientId = clientId;
1176
+ this.consumerId = consumerId;
1177
+ this.projectId = projectId;
1178
+ this.workspaceId = workspaceId;
1179
+ this.accessToken = accessToken;
1180
+ this.endpoint = IoEventsGlobals.BASE_URL;
1181
+ if (!clientId?.trim()) {
1182
+ throw new Error("clientId is required and cannot be empty");
1183
+ }
1184
+ if (!consumerId?.trim()) {
1185
+ throw new Error("consumerId is required and cannot be empty");
1186
+ }
1187
+ if (!projectId?.trim()) {
1188
+ throw new Error("projectId is required and cannot be empty");
1189
+ }
1190
+ if (!workspaceId?.trim()) {
1191
+ throw new Error("workspaceId is required and cannot be empty");
1192
+ }
1193
+ if (!accessToken?.trim()) {
1194
+ throw new Error("accessToken is required and cannot be empty");
1195
+ }
1196
+ this.restClient = new rest_client_default();
1197
+ }
1198
+ /**
1199
+ * Execute the create provider API call
1200
+ *
1201
+ * @param providerData - Provider input data
1202
+ * @returns Promise<Provider> - The created provider
1203
+ * @throws IOEventsApiError - When API call fails with specific error details
1204
+ */
1205
+ async execute(providerData) {
1206
+ try {
1207
+ if (!providerData) {
1208
+ throw new Error("providerData is required");
1209
+ }
1210
+ if (!providerData.label?.trim()) {
1211
+ throw new Error("label is required in providerData");
1212
+ }
1213
+ const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers`;
1214
+ const headers = {
1215
+ Authorization: `Bearer ${this.accessToken}`,
1216
+ "x-api-key": this.clientId,
1217
+ Accept: "application/hal+json",
1218
+ "Content-Type": "application/json"
1219
+ };
1220
+ const response = await this.restClient.post(url, headers, providerData);
1221
+ if (response === null || response === void 0) {
1222
+ throw new Error("Invalid response format: Expected provider object");
1223
+ }
1224
+ if (typeof response !== "object") {
1225
+ throw new Error("Invalid response format: Expected provider object");
1226
+ }
1227
+ if (!response.id) {
1228
+ throw new Error("Invalid response format: Missing provider id");
1229
+ }
1230
+ return response;
1231
+ } catch (error) {
1232
+ this.handleError(error);
1233
+ }
1234
+ }
1235
+ /**
1236
+ * Handle and transform errors from the API call
1237
+ * @private
1238
+ * @param error - The caught error
1239
+ * @throws IOEventsApiError - Transformed error with proper details
1240
+ */
1241
+ handleError(error) {
1242
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
1243
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
1244
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
1245
+ throw new IOEventsApiError(errorMessage, statusCode);
1246
+ }
1247
+ if (error.response?.body) {
1248
+ const errorBody = error.response.body;
1249
+ const statusCode = error.response.statusCode || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1250
+ const message = errorBody.message || errorBody.error || this.getErrorMessageForStatus(statusCode);
1251
+ if (statusCode === IoEventsGlobals.STATUS_CODES.CONFLICT && error.response.headers?.[IoEventsGlobals.HEADERS.CONFLICTING_ID]) {
1252
+ const conflictingId = error.response.headers[IoEventsGlobals.HEADERS.CONFLICTING_ID];
1253
+ throw new IOEventsApiError(
1254
+ `Provider already exists with conflicting ID: ${conflictingId}`,
1255
+ statusCode,
1256
+ "CONFLICT_ERROR",
1257
+ `Conflicting provider ID: ${conflictingId}`
1258
+ );
1259
+ }
1260
+ throw new IOEventsApiError(message, statusCode, errorBody.error_code, errorBody.details);
1261
+ }
1262
+ if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
1263
+ throw new IOEventsApiError(
1264
+ "Network error: Unable to connect to Adobe I/O Events API",
1265
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1266
+ "NETWORK_ERROR"
1267
+ );
1268
+ }
1269
+ if (error.code === "ETIMEDOUT") {
1270
+ throw new IOEventsApiError(
1271
+ "Request timeout: Adobe I/O Events API did not respond in time",
1272
+ IoEventsGlobals.STATUS_CODES.TIMEOUT,
1273
+ "TIMEOUT_ERROR"
1274
+ );
1275
+ }
1276
+ if (error.message?.includes("JSON")) {
1277
+ throw new IOEventsApiError(
1278
+ "Invalid response format from Adobe I/O Events API",
1279
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1280
+ "PARSE_ERROR"
1281
+ );
1282
+ }
1283
+ if (error.message?.includes("is required") || error.message?.includes("Invalid response format")) {
1284
+ throw new IOEventsApiError(
1285
+ error.message,
1286
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST,
1287
+ "VALIDATION_ERROR"
1288
+ );
1289
+ }
1290
+ throw new IOEventsApiError(
1291
+ `Failed to create provider: ${error.message || "Unknown error occurred"}`,
1292
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1293
+ "UNKNOWN_ERROR"
1294
+ );
1295
+ }
1296
+ /**
1297
+ * Extracts the status code from RestClient error message
1298
+ *
1299
+ * @param errorMessage - Error message like "HTTP error! status: 404"
1300
+ * @returns The HTTP status code
1301
+ */
1302
+ extractStatusCodeFromMessage(errorMessage) {
1303
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
1304
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1305
+ }
1306
+ /**
1307
+ * Get specific error message based on HTTP status code
1308
+ */
1309
+ getErrorMessageForStatus(status) {
1310
+ switch (status) {
1311
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
1312
+ return "Unauthorized: Invalid or expired access token";
1313
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
1314
+ return "Forbidden: Insufficient permissions or invalid scopes, or attempt to create non multi-instance provider";
1315
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
1316
+ return "Provider metadata provided in the input model does not exist";
1317
+ case IoEventsGlobals.STATUS_CODES.CONFLICT:
1318
+ return "The event provider already exists";
1319
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
1320
+ return "Internal server error occurred while creating provider";
1321
+ default:
1322
+ return `HTTP ${status}: Provider creation failed`;
1323
+ }
1324
+ }
1325
+ };
1326
+ __name(_Create, "Create");
1327
+ var Create = _Create;
1328
+ var create_default = Create;
1329
+
1330
+ // src/io-events/provider/delete/index.ts
1331
+ var _Delete = class _Delete {
1332
+ /**
1333
+ * Creates an instance of Delete service
1334
+ *
1335
+ * @param clientId - Client ID from Adobe Developer Console
1336
+ * @param consumerId - Project Organization ID
1337
+ * @param projectId - Project ID from Adobe Developer Console
1338
+ * @param workspaceId - Workspace ID from Adobe Developer Console
1339
+ * @param accessToken - IMS token for authentication
1340
+ */
1341
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
1342
+ this.clientId = clientId;
1343
+ this.consumerId = consumerId;
1344
+ this.projectId = projectId;
1345
+ this.workspaceId = workspaceId;
1346
+ this.accessToken = accessToken;
1347
+ this.endpoint = IoEventsGlobals.BASE_URL;
1348
+ if (!clientId?.trim()) {
1349
+ throw new Error("clientId is required and cannot be empty");
1350
+ }
1351
+ if (!consumerId?.trim()) {
1352
+ throw new Error("consumerId is required and cannot be empty");
1353
+ }
1354
+ if (!projectId?.trim()) {
1355
+ throw new Error("projectId is required and cannot be empty");
1356
+ }
1357
+ if (!workspaceId?.trim()) {
1358
+ throw new Error("workspaceId is required and cannot be empty");
1359
+ }
1360
+ if (!accessToken?.trim()) {
1361
+ throw new Error("accessToken is required and cannot be empty");
1362
+ }
1363
+ this.restClient = new rest_client_default();
1364
+ }
1365
+ /**
1366
+ * Delete a provider by ID
1367
+ *
1368
+ * @param providerId - The ID of the provider to delete
1369
+ * @returns Promise<void> - Resolves when provider is successfully deleted
1370
+ * @throws IOEventsApiError - When the API request fails
1371
+ */
1372
+ async execute(providerId) {
1373
+ try {
1374
+ if (!providerId?.trim()) {
1375
+ throw new Error("providerId is required and cannot be empty");
1376
+ }
1377
+ const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}`;
1378
+ const headers = {
1379
+ Authorization: `Bearer ${this.accessToken}`,
1380
+ "x-api-key": this.clientId,
1381
+ Accept: "application/hal+json",
1382
+ "Content-Type": "application/json"
1383
+ };
1384
+ await this.restClient.delete(url, headers);
1385
+ } catch (error) {
1386
+ this.handleError(error);
1387
+ }
1388
+ }
1389
+ /**
1390
+ * Handle and transform errors from the API call
1391
+ * @private
1392
+ * @param error - The caught error
1393
+ * @throws IOEventsApiError - Transformed error with proper details
1394
+ */
1395
+ handleError(error) {
1396
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
1397
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
1398
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
1399
+ throw new IOEventsApiError(errorMessage, statusCode);
1400
+ }
1401
+ if (error.response) {
1402
+ const status = this.extractStatusCode(error);
1403
+ const errorMessage = this.getErrorMessageForStatus(status);
1404
+ throw new IOEventsApiError(errorMessage, status, "API_ERROR");
1405
+ }
1406
+ if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
1407
+ throw new IOEventsApiError(
1408
+ "Network error: Unable to connect to Adobe I/O Events API",
1409
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1410
+ "NETWORK_ERROR"
1411
+ );
1412
+ }
1413
+ if (error.code === "ETIMEDOUT" || error.message?.includes("timeout")) {
1414
+ throw new IOEventsApiError(
1415
+ "Request timeout: Adobe I/O Events API did not respond in time",
1416
+ IoEventsGlobals.STATUS_CODES.TIMEOUT,
1417
+ "TIMEOUT_ERROR"
1418
+ );
1419
+ }
1420
+ if (error.message?.includes("JSON")) {
1421
+ throw new IOEventsApiError(
1422
+ "Invalid response format from Adobe I/O Events API",
1423
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1424
+ "PARSE_ERROR"
1425
+ );
1426
+ }
1427
+ if (error.message?.includes("required") || error.message?.includes("empty")) {
1428
+ throw new IOEventsApiError(
1429
+ `Validation error: ${error.message}`,
1430
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST,
1431
+ "VALIDATION_ERROR"
1432
+ );
1433
+ }
1434
+ if (error instanceof Error) {
1435
+ throw new IOEventsApiError(
1436
+ `Failed to delete provider: ${error.message}`,
1437
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1438
+ "UNKNOWN_ERROR"
1439
+ );
1440
+ }
1441
+ throw new IOEventsApiError(
1442
+ "Unexpected error: Unknown error occurred",
1443
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1444
+ "UNKNOWN_ERROR"
1445
+ );
1446
+ }
1447
+ /**
1448
+ * Extract status code from error response
1449
+ */
1450
+ extractStatusCode(error) {
1451
+ return error.response?.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1452
+ }
1453
+ /**
1454
+ * Extracts the status code from RestClient error message
1455
+ *
1456
+ * @param errorMessage - Error message like "HTTP error! status: 404"
1457
+ * @returns The HTTP status code
1458
+ */
1459
+ extractStatusCodeFromMessage(errorMessage) {
1460
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
1461
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1462
+ }
1463
+ /**
1464
+ * Get appropriate error message for HTTP status code
1465
+ */
1466
+ getErrorMessageForStatus(status) {
1467
+ switch (status) {
1468
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
1469
+ return "Unauthorized: Invalid or expired access token";
1470
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
1471
+ return "Forbidden: Insufficient permissions to delete provider";
1472
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
1473
+ return "Provider not found: The specified provider ID does not exist";
1474
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
1475
+ return "Internal server error occurred while deleting provider";
1476
+ default:
1477
+ return `HTTP ${status}: Provider deletion failed`;
1478
+ }
1479
+ }
1480
+ };
1481
+ __name(_Delete, "Delete");
1482
+ var Delete = _Delete;
1483
+
1484
+ // src/io-events/provider/index.ts
1485
+ var _ProviderManager = class _ProviderManager {
1486
+ /**
1487
+ * Constructor for Providers service
1488
+ *
1489
+ * @param clientId - Client ID from Adobe Developer Console (x-api-key header)
1490
+ * @param consumerId - Project Organization ID from Adobe Developer Console
1491
+ * @param projectId - Project ID from Adobe Developer Console
1492
+ * @param workspaceId - Workspace ID from Adobe Developer Console
1493
+ * @param accessToken - IMS token for authentication (Bearer token)
1494
+ */
1495
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
1496
+ this.clientId = clientId;
1497
+ this.consumerId = consumerId;
1498
+ this.projectId = projectId;
1499
+ this.workspaceId = workspaceId;
1500
+ this.accessToken = accessToken;
1501
+ this.listService = new list_default(clientId, consumerId, projectId, workspaceId, accessToken);
1502
+ this.getService = new get_default(clientId, consumerId, projectId, workspaceId, accessToken);
1503
+ this.createService = new create_default(clientId, consumerId, projectId, workspaceId, accessToken);
1504
+ this.deleteService = new Delete(clientId, consumerId, projectId, workspaceId, accessToken);
1505
+ }
1506
+ /**
1507
+ * List all event providers entitled to the provided organization ID
1508
+ *
1509
+ * @param queryParams - Optional query parameters for filtering providers
1510
+ * @param queryParams.providerMetadataId - Filter by provider metadata id
1511
+ * @param queryParams.instanceId - Filter by instance id
1512
+ * @param queryParams.providerMetadataIds - List of provider metadata ids to filter (mutually exclusive with providerMetadataId)
1513
+ * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)
1514
+ * @returns Promise<Provider[]> - Array of providers
1515
+ * @throws IOEventsApiError - When API call fails with specific error details
1516
+ *
1517
+ * @example
1518
+ * ```typescript
1519
+ * // List all providers
1520
+ * const providers = await providersService.list();
1521
+ *
1522
+ * // Filter by provider metadata ID
1523
+ * const customProviders = await providersService.list({
1524
+ * providerMetadataId: '3rd_party_custom_events'
1525
+ * });
1526
+ *
1527
+ * // Include event metadata in response
1528
+ * const providersWithMetadata = await providersService.list({
1529
+ * eventmetadata: true
1530
+ * });
1531
+ * ```
1532
+ */
1533
+ async list(queryParams = {}) {
1534
+ try {
1535
+ return await this.listService.execute(queryParams);
1536
+ } catch (error) {
1537
+ if (error instanceof IOEventsApiError) {
1538
+ throw error;
1539
+ }
1540
+ throw new IOEventsApiError(
1541
+ `Unexpected error in providers list: ${error instanceof Error ? error.message : "Unknown error"}`,
1542
+ 500,
1543
+ "UNEXPECTED_ERROR"
1544
+ );
1545
+ }
1546
+ }
1547
+ /**
1548
+ * Get a specific event provider by its ID
1549
+ *
1550
+ * @param providerId - The ID of the provider to retrieve
1551
+ * @param queryParams - Optional query parameters
1552
+ * @param queryParams.eventmetadata - Boolean to fetch provider's event metadata (default: false)
1553
+ * @returns Promise<Provider> - The provider details
1554
+ * @throws IOEventsApiError - When API call fails with specific error details
1555
+ *
1556
+ * @example
1557
+ * ```typescript
1558
+ * // Get basic provider details
1559
+ * const provider = await providersService.get('provider-123');
1560
+ *
1561
+ * // Get provider details with event metadata
1562
+ * const providerWithMetadata = await providersService.get('provider-123', {
1563
+ * eventmetadata: true
1564
+ * });
1565
+ * ```
1566
+ */
1567
+ async get(providerId, queryParams = {}) {
1568
+ try {
1569
+ return await this.getService.execute(providerId, queryParams);
1570
+ } catch (error) {
1571
+ if (error instanceof IOEventsApiError) {
1572
+ throw error;
1573
+ }
1574
+ throw new IOEventsApiError(
1575
+ `Unexpected error in providers get: ${error instanceof Error ? error.message : "Unknown error"}`,
1576
+ 500,
1577
+ "UNEXPECTED_ERROR"
1578
+ );
1579
+ }
1580
+ }
1581
+ /**
1582
+ * Create a new event provider
1583
+ *
1584
+ * @param providerData - Provider input data
1585
+ * @param providerData.label - The label of this event provider (required)
1586
+ * @param providerData.description - Optional description for the provider
1587
+ * @param providerData.docs_url - Optional documentation URL for the provider
1588
+ * @param providerData.provider_metadata - Optional provider metadata ID (defaults to '3rd_party_custom_events')
1589
+ * @param providerData.instance_id - Optional technical instance ID
1590
+ * @param providerData.data_residency_region - Optional data residency region (defaults to 'va6')
1591
+ * @returns Promise<Provider> - The created provider
1592
+ * @throws IOEventsApiError - When API call fails with specific error details
1593
+ *
1594
+ * @example
1595
+ * ```typescript
1596
+ * // Create a basic provider
1597
+ * const provider = await providersService.create({
1598
+ * label: 'My Event Provider'
1599
+ * });
1600
+ *
1601
+ * // Create a provider with custom details
1602
+ * const customProvider = await providersService.create({
1603
+ * label: 'My Custom Provider',
1604
+ * description: 'Provider for custom business events',
1605
+ * provider_metadata: '3rd_party_custom_events',
1606
+ * instance_id: 'production-instance'
1607
+ * });
1608
+ * ```
1609
+ */
1610
+ async create(providerData) {
1611
+ try {
1612
+ return await this.createService.execute(providerData);
1613
+ } catch (error) {
1614
+ if (error instanceof IOEventsApiError) {
1615
+ throw error;
1616
+ }
1617
+ throw new IOEventsApiError(
1618
+ `Unexpected error in providers create: ${error instanceof Error ? error.message : "Unknown error"}`,
1619
+ 500,
1620
+ "UNEXPECTED_ERROR"
1621
+ );
1622
+ }
1623
+ }
1624
+ /**
1625
+ * Delete an event provider by ID
1626
+ *
1627
+ * @param providerId - The ID of the provider to delete
1628
+ * @returns Promise<void> - Resolves when provider is successfully deleted
1629
+ * @throws IOEventsApiError - When API call fails with specific error details
1630
+ *
1631
+ * @example
1632
+ * ```typescript
1633
+ * // Delete a provider by ID
1634
+ * await providersService.delete('provider-123');
1635
+ * console.log('Provider deleted successfully');
1636
+ * ```
1637
+ */
1638
+ async delete(providerId) {
1639
+ try {
1640
+ return await this.deleteService.execute(providerId);
1641
+ } catch (error) {
1642
+ if (error instanceof IOEventsApiError) {
1643
+ throw error;
1644
+ }
1645
+ throw new IOEventsApiError(
1646
+ `Unexpected error in providers delete: ${error instanceof Error ? error.message : "Unknown error"}`,
1647
+ 500,
1648
+ "UNEXPECTED_ERROR"
1649
+ );
1650
+ }
1651
+ }
1652
+ };
1653
+ __name(_ProviderManager, "ProviderManager");
1654
+ var ProviderManager = _ProviderManager;
1655
+ var provider_default = ProviderManager;
1656
+
1657
+ // src/io-events/event-metadata/list/index.ts
1658
+ var _List2 = class _List2 {
1659
+ /**
1660
+ * Creates an instance of List service
1661
+ *
1662
+ * @param clientId - The Adobe I/O client ID (API key)
1663
+ * @param consumerId - The consumer organization ID
1664
+ * @param projectId - The project ID
1665
+ * @param workspaceId - The workspace ID
1666
+ * @param accessToken - The access token for authentication
1667
+ */
1668
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
1669
+ this.clientId = clientId;
1670
+ this.consumerId = consumerId;
1671
+ this.projectId = projectId;
1672
+ this.workspaceId = workspaceId;
1673
+ this.accessToken = accessToken;
1674
+ if (!clientId?.trim()) {
1675
+ throw new Error("clientId is required and cannot be empty");
1676
+ }
1677
+ if (!consumerId?.trim()) {
1678
+ throw new Error("consumerId is required and cannot be empty");
1679
+ }
1680
+ if (!projectId?.trim()) {
1681
+ throw new Error("projectId is required and cannot be empty");
1682
+ }
1683
+ if (!workspaceId?.trim()) {
1684
+ throw new Error("workspaceId is required and cannot be empty");
1685
+ }
1686
+ if (!accessToken?.trim()) {
1687
+ throw new Error("accessToken is required and cannot be empty");
1688
+ }
1689
+ this.restClient = new rest_client_default();
1690
+ }
1691
+ /**
1692
+ * Retrieves all event metadata for a provider with automatic pagination
1693
+ *
1694
+ * This method automatically follows pagination links to fetch all event metadata
1695
+ * across multiple pages, returning a complete array of all event metadata.
1696
+ *
1697
+ * @param providerId - The ID of the provider to fetch event metadata for
1698
+ * @returns Promise<EventMetadata[]> - Array of all event metadata across all pages
1699
+ * @throws IOEventsApiError - When the API request fails
1700
+ */
1701
+ async execute(providerId) {
1702
+ if (!providerId?.trim()) {
1703
+ throw new IOEventsApiError(
1704
+ "providerId is required and cannot be empty",
1705
+ 400,
1706
+ "VALIDATION_ERROR"
1707
+ );
1708
+ }
1709
+ try {
1710
+ const url = `${IoEventsGlobals.BASE_URL}/events/providers/${providerId}/eventmetadata`;
1711
+ return await this.fetchAllPages(url);
1712
+ } catch (error) {
1713
+ this.handleError(error);
1714
+ }
1715
+ }
1716
+ /**
1717
+ * Recursively fetches all pages of event metadata using pagination links
1718
+ *
1719
+ * @param url - The URL to fetch (either initial URL or next page URL)
1720
+ * @param accumulatedResults - Array to accumulate results across pages
1721
+ * @returns Promise<EventMetadata[]> - Complete array of all event metadata
1722
+ * @private
1723
+ */
1724
+ async fetchAllPages(url, accumulatedResults = []) {
1725
+ const response = await this.restClient.get(url, {
1726
+ Authorization: `Bearer ${this.accessToken}`,
1727
+ "x-api-key": this.clientId,
1728
+ Accept: "application/hal+json"
1729
+ });
1730
+ if (response === null || response === void 0) {
1731
+ throw new IOEventsApiError(
1732
+ "Invalid response format: Expected object",
1733
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1734
+ "PARSE_ERROR"
1735
+ );
1736
+ }
1737
+ if (typeof response !== "object") {
1738
+ throw new IOEventsApiError(
1739
+ "Invalid response format: Expected object",
1740
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1741
+ "PARSE_ERROR"
1742
+ );
1743
+ }
1744
+ const data = response;
1745
+ if (!data._embedded || !Array.isArray(data._embedded.eventmetadata)) {
1746
+ throw new IOEventsApiError(
1747
+ "Invalid response format: Expected eventmetadata array",
1748
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1749
+ "PARSE_ERROR"
1750
+ );
1751
+ }
1752
+ const currentPageResults = data._embedded.eventmetadata;
1753
+ const allResults = [...accumulatedResults, ...currentPageResults];
1754
+ const nextPageUrl = data._links?.next?.href;
1755
+ if (nextPageUrl) {
1756
+ return await this.fetchAllPages(nextPageUrl, allResults);
1757
+ }
1758
+ return allResults;
1759
+ }
1760
+ /**
1761
+ * Handles errors from the API request
1762
+ *
1763
+ * @param error - The error object from the API request
1764
+ * @throws IOEventsApiError - Always throws with appropriate error details
1765
+ */
1766
+ handleError(error) {
1767
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
1768
+ const statusCode2 = this.extractStatusCodeFromMessage(error.message);
1769
+ const errorMessage2 = this.getErrorMessageForStatus(statusCode2);
1770
+ throw new IOEventsApiError(errorMessage2, statusCode2);
1771
+ }
1772
+ if (error.response) {
1773
+ const statusCode2 = this.extractStatusCode(error);
1774
+ const errorMessage2 = error.response.body?.message || this.getErrorMessageForStatus(statusCode2);
1775
+ throw new IOEventsApiError(
1776
+ errorMessage2,
1777
+ statusCode2,
1778
+ error.response.body,
1779
+ error.response.headers
1780
+ );
1781
+ }
1782
+ let errorMessage;
1783
+ let statusCode;
1784
+ if (error instanceof Error) {
1785
+ if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) {
1786
+ errorMessage = "Request timeout while listing event metadata";
1787
+ statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;
1788
+ } else if (error.message.includes("JSON") || error.message.includes("parse")) {
1789
+ errorMessage = "Invalid response format from Adobe I/O Events API";
1790
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1791
+ throw new IOEventsApiError(errorMessage, statusCode, "PARSE_ERROR");
1792
+ } else {
1793
+ errorMessage = `Network error: ${error.message}`;
1794
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1795
+ }
1796
+ } else {
1797
+ errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;
1798
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1799
+ }
1800
+ throw new IOEventsApiError(errorMessage, statusCode);
1801
+ }
1802
+ /**
1803
+ * Extracts the status code from the error response
1804
+ *
1805
+ * @param error - The error object
1806
+ * @returns The HTTP status code
1807
+ */
1808
+ extractStatusCode(error) {
1809
+ return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1810
+ }
1811
+ /**
1812
+ * Extracts the status code from RestClient error message
1813
+ *
1814
+ * @param errorMessage - Error message like "HTTP error! status: 404"
1815
+ * @returns The HTTP status code
1816
+ */
1817
+ extractStatusCodeFromMessage(errorMessage) {
1818
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
1819
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1820
+ }
1821
+ /**
1822
+ * Gets a human-readable error message for a given HTTP status code
1823
+ *
1824
+ * @param statusCode - The HTTP status code
1825
+ * @returns A descriptive error message
1826
+ */
1827
+ getErrorMessageForStatus(statusCode) {
1828
+ switch (statusCode) {
1829
+ case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:
1830
+ return "Invalid request parameters for listing event metadata";
1831
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
1832
+ return "Authentication failed. Please check your access token";
1833
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
1834
+ return "Access forbidden. You do not have permission to access event metadata";
1835
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
1836
+ return "Provider not found or no event metadata available";
1837
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
1838
+ return "Internal server error occurred while listing event metadata";
1839
+ default:
1840
+ return `Unexpected error occurred: HTTP ${statusCode}`;
1841
+ }
1842
+ }
1843
+ };
1844
+ __name(_List2, "List");
1845
+ var List2 = _List2;
1846
+
1847
+ // src/io-events/event-metadata/get/index.ts
1848
+ var _Get2 = class _Get2 {
1849
+ /**
1850
+ * Creates an instance of Get service
1851
+ *
1852
+ * @param clientId - The Adobe I/O client ID (API key)
1853
+ * @param consumerId - The consumer organization ID
1854
+ * @param projectId - The project ID
1855
+ * @param workspaceId - The workspace ID
1856
+ * @param accessToken - The access token for authentication
1857
+ */
1858
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
1859
+ this.clientId = clientId;
1860
+ this.consumerId = consumerId;
1861
+ this.projectId = projectId;
1862
+ this.workspaceId = workspaceId;
1863
+ this.accessToken = accessToken;
1864
+ if (!clientId?.trim()) {
1865
+ throw new Error("clientId is required and cannot be empty");
1866
+ }
1867
+ if (!consumerId?.trim()) {
1868
+ throw new Error("consumerId is required and cannot be empty");
1869
+ }
1870
+ if (!projectId?.trim()) {
1871
+ throw new Error("projectId is required and cannot be empty");
1872
+ }
1873
+ if (!workspaceId?.trim()) {
1874
+ throw new Error("workspaceId is required and cannot be empty");
1875
+ }
1876
+ if (!accessToken?.trim()) {
1877
+ throw new Error("accessToken is required and cannot be empty");
1878
+ }
1879
+ this.restClient = new rest_client_default();
1880
+ }
1881
+ /**
1882
+ * Retrieves specific event metadata by provider ID and event code
1883
+ *
1884
+ * @param providerId - The ID of the provider
1885
+ * @param eventCode - The event code to get metadata for
1886
+ * @returns Promise<EventMetadata> - The event metadata
1887
+ * @throws IOEventsApiError - When the API request fails
1888
+ */
1889
+ async execute(providerId, eventCode) {
1890
+ if (!providerId?.trim()) {
1891
+ throw new IOEventsApiError(
1892
+ "providerId is required and cannot be empty",
1893
+ 400,
1894
+ "VALIDATION_ERROR"
1895
+ );
1896
+ }
1897
+ if (!eventCode?.trim()) {
1898
+ throw new IOEventsApiError(
1899
+ "eventCode is required and cannot be empty",
1900
+ 400,
1901
+ "VALIDATION_ERROR"
1902
+ );
1903
+ }
1904
+ try {
1905
+ const url = `${IoEventsGlobals.BASE_URL}/events/providers/${providerId}/eventmetadata/${encodeURIComponent(eventCode)}`;
1906
+ const response = await this.restClient.get(url, {
1907
+ Authorization: `Bearer ${this.accessToken}`,
1908
+ "x-api-key": this.clientId,
1909
+ Accept: "application/hal+json"
1910
+ });
1911
+ if (response === null || response === void 0) {
1912
+ throw new IOEventsApiError(
1913
+ "Invalid response format: Expected object",
1914
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1915
+ "PARSE_ERROR"
1916
+ );
1917
+ }
1918
+ if (typeof response !== "object") {
1919
+ throw new IOEventsApiError(
1920
+ "Invalid response format: Expected object",
1921
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR,
1922
+ "PARSE_ERROR"
1923
+ );
1924
+ }
1925
+ return response;
1926
+ } catch (error) {
1927
+ this.handleError(error);
1928
+ }
1929
+ }
1930
+ /**
1931
+ * Handles errors from the API request
1932
+ *
1933
+ * @param error - The error object from the API request
1934
+ * @throws IOEventsApiError - Always throws with appropriate error details
1935
+ */
1936
+ handleError(error) {
1937
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
1938
+ const statusCode2 = this.extractStatusCodeFromMessage(error.message);
1939
+ const errorMessage2 = this.getErrorMessageForStatus(statusCode2);
1940
+ throw new IOEventsApiError(errorMessage2, statusCode2);
1941
+ }
1942
+ if (error.response) {
1943
+ const statusCode2 = this.extractStatusCode(error);
1944
+ const errorMessage2 = error.response.body?.message || this.getErrorMessageForStatus(statusCode2);
1945
+ throw new IOEventsApiError(
1946
+ errorMessage2,
1947
+ statusCode2,
1948
+ error.response.body?.error_code,
1949
+ error.response.body?.details
1950
+ );
1951
+ }
1952
+ let errorMessage;
1953
+ let statusCode;
1954
+ if (error instanceof Error) {
1955
+ if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) {
1956
+ errorMessage = "Request timeout while getting event metadata";
1957
+ statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;
1958
+ } else if (error.message.includes("JSON") || error.message.includes("parse")) {
1959
+ errorMessage = "Invalid response format from Adobe I/O Events API";
1960
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1961
+ throw new IOEventsApiError(errorMessage, statusCode, "PARSE_ERROR");
1962
+ } else {
1963
+ errorMessage = `Network error: ${error.message}`;
1964
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1965
+ }
1966
+ } else {
1967
+ errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;
1968
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1969
+ }
1970
+ throw new IOEventsApiError(errorMessage, statusCode);
1971
+ }
1972
+ /**
1973
+ * Extracts the status code from the error response
1974
+ *
1975
+ * @param error - The error object
1976
+ * @returns The HTTP status code
1977
+ */
1978
+ extractStatusCode(error) {
1979
+ return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1980
+ }
1981
+ /**
1982
+ * Extracts the status code from RestClient error message
1983
+ *
1984
+ * @param errorMessage - Error message like "HTTP error! status: 404"
1985
+ * @returns The HTTP status code
1986
+ */
1987
+ extractStatusCodeFromMessage(errorMessage) {
1988
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
1989
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
1990
+ }
1991
+ /**
1992
+ * Gets a human-readable error message for a given HTTP status code
1993
+ *
1994
+ * @param statusCode - The HTTP status code
1995
+ * @returns A descriptive error message
1996
+ */
1997
+ getErrorMessageForStatus(statusCode) {
1998
+ switch (statusCode) {
1999
+ case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:
2000
+ return "Invalid request parameters for getting event metadata";
2001
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
2002
+ return "Authentication failed. Please check your access token";
2003
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
2004
+ return "Access forbidden. You do not have permission to access this event metadata";
2005
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
2006
+ return "Event metadata not found for the specified provider and event code";
2007
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
2008
+ return "Internal server error occurred while getting event metadata";
2009
+ default:
2010
+ return `Unexpected error occurred: HTTP ${statusCode}`;
2011
+ }
2012
+ }
2013
+ };
2014
+ __name(_Get2, "Get");
2015
+ var Get2 = _Get2;
2016
+
2017
+ // src/io-events/event-metadata/create/index.ts
2018
+ var _Create2 = class _Create2 {
2019
+ /**
2020
+ * Constructor for Create event metadata service
2021
+ *
2022
+ * @param clientId - Client ID from Adobe Developer Console (x-api-key header)
2023
+ * @param consumerId - Project Organization ID from Adobe Developer Console
2024
+ * @param projectId - Project ID from Adobe Developer Console
2025
+ * @param workspaceId - Workspace ID from Adobe Developer Console
2026
+ * @param accessToken - IMS token for authentication (Bearer token)
2027
+ */
2028
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
2029
+ this.clientId = clientId;
2030
+ this.consumerId = consumerId;
2031
+ this.projectId = projectId;
2032
+ this.workspaceId = workspaceId;
2033
+ this.accessToken = accessToken;
2034
+ this.endpoint = IoEventsGlobals.BASE_URL;
2035
+ if (!clientId?.trim()) {
2036
+ throw new Error("clientId is required and cannot be empty");
2037
+ }
2038
+ if (!consumerId?.trim()) {
2039
+ throw new Error("consumerId is required and cannot be empty");
2040
+ }
2041
+ if (!projectId?.trim()) {
2042
+ throw new Error("projectId is required and cannot be empty");
2043
+ }
2044
+ if (!workspaceId?.trim()) {
2045
+ throw new Error("workspaceId is required and cannot be empty");
2046
+ }
2047
+ if (!accessToken?.trim()) {
2048
+ throw new Error("accessToken is required and cannot be empty");
2049
+ }
2050
+ this.restClient = new rest_client_default();
2051
+ }
2052
+ /**
2053
+ * Execute the create event metadata API call
2054
+ *
2055
+ * @param providerId - The ID of the provider to create event metadata for
2056
+ * @param eventMetadataData - The event metadata input model
2057
+ * @returns Promise<EventMetadata> - The created event metadata
2058
+ * @throws IOEventsApiError - When API call fails with specific error details
2059
+ */
2060
+ async execute(providerId, eventMetadataData) {
2061
+ try {
2062
+ if (!providerId?.trim()) {
2063
+ throw new IOEventsApiError(
2064
+ "providerId is required and cannot be empty",
2065
+ 400,
2066
+ "VALIDATION_ERROR"
2067
+ );
2068
+ }
2069
+ if (!eventMetadataData) {
2070
+ throw new IOEventsApiError("eventMetadataData is required", 400, "VALIDATION_ERROR");
2071
+ }
2072
+ this.validateEventMetadataInput(eventMetadataData);
2073
+ const apiPayload = this.convertToApiPayload(eventMetadataData);
2074
+ const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}/eventmetadata`;
2075
+ const headers = {
2076
+ Authorization: `Bearer ${this.accessToken}`,
2077
+ "x-api-key": this.clientId,
2078
+ Accept: "application/hal+json",
2079
+ "Content-Type": "application/json"
2080
+ };
2081
+ const response = await this.restClient.post(url, headers, apiPayload);
2082
+ if (response === null || response === void 0) {
2083
+ throw new IOEventsApiError(
2084
+ "Invalid response format: Expected object",
2085
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR
2086
+ );
2087
+ }
2088
+ if (typeof response !== "object") {
2089
+ throw new IOEventsApiError(
2090
+ "Invalid response format: Expected object",
2091
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR
2092
+ );
2093
+ }
2094
+ return response;
2095
+ } catch (error) {
2096
+ this.handleError(error);
2097
+ }
2098
+ }
2099
+ /**
2100
+ * Validates the event metadata input data
2101
+ *
2102
+ * @param eventMetadataData - The event metadata input to validate
2103
+ * @throws Error - When validation fails
2104
+ * @private
2105
+ */
2106
+ validateEventMetadataInput(eventMetadataData) {
2107
+ const { description, label, event_code, sample_event_template } = eventMetadataData;
2108
+ if (!description?.trim()) {
2109
+ throw new IOEventsApiError(
2110
+ "description is required and cannot be empty",
2111
+ 400,
2112
+ "VALIDATION_ERROR"
2113
+ );
2114
+ }
2115
+ if (!label?.trim()) {
2116
+ throw new IOEventsApiError("label is required and cannot be empty", 400, "VALIDATION_ERROR");
2117
+ }
2118
+ if (!event_code?.trim()) {
2119
+ throw new IOEventsApiError(
2120
+ "event_code is required and cannot be empty",
2121
+ 400,
2122
+ "VALIDATION_ERROR"
2123
+ );
2124
+ }
2125
+ if (description.length > 255) {
2126
+ throw new Error("description cannot exceed 255 characters");
2127
+ }
2128
+ if (label.length > 255) {
2129
+ throw new Error("label cannot exceed 255 characters");
2130
+ }
2131
+ if (event_code.length > 255) {
2132
+ throw new Error("event_code cannot exceed 255 characters");
2133
+ }
2134
+ const descriptionPattern = /^[\w\s\-_.(),:''`?#!]+$/;
2135
+ if (!descriptionPattern.test(description)) {
2136
+ throw new Error("description contains invalid characters");
2137
+ }
2138
+ const labelPattern = /^[\w\s\-_.(),:''`?#!]+$/;
2139
+ if (!labelPattern.test(label)) {
2140
+ throw new Error("label contains invalid characters");
2141
+ }
2142
+ const eventCodePattern = /^[\w\-_.]+$/;
2143
+ if (!eventCodePattern.test(event_code)) {
2144
+ throw new Error("event_code contains invalid characters");
2145
+ }
2146
+ if (sample_event_template !== void 0) {
2147
+ if (typeof sample_event_template !== "object" || sample_event_template === null) {
2148
+ throw new Error("sample_event_template must be a valid JSON object");
2149
+ }
2150
+ try {
2151
+ const jsonString = JSON.stringify(sample_event_template);
2152
+ const base64Length = Buffer.from(jsonString).toString("base64").length;
2153
+ if (base64Length > 87382) {
2154
+ throw new Error("sample_event_template JSON object is too large when base64 encoded");
2155
+ }
2156
+ } catch (error) {
2157
+ if (error instanceof Error && error.message.includes("sample_event_template JSON object is too large")) {
2158
+ throw error;
2159
+ }
2160
+ throw new Error("sample_event_template must be a valid JSON object");
2161
+ }
2162
+ }
2163
+ }
2164
+ /**
2165
+ * Converts the input data to the format expected by the API
2166
+ *
2167
+ * @param eventMetadataData - The event metadata input data
2168
+ * @returns The converted payload for the API
2169
+ * @private
2170
+ */
2171
+ convertToApiPayload(eventMetadataData) {
2172
+ const { sample_event_template, ...rest } = eventMetadataData;
2173
+ const payload = { ...rest };
2174
+ if (sample_event_template !== void 0) {
2175
+ payload.sample_event_template = Buffer.from(JSON.stringify(sample_event_template)).toString(
2176
+ "base64"
2177
+ );
2178
+ }
2179
+ return payload;
2180
+ }
2181
+ /**
2182
+ * Handles errors from the API request
2183
+ *
2184
+ * @param error - The error object from the API request
2185
+ * @throws IOEventsApiError - Always throws with appropriate error details
2186
+ * @private
2187
+ */
2188
+ handleError(error) {
2189
+ if (error instanceof IOEventsApiError) {
2190
+ throw error;
2191
+ }
2192
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
2193
+ const statusCode2 = this.extractStatusCodeFromMessage(error.message);
2194
+ const errorMessage2 = this.getErrorMessageForStatus(statusCode2);
2195
+ throw new IOEventsApiError(errorMessage2, statusCode2);
2196
+ }
2197
+ if (error.response) {
2198
+ const statusCode2 = this.extractStatusCode(error);
2199
+ const errorMessage2 = error.response.body?.message || this.getErrorMessageForStatus(statusCode2);
2200
+ throw new IOEventsApiError(
2201
+ errorMessage2,
2202
+ statusCode2,
2203
+ error.response.body?.error_code,
2204
+ error.response.body?.details
2205
+ );
2206
+ }
2207
+ let errorMessage;
2208
+ let statusCode;
2209
+ if (error instanceof Error) {
2210
+ if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) {
2211
+ errorMessage = "Request timeout while creating event metadata";
2212
+ statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;
2213
+ } else if (error.message.includes("is required") || error.message.includes("cannot be empty") || error.message.includes("cannot exceed") || error.message.includes("contains invalid characters") || error.message.includes("must be a valid") || error.message.includes("too large when base64 encoded")) {
2214
+ throw new IOEventsApiError(
2215
+ error.message,
2216
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST,
2217
+ "VALIDATION_ERROR"
2218
+ );
2219
+ } else if (error.message.includes("JSON") || error.message.includes("parse")) {
2220
+ errorMessage = "Invalid response format from Adobe I/O Events API";
2221
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2222
+ } else {
2223
+ errorMessage = `Network error: ${error.message}`;
2224
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2225
+ }
2226
+ } else {
2227
+ errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;
2228
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2229
+ }
2230
+ throw new IOEventsApiError(errorMessage, statusCode);
2231
+ }
2232
+ /**
2233
+ * Extracts the status code from the error response
2234
+ *
2235
+ * @param error - The error object
2236
+ * @returns The HTTP status code
2237
+ * @private
2238
+ */
2239
+ extractStatusCode(error) {
2240
+ return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2241
+ }
2242
+ /**
2243
+ * Extracts the status code from RestClient error message
2244
+ *
2245
+ * @param errorMessage - Error message like "HTTP error! status: 404"
2246
+ * @returns The HTTP status code
2247
+ * @private
2248
+ */
2249
+ extractStatusCodeFromMessage(errorMessage) {
2250
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
2251
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2252
+ }
2253
+ /**
2254
+ * Gets a human-readable error message based on HTTP status code
2255
+ *
2256
+ * @param statusCode - HTTP status code
2257
+ * @returns string - User-friendly error message
2258
+ * @private
2259
+ */
2260
+ getErrorMessageForStatus(statusCode) {
2261
+ switch (statusCode) {
2262
+ case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:
2263
+ return "Invalid request parameters for creating event metadata";
2264
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
2265
+ return "Authentication failed. Please check your access token";
2266
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
2267
+ return "Access forbidden. You do not have permission to create event metadata";
2268
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
2269
+ return "Provider not found. The specified provider ID does not exist";
2270
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
2271
+ return "Internal server error occurred while creating event metadata";
2272
+ default:
2273
+ return `Unexpected error occurred: HTTP ${statusCode}`;
2274
+ }
2275
+ }
2276
+ };
2277
+ __name(_Create2, "Create");
2278
+ var Create2 = _Create2;
2279
+ var create_default2 = Create2;
2280
+
2281
+ // src/io-events/event-metadata/delete/index.ts
2282
+ var _Delete2 = class _Delete2 {
2283
+ /**
2284
+ * Constructor for Delete event metadata service
2285
+ *
2286
+ * @param clientId - Client ID from Adobe Developer Console (x-api-key header)
2287
+ * @param consumerId - Project Organization ID from Adobe Developer Console
2288
+ * @param projectId - Project ID from Adobe Developer Console
2289
+ * @param workspaceId - Workspace ID from Adobe Developer Console
2290
+ * @param accessToken - IMS token for authentication (Bearer token)
2291
+ */
2292
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
2293
+ this.clientId = clientId;
2294
+ this.consumerId = consumerId;
2295
+ this.projectId = projectId;
2296
+ this.workspaceId = workspaceId;
2297
+ this.accessToken = accessToken;
2298
+ this.endpoint = IoEventsGlobals.BASE_URL;
2299
+ if (!clientId?.trim()) {
2300
+ throw new Error("clientId is required and cannot be empty");
2301
+ }
2302
+ if (!consumerId?.trim()) {
2303
+ throw new Error("consumerId is required and cannot be empty");
2304
+ }
2305
+ if (!projectId?.trim()) {
2306
+ throw new Error("projectId is required and cannot be empty");
2307
+ }
2308
+ if (!workspaceId?.trim()) {
2309
+ throw new Error("workspaceId is required and cannot be empty");
2310
+ }
2311
+ if (!accessToken?.trim()) {
2312
+ throw new Error("accessToken is required and cannot be empty");
2313
+ }
2314
+ this.restClient = new rest_client_default();
2315
+ }
2316
+ /**
2317
+ * Execute the delete event metadata API call
2318
+ *
2319
+ * @param providerId - The ID of the provider to delete event metadata for
2320
+ * @param eventCode - Optional event code to delete specific event metadata. If not provided, deletes all event metadata for the provider
2321
+ * @returns Promise<void> - No content returned on successful deletion (204)
2322
+ * @throws IOEventsApiError - When API call fails with specific error details
2323
+ */
2324
+ async execute(providerId, eventCode) {
2325
+ try {
2326
+ if (!providerId?.trim()) {
2327
+ throw new IOEventsApiError(
2328
+ "providerId is required and cannot be empty",
2329
+ 400,
2330
+ "VALIDATION_ERROR"
2331
+ );
2332
+ }
2333
+ if (eventCode !== void 0 && !eventCode?.trim()) {
2334
+ throw new IOEventsApiError(
2335
+ "eventCode cannot be empty when provided",
2336
+ 400,
2337
+ "VALIDATION_ERROR"
2338
+ );
2339
+ }
2340
+ let url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/providers/${providerId}/eventmetadata`;
2341
+ if (eventCode?.trim()) {
2342
+ url += `/${encodeURIComponent(eventCode.trim())}`;
2343
+ }
2344
+ const headers = {
2345
+ Authorization: `Bearer ${this.accessToken}`,
2346
+ "x-api-key": this.clientId,
2347
+ Accept: "application/hal+json"
2348
+ };
2349
+ await this.restClient.delete(url, headers);
2350
+ } catch (error) {
2351
+ this.handleError(error);
2352
+ }
2353
+ }
2354
+ /**
2355
+ * Handles errors from the API request
2356
+ *
2357
+ * @param error - The error object from the API request
2358
+ * @throws IOEventsApiError - Always throws with appropriate error details
2359
+ * @private
2360
+ */
2361
+ handleError(error) {
2362
+ if (error instanceof IOEventsApiError) {
2363
+ throw error;
2364
+ }
2365
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
2366
+ const statusCode2 = this.extractStatusCodeFromMessage(error.message);
2367
+ const errorMessage2 = this.getErrorMessageForStatus(statusCode2);
2368
+ throw new IOEventsApiError(errorMessage2, statusCode2);
2369
+ }
2370
+ if (error.response) {
2371
+ const statusCode2 = this.extractStatusCode(error);
2372
+ const errorMessage2 = error.response.body?.message || this.getErrorMessageForStatus(statusCode2);
2373
+ throw new IOEventsApiError(
2374
+ errorMessage2,
2375
+ statusCode2,
2376
+ error.response.body?.error_code,
2377
+ error.response.body?.details
2378
+ );
2379
+ }
2380
+ let errorMessage;
2381
+ let statusCode;
2382
+ if (error instanceof Error) {
2383
+ if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) {
2384
+ errorMessage = "Request timeout while deleting event metadata";
2385
+ statusCode = IoEventsGlobals.STATUS_CODES.REQUEST_TIMEOUT;
2386
+ } else if (error.message.includes("is required") || error.message.includes("cannot be empty")) {
2387
+ throw new IOEventsApiError(
2388
+ error.message,
2389
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST,
2390
+ "VALIDATION_ERROR"
2391
+ );
2392
+ } else if (error.message.includes("JSON") || error.message.includes("parse")) {
2393
+ errorMessage = "Invalid response format from Adobe I/O Events API";
2394
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2395
+ } else {
2396
+ errorMessage = `Network error: ${error.message}`;
2397
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2398
+ }
2399
+ } else {
2400
+ errorMessage = `API Error: HTTP ${IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR}`;
2401
+ statusCode = IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2402
+ }
2403
+ throw new IOEventsApiError(errorMessage, statusCode);
2404
+ }
2405
+ /**
2406
+ * Extracts the status code from the error response
2407
+ *
2408
+ * @param error - The error object
2409
+ * @returns The HTTP status code
2410
+ * @private
2411
+ */
2412
+ extractStatusCode(error) {
2413
+ return error.response?.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2414
+ }
2415
+ /**
2416
+ * Extracts the status code from RestClient error message
2417
+ *
2418
+ * @param errorMessage - Error message like "HTTP error! status: 404"
2419
+ * @returns The HTTP status code
2420
+ * @private
2421
+ */
2422
+ extractStatusCodeFromMessage(errorMessage) {
2423
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
2424
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
2425
+ }
2426
+ /**
2427
+ * Gets a human-readable error message based on HTTP status code
2428
+ *
2429
+ * @param statusCode - HTTP status code
2430
+ * @returns string - User-friendly error message
2431
+ * @private
2432
+ */
2433
+ getErrorMessageForStatus(statusCode) {
2434
+ switch (statusCode) {
2435
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
2436
+ return "Authentication failed. Please check your access token";
2437
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
2438
+ return "Access forbidden. You do not have permission to delete event metadata";
2439
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
2440
+ return "Provider or event metadata not found. The specified provider ID or event code does not exist";
2441
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
2442
+ return "Internal server error occurred while deleting event metadata";
2443
+ default:
2444
+ return `Unexpected error occurred: HTTP ${statusCode}`;
2445
+ }
2446
+ }
2447
+ };
2448
+ __name(_Delete2, "Delete");
2449
+ var Delete2 = _Delete2;
2450
+ var delete_default = Delete2;
2451
+
2452
+ // src/io-events/event-metadata/index.ts
2453
+ var _EventMetadataManager = class _EventMetadataManager {
2454
+ /**
2455
+ * Creates an instance of EventMetadataManager
2456
+ *
2457
+ * @param clientId - Adobe I/O Client ID for API authentication
2458
+ * @param consumerId - Consumer organization ID
2459
+ * @param projectId - Project ID within the consumer organization
2460
+ * @param workspaceId - Workspace ID within the project
2461
+ * @param accessToken - Access token for API authentication
2462
+ */
2463
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
2464
+ this.clientId = clientId;
2465
+ this.consumerId = consumerId;
2466
+ this.projectId = projectId;
2467
+ this.workspaceId = workspaceId;
2468
+ this.accessToken = accessToken;
2469
+ this.listService = new List2(clientId, consumerId, projectId, workspaceId, accessToken);
2470
+ this.getService = new Get2(clientId, consumerId, projectId, workspaceId, accessToken);
2471
+ this.createService = new create_default2(clientId, consumerId, projectId, workspaceId, accessToken);
2472
+ this.deleteService = new delete_default(clientId, consumerId, projectId, workspaceId, accessToken);
2473
+ }
2474
+ /**
2475
+ * Lists all event metadata for a provider
2476
+ *
2477
+ * @param providerId - The ID of the provider to fetch event metadata for
2478
+ * @returns Promise<EventMetadata[]> - Array of event metadata
2479
+ * @throws IOEventsApiError - When the API request fails
2480
+ *
2481
+ * @example
2482
+ * // List all event metadata for a provider
2483
+ * const allMetadata = await eventMetadata.list('provider-123');
2484
+ */
2485
+ async list(providerId) {
2486
+ try {
2487
+ return await this.listService.execute(providerId);
2488
+ } catch (error) {
2489
+ if (error instanceof IOEventsApiError) {
2490
+ throw error;
2491
+ }
2492
+ throw new IOEventsApiError(
2493
+ `Unexpected error in event metadata list: ${error instanceof Error ? error.message : "Unknown error"}`,
2494
+ 500,
2495
+ "UNEXPECTED_ERROR"
2496
+ );
2497
+ }
2498
+ }
2499
+ /**
2500
+ * Gets specific event metadata by provider ID and event code
2501
+ *
2502
+ * @param providerId - The ID of the provider
2503
+ * @param eventCode - The event code to get metadata for
2504
+ * @returns Promise<EventMetadata> - The event metadata
2505
+ * @throws IOEventsApiError - When the API request fails
2506
+ *
2507
+ * @example
2508
+ * // Get specific event metadata by event code
2509
+ * const specificMetadata = await eventMetadata.get('provider-123', 'user.created');
2510
+ */
2511
+ async get(providerId, eventCode) {
2512
+ try {
2513
+ return await this.getService.execute(providerId, eventCode);
2514
+ } catch (error) {
2515
+ if (error instanceof IOEventsApiError) {
2516
+ throw error;
2517
+ }
2518
+ throw new IOEventsApiError(
2519
+ `Unexpected error in event metadata get: ${error instanceof Error ? error.message : "Unknown error"}`,
2520
+ 500,
2521
+ "UNEXPECTED_ERROR"
2522
+ );
2523
+ }
2524
+ }
2525
+ /**
2526
+ * Creates new event metadata for a provider
2527
+ *
2528
+ * @param providerId - The ID of the provider to create event metadata for
2529
+ * @param eventMetadataData - The event metadata input data
2530
+ * @returns Promise<EventMetadata> - The created event metadata
2531
+ * @throws IOEventsApiError - When the API request fails
2532
+ *
2533
+ * @example
2534
+ * // Create new event metadata
2535
+ * const newMetadata = await eventMetadata.create('provider-123', {
2536
+ * event_code: 'com.example.user.created',
2537
+ * label: 'User Created',
2538
+ * description: 'Triggered when a new user is created',
2539
+ * sample_event_template: { name: 'John Doe', email: 'john@example.com' } // JSON object
2540
+ * });
2541
+ */
2542
+ async create(providerId, eventMetadataData) {
2543
+ try {
2544
+ return await this.createService.execute(providerId, eventMetadataData);
2545
+ } catch (error) {
2546
+ if (error instanceof IOEventsApiError) {
2547
+ throw error;
2548
+ }
2549
+ throw new IOEventsApiError(
2550
+ `Unexpected error in event metadata create: ${error instanceof Error ? error.message : "Unknown error"}`,
2551
+ 500,
2552
+ "UNEXPECTED_ERROR"
2553
+ );
2554
+ }
2555
+ }
2556
+ /**
2557
+ * Deletes event metadata for a provider
2558
+ *
2559
+ * @param providerId - The ID of the provider to delete event metadata for
2560
+ * @param eventCode - Optional event code to delete specific event metadata. If not provided, deletes all event metadata for the provider
2561
+ * @returns Promise<void> - No content returned on successful deletion
2562
+ * @throws IOEventsApiError - When the API request fails
2563
+ *
2564
+ * @example
2565
+ * // Delete all event metadata for a provider
2566
+ * await eventMetadata.delete('provider-123');
2567
+ *
2568
+ * @example
2569
+ * // Delete specific event metadata by event code
2570
+ * await eventMetadata.delete('provider-123', 'com.example.user.created');
2571
+ */
2572
+ async delete(providerId, eventCode) {
2573
+ try {
2574
+ return await this.deleteService.execute(providerId, eventCode);
2575
+ } catch (error) {
2576
+ if (error instanceof IOEventsApiError) {
2577
+ throw error;
2578
+ }
2579
+ throw new IOEventsApiError(
2580
+ `Unexpected error in event metadata delete: ${error instanceof Error ? error.message : "Unknown error"}`,
2581
+ 500,
2582
+ "UNEXPECTED_ERROR"
2583
+ );
2584
+ }
2585
+ }
2586
+ };
2587
+ __name(_EventMetadataManager, "EventMetadataManager");
2588
+ var EventMetadataManager = _EventMetadataManager;
2589
+ var event_metadata_default = EventMetadataManager;
2590
+
2591
+ // src/io-events/registration/create/index.ts
2592
+ var _Create3 = class _Create3 {
2593
+ /**
2594
+ * Initialize the Create service
2595
+ */
2596
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
2597
+ if (!clientId?.trim()) {
2598
+ throw new IOEventsApiError("clientId is required and cannot be empty", 400);
2599
+ }
2600
+ if (!consumerId?.trim()) {
2601
+ throw new IOEventsApiError("consumerId is required and cannot be empty", 400);
2602
+ }
2603
+ if (!projectId?.trim()) {
2604
+ throw new IOEventsApiError("projectId is required and cannot be empty", 400);
2605
+ }
2606
+ if (!workspaceId?.trim()) {
2607
+ throw new IOEventsApiError("workspaceId is required and cannot be empty", 400);
2608
+ }
2609
+ if (!accessToken?.trim()) {
2610
+ throw new IOEventsApiError("accessToken is required and cannot be empty", 400);
2611
+ }
2612
+ this.restClient = new rest_client_default();
2613
+ this.endpoint = IoEventsGlobals.BASE_URL;
2614
+ this.clientId = clientId;
2615
+ this.consumerId = consumerId;
2616
+ this.projectId = projectId;
2617
+ this.workspaceId = workspaceId;
2618
+ this.accessToken = accessToken;
2619
+ }
2620
+ /**
2621
+ * Create a new registration
2622
+ *
2623
+ * @param registrationData - The registration data to create
2624
+ * @returns Promise<Registration> - The created registration
2625
+ * @throws IOEventsApiError - When the API call fails
2626
+ *
2627
+ * @example
2628
+ * ```typescript
2629
+ * const registration = await registrationManager.create({
2630
+ * client_id: 'your-client-id',
2631
+ * name: 'My Registration',
2632
+ * description: 'Registration for user events',
2633
+ * webhook_url: 'https://example.com/webhook',
2634
+ * events_of_interest: [
2635
+ * {
2636
+ * provider_id: 'provider-123',
2637
+ * event_code: 'com.example.user.created'
2638
+ * }
2639
+ * ],
2640
+ * delivery_type: 'webhook',
2641
+ * enabled: true
2642
+ * });
2643
+ * console.log(registration.registration_id);
2644
+ * ```
2645
+ */
2646
+ async execute(registrationData) {
2647
+ try {
2648
+ this.validateRegistrationInput(registrationData);
2649
+ const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations`;
2650
+ const response = await this.restClient.post(
2651
+ url,
2652
+ {
2653
+ Authorization: `Bearer ${this.accessToken}`,
2654
+ "x-api-key": this.clientId,
2655
+ "Content-Type": "application/json",
2656
+ Accept: "application/hal+json"
2657
+ },
2658
+ registrationData
2659
+ );
2660
+ return response;
2661
+ } catch (error) {
2662
+ this.handleError(error);
2663
+ }
2664
+ }
2665
+ /**
2666
+ * Validates the registration input data
2667
+ */
2668
+ validateRegistrationInput(registrationData) {
2669
+ if (!registrationData) {
2670
+ throw new IOEventsApiError("Registration data is required", 400);
2671
+ }
2672
+ if (!registrationData.client_id?.trim()) {
2673
+ throw new IOEventsApiError("Client ID is required", 400);
2674
+ }
2675
+ if (registrationData.client_id.length < 3 || registrationData.client_id.length > 255) {
2676
+ throw new IOEventsApiError("Client ID must be between 3 and 255 characters", 400);
2677
+ }
2678
+ if (!registrationData.name?.trim()) {
2679
+ throw new IOEventsApiError("Registration name is required", 400);
2680
+ }
2681
+ if (registrationData.name.length < 3 || registrationData.name.length > 255) {
2682
+ throw new IOEventsApiError("Registration name must be between 3 and 255 characters", 400);
2683
+ }
2684
+ if (registrationData.description && registrationData.description.length > 5e3) {
2685
+ throw new IOEventsApiError("Description must not exceed 5000 characters", 400);
2686
+ }
2687
+ if (registrationData.webhook_url && registrationData.webhook_url.length > 4e3) {
2688
+ throw new IOEventsApiError("Webhook URL must not exceed 4000 characters", 400);
2689
+ }
2690
+ if (!registrationData.events_of_interest || !Array.isArray(registrationData.events_of_interest)) {
2691
+ throw new IOEventsApiError("Events of interest is required and must be an array", 400);
2692
+ }
2693
+ if (registrationData.events_of_interest.length === 0) {
2694
+ throw new IOEventsApiError("At least one event of interest is required", 400);
2695
+ }
2696
+ registrationData.events_of_interest.forEach((event, index) => {
2697
+ if (!event.provider_id?.trim()) {
2698
+ throw new IOEventsApiError(`Provider ID is required for event at index ${index}`, 400);
2699
+ }
2700
+ if (!event.event_code?.trim()) {
2701
+ throw new IOEventsApiError(`Event code is required for event at index ${index}`, 400);
2702
+ }
2703
+ });
2704
+ if (!registrationData.delivery_type?.trim()) {
2705
+ throw new IOEventsApiError("Delivery type is required", 400);
2706
+ }
2707
+ const validDeliveryTypes = ["webhook", "webhook_batch", "journal", "aws_eventbridge"];
2708
+ if (!validDeliveryTypes.includes(registrationData.delivery_type)) {
2709
+ throw new IOEventsApiError(
2710
+ `Delivery type must be one of: ${validDeliveryTypes.join(", ")}`,
2711
+ 400
2712
+ );
2713
+ }
2714
+ if (registrationData.runtime_action && registrationData.runtime_action.length > 255) {
2715
+ throw new IOEventsApiError("Runtime action must not exceed 255 characters", 400);
2716
+ }
2717
+ }
2718
+ /**
2719
+ * Handles errors from the API call
2720
+ */
2721
+ handleError(error) {
2722
+ if (error instanceof IOEventsApiError) {
2723
+ throw error;
2724
+ }
2725
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
2726
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
2727
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2728
+ throw new IOEventsApiError(errorMessage, statusCode);
2729
+ }
2730
+ if (error.response?.status) {
2731
+ const statusCode = error.response.status;
2732
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2733
+ throw new IOEventsApiError(errorMessage, statusCode);
2734
+ }
2735
+ if (error.status) {
2736
+ const statusCode = error.status;
2737
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2738
+ throw new IOEventsApiError(errorMessage, statusCode);
2739
+ }
2740
+ throw new IOEventsApiError("Network error occurred", 500);
2741
+ }
2742
+ /**
2743
+ * Extracts status code from HTTP error message
2744
+ */
2745
+ extractStatusCodeFromMessage(message) {
2746
+ const match = message.match(/HTTP error! status:\s*(\d+)/);
2747
+ return match ? parseInt(match[1], 10) : 500;
2748
+ }
2749
+ /**
2750
+ * Gets appropriate error message for HTTP status code
2751
+ */
2752
+ getErrorMessageForStatus(statusCode) {
2753
+ switch (statusCode) {
2754
+ case 400:
2755
+ return "Bad request: Invalid registration data provided";
2756
+ case 401:
2757
+ return "Unauthorized: Invalid or missing authentication";
2758
+ case 403:
2759
+ return "Forbidden: Insufficient permissions";
2760
+ case 409:
2761
+ return "Conflict: Registration with this name already exists";
2762
+ case 422:
2763
+ return "Unprocessable entity: Invalid registration data";
2764
+ case 500:
2765
+ return "Internal server error";
2766
+ default:
2767
+ return `API error: HTTP ${statusCode}`;
2768
+ }
2769
+ }
2770
+ };
2771
+ __name(_Create3, "Create");
2772
+ var Create3 = _Create3;
2773
+ var create_default3 = Create3;
2774
+
2775
+ // src/io-events/registration/delete/index.ts
2776
+ var _Delete3 = class _Delete3 {
2777
+ /**
2778
+ * Initialize the Delete service
2779
+ */
2780
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
2781
+ if (!clientId?.trim()) {
2782
+ throw new IOEventsApiError("clientId is required and cannot be empty", 400);
2783
+ }
2784
+ if (!consumerId?.trim()) {
2785
+ throw new IOEventsApiError("consumerId is required and cannot be empty", 400);
2786
+ }
2787
+ if (!projectId?.trim()) {
2788
+ throw new IOEventsApiError("projectId is required and cannot be empty", 400);
2789
+ }
2790
+ if (!workspaceId?.trim()) {
2791
+ throw new IOEventsApiError("workspaceId is required and cannot be empty", 400);
2792
+ }
2793
+ if (!accessToken?.trim()) {
2794
+ throw new IOEventsApiError("accessToken is required and cannot be empty", 400);
2795
+ }
2796
+ this.restClient = new rest_client_default();
2797
+ this.endpoint = IoEventsGlobals.BASE_URL;
2798
+ this.clientId = clientId;
2799
+ this.consumerId = consumerId;
2800
+ this.projectId = projectId;
2801
+ this.workspaceId = workspaceId;
2802
+ this.accessToken = accessToken;
2803
+ }
2804
+ /**
2805
+ * Delete a registration by ID
2806
+ *
2807
+ * @param registrationId - The registration ID to delete
2808
+ * @returns Promise<void> - Resolves when deletion is successful
2809
+ * @throws IOEventsApiError - When the API call fails
2810
+ *
2811
+ * @example
2812
+ * ```typescript
2813
+ * await registrationManager.delete('your-registration-id');
2814
+ * console.log('Registration deleted successfully');
2815
+ * ```
2816
+ */
2817
+ async execute(registrationId) {
2818
+ try {
2819
+ this.validateInputs(registrationId);
2820
+ const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations/${registrationId}`;
2821
+ await this.restClient.delete(url, {
2822
+ Authorization: `Bearer ${this.accessToken}`,
2823
+ "x-api-key": this.clientId,
2824
+ Accept: "text/plain"
2825
+ });
2826
+ } catch (error) {
2827
+ this.handleError(error);
2828
+ }
2829
+ }
2830
+ /**
2831
+ * Validates the input parameters
2832
+ */
2833
+ validateInputs(registrationId) {
2834
+ if (!registrationId?.trim()) {
2835
+ throw new IOEventsApiError("Registration ID is required", 400);
2836
+ }
2837
+ }
2838
+ /**
2839
+ * Handles errors from the API call
2840
+ */
2841
+ handleError(error) {
2842
+ if (error instanceof IOEventsApiError) {
2843
+ throw error;
2844
+ }
2845
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
2846
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
2847
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2848
+ throw new IOEventsApiError(errorMessage, statusCode);
2849
+ }
2850
+ if (error.response?.status) {
2851
+ const statusCode = error.response.status;
2852
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2853
+ throw new IOEventsApiError(errorMessage, statusCode);
2854
+ }
2855
+ if (error.status) {
2856
+ const statusCode = error.status;
2857
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2858
+ throw new IOEventsApiError(errorMessage, statusCode);
2859
+ }
2860
+ throw new IOEventsApiError("Network error occurred", 500);
2861
+ }
2862
+ /**
2863
+ * Extracts status code from HTTP error message
2864
+ */
2865
+ extractStatusCodeFromMessage(message) {
2866
+ const match = message.match(/HTTP error! status:\s*(\d+)/);
2867
+ return match ? parseInt(match[1], 10) : 500;
2868
+ }
2869
+ /**
2870
+ * Gets appropriate error message for HTTP status code
2871
+ */
2872
+ getErrorMessageForStatus(statusCode) {
2873
+ switch (statusCode) {
2874
+ case 400:
2875
+ return "Bad request: Invalid registration ID provided";
2876
+ case 401:
2877
+ return "Unauthorized: Invalid or missing authentication";
2878
+ case 403:
2879
+ return "Forbidden: Insufficient permissions";
2880
+ case 404:
2881
+ return "Registration not found";
2882
+ case 500:
2883
+ return "Internal server error";
2884
+ default:
2885
+ return `API error: HTTP ${statusCode}`;
2886
+ }
2887
+ }
2888
+ };
2889
+ __name(_Delete3, "Delete");
2890
+ var Delete3 = _Delete3;
2891
+ var delete_default2 = Delete3;
2892
+
2893
+ // src/io-events/registration/get/index.ts
2894
+ var _Get3 = class _Get3 {
2895
+ /**
2896
+ * Initialize the Get service
2897
+ */
2898
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
2899
+ if (!clientId?.trim()) {
2900
+ throw new IOEventsApiError("clientId is required and cannot be empty", 400);
2901
+ }
2902
+ if (!consumerId?.trim()) {
2903
+ throw new IOEventsApiError("consumerId is required and cannot be empty", 400);
2904
+ }
2905
+ if (!projectId?.trim()) {
2906
+ throw new IOEventsApiError("projectId is required and cannot be empty", 400);
2907
+ }
2908
+ if (!workspaceId?.trim()) {
2909
+ throw new IOEventsApiError("workspaceId is required and cannot be empty", 400);
2910
+ }
2911
+ if (!accessToken?.trim()) {
2912
+ throw new IOEventsApiError("accessToken is required and cannot be empty", 400);
2913
+ }
2914
+ this.restClient = new rest_client_default();
2915
+ this.endpoint = IoEventsGlobals.BASE_URL;
2916
+ this.clientId = clientId;
2917
+ this.consumerId = consumerId;
2918
+ this.projectId = projectId;
2919
+ this.workspaceId = workspaceId;
2920
+ this.accessToken = accessToken;
2921
+ }
2922
+ /**
2923
+ * Get a registration by ID
2924
+ *
2925
+ * @param registrationId - The registration ID to retrieve
2926
+ * @returns Promise<Registration> - The registration data
2927
+ * @throws IOEventsApiError - When the API call fails
2928
+ *
2929
+ * @example
2930
+ * ```typescript
2931
+ * const registration = await registrationManager.get('your-registration-id');
2932
+ * console.log(registration.name);
2933
+ * ```
2934
+ */
2935
+ async execute(registrationId) {
2936
+ try {
2937
+ this.validateInputs(registrationId);
2938
+ const url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations/${registrationId}`;
2939
+ const response = await this.restClient.get(url, {
2940
+ Authorization: `Bearer ${this.accessToken}`,
2941
+ "x-api-key": this.clientId,
2942
+ Accept: "application/hal+json"
2943
+ });
2944
+ return response;
2945
+ } catch (error) {
2946
+ this.handleError(error);
2947
+ }
2948
+ }
2949
+ /**
2950
+ * Validates the input parameters
2951
+ */
2952
+ validateInputs(registrationId) {
2953
+ if (!registrationId?.trim()) {
2954
+ throw new IOEventsApiError("Registration ID is required", 400);
2955
+ }
2956
+ }
2957
+ /**
2958
+ * Handles errors from the API call
2959
+ */
2960
+ handleError(error) {
2961
+ if (error instanceof IOEventsApiError) {
2962
+ throw error;
2963
+ }
2964
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
2965
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
2966
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2967
+ throw new IOEventsApiError(errorMessage, statusCode);
2968
+ }
2969
+ if (error.response?.status) {
2970
+ const statusCode = error.response.status;
2971
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2972
+ throw new IOEventsApiError(errorMessage, statusCode);
2973
+ }
2974
+ if (error.status) {
2975
+ const statusCode = error.status;
2976
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
2977
+ throw new IOEventsApiError(errorMessage, statusCode);
2978
+ }
2979
+ throw new IOEventsApiError("Network error occurred", 500);
2980
+ }
2981
+ /**
2982
+ * Extracts status code from HTTP error message
2983
+ */
2984
+ extractStatusCodeFromMessage(message) {
2985
+ const match = message.match(/HTTP error! status:\s*(\d+)/);
2986
+ return match ? parseInt(match[1], 10) : 500;
2987
+ }
2988
+ /**
2989
+ * Gets appropriate error message for HTTP status code
2990
+ */
2991
+ getErrorMessageForStatus(statusCode) {
2992
+ switch (statusCode) {
2993
+ case 400:
2994
+ return "Bad request: Invalid parameters provided";
2995
+ case 401:
2996
+ return "Unauthorized: Invalid or missing authentication";
2997
+ case 403:
2998
+ return "Forbidden: Insufficient permissions";
2999
+ case 404:
3000
+ return "Registration not found";
3001
+ case 500:
3002
+ return "Internal server error";
3003
+ default:
3004
+ return `API error: HTTP ${statusCode}`;
3005
+ }
3006
+ }
3007
+ };
3008
+ __name(_Get3, "Get");
3009
+ var Get3 = _Get3;
3010
+ var get_default2 = Get3;
3011
+
3012
+ // src/io-events/registration/list/index.ts
3013
+ var _List3 = class _List3 {
3014
+ /**
3015
+ * Initialize the List service
3016
+ */
3017
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
3018
+ if (!clientId?.trim()) {
3019
+ throw new IOEventsApiError("clientId is required and cannot be empty", 400);
3020
+ }
3021
+ if (!consumerId?.trim()) {
3022
+ throw new IOEventsApiError("consumerId is required and cannot be empty", 400);
3023
+ }
3024
+ if (!projectId?.trim()) {
3025
+ throw new IOEventsApiError("projectId is required and cannot be empty", 400);
3026
+ }
3027
+ if (!workspaceId?.trim()) {
3028
+ throw new IOEventsApiError("workspaceId is required and cannot be empty", 400);
3029
+ }
3030
+ if (!accessToken?.trim()) {
3031
+ throw new IOEventsApiError("accessToken is required and cannot be empty", 400);
3032
+ }
3033
+ this.restClient = new rest_client_default();
3034
+ this.endpoint = IoEventsGlobals.BASE_URL;
3035
+ this.clientId = clientId;
3036
+ this.consumerId = consumerId;
3037
+ this.projectId = projectId;
3038
+ this.workspaceId = workspaceId;
3039
+ this.accessToken = accessToken;
3040
+ }
3041
+ /**
3042
+ * Execute registration list with automatic pagination
3043
+ */
3044
+ async execute(queryParams) {
3045
+ try {
3046
+ this.validateInputs();
3047
+ let url = `${this.endpoint}/events/${this.consumerId}/${this.projectId}/${this.workspaceId}/registrations`;
3048
+ if (queryParams && Object.keys(queryParams).length > 0) {
3049
+ const searchParams = new URLSearchParams();
3050
+ Object.entries(queryParams).forEach(([key, value]) => {
3051
+ if (value !== void 0 && value !== null) {
3052
+ searchParams.append(key, String(value));
3053
+ }
3054
+ });
3055
+ if (searchParams.toString()) {
3056
+ url += `?${searchParams.toString()}`;
3057
+ }
3058
+ }
3059
+ return await this.fetchAllPages(url);
3060
+ } catch (error) {
3061
+ this.handleError(error);
3062
+ }
3063
+ }
3064
+ /**
3065
+ * Fetch all pages recursively
3066
+ */
3067
+ async fetchAllPages(url, accumulatedResults = []) {
3068
+ const headers = {
3069
+ Authorization: `Bearer ${this.accessToken}`,
3070
+ "x-api-key": this.clientId,
3071
+ "Content-Type": "application/json"
3072
+ };
3073
+ const data = await this.restClient.get(url, headers);
3074
+ const currentPageRegistrations = data._embedded?.registrations || [];
3075
+ const allResults = [...accumulatedResults, ...currentPageRegistrations];
3076
+ const nextPageUrl = data._links?.next?.href;
3077
+ if (nextPageUrl) {
3078
+ return await this.fetchAllPages(nextPageUrl, allResults);
3079
+ }
3080
+ return allResults;
3081
+ }
3082
+ /**
3083
+ * Validate required inputs
3084
+ */
3085
+ validateInputs() {
3086
+ if (!this.consumerId?.trim()) {
3087
+ throw new IOEventsApiError(
3088
+ "Consumer ID is required",
3089
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST
3090
+ );
3091
+ }
3092
+ if (!this.projectId?.trim()) {
3093
+ throw new IOEventsApiError(
3094
+ "Project ID is required",
3095
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST
3096
+ );
3097
+ }
3098
+ if (!this.workspaceId?.trim()) {
3099
+ throw new IOEventsApiError(
3100
+ "Workspace ID is required",
3101
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST
3102
+ );
3103
+ }
3104
+ if (!this.accessToken?.trim()) {
3105
+ throw new IOEventsApiError(
3106
+ "Access token is required",
3107
+ IoEventsGlobals.STATUS_CODES.BAD_REQUEST
3108
+ );
3109
+ }
3110
+ }
3111
+ /**
3112
+ * Handle and categorize errors
3113
+ */
3114
+ handleError(error) {
3115
+ if (error instanceof Error && error.message.includes("HTTP error! status:")) {
3116
+ const statusCode = this.extractStatusCodeFromMessage(error.message);
3117
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
3118
+ throw new IOEventsApiError(errorMessage, statusCode);
3119
+ }
3120
+ if (error.response) {
3121
+ const statusCode = error.response.status || error.status || IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
3122
+ const errorMessage = this.getErrorMessageForStatus(statusCode);
3123
+ throw new IOEventsApiError(errorMessage, statusCode);
3124
+ }
3125
+ if (error instanceof IOEventsApiError) {
3126
+ throw error;
3127
+ }
3128
+ throw new IOEventsApiError(
3129
+ error.message || "An unexpected error occurred while listing registrations",
3130
+ IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR
3131
+ );
3132
+ }
3133
+ /**
3134
+ * Extract status code from error message
3135
+ */
3136
+ extractStatusCodeFromMessage(errorMessage) {
3137
+ const match = errorMessage.match(/HTTP error! status:\s*(\d+)/);
3138
+ return match ? parseInt(match[1], 10) : IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR;
3139
+ }
3140
+ /**
3141
+ * Get appropriate error message for status code
3142
+ */
3143
+ getErrorMessageForStatus(statusCode) {
3144
+ switch (statusCode) {
3145
+ case IoEventsGlobals.STATUS_CODES.BAD_REQUEST:
3146
+ return "Bad request. Please check your input parameters";
3147
+ case IoEventsGlobals.STATUS_CODES.UNAUTHORIZED:
3148
+ return "Unauthorized. Please check your access token";
3149
+ case IoEventsGlobals.STATUS_CODES.FORBIDDEN:
3150
+ return "Forbidden. You do not have permission to access registrations";
3151
+ case IoEventsGlobals.STATUS_CODES.NOT_FOUND:
3152
+ return "Registrations not found. The specified workspace may not exist or have no registrations";
3153
+ case IoEventsGlobals.STATUS_CODES.INTERNAL_SERVER_ERROR:
3154
+ return "Internal server error. Please try again later";
3155
+ default:
3156
+ return `API request failed with status ${statusCode}`;
3157
+ }
3158
+ }
3159
+ };
3160
+ __name(_List3, "List");
3161
+ var List3 = _List3;
3162
+ var list_default2 = List3;
3163
+
3164
+ // src/io-events/registration/index.ts
3165
+ var _RegistrationManager = class _RegistrationManager {
3166
+ /**
3167
+ * Initialize the RegistrationManager
3168
+ */
3169
+ constructor(clientId, consumerId, projectId, workspaceId, accessToken) {
3170
+ this.createService = new create_default3(clientId, consumerId, projectId, workspaceId, accessToken);
3171
+ this.deleteService = new delete_default2(clientId, consumerId, projectId, workspaceId, accessToken);
3172
+ this.getService = new get_default2(clientId, consumerId, projectId, workspaceId, accessToken);
3173
+ this.listService = new list_default2(clientId, consumerId, projectId, workspaceId, accessToken);
3174
+ }
3175
+ /**
3176
+ * Create a new registration
3177
+ *
3178
+ * @param registrationData - The registration data to create
3179
+ * @returns Promise<Registration> - The created registration
3180
+ *
3181
+ * @example
3182
+ * ```typescript
3183
+ * const registration = await registrationManager.create({
3184
+ * client_id: 'your-client-id',
3185
+ * name: 'My Registration',
3186
+ * description: 'Registration for user events',
3187
+ * webhook_url: 'https://example.com/webhook',
3188
+ * events_of_interest: [
3189
+ * {
3190
+ * provider_id: 'provider-123',
3191
+ * event_code: 'com.example.user.created'
3192
+ * }
3193
+ * ],
3194
+ * delivery_type: 'webhook',
3195
+ * enabled: true
3196
+ * });
3197
+ * console.log(registration.registration_id);
3198
+ * ```
3199
+ */
3200
+ async create(registrationData) {
3201
+ return await this.createService.execute(registrationData);
3202
+ }
3203
+ /**
3204
+ * Delete a registration by ID
3205
+ *
3206
+ * @param registrationId - The registration ID to delete
3207
+ * @returns Promise<void> - Resolves when deletion is successful
3208
+ *
3209
+ * @example
3210
+ * ```typescript
3211
+ * await registrationManager.delete('your-registration-id');
3212
+ * console.log('Registration deleted successfully');
3213
+ * ```
3214
+ */
3215
+ async delete(registrationId) {
3216
+ return await this.deleteService.execute(registrationId);
3217
+ }
3218
+ /**
3219
+ * Get a registration by ID
3220
+ *
3221
+ * @param registrationId - The registration ID to retrieve
3222
+ * @returns Promise<Registration> - The registration data
3223
+ *
3224
+ * @example
3225
+ * ```typescript
3226
+ * const registration = await registrationManager.get('your-registration-id');
3227
+ * console.log(registration.name);
3228
+ * ```
3229
+ */
3230
+ async get(registrationId) {
3231
+ return await this.getService.execute(registrationId);
3232
+ }
3233
+ /**
3234
+ * List all registrations with automatic pagination
3235
+ *
3236
+ * @param queryParams - Optional query parameters for filtering
3237
+ * @returns Promise<Registration[]> - Array of all registrations across all pages
3238
+ *
3239
+ * @example
3240
+ * ```typescript
3241
+ * // List all registrations
3242
+ * const registrations = await registrationManager.list();
3243
+ *
3244
+ * // List with query parameters
3245
+ * const filteredRegistrations = await registrationManager.list({
3246
+ * enabled: true
3247
+ * });
3248
+ * ```
3249
+ */
3250
+ async list(queryParams) {
3251
+ return await this.listService.execute(queryParams);
3252
+ }
3253
+ };
3254
+ __name(_RegistrationManager, "RegistrationManager");
3255
+ var RegistrationManager = _RegistrationManager;
3256
+ var registration_default = RegistrationManager;
3257
+
3258
+ // src/integration/onboard-events/create-providers/index.ts
3259
+ var import_crypto = require("crypto");
3260
+ var _CreateProviders = class _CreateProviders {
3261
+ /**
3262
+ * Creates a new CreateProviders instance
3263
+ *
3264
+ * @param consumerId - Adobe I/O consumer ID
3265
+ * @param projectId - Adobe I/O project ID
3266
+ * @param workspaceId - Adobe I/O workspace ID
3267
+ * @param apiKey - API key for authentication
3268
+ * @param accessToken - Access token for API calls
3269
+ * @param logger - Logger instance for consistent logging
3270
+ */
3271
+ constructor(consumerId, projectId, workspaceId, apiKey, accessToken, logger) {
3272
+ this.consumerId = consumerId;
3273
+ this.projectId = projectId;
3274
+ this.workspaceId = workspaceId;
3275
+ this.apiKey = apiKey;
3276
+ this.accessToken = accessToken;
3277
+ this.providerManager = null;
3278
+ const config = {
3279
+ consumerId: this.consumerId,
3280
+ projectId: this.projectId,
3281
+ workspaceId: this.workspaceId,
3282
+ apiKey: this.apiKey,
3283
+ accessToken: this.accessToken
3284
+ };
3285
+ const required = ["consumerId", "projectId", "workspaceId", "apiKey", "accessToken"];
3286
+ const missing = required.filter(
3287
+ (key) => !config[key] || config[key].trim() === ""
3288
+ );
3289
+ if (missing.length > 0) {
3290
+ throw new Error(`Missing required configuration: ${missing.join(", ")}`);
3291
+ }
3292
+ if (!logger) {
3293
+ throw new Error("Logger is required");
3294
+ }
3295
+ this.logger = logger;
3296
+ this.logger.debug(`[INIT] CreateProviders initialized with valid configuration`);
3297
+ }
3298
+ /**
3299
+ * Processes providers for creation in the Adobe Commerce integration
3300
+ *
3301
+ * @param providers - Array of parsed provider configurations to create
3302
+ * @param projectName - Name of the project for enhanced labeling
3303
+ * @returns Promise resolving to processing result
3304
+ */
3305
+ async process(providers, projectName = "Unknown Project") {
3306
+ this.logger.debug(`[CREATE] Creating providers for project: ${projectName}`);
3307
+ this.logger.debug(`[INFO] Processing ${providers.length} provider(s)...`);
3308
+ try {
3309
+ const existingProviders = await this.getProviders();
3310
+ const results = [];
3311
+ for (const provider of providers) {
3312
+ const result = await this.createProvider(provider, projectName, existingProviders);
3313
+ results.push(result);
3314
+ }
3315
+ this.logger.debug("[DONE] Provider creation completed");
3316
+ results.forEach((result) => {
3317
+ if (result.provider.id) {
3318
+ this.logger.debug(
3319
+ `[ID] Provider ID: ${result.provider.id} (${result.provider.originalLabel})`
3320
+ );
3321
+ }
3322
+ });
3323
+ return results;
3324
+ } catch (error) {
3325
+ this.logger.error(`[ERROR] Provider creation failed: ${error.message}`);
3326
+ throw error;
3327
+ }
3328
+ }
3329
+ /**
3330
+ * Gets the Provider SDK instance from the framework
3331
+ * @private
3332
+ */
3333
+ getProviderManager() {
3334
+ if (!this.providerManager) {
3335
+ this.providerManager = new provider_default(
3336
+ this.apiKey,
3337
+ this.consumerId,
3338
+ this.projectId,
3339
+ this.workspaceId,
3340
+ this.accessToken
3341
+ );
3342
+ }
3343
+ return this.providerManager;
3344
+ }
3345
+ /**
3346
+ * Gets existing providers from Adobe I/O
3347
+ * @returns Promise<Map> Map of existing providers by label
3348
+ */
3349
+ async getProviders() {
3350
+ this.logger.debug("[FETCH] Fetching existing providers...");
3351
+ try {
3352
+ const providerManager = this.getProviderManager();
3353
+ const providerList = await providerManager.list();
3354
+ const existingProviders = /* @__PURE__ */ new Map();
3355
+ providerList.forEach((provider) => {
3356
+ existingProviders.set(provider.label, provider);
3357
+ });
3358
+ this.logger.debug(`[INFO] Found ${existingProviders.size} existing providers`);
3359
+ return existingProviders;
3360
+ } catch (error) {
3361
+ this.logger.error(`[ERROR] Failed to fetch existing providers: ${error.message}`);
3362
+ throw error;
3363
+ }
3364
+ }
3365
+ /**
3366
+ * Creates a single provider
3367
+ * @param providerData - Provider configuration data
3368
+ * @param projectName - Project name for enhanced labeling
3369
+ * @param existingProviders - Map of existing providers by label
3370
+ * @private
3371
+ */
3372
+ async createProvider(providerData, projectName, existingProviders) {
3373
+ const enhancedLabel = `${projectName} - ${providerData.label}`;
3374
+ this.logger.debug(
3375
+ `[PROCESS] Processing provider: ${providerData.label} with enhanced label: ${enhancedLabel}`
3376
+ );
3377
+ const existingProvider = existingProviders.get(enhancedLabel);
3378
+ if (existingProvider) {
3379
+ this.logger.debug(`[SKIP] Provider already exists - skipping creation`);
3380
+ this.logger.debug(`[ID] Existing ID: ${existingProvider.id}`);
3381
+ return {
3382
+ created: false,
3383
+ skipped: true,
3384
+ provider: {
3385
+ id: existingProvider.id,
3386
+ ...existingProvider.instance_id && { instanceId: existingProvider.instance_id },
3387
+ key: providerData.key,
3388
+ label: enhancedLabel,
3389
+ originalLabel: providerData.label,
3390
+ description: providerData.description,
3391
+ docsUrl: providerData.docsUrl
3392
+ },
3393
+ reason: "Already exists",
3394
+ raw: existingProvider
3395
+ };
3396
+ }
3397
+ try {
3398
+ const providerInput = this.preparePayload(providerData, enhancedLabel);
3399
+ this.logger.debug(
3400
+ `[NEW] Creating new provider with payload: ${JSON.stringify(providerInput)}`
3401
+ );
3402
+ const createdProvider = await this.getProviderManager().create(providerInput);
3403
+ this.logger.debug(
3404
+ `[INFO] Provider created successfully! ID: ${createdProvider.id}, Instance ID: ${createdProvider.instance_id}`
3405
+ );
3406
+ const result = {
3407
+ created: true,
3408
+ skipped: false,
3409
+ provider: {
3410
+ id: createdProvider.id,
3411
+ ...createdProvider.instance_id && { instanceId: createdProvider.instance_id },
3412
+ key: providerData.key,
3413
+ label: createdProvider.label,
3414
+ originalLabel: providerData.label,
3415
+ description: providerData.description,
3416
+ docsUrl: providerData.docsUrl
3417
+ },
3418
+ raw: createdProvider
3419
+ };
3420
+ return result;
3421
+ } catch (error) {
3422
+ this.logger.error(`[ERROR] Failed to create provider "${enhancedLabel}": ${error.message}`);
3423
+ return {
3424
+ created: false,
3425
+ skipped: false,
3426
+ error: error.message,
3427
+ provider: {
3428
+ key: providerData.key,
3429
+ label: enhancedLabel,
3430
+ originalLabel: providerData.label,
3431
+ description: providerData.description,
3432
+ docsUrl: providerData.docsUrl
3433
+ }
3434
+ };
3435
+ }
3436
+ }
3437
+ /**
3438
+ * Prepares payload object for Adobe I/O API
3439
+ * @param providerData - Provider configuration data
3440
+ * @param enhancedLabel - Enhanced provider label
3441
+ * @private
3442
+ */
3443
+ preparePayload(providerData, enhancedLabel) {
3444
+ const input = {
3445
+ label: enhancedLabel
3446
+ };
3447
+ if (providerData.description) {
3448
+ input.description = providerData.description;
3449
+ }
3450
+ if (providerData.docsUrl) {
3451
+ input.docs_url = providerData.docsUrl;
3452
+ }
3453
+ if (this.isCommerceProvider(providerData)) {
3454
+ input.provider_metadata = "dx_commerce_events";
3455
+ input.instance_id = (0, import_crypto.randomUUID)();
3456
+ }
3457
+ return input;
3458
+ }
3459
+ /**
3460
+ * Determines if provider is a commerce provider
3461
+ * @private
3462
+ */
3463
+ isCommerceProvider(providerData) {
3464
+ const commerceIndicators = ["commerce", "magento", "adobe commerce"];
3465
+ const key = providerData.key.toLowerCase();
3466
+ const label = providerData.label.toLowerCase();
3467
+ const description = (providerData.description || "").toLowerCase();
3468
+ return commerceIndicators.some(
3469
+ (indicator) => key.includes(indicator) || label.includes(indicator) || description.includes(indicator)
3470
+ );
3471
+ }
3472
+ };
3473
+ __name(_CreateProviders, "CreateProviders");
3474
+ var CreateProviders = _CreateProviders;
3475
+ var create_providers_default = CreateProviders;
3476
+
3477
+ // src/integration/onboard-events/create-events/index.ts
3478
+ var _CreateEvents = class _CreateEvents {
3479
+ /**
3480
+ * Creates a new CreateEvents instance
3481
+ *
3482
+ * @param consumerId - Adobe I/O consumer ID
3483
+ * @param projectId - Adobe I/O project ID
3484
+ * @param workspaceId - Adobe I/O workspace ID
3485
+ * @param clientId - Adobe I/O client ID
3486
+ * @param accessToken - Adobe I/O access token
3487
+ * @param logger - Logger instance for consistent logging
3488
+ */
3489
+ constructor(consumerId, projectId, workspaceId, clientId, accessToken, logger) {
3490
+ this.consumerId = consumerId;
3491
+ this.projectId = projectId;
3492
+ this.workspaceId = workspaceId;
3493
+ this.clientId = clientId;
3494
+ this.accessToken = accessToken;
3495
+ this.eventMetadataManager = null;
3496
+ const config = {
3497
+ consumerId: this.consumerId,
3498
+ projectId: this.projectId,
3499
+ workspaceId: this.workspaceId,
3500
+ clientId: this.clientId,
3501
+ accessToken: this.accessToken
3502
+ };
3503
+ const required = ["consumerId", "projectId", "workspaceId", "clientId", "accessToken"];
3504
+ const missing = required.filter(
3505
+ (key) => !config[key] || config[key].trim() === ""
3506
+ );
3507
+ if (missing.length > 0) {
3508
+ throw new Error(`Missing required configuration: ${missing.join(", ")}`);
3509
+ }
3510
+ if (!logger) {
3511
+ throw new Error("Logger is required");
3512
+ }
3513
+ this.logger = logger;
3514
+ this.logger.debug(`[INIT] CreateEvents initialized with valid configuration`);
3515
+ }
3516
+ /**
3517
+ * Gets the EventMetadataManager instance (lazy initialization)
3518
+ * @private
3519
+ * @returns EventMetadataManager instance
3520
+ */
3521
+ getEventMetadataManager() {
3522
+ if (!this.eventMetadataManager) {
3523
+ this.eventMetadataManager = new event_metadata_default(
3524
+ this.clientId,
3525
+ this.consumerId,
3526
+ this.projectId,
3527
+ this.workspaceId,
3528
+ this.accessToken
3529
+ );
3530
+ }
3531
+ return this.eventMetadataManager;
3532
+ }
3533
+ /**
3534
+ * Creates event metadata for a specific provider
3535
+ * @private
3536
+ * @param providerId - Provider ID to create event for
3537
+ * @param event - Parsed event data
3538
+ * @param existingEvents - Array of existing event metadata
3539
+ * @returns Promise<CreateEventResult> - Event creation result
3540
+ */
3541
+ async createEvent(providerId, event, existingEvents) {
3542
+ try {
3543
+ const eventCode = event.eventCode;
3544
+ this.logger.debug(`[INFO] Processing event: ${eventCode}`);
3545
+ const existingEvent = existingEvents.find((metadata) => metadata.event_code === eventCode);
3546
+ if (existingEvent) {
3547
+ this.logger.debug(
3548
+ `[INFO] Event code '${eventCode}' already exists for provider ${providerId}`
3549
+ );
3550
+ this.logger.debug(`[SKIP] Event metadata already exists for: ${eventCode} - skipping`);
3551
+ return {
3552
+ created: false,
3553
+ skipped: true,
3554
+ event: {
3555
+ id: existingEvent.id,
3556
+ eventCode,
3557
+ ...existingEvent.label && { label: existingEvent.label },
3558
+ ...existingEvent.description && { description: existingEvent.description },
3559
+ ...existingEvent.sample_event_template && {
3560
+ sampleEventTemplate: existingEvent.sample_event_template
3561
+ }
3562
+ },
3563
+ raw: existingEvent
3564
+ };
3565
+ }
3566
+ this.logger.debug(`[CREATE] Creating event metadata: ${eventCode}`);
3567
+ const metadataPayload = {
3568
+ event_code: eventCode,
3569
+ label: eventCode,
3570
+ description: eventCode,
3571
+ ...event.sampleEventTemplate ? { sample_event_template: event.sampleEventTemplate } : {}
3572
+ };
3573
+ const eventMetadata = this.getEventMetadataManager();
3574
+ const result = await eventMetadata.create(providerId, metadataPayload);
3575
+ if (result) {
3576
+ const eventId = result.id || result.event_code || eventCode;
3577
+ this.logger.debug(`[SUCCESS] Event metadata created successfully: ${eventCode}`);
3578
+ return {
3579
+ created: true,
3580
+ skipped: false,
3581
+ event: {
3582
+ id: eventId,
3583
+ eventCode,
3584
+ label: metadataPayload.label,
3585
+ description: metadataPayload.description,
3586
+ ...metadataPayload.sample_event_template && {
3587
+ sampleEventTemplate: metadataPayload.sample_event_template
3588
+ }
3589
+ },
3590
+ raw: result
3591
+ };
3592
+ } else {
3593
+ throw new Error("Event metadata creation returned no result");
3594
+ }
3595
+ } catch (error) {
3596
+ const eventCode = event.eventCode;
3597
+ this.logger.error(
3598
+ `[ERROR] Error creating event metadata for ${eventCode}: ${error.message}`
3599
+ );
3600
+ return {
3601
+ created: false,
3602
+ skipped: false,
3603
+ event: {
3604
+ eventCode
3605
+ },
3606
+ error: error.message
3607
+ };
3608
+ }
3609
+ }
3610
+ /**
3611
+ * Fetches existing event metadata for a provider to avoid duplicates
3612
+ * @private
3613
+ * @param providerId - Provider ID to fetch metadata for
3614
+ * @returns Promise<EventMetadata[]> - List of existing event metadata
3615
+ */
3616
+ async fetchMetadata(providerId) {
3617
+ try {
3618
+ this.logger.debug(`[INFO] Fetching existing event metadata for provider: ${providerId}`);
3619
+ const eventMetadata = this.getEventMetadataManager();
3620
+ const existingList = await eventMetadata.list(providerId);
3621
+ this.logger.debug(`[INFO] Found ${existingList.length} existing event metadata entries`);
3622
+ return existingList;
3623
+ } catch (error) {
3624
+ this.logger.error(
3625
+ `[ERROR] Error fetching existing metadata for provider ${providerId}: ${error.message}`
3626
+ );
3627
+ return [];
3628
+ }
3629
+ }
3630
+ /**
3631
+ * Processes events for creation based on parsed events and provider results
3632
+ *
3633
+ * @param events - Array of parsed events from InputParser
3634
+ * @param providerResults - Array of provider creation results
3635
+ * @param projectName - Name of the project for enhanced labeling
3636
+ * @returns Promise resolving to event creation results
3637
+ */
3638
+ async process(events, providerResults, projectName = "Unknown Project") {
3639
+ this.logger.debug(`[CREATE] Creating events for project: ${projectName}`);
3640
+ this.logger.debug(
3641
+ `[INFO] Processing ${events.length} event(s) across ${providerResults.length} provider(s)...`
3642
+ );
3643
+ if (!events || events.length === 0) {
3644
+ this.logger.debug("[INFO] No events to process.");
3645
+ return [];
3646
+ }
3647
+ if (!providerResults || providerResults.length === 0) {
3648
+ this.logger.debug("[INFO] No provider results to process.");
3649
+ return [];
3650
+ }
3651
+ try {
3652
+ const results = [];
3653
+ for (const providerResult of providerResults) {
3654
+ const providerId = providerResult.provider.id;
3655
+ if (!providerId) {
3656
+ this.logger.debug(
3657
+ `[WARN] Skipping provider without ID: ${providerResult.provider.originalLabel}`
3658
+ );
3659
+ continue;
3660
+ }
3661
+ this.logger.debug(
3662
+ `[INFO] Processing events for provider: ${providerResult.provider.originalLabel}`
3663
+ );
3664
+ const existingEvents = await this.fetchMetadata(providerId);
3665
+ const providerEvents = events.filter(
3666
+ (event) => event.providerKey === providerResult.provider.key
3667
+ );
3668
+ if (providerEvents.length === 0) {
3669
+ this.logger.debug(
3670
+ `[INFO] No events found for provider: ${providerResult.provider.originalLabel}`
3671
+ );
3672
+ continue;
3673
+ }
3674
+ this.logger.debug(`[INFO] Found ${providerEvents.length} event(s) for this provider`);
3675
+ for (const event of providerEvents) {
3676
+ const eventResult = await this.createEvent(providerId, event, existingEvents);
3677
+ eventResult.provider = providerResult.provider;
3678
+ results.push(eventResult);
3679
+ }
3680
+ }
3681
+ return results;
3682
+ } catch (error) {
3683
+ this.logger.error(`[ERROR] Event metadata creation failed: ${error.message}`);
3684
+ throw error;
3685
+ }
3686
+ }
3687
+ };
3688
+ __name(_CreateEvents, "CreateEvents");
3689
+ var CreateEvents = _CreateEvents;
3690
+ var create_events_default = CreateEvents;
3691
+
3692
+ // src/integration/onboard-events/create-registrations/index.ts
3693
+ var _CreateRegistrations = class _CreateRegistrations {
3694
+ /**
3695
+ * Creates a new CreateRegistrations instance
3696
+ *
3697
+ * @param consumerId - Adobe I/O consumer ID
3698
+ * @param projectId - Adobe I/O project ID
3699
+ * @param workspaceId - Adobe I/O workspace ID
3700
+ * @param clientId - Adobe I/O client ID
3701
+ * @param accessToken - Adobe I/O access token
3702
+ * @param logger - Logger instance for consistent logging
3703
+ */
3704
+ constructor(consumerId, projectId, workspaceId, clientId, accessToken, logger) {
3705
+ this.consumerId = consumerId;
3706
+ this.projectId = projectId;
3707
+ this.workspaceId = workspaceId;
3708
+ this.clientId = clientId;
3709
+ this.accessToken = accessToken;
3710
+ const config = {
3711
+ consumerId: this.consumerId,
3712
+ projectId: this.projectId,
3713
+ workspaceId: this.workspaceId,
3714
+ clientId: this.clientId,
3715
+ accessToken: this.accessToken
3716
+ };
3717
+ const required = ["consumerId", "projectId", "workspaceId", "clientId", "accessToken"];
3718
+ const missing = required.filter(
3719
+ (key) => !config[key] || config[key].trim() === ""
3720
+ );
3721
+ if (missing.length > 0) {
3722
+ throw new Error(`Missing required configuration: ${missing.join(", ")}`);
3723
+ }
3724
+ if (!logger) {
3725
+ throw new Error("Logger is required");
3726
+ }
3727
+ this.logger = logger;
3728
+ this.logger.debug(`[INIT] CreateRegistrations initialized with valid configuration`);
3729
+ }
3730
+ /**
3731
+ * Process multiple registrations for creation
3732
+ *
3733
+ * @param registrations - Array of parsed registrations to process
3734
+ * @param events - Array of parsed events for registration creation
3735
+ * @param providerResults - Array of provider results to link registrations to
3736
+ * @param projectName - Optional project name for logging
3737
+ * @returns Promise resolving to array of registration creation results
3738
+ */
3739
+ async process(registrations, events, providerResults, projectName = "Unknown Project") {
3740
+ this.logger.debug(`[INFO] Creating registrations for project: ${projectName}`);
3741
+ this.logger.debug(
3742
+ `[PROCESSING] Processing ${registrations.length} registration(s) with ${events.length} event(s) across ${providerResults.length} provider(s)...`
3743
+ );
3744
+ if (!registrations || registrations.length === 0) {
3745
+ this.logger.debug("[SKIP] No registrations to process.");
3746
+ return [];
3747
+ }
3748
+ if (!events || events.length === 0) {
3749
+ this.logger.debug("[SKIP] No events to process.");
3750
+ return [];
3751
+ }
3752
+ if (!providerResults || providerResults.length === 0) {
3753
+ this.logger.debug("[SKIP] No provider results to process.");
3754
+ return [];
3755
+ }
3756
+ try {
3757
+ const existingRegistrations = await this.fetchRegistrations();
3758
+ const results = [];
3759
+ for (const registration of registrations) {
3760
+ this.logger.debug(`[PROCESSING] Processing registration: ${registration.label}`);
3761
+ const registrationEvents = events.filter(
3762
+ (event) => event.registrationKey === registration.key
3763
+ );
3764
+ if (registrationEvents.length === 0) {
3765
+ this.logger.debug(`[SKIP] No events found for registration: ${registration.label}`);
3766
+ continue;
3767
+ }
3768
+ this.logger.debug(
3769
+ `[INFO] Found ${registrationEvents.length} event(s) for this registration`
3770
+ );
3771
+ const eventsByProvider = this.groupEventsByProvider(registrationEvents);
3772
+ for (const [providerKey, providerEvents] of Object.entries(eventsByProvider)) {
3773
+ const provider = providerResults.find((p) => p.provider.key === providerKey);
3774
+ if (!provider || !provider.provider.id) {
3775
+ this.logger.debug(`[SKIP] Provider not found or missing ID for: ${providerKey}`);
3776
+ continue;
3777
+ }
3778
+ const result = await this.createRegistration(
3779
+ registration,
3780
+ providerEvents,
3781
+ provider,
3782
+ existingRegistrations
3783
+ );
3784
+ results.push(result);
3785
+ }
3786
+ }
3787
+ return results;
3788
+ } catch (error) {
3789
+ this.logger.error(`[ERROR] Registration creation failed: ${error.message}`);
3790
+ throw error;
3791
+ }
3792
+ }
3793
+ /**
3794
+ * Lazy initialization of RegistrationManager
3795
+ * @private
3796
+ * @returns RegistrationManager instance
3797
+ */
3798
+ getRegistrationManager() {
3799
+ if (!this.registrationManager) {
3800
+ this.registrationManager = new RegistrationManager(
3801
+ this.clientId,
3802
+ this.consumerId,
3803
+ this.projectId,
3804
+ this.workspaceId,
3805
+ this.accessToken
3806
+ );
3807
+ }
3808
+ return this.registrationManager;
3809
+ }
3810
+ /**
3811
+ * Fetches existing registrations to avoid duplicates
3812
+ * @returns {Promise<Map>} Map of existing registrations by name
3813
+ */
3814
+ async fetchRegistrations() {
3815
+ this.logger.debug("[INFO] Fetching existing registrations...");
3816
+ try {
3817
+ const registrationSDK = this.getRegistrationManager();
3818
+ const registrationList = await registrationSDK.list();
3819
+ const existingRegistrations = /* @__PURE__ */ new Map();
3820
+ registrationList.forEach((registration) => {
3821
+ existingRegistrations.set(registration.name, registration);
3822
+ });
3823
+ this.logger.debug(`[INFO] Found ${existingRegistrations.size} existing registrations`);
3824
+ return existingRegistrations;
3825
+ } catch (error) {
3826
+ this.logger.error(
3827
+ `[ERROR] Failed to fetch existing registrations: ${error.message}`
3828
+ );
3829
+ throw error;
3830
+ }
3831
+ }
3832
+ /**
3833
+ * Groups events by their provider key
3834
+ * @private
3835
+ * @param events - Events to group
3836
+ * @returns Events grouped by provider key
3837
+ */
3838
+ groupEventsByProvider(events) {
3839
+ const grouped = {};
3840
+ events.forEach((event) => {
3841
+ if (!grouped[event.providerKey]) {
3842
+ grouped[event.providerKey] = [];
3843
+ }
3844
+ grouped[event.providerKey].push(event);
3845
+ });
3846
+ return grouped;
3847
+ }
3848
+ /**
3849
+ * Builds registration input object for Adobe I/O API
3850
+ * @private
3851
+ * @param registration - Registration entity
3852
+ * @param events - Events for this registration
3853
+ * @param provider - Provider result
3854
+ * @param registrationName - Enhanced registration name
3855
+ * @param firstEvent - First event for common properties
3856
+ * @returns Registration input for API
3857
+ */
3858
+ preparePayload(registration, events, provider, registrationName, firstEvent) {
3859
+ const eventsOfInterest = events.map((event) => ({
3860
+ provider_id: provider.provider.id || "",
3861
+ event_code: event.eventCode
3862
+ }));
3863
+ const input = {
3864
+ client_id: this.clientId,
3865
+ name: registrationName,
3866
+ description: registration.description || registrationName,
3867
+ delivery_type: firstEvent.deliveryType || "webhook",
3868
+ events_of_interest: eventsOfInterest,
3869
+ ...firstEvent.runtimeAction && { runtime_action: firstEvent.runtimeAction }
3870
+ };
3871
+ return input;
3872
+ }
3873
+ /**
3874
+ * Creates a single registration for a provider and its events
3875
+ * @private
3876
+ * @param registrationData - Registration entity
3877
+ * @param events - Events for this registration
3878
+ * @param provider - Provider result
3879
+ * @param existingRegistrations - Map of existing registrations
3880
+ * @returns Registration creation result
3881
+ */
3882
+ async createRegistration(registrationData, events, provider, existingRegistrations) {
3883
+ const firstEvent = events[0];
3884
+ if (!firstEvent) {
3885
+ throw new Error("No events provided for registration creation");
3886
+ }
3887
+ const registrationName = registrationData.label;
3888
+ this.logger.debug(
3889
+ `[PROCESSING] Processing registration: ${registrationData.label} for provider: ${provider.provider.originalLabel}`
3890
+ );
3891
+ this.logger.debug(`[INFO] Registration name: ${registrationName}`);
3892
+ const existingRegistration = existingRegistrations.get(registrationName);
3893
+ if (existingRegistration) {
3894
+ this.logger.debug("[SKIP] Registration already exists - skipping creation");
3895
+ this.logger.debug(`[INFO] Existing ID: ${existingRegistration.id}`);
3896
+ return {
3897
+ created: false,
3898
+ skipped: true,
3899
+ registration: {
3900
+ id: existingRegistration.id,
3901
+ key: registrationData.key,
3902
+ label: registrationData.label,
3903
+ originalLabel: registrationData.label,
3904
+ name: registrationName,
3905
+ description: registrationData.description
3906
+ },
3907
+ reason: "Already exists",
3908
+ raw: existingRegistration
3909
+ };
3910
+ }
3911
+ this.logger.debug("[CREATE] Creating new registration...");
3912
+ try {
3913
+ const registrationInput = this.preparePayload(
3914
+ registrationData,
3915
+ events,
3916
+ provider,
3917
+ registrationName,
3918
+ firstEvent
3919
+ );
3920
+ this.logger.debug(`[INFO] Registration input: ${JSON.stringify(registrationInput, null, 2)}`);
3921
+ const registrationSDK = this.getRegistrationManager();
3922
+ const createdRegistration = await registrationSDK.create(registrationInput);
3923
+ this.logger.debug("[SUCCESS] Registration created successfully!");
3924
+ this.logger.debug(`[INFO] New ID: ${createdRegistration.id}`);
3925
+ this.logger.debug(`[INFO] Registration ID: ${createdRegistration.registration_id}`);
3926
+ const result = {
3927
+ created: true,
3928
+ skipped: false,
3929
+ registration: {
3930
+ id: createdRegistration.id,
3931
+ key: registrationData.key,
3932
+ label: registrationData.label,
3933
+ originalLabel: registrationData.label,
3934
+ name: createdRegistration.name,
3935
+ description: registrationData.description
3936
+ },
3937
+ provider: provider.provider,
3938
+ raw: createdRegistration
3939
+ };
3940
+ return result;
3941
+ } catch (error) {
3942
+ this.logger.error(
3943
+ `[ERROR] Failed to create registration "${registrationName}": ${error.message}`
3944
+ );
3945
+ return {
3946
+ created: false,
3947
+ skipped: false,
3948
+ error: error.message,
3949
+ registration: {
3950
+ key: registrationData.key,
3951
+ label: registrationData.label,
3952
+ originalLabel: registrationData.label,
3953
+ name: registrationName,
3954
+ description: registrationData.description
3955
+ },
3956
+ provider: provider.provider
3957
+ };
3958
+ }
3959
+ }
3960
+ };
3961
+ __name(_CreateRegistrations, "CreateRegistrations");
3962
+ var CreateRegistrations = _CreateRegistrations;
3963
+ var create_registrations_default = CreateRegistrations;
3964
+
3965
+ // src/integration/onboard-events/input-parser/index.ts
3966
+ var _InputParser = class _InputParser {
3967
+ constructor(input) {
3968
+ this.entities = {
3969
+ providers: [],
3970
+ registrations: [],
3971
+ events: []
3972
+ };
3973
+ for (const provider of input.providers) {
3974
+ this.entities.providers.push(this.createProviderEntity(provider));
3975
+ for (const registration of provider.registrations) {
3976
+ this.entities.registrations.push(this.createRegistrationEntity(registration, provider.key));
3977
+ for (const event of registration.events) {
3978
+ this.entities.events.push(this.createEventEntity(event, registration.key, provider.key));
3979
+ }
3980
+ }
3981
+ }
3982
+ }
3983
+ /**
3984
+ * Create provider entity structure
3985
+ */
3986
+ createProviderEntity(provider) {
3987
+ return {
3988
+ key: provider.key,
3989
+ label: provider.label,
3990
+ description: provider.description,
3991
+ docsUrl: provider.docsUrl
3992
+ };
3993
+ }
3994
+ /**
3995
+ * Create registration entity structure
3996
+ */
3997
+ createRegistrationEntity(registration, providerKey) {
3998
+ return {
3999
+ key: registration.key,
4000
+ label: registration.label,
4001
+ description: registration.description,
4002
+ providerKey
4003
+ };
4004
+ }
4005
+ /**
4006
+ * Create event entity structure
4007
+ */
4008
+ createEventEntity(event, registrationKey, providerKey) {
4009
+ return {
4010
+ eventCode: event.eventCode,
4011
+ runtimeAction: event.runtimeAction,
4012
+ deliveryType: event.deliveryType,
4013
+ sampleEventTemplate: event.sampleEventTemplate,
4014
+ registrationKey,
4015
+ providerKey
4016
+ };
4017
+ }
4018
+ getEntities() {
4019
+ return this.entities;
4020
+ }
4021
+ };
4022
+ __name(_InputParser, "InputParser");
4023
+ var InputParser = _InputParser;
4024
+ var input_parser_default = InputParser;
4025
+
4026
+ // src/integration/onboard-events/index.ts
4027
+ var _OnboardEvents = class _OnboardEvents {
4028
+ /**
4029
+ * Creates a new OnboardEvents instance
4030
+ *
4031
+ * @param projectName - Name of the Adobe Commerce project
4032
+ * @param consumerId - Adobe I/O consumer ID
4033
+ * @param projectId - Adobe I/O project ID
4034
+ * @param workspaceId - Adobe I/O workspace ID
4035
+ * @param apiKey - API key for authentication
4036
+ * @param accessToken - Access token for API calls
4037
+ */
4038
+ constructor(projectName, consumerId, projectId, workspaceId, apiKey, accessToken) {
4039
+ this.projectName = projectName;
4040
+ this.consumerId = consumerId;
4041
+ this.projectId = projectId;
4042
+ this.workspaceId = workspaceId;
4043
+ this.apiKey = apiKey;
4044
+ this.accessToken = accessToken;
4045
+ if (!projectName) {
4046
+ throw new Error("Project name is required");
4047
+ }
4048
+ if (!consumerId) {
4049
+ throw new Error("Consumer ID is required");
4050
+ }
4051
+ if (!projectId) {
4052
+ throw new Error("Project ID is required");
4053
+ }
4054
+ if (!workspaceId) {
4055
+ throw new Error("Workspace ID is required");
4056
+ }
4057
+ if (!apiKey) {
4058
+ throw new Error("API key is required");
4059
+ }
4060
+ if (!accessToken) {
4061
+ throw new Error("Access token is required");
4062
+ }
4063
+ const loggerName = projectName.toLowerCase().replace(/[^a-z0-9\s-_]/g, "").replace(/\s+/g, "-").replace(/_{2,}/g, "_").replace(/-{2,}/g, "-").trim().concat("-onboard-events");
4064
+ this.logger = import_aio_sdk5.Core.Logger(loggerName, { level: "debug" });
4065
+ this.createProviders = new create_providers_default(
4066
+ consumerId,
4067
+ projectId,
4068
+ workspaceId,
4069
+ apiKey,
4070
+ accessToken,
4071
+ this.logger
4072
+ );
4073
+ this.createEvents = new create_events_default(
4074
+ consumerId,
4075
+ projectId,
4076
+ workspaceId,
4077
+ apiKey,
4078
+ // Using apiKey as clientId
4079
+ accessToken,
4080
+ this.logger
4081
+ );
4082
+ this.createRegistrations = new create_registrations_default(
4083
+ consumerId,
4084
+ projectId,
4085
+ workspaceId,
4086
+ apiKey,
4087
+ // Using apiKey as clientId
4088
+ accessToken,
4089
+ this.logger
4090
+ );
4091
+ }
4092
+ /**
4093
+ * Gets the configured logger instance for consistent logging
4094
+ *
4095
+ * @returns The configured logger instance
4096
+ */
4097
+ getLogger() {
4098
+ return this.logger;
4099
+ }
4100
+ /**
4101
+ * Processes the onboarding events
4102
+ *
4103
+ * @param input - Onboard events input configuration containing providers, registrations, and events
4104
+ * @returns Promise resolving to processing result with created providers
4105
+ */
4106
+ async process(input) {
4107
+ this.logger.debug(
4108
+ `[START] Processing onboard events for project: ${this.projectName} (${this.projectId}) with ${input.providers.length} providers`
4109
+ );
4110
+ const inputParser = new input_parser_default(input);
4111
+ const entities = inputParser.getEntities();
4112
+ const providerResults = await this.createProviders.process(
4113
+ entities.providers,
4114
+ this.projectName
4115
+ );
4116
+ const eventResults = await this.createEvents.process(
4117
+ entities.events,
4118
+ providerResults,
4119
+ this.projectName
4120
+ );
4121
+ const registrationResults = await this.createRegistrations.process(
4122
+ entities.registrations,
4123
+ entities.events,
4124
+ providerResults,
4125
+ this.projectName
4126
+ );
4127
+ const response = {
4128
+ createdProviders: providerResults,
4129
+ createdEvents: eventResults,
4130
+ createdRegistrations: registrationResults
4131
+ };
4132
+ const summary = this.generateSummary(response);
4133
+ this.logSummary(summary);
4134
+ return response;
4135
+ }
4136
+ /**
4137
+ * Generates a concise summary of onboard events processing results
4138
+ * @private
4139
+ * @param response - The response from the onboard events processing
4140
+ * @returns A concise summary with IDs and status information
4141
+ */
4142
+ generateSummary(response) {
4143
+ const providerItems = response.createdProviders.map((result) => ({
4144
+ id: result.provider.id,
4145
+ key: result.provider.key,
4146
+ label: result.provider.label,
4147
+ status: result.created ? "created" : result.skipped ? "existing" : "failed",
4148
+ error: result.error
4149
+ }));
4150
+ const providerCounts = {
4151
+ created: response.createdProviders.filter((r) => r.created).length,
4152
+ existing: response.createdProviders.filter((r) => r.skipped).length,
4153
+ failed: response.createdProviders.filter((r) => !r.created && !r.skipped).length,
4154
+ total: response.createdProviders.length
4155
+ };
4156
+ const eventItems = response.createdEvents.map((result) => ({
4157
+ id: result.event.id,
4158
+ eventCode: result.event.eventCode,
4159
+ label: result.event.eventCode,
4160
+ status: result.created ? "created" : result.skipped ? "existing" : "failed",
4161
+ provider: result.provider?.key,
4162
+ error: result.error
4163
+ }));
4164
+ const eventCounts = {
4165
+ created: response.createdEvents.filter((r) => r.created).length,
4166
+ existing: response.createdEvents.filter((r) => r.skipped).length,
4167
+ failed: response.createdEvents.filter((r) => !r.created && !r.skipped).length,
4168
+ total: response.createdEvents.length
4169
+ };
4170
+ const registrationItems = response.createdRegistrations.map((result) => ({
4171
+ id: result.registration.id,
4172
+ key: result.registration.key,
4173
+ label: result.registration.label,
4174
+ status: result.created ? "created" : result.skipped ? "existing" : "failed",
4175
+ provider: result.provider?.key,
4176
+ error: result.error
4177
+ }));
4178
+ const registrationCounts = {
4179
+ created: response.createdRegistrations.filter((r) => r.created).length,
4180
+ existing: response.createdRegistrations.filter((r) => r.skipped).length,
4181
+ failed: response.createdRegistrations.filter((r) => !r.created && !r.skipped).length,
4182
+ total: response.createdRegistrations.length
4183
+ };
4184
+ const overall = {
4185
+ totalProcessed: providerCounts.total + eventCounts.total + registrationCounts.total,
4186
+ totalCreated: providerCounts.created + eventCounts.created + registrationCounts.created,
4187
+ totalExisting: providerCounts.existing + eventCounts.existing + registrationCounts.existing,
4188
+ totalFailed: providerCounts.failed + eventCounts.failed + registrationCounts.failed
4189
+ };
4190
+ return {
4191
+ providers: {
4192
+ items: providerItems,
4193
+ counts: providerCounts
4194
+ },
4195
+ events: {
4196
+ items: eventItems,
4197
+ counts: eventCounts
4198
+ },
4199
+ registrations: {
4200
+ items: registrationItems,
4201
+ counts: registrationCounts
4202
+ },
4203
+ overall
4204
+ };
4205
+ }
4206
+ /**
4207
+ * Logs a formatted summary of onboard events processing results
4208
+ * @private
4209
+ * @param summary - The summary to log
4210
+ */
4211
+ logSummary(summary) {
4212
+ this.logger.info("=".repeat(60));
4213
+ this.logger.info(`\u{1F4CA} ONBOARD EVENTS SUMMARY - ${this.projectName}`);
4214
+ this.logger.info("=".repeat(60));
4215
+ this.logger.info("");
4216
+ this.logger.info(
4217
+ `\u{1F4C8} OVERALL: ${summary.overall.totalProcessed} processed | ${summary.overall.totalCreated} created | ${summary.overall.totalExisting} existing | ${summary.overall.totalFailed} failed`
4218
+ );
4219
+ this.logger.info("");
4220
+ if (summary.providers.counts.total > 0) {
4221
+ this.logger.info(`\u{1F3ED} PROVIDERS (${summary.providers.counts.total}):`);
4222
+ summary.providers.items.forEach((item) => {
4223
+ const status = item.status === "created" ? "\u2705" : item.status === "existing" ? "\u23ED\uFE0F" : "\u274C";
4224
+ const id = item.id ? ` [ID: ${item.id}]` : "";
4225
+ const error = item.error ? ` - Error: ${item.error}` : "";
4226
+ this.logger.info(` ${status} ${item.key} - ${item.label}${id}${error}`);
4227
+ });
4228
+ this.logger.info("");
4229
+ }
4230
+ if (summary.events.counts.total > 0) {
4231
+ this.logger.info(`\u{1F4C5} EVENTS (${summary.events.counts.total}):`);
4232
+ summary.events.items.forEach((item) => {
4233
+ const status = item.status === "created" ? "\u2705" : item.status === "existing" ? "\u23ED\uFE0F" : "\u274C";
4234
+ const id = item.id ? ` [ID: ${item.id}]` : "";
4235
+ const provider = item.provider ? ` (Provider: ${item.provider})` : "";
4236
+ const error = item.error ? ` - Error: ${item.error}` : "";
4237
+ this.logger.info(` ${status} ${item.eventCode}${provider}${id}${error}`);
4238
+ });
4239
+ this.logger.info("");
4240
+ }
4241
+ if (summary.registrations.counts.total > 0) {
4242
+ this.logger.info(`\u{1F4CB} REGISTRATIONS (${summary.registrations.counts.total}):`);
4243
+ summary.registrations.items.forEach((item) => {
4244
+ const status = item.status === "created" ? "\u2705" : item.status === "existing" ? "\u23ED\uFE0F" : "\u274C";
4245
+ const id = item.id ? ` [ID: ${item.id}]` : "";
4246
+ const provider = item.provider ? ` (Provider: ${item.provider})` : "";
4247
+ const error = item.error ? ` - Error: ${item.error}` : "";
4248
+ this.logger.info(` ${status} ${item.key} - ${item.label}${provider}${id}${error}`);
4249
+ });
4250
+ this.logger.info("");
4251
+ }
4252
+ this.logger.info("=".repeat(60));
4253
+ }
4254
+ };
4255
+ __name(_OnboardEvents, "OnboardEvents");
4256
+ var OnboardEvents = _OnboardEvents;
4257
+ var onboard_events_default = OnboardEvents;
4258
+
4259
+ // src/integration/infinite-loop-breaker/index.ts
4260
+ var import_aio_sdk6 = require("@adobe/aio-sdk");
4261
+ var import_crypto2 = __toESM(require("crypto"));
4262
+ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
4263
+ // seconds
4264
+ /**
4265
+ * This function checks if there is a potential infinite loop
4266
+ *
4267
+ * @param state - The state object
4268
+ * @param infiniteLoopData - The event data containing the key and fingerprint functions, event types, and event name
4269
+ * @returns Returns true if the event is a potential infinite loop
4270
+ */
4271
+ static async isInfiniteLoop({
4272
+ keyFn,
4273
+ fingerprintFn,
4274
+ eventTypes,
4275
+ event
4276
+ }) {
4277
+ const logLevel = process.env.LOG_LEVEL || "info";
4278
+ const logger = import_aio_sdk6.Core.Logger("infiniteLoopBreaker", { level: logLevel });
4279
+ logger.debug(`Checking for potential infinite loop for event: ${event}`);
4280
+ if (!eventTypes.includes(event)) {
4281
+ logger.debug(`Event type ${event} is not in the infinite loop event types list`);
4282
+ return false;
4283
+ }
4284
+ const key = typeof keyFn === "function" ? keyFn() : keyFn;
4285
+ const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
4286
+ const state = await import_aio_sdk6.State.init();
4287
+ const persistedFingerPrint = await state.get(key);
4288
+ if (!persistedFingerPrint) {
4289
+ logger.debug(`No persisted fingerprint found for key ${key}`);
4290
+ return false;
4291
+ }
4292
+ logger.debug(
4293
+ `Persisted fingerprint found for key ${key}: ${persistedFingerPrint.value}, Generated fingerprint: ${_InfiniteLoopBreaker.fingerPrint(data)}`
4294
+ );
4295
+ return persistedFingerPrint && persistedFingerPrint.value === _InfiniteLoopBreaker.fingerPrint(data);
4296
+ }
4297
+ /**
4298
+ * This function stores the fingerprint in the state
4299
+ *
4300
+ * @param keyFn - Function to generate the key for the fingerprint
4301
+ * @param fingerprintFn - Function to generate the fingerprint
4302
+ * @param ttl - The time to live for the fingerprint in the lib state
4303
+ */
4304
+ static async storeFingerPrint(keyFn, fingerprintFn, ttl) {
4305
+ const key = typeof keyFn === "function" ? keyFn() : keyFn;
4306
+ const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
4307
+ const state = await import_aio_sdk6.State.init();
4308
+ await state.put(key, _InfiniteLoopBreaker.fingerPrint(data), {
4309
+ ttl: ttl !== void 0 ? ttl : _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL
4310
+ });
4311
+ }
4312
+ /**
4313
+ * This function generates a function to generate fingerprint for the data to be used in infinite loop detection based on params.
4314
+ *
4315
+ * @param obj - Data received from the event
4316
+ * @returns The function that generates the fingerprint
4317
+ */
4318
+ static fnFingerprint(obj) {
4319
+ return () => {
4320
+ return obj;
4321
+ };
4322
+ }
4323
+ /**
4324
+ * This function generates a function to create a key for the infinite loop detection based on params.
4325
+ *
4326
+ * @param key - Data received from the event
4327
+ * @returns The function that generates the key
4328
+ */
4329
+ static fnInfiniteLoopKey(key) {
4330
+ return () => {
4331
+ return key;
4332
+ };
4333
+ }
4334
+ /**
4335
+ * This function generates a fingerprint for the data
4336
+ *
4337
+ * @param data - The data to generate the fingerprint
4338
+ * @returns The fingerprint
4339
+ */
4340
+ static fingerPrint(data) {
4341
+ const hash = import_crypto2.default.createHash(_InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);
4342
+ hash.update(JSON.stringify(data));
4343
+ return hash.digest(_InfiniteLoopBreaker.FINGERPRINT_ENCODING);
4344
+ }
4345
+ };
4346
+ __name(_InfiniteLoopBreaker, "InfiniteLoopBreaker");
4347
+ /** The algorithm used to generate the fingerprint */
4348
+ _InfiniteLoopBreaker.FINGERPRINT_ALGORITHM = "sha256";
4349
+ /** The encoding used to generate the fingerprint */
4350
+ _InfiniteLoopBreaker.FINGERPRINT_ENCODING = "hex";
4351
+ /** The default time to live for the fingerprint in the lib state */
4352
+ _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60;
4353
+ var InfiniteLoopBreaker = _InfiniteLoopBreaker;
4354
+ var infinite_loop_breaker_default = InfiniteLoopBreaker;
4355
+
4356
+ // src/commerce/adobe-auth/index.ts
4357
+ var import_aio_lib_ims = require("@adobe/aio-lib-ims");
4358
+ var _AdobeAuth = class _AdobeAuth {
4359
+ /**
4360
+ * Retrieves an authentication token from Adobe IMS
4361
+ *
4362
+ * @param clientId - The client ID for the Adobe IMS integration
4363
+ * @param clientSecret - The client secret for the Adobe IMS integration
4364
+ * @param technicalAccountId - The technical account ID for the Adobe IMS integration
4365
+ * @param technicalAccountEmail - The technical account email for the Adobe IMS integration
4366
+ * @param imsOrgId - The IMS organization ID
4367
+ * @param scopes - Array of permission scopes to request for the token
4368
+ * @param currentContext - The context name for storing the configuration (defaults to 'onboarding-config')
4369
+ * @returns Promise<string> - A promise that resolves to the authentication token
4370
+ *
4371
+ * @example
4372
+ * const token = await AdobeAuth.getToken(
4373
+ * 'your-client-id',
4374
+ * 'your-client-secret',
4375
+ * 'your-technical-account-id',
4376
+ * 'your-technical-account-email',
4377
+ * 'your-ims-org-id',
4378
+ * ['AdobeID', 'openid', 'adobeio_api']
4379
+ * );
4380
+ */
4381
+ static async getToken(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, currentContext = "onboarding-config") {
4382
+ const config = {
4383
+ client_id: clientId,
4384
+ client_secrets: [clientSecret],
4385
+ technical_account_id: technicalAccountId,
4386
+ technical_account_email: technicalAccountEmail,
4387
+ ims_org_id: imsOrgId,
4388
+ scopes
4389
+ };
4390
+ await import_aio_lib_ims.context.setCurrent(currentContext);
4391
+ await import_aio_lib_ims.context.set(currentContext, config);
4392
+ return await (0, import_aio_lib_ims.getToken)();
4393
+ }
4394
+ };
4395
+ __name(_AdobeAuth, "AdobeAuth");
4396
+ var AdobeAuth = _AdobeAuth;
4397
+ var adobe_auth_default = AdobeAuth;
4398
+
4399
+ // src/commerce/adobe-commerce-client/index.ts
4400
+ var import_aio_sdk7 = require("@adobe/aio-sdk");
4401
+ var import_got = __toESM(require("got"));
4402
+ var _AdobeCommerceClient = class _AdobeCommerceClient {
4403
+ /**
4404
+ * @param baseUrl
4405
+ * @param connection
4406
+ * @param logger
4407
+ */
4408
+ constructor(baseUrl, connection, logger = null) {
4409
+ if (!baseUrl) {
4410
+ throw new Error("Commerce URL must be provided");
4411
+ }
4412
+ this.baseUrl = baseUrl;
4413
+ this.connection = connection;
4414
+ if (logger === null) {
4415
+ logger = import_aio_sdk7.Core.Logger("adobe-commerce-client", {
4416
+ level: "debug"
4417
+ });
4418
+ }
4419
+ this.logger = logger;
4420
+ }
4421
+ /**
4422
+ * @param endpoint
4423
+ * @param headers
4424
+ */
4425
+ async get(endpoint, headers = {}) {
4426
+ return await this.apiCall(endpoint, "GET", headers);
4427
+ }
4428
+ /**
4429
+ * @param endpoint
4430
+ * @param headers
4431
+ * @param payload
4432
+ */
4433
+ async post(endpoint, headers = {}, payload = null) {
4434
+ return await this.apiCall(endpoint, "POST", headers, payload);
4435
+ }
4436
+ /**
4437
+ * @param endpoint
4438
+ * @param headers
4439
+ * @param payload
4440
+ */
4441
+ async put(endpoint, headers = {}, payload = null) {
4442
+ return await this.apiCall(endpoint, "PUT", headers, payload);
4443
+ }
4444
+ /**
4445
+ * @param endpoint
4446
+ * @param headers
4447
+ */
4448
+ async delete(endpoint, headers = {}) {
4449
+ return await this.apiCall(endpoint, "DELETE", headers);
4450
+ }
4451
+ /**
4452
+ * @param endpoint
4453
+ * @param method
4454
+ * @param headers
4455
+ * @param payload
4456
+ * @private
4457
+ */
4458
+ async apiCall(endpoint, method, headers, payload = null) {
4459
+ const commerceGot = await this.getHttpClient();
4460
+ commerceGot.extend({
4461
+ headers
4462
+ });
4463
+ const wrapper = /* @__PURE__ */ __name(async (callable) => {
4464
+ try {
4465
+ const message = await callable();
4466
+ return { success: true, message };
4467
+ } catch (e) {
4468
+ if (e.code === "ERR_GOT_REQUEST_ERROR") {
4469
+ this.logger.error("Error while calling Commerce API", e);
4470
+ return {
4471
+ success: false,
4472
+ statusCode: 500 /* INTERNAL_ERROR */,
4473
+ message: `Unexpected error, check logs. Original error "${e.message}"`
4474
+ };
4475
+ }
4476
+ return {
4477
+ success: false,
4478
+ statusCode: e.response?.statusCode || 500 /* INTERNAL_ERROR */,
4479
+ message: e.message,
4480
+ body: e.responseBody
4481
+ };
4482
+ }
4483
+ }, "wrapper");
4484
+ let options = {
4485
+ method
4486
+ };
4487
+ if (payload !== null) {
4488
+ options = {
4489
+ ...options,
4490
+ json: payload
4491
+ };
4492
+ }
4493
+ return await wrapper(() => commerceGot(endpoint, options).json());
4494
+ }
4495
+ /**
4496
+ * @private
4497
+ */
4498
+ async getHttpClient() {
4499
+ const commerceGot = import_got.default.extend({
4500
+ http2: true,
4501
+ responseType: "json",
4502
+ prefixUrl: this.baseUrl,
4503
+ headers: {
4504
+ "Content-Type": "application/json"
4505
+ },
4506
+ hooks: {
4507
+ beforeRequest: [
4508
+ (options) => this.logger.debug(`Request [${options.method}] ${options.url}`)
4509
+ ],
4510
+ beforeRetry: [
4511
+ (options, error, retryCount) => this.logger.debug(
4512
+ `Retrying request [${options.method}] ${options.url} - count: ${retryCount} - error: ${error?.code} - ${error?.message}`
4513
+ )
4514
+ ],
4515
+ beforeError: [
4516
+ (error) => {
4517
+ const { response } = error;
4518
+ if (response?.body) {
4519
+ error.responseBody = response.body;
4520
+ }
4521
+ return error;
4522
+ }
4523
+ ],
4524
+ afterResponse: [
4525
+ (response) => {
4526
+ this.logger.debug(
4527
+ `Response [${response.request.options.method}] ${response.request.options.url} - ${response.statusCode} ${response.statusMessage}`
4528
+ );
4529
+ return response;
4530
+ }
4531
+ ]
4532
+ }
4533
+ });
4534
+ return await this.connection.extend(commerceGot);
4535
+ }
4536
+ };
4537
+ __name(_AdobeCommerceClient, "AdobeCommerceClient");
4538
+ var AdobeCommerceClient = _AdobeCommerceClient;
4539
+ var adobe_commerce_client_default = AdobeCommerceClient;
4540
+
4541
+ // src/commerce/adobe-commerce-client/basic-auth-connection/index.ts
4542
+ var import_aio_sdk9 = require("@adobe/aio-sdk");
4543
+
4544
+ // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
4545
+ var import_aio_sdk8 = require("@adobe/aio-sdk");
4546
+ var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
4547
+ /**
4548
+ * @param baseUrl
4549
+ * @param username
4550
+ * @param password
4551
+ * @param logger
4552
+ */
4553
+ constructor(baseUrl, username, password, logger = null) {
4554
+ this.baseUrl = baseUrl;
4555
+ this.username = username;
4556
+ this.password = password;
4557
+ this.key = "adobe_commerce_basic_auth_token";
4558
+ if (logger === null) {
4559
+ logger = import_aio_sdk8.Core.Logger("adobe-commerce-client", {
4560
+ level: "debug"
4561
+ });
4562
+ }
4563
+ this.logger = logger;
4564
+ }
4565
+ /**
4566
+ * @return string | null
4567
+ */
4568
+ async execute() {
4569
+ const currentValue = await this.getValue();
4570
+ if (currentValue !== null) {
4571
+ return currentValue;
4572
+ }
4573
+ let result = {
4574
+ token: null,
4575
+ expire_in: 3600
4576
+ };
4577
+ const response = await this.getCommerceToken();
4578
+ if (response !== null) {
4579
+ result = response;
4580
+ }
4581
+ this.logger.debug(`Token: ${JSON.stringify(result)}`);
4582
+ if (result.token !== null) {
4583
+ await this.setValue(result);
4584
+ }
4585
+ return result.token;
4586
+ }
4587
+ /**
4588
+ * @return TokenResult | null
4589
+ */
4590
+ async getCommerceToken() {
4591
+ const endpoint = this.createEndpoint("rest/V1/integration/admin/token");
4592
+ this.logger.debug(`Endpoint: ${endpoint}`);
4593
+ try {
4594
+ const restClient = new rest_client_default();
4595
+ const response = await restClient.post(
4596
+ endpoint,
4597
+ {
4598
+ "Content-Type": "application/json"
4599
+ },
4600
+ {
4601
+ username: this.username,
4602
+ password: this.password
4603
+ }
4604
+ );
4605
+ this.logger.debug(`Raw response type: ${typeof response}`);
4606
+ this.logger.debug(`Raw response: ${JSON.stringify(response)}`);
4607
+ if (response !== null && response !== void 0) {
4608
+ let tokenValue;
4609
+ if (typeof response === "string") {
4610
+ tokenValue = response;
4611
+ } else if (typeof response === "object" && response.token) {
4612
+ tokenValue = response.token;
4613
+ } else {
4614
+ try {
4615
+ tokenValue = response.toString();
4616
+ this.logger.debug(`Converted response to string: ${tokenValue?.substring(0, 10)}...`);
4617
+ } catch {
4618
+ this.logger.error(`Unexpected response format: ${JSON.stringify(response)}`);
4619
+ return null;
4620
+ }
4621
+ }
4622
+ this.logger.debug(`Extracted token: ${tokenValue?.substring(0, 10)}...`);
4623
+ return {
4624
+ token: tokenValue,
4625
+ expire_in: 3600
4626
+ // Adobe Commerce tokens typically expire in 1 hour
4627
+ };
4628
+ }
4629
+ this.logger.error("Received null or undefined response from Commerce API");
4630
+ return null;
4631
+ } catch (error) {
4632
+ this.logger.error(`Failed to get Commerce token: ${error.message}`);
4633
+ this.logger.debug(`Full error: ${JSON.stringify(error)}`);
4634
+ return null;
4635
+ }
4636
+ }
4637
+ /**
4638
+ * @param endpoint
4639
+ * @return string
4640
+ */
4641
+ createEndpoint(endpoint) {
4642
+ const normalizedBaseUrl = this.baseUrl.replace(/\/+$/, "");
4643
+ const normalizedEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
4644
+ return `${normalizedBaseUrl}${normalizedEndpoint}`;
4645
+ }
4646
+ /**
4647
+ * @param result
4648
+ * @return boolean
4649
+ */
4650
+ async setValue(result) {
4651
+ try {
4652
+ const state = await this.getState();
4653
+ if (state === null) {
4654
+ return true;
4655
+ }
4656
+ await state.put(this.key, result.token, { ttl: result.expire_in });
4657
+ return true;
4658
+ } catch (error) {
4659
+ this.logger.debug("Failed to cache token, continuing without caching");
4660
+ return true;
4661
+ }
4662
+ }
4663
+ /**
4664
+ * @return string | null
4665
+ */
4666
+ async getValue() {
4667
+ try {
4668
+ const state = await this.getState();
4669
+ if (state === null) {
4670
+ return null;
4671
+ }
4672
+ const value = await state.get(this.key);
4673
+ if (value !== void 0) {
4674
+ return value.value;
4675
+ }
4676
+ } catch (error) {
4677
+ this.logger.debug("State API not available, skipping cache lookup");
4678
+ }
4679
+ return null;
4680
+ }
4681
+ /**
4682
+ * @return any
4683
+ */
4684
+ async getState() {
4685
+ if (this.state === void 0) {
4686
+ try {
4687
+ this.state = await import_aio_sdk8.State.init();
4688
+ } catch (error) {
4689
+ this.logger.debug("State API initialization failed, running without caching");
4690
+ this.state = null;
4691
+ }
4692
+ }
4693
+ return this.state;
4694
+ }
4695
+ };
4696
+ __name(_GenerateBasicAuthToken, "GenerateBasicAuthToken");
4697
+ var GenerateBasicAuthToken = _GenerateBasicAuthToken;
4698
+ var generate_basic_auth_token_default = GenerateBasicAuthToken;
4699
+
4700
+ // src/commerce/adobe-commerce-client/basic-auth-connection/index.ts
4701
+ var _BasicAuthConnection = class _BasicAuthConnection {
4702
+ /**
4703
+ * @param baseUrl
4704
+ * @param username
4705
+ * @param password
4706
+ * @param logger
4707
+ */
4708
+ constructor(baseUrl, username, password, logger = null) {
4709
+ this.baseUrl = baseUrl;
4710
+ this.username = username;
4711
+ this.password = password;
4712
+ if (logger === null) {
4713
+ logger = import_aio_sdk9.Core.Logger("adobe-commerce-client", {
4714
+ level: "debug"
4715
+ });
4716
+ }
4717
+ this.logger = logger;
4718
+ }
4719
+ /**
4720
+ * @param commerceGot
4721
+ */
4722
+ async extend(commerceGot) {
4723
+ this.logger.debug("Using Commerce client with integration options");
4724
+ const generateToken = new generate_basic_auth_token_default(
4725
+ this.baseUrl,
4726
+ this.username,
4727
+ this.password,
4728
+ this.logger
4729
+ );
4730
+ const token = await generateToken.execute();
4731
+ return commerceGot.extend({
4732
+ headers: {
4733
+ Authorization: `Bearer ${token}`
4734
+ }
4735
+ });
4736
+ }
4737
+ };
4738
+ __name(_BasicAuthConnection, "BasicAuthConnection");
4739
+ var BasicAuthConnection = _BasicAuthConnection;
4740
+ var basic_auth_connection_default = BasicAuthConnection;
4741
+
4742
+ // src/commerce/adobe-commerce-client/oauth1a-connection/index.ts
4743
+ var import_aio_sdk10 = require("@adobe/aio-sdk");
4744
+ var import_oauth_1 = __toESM(require("oauth-1.0a"));
4745
+ var crypto2 = __toESM(require("crypto"));
4746
+ var _Oauth1aConnection = class _Oauth1aConnection {
4747
+ /**
4748
+ * @param consumerKey
4749
+ * @param consumerSecret
4750
+ * @param accessToken
4751
+ * @param accessTokenSecret
4752
+ * @param logger
4753
+ */
4754
+ constructor(consumerKey, consumerSecret, accessToken, accessTokenSecret, logger = null) {
4755
+ this.consumerKey = consumerKey;
4756
+ this.consumerSecret = consumerSecret;
4757
+ this.accessToken = accessToken;
4758
+ this.accessTokenSecret = accessTokenSecret;
4759
+ if (logger === null) {
4760
+ logger = import_aio_sdk10.Core.Logger("adobe-commerce-client", {
4761
+ level: "debug"
4762
+ });
4763
+ }
4764
+ this.logger = logger;
4765
+ }
4766
+ /**
4767
+ * @param commerceGot
4768
+ */
4769
+ async extend(commerceGot) {
4770
+ this.logger.debug("Using Commerce client with integration options");
4771
+ const headers = this.headersProvider();
4772
+ return commerceGot.extend({
4773
+ handlers: [
4774
+ (options, next) => {
4775
+ options.headers = {
4776
+ ...options.headers,
4777
+ ...headers(options.url.toString(), options.method)
4778
+ };
4779
+ return next(options);
4780
+ }
4781
+ ]
4782
+ });
4783
+ }
4784
+ /**
4785
+ * return () => { }
4786
+ */
4787
+ headersProvider() {
4788
+ const oauth = new import_oauth_1.default({
4789
+ consumer: {
4790
+ key: this.consumerKey,
4791
+ secret: this.consumerSecret
4792
+ },
4793
+ signature_method: "HMAC-SHA256",
4794
+ hash_function: /* @__PURE__ */ __name((baseString, key) => crypto2.createHmac("sha256", key).update(baseString).digest("base64"), "hash_function")
4795
+ });
4796
+ const oauthToken = {
4797
+ key: this.accessToken,
4798
+ secret: this.accessTokenSecret
4799
+ };
4800
+ return (url, method) => oauth.toHeader(oauth.authorize({ url, method }, oauthToken));
4801
+ }
4802
+ };
4803
+ __name(_Oauth1aConnection, "Oauth1aConnection");
4804
+ var Oauth1aConnection = _Oauth1aConnection;
4805
+ var oauth1a_connection_default = Oauth1aConnection;
4806
+
4807
+ // src/commerce/adobe-commerce-client/ims-connection/index.ts
4808
+ var import_aio_sdk11 = require("@adobe/aio-sdk");
4809
+ var _ImsConnection = class _ImsConnection {
4810
+ /**
4811
+ * @param clientId
4812
+ * @param clientSecret
4813
+ * @param technicalAccountId
4814
+ * @param technicalAccountEmail
4815
+ * @param imsOrgId
4816
+ * @param scopes
4817
+ * @param logger
4818
+ * @param currentContext
4819
+ */
4820
+ constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, logger = null, currentContext = "adobe-commerce-client") {
4821
+ this.clientId = clientId;
4822
+ this.clientSecret = clientSecret;
4823
+ this.technicalAccountId = technicalAccountId;
4824
+ this.technicalAccountEmail = technicalAccountEmail;
4825
+ this.imsOrgId = imsOrgId;
4826
+ this.scopes = scopes;
4827
+ this.currentContext = currentContext;
4828
+ if (logger === null) {
4829
+ logger = import_aio_sdk11.Core.Logger(currentContext, {
4830
+ level: "debug"
4831
+ });
4832
+ }
4833
+ this.logger = logger;
4834
+ }
4835
+ /**
4836
+ * @param commerceGot
4837
+ */
4838
+ async extend(commerceGot) {
4839
+ this.logger.debug("Using Commerce client with IMS authentication");
4840
+ const token = await adobe_auth_default.getToken(
4841
+ this.clientId,
4842
+ this.clientSecret,
4843
+ this.technicalAccountId,
4844
+ this.technicalAccountEmail,
4845
+ this.imsOrgId,
4846
+ this.scopes,
4847
+ this.currentContext
4848
+ );
4849
+ this.logger.debug(`IMS token being extended to header: ${token}`);
4850
+ return commerceGot.extend({
4851
+ headers: {
4852
+ Authorization: `Bearer ${token}`
4853
+ }
4854
+ });
4855
+ }
4856
+ };
4857
+ __name(_ImsConnection, "ImsConnection");
4858
+ var ImsConnection = _ImsConnection;
4859
+ var ims_connection_default = ImsConnection;
4860
+ // Annotate the CommonJS export names for ESM import in node:
4861
+ 0 && (module.exports = {
4862
+ AdobeAuth,
4863
+ AdobeCommerceClient,
4864
+ BasicAuthConnection,
4865
+ BearerToken,
4866
+ CreateEvents,
4867
+ CreateRegistrations,
4868
+ EventConsumerAction,
4869
+ EventMetadataManager,
4870
+ FileRepository,
4871
+ GenerateBasicAuthToken,
4872
+ GraphQlAction,
4873
+ HttpMethod,
4874
+ HttpStatus,
4875
+ IOEventsApiError,
4876
+ ImsConnection,
4877
+ InfiniteLoopBreaker,
4878
+ IoEventsGlobals,
4879
+ Oauth1aConnection,
4880
+ OnboardEvents,
4881
+ Openwhisk,
4882
+ OpenwhiskAction,
4883
+ Parameters,
4884
+ ProviderManager,
4885
+ RegistrationManager,
4886
+ RestClient,
4887
+ RuntimeAction,
4888
+ RuntimeActionResponse,
4889
+ Validator
4890
+ });
4891
+ //# sourceMappingURL=index.js.map