@adobe/aio-commerce-lib-app 1.7.0 → 1.8.0-alpha-20260722091448

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/dist/cjs/actions/app-config/index.cjs +41 -38
  3. package/dist/cjs/actions/app-config/index.d.cts +1 -1
  4. package/dist/cjs/actions/association/index.cjs +85 -0
  5. package/dist/cjs/actions/{registration → association}/index.d.cts +9 -13
  6. package/dist/cjs/actions/config/index.cjs +21 -32
  7. package/dist/cjs/actions/installation/index.cjs +72 -51
  8. package/dist/cjs/actions/installation/index.d.cts +2 -2
  9. package/dist/cjs/actions/scope-tree/index.cjs +18 -17
  10. package/dist/{es/app-DrYHK-z1.d.mts → cjs/app-BwehWeu1.d.cts} +1237 -1031
  11. package/dist/cjs/commands/index.cjs +523 -301
  12. package/dist/cjs/commands/templates/admin-ui/tsconfig.json +14 -0
  13. package/dist/cjs/commands/templates/admin-ui/web-src/index.css +5 -0
  14. package/dist/cjs/commands/templates/admin-ui/web-src/index.html +17 -0
  15. package/dist/cjs/commands/templates/admin-ui/web-src/src/app.jsx +12 -0
  16. package/dist/cjs/commands/templates/admin-ui/web-src/src/components/welcome.jsx +16 -0
  17. package/dist/cjs/commands/templates/admin-ui/web-src/src/pages/main-page.jsx +10 -0
  18. package/dist/cjs/commands/templates/{admin-ui-sdk/registration.js.template → admin-ui/web-src-template.d.ts} +11 -6
  19. package/dist/cjs/commands/templates/app-management/app-config.js.template +1 -14
  20. package/dist/cjs/commands/templates/app-management/association.js.template +6 -0
  21. package/dist/cjs/commands/templates/app-management/installation.js.template +1 -13
  22. package/dist/cjs/commands/templates/business-configuration/config.js.template +2 -15
  23. package/dist/cjs/commands/templates/business-configuration/scope-tree.js.template +0 -12
  24. package/dist/cjs/config/index.browser.cjs +18 -0
  25. package/dist/cjs/config/index.browser.d.cts +16 -0
  26. package/dist/cjs/config/{index.cjs → index.node.cjs} +9 -8
  27. package/dist/{es/config/index.d.mts → cjs/config/index.node.d.cts} +1065 -394
  28. package/dist/cjs/define-DOqVyexT.d.cts +34 -0
  29. package/dist/cjs/define-hlcQw7Cv.cjs +41 -0
  30. package/dist/cjs/environment-B7EnozSg.cjs +135 -0
  31. package/dist/cjs/{index-B5gJ-q4U.d.cts → index-B3ISkC54.d.cts} +17 -12
  32. package/dist/cjs/index.cjs +268 -0
  33. package/dist/cjs/index.d.cts +230 -0
  34. package/dist/cjs/{config-D-s0GSep.cjs → index.node-BWZuZLgs.cjs} +144 -44
  35. package/dist/cjs/{logging-BVz3weoC.cjs → logging-udPuAJPt.cjs} +2 -2
  36. package/dist/cjs/management/index.cjs +1 -1
  37. package/dist/cjs/management/index.d.cts +1 -1
  38. package/dist/cjs/{management-Dehz9qSJ.cjs → management-DEsRVP2L.cjs} +385 -582
  39. package/dist/cjs/{openapi-Cux6K4ZD.cjs → openapi-CwytYdWl.cjs} +476 -600
  40. package/dist/cjs/repository-CbceYZqc.cjs +69 -0
  41. package/dist/cjs/{router-BOR7T6qR.cjs → router-hA_Y9gZ1.cjs} +42 -44
  42. package/dist/cjs/{schemas-FngDuIeo.cjs → schemas-mLxMh_ko.cjs} +2 -2
  43. package/dist/cjs/utils-DSCmZ_iJ.cjs +408 -0
  44. package/dist/cjs/{validate-oAOpyFyb.cjs → validate-C_eCKp21.cjs} +21 -21
  45. package/dist/cjs/{webhooks-tbZy9G3p.cjs → webhooks-L4DWHSOl.cjs} +159 -151
  46. package/dist/es/actions/app-config/index.d.mts +1 -1
  47. package/dist/es/actions/app-config/index.mjs +39 -36
  48. package/dist/es/actions/{registration → association}/index.d.mts +9 -13
  49. package/dist/es/actions/association/index.mjs +82 -0
  50. package/dist/es/actions/config/index.mjs +17 -28
  51. package/dist/es/actions/installation/index.d.mts +2 -2
  52. package/dist/es/actions/installation/index.mjs +69 -48
  53. package/dist/es/actions/scope-tree/index.mjs +14 -13
  54. package/dist/{cjs/app-DrYHK-z1.d.cts → es/app-BwehWeu1.d.mts} +1237 -1031
  55. package/dist/es/commands/index.mjs +556 -332
  56. package/dist/es/commands/templates/admin-ui/tsconfig.json +14 -0
  57. package/dist/es/commands/templates/admin-ui/web-src/index.css +5 -0
  58. package/dist/es/commands/templates/admin-ui/web-src/index.html +17 -0
  59. package/dist/es/commands/templates/admin-ui/web-src/src/app.jsx +12 -0
  60. package/dist/es/commands/templates/admin-ui/web-src/src/components/welcome.jsx +16 -0
  61. package/dist/es/commands/templates/admin-ui/web-src/src/pages/main-page.jsx +10 -0
  62. package/dist/es/commands/templates/{admin-ui-sdk/registration.js.template → admin-ui/web-src-template.d.ts} +11 -6
  63. package/dist/es/commands/templates/app-management/app-config.js.template +1 -14
  64. package/dist/es/commands/templates/app-management/association.js.template +6 -0
  65. package/dist/es/commands/templates/app-management/installation.js.template +1 -13
  66. package/dist/es/commands/templates/business-configuration/config.js.template +2 -15
  67. package/dist/es/commands/templates/business-configuration/scope-tree.js.template +0 -12
  68. package/dist/es/config/index.browser.d.mts +16 -0
  69. package/dist/es/config/index.browser.mjs +17 -0
  70. package/dist/{cjs/config/index.d.cts → es/config/index.node.d.mts} +1066 -393
  71. package/dist/es/config/{index.mjs → index.node.mjs} +5 -4
  72. package/dist/es/define-DxH1BFia.d.mts +34 -0
  73. package/dist/es/define-Z_Glf1-_.mjs +35 -0
  74. package/dist/es/environment-C84BPRJZ.mjs +104 -0
  75. package/dist/es/{index-DLMbTtKS.d.mts → index-DSk-RmwM.d.mts} +17 -12
  76. package/dist/es/index.d.mts +230 -0
  77. package/dist/es/index.mjs +259 -0
  78. package/dist/es/{config-3I4eLyyR.mjs → index.node-DuvW9Sha.mjs} +113 -39
  79. package/dist/es/management/index.d.mts +1 -1
  80. package/dist/es/management/index.mjs +1 -1
  81. package/dist/es/{management-BUX-w2Ji.mjs → management-D5pmBBec.mjs} +353 -550
  82. package/dist/es/{openapi-B6uP0SRn.mjs → openapi-CXonvevE.mjs} +476 -600
  83. package/dist/es/repository-BGmy0YeZ.mjs +52 -0
  84. package/dist/es/{router-D58JJHHA.mjs → router-B_h0cvjc.mjs} +40 -42
  85. package/dist/es/utils-_gj8L6eN.mjs +289 -0
  86. package/dist/es/{validate-Dfajrp99.mjs → validate-t0T0F2MF.mjs} +18 -18
  87. package/dist/es/{webhooks-B5oq9ULL.mjs → webhooks-D7DExIDM.mjs} +150 -142
  88. package/package.json +40 -17
  89. package/dist/cjs/actions/registration/index.cjs +0 -50
  90. package/dist/cjs/admin-ui-sdk-EU915zlR.d.cts +0 -664
  91. package/dist/es/actions/registration/index.mjs +0 -49
  92. package/dist/es/admin-ui-sdk-BwnD0xjK.d.mts +0 -664
  93. /package/dist/cjs/{chunk-Cozy-1ZF.cjs → rolldown-runtime-Cozy-1ZF.cjs} +0 -0
@@ -12,37 +12,25 @@
12
12
  * governing permissions and limitations under the License.
13
13
  */
14
14
 
15
- const require_chunk = require('./chunk-Cozy-1ZF.cjs');
15
+ const require_rolldown_runtime = require('./rolldown-runtime-Cozy-1ZF.cjs');
16
+ const require_utils = require('./utils-DSCmZ_iJ.cjs');
16
17
  const require_error = require('./error-D-N0PKSl.cjs');
17
- const require_webhooks = require('./webhooks-tbZy9G3p.cjs');
18
- const require_logging = require('./logging-BVz3weoC.cjs');
19
- let _adobe_aio_commerce_lib_core_error = require("@adobe/aio-commerce-lib-core/error");
18
+ const require_environment = require('./environment-B7EnozSg.cjs');
19
+ const require_webhooks = require('./webhooks-L4DWHSOl.cjs');
20
+ const require_logging = require('./logging-udPuAJPt.cjs');
21
+ let _adobe_aio_commerce_lib_api = require("@adobe/aio-commerce-lib-api");
22
+ let _adobe_aio_commerce_lib_config = require("@adobe/aio-commerce-lib-config");
23
+ let _adobe_aio_commerce_lib_auth = require("@adobe/aio-commerce-lib-auth");
20
24
  let valibot = require("valibot");
21
- valibot = require_chunk.__toESM(valibot, 1);
25
+ valibot = require_rolldown_runtime.__toESM(valibot, 1);
22
26
  let _adobe_aio_commerce_lib_api_utils = require("@adobe/aio-commerce-lib-api/utils");
23
27
  let camelcase = require("camelcase");
24
- camelcase = require_chunk.__toESM(camelcase, 1);
28
+ camelcase = require_rolldown_runtime.__toESM(camelcase, 1);
25
29
  let _adobe_aio_commerce_lib_admin_ui_api = require("@adobe/aio-commerce-lib-admin-ui/api");
26
- let _adobe_aio_commerce_lib_api = require("@adobe/aio-commerce-lib-api");
27
- let _adobe_aio_commerce_lib_auth = require("@adobe/aio-commerce-lib-auth");
28
30
  let _adobe_aio_commerce_lib_events_commerce = require("@adobe/aio-commerce-lib-events/commerce");
29
31
  let _adobe_aio_commerce_lib_events_io_events = require("@adobe/aio-commerce-lib-events/io-events");
30
32
  let _adobe_aio_commerce_lib_webhooks_api = require("@adobe/aio-commerce-lib-webhooks/api");
31
33
 
32
- //#region ../../packages-private/common-utils/source/valibot/utils.ts
33
- /**
34
- * Parses the input using the provided schema and throws a {@link CommerceSdkValidationError} error if the input is invalid.
35
- * @param schema - The schema to use for parsing.
36
- * @param input - The input to parse.
37
- * @param message - Optional custom error message for the validation error.
38
- */
39
- function parseOrThrow(schema, input, message) {
40
- const result = valibot.safeParse(schema, input);
41
- if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(message ?? "Invalid input", { issues: result.issues });
42
- return result.output;
43
- }
44
-
45
- //#endregion
46
34
  //#region source/management/installation/workflow/hooks.ts
47
35
  /** Helper to call a hook if it exists. */
48
36
  async function callHook(hooks, hookName, ...args) {
@@ -77,13 +65,13 @@ function isBranchStep(step) {
77
65
  */
78
66
  function defineLeafStep(options) {
79
67
  return {
80
- type: "leaf",
81
- name: options.name,
82
- meta: options.meta,
83
- when: options.when,
84
68
  install: options.install,
69
+ meta: options.meta,
70
+ name: options.name,
71
+ type: "leaf",
85
72
  uninstall: options.uninstall,
86
- validate: options.validate
73
+ validate: options.validate,
74
+ when: options.when
87
75
  };
88
76
  }
89
77
  /**
@@ -102,13 +90,13 @@ function defineLeafStep(options) {
102
90
  */
103
91
  function defineBranchStep(options) {
104
92
  return {
105
- type: "branch",
106
- name: options.name,
107
- meta: options.meta,
108
- when: options.when,
109
- context: options.context,
110
93
  children: options.children,
111
- validate: options.validate
94
+ context: options.context,
95
+ meta: options.meta,
96
+ name: options.name,
97
+ type: "branch",
98
+ validate: options.validate,
99
+ when: options.when
112
100
  };
113
101
  }
114
102
 
@@ -123,7 +111,7 @@ function setAtPath(data, path, value) {
123
111
  const lastKey = path.at(-1);
124
112
  if (!lastKey) return;
125
113
  let current = data;
126
- for (let i = 0; i < path.length - 1; i++) {
114
+ for (let i = 0; i < path.length - 1; i += 1) {
127
115
  const key = path[i];
128
116
  current[key] ??= {};
129
117
  current = current[key];
@@ -134,7 +122,7 @@ function setAtPath(data, path, value) {
134
122
  function getAtPath(data, path) {
135
123
  let current = data;
136
124
  for (const key of path) {
137
- if (current == null || typeof current !== "object") return;
125
+ if (current === null || current === void 0 || typeof current !== "object") return;
138
126
  current = current[key];
139
127
  }
140
128
  return current;
@@ -142,26 +130,26 @@ function getAtPath(data, path) {
142
130
  /** Creates an installation error from an exception. */
143
131
  async function createInstallationError(err, path, key = "STEP_EXECUTION_FAILED") {
144
132
  return {
145
- path,
146
133
  key,
147
- message: await (0, _adobe_aio_commerce_lib_api_utils.unwrapHttpError)(err)
134
+ message: await (0, _adobe_aio_commerce_lib_api_utils.unwrapHttpError)(err),
135
+ path
148
136
  };
149
137
  }
150
138
  /** Creates a succeeded installation state. */
151
139
  function createSucceededState(base) {
152
140
  return {
153
141
  ...base,
154
- status: "succeeded",
155
- completedAt: nowIsoString()
142
+ completedAt: nowIsoString(),
143
+ status: "succeeded"
156
144
  };
157
145
  }
158
146
  /** Creates a failed installation state. */
159
147
  function createFailedState(base, error) {
160
148
  return {
161
149
  ...base,
162
- status: "failed",
163
150
  completedAt: nowIsoString(),
164
- error
151
+ error,
152
+ status: "failed"
165
153
  };
166
154
  }
167
155
 
@@ -176,11 +164,12 @@ function createFailedState(base, error) {
176
164
  function createInitialState(options) {
177
165
  const { rootStep, config, mode } = options;
178
166
  return {
167
+ config,
168
+ data: null,
179
169
  id: crypto.randomUUID(),
180
170
  startedAt: nowIsoString(),
181
171
  status: "in-progress",
182
- step: buildInitialStepStatus(rootStep, config, [], mode),
183
- data: null
172
+ step: buildInitialStepStatus(rootStep, config, [], mode)
184
173
  };
185
174
  }
186
175
  /**
@@ -190,19 +179,20 @@ function createInitialState(options) {
190
179
  */
191
180
  function createRetryState(failedState) {
192
181
  return {
182
+ config: failedState.config,
183
+ data: failedState.data,
193
184
  id: failedState.id,
194
185
  startedAt: failedState.startedAt,
195
186
  status: "in-progress",
196
- step: resetFailedSteps(failedState.step),
197
- data: failedState.data
187
+ step: resetFailedSteps(failedState.step)
198
188
  };
199
189
  }
200
190
  /** Recursively resets non-succeeded steps back to "pending". */
201
191
  function resetFailedSteps(step) {
202
192
  return {
203
193
  ...step,
204
- status: step.status === "succeeded" ? "succeeded" : "pending",
205
- children: step.children.map(resetFailedSteps)
194
+ children: step.children.map(resetFailedSteps),
195
+ status: step.status === "succeeded" ? "succeeded" : "pending"
206
196
  };
207
197
  }
208
198
  /**
@@ -225,34 +215,36 @@ async function executeWorkflowWithMode(options, mode) {
225
215
  const { rootStep, installationContext, config, initialState, hooks } = options;
226
216
  const step = structuredClone(initialState.step);
227
217
  const context = {
228
- installationContext,
229
218
  config,
230
- id: initialState.id,
231
- startedAt: initialState.startedAt,
232
- step,
233
219
  data: initialState.data,
234
220
  error: null,
235
221
  hooks,
236
- mode
222
+ id: initialState.id,
223
+ installationContext,
224
+ mode,
225
+ startedAt: initialState.startedAt,
226
+ step
237
227
  };
238
228
  await callHook(hooks, "onInstallationStart", snapshot(context));
239
229
  try {
240
230
  await executeStep(rootStep, context.step, {}, context);
241
231
  const succeeded = createSucceededState({
232
+ config: context.config,
233
+ data: context.data,
242
234
  id: context.id,
243
235
  startedAt: context.startedAt,
244
- step: context.step,
245
- data: context.data
236
+ step: context.step
246
237
  });
247
238
  await callHook(hooks, "onInstallationSuccess", succeeded);
248
239
  return succeeded;
249
240
  } catch (err) {
250
241
  const error = context.error ?? await createInstallationError(err, [], "INSTALLATION_FAILED");
251
242
  const failed = createFailedState({
252
- step: context.step,
243
+ config: context.config,
244
+ data: context.data,
253
245
  id: context.id,
254
246
  startedAt: context.startedAt,
255
- data: context.data
247
+ step: context.step
256
248
  }, error);
257
249
  await callHook(hooks, "onInstallationFailure", failed);
258
250
  return failed;
@@ -270,22 +262,23 @@ function buildInitialStepStatus(step, config, parentPath, mode) {
270
262
  children.push(buildInitialStepStatus(child, config, path, mode));
271
263
  }
272
264
  return {
265
+ children,
273
266
  id: crypto.randomUUID(),
267
+ meta: mode === "uninstall" && step.meta.uninstall ? step.meta.uninstall : step.meta.install,
274
268
  name: step.name,
275
269
  path,
276
- meta: mode === "uninstall" && step.meta.uninstall ? step.meta.uninstall : step.meta.install,
277
- status: "pending",
278
- children
270
+ status: "pending"
279
271
  };
280
272
  }
281
273
  /** Snapshot current execution as InProgressInstallationState. */
282
274
  function snapshot(context) {
283
275
  return {
276
+ config: context.config,
277
+ data: context.data,
284
278
  id: context.id,
285
279
  startedAt: context.startedAt,
286
280
  status: "in-progress",
287
- step: context.step,
288
- data: context.data
281
+ step: context.step
289
282
  };
290
283
  }
291
284
  /** Executes a single step (branch or leaf) recursively. */
@@ -295,9 +288,9 @@ async function executeStep(step, stepStatus, inherited, context) {
295
288
  const isLeaf = isLeafStep(step);
296
289
  stepStatus.status = "in-progress";
297
290
  await callHook(context.hooks, "onStepStart", {
291
+ isLeaf,
298
292
  path,
299
- stepName: step.name,
300
- isLeaf
293
+ stepName: step.name
301
294
  }, snapshot(context));
302
295
  try {
303
296
  if (isBranchStep(step)) await executeBranchStep(step, stepStatus, inherited, context);
@@ -305,19 +298,19 @@ async function executeStep(step, stepStatus, inherited, context) {
305
298
  stepStatus.status = "succeeded";
306
299
  context.data ??= {};
307
300
  await callHook(context.hooks, "onStepSuccess", {
308
- path,
309
- stepName: step.name,
310
301
  isLeaf,
311
- result: getAtPath(context.data, path)
302
+ path,
303
+ result: getAtPath(context.data, path),
304
+ stepName: step.name
312
305
  }, snapshot(context));
313
306
  } catch (err) {
314
307
  stepStatus.status = "failed";
315
308
  context.error ??= await createInstallationError(err, path);
316
309
  await callHook(context.hooks, "onStepFailure", {
317
- path,
318
- stepName: step.name,
310
+ error: context.error,
319
311
  isLeaf,
320
- error: context.error
312
+ path,
313
+ stepName: step.name
321
314
  }, snapshot(context));
322
315
  throw err;
323
316
  }
@@ -388,9 +381,9 @@ async function validateStepTree(options) {
388
381
  const result = await validateStep(rootStep, config, validationContext, []);
389
382
  const summary = aggregateSummary(result);
390
383
  return {
391
- valid: summary.errors === 0 && summary.warnings === 0,
392
384
  result,
393
- summary
385
+ summary,
386
+ valid: summary.errors === 0 && summary.warnings === 0
394
387
  };
395
388
  }
396
389
  /** Recursively validates a single step and its children. */
@@ -407,11 +400,11 @@ async function validateStep(step, config, context, parentPath) {
407
400
  }
408
401
  }
409
402
  return {
410
- name: step.name,
411
- path,
412
- meta: step.meta.install,
403
+ children,
413
404
  issues,
414
- children
405
+ meta: step.meta.install,
406
+ name: step.name,
407
+ path
415
408
  };
416
409
  }
417
410
  /** Resolves the child context for a branch step, reporting errors as issues. */
@@ -457,16 +450,16 @@ async function runStepValidation(step, config, context) {
457
450
  function aggregateSummary(result) {
458
451
  let errors = 0;
459
452
  let warnings = 0;
460
- for (const issue of result.issues) if (issue.severity === "error") errors++;
461
- else if (issue.severity === "warning") warnings++;
453
+ for (const issue of result.issues) if (issue.severity === "error") errors += 1;
454
+ else if (issue.severity === "warning") warnings += 1;
462
455
  for (const child of result.children) {
463
456
  const childSummary = aggregateSummary(child);
464
457
  errors += childSummary.errors;
465
458
  warnings += childSummary.warnings;
466
459
  }
467
460
  return {
468
- totalIssues: errors + warnings,
469
461
  errors,
462
+ totalIssues: errors + warnings,
470
463
  warnings
471
464
  };
472
465
  }
@@ -485,7 +478,7 @@ const ScriptModuleSchema = valibot.union([valibot.function(), valibot.object({
485
478
  * @throws If the export is not a function or an object with an `install` function.
486
479
  */
487
480
  function assertScriptModule(module) {
488
- parseOrThrow(ScriptModuleSchema, module, "Invalid script module format. Expected a function or an object with an `install` method.");
481
+ require_environment.parseOrThrow(ScriptModuleSchema, module, "Invalid script module format. Expected a function or an object with an `install` method.");
489
482
  }
490
483
  /**
491
484
  * Parses and validates a custom script module from the provided customScripts context.
@@ -493,10 +486,11 @@ function assertScriptModule(module) {
493
486
  *
494
487
  * @param customScripts - The customScripts context containing the loaded modules
495
488
  * @param script - The script path to resolve the module for
489
+ * @returns The resolved script module, or `undefined` if the script is not present in the context.
496
490
  */
497
491
  function getScriptModule(customScripts, script) {
498
492
  let scriptModule = customScripts[script];
499
- if (!scriptModule) throw new Error(`Script ${script} not found in customScripts context. Make sure the script is defined in the configuration and the action was generated with custom scripts support.`);
493
+ if (!scriptModule) return;
500
494
  if (typeof scriptModule === "object" && "default" in scriptModule) scriptModule = scriptModule.default;
501
495
  assertScriptModule(scriptModule);
502
496
  return scriptModule;
@@ -512,28 +506,35 @@ function resolveCustomScriptHandler(scriptModule, handler) {
512
506
  function createCustomScriptStep(scriptConfig) {
513
507
  const { script, name, description } = scriptConfig;
514
508
  return defineLeafStep({
515
- name: camelcase$1(name),
516
- meta: { install: {
517
- label: name,
518
- description
519
- } },
520
509
  install: async (config, context) => {
521
510
  const { logger } = context;
522
511
  const customScripts = context.customScripts || {};
523
512
  logger.info(`Executing custom installation script: ${name}`);
524
513
  logger.debug(`Script path: ${script}`);
525
- const scriptResult = await resolveCustomScriptHandler(getScriptModule(customScripts, script), "install")(config, context);
514
+ const scriptModule = getScriptModule(customScripts, script);
515
+ if (!scriptModule) throw new Error(`Script ${script} not found in customScripts context. Make sure the script is defined in the configuration and the action was generated with custom scripts support.`);
516
+ const scriptResult = await resolveCustomScriptHandler(scriptModule, "install")(config, context);
526
517
  logger.info(`Successfully executed script: ${name}`);
527
518
  return {
528
- script,
529
- data: scriptResult
519
+ data: scriptResult,
520
+ script
530
521
  };
531
522
  },
523
+ meta: { install: {
524
+ description,
525
+ label: name
526
+ } },
527
+ name: camelcase$1(name),
532
528
  uninstall: async (config, context) => {
533
529
  const { logger } = context;
534
530
  const customScripts = context.customScripts || {};
535
531
  logger.debug(`Uninstalling custom script: ${name}`);
536
- const uninstall = resolveCustomScriptHandler(getScriptModule(customScripts, script), "uninstall");
532
+ const scriptModule = getScriptModule(customScripts, script);
533
+ if (!scriptModule) {
534
+ logger.warn(`Script ${script} not found in customScripts context, skipping uninstall. It may have been removed from the project after being configured.`);
535
+ return;
536
+ }
537
+ const uninstall = resolveCustomScriptHandler(scriptModule, "uninstall");
537
538
  if (!uninstall) {
538
539
  logger.debug(`Script ${script} does not export an uninstall function, skipping uninstall.`);
539
540
  return;
@@ -558,19 +559,19 @@ function createCustomScriptSteps(config) {
558
559
  //#region source/management/installation/custom-installation/branch.ts
559
560
  /** Root custom installation step that executes custom installation scripts. */
560
561
  const customInstallationStepBase = defineBranchStep({
561
- name: "customInstallationSteps",
562
+ children: [],
562
563
  meta: {
563
564
  install: {
564
- label: "Custom Installation Steps",
565
- description: "Executes custom installation scripts defined in the application configuration"
565
+ description: "Executes custom installation scripts defined in the application configuration",
566
+ label: "Custom Installation Steps"
566
567
  },
567
568
  uninstall: {
568
- label: "Custom Uninstallation Steps",
569
- description: "Executes custom uninstallation scripts defined in the application configuration"
569
+ description: "Executes custom uninstallation scripts defined in the application configuration",
570
+ label: "Custom Uninstallation Steps"
570
571
  }
571
572
  },
572
- when: require_webhooks.hasCustomInstallationSteps,
573
- children: []
573
+ name: "customInstallationSteps",
574
+ when: require_webhooks.hasCustomInstallationSteps
574
575
  });
575
576
  /**
576
577
  * Creates the custom installation step with dynamic children based on config.
@@ -636,370 +637,127 @@ async function throwHttpError(logger, error, prefix) {
636
637
  }
637
638
 
638
639
  //#endregion
639
- //#region source/management/installation/admin-ui-sdk/helpers.ts
640
+ //#region source/management/installation/admin-ui/helpers.ts
641
+ /**
642
+ * Enables the Admin UI SDK in Commerce via PUT /V1/adminuisdk/config.
643
+ * Must run before {@link registerExtension} so Commerce accepts the extension.
644
+ *
645
+ * @param context - The execution context providing the Admin UI client and logger.
646
+ */
647
+ async function enableAdminUiSdk(context) {
648
+ const { adminUiClient, logger } = context;
649
+ logger.info("Enabling Admin UI SDK in Adobe Commerce...");
650
+ await adminUiClient.enableAdminUiSdk().catch((error) => throwHttpError(logger, error, "Failed to enable Admin UI SDK"));
651
+ logger.info("Admin UI SDK enabled successfully.");
652
+ }
640
653
  /**
641
654
  * Registers the extension with Commerce via POST /V1/adminuisdk/extension.
642
655
  *
643
- * @param context - The execution context providing the Admin UI SDK client and logger.
656
+ * @param context - The execution context providing the Admin UI client and logger.
644
657
  */
645
658
  async function registerExtension(context) {
646
659
  const { adminUiClient, appData, logger } = context;
647
660
  const extensionName = process.env.__OW_NAMESPACE;
648
661
  if (!extensionName) throw new Error("__OW_NAMESPACE environment variable is not set");
649
- logger.info(`Registering Admin UI SDK extension: ${appData.projectName}`);
662
+ logger.info(`Registering Admin UI extension: ${appData.projectName}`);
650
663
  const { extensionId } = await adminUiClient.registerExtension({
651
664
  extensionName,
652
665
  extensionTitle: appData.projectTitle,
653
- extensionUrl: `https://${extensionName}.adobeio-static.net/index.html`,
654
666
  extensionWorkspace: appData.workspaceName
655
- }).catch((error) => throwHttpError(logger, error, "Failed to register Admin UI SDK extension"));
656
- logger.info(`Admin UI SDK extension registered successfully: ${extensionId}`);
667
+ }).catch((error) => throwHttpError(logger, error, "Failed to register Admin UI extension"));
668
+ logger.info(`Admin UI extension registered successfully: ${extensionId}`);
657
669
  }
658
670
  /**
659
671
  * Unregisters the extension from Commerce via DELETE /V1/adminuisdk/extension/:workspace_name/:extension_name.
660
672
  * Best-effort: errors are logged as warnings and do not stop the uninstall workflow.
661
673
  *
662
- * @param context - The execution context providing the Admin UI SDK client and logger.
674
+ * @param context - The execution context providing the Admin UI client and logger.
663
675
  */
664
676
  async function unregisterExtension(context) {
665
677
  const { adminUiClient, appData, logger } = context;
666
678
  const extensionName = process.env.__OW_NAMESPACE;
667
679
  if (!extensionName) {
668
- logger.warn("__OW_NAMESPACE environment variable is not set; skipping Admin UI SDK extension unregistration. Continuing uninstall.");
680
+ logger.warn("__OW_NAMESPACE environment variable is not set; skipping Admin UI extension unregistration. Continuing uninstall.");
669
681
  return;
670
682
  }
671
- logger.info(`Unregistering Admin UI SDK extension "${extensionName}" from workspace "${appData.workspaceName}"...`);
683
+ logger.info(`Unregistering Admin UI extension "${extensionName}" from workspace "${appData.workspaceName}"...`);
672
684
  try {
673
685
  await adminUiClient.unregisterExtension({
674
- workspaceName: appData.workspaceName,
675
- extensionName
686
+ extensionName,
687
+ workspaceName: appData.workspaceName
676
688
  });
677
- logger.info(`Admin UI SDK extension "${extensionName}" unregistered successfully.`);
689
+ logger.info(`Admin UI extension "${extensionName}" unregistered successfully.`);
678
690
  } catch (error) {
679
691
  const msg = await (0, _adobe_aio_commerce_lib_api_utils.unwrapHttpError)(error);
680
- logger.warn(`Failed to unregister Admin UI SDK extension "${extensionName}": ${msg}. Continuing uninstall.`);
692
+ logger.warn(`Failed to unregister Admin UI extension "${extensionName}": ${msg}. Continuing uninstall.`);
681
693
  }
682
694
  }
683
695
 
684
696
  //#endregion
685
- //#region source/management/installation/admin-ui-sdk/utils.ts
697
+ //#region source/management/installation/admin-ui/utils.ts
686
698
  function createAdminUiClient(params) {
687
699
  return (0, _adobe_aio_commerce_lib_admin_ui_api.createAdminUiApiClient)((0, _adobe_aio_commerce_lib_api.resolveCommerceHttpClientParams)(params, { tryForwardAuthProvider: true }));
688
700
  }
689
- /** Creates the Admin UI SDK step context with a lazy-initialized API client. */
690
- const createAdminUiSdkStepContext = (installation) => {
701
+ /** Creates the Admin UI step context with a lazy-initialized API client. */
702
+ const createAdminUiStepContext = (installation) => {
691
703
  const { params } = installation;
692
704
  let adminUiClient = null;
693
705
  return { get adminUiClient() {
694
- if (adminUiClient === null) adminUiClient = createAdminUiClient(params);
706
+ adminUiClient ??= createAdminUiClient(params);
695
707
  return adminUiClient;
696
708
  } };
697
709
  };
698
710
 
699
711
  //#endregion
700
- //#region source/management/installation/admin-ui-sdk/branch.ts
712
+ //#region source/management/installation/admin-ui/branch.ts
713
+ /**
714
+ * Leaf step that enables the Admin UI SDK (PUT) on install. Runs before
715
+ * {@link registerExtensionStep} so Commerce accepts the extension registration.
716
+ * Install-only: enabling the SDK is not reverted on uninstall since other
717
+ * extensions may still rely on it.
718
+ */
719
+ const enableAdminUiSdkStep = defineLeafStep({
720
+ install: (_, context) => enableAdminUiSdk(context),
721
+ meta: { install: {
722
+ description: "Enables the Admin UI SDK in Adobe Commerce",
723
+ label: "Enable Admin UI SDK"
724
+ } },
725
+ name: "enable-admin-ui-sdk"
726
+ });
701
727
  /** Leaf step that registers the extension (POST) on install and unregisters it (DELETE) on uninstall. */
702
728
  const registerExtensionStep = defineLeafStep({
703
- name: "register-extension",
729
+ install: (_, context) => registerExtension(context),
704
730
  meta: {
705
731
  install: {
706
- label: "Register Extension",
707
- description: "Registers the Admin UI SDK extension in Adobe Commerce"
732
+ description: "Registers the Admin UI extension in Adobe Commerce",
733
+ label: "Register Extension"
708
734
  },
709
735
  uninstall: {
710
- label: "Unregister Extension",
711
- description: "Removes the Admin UI SDK extension from Adobe Commerce"
736
+ description: "Removes the Admin UI extension from Adobe Commerce",
737
+ label: "Unregister Extension"
712
738
  }
713
739
  },
714
- install: (_, context) => registerExtension(context),
740
+ name: "register-extension",
715
741
  uninstall: (_, context) => unregisterExtension(context)
716
742
  });
717
- /** Branch step for setting up the Admin UI SDK extension registration. */
718
- const adminUiSdkStep = defineBranchStep({
719
- name: "admin-ui-sdk",
743
+ /** Branch step for setting up the Admin UI extension registration. */
744
+ const adminUiStep = defineBranchStep({
745
+ children: [enableAdminUiSdkStep, registerExtensionStep],
746
+ context: createAdminUiStepContext,
720
747
  meta: {
721
748
  install: {
722
- label: "Admin UI SDK",
723
- description: "Registers the extension with Adobe Commerce Admin UI SDK"
749
+ description: "Registers the extension with Adobe Commerce Admin UI",
750
+ label: "Admin UI"
724
751
  },
725
752
  uninstall: {
726
- label: "Admin UI SDK",
727
- description: "Removes the extension from Adobe Commerce Admin UI SDK"
753
+ description: "Removes the extension from Adobe Commerce Admin UI",
754
+ label: "Admin UI"
728
755
  }
729
756
  },
730
- when: require_webhooks.hasAdminUiSdk,
731
- context: createAdminUiSdkStepContext,
732
- children: [registerExtensionStep]
757
+ name: "admin-ui",
758
+ when: require_webhooks.hasAdminUi
733
759
  });
734
760
 
735
- //#endregion
736
- //#region source/management/installation/events/utils.ts
737
- const COMMERCE_PROVIDER_TYPE = "dx_commerce_events";
738
- const EXTERNAL_PROVIDER_TYPE = "3rd_party_custom_events";
739
- const PROVIDER_TYPE_TO_LABEL = {
740
- [COMMERCE_PROVIDER_TYPE]: "Commerce",
741
- [EXTERNAL_PROVIDER_TYPE]: "External"
742
- };
743
- /** Max characters taken from `metadata.id` in the I/O Events provider `instance_id`. */
744
- const METADATA_ID_MAX_LENGTH_FOR_INSTANCE_ID = 100;
745
- /**
746
- * Generates a unique instance ID for I/O Events for this app deployment.
747
- * Uses `{metadata.id (first 100 chars)}-{providerKeyOrSlug}-{workspaceId}` (lowercased).
748
- *
749
- * @param metadata - The metadata of the application
750
- * @param provider - The event provider (optional `key`, else label is slugified)
751
- * @param workspaceId - Adobe I/O Developer Console workspace ID for this deployment
752
- */
753
- function generateInstanceId(metadata, provider, workspaceId) {
754
- const appId = metadata.id.slice(0, METADATA_ID_MAX_LENGTH_FOR_INSTANCE_ID);
755
- const slugLabel = provider.label.toLowerCase().replace(/\s+/g, "-");
756
- return `${appId}-${provider.key ?? slugLabel}-${workspaceId}`.toLowerCase();
757
- }
758
- /**
759
- * Old version of instanceId generator which can be not unique within the same ORG.
760
- *
761
- * @param metadata - The metadata of the application
762
- * @param provider - The event provider for which to generate the instance ID
763
- * @deprecated use {@link generateInstanceId} instead
764
- */
765
- function generateInstanceIdDeprecated(metadata, provider) {
766
- const slugLabel = provider.label.toLowerCase().replace(/\s+/g, "-");
767
- return `${metadata.id}-${provider.key ?? slugLabel}`.toLowerCase();
768
- }
769
- /**
770
- * Find an existing event provider by its instance ID.
771
- * @param allProviders - The list of all existing event providers.
772
- * @param instanceId - The instance ID to search for.
773
- */
774
- function findExistingProvider(allProviders, instanceId) {
775
- return allProviders.find((provider) => provider.instance_id === instanceId) ?? null;
776
- }
777
- /**
778
- * Find existing event metadata by its event name.
779
- * @param allMetadata - The list of all existing event metadata.
780
- * @param eventName - The event name to search for.
781
- */
782
- function findExistingProviderMetadata(allMetadata, eventName) {
783
- return allMetadata.find((meta) => meta.event_code === eventName) ?? null;
784
- }
785
- /**
786
- * Find existing event registrations by client ID and name.
787
- * @param allRegistrations - The list of all existing event registrations.
788
- * @param clientId - The client ID of the workspace where the registration was created.
789
- * @param name - The name of the registration to search for.
790
- */
791
- function findExistingRegistrations(allRegistrations, clientId, name) {
792
- return allRegistrations.find((reg) => reg.client_id === clientId && reg.name === name);
793
- }
794
- /**
795
- * Generates a namespaced event name by combining the application ID with the event name.
796
- * @param metadata
797
- * @param name
798
- */
799
- function getNamespacedEvent(metadata, name) {
800
- return `${metadata.id}.${name}`.toLowerCase();
801
- }
802
- /**
803
- * Get the fully qualified name of an event for I/O Events based on the provider type.
804
- * @param name - The name of the event.
805
- * @param providerType - The type of the event provider.
806
- */
807
- function getIoEventCode(name, providerType) {
808
- return providerType === "dx_commerce_events" ? `com.adobe.commerce.${name}` : name;
809
- }
810
- /** Maps a provider's metadata type to its human-readable label ("Commerce" or "External"). */
811
- function getProviderTypeLabel(provider) {
812
- return PROVIDER_TYPE_TO_LABEL[provider.provider_metadata];
813
- }
814
- /**
815
- * Generates a registration name based on the provider type, provider label, and runtime action.
816
- *
817
- * Prefixes with the provider type label ("Commerce" or "External") for readability, then the
818
- * provider's own label to ensure uniqueness when multiple providers of the same type route
819
- * events to the same runtime action.
820
- *
821
- * @param provider - The provider this registration is associated to.
822
- * @param runtimeAction - The runtime action this registration points to.
823
- */
824
- function getRegistrationName(provider, runtimeAction) {
825
- const [packageName, actionName] = runtimeAction.split("/").map(kebabToTitleCase);
826
- return `${getProviderTypeLabel(provider)} Event Registration: ${provider.label} - ${actionName} (${packageName})`;
827
- }
828
- /**
829
- * Returns the registration name in the legacy format used by SDK versions that built
830
- * the name from the generic provider type label ("Commerce" / "External") rather than
831
- * the provider's own label. Used during uninstall to match registrations that were
832
- * created before the naming change.
833
- *
834
- * @param provider - The provider this registration is associated to.
835
- * @param runtimeAction - The runtime action this registration points to.
836
- * @deprecated Use {@link getRegistrationName} for all new registrations.
837
- */
838
- function getLegacyRegistrationName(provider, runtimeAction) {
839
- const [packageName, actionName] = runtimeAction.split("/").map(kebabToTitleCase);
840
- return `${getProviderTypeLabel(provider)} Event Registration: ${actionName} (${packageName})`;
841
- }
842
- /**
843
- * Generates a registration name and description based on the provider, events, and runtime action.
844
- * @param provider - The provider this registration is associated to.
845
- * @param events - The events routed by this registration.
846
- * @param runtimeAction - The runtime action this registration points to.
847
- */
848
- function getRegistrationDescription(provider, events, runtimeAction) {
849
- return [
850
- "This registration was automatically created by @adobe/aio-commerce-lib-app. ",
851
- `It belongs to the provider "${provider.label}" (instance ID: ${provider.instance_id}). `,
852
- `It routes ${events.length} event(s) to the runtime action "${runtimeAction}".`
853
- ].join("\n");
854
- }
855
- /**
856
- * Converts a kebab-case string to Title Case.
857
- * @param str - The kebab-case string to convert.
858
- */
859
- function kebabToTitleCase(str) {
860
- return str.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
861
- }
862
- /**
863
- * Groups events by their runtime actions. Since each event can have multiple
864
- * runtime actions, this function creates a mapping where each unique runtime
865
- * action points to all events that target it.
866
- *
867
- * @param events - The events to group by runtime actions.
868
- */
869
- function groupEventsByRuntimeActions(events) {
870
- const actionEventsMap = /* @__PURE__ */ new Map();
871
- for (const event of events) for (const runtimeAction of event.runtimeActions) {
872
- const existingEvents = actionEventsMap.get(runtimeAction) ?? [];
873
- actionEventsMap.set(runtimeAction, [...existingEvents, event]);
874
- }
875
- return actionEventsMap;
876
- }
877
- function findExistingSubscription(allSubscriptions, eventName) {
878
- return allSubscriptions.get(eventName) ?? null;
879
- }
880
- /**
881
- * Builds the payload to send to Commerce when configuring Eventing.
882
- * Returns `null` when no update call is needed.
883
- *
884
- * @param initialParams - Initial Commerce Eventing configuration parameters.
885
- * @param existingData - Existing Commerce Eventing state from the API.
886
- */
887
- function getCommerceEventingConfigurationUpdateParams(initialParams, existingData) {
888
- const { isDefaultProviderConfigured, isDefaultWorkspaceConfigurationEmpty } = existingData;
889
- if (isDefaultProviderConfigured && !isDefaultWorkspaceConfigurationEmpty) return null;
890
- const { workspace_configuration, ...configWithoutWorkspace } = initialParams;
891
- let updateParams = { enabled: true };
892
- if (isDefaultWorkspaceConfigurationEmpty) {
893
- if (!workspace_configuration) throw new Error("Workspace configuration is required to enable Commerce Eventing when there is not an existing one.");
894
- updateParams.workspace_configuration = workspace_configuration;
895
- }
896
- if (!isDefaultProviderConfigured) updateParams = {
897
- ...updateParams,
898
- ...configWithoutWorkspace
899
- };
900
- return updateParams;
901
- }
902
- /**
903
- * Sanitizes a Commerce Eventing identifier.
904
- * Preserves underscores, converts spaces to underscores, lowercases, and strips the rest.
905
- *
906
- * @param value - The raw identifier value to normalize.
907
- */
908
- function sanitizeEventingIdentifier(value) {
909
- return value.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, "");
910
- }
911
- /**
912
- * Creates a partially filled workspace configuration object based on the app credentials and parameters.
913
- * This configuration is used when creating an event provider in Commerce.
914
- *
915
- * @param context - The execution context containing app credentials and parameters.
916
- */
917
- function makeWorkspaceConfig(context) {
918
- const { appData, params } = context;
919
- const { consumerOrgId, orgName, projectId, projectName, projectTitle, workspaceId, workspaceName, workspaceTitle } = appData;
920
- const authParams = (0, _adobe_aio_commerce_lib_auth.resolveAuthParams)(params);
921
- if (authParams.strategy !== "ims") throw new Error("Failed to resolve IMS authentication parameters from the runtime action inputs.");
922
- const { clientId, clientSecrets, technicalAccountEmail, technicalAccountId, imsOrgId, scopes } = authParams;
923
- return { project: {
924
- id: projectId,
925
- name: projectName,
926
- title: projectTitle,
927
- org: {
928
- id: consumerOrgId,
929
- name: orgName,
930
- ims_org_id: imsOrgId
931
- },
932
- workspace: {
933
- id: workspaceId,
934
- name: workspaceName,
935
- title: workspaceTitle,
936
- action_url: `https://${process.env.__OW_NAMESPACE}.adobeioruntime.net`,
937
- app_url: `https://${process.env.__OW_NAMESPACE}.adobeio-static.net`,
938
- details: { credentials: [{
939
- id: "000000",
940
- name: `aio-${workspaceId}`,
941
- integration_type: "oauth_server_to_server",
942
- oauth_server_to_server: {
943
- client_id: clientId,
944
- client_secrets: clientSecrets,
945
- technical_account_email: technicalAccountEmail,
946
- technical_account_id: technicalAccountId,
947
- scopes: scopes.map((scope) => scope.trim())
948
- }
949
- }] }
950
- }
951
- } };
952
- }
953
- /**
954
- * Retrieves the current existing data and returns it in a normalized way.
955
- * @param context The execution context.
956
- */
957
- async function getIoEventsExistingData(context) {
958
- const { ioEventsClient, appData } = context;
959
- const appCredentials = {
960
- consumerOrgId: appData.consumerOrgId,
961
- projectId: appData.projectId,
962
- workspaceId: appData.workspaceId
963
- };
964
- const { _embedded: { providers: existingProviders } } = await ioEventsClient.getAllEventProviders({
965
- consumerOrgId: appData.consumerOrgId,
966
- withEventMetadata: true
967
- });
968
- const providersWithMetadata = existingProviders.map((providerHal) => {
969
- const { _embedded, _links, ...providerData } = providerHal;
970
- const actualMetadata = (_embedded?.eventmetadata ?? []).map(({ _embedded, _links, ...meta }) => ({
971
- ...meta,
972
- sample: _embedded?.sample_event ?? null
973
- }));
974
- return {
975
- ...providerData,
976
- metadata: actualMetadata
977
- };
978
- });
979
- const { _embedded: { registrations: registrationsHal } } = await ioEventsClient.getAllRegistrations(appCredentials);
980
- return {
981
- providersWithMetadata,
982
- registrations: registrationsHal.map(({ _links, ...reg }) => reg)
983
- };
984
- }
985
- /**
986
- * Retrieves the current existing Commerce eventing data and returns it in a normalized way.
987
- * @param context - The execution context.
988
- */
989
- async function getCommerceEventingExistingData(context) {
990
- const { commerceEventsClient } = context;
991
- const existingProviders = await commerceEventsClient.getAllEventProviders();
992
- const existingSubscriptions = await commerceEventsClient.getAllEventSubscriptions();
993
- const defaultProvider = existingProviders.find((provider) => !("id" in provider)) ?? null;
994
- const isDefaultProviderConfigured = defaultProvider !== null;
995
- return {
996
- isDefaultProviderConfigured,
997
- isDefaultWorkspaceConfigurationEmpty: isDefaultProviderConfigured ? !defaultProvider.workspace_configuration?.trim() : true,
998
- providers: existingProviders,
999
- subscriptions: new Map(existingSubscriptions.map((subscription) => [subscription.name, subscription]))
1000
- };
1001
- }
1002
-
1003
761
  //#endregion
1004
762
  //#region source/management/installation/events/helpers.ts
1005
763
  /**
@@ -1017,10 +775,10 @@ async function createIoEventProvider(params) {
1017
775
  logger.info(`Creating provider "${provider.label}" with instance ID "${provider.instanceId}"`);
1018
776
  return ioEventsClient.createEventProvider({
1019
777
  ...appCredentials,
1020
- label: provider.label,
1021
- providerType: provider.type,
778
+ description: provider.description,
1022
779
  instanceId: provider.instanceId,
1023
- description: provider.description
780
+ label: provider.label,
781
+ providerType: provider.type
1024
782
  }).then((res) => {
1025
783
  logger.info(`Provider "${provider.label}" created with ID '${res.id}'`);
1026
784
  return res;
@@ -1035,7 +793,7 @@ async function createOrGetIoEventProvider(params, existingData) {
1035
793
  const { context, provider } = params;
1036
794
  const { logger } = context;
1037
795
  const { instanceId, ...providerData } = provider;
1038
- const existing = findExistingProvider(existingData, instanceId);
796
+ const existing = require_utils.findExistingProvider(existingData, instanceId);
1039
797
  if (existing) {
1040
798
  logger.info(`Provider "${provider.label}" already exists with ID "${existing.id}", skipping creation.`);
1041
799
  return existing;
@@ -1060,14 +818,14 @@ async function createIoEventProviderEventMetadata(params) {
1060
818
  projectId: appData.projectId,
1061
819
  workspaceId: appData.workspaceId
1062
820
  };
1063
- const eventCode = getIoEventCode(getNamespacedEvent(metadata, event.name), type);
821
+ const eventCode = require_utils.getIoEventCode(require_utils.getNamespacedEvent(metadata, event.name), type);
1064
822
  logger.info(`Creating event metadata (${eventCode}) for provider "${provider.label}" (instance ID: ${provider.instance_id}))`);
1065
823
  return ioEventsClient.createEventMetadataForProvider({
1066
824
  ...appCredentials,
1067
- providerId: provider.id,
1068
- label: event.label,
1069
825
  description: event.description,
1070
- eventCode
826
+ eventCode,
827
+ label: event.label,
828
+ providerId: provider.id
1071
829
  }).then((res) => {
1072
830
  logger.info(`Event metadata "${event.label}" created for provider "${provider.label}"`);
1073
831
  return res;
@@ -1081,7 +839,7 @@ async function createIoEventProviderEventMetadata(params) {
1081
839
  async function createOrGetIoProviderEventMetadata(params, existingData) {
1082
840
  const { context, event, provider, type, metadata } = params;
1083
841
  const { logger } = context;
1084
- const existing = findExistingProviderMetadata(existingData, getIoEventCode(getNamespacedEvent(metadata, event.name), type));
842
+ const existing = require_utils.findExistingProviderMetadata(existingData, require_utils.getIoEventCode(require_utils.getNamespacedEvent(metadata, event.name), type));
1085
843
  if (existing) {
1086
844
  logger.info(`Event metadata "${event.label}" already exists for provider "${provider.label}" (instance ID: ${provider.instance_id}), skipping creation.`);
1087
845
  return existing;
@@ -1101,20 +859,20 @@ async function createIoEventRegistration(params) {
1101
859
  workspaceId: appData.workspaceId
1102
860
  };
1103
861
  logger.info(`Creating registration(s) to runtime action "${runtimeAction}" for ${events.length} event(s) with provider "${provider.label}" (instance ID: ${provider.instance_id}))`);
1104
- const name = getRegistrationName(provider, runtimeAction);
1105
- const description = getRegistrationDescription(provider, events, runtimeAction);
862
+ const name = require_utils.getRegistrationName(provider, runtimeAction);
863
+ const description = require_utils.getRegistrationDescription(provider, events, runtimeAction);
1106
864
  const payload = {
1107
865
  ...appCredentials,
1108
- name,
1109
866
  clientId: runtimeParams.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,
1110
- description,
1111
867
  deliveryType: "webhook",
1112
- runtimeAction,
868
+ description,
1113
869
  enabled: true,
1114
870
  eventsOfInterest: events.map((event) => ({
1115
- providerId: provider.id,
1116
- eventCode: getIoEventCode(getNamespacedEvent(metadata, event.name), provider.provider_metadata)
1117
- }))
871
+ eventCode: require_utils.getIoEventCode(require_utils.getNamespacedEvent(metadata, event.name), provider.provider_metadata),
872
+ providerId: provider.id
873
+ })),
874
+ name,
875
+ runtimeAction
1118
876
  };
1119
877
  return ioEventsClient.createRegistration(payload).then((res) => {
1120
878
  logger.info(`Registration "${name}" created for provider "${provider.label}" with ID '${res.id}'`);
@@ -1129,8 +887,8 @@ async function createIoEventRegistration(params) {
1129
887
  async function createOrGetIoEventRegistration(params, registrations) {
1130
888
  const { context, provider, runtimeAction } = params;
1131
889
  const { logger, params: runtimeParams } = context;
1132
- const name = getRegistrationName(provider, runtimeAction);
1133
- const existing = findExistingRegistrations(registrations, runtimeParams.AIO_COMMERCE_AUTH_IMS_CLIENT_ID, name);
890
+ const name = require_utils.getRegistrationName(provider, runtimeAction);
891
+ const existing = require_utils.findExistingRegistrations(registrations, runtimeParams.AIO_COMMERCE_AUTH_IMS_CLIENT_ID, name);
1134
892
  if (existing) {
1135
893
  logger.info(`Registration "${name}" already exists for provider "${provider.label}" with ID '${existing.id}', skipping creation.`);
1136
894
  return existing;
@@ -1146,7 +904,7 @@ async function configureCommerceEventing(params, existingData) {
1146
904
  const { context, config } = params;
1147
905
  const { commerceEventsClient, logger } = context;
1148
906
  logger.info("Starting configuration of the Commerce Eventing Module");
1149
- const updateParams = getCommerceEventingConfigurationUpdateParams(config, existingData);
907
+ const updateParams = require_utils.getCommerceEventingConfigurationUpdateParams(config, existingData);
1150
908
  if (updateParams === null) {
1151
909
  logger.info("Commerce Eventing Module is already configured, skipping configuration step.");
1152
910
  return;
@@ -1195,7 +953,7 @@ async function createOrGetCommerceProvider(params, existingProviders) {
1195
953
  logger.info(`Provider "${provider.label}" already exists with provider ID "${provider.id}", skipping creation.`);
1196
954
  return existingByProviderId;
1197
955
  }
1198
- const existingByInstanceId = findExistingProvider(existingProviders, provider.instance_id);
956
+ const existingByInstanceId = require_utils.findExistingProvider(existingProviders, provider.instance_id);
1199
957
  if (existingByInstanceId) logger.warn(`Provider "${provider.label}" exists (instance ID: ${provider.instance_id}) but with a different provider ID ("${existingByInstanceId.provider_id}" → "${provider.id}"). Registering updated provider in Commerce.`);
1200
958
  return createCommerceProvider(params);
1201
959
  }
@@ -1206,18 +964,18 @@ async function createOrGetCommerceProvider(params, existingProviders) {
1206
964
  async function createCommerceEventSubscription(params) {
1207
965
  const { context, metadata, provider, event } = params;
1208
966
  const { logger, commerceEventsClient } = context;
1209
- const eventName = getNamespacedEvent(metadata, event.config.name);
967
+ const eventName = require_utils.getNamespacedEvent(metadata, event.config.name);
1210
968
  logger.info(`Creating event subscription for event "${event.config.name}" to provider "${provider.label}" (instance ID: ${provider.instance_id})`);
1211
969
  const eventSpec = {
1212
- name: eventName,
1213
- parent: event.config.name,
1214
- fields: event.config.fields,
1215
- rules: event.config.rules,
1216
- provider_id: provider.id,
1217
970
  destination: event.config.destination,
971
+ fields: event.config.fields,
972
+ force: event.config.force,
1218
973
  hipaa_audit_required: event.config.hipaa_audit_required,
974
+ name: eventName,
975
+ parent: event.config.name,
1219
976
  priority: event.config.priority,
1220
- force: event.config.force
977
+ provider_id: provider.id,
978
+ rules: event.config.rules
1221
979
  };
1222
980
  logger.debug(`Event subscription specification for event "${event.config.name}": ${require_logging.inspect(eventSpec)}`);
1223
981
  return commerceEventsClient.createEventSubscription(eventSpec).then((_res) => {
@@ -1233,7 +991,7 @@ async function createCommerceEventSubscription(params) {
1233
991
  async function createOrGetCommerceEventSubscription(params, existingData) {
1234
992
  const { context, metadata, event } = params;
1235
993
  const { logger } = context;
1236
- const existing = findExistingSubscription(existingData, getNamespacedEvent(metadata, event.config.name));
994
+ const existing = require_utils.findExistingSubscription(existingData, require_utils.getNamespacedEvent(metadata, event.config.name));
1237
995
  if (existing) {
1238
996
  logger.info(`Subscription for event "${event.config.name}" already exists, skipping creation.`);
1239
997
  return existing;
@@ -1250,7 +1008,7 @@ async function createOrGetCommerceEventSubscription(params, existingData) {
1250
1008
  async function onboardIoEvents(params, existingData) {
1251
1009
  const { providersWithMetadata, registrations } = existingData;
1252
1010
  const { context, metadata, provider, providerType, events } = params;
1253
- const instanceId = generateInstanceId(metadata, provider, context.appData.workspaceId);
1011
+ const instanceId = require_utils.generateInstanceId(metadata, provider, context.appData.workspaceId);
1254
1012
  const providerData = await createOrGetIoEventProvider({
1255
1013
  context,
1256
1014
  provider: {
@@ -1260,26 +1018,26 @@ async function onboardIoEvents(params, existingData) {
1260
1018
  }
1261
1019
  }, providersWithMetadata);
1262
1020
  const metadataPromises = events.map((event) => createOrGetIoProviderEventMetadata({
1263
- metadata,
1264
1021
  context,
1265
- type: providerType,
1022
+ event,
1023
+ metadata,
1266
1024
  provider: providerData,
1267
- event
1025
+ type: providerType
1268
1026
  }, providersWithMetadata.find((p) => p.id === providerData.id)?.metadata ?? []));
1269
- const actionEventsMap = groupEventsByRuntimeActions(events);
1027
+ const actionEventsMap = require_utils.groupEventsByRuntimeActions(events);
1270
1028
  const registrationPromises = Array.from(actionEventsMap.entries()).map(([runtimeAction, groupedEvents]) => createOrGetIoEventRegistration({
1271
- metadata,
1272
1029
  context,
1273
1030
  events: groupedEvents,
1031
+ metadata,
1274
1032
  provider: providerData,
1275
1033
  runtimeAction
1276
1034
  }, registrations));
1277
1035
  const [metadataData, registrationsData] = await Promise.all([Promise.all(metadataPromises), Promise.all(registrationPromises)]);
1278
1036
  return {
1279
- providerData,
1280
1037
  eventsData: events.map((event, index) => {
1281
1038
  const eventRegistrations = event.runtimeActions.map((runtimeAction) => {
1282
- return registrationsData[Array.from(actionEventsMap.keys()).indexOf(runtimeAction)];
1039
+ const registrationIndex = Array.from(actionEventsMap.keys()).indexOf(runtimeAction);
1040
+ return registrationsData[registrationIndex];
1283
1041
  });
1284
1042
  return {
1285
1043
  config: {
@@ -1291,7 +1049,8 @@ async function onboardIoEvents(params, existingData) {
1291
1049
  registrations: eventRegistrations
1292
1050
  }
1293
1051
  };
1294
- })
1052
+ }),
1053
+ providerData
1295
1054
  };
1296
1055
  }
1297
1056
  /**
@@ -1302,26 +1061,24 @@ async function onboardCommerceEventing(params, existingData) {
1302
1061
  const { context, metadata, ioData } = params;
1303
1062
  const { events, provider, workspaceConfiguration } = ioData;
1304
1063
  const instanceId = provider.instance_id;
1305
- const subscriptions = [];
1306
1064
  const { workspace_configuration: _, ...commerceProviderData } = await createOrGetCommerceProvider({
1307
1065
  context,
1308
1066
  provider: {
1067
+ description: provider.description,
1309
1068
  id: provider.id,
1310
1069
  instance_id: instanceId,
1311
1070
  label: provider.label,
1312
- description: provider.description,
1313
1071
  workspace_configuration: workspaceConfiguration
1314
1072
  }
1315
1073
  }, existingData.providers);
1316
- for (const event of events) subscriptions.push(await createOrGetCommerceEventSubscription({
1317
- context,
1318
- metadata,
1319
- provider,
1320
- event
1321
- }, existingData.subscriptions));
1322
1074
  return {
1323
1075
  commerceProvider: commerceProviderData,
1324
- subscriptions
1076
+ subscriptions: await Promise.all(events.map((event) => createOrGetCommerceEventSubscription({
1077
+ context,
1078
+ event,
1079
+ metadata,
1080
+ provider
1081
+ }, existingData.subscriptions)))
1325
1082
  };
1326
1083
  }
1327
1084
  /**
@@ -1336,9 +1093,9 @@ async function deleteIoEventRegistrations(providerData, provider, events, regist
1336
1093
  projectId: appData.projectId,
1337
1094
  workspaceId: appData.workspaceId
1338
1095
  };
1339
- const actionEventsMap = groupEventsByRuntimeActions(events);
1096
+ const actionEventsMap = require_utils.groupEventsByRuntimeActions(events);
1340
1097
  const runtimeActions = Array.from(actionEventsMap.keys());
1341
- const registrationNames = new Set([...runtimeActions.map((runtimeAction) => getRegistrationName(providerData, runtimeAction)), ...runtimeActions.map((runtimeAction) => getLegacyRegistrationName(providerData, runtimeAction))]);
1098
+ const registrationNames = /* @__PURE__ */ new Set([...runtimeActions.map((runtimeAction) => require_utils.getRegistrationName(providerData, runtimeAction)), ...runtimeActions.map((runtimeAction) => require_utils.getLegacyRegistrationName(providerData, runtimeAction))]);
1342
1099
  const providerRegistrations = registrations.filter((reg) => reg.client_id === runtimeParams.AIO_COMMERCE_AUTH_IMS_CLIENT_ID && registrationNames.has(reg.name));
1343
1100
  if (providerRegistrations.length === 0) {
1344
1101
  logger.info(`No I/O Events registrations found for provider "${provider.label}" (instance ID: "${providerData.instance_id}").`);
@@ -1381,8 +1138,8 @@ async function deleteIoEventMetadata(providerData, provider, context) {
1381
1138
  try {
1382
1139
  await ioEventsClient.deleteEventMetadataForProvider({
1383
1140
  ...appCredentials,
1384
- providerId: providerData.id,
1385
- eventCode: eventMetadata.event_code
1141
+ eventCode: eventMetadata.event_code,
1142
+ providerId: providerData.id
1386
1143
  });
1387
1144
  logger.info(`Deleted event metadata "${eventMetadata.event_code}" from provider "${providerData.id}".`);
1388
1145
  } catch (error) {
@@ -1429,8 +1186,8 @@ async function deleteIoEventProvider(providerData, provider, context) {
1429
1186
  async function offboardIoEvents(params, existingData) {
1430
1187
  const { context, metadata, provider, events } = params;
1431
1188
  const { appData, logger } = context;
1432
- const instanceId = generateInstanceId(metadata, provider, appData.workspaceId);
1433
- const instanceIdOldVersion = generateInstanceIdDeprecated(metadata, provider);
1189
+ const instanceId = require_utils.generateInstanceId(metadata, provider, appData.workspaceId);
1190
+ const instanceIdOldVersion = require_utils.generateInstanceIdDeprecated(metadata, provider);
1434
1191
  const providerData = existingData.providersWithMetadata.find((p) => p.instance_id === instanceId || p.instance_id === instanceIdOldVersion);
1435
1192
  if (!providerData) {
1436
1193
  logger.info(`No I/O Events provider found with instance ID "${instanceId}", skipping offboarding.`);
@@ -1449,7 +1206,7 @@ async function deleteCommerceEventSubscriptions(events, metadata, provider, exis
1449
1206
  const { commerceEventsClient, logger } = context;
1450
1207
  logger.info(`Unsubscribing Commerce event subscriptions for provider "${provider.label}"...`);
1451
1208
  for (const event of events) {
1452
- const eventName = getNamespacedEvent(metadata, event.name);
1209
+ const eventName = require_utils.getNamespacedEvent(metadata, event.name);
1453
1210
  if (!existingSubscriptions.has(eventName)) {
1454
1211
  logger.info(`No Commerce subscription found for event "${event.name}" (namespaced: "${eventName}"), skipping.`);
1455
1212
  continue;
@@ -1471,8 +1228,8 @@ async function deleteCommerceEventSubscriptions(events, metadata, provider, exis
1471
1228
  */
1472
1229
  async function deleteCommerceEventProvider(metadata, provider, existingProviders, context) {
1473
1230
  const { commerceEventsClient, appData, logger } = context;
1474
- const instanceId = generateInstanceId(metadata, provider, appData.workspaceId);
1475
- const instanceIdOldVersion = generateInstanceIdDeprecated(metadata, provider);
1231
+ const instanceId = require_utils.generateInstanceId(metadata, provider, appData.workspaceId);
1232
+ const instanceIdOldVersion = require_utils.generateInstanceIdDeprecated(metadata, provider);
1476
1233
  const commerceProvider = existingProviders.find((p) => p.instance_id === instanceId || p.instance_id === instanceIdOldVersion);
1477
1234
  if (!commerceProvider) {
1478
1235
  logger.info(`No Commerce event provider found with instance ID "${instanceId}", skipping provider deletion.`);
@@ -1510,20 +1267,20 @@ async function offboardCommerceEventing(params, existingData) {
1510
1267
  //#region source/management/installation/events/commerce.ts
1511
1268
  /** Leaf step for installing commerce event sources. */
1512
1269
  const commerceEventsStep = defineLeafStep({
1513
- name: "commerce",
1270
+ install: createCommerceEvents,
1514
1271
  meta: {
1515
1272
  install: {
1516
- label: "Configure Commerce Events",
1517
- description: "Sets up I/O Events for Adobe Commerce event sources"
1273
+ description: "Sets up I/O Events for Adobe Commerce event sources",
1274
+ label: "Configure Commerce Events"
1518
1275
  },
1519
1276
  uninstall: {
1520
- label: "Remove Commerce Events",
1521
- description: "Removes I/O Events for Adobe Commerce event sources"
1277
+ description: "Removes I/O Events for Adobe Commerce event sources",
1278
+ label: "Remove Commerce Events"
1522
1279
  }
1523
1280
  },
1524
- when: require_webhooks.hasCommerceEvents,
1525
- install: createCommerceEvents,
1526
- uninstall: removeCommerceEvents
1281
+ name: "commerce",
1282
+ uninstall: removeCommerceEvents,
1283
+ when: require_webhooks.hasCommerceEvents
1527
1284
  });
1528
1285
  /**
1529
1286
  * Creates all needed entities for Eventing to work with Commerce and Adobe I/O Events.
@@ -1534,53 +1291,74 @@ async function createCommerceEvents(config, context) {
1534
1291
  const { logger } = context;
1535
1292
  logger.debug("Starting installation of Commerce Events with config:", config);
1536
1293
  const stepData = [];
1537
- const workspaceConfiguration = JSON.stringify(makeWorkspaceConfig(context));
1538
- const existingIoEventsData = await getIoEventsExistingData(context);
1539
- const commerceEventingExistingData = await getCommerceEventingExistingData(context);
1540
- for (let i = 0; i < config.eventing.commerce.length; i++) {
1541
- const { provider, events } = config.eventing.commerce[i];
1294
+ const env = require_environment.getInstallCommerceEnv(context.params);
1295
+ const workspaceConfiguration = JSON.stringify(require_utils.makeWorkspaceConfig(context));
1296
+ const existingIoEventsData = await require_utils.getIoEventsExistingData(context);
1297
+ const commerceEventingExistingData = await require_utils.getCommerceEventingExistingData(context);
1298
+ let eventingConfigured = false;
1299
+ const storedProviders = {};
1300
+ for (const { provider, events: providerEvents } of config.eventing.commerce) {
1301
+ const events = providerEvents.filter((event) => require_environment.appliesToEnv(event, env));
1302
+ if (events.length === 0) {
1303
+ logger.debug(`Skipping Commerce event provider "${provider.label}": no events apply to environment "${env}".`);
1304
+ continue;
1305
+ }
1542
1306
  const { providerData, eventsData } = await onboardIoEvents({
1543
1307
  context,
1308
+ events,
1544
1309
  metadata: config.metadata,
1545
1310
  provider,
1546
- events,
1547
- providerType: COMMERCE_PROVIDER_TYPE
1311
+ providerType: require_utils.COMMERCE_PROVIDER_TYPE
1548
1312
  }, existingIoEventsData);
1549
- if (i === 0) await configureCommerceEventing({
1550
- context,
1551
- config: {
1552
- enabled: true,
1553
- merchant_id: sanitizeEventingIdentifier(context.appData.orgName),
1554
- environment_id: sanitizeEventingIdentifier(context.appData.projectName),
1555
- instance_id: providerData.instance_id,
1556
- workspace_configuration: workspaceConfiguration
1557
- }
1558
- }, commerceEventingExistingData);
1313
+ if (!eventingConfigured) {
1314
+ await configureCommerceEventing({
1315
+ config: {
1316
+ enabled: true,
1317
+ environment_id: require_utils.sanitizeEventingIdentifier(context.appData.projectName),
1318
+ instance_id: providerData.instance_id,
1319
+ merchant_id: require_utils.sanitizeEventingIdentifier(context.appData.orgName),
1320
+ workspace_configuration: workspaceConfiguration
1321
+ },
1322
+ context
1323
+ }, commerceEventingExistingData);
1324
+ eventingConfigured = true;
1325
+ }
1559
1326
  const { commerceProvider, subscriptions } = await onboardCommerceEventing({
1560
1327
  context,
1561
- metadata: config.metadata,
1562
- provider,
1563
1328
  ioData: {
1564
- provider: providerData,
1565
1329
  events: eventsData,
1330
+ provider: providerData,
1566
1331
  workspaceConfiguration
1567
- }
1332
+ },
1333
+ metadata: config.metadata,
1334
+ provider
1568
1335
  }, commerceEventingExistingData);
1569
1336
  stepData.push({ provider: {
1570
1337
  config: provider,
1571
1338
  data: {
1572
- ioEvents: providerData,
1573
1339
  commerce: commerceProvider,
1574
- events: eventsData.map(({ config, data }, index) => ({
1575
- config,
1340
+ events: eventsData.map(({ config: eventConfig, data }, index) => ({
1341
+ config: eventConfig,
1576
1342
  data: {
1577
1343
  ...data,
1578
1344
  subscription: subscriptions[index]
1579
1345
  }
1580
- }))
1346
+ })),
1347
+ ioEvents: providerData
1581
1348
  }
1582
1349
  } });
1350
+ if (provider.key) storedProviders[provider.key] = {
1351
+ events: Object.fromEntries(eventsData.map(({ config: eventConfig, data: eventData }) => [eventConfig.name, {
1352
+ code: eventData.metadata.event_code,
1353
+ isPhiData: eventConfig.hipaa_audit_required ?? false
1354
+ }])),
1355
+ id: providerData.id
1356
+ };
1583
1357
  }
1358
+ await (0, _adobe_aio_commerce_lib_config.setSystemConfigByKey)(require_utils.EVENTS_STORAGE_KEY, { providers: {
1359
+ ...(await (0, _adobe_aio_commerce_lib_config.getSystemConfigByKey)("events") ?? { providers: {} }).providers,
1360
+ ...storedProviders
1361
+ } });
1584
1362
  logger.debug("Completed Commerce Events installation step.");
1585
1363
  return stepData;
1586
1364
  }
@@ -1592,19 +1370,19 @@ async function createCommerceEvents(config, context) {
1592
1370
  async function removeCommerceEvents(config, context) {
1593
1371
  const { logger } = context;
1594
1372
  logger.debug("Starting uninstall of Commerce Events with config:", config);
1595
- const [existingIoEventsData, commerceEventingExistingData] = await Promise.all([getIoEventsExistingData(context), getCommerceEventingExistingData(context)]);
1373
+ const [existingIoEventsData, commerceEventingExistingData] = await Promise.all([require_utils.getIoEventsExistingData(context), require_utils.getCommerceEventingExistingData(context)]);
1596
1374
  for (const { provider, events } of config.eventing.commerce) {
1597
1375
  await offboardCommerceEventing({
1598
1376
  context,
1377
+ events,
1599
1378
  metadata: config.metadata,
1600
- provider,
1601
- events
1379
+ provider
1602
1380
  }, commerceEventingExistingData);
1603
1381
  await offboardIoEvents({
1604
1382
  context,
1383
+ events,
1605
1384
  metadata: config.metadata,
1606
- provider,
1607
- events
1385
+ provider
1608
1386
  }, existingIoEventsData);
1609
1387
  }
1610
1388
  logger.debug("Completed Commerce Events uninstall step.");
@@ -1622,10 +1400,10 @@ function createCommerceEventsApiClient(params) {
1622
1400
  commerceClientParams.fetchOptions.timeout = 1e3 * 60 * 2;
1623
1401
  return (0, _adobe_aio_commerce_lib_events_commerce.createCustomCommerceEventsApiClient)(commerceClientParams, {
1624
1402
  createEventProvider: _adobe_aio_commerce_lib_events_commerce.createEventProvider,
1625
- getAllEventProviders: _adobe_aio_commerce_lib_events_commerce.getAllEventProviders,
1626
1403
  createEventSubscription: _adobe_aio_commerce_lib_events_commerce.createEventSubscription,
1627
1404
  deleteEventProvider: _adobe_aio_commerce_lib_events_commerce.deleteEventProvider,
1628
1405
  deleteEventSubscription: _adobe_aio_commerce_lib_events_commerce.deleteEventSubscription,
1406
+ getAllEventProviders: _adobe_aio_commerce_lib_events_commerce.getAllEventProviders,
1629
1407
  getAllEventSubscriptions: _adobe_aio_commerce_lib_events_commerce.getAllEventSubscriptions,
1630
1408
  updateEventingConfiguration: _adobe_aio_commerce_lib_events_commerce.updateEventingConfiguration
1631
1409
  });
@@ -1639,8 +1417,8 @@ function createIoEventsApiClient(params) {
1639
1417
  ioEventsClientParams.fetchOptions ??= {};
1640
1418
  ioEventsClientParams.fetchOptions.timeout = 1e3 * 60 * 2;
1641
1419
  return (0, _adobe_aio_commerce_lib_events_io_events.createCustomAdobeIoEventsApiClient)(ioEventsClientParams, {
1642
- createEventProvider: _adobe_aio_commerce_lib_events_io_events.createEventProvider,
1643
1420
  createEventMetadataForProvider: _adobe_aio_commerce_lib_events_io_events.createEventMetadataForProvider,
1421
+ createEventProvider: _adobe_aio_commerce_lib_events_io_events.createEventProvider,
1644
1422
  createRegistration: _adobe_aio_commerce_lib_events_io_events.createRegistration,
1645
1423
  deleteEventMetadataForProvider: _adobe_aio_commerce_lib_events_io_events.deleteEventMetadataForProvider,
1646
1424
  deleteEventProvider: _adobe_aio_commerce_lib_events_io_events.deleteEventProvider,
@@ -1670,20 +1448,20 @@ function createEventsStepContext(installation) {
1670
1448
  //#region source/management/installation/events/external.ts
1671
1449
  /** Leaf step for installing external event sources. */
1672
1450
  const externalEventsStep = defineLeafStep({
1673
- name: "external",
1451
+ install: createExternalEvents,
1674
1452
  meta: {
1675
1453
  install: {
1676
- label: "Configure External Events",
1677
- description: "Sets up I/O Events for external event sources"
1454
+ description: "Sets up I/O Events for external event sources",
1455
+ label: "Configure External Events"
1678
1456
  },
1679
1457
  uninstall: {
1680
- label: "Remove External Events",
1681
- description: "Removes I/O Events for external event sources"
1458
+ description: "Removes I/O Events for external event sources",
1459
+ label: "Remove External Events"
1682
1460
  }
1683
1461
  },
1684
- when: require_webhooks.hasExternalEvents,
1685
- install: createExternalEvents,
1686
- uninstall: removeExternalEvents
1462
+ name: "external",
1463
+ uninstall: removeExternalEvents,
1464
+ when: require_webhooks.hasExternalEvents
1687
1465
  });
1688
1466
  /**
1689
1467
  * Creates all needed entities for External Events to work with Adobe I/O Events.
@@ -1693,27 +1471,46 @@ const externalEventsStep = defineLeafStep({
1693
1471
  async function createExternalEvents(config, context) {
1694
1472
  const { logger } = context;
1695
1473
  logger.debug("Starting installation of External Events with config:", config);
1696
- const stepData = [];
1697
- const existingIoEventsData = await getIoEventsExistingData(context);
1698
- for (const { provider, events } of config.eventing.external) {
1474
+ const env = require_environment.getInstallCommerceEnv(context.params);
1475
+ const existingIoEventsData = await require_utils.getIoEventsExistingData(context);
1476
+ const storedProviders = {};
1477
+ const eligibleProviders = config.eventing.external.map(({ provider, events: providerEvents }) => ({
1478
+ events: providerEvents.filter((event) => require_environment.appliesToEnv(event, env)),
1479
+ provider
1480
+ })).filter(({ events, provider }) => {
1481
+ if (events.length === 0) logger.debug(`Skipping external event provider "${provider.label}": no events apply to environment "${env}".`);
1482
+ return events.length > 0;
1483
+ });
1484
+ const stepData = await Promise.all(eligibleProviders.map(async ({ provider, events }) => {
1699
1485
  const { providerData, eventsData } = await onboardIoEvents({
1700
1486
  context,
1487
+ events,
1701
1488
  metadata: config.metadata,
1702
1489
  provider,
1703
- events,
1704
- providerType: EXTERNAL_PROVIDER_TYPE
1490
+ providerType: require_utils.EXTERNAL_PROVIDER_TYPE
1705
1491
  }, existingIoEventsData);
1706
- stepData.push({ provider: {
1492
+ if (provider.key) storedProviders[provider.key] = {
1493
+ events: Object.fromEntries(eventsData.map(({ config: eventConfig, data: eventData }) => [eventConfig.name, {
1494
+ code: eventData.metadata.event_code,
1495
+ isPhiData: eventConfig.hipaa_audit_required ?? false
1496
+ }])),
1497
+ id: providerData.id
1498
+ };
1499
+ return { provider: {
1707
1500
  config: provider,
1708
1501
  data: {
1709
- ioEvents: providerData,
1710
1502
  events: {
1711
1503
  config: events,
1712
1504
  data: eventsData
1713
- }
1505
+ },
1506
+ ioEvents: providerData
1714
1507
  }
1715
- } });
1716
- }
1508
+ } };
1509
+ }));
1510
+ await (0, _adobe_aio_commerce_lib_config.setSystemConfigByKey)(require_utils.EVENTS_STORAGE_KEY, { providers: {
1511
+ ...(await (0, _adobe_aio_commerce_lib_config.getSystemConfigByKey)("events") ?? { providers: {} }).providers,
1512
+ ...storedProviders
1513
+ } });
1717
1514
  logger.debug("Completed External Events installation step.");
1718
1515
  return stepData;
1719
1516
  }
@@ -1725,12 +1522,12 @@ async function createExternalEvents(config, context) {
1725
1522
  async function removeExternalEvents(config, context) {
1726
1523
  const { logger } = context;
1727
1524
  logger.debug("Starting uninstall of External Events with config:", config);
1728
- const existingIoEventsData = await getIoEventsExistingData(context);
1525
+ const existingIoEventsData = await require_utils.getIoEventsExistingData(context);
1729
1526
  for (const { provider, events } of config.eventing.external) await offboardIoEvents({
1730
1527
  context,
1528
+ events,
1731
1529
  metadata: config.metadata,
1732
- provider,
1733
- events
1530
+ provider
1734
1531
  }, existingIoEventsData);
1735
1532
  logger.debug("Completed External Events uninstall step.");
1736
1533
  }
@@ -1739,20 +1536,20 @@ async function removeExternalEvents(config, context) {
1739
1536
  //#region source/management/installation/events/branch.ts
1740
1537
  /** Root eventing step that contains commerce and external event sub-steps. */
1741
1538
  const eventingStep = defineBranchStep({
1742
- name: "eventing",
1539
+ children: [commerceEventsStep, externalEventsStep],
1540
+ context: createEventsStepContext,
1743
1541
  meta: {
1744
1542
  install: {
1745
- label: "Eventing",
1746
- description: "Sets up the I/O Events and the Commerce events required by the application"
1543
+ description: "Sets up the I/O Events and the Commerce events required by the application",
1544
+ label: "Eventing"
1747
1545
  },
1748
1546
  uninstall: {
1749
- label: "Eventing",
1750
- description: "Removes the I/O Events and Commerce events configured by the application"
1547
+ description: "Removes the I/O Events and Commerce events configured by the application",
1548
+ label: "Eventing"
1751
1549
  }
1752
1550
  },
1753
- when: require_webhooks.hasEventing,
1754
- context: createEventsStepContext,
1755
- children: [commerceEventsStep, externalEventsStep]
1551
+ name: "eventing",
1552
+ when: require_webhooks.hasEventing
1756
1553
  });
1757
1554
 
1758
1555
  //#endregion
@@ -1805,8 +1602,9 @@ const ENVIRONMENT_STAGING = "staging";
1805
1602
  * @param context - The webhooks execution context (provides the Commerce API client and logger).
1806
1603
  */
1807
1604
  async function validateWebhookConflicts(config, context) {
1808
- const { logger, commerceWebhooksClient } = context;
1809
- const modificationWebhooks = config.webhooks.filter((entry) => entry.category === "modification");
1605
+ const { logger, commerceWebhooksClient, params } = context;
1606
+ const env = require_environment.getInstallCommerceEnv(params);
1607
+ const modificationWebhooks = config.webhooks.filter((entry) => entry.category === "modification" && require_environment.appliesToEnv(entry, env));
1810
1608
  if (modificationWebhooks.length === 0) {
1811
1609
  logger.debug("No modification webhooks to validate, skipping conflict check.");
1812
1610
  return [];
@@ -1829,9 +1627,9 @@ async function validateWebhookConflicts(config, context) {
1829
1627
  }
1830
1628
  if (conflictedWebhooks.length > 0) return [{
1831
1629
  code: "WEBHOOK_CONFLICTS",
1630
+ details: { conflictedWebhooks },
1832
1631
  message: `Webhook conflicts detected: ${conflictedWebhooks.length} webhook(s) already registered for the same method and type by another app`,
1833
- severity: "warning",
1834
- details: { conflictedWebhooks }
1632
+ severity: "warning"
1835
1633
  }];
1836
1634
  logger.info("No webhook conflicts found.");
1837
1635
  return [];
@@ -1845,19 +1643,25 @@ async function validateWebhookConflicts(config, context) {
1845
1643
  */
1846
1644
  async function createWebhookSubscriptions(config, context) {
1847
1645
  const { logger, commerceWebhooksClient, params } = context;
1848
- logger.info(`Subscribing ${config.webhooks.length} webhook(s) to Commerce...`);
1646
+ const env = require_environment.getInstallCommerceEnv(params);
1647
+ const webhooks = config.webhooks.filter((entry) => require_environment.appliesToEnv(entry, env));
1648
+ if (webhooks.length === 0) {
1649
+ logger.info("No webhooks apply to this environment, skipping subscription.");
1650
+ return { subscribedWebhooks: [] };
1651
+ }
1652
+ logger.info(`Subscribing ${webhooks.length} webhook(s) to Commerce...`);
1849
1653
  const idPrefix = buildWebhookIdPrefix(config.metadata.id);
1850
1654
  const subscribedWebhooks = [];
1851
1655
  const existingWebhooks = await commerceWebhooksClient.getWebhookList();
1852
- for (const entry of config.webhooks) {
1656
+ for (const entry of webhooks) {
1853
1657
  const { webhook } = entry;
1854
1658
  const resolvedUrl = "runtimeAction" in entry ? generateUrlForRuntimeAction(entry.runtimeAction) : entry.webhook.url;
1855
1659
  logger.debug(`Subscribing webhook "${getWebhookName(webhook)}" (runtimeAction: ${"runtimeAction" in entry ? entry.runtimeAction : "none"})`);
1856
1660
  const resolvedWebhook = {
1857
1661
  ...webhook,
1858
- url: resolvedUrl,
1859
1662
  batch_name: `${idPrefix}${webhook.batch_name}`,
1860
1663
  hook_name: `${idPrefix}${webhook.hook_name}`,
1664
+ url: resolvedUrl,
1861
1665
  ..."runtimeAction" in entry && entry.requireAdobeAuth !== false && { developer_console_oauth: resolveDeveloperConsoleOAuthCredentials(params) }
1862
1666
  };
1863
1667
  subscribedWebhooks.push(await createOrGetWebhookSubscription(existingWebhooks, commerceWebhooksClient, resolvedWebhook, logger));
@@ -1876,17 +1680,15 @@ async function deleteWebhookSubscriptions(config, context) {
1876
1680
  const { logger, commerceWebhooksClient } = context;
1877
1681
  logger.info(`Unsubscribing ${config.webhooks.length} webhook(s) from Commerce...`);
1878
1682
  const idPrefix = buildWebhookIdPrefix(config.metadata.id);
1879
- const unsubscribedWebhooks = [];
1880
1683
  const existingWebhooks = await commerceWebhooksClient.getWebhookList();
1684
+ const unsubscribedWebhooks = [];
1881
1685
  for (const entry of config.webhooks) {
1882
1686
  const { webhook } = entry;
1883
- const resolvedBatch = `${idPrefix}${webhook.batch_name}`;
1884
- const resolvedHook = `${idPrefix}${webhook.hook_name}`;
1885
1687
  const params = {
1688
+ batch_name: `${idPrefix}${webhook.batch_name}`,
1689
+ hook_name: `${idPrefix}${webhook.hook_name}`,
1886
1690
  webhook_method: webhook.webhook_method,
1887
- webhook_type: webhook.webhook_type,
1888
- batch_name: resolvedBatch,
1889
- hook_name: resolvedHook
1691
+ webhook_type: webhook.webhook_type
1890
1692
  };
1891
1693
  if (!isWebhookInList(existingWebhooks, params)) {
1892
1694
  logger.debug(`Webhook not found, skipping unsubscribe: ${getWebhookName(webhook)}`);
@@ -1960,8 +1762,8 @@ function resolveDeveloperConsoleOAuthCredentials(params) {
1960
1762
  return {
1961
1763
  client_id: clientId,
1962
1764
  client_secret: clientSecrets[0],
1963
- org_id: imsOrgId,
1964
- environment: !imsEnvironment || String(imsEnvironment).startsWith("prod") ? ENVIRONMENT_PRODUCTION : ENVIRONMENT_STAGING
1765
+ environment: !imsEnvironment || String(imsEnvironment).startsWith("prod") ? ENVIRONMENT_PRODUCTION : ENVIRONMENT_STAGING,
1766
+ org_id: imsOrgId
1965
1767
  };
1966
1768
  }
1967
1769
  /**
@@ -2028,39 +1830,39 @@ function getWebhookName(webhook) {
2028
1830
  //#endregion
2029
1831
  //#region source/management/installation/webhooks/branch.ts
2030
1832
  const subscriptionsStep = defineLeafStep({
2031
- name: "subscriptions",
1833
+ install: (config, context) => createWebhookSubscriptions(config, context),
2032
1834
  meta: {
2033
1835
  install: {
2034
- label: "Create Subscriptions",
2035
- description: "Creates webhook subscriptions in Adobe Commerce"
1836
+ description: "Creates webhook subscriptions in Adobe Commerce",
1837
+ label: "Create Subscriptions"
2036
1838
  },
2037
1839
  uninstall: {
2038
- label: "Delete Subscriptions",
2039
- description: "Deletes webhook subscriptions from Adobe Commerce"
1840
+ description: "Deletes webhook subscriptions from Adobe Commerce",
1841
+ label: "Delete Subscriptions"
2040
1842
  }
2041
1843
  },
2042
- validate: (config, context) => validateWebhookConflicts(config, context),
2043
- install: (config, context) => createWebhookSubscriptions(config, context),
1844
+ name: "subscriptions",
2044
1845
  uninstall: async (config, context) => {
2045
1846
  await deleteWebhookSubscriptions(config, context);
2046
- }
1847
+ },
1848
+ validate: (config, context) => validateWebhookConflicts(config, context)
2047
1849
  });
2048
1850
  /** Branch step for setting up Commerce webhooks. */
2049
1851
  const webhooksStep = defineBranchStep({
2050
- name: "webhooks",
1852
+ children: [subscriptionsStep],
1853
+ context: createWebhooksStepContext,
2051
1854
  meta: {
2052
1855
  install: {
2053
- label: "Webhooks",
2054
- description: "Sets up Commerce webhooks"
1856
+ description: "Sets up Commerce webhooks",
1857
+ label: "Webhooks"
2055
1858
  },
2056
1859
  uninstall: {
2057
- label: "Webhooks",
2058
- description: "Removes Commerce webhooks"
1860
+ description: "Removes Commerce webhooks",
1861
+ label: "Webhooks"
2059
1862
  }
2060
1863
  },
2061
- when: require_webhooks.hasWebhooks,
2062
- context: createWebhooksStepContext,
2063
- children: [subscriptionsStep]
1864
+ name: "webhooks",
1865
+ when: require_webhooks.hasWebhooks
2064
1866
  });
2065
1867
 
2066
1868
  //#endregion
@@ -2072,7 +1874,7 @@ function createDefaultChildSteps(config) {
2072
1874
  return [
2073
1875
  eventingStep,
2074
1876
  webhooksStep,
2075
- adminUiSdkStep,
1877
+ adminUiStep,
2076
1878
  createCustomInstallationStep(config)
2077
1879
  ];
2078
1880
  }
@@ -2081,12 +1883,12 @@ function createDefaultChildSteps(config) {
2081
1883
  */
2082
1884
  function createRootInstallationStep(config) {
2083
1885
  return defineBranchStep({
2084
- name: "installation",
1886
+ children: createDefaultChildSteps(config),
2085
1887
  meta: { install: {
2086
- label: "Installation",
2087
- description: "App installation workflow"
1888
+ description: "App installation workflow",
1889
+ label: "Installation"
2088
1890
  } },
2089
- children: createDefaultChildSteps(config)
1891
+ name: "installation"
2090
1892
  });
2091
1893
  }
2092
1894
  /**
@@ -2094,12 +1896,12 @@ function createRootInstallationStep(config) {
2094
1896
  */
2095
1897
  function createRootUninstallationStep(config) {
2096
1898
  return defineBranchStep({
2097
- name: "uninstallation",
1899
+ children: createDefaultChildSteps(config),
2098
1900
  meta: { install: {
2099
- label: "Uninstallation",
2100
- description: "App uninstallation workflow"
1901
+ description: "App uninstallation workflow",
1902
+ label: "Uninstallation"
2101
1903
  } },
2102
- children: createDefaultChildSteps(config)
1904
+ name: "uninstallation"
2103
1905
  });
2104
1906
  }
2105
1907
 
@@ -2113,8 +1915,8 @@ function createRootUninstallationStep(config) {
2113
1915
  function createInitialInstallationState(options) {
2114
1916
  const { config } = options;
2115
1917
  return createInitialState({
2116
- rootStep: createRootInstallationStep(config),
2117
- config
1918
+ config,
1919
+ rootStep: createRootInstallationStep(config)
2118
1920
  });
2119
1921
  }
2120
1922
  /**
@@ -2127,36 +1929,37 @@ async function runInstallation(options) {
2127
1929
  const { installationContext, config, initialState, hooks } = options;
2128
1930
  const rootStep = createRootInstallationStep(config);
2129
1931
  const firstResult = await executeWorkflow({
2130
- rootStep,
2131
- installationContext,
2132
1932
  config,
2133
- initialState,
2134
1933
  hooks: {
2135
1934
  ...hooks,
2136
1935
  onInstallationFailure: void 0,
2137
1936
  onStepFailure: void 0
2138
- }
1937
+ },
1938
+ initialState,
1939
+ installationContext,
1940
+ rootStep
2139
1941
  });
2140
1942
  if (firstResult.status === "succeeded") return firstResult;
2141
1943
  const { error } = firstResult;
2142
1944
  installationContext.logger.warn(`Installation attempt 1 failed: step "${error.path.join(".")}", key "${error.key}"${error.message ? `, message "${error.message}"` : ""}. Retrying once.`);
1945
+ const retryState = createRetryState(firstResult);
2143
1946
  return {
2144
1947
  ...await executeWorkflow({
2145
- rootStep,
2146
- installationContext,
2147
1948
  config,
2148
- initialState: createRetryState(firstResult),
2149
1949
  hooks: hooks && {
2150
1950
  ...hooks,
2151
- onInstallationSuccess: (state) => hooks.onInstallationSuccess?.({
1951
+ onInstallationFailure: (state) => hooks.onInstallationFailure?.({
2152
1952
  ...state,
2153
1953
  metadata: { isRetry: true }
2154
1954
  }),
2155
- onInstallationFailure: (state) => hooks.onInstallationFailure?.({
1955
+ onInstallationSuccess: (state) => hooks.onInstallationSuccess?.({
2156
1956
  ...state,
2157
1957
  metadata: { isRetry: true }
2158
1958
  })
2159
- }
1959
+ },
1960
+ initialState: retryState,
1961
+ installationContext,
1962
+ rootStep
2160
1963
  }),
2161
1964
  metadata: { isRetry: true }
2162
1965
  };
@@ -2167,9 +1970,9 @@ async function runInstallation(options) {
2167
1970
  function createInitialUninstallationState(options) {
2168
1971
  const { config } = options;
2169
1972
  return createInitialState({
2170
- rootStep: createRootUninstallationStep(config),
2171
1973
  config,
2172
- mode: "uninstall"
1974
+ mode: "uninstall",
1975
+ rootStep: createRootUninstallationStep(config)
2173
1976
  });
2174
1977
  }
2175
1978
  /**
@@ -2178,11 +1981,11 @@ function createInitialUninstallationState(options) {
2178
1981
  function runUninstallation(options) {
2179
1982
  const { installationContext, config, initialState, hooks } = options;
2180
1983
  return executeUninstallWorkflow({
2181
- rootStep: createRootUninstallationStep(config),
2182
- installationContext,
2183
1984
  config,
1985
+ hooks,
2184
1986
  initialState,
2185
- hooks
1987
+ installationContext,
1988
+ rootStep: createRootUninstallationStep(config)
2186
1989
  });
2187
1990
  }
2188
1991
  /**
@@ -2196,9 +1999,9 @@ function runUninstallation(options) {
2196
1999
  function runValidation(options) {
2197
2000
  const { validationContext, config } = options;
2198
2001
  return validateStepTree({
2002
+ config,
2199
2003
  rootStep: createRootInstallationStep(config),
2200
- validationContext,
2201
- config
2004
+ validationContext
2202
2005
  });
2203
2006
  }
2204
2007