@adobe/aio-commerce-lib-app 2.2.0 → 2.3.0-alpha-20261203134759

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 (102) hide show
  1. package/CHANGELOG.md +44 -1
  2. package/bin/cli.mjs +22 -1
  3. package/dist/cjs/actions/app-config/index.cjs +8 -8
  4. package/dist/cjs/actions/app-config/index.d.cts +2 -2
  5. package/dist/cjs/actions/association/index.cjs +4 -4
  6. package/dist/cjs/actions/config/index.cjs +19 -8
  7. package/dist/cjs/actions/config/index.d.cts +1 -1
  8. package/dist/cjs/actions/installation/index.cjs +39 -15
  9. package/dist/cjs/actions/installation/index.d.cts +3 -3
  10. package/dist/cjs/actions/scope-tree/index.cjs +6 -6
  11. package/dist/cjs/{app-B3bAEor-.d.cts → app-Cb6-5mKk.d.cts} +637 -45
  12. package/dist/cjs/config/index.browser.d.cts +1 -1
  13. package/dist/cjs/config/index.node.cjs +11 -7
  14. package/dist/cjs/config/index.node.d.cts +150 -14
  15. package/dist/cjs/{define-eBMdGAq6.d.cts → define-Dk0uzfO9.d.cts} +1 -1
  16. package/dist/cjs/{commands → deprecated/commands}/index.cjs +1828 -864
  17. package/dist/cjs/{environment-CW6M76gS.cjs → environment-CaV1hi2-.cjs} +1 -1
  18. package/dist/cjs/{index-BEeludy0.d.cts → index-Cmxlkzpm.d.cts} +2 -2
  19. package/dist/cjs/index.cjs +3 -3
  20. package/dist/cjs/index.d.cts +1 -1
  21. package/dist/cjs/index.node-QXhLROom.cjs +117 -0
  22. package/dist/cjs/{logging-Emi7P923.cjs → logging-r-r2bUWO.cjs} +1 -1
  23. package/dist/cjs/management/index.cjs +1 -1
  24. package/dist/cjs/management/index.d.cts +1 -1
  25. package/dist/cjs/{management-5Et1mEUp.cjs → management-BX9sUQw-.cjs} +123 -108
  26. package/dist/cjs/{openapi-DghfuM8S.cjs → openapi-BaKoO7GY.cjs} +177 -26
  27. package/dist/cjs/{index.node-9bfp79rs.cjs → parser-XcHKOYKN.cjs} +46 -16
  28. package/dist/cjs/project/index.cjs +637 -0
  29. package/dist/cjs/project/index.d.cts +212 -0
  30. package/dist/cjs/{rolldown-runtime-CoOt0iuZ.cjs → rolldown-runtime-BKfnhsn2.cjs} +4 -4
  31. package/dist/cjs/{schemas-B6ITl1bG.cjs → schemas-B-jCi6Oz.cjs} +1 -1
  32. package/dist/cjs/{utils-CoR_PBHz.cjs → utils-CuzJBLgo.cjs} +2 -2
  33. package/dist/cjs/{utils-DSS0XlXq.cjs → utils-bwFwJcPW.cjs} +1 -1
  34. package/dist/cjs/{validate-BC3rnRLc.cjs → validate-BumkVjJy.cjs} +22 -6
  35. package/dist/cjs/{version-5MonNzl5.cjs → version-Bczstmvz.cjs} +3 -3
  36. package/dist/{es/webhooks-DgaLfP36.d.mts → cjs/webhooks-BBuoVWq_.d.cts} +382 -43
  37. package/dist/cjs/{webhooks-ZPh2gVb3.cjs → webhooks-VZTBeI8L.cjs} +84 -23
  38. package/dist/es/actions/app-config/index.d.mts +2 -2
  39. package/dist/es/actions/app-config/index.mjs +6 -6
  40. package/dist/es/actions/association/index.mjs +3 -3
  41. package/dist/es/actions/config/index.d.mts +2 -2
  42. package/dist/es/actions/config/index.mjs +19 -8
  43. package/dist/es/actions/installation/index.d.mts +4 -4
  44. package/dist/es/actions/installation/index.mjs +38 -14
  45. package/dist/es/actions/scope-tree/index.mjs +5 -5
  46. package/dist/es/{app-B3bAEor-.d.mts → app-Cb6-5mKk.d.mts} +637 -45
  47. package/dist/es/config/index.browser.d.mts +1 -1
  48. package/dist/es/config/index.node.d.mts +151 -15
  49. package/dist/es/config/index.node.mjs +5 -4
  50. package/dist/es/{define-BdXyLAwb.d.mts → define-D7EjSr-Z.d.mts} +1 -1
  51. package/dist/es/{commands → deprecated/commands}/index.mjs +1773 -807
  52. package/dist/es/{environment-DUhU0_9z.mjs → environment-B1JJFHZw.mjs} +1 -1
  53. package/dist/es/{index-DE2KVXfH.d.mts → index-BkqV8WU_.d.mts} +4 -4
  54. package/dist/es/{index-DUJtT78x.d.mts → index-U7CXicoW.d.mts} +1 -1
  55. package/dist/es/index.d.mts +2 -2
  56. package/dist/es/index.mjs +3 -3
  57. package/dist/es/index.node-DipCrOq_.mjs +112 -0
  58. package/dist/es/management/index.d.mts +1 -1
  59. package/dist/es/management/index.mjs +1 -1
  60. package/dist/es/{management-BAQ64OyR.mjs → management-DSu69_ub.mjs} +128 -113
  61. package/dist/es/{openapi-BvPVTUMt.mjs → openapi-ChihLuvm.mjs} +177 -26
  62. package/dist/es/{index.node-CURztkP5.mjs → parser-DdhiGXVf.mjs} +33 -15
  63. package/dist/es/project/index.d.mts +212 -0
  64. package/dist/es/project/index.mjs +636 -0
  65. package/dist/es/{utils-DB8HaSj0.mjs → utils-Bg_LIAGV.mjs} +2 -2
  66. package/dist/es/{validate-xS9Dc-4m.mjs → validate-CYWj7Nzp.mjs} +10 -6
  67. package/dist/es/{version-BWgrh_QM.mjs → version-CVSRkbJP.mjs} +1 -1
  68. package/dist/es/{webhooks-HBe_DEKA.mjs → webhooks-Ba-OdU8e.mjs} +76 -21
  69. package/dist/{cjs/webhooks-DNLuuv9_.d.cts → es/webhooks-Deujdgcm.d.mts} +382 -43
  70. package/package.json +29 -24
  71. /package/dist/cjs/{commands → deprecated/commands}/index.d.cts +0 -0
  72. /package/dist/cjs/{commands → deprecated/commands}/templates/typescript/webpack-config.cjs +0 -0
  73. /package/dist/cjs/{commands → project}/templates/admin-ui/tsconfig.json +0 -0
  74. /package/dist/cjs/{commands → project}/templates/admin-ui/web-src/.babelrc +0 -0
  75. /package/dist/cjs/{commands → project}/templates/admin-ui/web-src/index.css +0 -0
  76. /package/dist/cjs/{commands → project}/templates/admin-ui/web-src/index.html +0 -0
  77. /package/dist/cjs/{commands → project}/templates/admin-ui/web-src/src/app.jsx +0 -0
  78. /package/dist/cjs/{commands → project}/templates/admin-ui/web-src/src/components/welcome.jsx +0 -0
  79. /package/dist/cjs/{commands → project}/templates/admin-ui/web-src/src/pages/main-page.jsx +0 -0
  80. /package/dist/cjs/{commands → project}/templates/admin-ui/web-src-template.d.ts +0 -0
  81. /package/dist/cjs/{commands → project}/templates/app-management/app-config.js.template +0 -0
  82. /package/dist/cjs/{commands → project}/templates/app-management/association.js.template +0 -0
  83. /package/dist/cjs/{commands → project}/templates/app-management/custom-scripts.js.template +0 -0
  84. /package/dist/cjs/{commands → project}/templates/app-management/installation.js.template +0 -0
  85. /package/dist/cjs/{commands → project}/templates/business-configuration/config.js.template +0 -0
  86. /package/dist/cjs/{commands → project}/templates/business-configuration/scope-tree.js.template +0 -0
  87. /package/dist/es/{commands → deprecated/commands}/index.d.mts +0 -0
  88. /package/dist/es/{commands → deprecated/commands}/templates/typescript/webpack-config.cjs +0 -0
  89. /package/dist/es/{commands → project}/templates/admin-ui/tsconfig.json +0 -0
  90. /package/dist/es/{commands → project}/templates/admin-ui/web-src/.babelrc +0 -0
  91. /package/dist/es/{commands → project}/templates/admin-ui/web-src/index.css +0 -0
  92. /package/dist/es/{commands → project}/templates/admin-ui/web-src/index.html +0 -0
  93. /package/dist/es/{commands → project}/templates/admin-ui/web-src/src/app.jsx +0 -0
  94. /package/dist/es/{commands → project}/templates/admin-ui/web-src/src/components/welcome.jsx +0 -0
  95. /package/dist/es/{commands → project}/templates/admin-ui/web-src/src/pages/main-page.jsx +0 -0
  96. /package/dist/es/{commands → project}/templates/admin-ui/web-src-template.d.ts +0 -0
  97. /package/dist/es/{commands → project}/templates/app-management/app-config.js.template +0 -0
  98. /package/dist/es/{commands → project}/templates/app-management/association.js.template +0 -0
  99. /package/dist/es/{commands → project}/templates/app-management/custom-scripts.js.template +0 -0
  100. /package/dist/es/{commands → project}/templates/app-management/installation.js.template +0 -0
  101. /package/dist/es/{commands → project}/templates/business-configuration/config.js.template +0 -0
  102. /package/dist/es/{commands → project}/templates/business-configuration/scope-tree.js.template +0 -0
@@ -13,45 +13,45 @@
13
13
  * governing permissions and limitations under the License.
14
14
  */
15
15
 
16
- const require_rolldown_runtime = require("../rolldown-runtime-CoOt0iuZ.cjs");
17
- const require_index_node = require("../index.node-9bfp79rs.cjs");
18
- const require_webhooks = require("../webhooks-ZPh2gVb3.cjs");
19
- const require_validate = require("../validate-BC3rnRLc.cjs");
20
- const require_utils = require("../utils-DSS0XlXq.cjs");
21
- const require_schemas = require("../schemas-B6ITl1bG.cjs");
22
- const require_logging = require("../logging-Emi7P923.cjs");
23
- let _adobe_aio_commerce_lib_config = require("@adobe/aio-commerce-lib-config");
16
+ const require_rolldown_runtime = require("../../rolldown-runtime-BKfnhsn2.cjs");
24
17
  let _adobe_aio_commerce_lib_core_error = require("@adobe/aio-commerce-lib-core/error");
25
- let valibot = require("valibot");
26
- valibot = require_rolldown_runtime.__toESM(valibot, 1);
27
18
  let consola = require("consola");
28
- consola = require_rolldown_runtime.__toESM(consola, 1);
19
+ const require_parser = require("../../parser-XcHKOYKN.cjs");
20
+ const require_webhooks = require("../../webhooks-VZTBeI8L.cjs");
21
+ const require_validate = require("../../validate-BumkVjJy.cjs");
29
22
  let fs = require("fs");
30
23
  let fs_promises = require("fs/promises");
31
24
  let path = require("path");
32
- path = require_rolldown_runtime.__toESM(path, 1);
33
25
  let consola_utils = require("consola/utils");
34
26
  let url = require("url");
35
27
  let child_process = require("child_process");
28
+ let _adobe_aio_commerce_lib_config = require("@adobe/aio-commerce-lib-config");
36
29
  let prettier = require("prettier");
37
- prettier = require_rolldown_runtime.__toESM(prettier, 1);
38
30
  let yaml = require("yaml");
39
31
  let safe_stable_stringify = require("safe-stable-stringify");
32
+ let _adobe_aio_commerce_lib_core_responses = require("@adobe/aio-commerce-lib-core/responses");
40
33
  let os = require("os");
41
34
  let net = require("net");
42
- net = require_rolldown_runtime.__toESM(net, 1);
43
35
  let _adobe_aio_lib_ims = require("@adobe/aio-lib-ims");
44
- _adobe_aio_lib_ims = require_rolldown_runtime.__toESM(_adobe_aio_lib_ims, 1);
45
- let _adobe_aio_lib_core_config = require("@adobe/aio-lib-core-config");
46
- _adobe_aio_lib_core_config = require_rolldown_runtime.__toESM(_adobe_aio_lib_core_config, 1);
36
+ const require_utils = require("../../utils-bwFwJcPW.cjs");
37
+ let valibot = require("valibot");
47
38
  let ky = require("ky");
39
+ const require_schemas = require("../../schemas-B-jCi6Oz.cjs");
40
+ let _adobe_aio_commerce_lib_core_commerce = require("@adobe/aio-commerce-lib-core/commerce");
41
+ let _adobe_aio_lib_core_config = require("@adobe/aio-lib-core-config");
42
+ let util = require("util");
43
+ let _adobe_aio_cli_lib_app_config = require("@adobe/aio-cli-lib-app-config");
44
+ const require_logging = require("../../logging-r-r2bUWO.cjs");
45
+ const require_index_node = require("../../index.node-QXhLROom.cjs");
46
+ consola = require_rolldown_runtime.__toESM(consola, 1);
47
+ prettier = require_rolldown_runtime.__toESM(prettier, 1);
48
+ net = require_rolldown_runtime.__toESM(net, 1);
49
+ _adobe_aio_lib_ims = require_rolldown_runtime.__toESM(_adobe_aio_lib_ims, 1);
50
+ valibot = require_rolldown_runtime.__toESM(valibot, 1);
48
51
  ky = require_rolldown_runtime.__toESM(ky, 1);
49
- let _adobe_aio_commerce_lib_core_responses = require("@adobe/aio-commerce-lib-core/responses");
50
- let timers_promises = require("timers/promises");
51
- let dotenv = require("dotenv");
52
- dotenv = require_rolldown_runtime.__toESM(dotenv, 1);
52
+ _adobe_aio_lib_core_config = require_rolldown_runtime.__toESM(_adobe_aio_lib_core_config, 1);
53
53
 
54
- // source/commands/constants.ts
54
+ // source/deprecated/commands/constants.ts
55
55
  /** The name of the package containing all the generated runtime actions */
56
56
  const PACKAGE_NAME = "app-management";
57
57
  /** The path to the directory containing the generated files */
@@ -97,7 +97,7 @@ const CONFIG_SCHEMA_FILE_NAME = "configuration-schema.json";
97
97
  /** The name of the project package file */
98
98
  const PACKAGE_JSON_FILE = "package.json";
99
99
  /** The name of the app configuration file */
100
- const APP_CONFIG_FILE = "app.config.yaml";
100
+ const APP_CONFIG_FILE$1 = "app.config.yaml";
101
101
  /** The name of the install configuration file */
102
102
  const INSTALL_YAML_FILE = "install.yaml";
103
103
  /** Get the path to the extension point folder */
@@ -105,16 +105,14 @@ function getExtensionPointFolderPath(extensionPointId) {
105
105
  return `src/${extensionPointId.replaceAll("/", "-")}`;
106
106
  }
107
107
 
108
- // source/commands/generate/actions/constants.ts
109
- const __filename$1 = (0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href);
110
- const __dirname$1 = (0, path.dirname)(__filename$1);
111
- /** The path to the action templates directory, sibling to this file. */
112
- const TEMPLATES_DIR = (0, path.join)(__dirname$1, "templates");
113
- const CUSTOM_IMPORTS_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_IMPORTS}}";
114
- const CUSTOM_SCRIPTS_MAP_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_MAP}}";
115
- const CUSTOM_SCRIPTS_LOADER_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_LOADER}}";
108
+ // source/deprecated/commands/templates-dir.ts
109
+ const MODULE_DIR = (0, path.dirname)((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
110
+ /** The generation templates. */
111
+ const TEMPLATES_DIR = (0, path.join)(MODULE_DIR, "..", "..", "project", "templates");
112
+ /** The TypeScript build templates, which only the deprecated commands use. */
113
+ const TYPESCRIPT_TEMPLATES_DIR = (0, path.join)(MODULE_DIR, "templates", "typescript");
116
114
 
117
- // source/commands/utils.ts
115
+ // source/deprecated/commands/utils.ts
118
116
  /** Format file content using prettier, inferring the parser from the file path. */
119
117
  function prettierFormat(content, filepath) {
120
118
  return prettier.format(content, {
@@ -135,7 +133,7 @@ function prettierFormat(content, filepath) {
135
133
  * @param projectRoot - Resolved project root containing the app configuration.
136
134
  */
137
135
  async function loadAppManifest(projectRoot) {
138
- const appConfig = await require_index_node.parseCommerceAppConfig(projectRoot);
136
+ const appConfig = await require_parser.parseCommerceAppConfig(projectRoot);
139
137
  consola.default.debug("Loaded app commerce config");
140
138
  return appConfig;
141
139
  }
@@ -150,7 +148,7 @@ function runInstall(packageManager, dependencies, cwd = process.cwd(), options =
150
148
  if (dependencies.length === 0) return;
151
149
  const dependencyListString = dependencies.map((dependency) => ` - ${dependency}`).join("\n");
152
150
  consola.default.start([`Installing the following dependencies with ${packageManager}:\n${dependencyListString}\n`, "This may take a few seconds...\n"].join("\n"));
153
- const { command, args } = require_index_node.getInstallCommand(packageManager, dependencies, options);
151
+ const { command, args } = require_parser.getInstallCommand(packageManager, dependencies, options);
154
152
  const displayCommand = [command, ...args].join(" ");
155
153
  const result = (0, child_process.spawnSync)(command, args, {
156
154
  cwd,
@@ -167,7 +165,7 @@ function runInstall(packageManager, dependencies, cwd = process.cwd(), options =
167
165
  */
168
166
  function runProjectInstall(packageManager, cwd = process.cwd()) {
169
167
  consola.default.start([`Installing project dependencies with ${packageManager}...`, "This may take a few seconds...\n"].join("\n"));
170
- const { command, args } = require_index_node.getProjectInstallCommand(packageManager);
168
+ const { command, args } = require_parser.getProjectInstallCommand(packageManager);
171
169
  const displayCommand = [command, ...args].join(" ");
172
170
  const result = (0, child_process.spawnSync)(command, args, {
173
171
  cwd,
@@ -191,7 +189,7 @@ function hasDynamicAppConfig(appConfig) {
191
189
  * @param projectRoot - Resolved project root containing the source config.
192
190
  */
193
191
  async function requiresJavaScriptAppConfig(appConfig, projectRoot) {
194
- return hasDynamicAppConfig(appConfig) || await require_index_node.hasNamedCommerceAppConfigExports(projectRoot);
192
+ return hasDynamicAppConfig(appConfig) || await require_parser.hasNamedCommerceAppConfigExports(projectRoot);
195
193
  }
196
194
  /**
197
195
  * Path to an extension point's `.generated` directory, relative to the project root.
@@ -238,7 +236,7 @@ function getSchemaPath() {
238
236
  return (0, path.join)(getGeneratedDir(CONFIGURATION_EXTENSION_POINT_ID), CONFIG_SCHEMA_FILE_NAME);
239
237
  }
240
238
 
241
- // source/commands/typescript.ts
239
+ // source/deprecated/commands/typescript.ts
242
240
  const WEBPACK_CONFIG_PATTERN = /^webpack-config\.(?:cjs|js)$/u;
243
241
  const WEBPACK_CONFIG_FILE = "webpack-config.cjs";
244
242
  const TSCONFIG_FILE = "tsconfig.json";
@@ -285,7 +283,7 @@ async function scaffoldWebpackConfig(projectRoot) {
285
283
  consola.consola.info(`Found ${existingConfig.name}; leaving it unchanged.`);
286
284
  return;
287
285
  }
288
- await (0, fs_promises.copyFile)((0, path.join)(TEMPLATES_DIR, "typescript", WEBPACK_CONFIG_FILE), (0, path.join)(projectRoot, WEBPACK_CONFIG_FILE));
286
+ await (0, fs_promises.copyFile)((0, path.join)(TYPESCRIPT_TEMPLATES_DIR, WEBPACK_CONFIG_FILE), (0, path.join)(projectRoot, WEBPACK_CONFIG_FILE));
289
287
  }
290
288
  /**
291
289
  * Create the Runtime actions TypeScript configuration when it does not exist.
@@ -301,7 +299,7 @@ async function scaffoldTypeScriptConfig(projectRoot) {
301
299
  * @param projectRoot Project root directory.
302
300
  */
303
301
  async function installTypeScriptDependencies(packageManager, projectRoot) {
304
- const installPlan = await require_index_node.getPackageDependencyInstallPlan(TYPESCRIPT_DEV_DEPENDENCIES, projectRoot);
302
+ const installPlan = await require_parser.getPackageDependencyInstallPlan(TYPESCRIPT_DEV_DEPENDENCIES, projectRoot);
305
303
  if (installPlan.incompatible.length > 0) {
306
304
  const dependencies = installPlan.incompatible.map(({ name, version, installedVersion }) => `${name}@${installedVersion} does not satisfy ${version}`).join("\n");
307
305
  throw new Error(`Cannot configure TypeScript because installed dependencies are incompatible:\n${dependencies}`);
@@ -325,14 +323,14 @@ async function scaffoldTypeScriptProject(packageManager, projectRoot) {
325
323
  * @param projectRoot Resolved project root.
326
324
  */
327
325
  async function syncTypecheckScript(scriptName, command, projectRoot) {
328
- const pkg = await require_index_node.loadPackageJson(projectRoot);
326
+ const pkg = await require_parser.loadPackageJson(projectRoot);
329
327
  if (pkg === null) throw new Error("Could not find package.json.");
330
328
  const scripts = {
331
329
  ...pkg.content.scripts,
332
330
  [scriptName]: command
333
331
  };
334
- const packageManager = await require_index_node.detectPackageManager(projectRoot);
335
- const typecheck = require_index_node.appendCommand(scripts.typecheck, require_index_node.getRunScriptCommand(packageManager, scriptName));
332
+ const packageManager = await require_parser.detectPackageManager(projectRoot);
333
+ const typecheck = require_parser.appendCommand(scripts.typecheck, require_parser.getRunScriptCommand(packageManager, scriptName));
336
334
  pkg.update({ scripts: {
337
335
  ...scripts,
338
336
  typecheck
@@ -354,7 +352,7 @@ async function syncWebSourceTypecheckScript(projectRoot) {
354
352
  await syncTypecheckScript(WEB_SOURCE_TYPECHECK_SCRIPT, WEB_SOURCE_TYPECHECK_COMMAND, projectRoot);
355
353
  }
356
354
 
357
- // source/commands/generate/web-src.ts
355
+ // source/deprecated/commands/generate/web-src.ts
358
356
  const JSX_FILE_EXTENSION = ".jsx";
359
357
  const TSX_FILE_EXTENSION = ".tsx";
360
358
  const APP_TITLE_PLACEHOLDER = "APP_TITLE";
@@ -367,7 +365,7 @@ const LEADING_DOT_SLASH_PATTERN$1 = /^\.\//u;
367
365
  const WEB_SOURCE_DEPENDENCIES = [
368
366
  {
369
367
  name: "@adobe/aio-commerce-lib-admin-ui",
370
- version: "^1.3.0"
368
+ version: "^1.3.1-alpha-20261203134759"
371
369
  },
372
370
  {
373
371
  name: "react",
@@ -447,11 +445,11 @@ function getWebSourceEntrypoint(extConfig) {
447
445
  * @param extension - Web source extension whose tooling is configured.
448
446
  */
449
447
  async function prepareWebSourcePackage(projectRoot, extension, scaffoldRequired) {
450
- const pkg = await require_index_node.loadPackageJson(projectRoot);
448
+ const pkg = await require_parser.loadPackageJson(projectRoot);
451
449
  if (pkg === null) throw new Error("Could not find package.json.");
452
450
  const dependencies = scaffoldRequired ? WEB_SOURCE_DEPENDENCIES : [];
453
451
  const requiredDevDependencies = scaffoldRequired ? [...WEB_SOURCE_DEV_DEPENDENCIES, ...extension === "tsx" ? SHARED_TYPESCRIPT_DEV_DEPENDENCIES : []] : WEB_SOURCE_REQUIRED_DEV_DEPENDENCIES;
454
- const installPlan = await require_index_node.getPackageDependencyInstallPlan([...dependencies, ...requiredDevDependencies], projectRoot);
452
+ const installPlan = await require_parser.getPackageDependencyInstallPlan([...dependencies, ...requiredDevDependencies], projectRoot);
455
453
  if (installPlan.incompatible.length > 0) {
456
454
  const incompatibleDependencies = installPlan.incompatible.map(({ name, version, installedVersion }) => `${name}@${installedVersion} does not satisfy ${version}`).join("\n");
457
455
  throw new Error(`Cannot scaffold web-src because installed dependencies are incompatible:\n${incompatibleDependencies}`);
@@ -475,9 +473,9 @@ async function prepareWebSourcePackage(projectRoot, extension, scaffoldRequired)
475
473
  ...pkg.content["@parcel/resolver-default"],
476
474
  packageExports: true
477
475
  },
478
- dependencies: require_index_node.mergePackageJsonDependencies(existingDependencies, WEB_SOURCE_DEPENDENCIES, dependencyMaps)
476
+ dependencies: require_parser.mergePackageJsonDependencies(existingDependencies, WEB_SOURCE_DEPENDENCIES, dependencyMaps)
479
477
  },
480
- devDependencies: require_index_node.mergePackageJsonDependencies(devDependencies, requiredDevDependencies, dependencyMaps)
478
+ devDependencies: require_parser.mergePackageJsonDependencies(devDependencies, requiredDevDependencies, dependencyMaps)
481
479
  });
482
480
  await pkg.save();
483
481
  if (installPlan.missing.length === 0) {
@@ -486,7 +484,7 @@ async function prepareWebSourcePackage(projectRoot, extension, scaffoldRequired)
486
484
  }
487
485
  consola.consola.info("Installing missing web-src dependencies from package.json:");
488
486
  consola.consola.log.raw((0, consola_utils.formatTree)(installPlan.missing.map(({ name, version }) => ` ${name}@${version}`)));
489
- const packageManager = await require_index_node.detectPackageManager(projectRoot);
487
+ const packageManager = await require_parser.detectPackageManager(projectRoot);
490
488
  runProjectInstall(packageManager, projectRoot);
491
489
  }
492
490
  /**
@@ -511,7 +509,7 @@ async function copyMissingWebSourceFiles(sourceDir, targetDir, projectRoot) {
511
509
  async function prepareWebSourceImportAlias(extConfig, projectRoot) {
512
510
  const entrypoint = getWebSourceEntrypoint(extConfig);
513
511
  if (entrypoint === null) return;
514
- const pkg = await require_index_node.loadPackageJson(projectRoot);
512
+ const pkg = await require_parser.loadPackageJson(projectRoot);
515
513
  if (pkg === null) throw new Error("Could not find package.json.");
516
514
  const existingImports = typeof pkg.content.imports === "object" && pkg.content.imports !== null ? pkg.content.imports : {};
517
515
  const webSourceSrcPath = (0, path.join)((0, path.dirname)(entrypoint), "src");
@@ -523,8 +521,8 @@ async function prepareWebSourceImportAlias(extConfig, projectRoot) {
523
521
  }
524
522
  /** Resolve the generated web-src file extension from the app config file type. */
525
523
  async function resolveWebSourceExtension(projectRoot) {
526
- const configFilePath = await require_index_node.resolveCommerceAppConfig(projectRoot);
527
- return configFilePath !== null && require_index_node.isTypeScriptConfig(configFilePath) ? "tsx" : "jsx";
524
+ const configFilePath = await require_parser.resolveCommerceAppConfig(projectRoot);
525
+ return configFilePath !== null && require_parser.isTypeScriptConfig(configFilePath) ? "tsx" : "jsx";
528
526
  }
529
527
  async function writeWebSourceTypeScriptConfig(targetDir) {
530
528
  const tsconfigPath = (0, path.join)(targetDir, WEB_SOURCE_TSCONFIG_FILE);
@@ -601,7 +599,7 @@ async function generateWebSrc(extConfig, appName, projectRoot, templatesDir = TE
601
599
  }
602
600
  }
603
601
 
604
- // source/commands/generate/actions/config.ts
602
+ // source/deprecated/commands/generate/actions/config.ts
605
603
  /**
606
604
  * Creates a runtime action configuration.
607
605
  * @param actionName - The name of the action.
@@ -818,10 +816,7 @@ function getOrCreateMap(doc, path, options) {
818
816
  function getExistingInputs(existingAction) {
819
817
  const inputs = existingAction?.get("inputs");
820
818
  if (!(0, yaml.isMap)(inputs)) return {};
821
- return Object.fromEntries(inputs.items.map((item) => {
822
- if (!(0, yaml.isPair)(item)) return [];
823
- return [String(item.key), (0, yaml.isScalar)(item.value) ? item.value.value : item.value];
824
- }));
819
+ return Object.fromEntries(inputs.items.map((item) => [String(item.key), (0, yaml.isScalar)(item.value) ? item.value.value : item.value]));
825
820
  }
826
821
  /**
827
822
  * Read a string field from an existing YAML action definition. Used by codegen
@@ -991,14 +986,14 @@ async function buildHooks(extConfig, hooks) {
991
986
  pair.key.spaceBefore = true;
992
987
  pair.key.commentBefore = ` The ${generatedHooks} hooks are auto-generated. Do not remove or manually edit.`;
993
988
  } });
994
- const projectRoot = await require_index_node.getProjectRootDirectory();
995
- const packageManager = await require_index_node.detectPackageManager(projectRoot);
996
- const execCommand = require_index_node.getExecCommand(packageManager);
989
+ const projectRoot = await require_parser.getProjectRootDirectory();
990
+ const packageManager = await require_parser.detectPackageManager(projectRoot);
991
+ const execCommand = require_parser.getExecCommand(packageManager);
997
992
  for (const [name, command] of Object.entries(hooks)) {
998
993
  const fullCommand = `${command.replaceAll("$packageExec", execCommand)}`;
999
994
  const prevValue = (hooksMap.get(name) ?? "").trim();
1000
995
  if (prevValue.endsWith("js") || prevValue.endsWith("ts")) throw new Error(`Conflicting hook definition found. The "${name}" hook needs to be a command, not a script.`);
1001
- hooksMap.set(name, require_index_node.appendCommand(prevValue || void 0, fullCommand));
996
+ hooksMap.set(name, require_parser.appendCommand(prevValue || void 0, fullCommand));
1002
997
  }
1003
998
  }
1004
999
  /**
@@ -1015,7 +1010,12 @@ async function writeExtConfig(configPath, doc) {
1015
1010
  await (0, fs_promises.writeFile)(configPath, yamlContent, "utf-8");
1016
1011
  }
1017
1012
 
1018
- // source/commands/generate/actions/lib.ts
1013
+ // source/deprecated/commands/generate/actions/constants.ts
1014
+ const CUSTOM_IMPORTS_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_IMPORTS}}";
1015
+ const CUSTOM_SCRIPTS_MAP_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_MAP}}";
1016
+ const CUSTOM_SCRIPTS_LOADER_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_LOADER}}";
1017
+
1018
+ // source/deprecated/commands/generate/actions/lib.ts
1019
1019
  const ESBUILD_PACKAGE = "esbuild@0.28.0";
1020
1020
  const LEADING_DOT_SLASH_PATTERN = /^\.\//u;
1021
1021
  /** Normalize a path for use as an ESM import specifier. */
@@ -1029,7 +1029,7 @@ function normalizePackageJsonPath(path) {
1029
1029
  }
1030
1030
  /** Add or update the package import alias used by dynamic generated actions. */
1031
1031
  async function updateAppConfigImportAlias(projectRoot, runtimeConfigPath) {
1032
- const pkg = await require_index_node.loadPackageJson(projectRoot);
1032
+ const pkg = await require_parser.loadPackageJson(projectRoot);
1033
1033
  if (pkg === null) throw new Error("Could not find package.json.");
1034
1034
  const existingImports = typeof pkg.content.imports === "object" && pkg.content.imports !== null ? pkg.content.imports : {};
1035
1035
  pkg.update({ imports: {
@@ -1062,8 +1062,8 @@ async function writeJavaScriptAppConfigModule(configFilePath, outputPath) {
1062
1062
  * @param projectRoot - Resolved project root used to run the bundler.
1063
1063
  */
1064
1064
  async function bundleTypeScriptAppConfigModule(configFilePath, outputPath, projectRoot) {
1065
- const packageManager = await require_index_node.detectPackageManager(projectRoot);
1066
- const { command, args } = require_index_node.getPackageExecutionCommand(packageManager, [
1065
+ const packageManager = await require_parser.detectPackageManager(projectRoot);
1066
+ const { command, args } = require_parser.getPackageExecutionCommand(packageManager, [
1067
1067
  ESBUILD_PACKAGE,
1068
1068
  configFilePath,
1069
1069
  "--bundle",
@@ -1088,7 +1088,7 @@ async function bundleTypeScriptAppConfigModule(configFilePath, outputPath, proje
1088
1088
  async function prepareStaticAppConfigImportAlias(projectRoot) {
1089
1089
  const runtimeConfigPath = getRuntimeAppConfigPath();
1090
1090
  const outputPath = (0, path.join)(projectRoot, runtimeConfigPath);
1091
- await require_index_node.makeOutputDirFor((0, path.dirname)(runtimeConfigPath), projectRoot);
1091
+ await require_parser.makeOutputDirFor((0, path.dirname)(runtimeConfigPath), projectRoot);
1092
1092
  await writeJavaScriptAppConfigModule((0, path.join)(projectRoot, getManifestPath()), outputPath);
1093
1093
  }
1094
1094
  /**
@@ -1102,12 +1102,12 @@ async function prepareStaticAppConfigImportAlias(projectRoot) {
1102
1102
  * @param projectRoot - Resolved project root where the module is generated.
1103
1103
  */
1104
1104
  async function prepareRuntimeAppConfigModule(appManifest, projectRoot) {
1105
- const configFilePath = await require_index_node.resolveCommerceAppConfig(projectRoot);
1105
+ const configFilePath = await require_parser.resolveCommerceAppConfig(projectRoot);
1106
1106
  if (await requiresJavaScriptAppConfig(appManifest, projectRoot)) {
1107
1107
  if (configFilePath === null) throw new Error("Generating a runtime config module requires an app.commerce.config.* file.");
1108
- await require_index_node.makeOutputDirFor((0, path.dirname)(getRuntimeAppConfigPath()), projectRoot);
1108
+ await require_parser.makeOutputDirFor((0, path.dirname)(getRuntimeAppConfigPath()), projectRoot);
1109
1109
  const outputPath = (0, path.join)(projectRoot, getRuntimeAppConfigPath());
1110
- if (require_index_node.isTypeScriptConfig(configFilePath)) await bundleTypeScriptAppConfigModule(configFilePath, outputPath, projectRoot);
1110
+ if (require_parser.isTypeScriptConfig(configFilePath)) await bundleTypeScriptAppConfigModule(configFilePath, outputPath, projectRoot);
1111
1111
  else await writeJavaScriptAppConfigModule(configFilePath, outputPath);
1112
1112
  } else await prepareStaticAppConfigImportAlias(projectRoot);
1113
1113
  await updateAppConfigImportAlias(projectRoot, getRuntimeAppConfigPath());
@@ -1196,7 +1196,7 @@ function removeLegacyLogLevelInputs(extConfigDoc, extConfig) {
1196
1196
  */
1197
1197
  async function updateExtConfig(appConfig, extensionPointId, projectRoot) {
1198
1198
  consola.consola.info(`Updating ext.config.yaml for ${extensionPointId}...`);
1199
- await require_index_node.makeOutputDirFor(getExtensionPointFolderPath(extensionPointId), projectRoot);
1199
+ await require_parser.makeOutputDirFor(getExtensionPointFolderPath(extensionPointId), projectRoot);
1200
1200
  const { path: extConfigPath, doc: extConfigDoc } = await readExtConfig(extensionPointId, projectRoot);
1201
1201
  let extConfig;
1202
1202
  switch (extensionPointId) {
@@ -1226,7 +1226,7 @@ async function updateExtConfig(appConfig, extensionPointId, projectRoot) {
1226
1226
  */
1227
1227
  async function generateActionFiles(appManifest, actions, extensionPointId, templatesDir, projectRoot) {
1228
1228
  consola.consola.start("Generating runtime actions...");
1229
- await require_index_node.makeOutputDirFor(getActionsDir(extensionPointId), projectRoot);
1229
+ await require_parser.makeOutputDirFor(getActionsDir(extensionPointId), projectRoot);
1230
1230
  const outputFiles = await Promise.all(actions.map(async (action) => {
1231
1231
  const templatePath = (0, path.join)(templatesDir, action.templateFile);
1232
1232
  let template = await (0, fs_promises.readFile)(templatePath, "utf-8");
@@ -1276,7 +1276,7 @@ async function generateCustomScriptsTemplate(template, appManifest, projectRoot)
1276
1276
  return template.replace(CUSTOM_IMPORTS_PLACEHOLDER, importStatements).replace(CUSTOM_SCRIPTS_MAP_PLACEHOLDER, scriptMap);
1277
1277
  }
1278
1278
 
1279
- // source/commands/generate/actions/main.ts
1279
+ // source/deprecated/commands/generate/actions/main.ts
1280
1280
  /**
1281
1281
  * Generates extension configs, runtime actions, and Admin UI web source for the configured domains.
1282
1282
  * @param appManifest - App configuration used to determine the generated content.
@@ -1302,7 +1302,7 @@ async function run$9(appManifest, projectRoot, templatesDir = TEMPLATES_DIR) {
1302
1302
  /** Run the generate actions command */
1303
1303
  async function exec$10() {
1304
1304
  try {
1305
- const projectRoot = await require_index_node.getProjectRootDirectory();
1305
+ const projectRoot = await require_parser.getProjectRootDirectory();
1306
1306
  await run$9(await loadAppManifest(projectRoot), projectRoot);
1307
1307
  } catch (error) {
1308
1308
  if (error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) consola.consola.error(error.display());
@@ -1311,7 +1311,7 @@ async function exec$10() {
1311
1311
  }
1312
1312
  }
1313
1313
 
1314
- // source/commands/generate/manifest/main.ts
1314
+ // source/deprecated/commands/generate/manifest/main.ts
1315
1315
  /**
1316
1316
  * Generates or removes the static app manifest as required by the app config.
1317
1317
  * @param appConfig - Validated app configuration to serialize.
@@ -1329,7 +1329,7 @@ async function run$8(appConfig, projectRoot) {
1329
1329
  consola.consola.log("");
1330
1330
  consola.consola.info("Generating app manifest...");
1331
1331
  const contents = (0, safe_stable_stringify.stringify)(appConfig, null, 2);
1332
- const outputDir = await require_index_node.makeOutputDirFor(getGeneratedDir(EXTENSIBILITY_EXTENSION_POINT_ID), projectRoot);
1332
+ const outputDir = await require_parser.makeOutputDirFor(getGeneratedDir(EXTENSIBILITY_EXTENSION_POINT_ID), projectRoot);
1333
1333
  const manifestPath = (0, path.join)(outputDir, APP_MANIFEST_FILE);
1334
1334
  await (0, fs_promises.writeFile)(manifestPath, contents, "utf-8");
1335
1335
  consola.consola.success(`Generated ${APP_MANIFEST_FILE}\n`);
@@ -1337,7 +1337,7 @@ async function run$8(appConfig, projectRoot) {
1337
1337
  /** Run the generate manifest command */
1338
1338
  async function exec$9() {
1339
1339
  try {
1340
- const projectRoot = await require_index_node.getProjectRootDirectory();
1340
+ const projectRoot = await require_parser.getProjectRootDirectory();
1341
1341
  await run$8(await loadAppManifest(projectRoot), projectRoot);
1342
1342
  } catch (error) {
1343
1343
  if (error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) consola.consola.error(error.display());
@@ -1348,6 +1348,21 @@ async function exec$9() {
1348
1348
 
1349
1349
  // ../../packages-private/scripting-utils/source/filesystem/helpers.ts
1350
1350
  /**
1351
+ * Reads a text file that may not exist.
1352
+ *
1353
+ * @param filePath - The path of the file to read.
1354
+ *
1355
+ * @returns The content, or `undefined` when there is no file.
1356
+ */
1357
+ async function readOptionalFile(filePath) {
1358
+ try {
1359
+ return await (0, fs_promises.readFile)(filePath, "utf-8");
1360
+ } catch (error) {
1361
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
1362
+ throw error;
1363
+ }
1364
+ }
1365
+ /**
1351
1366
  * Touch a file, creating it if it doesn't exist.
1352
1367
  * @param filePath The path of the file to touch
1353
1368
  */
@@ -1357,7 +1372,7 @@ async function touch(filePath) {
1357
1372
  });
1358
1373
  }
1359
1374
 
1360
- // source/commands/generate/schema/main.ts
1375
+ // source/deprecated/commands/generate/schema/main.ts
1361
1376
  /**
1362
1377
  * Generates the business configuration schema and prepares encryption when needed.
1363
1378
  * @param appConfig - Validated app configuration containing the schema.
@@ -1372,7 +1387,7 @@ async function run$7(appConfig, projectRoot) {
1372
1387
  await touch(envPath);
1373
1388
  process.loadEnvFile(envPath);
1374
1389
  if (appConfig.businessConfig.schema.some((field) => field.type === "password")) {
1375
- const packageExec = require_index_node.getExecCommand(await require_index_node.detectPackageManager(projectRoot));
1390
+ const packageExec = require_parser.getExecCommand(await require_parser.detectPackageManager(projectRoot));
1376
1391
  if ("AIO_COMMERCE_CONFIG_ENCRYPTION_KEY" in process.env && String(process.env.AIO_COMMERCE_CONFIG_ENCRYPTION_KEY).trim().length > 0) (0, child_process.execSync)(`${packageExec} aio-commerce-lib-config encryption validate`);
1377
1392
  else (0, child_process.execSync)(`${packageExec} aio-commerce-lib-config encryption setup`);
1378
1393
  }
@@ -1385,7 +1400,7 @@ async function run$7(appConfig, projectRoot) {
1385
1400
  return;
1386
1401
  }
1387
1402
  consola.consola.info("Generating configuration schema...");
1388
- const outputDir = await require_index_node.makeOutputDirFor(getGeneratedDir(CONFIGURATION_EXTENSION_POINT_ID), projectRoot);
1403
+ const outputDir = await require_parser.makeOutputDirFor(getGeneratedDir(CONFIGURATION_EXTENSION_POINT_ID), projectRoot);
1389
1404
  const contents = (0, safe_stable_stringify.stringify)(appConfig.businessConfig.schema, null, 2);
1390
1405
  const schemaPath = (0, path.join)(outputDir, CONFIG_SCHEMA_FILE_NAME);
1391
1406
  await (0, fs_promises.writeFile)(schemaPath, contents, "utf-8");
@@ -1394,7 +1409,7 @@ async function run$7(appConfig, projectRoot) {
1394
1409
  /** Run the generate schema command */
1395
1410
  async function exec$8() {
1396
1411
  try {
1397
- const projectRoot = await require_index_node.getProjectRootDirectory();
1412
+ const projectRoot = await require_parser.getProjectRootDirectory();
1398
1413
  await run$7(await loadAppManifest(projectRoot), projectRoot);
1399
1414
  } catch (error) {
1400
1415
  if (error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) consola.consola.error(error.display());
@@ -1403,220 +1418,72 @@ async function exec$8() {
1403
1418
  }
1404
1419
  }
1405
1420
 
1406
- // ../../packages-private/scripting-utils/source/process/liveness.ts
1407
- /** Whether a process with the pid exists. A process we may not signal still exists. */
1408
- function isProcessAlive(pid) {
1409
- try {
1410
- process.kill(pid, 0);
1411
- return true;
1412
- } catch (error) {
1413
- return error.code === "EPERM";
1414
- }
1415
- }
1416
- /** The environment variable that holds the pid of the process that started a detached process. */
1417
- const OWNER_PID_ENV = "__AIO_COMMERCE_SDK_DETACHED_OWNER_PID";
1418
- /**
1419
- * The environment variable that holds the file descriptor of the liveness pipe of a detached
1420
- * process. It is only set when that descriptor is such a pipe.
1421
- */
1422
- const LIVENESS_FD_ENV = "__AIO_COMMERCE_SDK_DETACHED_LIVENESS_FD";
1423
- /** How often the owner pid is checked. */
1424
- const LIVENESS_CHECK_INTERVAL_MS = 1e3;
1425
- /** Opens the read end of the liveness pipe, or returns `undefined` when there is none. */
1426
- function openLivenessPipe() {
1427
- const fd = Number(process.env[LIVENESS_FD_ENV]);
1428
- if (!Number.isInteger(fd) || fd <= 0) return;
1429
- try {
1430
- const pipe = new net.default.Socket({
1431
- fd,
1432
- readable: true,
1433
- writable: false
1434
- });
1435
- pipe.on("error", () => pipe.destroy());
1436
- pipe.unref();
1437
- return pipe;
1438
- } catch {
1439
- return;
1440
- }
1441
- }
1421
+ // ../../packages-private/cams-client/source/lib/answer.ts
1422
+ /** The content type of an answer about a problem of CAMS itself. */
1423
+ const PROBLEM_CONTENT_TYPE = "application/problem+json";
1442
1424
  /**
1443
- * Resolves when the process that started this one is gone. Does nothing else until then.
1444
- *
1445
- * It only works in a process that {@link spawnDetached} started, which tells it the pid of the
1446
- * owner and the file descriptor of the liveness pipe through the environment variables
1447
- * {@link OWNER_PID_ENV} and {@link LIVENESS_FD_ENV}. Without the pipe it relies on the pid check
1448
- * alone.
1449
- *
1450
- * @throws A `RangeError` if {@link OWNER_PID_ENV} is not set to a positive integer.
1451
- *
1452
- * Two signals:
1453
- * 1. The pipe closes, which follows the end of the pipe. The kernel closes the owner's end when
1454
- * the owner dies, so this is immediate and an owner that died but was not reaped yet still
1455
- * counts as dead.
1456
- * 2. The owner pid no longer exists, checked on a timer. It covers a missing or failed pipe, and
1457
- * it is the weaker signal, because an owner that died but was not reaped still answers as alive.
1425
+ * The HTTP statuses that can succeed when the same request is sent again, as CAMS counts them when
1426
+ * it calls an app.
1458
1427
  */
1459
- async function waitForOwnerExit() {
1460
- const ownerPid = Number(process.env[OWNER_PID_ENV]);
1461
- if (!Number.isInteger(ownerPid) || ownerPid <= 0) throw new RangeError(`${OWNER_PID_ENV} must be a positive integer, got ${process.env[OWNER_PID_ENV]}`);
1462
- const pipe = openLivenessPipe();
1463
- return await new Promise((resolve) => {
1464
- const finish = (signal) => {
1465
- clearInterval(timer);
1466
- resolve(signal);
1467
- };
1468
- const timer = setInterval(() => {
1469
- if (!isProcessAlive(ownerPid)) finish("pid");
1470
- }, LIVENESS_CHECK_INTERVAL_MS);
1471
- let pipeFailed = false;
1472
- pipe?.resume();
1473
- pipe?.once("error", () => {
1474
- pipeFailed = true;
1475
- });
1476
- pipe?.once("close", () => {
1477
- if (!pipeFailed) finish("pipe");
1478
- });
1479
- });
1480
- }
1481
-
1482
- // ../../packages-private/scripting-utils/source/process/detached.ts
1428
+ const RETRYABLE_STATUSES = [
1429
+ 408,
1430
+ 425,
1431
+ 429,
1432
+ 500,
1433
+ 502,
1434
+ 503,
1435
+ 504
1436
+ ];
1483
1437
  /**
1484
- * The path of a log file in the temp folder, for {@link SpawnDetachedOptions.logPath}.
1485
- *
1486
- * @param name - The name of the log. Characters that a file name should not hold become `_`.
1487
- * @param directory - The folder of the file. Defaults to the temp folder of the system.
1438
+ * The JSON object of an error answer, with the fields that CAMS problems and app errors carry typed
1439
+ * and the rest kept as they came. A field of another type counts as absent.
1488
1440
  */
1489
- function getTempLogPath(name, directory = (0, os.tmpdir)()) {
1490
- const filename = name.replaceAll(/[^\w-]/gu, (character) => "_".repeat(character.length));
1491
- return (0, path.join)(directory, `${filename}.log`);
1492
- }
1493
- /** The file descriptor of the liveness pipe in the process that is started. */
1494
- const LIVENESS_PIPE_FD = 3;
1495
- /** Keeps the parent end of every liveness pipe referenced until its child exits. */
1496
- const livenessPipes = [];
1441
+ const ErrorBodySchema = valibot.looseObject({
1442
+ code: valibot.fallback(valibot.optional(valibot.string()), void 0),
1443
+ detail: valibot.fallback(valibot.optional(valibot.string()), void 0),
1444
+ message: valibot.fallback(valibot.optional(valibot.string()), void 0),
1445
+ retryable: valibot.fallback(valibot.optional(valibot.boolean()), void 0)
1446
+ });
1447
+ /** The text of an error answer, read as the JSON object of {@link ErrorBodySchema}. */
1448
+ const ErrorBodyTextSchema = valibot.pipe(valibot.string(), valibot.parseJson(), ErrorBodySchema);
1497
1449
  /**
1498
- * Starts a Node.js script as a detached process that outlives this one.
1450
+ * Reads the error answer of a response with an error status.
1499
1451
  *
1500
- * The process runs in its own session without a terminal, so Ctrl-C, a closed terminal and a kill
1501
- * of this process do not reach it. Its standard input is closed, and its output goes to a log
1502
- * file. A pipe on file descriptor 3 lets the process see this one die. The process tells it
1503
- * through the environment variables {@link OWNER_PID_ENV}, with the pid of this process, and
1504
- * {@link LIVENESS_FD_ENV}, with the file descriptor of the pipe, which {@link waitForOwnerExit}
1505
- * reads.
1506
- *
1507
- * Failures after the spawn, such as a missing node binary, arrive only through `onError`. A script
1508
- * that does not exist shows up only in the log file.
1509
- *
1510
- * @returns The process, or `undefined` when it could not start.
1511
- */
1512
- function spawnDetached(options) {
1513
- const { script, args = [], logPath, env, cwd, onError, spawnProcess = child_process.spawn } = options;
1514
- let logFd;
1515
- try {
1516
- logFd = (0, fs.openSync)(logPath, "a");
1517
- const child = spawnProcess(process.execPath, [script, ...args], {
1518
- cwd,
1519
- detached: true,
1520
- env: {
1521
- ...env ?? process.env,
1522
- [LIVENESS_FD_ENV]: String(LIVENESS_PIPE_FD),
1523
- [OWNER_PID_ENV]: String(process.pid)
1524
- },
1525
- stdio: [
1526
- "ignore",
1527
- logFd,
1528
- logFd,
1529
- "pipe"
1530
- ],
1531
- windowsHide: true
1532
- });
1533
- child.once("error", (error) => onError?.(error));
1534
- const pipe = child.stdio[3];
1535
- if (pipe) {
1536
- pipe.on("error", () => void 0);
1537
- pipe.unref();
1538
- livenessPipes.push(pipe);
1539
- child.once("exit", () => {
1540
- pipe.destroy();
1541
- livenessPipes.splice(livenessPipes.indexOf(pipe), 1);
1542
- });
1543
- }
1544
- child.unref();
1545
- return { child };
1546
- } catch (error) {
1547
- onError?.(error);
1548
- } finally {
1549
- if (logFd !== void 0) (0, fs.closeSync)(logFd);
1550
- }
1551
- }
1552
-
1553
- // ../../packages-private/scripting-utils/source/aio/auth.ts
1554
- const { context: context$1, getToken } = _adobe_aio_lib_ims.default;
1555
- /** Gets an IMS access token for the current CLI IMS context. */
1556
- async function getUserToken() {
1557
- const contextName = await context$1.getCurrent() ?? "cli";
1558
- return getToken(contextName, {});
1559
- }
1560
-
1561
- // ../../packages-private/scripting-utils/source/aio/context.ts
1562
- /**
1563
- * Reads the current App Builder project and Runtime namespace from the local AIO CLI config.
1564
- * @throws If either the project or the runtime namespace is not configured.
1452
+ * @param response - The response, which stays readable: its body is read from a clone.
1565
1453
  */
1566
- function getAioProjectContext() {
1567
- const project = _adobe_aio_lib_core_config.default.get("project");
1568
- const namespace = _adobe_aio_lib_core_config.default.get("runtime.namespace");
1569
- if (!(project && namespace)) throw new Error("The current App Builder project and Runtime namespace are required");
1454
+ async function readErrorAnswer(response) {
1455
+ const text = await response.clone().text().then((body) => body.trim()).catch(() => "");
1456
+ const parsed = valibot.safeParse(ErrorBodyTextSchema, text);
1457
+ const json = parsed.success ? parsed.output : void 0;
1458
+ const { code, detail, message, retryable } = json ?? {};
1459
+ const isProblem = (response.headers.get("content-type") ?? "").includes(PROBLEM_CONTENT_TYPE);
1460
+ let origin;
1461
+ if (isProblem) origin = "service";
1462
+ else if (code !== void 0 && message !== void 0) origin = "app";
1570
1463
  return {
1571
- namespace,
1572
- project
1464
+ body: json ?? {},
1465
+ code,
1466
+ message: json ? message ?? detail ?? "" : text,
1467
+ origin,
1468
+ retryable: retryable ?? RETRYABLE_STATUSES.includes(response.status),
1469
+ status: response.status
1573
1470
  };
1574
1471
  }
1575
- /** Reads the configured AIO CLI environment, defaulting to `"prod"`. */
1576
- function getAioCliEnv() {
1577
- return _adobe_aio_lib_core_config.default.get("cli.env") === "stage" ? "stage" : "prod";
1578
- }
1579
1472
 
1580
- // source/commands/common/cams/config.ts
1581
- /** Environment variable that overrides the CAMS base URL. */
1582
- const CAMS_URL_ENV_VAR = "AIO_COMMERCE_APP_MANAGEMENT_SERVICE_URL";
1583
- /** Environment variable that selects the AIO CLI environment. */
1584
- const AIO_CLI_ENV_VAR = "AIO_CLI_ENV";
1473
+ // ../../packages-private/cams-client/source/lib/config.ts
1585
1474
  /** The CAMS host for the stage environment. */
1586
1475
  const STAGE_CAMS_URL = "https://app-management-stage.api.commerce.adobe.com";
1587
1476
  /** The CAMS host for the production environment. */
1588
1477
  const PROD_CAMS_URL = "https://app-management.api.commerce.adobe.com";
1589
- /**
1590
- * The time in milliseconds a CAMS request may take before it fails with a timeout.
1591
- *
1592
- * CAMS calls the app on Adobe I/O Runtime for some requests, for example to plan an upgrade, and a
1593
- * cold start after a deploy can take longer than ky's 10 second default.
1594
- */
1478
+ /** The time in milliseconds a CAMS request may take before it fails with a timeout. */
1595
1479
  const CAMS_REQUEST_TIMEOUT_MS = 6e4;
1596
- const URL_SCHEME_PATTERN = /^[hH][tT][tT][pP][sS]?:\/\//u;
1597
- /**
1598
- * Resolves the base URL of the Commerce App Management Service (CAMS).
1599
- *
1600
- * The override variable wins. A value without a scheme is read as an https URL.
1601
- * Otherwise `AIO_CLI_ENV` (`stage` or `prod`) selects the host, falling back to `env`.
1602
- *
1603
- * @param env - The configured AIO CLI environment, used when `AIO_CLI_ENV` is unset or unknown.
1604
- * @param variables - The environment variables to read the override from.
1605
- */
1606
- function resolveCamsBaseUrl(env, variables = process.env) {
1607
- const override = variables[CAMS_URL_ENV_VAR]?.trim();
1608
- if (override) return URL_SCHEME_PATTERN.test(override) ? override : `https://${override}`;
1609
- const cliEnv = variables[AIO_CLI_ENV_VAR]?.trim();
1610
- return (cliEnv === "stage" || cliEnv === "prod" ? cliEnv : env) === "stage" ? STAGE_CAMS_URL : PROD_CAMS_URL;
1611
- }
1612
1480
 
1613
- // source/commands/common/cams/errors.ts
1614
- const HTTP_BAD_GATEWAY = 502;
1615
- const HTTP_SERVICE_UNAVAILABLE = 503;
1481
+ // ../../packages-private/cams-client/source/lib/errors.ts
1616
1482
  /**
1617
1483
  * Error of every failure while talking to the Commerce App Management Service (CAMS): the user
1618
- * token cannot be read, CAMS cannot be reached, it answers with an error status, or its answer
1619
- * does not have the expected shape.
1484
+ * token cannot be read, CAMS cannot be reached or does not answer in time, it answers with an error
1485
+ * that is not one of the documented outcomes of the call, or its answer does not have the expected
1486
+ * shape.
1620
1487
  */
1621
1488
  var CamsClientError = class extends _adobe_aio_commerce_lib_core_error.CommerceSdkErrorBase {
1622
1489
  /** Whether repeating the same request later can succeed. */
@@ -1625,410 +1492,1425 @@ var CamsClientError = class extends _adobe_aio_commerce_lib_core_error.CommerceS
1625
1492
  status;
1626
1493
  /** The machine-readable code of the answer, when it has one. */
1627
1494
  code;
1495
+ /**
1496
+ * Whether CAMS refused the request itself (`service`, an `application/problem+json` answer) or
1497
+ * passed through an error of the app (`app`, an `application/json` answer). `undefined` when the
1498
+ * answer is neither, for example a gateway error.
1499
+ */
1500
+ origin;
1628
1501
  /** The request that CAMS answered with an error, when CAMS answered. */
1629
1502
  request;
1630
1503
  constructor(message, options = {}) {
1631
- const { retryable = false, status, code, request, ...rest } = options;
1504
+ const { retryable = false, status, code, origin, request, ...rest } = options;
1632
1505
  super(message, rest);
1633
1506
  this.retryable = retryable;
1634
1507
  this.status = status;
1635
1508
  this.code = code;
1509
+ this.origin = origin;
1636
1510
  this.request = request;
1637
1511
  }
1638
1512
  };
1639
- /** Thrown when CAMS refuses a request with a 409. Its `code` tells why. */
1640
- var CamsConflictError = class extends CamsClientError {};
1641
- /** The `code` and text of an error answer, plus retryability when provided. */
1642
- async function readAnswer(response) {
1643
- const body = (await response.clone().text().catch(() => "")).trim();
1644
- try {
1645
- const json = JSON.parse(body);
1646
- if (typeof json === "object" && json !== null) {
1647
- const { code, message, detail, retryable } = json;
1648
- const text = [message, detail].find((value) => typeof value === "string");
1649
- return {
1650
- code: typeof code === "string" ? code : void 0,
1651
- retryable: typeof retryable === "boolean" ? retryable : void 0,
1652
- text: typeof text === "string" ? text : ""
1653
- };
1654
- }
1655
- } catch {}
1656
- return {
1657
- code: void 0,
1658
- retryable: void 0,
1659
- text: body
1660
- };
1661
- }
1662
1513
  /**
1663
- * Builds the error for an answer with an error status. The backend retryable flag takes precedence;
1664
- * older responses fall back to treating 502 and 503 as retryable.
1514
+ * Builds the error for an answer with an error status.
1515
+ *
1516
+ * @param error - The error ky threw for the answer.
1517
+ * @param answer - The error answer read from its body.
1665
1518
  */
1666
- async function toCamsResponseError(error) {
1519
+ function toCamsResponseError(error, answer) {
1667
1520
  const { status, statusText } = error.response;
1668
- const { code, retryable: backendRetryable, text } = await readAnswer(error.response);
1669
- const retryable = backendRetryable ?? (status === HTTP_BAD_GATEWAY || status === HTTP_SERVICE_UNAVAILABLE);
1670
- const answer = [status, statusText].filter(Boolean).join(" ");
1671
- const message = text || `The Commerce App Management Service answered with HTTP ${answer}`;
1672
- const options = {
1521
+ const answered = [status, statusText].filter(Boolean).join(" ");
1522
+ const message = answer.message || `The Commerce App Management Service answered with HTTP ${answered}`;
1523
+ return new CamsClientError(message, {
1673
1524
  cause: error,
1674
- code,
1525
+ code: answer.code,
1526
+ origin: answer.origin,
1675
1527
  request: {
1676
1528
  method: error.request.method,
1677
1529
  path: new URL(error.request.url).pathname
1678
1530
  },
1679
- retryable,
1531
+ retryable: answer.retryable,
1680
1532
  status
1681
- };
1682
- if (status === _adobe_aio_commerce_lib_core_responses.HTTP_CONFLICT) return new CamsConflictError(message, options);
1683
- return new CamsClientError(message, options);
1533
+ });
1684
1534
  }
1685
1535
 
1686
- // source/commands/common/cams/schema.ts
1687
- /** The statuses a lifecycle attempt can have. */
1688
- const ATTEMPT_STATUSES = [
1689
- "pending",
1690
- "in-progress",
1691
- "succeeded",
1692
- "failed"
1693
- ];
1694
- /** An extension of the service, as listed for a workspace. */
1695
- const ExtensionSchema = valibot.object({
1696
- id: valibot.string(),
1697
- scope: valibot.optional(valibot.object({
1698
- commerceBaseUrl: valibot.optional(valibot.nullable(valibot.string())),
1699
- commerceEnv: valibot.optional(valibot.nullable(valibot.picklist(["paas", "saas"]))),
1700
- commerceId: valibot.optional(valibot.string()),
1701
- workspaceId: valibot.optional(valibot.string()),
1702
- workspaceName: valibot.optional(valibot.string())
1703
- }))
1704
- });
1705
- /** The answer of the service to a lookup by workspace. */
1706
- const ExtensionListSchema = valibot.array(ExtensionSchema);
1707
- /** The plan the service returns for review. */
1708
- const UpgradePlanAnswerSchema = valibot.object({ plan: valibot.looseObject({
1709
- id: valibot.string(),
1710
- issues: valibot.array(valibot.looseObject({ blocking: valibot.boolean() })),
1711
- operation: valibot.string(),
1712
- sourceVersion: valibot.optional(valibot.nullable(valibot.string())),
1713
- targetVersion: valibot.optional(valibot.nullable(valibot.string()))
1714
- }) });
1715
- /** The status of a lifecycle attempt, as the app reports it through the service. */
1716
- const AttemptStatusSchema = valibot.object({
1717
- activations: valibot.optional(valibot.object({
1718
- execution: valibot.optional(valibot.string()),
1719
- start: valibot.optional(valibot.string())
1720
- })),
1721
- error: valibot.optional(valibot.object({
1722
- key: valibot.string(),
1723
- message: valibot.optional(valibot.string())
1724
- })),
1725
- id: valibot.string(),
1726
- result: valibot.optional(valibot.nullable(valibot.object({
1727
- appVersion: valibot.string(),
1728
- snapshotId: valibot.string()
1729
- }))),
1730
- status: valibot.picklist(ATTEMPT_STATUSES)
1731
- });
1732
- /** The parameters to find the extension associated with a workspace. */
1733
- const FindExtensionParamsSchema = valibot.object({ workspaceId: require_schemas.nonEmptyStringValueSchema("workspaceId") });
1734
- /** The parameters of the calls that act on the upgrades of an extension. */
1735
- const ExtensionParamsSchema = valibot.object({ extensionId: require_schemas.nonEmptyStringValueSchema("extensionId") });
1736
- /** The parameters to find a specific upgrade attempt. */
1737
- const FindAttemptParamsSchema = valibot.object({
1738
- ...ExtensionParamsSchema.entries,
1536
+ // ../../packages-private/cams-client/source/lib/response.ts
1537
+ /**
1538
+ * Checks a value of an answer against the schema.
1539
+ *
1540
+ * @throws A {@link CamsClientError} If the value does not match the schema.
1541
+ */
1542
+ function parseBody(schema, body) {
1543
+ try {
1544
+ return require_utils.parseOrThrow(schema, body);
1545
+ } catch (error) {
1546
+ throw new CamsClientError("The Commerce App Management Service sent an unexpected answer", { cause: error });
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Reads the JSON body of a response and checks it against the schema.
1551
+ *
1552
+ * @throws A {@link CamsClientError} If the body is not JSON or does not match the schema.
1553
+ */
1554
+ async function readBody(schema, response) {
1555
+ let text;
1556
+ try {
1557
+ text = await response.text();
1558
+ } catch (error) {
1559
+ throw new CamsClientError("The answer of the Commerce App Management Service was cut off", {
1560
+ cause: error,
1561
+ retryable: true
1562
+ });
1563
+ }
1564
+ let body;
1565
+ try {
1566
+ body = JSON.parse(text);
1567
+ } catch (error) {
1568
+ throw new CamsClientError("The Commerce App Management Service sent an answer that is not JSON", { cause: error });
1569
+ }
1570
+ return parseBody(schema, body);
1571
+ }
1572
+ /**
1573
+ * Waits for the answer of a request and reads it. An error answer that `readError` turns into an
1574
+ * outcome is returned as that outcome.
1575
+ *
1576
+ * @param request - The request sent with the HTTP client.
1577
+ * @param read - Reads an answer with a success status.
1578
+ * @param readError - Reads an error answer as an outcome, or returns `undefined` when it is not
1579
+ * one.
1580
+ *
1581
+ * @throws A {@link CamsClientError} If the request got no answer, the answer is an error that is
1582
+ * not an outcome, or the answer does not have the expected shape.
1583
+ */
1584
+ async function send(request, read, readError) {
1585
+ let response;
1586
+ try {
1587
+ response = await request;
1588
+ } catch (error) {
1589
+ if (error instanceof ky.TimeoutError) throw new CamsClientError(`The Commerce App Management Service did not answer within ${CAMS_REQUEST_TIMEOUT_MS / 1e3} seconds`, {
1590
+ cause: error,
1591
+ retryable: true
1592
+ });
1593
+ if (error instanceof TypeError) throw new CamsClientError("The Commerce App Management Service could not be reached", {
1594
+ cause: error,
1595
+ retryable: true
1596
+ });
1597
+ if (!(error instanceof ky.HTTPError)) throw error;
1598
+ const answer = await readErrorAnswer(error.response);
1599
+ const outcome = readError?.(answer);
1600
+ if (outcome !== void 0) return outcome;
1601
+ throw toCamsResponseError(error, answer);
1602
+ }
1603
+ return await read(response);
1604
+ }
1605
+
1606
+ // ../../packages-private/cams-client/source/lib/schema.ts
1607
+ /** The statuses a lifecycle run and each of its steps can have. */
1608
+ const RUN_STATUSES = [
1609
+ "pending",
1610
+ "in-progress",
1611
+ "succeeded",
1612
+ "failed"
1613
+ ];
1614
+ /** The lifecycle operations a plan or a run can carry out. */
1615
+ const LIFECYCLE_OPERATIONS = [
1616
+ "install",
1617
+ "uninstall",
1618
+ "upgrade"
1619
+ ];
1620
+ /** The schema of {@link ExtensionParams}. */
1621
+ const ExtensionParamsSchema = valibot.object({ extensionId: require_schemas.nonEmptyStringValueSchema("extensionId") });
1622
+ /** The schema of {@link RunParams}. */
1623
+ const RunParamsSchema = valibot.object({
1624
+ ...ExtensionParamsSchema.entries,
1739
1625
  runId: require_schemas.nonEmptyStringValueSchema("runId")
1740
1626
  });
1741
- /** The parameters to start a planned upgrade. */
1742
- const StartUpgradeParamsSchema = valibot.object({
1627
+ /** The schema of {@link StartParams}. */
1628
+ const StartParamsSchema = valibot.object({
1629
+ ...ExtensionParamsSchema.entries,
1630
+ planId: valibot.optional(require_schemas.nonEmptyStringValueSchema("planId"))
1631
+ });
1632
+ /** The schema of {@link PlannedStartParams}. */
1633
+ const PlannedStartParamsSchema = valibot.object({
1743
1634
  ...ExtensionParamsSchema.entries,
1744
1635
  planId: require_schemas.nonEmptyStringValueSchema("planId")
1745
1636
  });
1637
+ /** The severities of the issues that planning or validating a lifecycle operation finds. */
1638
+ const ISSUE_SEVERITIES = [
1639
+ "error",
1640
+ "warning",
1641
+ "info"
1642
+ ];
1643
+ /** The schema of {@link PlanningIssue}. */
1644
+ const PlanningIssueSchema = valibot.looseObject({
1645
+ blocking: valibot.boolean(),
1646
+ code: valibot.string(),
1647
+ domain: valibot.string(),
1648
+ message: valibot.string(),
1649
+ path: valibot.optional(valibot.array(valibot.string())),
1650
+ severity: valibot.optional(valibot.picklist(ISSUE_SEVERITIES))
1651
+ });
1652
+ /** The schema of {@link Plan}. */
1653
+ const PlanSchema = valibot.looseObject({
1654
+ id: valibot.string(),
1655
+ issues: valibot.array(PlanningIssueSchema),
1656
+ operation: valibot.picklist(LIFECYCLE_OPERATIONS),
1657
+ sourceVersion: valibot.nullable(valibot.string()),
1658
+ targetVersion: valibot.nullable(valibot.string())
1659
+ });
1660
+ /** The label of a step and its description. */
1661
+ const StepMetaSchema = valibot.object({
1662
+ description: valibot.nullish(valibot.string()),
1663
+ label: valibot.string()
1664
+ });
1665
+ /** An issue that the validation of an app found. */
1666
+ const ValidationIssueSchema = valibot.object({
1667
+ code: valibot.string(),
1668
+ details: valibot.optional(valibot.unknown()),
1669
+ message: valibot.string(),
1670
+ severity: valibot.picklist(ISSUE_SEVERITIES)
1671
+ });
1672
+ /** The validation result of one step of an installation and of its children. */
1673
+ const StepResultSchema = valibot.object({
1674
+ children: valibot.array(valibot.lazy(() => StepResultSchema)),
1675
+ issues: valibot.array(ValidationIssueSchema),
1676
+ meta: StepMetaSchema,
1677
+ name: valibot.string(),
1678
+ path: valibot.array(valibot.string())
1679
+ });
1680
+ /** The schema of {@link Validation}. */
1681
+ const ValidationSchema = valibot.object({
1682
+ result: StepResultSchema,
1683
+ summary: valibot.object({
1684
+ errors: valibot.number(),
1685
+ totalIssues: valibot.number(),
1686
+ warnings: valibot.number()
1687
+ }),
1688
+ valid: valibot.boolean()
1689
+ });
1690
+ /** The schema of {@link PlanPreview}. */
1691
+ const PlanPreviewSchema = valibot.object({
1692
+ ...ValidationSchema.entries,
1693
+ plan: PlanSchema
1694
+ });
1695
+ /** One step of a lifecycle run and its children. */
1696
+ const RunStepSchema = valibot.object({
1697
+ children: valibot.array(valibot.lazy(() => RunStepSchema)),
1698
+ id: valibot.string(),
1699
+ meta: StepMetaSchema,
1700
+ name: valibot.string(),
1701
+ path: valibot.array(valibot.string()),
1702
+ status: valibot.picklist(RUN_STATUSES)
1703
+ });
1704
+ /** The schema of {@link RunStatus}. */
1705
+ const RunStatusSchema = valibot.object({
1706
+ activations: valibot.optional(valibot.object({
1707
+ execution: valibot.optional(valibot.string()),
1708
+ start: valibot.string()
1709
+ })),
1710
+ completedAt: valibot.nullish(valibot.string()),
1711
+ data: valibot.optional(valibot.unknown()),
1712
+ error: valibot.nullish(valibot.object({
1713
+ key: valibot.string(),
1714
+ message: valibot.nullish(valibot.string()),
1715
+ path: valibot.array(valibot.string()),
1716
+ payload: valibot.optional(valibot.unknown())
1717
+ })),
1718
+ executionDeadline: valibot.optional(valibot.string()),
1719
+ id: valibot.string(),
1720
+ operation: valibot.optional(valibot.picklist(LIFECYCLE_OPERATIONS)),
1721
+ plan: valibot.optional(PlanSchema),
1722
+ planDiff: valibot.optional(valibot.unknown()),
1723
+ planId: valibot.optional(valibot.string()),
1724
+ previousAttemptId: valibot.nullish(valibot.string()),
1725
+ previousPlanId: valibot.nullish(valibot.string()),
1726
+ result: valibot.nullish(valibot.object({
1727
+ appVersion: valibot.string(),
1728
+ snapshotId: valibot.string()
1729
+ })),
1730
+ startedAt: valibot.string(),
1731
+ status: valibot.picklist(RUN_STATUSES),
1732
+ step: RunStepSchema,
1733
+ targetConfig: valibot.optional(valibot.unknown())
1734
+ });
1746
1735
 
1747
- // source/commands/common/cams/endpoints.ts
1748
- /** The path of the upgrades of an extension, relative to the base URL. */
1749
- function upgradesPath(extensionId) {
1750
- return `v1/extensions/${encodeURIComponent(extensionId)}/upgrades`;
1736
+ // ../../packages-private/cams-client/source/lib/refusals.ts
1737
+ /** The app is already at the version the operation would reach. */
1738
+ const AlreadyCurrentRefusalSchema = valibot.object({
1739
+ kind: valibot.literal("already-current"),
1740
+ message: valibot.string()
1741
+ });
1742
+ /** Another run is open. It carries the open `run` when the app named it, else `null`. */
1743
+ const InProgressRefusalSchema = valibot.object({
1744
+ kind: valibot.literal("in-progress"),
1745
+ message: valibot.string(),
1746
+ run: valibot.fallback(valibot.nullable(RunStatusSchema), null)
1747
+ });
1748
+ /** The configuration lacks required values. It carries the `fields` to set. */
1749
+ const MissingRequiredConfigurationRefusalSchema = valibot.object({
1750
+ fields: valibot.array(valibot.string()),
1751
+ kind: valibot.literal("missing-required-configuration"),
1752
+ message: valibot.string()
1753
+ });
1754
+ /** The app is not associated with the Commerce instance. */
1755
+ const NotAssociatedRefusalSchema = valibot.object({
1756
+ kind: valibot.literal("not-associated"),
1757
+ message: valibot.string()
1758
+ });
1759
+ /** The app is not installed on the Commerce instance. */
1760
+ const NotInstalledRefusalSchema = valibot.object({
1761
+ kind: valibot.literal("not-installed"),
1762
+ message: valibot.string()
1763
+ });
1764
+ /** Planning found blocking issues. It carries the `issues`. */
1765
+ const PlanBlockedRefusalSchema = valibot.object({
1766
+ issues: valibot.array(PlanningIssueSchema),
1767
+ kind: valibot.literal("plan-blocked"),
1768
+ message: valibot.string()
1769
+ });
1770
+ /** The plan to start is no longer the pending one. */
1771
+ const StalePlanRefusalSchema = valibot.object({
1772
+ kind: valibot.literal("stale-plan"),
1773
+ message: valibot.string()
1774
+ });
1775
+ /**
1776
+ * Reads an error answer as one of the refusals `refusals` lists: its code becomes the `kind`, and
1777
+ * the answer's message its `message`.
1778
+ *
1779
+ * @param answer - The error answer.
1780
+ * @param refusals - The variant of the refusals that the call documents.
1781
+ *
1782
+ * @returns The refusal, or `undefined` when the answer has none of their codes.
1783
+ * @throws A {@link CamsClientError} If the refusal does not carry what its code needs.
1784
+ */
1785
+ function readRefusal(answer, refusals) {
1786
+ const codes = refusals.options.map((refusal) => refusal.entries.kind.literal);
1787
+ if (answer.code === void 0 || !codes.includes(answer.code)) return;
1788
+ return parseBody(refusals, {
1789
+ ...answer.body,
1790
+ kind: answer.code,
1791
+ message: answer.message,
1792
+ run: answer.body.attempt
1793
+ });
1751
1794
  }
1795
+
1796
+ // ../../packages-private/cams-client/source/api/extensions/schema.ts
1797
+ /** The statuses an extension can have. */
1798
+ const EXTENSION_STATUSES = [
1799
+ "ASSOCIATED",
1800
+ "INSTALLING",
1801
+ "PARTIALLY_INSTALLED",
1802
+ "INSTALLED",
1803
+ "UNINSTALLING",
1804
+ "UNINSTALLED",
1805
+ "UNASSOCIATED",
1806
+ "UPGRADE_AVAILABLE",
1807
+ "UPGRADE_FAILED",
1808
+ "UPGRADE_SUCCEEDED",
1809
+ "UPGRADING"
1810
+ ];
1811
+ /** The workspace and the Commerce instance an extension is associated with. */
1812
+ const ExtensionScopeSchema = valibot.object({
1813
+ commerceBaseUrl: valibot.nullable(valibot.string()),
1814
+ commerceEnv: valibot.nullable(_adobe_aio_commerce_lib_core_commerce.CommerceEnvSchema),
1815
+ commerceId: valibot.string(),
1816
+ workspaceId: valibot.string(),
1817
+ workspaceName: valibot.string()
1818
+ });
1819
+ /** One entry of the status history of an extension. */
1820
+ const StatusEntrySchema = valibot.object({
1821
+ attemptId: valibot.nullable(valibot.string()),
1822
+ error: valibot.nullable(valibot.object({
1823
+ code: valibot.nullable(valibot.string()),
1824
+ message: valibot.nullable(valibot.string())
1825
+ })),
1826
+ seq: valibot.number(),
1827
+ source: valibot.picklist([
1828
+ "USER",
1829
+ "S2S",
1830
+ "SYSTEM"
1831
+ ]),
1832
+ status: valibot.picklist(EXTENSION_STATUSES),
1833
+ timestamp: valibot.string(),
1834
+ upgradeMode: valibot.nullable(valibot.picklist(["auto", "manual"])),
1835
+ userDisplayName: valibot.nullable(valibot.string()),
1836
+ version: valibot.nullable(valibot.string())
1837
+ });
1838
+ /** The metadata of an app, with its display fields typed and the rest kept as the app wrote it. */
1839
+ const AppMetadataSchema = valibot.looseObject({
1840
+ description: valibot.optional(valibot.string()),
1841
+ displayName: valibot.optional(valibot.string()),
1842
+ version: valibot.optional(valibot.string())
1843
+ });
1844
+ /** The schema of {@link AppConfig}. */
1845
+ const AppConfigSchema = valibot.looseObject({ metadata: valibot.optional(AppMetadataSchema) });
1846
+ /** The schema of {@link Extension}. */
1847
+ const ExtensionSchema = valibot.object({
1848
+ configuration: valibot.object({
1849
+ appConfig: valibot.nullable(AppConfigSchema),
1850
+ icon: valibot.nullable(valibot.string()),
1851
+ project: valibot.unknown(),
1852
+ status: valibot.array(StatusEntrySchema),
1853
+ workspace: valibot.unknown()
1854
+ }),
1855
+ createdAt: valibot.nullable(valibot.string()),
1856
+ currentStatus: valibot.nullable(valibot.picklist(EXTENSION_STATUSES)),
1857
+ currentVersion: valibot.string(),
1858
+ description: valibot.nullable(valibot.string()),
1859
+ disabled: valibot.boolean(),
1860
+ expiresAt: valibot.nullable(valibot.string()),
1861
+ extId: valibot.string(),
1862
+ extName: valibot.string(),
1863
+ extensionPoints: valibot.unknown(),
1864
+ id: valibot.string(),
1865
+ name: valibot.string(),
1866
+ rowVersion: valibot.number(),
1867
+ scope: ExtensionScopeSchema,
1868
+ supportEmail: valibot.nullable(valibot.string()),
1869
+ title: valibot.string(),
1870
+ updatedAt: valibot.nullable(valibot.string())
1871
+ });
1872
+ /** The extensions on a Commerce instance. */
1873
+ const ExtensionListSchema = valibot.array(ExtensionSchema);
1874
+ /** The outcomes of a refresh of the scope tree that the scope sync route answers. */
1875
+ const SCOPE_SYNC_ROUTE_OUTCOMES = ["REFRESHED", "STALE"];
1876
+ /** The outcomes of a refresh of the scope tree that an association reports. */
1877
+ const SCOPE_SYNC_OUTCOMES = [
1878
+ ...SCOPE_SYNC_ROUTE_OUTCOMES,
1879
+ "FAILED",
1880
+ "UNKNOWN"
1881
+ ];
1882
+ /** The schema of {@link ScopeSync}. */
1883
+ const ScopeSyncSchema = valibot.object({
1884
+ outcome: valibot.picklist(SCOPE_SYNC_ROUTE_OUTCOMES),
1885
+ scopes: valibot.array(valibot.unknown())
1886
+ });
1887
+ /** The schema of {@link Unassociation}. */
1888
+ const UnassociationSchema = valibot.object({
1889
+ appCleanup: valibot.picklist(["DONE", "NOOP"]),
1890
+ extension: ExtensionSchema
1891
+ });
1892
+ /** The schema of {@link UpdateExtensionParams}. */
1893
+ const UpdateExtensionParamsSchema = valibot.object({
1894
+ ...ExtensionParamsSchema.entries,
1895
+ appConfig: valibot.optional(valibot.record(valibot.string(), valibot.unknown())),
1896
+ description: valibot.optional(valibot.string()),
1897
+ disabled: valibot.optional(valibot.boolean()),
1898
+ extensionPoints: valibot.optional(valibot.record(valibot.string(), valibot.unknown())),
1899
+ icon: valibot.optional(valibot.string()),
1900
+ ifMatch: valibot.optional(valibot.string()),
1901
+ supportEmail: valibot.optional(valibot.string()),
1902
+ title: valibot.optional(valibot.string())
1903
+ });
1904
+ /** The refusals of an update of an extension, by `kind`. */
1905
+ const UpdateRefusalSchema = valibot.variant("kind", [valibot.object({
1906
+ kind: valibot.literal("stale-config"),
1907
+ message: valibot.string()
1908
+ })]);
1909
+ /** The refusals of an unassociation, by `kind`. */
1910
+ const UnassociationRefusalSchema = valibot.variant("kind", [InProgressRefusalSchema, valibot.object({
1911
+ kind: valibot.literal("uninstall-required"),
1912
+ message: valibot.string()
1913
+ })]);
1914
+
1915
+ // ../../packages-private/cams-client/source/api/association/schema.ts
1916
+ /** The schema of {@link AssociationParams}. */
1917
+ const AssociationParamsSchema = valibot.object({
1918
+ projectId: require_schemas.nonEmptyStringValueSchema("projectId"),
1919
+ workspaceId: require_schemas.nonEmptyStringValueSchema("workspaceId")
1920
+ });
1921
+ /** The app that an association would create, flattened from its project, workspace and metadata. */
1922
+ const PreviewAppSchema = valibot.object({
1923
+ appId: valibot.string(),
1924
+ description: valibot.optional(valibot.string()),
1925
+ displayName: valibot.optional(valibot.string()),
1926
+ projectId: valibot.string(),
1927
+ projectName: valibot.string(),
1928
+ version: valibot.optional(valibot.string()),
1929
+ workspaceId: valibot.string(),
1930
+ workspaceName: valibot.string()
1931
+ });
1932
+ /** The fields of every verdict that refuses the association. */
1933
+ const RefusedPreviewSchema = valibot.object({
1934
+ canAssociate: valibot.literal(false),
1935
+ message: valibot.string()
1936
+ });
1937
+ /** The schema of {@link AssociationPreview}. */
1938
+ const AssociationPreviewSchema = valibot.variant("canAssociate", [valibot.object({
1939
+ app: PreviewAppSchema,
1940
+ appConfig: valibot.looseObject({ metadata: AppMetadataSchema }),
1941
+ canAssociate: valibot.literal(true)
1942
+ }), valibot.variant("reasonCode", [
1943
+ valibot.object({
1944
+ ...RefusedPreviewSchema.entries,
1945
+ reasonCode: valibot.picklist(["app-not-associable", "invalid-app-config"])
1946
+ }),
1947
+ valibot.object({
1948
+ ...RefusedPreviewSchema.entries,
1949
+ existingAssociationId: valibot.string(),
1950
+ reasonCode: valibot.literal("duplicate-association")
1951
+ }),
1952
+ valibot.object({
1953
+ ...RefusedPreviewSchema.entries,
1954
+ existingAssociationId: valibot.string(),
1955
+ existingCommerceId: valibot.string(),
1956
+ reasonCode: valibot.literal("workspace-already-associated")
1957
+ })
1958
+ ])]);
1959
+ /** The schema of {@link Association}. */
1960
+ const AssociationSchema = valibot.object({
1961
+ ...ExtensionSchema.entries,
1962
+ scopeSync: valibot.optional(valibot.picklist(SCOPE_SYNC_OUTCOMES))
1963
+ });
1964
+ /** The refusals of an association, by `kind`. */
1965
+ const AssociationRefusalSchema = valibot.variant("kind", [valibot.object({
1966
+ divergent: valibot.boolean(),
1967
+ existingId: valibot.optional(valibot.string()),
1968
+ kind: valibot.literal("duplicate-association"),
1969
+ message: valibot.string()
1970
+ }), valibot.object({
1971
+ commerceId: valibot.string(),
1972
+ existingId: valibot.string(),
1973
+ kind: valibot.literal("workspace-already-associated"),
1974
+ message: valibot.string()
1975
+ })]);
1976
+
1977
+ // ../../packages-private/cams-client/source/api/association/endpoints.ts
1752
1978
  /**
1753
- * Reads the JSON body of an answer and checks it against the schema.
1754
- * @throws A {@link CamsClientError} If the body is not JSON or does not match the schema.
1979
+ * Tells whether a workspace can be associated with the Commerce instance of the HTTP client,
1980
+ * without changing anything.
1981
+ *
1982
+ * @param httpClient - The client the request goes through, with the user's token and organization.
1983
+ * @param params - The project and the workspace to associate.
1984
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1985
+ *
1986
+ * @returns The app that the association would create, or the reason it cannot be created.
1987
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1988
+ * @throws A {@link CamsClientError} If the request fails.
1755
1989
  */
1756
- async function parseBody(schema, body) {
1757
- const parsed = valibot.safeParse(schema, body);
1758
- if (!parsed.success) throw new CamsClientError("The Commerce App Management Service sent an unexpected answer", { cause: new valibot.ValiError(parsed.issues) });
1759
- return parsed.output;
1990
+ async function previewAssociation(httpClient, params, fetchOptions) {
1991
+ const json = require_utils.parseOrThrow(AssociationParamsSchema, params);
1992
+ return await send(httpClient.post("v1/extensions/association/preview", {
1993
+ ...fetchOptions,
1994
+ json
1995
+ }), (response) => readBody(AssociationPreviewSchema, response));
1760
1996
  }
1761
1997
  /**
1762
- * Reads the JSON body of a response and checks it against the schema.
1763
- * @throws A {@link CamsClientError} If the body is not JSON or does not match the schema.
1998
+ * Associates a workspace with the Commerce instance of the HTTP client.
1999
+ *
2000
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2001
+ * @param params - The project and the workspace to associate.
2002
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2003
+ *
2004
+ * @returns The created extension and how the refresh of its scope tree ended, or why the workspace
2005
+ * cannot be associated: `duplicate-association` when it already is with this instance, or
2006
+ * `workspace-already-associated` when it is with another one.
2007
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2008
+ * @throws A {@link CamsClientError} If the request fails.
1764
2009
  */
1765
- async function readAndParseBody(schema, request) {
1766
- const response = await request;
1767
- try {
1768
- return parseBody(schema, await response.json());
1769
- } catch (error) {
1770
- throw new CamsClientError("The Commerce App Management Service sent an answer that is not JSON", { cause: error });
2010
+ async function createAssociation(httpClient, params, fetchOptions) {
2011
+ const json = require_utils.parseOrThrow(AssociationParamsSchema, params);
2012
+ return await send(httpClient.post("v1/extensions/association", {
2013
+ ...fetchOptions,
2014
+ json
2015
+ }), async (response) => ({
2016
+ association: await readBody(AssociationSchema, response),
2017
+ kind: "associated"
2018
+ }), (answer) => readRefusal(answer, AssociationRefusalSchema));
2019
+ }
2020
+
2021
+ // ../../packages-private/cams-client/source/api/extensions/endpoints.ts
2022
+ /**
2023
+ * Lists the extensions on the Commerce instance of the HTTP client.
2024
+ *
2025
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2026
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2027
+ *
2028
+ * @throws A {@link CamsClientError} If the request fails.
2029
+ */
2030
+ async function getAllExtensions(httpClient, fetchOptions) {
2031
+ return await send(httpClient.get("v1/extensions", fetchOptions), (response) => readBody(ExtensionListSchema, response));
2032
+ }
2033
+ /**
2034
+ * Gets an extension by its id.
2035
+ *
2036
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2037
+ * @param params - The extension to get.
2038
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2039
+ *
2040
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2041
+ * @throws A {@link CamsClientError} If the request fails.
2042
+ */
2043
+ async function getExtensionById(httpClient, params, fetchOptions) {
2044
+ const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
2045
+ return await send(httpClient.get(`v1/extensions/${encodeURIComponent(extensionId)}`, fetchOptions), (response) => readBody(ExtensionSchema, response));
2046
+ }
2047
+ /**
2048
+ * Updates the given fields of an extension.
2049
+ *
2050
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2051
+ * @param params - The extension, the fields to change and, optionally, the version to change.
2052
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2053
+ *
2054
+ * @returns The updated extension, or `stale-config` when the version to change is not the current
2055
+ * one.
2056
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2057
+ * @throws A {@link CamsClientError} If the request fails.
2058
+ */
2059
+ async function updateExtension(httpClient, params, fetchOptions) {
2060
+ const { extensionId, ifMatch, ...fields } = require_utils.parseOrThrow(UpdateExtensionParamsSchema, params);
2061
+ const headers = new Headers(fetchOptions?.headers);
2062
+ if (ifMatch !== void 0) headers.set("If-Match", ifMatch);
2063
+ return await send(httpClient.patch(`v1/extensions/${encodeURIComponent(extensionId)}`, {
2064
+ ...fetchOptions,
2065
+ headers,
2066
+ json: fields
2067
+ }), async (response) => ({
2068
+ extension: await readBody(ExtensionSchema, response),
2069
+ kind: "updated"
2070
+ }), (answer) => readRefusal(answer, UpdateRefusalSchema));
2071
+ }
2072
+ /**
2073
+ * Unassociates an extension that is not installed. It never uninstalls the app.
2074
+ *
2075
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2076
+ * @param params - The extension to unassociate.
2077
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2078
+ *
2079
+ * @returns The unassociated extension with the cleanup result, `already-unassociated`, or why it
2080
+ * was not unassociated: `uninstall-required` while the app is installed, or `in-progress` while a
2081
+ * run is open.
2082
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2083
+ * @throws A {@link CamsClientError} If the request fails, for example with `app-cleanup-failed`.
2084
+ */
2085
+ async function deleteExtension(httpClient, params, fetchOptions) {
2086
+ const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
2087
+ return await send(httpClient.delete(`v1/extensions/${encodeURIComponent(extensionId)}`, fetchOptions), async (response) => response.status === _adobe_aio_commerce_lib_core_responses.HTTP_NO_CONTENT ? { kind: "already-unassociated" } : {
2088
+ kind: "unassociated",
2089
+ unassociation: await readBody(UnassociationSchema, response)
2090
+ }, (answer) => readRefusal(answer, UnassociationRefusalSchema));
2091
+ }
2092
+ /**
2093
+ * Asks the app of an extension to refresh its scope tree from the Commerce instance.
2094
+ *
2095
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2096
+ * @param params - The extension to refresh the scopes of.
2097
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2098
+ *
2099
+ * @returns The outcome of the refresh and the scope tree.
2100
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2101
+ * @throws A {@link CamsClientError} If the request fails.
2102
+ */
2103
+ async function syncExtensionScopes(httpClient, params, fetchOptions) {
2104
+ const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
2105
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/scopes/sync`, fetchOptions), (response) => readBody(ScopeSyncSchema, response));
2106
+ }
2107
+
2108
+ // ../../packages-private/cams-client/source/lib/runs.ts
2109
+ /** How many retryable failures in a row following a run allows before it stops. */
2110
+ const DEFAULT_MAX_CONSECUTIVE_FAILURES = 10;
2111
+ /** The default milliseconds between two syncs of a followed run. */
2112
+ const POLL_INTERVAL_MS = 2e3;
2113
+ /** Waits for the given milliseconds, or rejects with the reason of the signal once it aborts. */
2114
+ async function wait(ms, signal) {
2115
+ await new Promise((resolve, reject) => {
2116
+ signal?.throwIfAborted();
2117
+ const onAbort = () => {
2118
+ clearTimeout(timer);
2119
+ reject(signal?.reason);
2120
+ };
2121
+ const timer = setTimeout(() => {
2122
+ signal?.removeEventListener("abort", onAbort);
2123
+ resolve();
2124
+ }, ms);
2125
+ signal?.addEventListener("abort", onAbort, { once: true });
2126
+ });
2127
+ }
2128
+ /** Whether the run will not change anymore: it succeeded or failed. */
2129
+ function isRunFinished(run) {
2130
+ return run.status === "succeeded" || run.status === "failed";
2131
+ }
2132
+ /**
2133
+ * Reads the run that a 409 `attempt-not-open` carries.
2134
+ *
2135
+ * @param answer - The error answer of a sync.
2136
+ *
2137
+ * @returns The run, or `undefined` for any other answer.
2138
+ * @throws A {@link CamsClientError} If the run does not have the expected shape.
2139
+ */
2140
+ function readRunNotOpen(answer) {
2141
+ return answer.status === _adobe_aio_commerce_lib_core_responses.HTTP_CONFLICT && answer.code === "attempt-not-open" && answer.body.attempt !== void 0 ? parseBody(RunStatusSchema, answer.body.attempt) : void 0;
2142
+ }
2143
+ /**
2144
+ * Builds the functions that sync, follow and read the runs of a lifecycle operation, with the
2145
+ * endpoint signature `(httpClient, params, options)`.
2146
+ *
2147
+ * @param operation - The path segment of the operation under an extension, such as `upgrades`.
2148
+ */
2149
+ function createRunEndpoints(operation) {
2150
+ function pathOf(params) {
2151
+ const { extensionId, runId } = require_utils.parseOrThrow(RunParamsSchema, params);
2152
+ return `v1/extensions/${encodeURIComponent(extensionId)}/${operation}/${encodeURIComponent(runId)}`;
2153
+ }
2154
+ async function syncRun(httpClient, params, fetchOptions) {
2155
+ return await send(httpClient.post(`${pathOf(params)}/sync`, {
2156
+ ...fetchOptions,
2157
+ retry: 0
2158
+ }), (response) => readBody(RunStatusSchema, response), readRunNotOpen);
1771
2159
  }
2160
+ async function* followRun(httpClient, params, options = {}) {
2161
+ const { pollInterval = POLL_INTERVAL_MS, maxConsecutiveFailures = 10, onRetry, ...fetchOptions } = options;
2162
+ const { signal } = fetchOptions;
2163
+ let failures = 0;
2164
+ while (true) {
2165
+ try {
2166
+ const run = await syncRun(httpClient, params, fetchOptions);
2167
+ failures = 0;
2168
+ yield run;
2169
+ if (isRunFinished(run)) return;
2170
+ } catch (error) {
2171
+ signal?.throwIfAborted();
2172
+ failures += 1;
2173
+ if (!(error instanceof CamsClientError && error.retryable) || failures >= maxConsecutiveFailures) throw error;
2174
+ onRetry?.(error, failures);
2175
+ }
2176
+ await wait(pollInterval, signal);
2177
+ }
2178
+ }
2179
+ async function getRun(httpClient, params, fetchOptions) {
2180
+ return await send(httpClient.get(pathOf(params), fetchOptions), (response) => readBody(RunStatusSchema, response));
2181
+ }
2182
+ return {
2183
+ followRun,
2184
+ getRun,
2185
+ syncRun
2186
+ };
1772
2187
  }
2188
+
2189
+ // ../../packages-private/cams-client/source/api/installation/schema.ts
2190
+ /** The answer to an installation started without a plan, with the run under `installation`. */
2191
+ const InstallationRunSchema = valibot.object({ installation: RunStatusSchema });
2192
+ /** The answer to a preview: the validation, with the plan of an app that has lifecycle plans. */
2193
+ const InstallationPreviewSchema = valibot.object({
2194
+ ...ValidationSchema.entries,
2195
+ plan: valibot.optional(PlanSchema)
2196
+ });
2197
+ /** The schema of {@link NotInstallableRefusal}. */
2198
+ const NotInstallableRefusalSchema = valibot.object({
2199
+ kind: valibot.literal("not-installable"),
2200
+ message: valibot.string()
2201
+ });
2202
+ /** The refusals of an installation preview, by `kind`. */
2203
+ const InstallationPreviewRefusalSchema = valibot.variant("kind", [
2204
+ AlreadyCurrentRefusalSchema,
2205
+ InProgressRefusalSchema,
2206
+ NotAssociatedRefusalSchema,
2207
+ NotInstallableRefusalSchema,
2208
+ PlanBlockedRefusalSchema
2209
+ ]);
2210
+ /** The refusals of an installation start, by `kind`. */
2211
+ const InstallationStartRefusalSchema = valibot.variant("kind", [
2212
+ ...InstallationPreviewRefusalSchema.options,
2213
+ MissingRequiredConfigurationRefusalSchema,
2214
+ StalePlanRefusalSchema
2215
+ ]);
2216
+
2217
+ // ../../packages-private/cams-client/source/api/installation/endpoints.ts
1773
2218
  /**
1774
- * Finds the extension associated with a workspace.
2219
+ * Asks the app of an extension for an installation plan, without changing anything.
1775
2220
  *
1776
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1777
- * @param params - The workspace to look the extension up by.
1778
- * @param fetchOptions - The {@link Options} to use to make the request.
2221
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2222
+ * @param params - The extension to plan the installation for.
2223
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1779
2224
  *
1780
- * @returns The extension, or `null` when the workspace is not associated.
2225
+ * @returns The plan with its validation, or why there is none: `validated` with the validation of
2226
+ * an app without lifecycle plans, `no-plan` when the app validates nothing either, or a refusal,
2227
+ * for example `plan-blocked` with the blocking issues or `not-installable` when the app is already
2228
+ * installed.
2229
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2230
+ * @throws A {@link CamsClientError} If the request fails.
2231
+ */
2232
+ async function previewInstallation(httpClient, params, fetchOptions) {
2233
+ const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
2234
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/installation/preview`, fetchOptions), async (response) => {
2235
+ if (response.status === _adobe_aio_commerce_lib_core_responses.HTTP_NO_CONTENT) return { kind: "no-plan" };
2236
+ const { plan, ...validation } = await readBody(InstallationPreviewSchema, response);
2237
+ return plan === void 0 ? {
2238
+ kind: "validated",
2239
+ validation
2240
+ } : {
2241
+ kind: "planned",
2242
+ preview: {
2243
+ ...validation,
2244
+ plan
2245
+ }
2246
+ };
2247
+ }, (answer) => readRefusal(answer, InstallationPreviewRefusalSchema));
2248
+ }
2249
+ /**
2250
+ * Starts the installation with the plan, or without one for an app without lifecycle plans.
2251
+ *
2252
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2253
+ * @param params - The extension and the plan to start.
2254
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2255
+ *
2256
+ * @returns The new run, `installed` with the extension when a start without a plan had nothing to
2257
+ * run, or why it did not start: for example `stale-plan` when the plan is no longer the pending
2258
+ * one, or `in-progress` with the open run.
1781
2259
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1782
- * @throws An {@link HTTPError} If the status code is not 2XX.
2260
+ * @throws A {@link CamsClientError} If the request fails.
1783
2261
  */
1784
- async function findExtension(httpClient, params, fetchOptions) {
1785
- const { workspaceId } = require_utils.parseOrThrow(FindExtensionParamsSchema, params);
1786
- const [extension] = await readAndParseBody(ExtensionListSchema, httpClient.get(`v1/workspaces/${encodeURIComponent(workspaceId)}/extensions`, fetchOptions));
1787
- return extension ?? null;
2262
+ async function startInstallation(httpClient, params, fetchOptions) {
2263
+ const { extensionId, planId } = require_utils.parseOrThrow(StartParamsSchema, params);
2264
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/installation`, {
2265
+ ...fetchOptions,
2266
+ json: planId === void 0 ? void 0 : { planId }
2267
+ }), async (response) => {
2268
+ if (planId !== void 0) return {
2269
+ kind: "started",
2270
+ run: await readBody(RunStatusSchema, response)
2271
+ };
2272
+ if (response.status === _adobe_aio_commerce_lib_core_responses.HTTP_OK) return {
2273
+ extension: await readBody(ExtensionSchema, response),
2274
+ kind: "installed"
2275
+ };
2276
+ const { installation } = await readBody(InstallationRunSchema, response);
2277
+ return {
2278
+ kind: "started",
2279
+ run: installation
2280
+ };
2281
+ }, (answer) => readRefusal(answer, InstallationStartRefusalSchema));
1788
2282
  }
2283
+ /** The run endpoints of the installations. */
2284
+ const installationRuns = createRunEndpoints("installation");
2285
+ /**
2286
+ * Syncs an installation run once: CAMS reads it from the app and records its outcome once it ended.
2287
+ * A run that is no longer the open one comes back as the app reports it, and nothing is recorded.
2288
+ * The request is not retried.
2289
+ *
2290
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2291
+ * @throws A {@link CamsClientError} If the request fails.
2292
+ */
2293
+ const syncInstallationRun = installationRuns.syncRun;
1789
2294
  /**
1790
- * Asks CAMS to plan an upgrade of the extension.
2295
+ * Syncs an installation run until it succeeds or fails, and yields its status after each sync. A
2296
+ * retryable failure, such as a timeout or a 503, is synced again after the poll interval, until too
2297
+ * many syncs in a row failed. An aborted signal ends it with the signal's reason.
1791
2298
  *
1792
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
2299
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2300
+ * @throws A {@link CamsClientError} If a sync fails with a failure that is not retryable, or too
2301
+ * many syncs in a row failed.
2302
+ */
2303
+ const followInstallationRun = installationRuns.followRun;
2304
+ /**
2305
+ * Reads an installation run without changing anything.
2306
+ *
2307
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2308
+ * @throws A {@link CamsClientError} If the request fails.
2309
+ */
2310
+ const getInstallationRun = installationRuns.getRun;
2311
+
2312
+ // ../../packages-private/cams-client/source/api/uninstallation/schema.ts
2313
+ /** The answer to an uninstallation started without a plan, with the run under `uninstallation`. */
2314
+ const UninstallationRunSchema = valibot.object({ uninstallation: RunStatusSchema });
2315
+ /** The answer to an uninstallation without a plan that needed no run. */
2316
+ const UninstallationResultSchema = valibot.object({ extension: ExtensionSchema });
2317
+ /** The refusals of an uninstallation preview, by `kind`. */
2318
+ const UninstallationPreviewRefusalSchema = valibot.variant("kind", [
2319
+ InProgressRefusalSchema,
2320
+ NotAssociatedRefusalSchema,
2321
+ PlanBlockedRefusalSchema
2322
+ ]);
2323
+ /** The refusals of an uninstallation start, by `kind`. */
2324
+ const UninstallationStartRefusalSchema = valibot.variant("kind", [
2325
+ ...UninstallationPreviewRefusalSchema.options,
2326
+ NotInstalledRefusalSchema,
2327
+ valibot.object({
2328
+ kind: valibot.literal("nothing-to-uninstall"),
2329
+ message: valibot.string()
2330
+ }),
2331
+ StalePlanRefusalSchema
2332
+ ]);
2333
+
2334
+ // ../../packages-private/cams-client/source/api/uninstallation/endpoints.ts
2335
+ /**
2336
+ * Asks the app of an extension for an uninstallation plan, without changing anything.
2337
+ *
2338
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2339
+ * @param params - The extension to plan the uninstallation for.
2340
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2341
+ *
2342
+ * @returns The plan with its validation, `no-plan` when the uninstallation needs none, or why there
2343
+ * is no plan: for example `plan-blocked` with the blocking issues.
2344
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2345
+ * @throws A {@link CamsClientError} If the request fails.
2346
+ */
2347
+ async function previewUninstallation(httpClient, params, fetchOptions) {
2348
+ const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
2349
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/uninstallation/preview`, fetchOptions), async (response) => response.status === _adobe_aio_commerce_lib_core_responses.HTTP_NO_CONTENT ? { kind: "no-plan" } : {
2350
+ kind: "planned",
2351
+ preview: await readBody(PlanPreviewSchema, response)
2352
+ }, (answer) => readRefusal(answer, UninstallationPreviewRefusalSchema));
2353
+ }
2354
+ /**
2355
+ * Starts the uninstallation with the plan, or without one when the preview returned `no-plan`. It
2356
+ * never unassociates the extension.
2357
+ *
2358
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2359
+ * @param params - The extension and the plan to start.
2360
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2361
+ *
2362
+ * @returns The new run, `uninstalled` with the extension when a start without a plan had nothing to
2363
+ * run, or why it did not start: for example `stale-plan` when the plan is no longer the pending
2364
+ * one, `nothing-to-uninstall` when the app needs a start without a plan, or `in-progress` with the
2365
+ * open run.
2366
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2367
+ * @throws A {@link CamsClientError} If the request fails.
2368
+ */
2369
+ async function startUninstallation(httpClient, params, fetchOptions) {
2370
+ const { extensionId, planId } = require_utils.parseOrThrow(StartParamsSchema, params);
2371
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/uninstallation`, {
2372
+ ...fetchOptions,
2373
+ json: planId === void 0 ? void 0 : { planId }
2374
+ }), async (response) => {
2375
+ if (planId !== void 0) return {
2376
+ kind: "started",
2377
+ run: await readBody(RunStatusSchema, response)
2378
+ };
2379
+ if (response.status === _adobe_aio_commerce_lib_core_responses.HTTP_OK) {
2380
+ const { extension } = await readBody(UninstallationResultSchema, response);
2381
+ return {
2382
+ extension,
2383
+ kind: "uninstalled"
2384
+ };
2385
+ }
2386
+ const { uninstallation } = await readBody(UninstallationRunSchema, response);
2387
+ return {
2388
+ kind: "started",
2389
+ run: uninstallation
2390
+ };
2391
+ }, (answer) => readRefusal(answer, UninstallationStartRefusalSchema));
2392
+ }
2393
+ /** The run endpoints of the uninstallations. */
2394
+ const uninstallationRuns = createRunEndpoints("uninstallation");
2395
+ /**
2396
+ * Syncs an uninstallation run once: CAMS reads it from the app and records its outcome once it
2397
+ * ended. A run that is no longer the open one comes back as the app reports it, and nothing is
2398
+ * recorded. The request is not retried.
2399
+ *
2400
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2401
+ * @throws A {@link CamsClientError} If the request fails.
2402
+ */
2403
+ const syncUninstallationRun = uninstallationRuns.syncRun;
2404
+ /**
2405
+ * Syncs an uninstallation run until it succeeds or fails, and yields its status after each sync.
2406
+ * A retryable failure, such as a timeout or a 503, is synced again after the poll interval, until
2407
+ * too many syncs in a row failed. An aborted signal ends it with the signal's reason.
2408
+ *
2409
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2410
+ * @throws A {@link CamsClientError} If a sync fails with a failure that is not retryable, or too
2411
+ * many syncs in a row failed.
2412
+ */
2413
+ const followUninstallationRun = uninstallationRuns.followRun;
2414
+ /**
2415
+ * Reads an uninstallation run without changing anything.
2416
+ *
2417
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2418
+ * @throws A {@link CamsClientError} If the request fails.
2419
+ */
2420
+ const getUninstallationRun = uninstallationRuns.getRun;
2421
+
2422
+ // ../../packages-private/cams-client/source/api/upgrades/schema.ts
2423
+ /** The schema of {@link UpgradeConflictRefusal}. */
2424
+ const UpgradeConflictRefusalSchema = valibot.object({
2425
+ kind: valibot.literal("upgrade-conflict"),
2426
+ message: valibot.string()
2427
+ });
2428
+ /** The refusals of an upgrade preview, by `kind`. */
2429
+ const UpgradePreviewRefusalSchema = valibot.variant("kind", [
2430
+ AlreadyCurrentRefusalSchema,
2431
+ InProgressRefusalSchema,
2432
+ NotAssociatedRefusalSchema,
2433
+ NotInstalledRefusalSchema,
2434
+ PlanBlockedRefusalSchema,
2435
+ UpgradeConflictRefusalSchema
2436
+ ]);
2437
+ /** The refusals of an upgrade start, by `kind`. */
2438
+ const UpgradeStartRefusalSchema = valibot.variant("kind", [
2439
+ ...UpgradePreviewRefusalSchema.options,
2440
+ MissingRequiredConfigurationRefusalSchema,
2441
+ StalePlanRefusalSchema
2442
+ ]);
2443
+
2444
+ // ../../packages-private/cams-client/source/api/upgrades/endpoints.ts
2445
+ /**
2446
+ * Asks the app of an extension for an upgrade plan. CAMS records that an upgrade is available.
2447
+ *
2448
+ * @param httpClient - The client the request goes through, with the user's token and organization.
1793
2449
  * @param params - The extension to plan the upgrade for.
1794
- * @param fetchOptions - The {@link Options} to use to make the request.
2450
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1795
2451
  *
2452
+ * @returns The plan with its validation, or why there is none: for example `already-current` when
2453
+ * the app is up to date, or `upgrade-conflict` while an upgrade runs.
1796
2454
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1797
- * @throws An {@link HTTPError} If the status code is not 2XX.
2455
+ * @throws A {@link CamsClientError} If the request fails.
1798
2456
  */
1799
- async function planUpgrade$1(httpClient, params, fetchOptions) {
2457
+ async function previewUpgrade(httpClient, params, fetchOptions) {
1800
2458
  const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
1801
- const { plan } = await readAndParseBody(UpgradePlanAnswerSchema, httpClient.post(`${upgradesPath(extensionId)}/preview`, fetchOptions));
1802
- return plan;
2459
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/upgrades/preview`, fetchOptions), async (response) => ({
2460
+ kind: "planned",
2461
+ preview: await readBody(PlanPreviewSchema, response)
2462
+ }), (answer) => readRefusal(answer, UpgradePreviewRefusalSchema));
1803
2463
  }
1804
2464
  /**
1805
2465
  * Starts the planned upgrade.
1806
2466
  *
1807
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
2467
+ * @param httpClient - The client the request goes through, with the user's token and organization.
1808
2468
  * @param params - The extension and the plan to start.
1809
- * @param fetchOptions - The {@link Options} to use to make the request.
2469
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1810
2470
  *
1811
- * @returns The status of the new attempt.
2471
+ * @returns The new run, or why it did not start: for example `stale-plan` when the plan is no
2472
+ * longer the pending one, or `in-progress` with the open run.
1812
2473
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1813
- * @throws An {@link HTTPError} If the status code is not 2XX.
2474
+ * @throws A {@link CamsClientError} If the request fails.
1814
2475
  */
1815
2476
  async function startUpgrade$1(httpClient, params, fetchOptions) {
1816
- const { extensionId, planId } = require_utils.parseOrThrow(StartUpgradeParamsSchema, params);
1817
- return await readAndParseBody(AttemptStatusSchema, httpClient.post(upgradesPath(extensionId), {
2477
+ const { extensionId, planId } = require_utils.parseOrThrow(PlannedStartParamsSchema, params);
2478
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/upgrades`, {
1818
2479
  ...fetchOptions,
1819
2480
  json: { planId }
1820
- }));
2481
+ }), async (response) => ({
2482
+ kind: "started",
2483
+ run: await readBody(RunStatusSchema, response)
2484
+ }), (answer) => readRefusal(answer, UpgradeStartRefusalSchema));
1821
2485
  }
2486
+ /** The run endpoints of the upgrades. */
2487
+ const upgradeRuns = createRunEndpoints("upgrades");
1822
2488
  /**
1823
- * Reads the status of an attempt once.
2489
+ * Syncs an upgrade run once: CAMS reads it from the app and records its outcome once it ended. A
2490
+ * run that is no longer the open one comes back as the app reports it, and nothing is recorded. The
2491
+ * request is not retried.
1824
2492
  *
1825
- * The request is not retried, because the polling loop is the retry.
2493
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2494
+ * @throws A {@link CamsClientError} If the request fails.
2495
+ */
2496
+ const syncUpgradeRun = upgradeRuns.syncRun;
2497
+ /**
2498
+ * Syncs an upgrade run until it succeeds or fails, and yields its status after each sync. A
2499
+ * retryable failure, such as a timeout or a 503, is synced again after the poll interval, until too
2500
+ * many syncs in a row failed. An aborted signal ends it with the signal's reason.
1826
2501
  *
1827
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1828
- * @param params - The extension and the attempt to read.
1829
- * @param fetchOptions - The {@link Options} to use to make the request.
2502
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2503
+ * @throws A {@link CamsClientError} If a sync fails with a failure that is not retryable, or too
2504
+ * many syncs in a row failed.
2505
+ */
2506
+ const followUpgradeRun = upgradeRuns.followRun;
2507
+ /**
2508
+ * Reads an upgrade run without changing anything.
1830
2509
  *
1831
2510
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1832
- * @throws An {@link HTTPError} If the status code is not 2XX.
2511
+ * @throws A {@link CamsClientError} If the request fails.
1833
2512
  */
1834
- async function pollUpgrade(httpClient, params, fetchOptions) {
1835
- const { extensionId, runId } = require_utils.parseOrThrow(FindAttemptParamsSchema, params);
1836
- return await readAndParseBody(AttemptStatusSchema, httpClient.post(`${upgradesPath(extensionId)}/${encodeURIComponent(runId)}/sync`, {
1837
- ...fetchOptions,
1838
- retry: 0
1839
- }));
2513
+ const getUpgradeRun = upgradeRuns.getRun;
2514
+ /**
2515
+ * Reads the latest upgrade run without changing anything. Runs of another operation do not count.
2516
+ *
2517
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2518
+ * @param params - The extension to read the latest run of.
2519
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2520
+ *
2521
+ * @returns The run, or `null` when there is none.
2522
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2523
+ * @throws A {@link CamsClientError} If the request fails.
2524
+ */
2525
+ async function getLatestUpgradeRun(httpClient, params, fetchOptions) {
2526
+ const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
2527
+ return await send(httpClient.get(`v1/extensions/${encodeURIComponent(extensionId)}/upgrades`, fetchOptions), async (response) => response.status === _adobe_aio_commerce_lib_core_responses.HTTP_NO_CONTENT ? null : await readBody(RunStatusSchema, response));
1840
2528
  }
2529
+
2530
+ // ../../packages-private/cams-client/source/api/workspaces/schema.ts
2531
+ /** The schema of {@link WorkspaceParams}. */
2532
+ const WorkspaceParamsSchema = valibot.object({ workspaceId: require_schemas.nonEmptyStringValueSchema("workspaceId") });
2533
+ /** The extensions associated with a workspace, with only their id, status and scope. */
2534
+ const WorkspaceExtensionListSchema = valibot.array(valibot.pick(ExtensionSchema, [
2535
+ "currentStatus",
2536
+ "id",
2537
+ "scope"
2538
+ ]));
2539
+
2540
+ // ../../packages-private/cams-client/source/api/workspaces/endpoints.ts
1841
2541
  /**
1842
- * Reads the latest upgrade attempt without changing anything. Attempts that ran another operation
1843
- * do not count.
2542
+ * Gets the extension associated with a workspace. CAMS also lists the workspace's unassociated
2543
+ * extensions for a while, which this skips.
1844
2544
  *
1845
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1846
- * @param params - The extension to read the latest attempt of.
1847
- * @param fetchOptions - The {@link Options} to use to make the request.
2545
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2546
+ * @param params - The workspace to look the extension up by.
2547
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1848
2548
  *
1849
- * @returns The attempt, or `null` when there is none.
2549
+ * @returns The extension, or `null` when the workspace is not associated.
1850
2550
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1851
- * @throws An {@link HTTPError} If the status code is not 2XX.
2551
+ * @throws A {@link CamsClientError} If the request fails.
2552
+ */
2553
+ async function getWorkspaceExtension(httpClient, params, fetchOptions) {
2554
+ const { workspaceId } = require_utils.parseOrThrow(WorkspaceParamsSchema, params);
2555
+ return (await send(httpClient.get(`v1/workspaces/${encodeURIComponent(workspaceId)}/extensions`, fetchOptions), (response) => readBody(WorkspaceExtensionListSchema, response))).find((extension) => extension.currentStatus !== "UNASSOCIATED") ?? null;
2556
+ }
2557
+
2558
+ // ../../packages-private/cams-client/source/lib/http-client.ts
2559
+ /**
2560
+ * Builds a before request hook that sets the user token as a bearer token, the IMS organization
2561
+ * id of the project and, when there is one, the Commerce instance.
2562
+ *
2563
+ * @param auth - The user token and the organization.
2564
+ * @param commerceInstance - The Commerce instance the requests act on, if any.
2565
+ *
2566
+ * @throws A {@link CamsClientError} If the token cannot be read.
2567
+ */
2568
+ function buildAuthHook(auth, commerceInstance) {
2569
+ return async (request) => {
2570
+ let token;
2571
+ try {
2572
+ token = await auth.getToken();
2573
+ } catch (error) {
2574
+ throw new CamsClientError((0, _adobe_aio_commerce_lib_core_error.stringifyError)(error), { cause: error });
2575
+ }
2576
+ request.headers.set("Authorization", `Bearer ${token}`);
2577
+ request.headers.set("x-org-id", auth.orgId);
2578
+ if (commerceInstance) {
2579
+ request.headers.set("x-ac-url", commerceInstance.baseUrl);
2580
+ request.headers.set("x-ac-env", commerceInstance.env);
2581
+ }
2582
+ };
2583
+ }
2584
+ /**
2585
+ * Tells ky not to retry a failure that is not retryable: a token that cannot be read, or an answer
2586
+ * whose `retryable` flag is `false`. ky retries the other answers when their status is one of
2587
+ * {@link RETRYABLE_STATUSES}.
2588
+ *
2589
+ * @param state - The failure of the last attempt.
2590
+ */
2591
+ async function shouldRetry({ error }) {
2592
+ if (error instanceof CamsClientError) return error.retryable;
2593
+ if (!(error instanceof ky.HTTPError)) return;
2594
+ const { body } = await readErrorAnswer(error.response);
2595
+ return body.retryable === false ? false : void 0;
2596
+ }
2597
+ /**
2598
+ * A Ky-based HTTP client used to make requests to CAMS.
2599
+ *
2600
+ * @see https://github.com/sindresorhus/ky
2601
+ */
2602
+ var CamsHttpClient = class {
2603
+ /** ky's `get` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2604
+ get;
2605
+ /** ky's `post` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2606
+ post;
2607
+ /** ky's `delete` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2608
+ delete;
2609
+ /** ky's `patch` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2610
+ patch;
2611
+ /**
2612
+ * @param params - The authentication, configuration and fetch options.
2613
+ */
2614
+ constructor(params) {
2615
+ const { auth, config, fetchOptions } = params;
2616
+ const client = ky.default.create({
2617
+ hooks: { beforeRequest: [buildAuthHook(auth, config?.commerceInstance)] },
2618
+ prefixUrl: config?.baseUrl ?? "https://app-management.api.commerce.adobe.com",
2619
+ retry: {
2620
+ shouldRetry,
2621
+ statusCodes: RETRYABLE_STATUSES
2622
+ },
2623
+ timeout: CAMS_REQUEST_TIMEOUT_MS
2624
+ }).extend(fetchOptions ?? {});
2625
+ this.get = client.get.bind(client);
2626
+ this.post = client.post.bind(client);
2627
+ this.delete = client.delete.bind(client);
2628
+ this.patch = client.patch.bind(client);
2629
+ }
2630
+ };
2631
+
2632
+ // ../../packages-private/cams-client/source/lib/api-client.ts
2633
+ /**
2634
+ * Creates a CAMS API client for the workspace operations, which send no Commerce instance headers.
2635
+ *
2636
+ * @param params - The parameters to build the HTTP client that will communicate with CAMS.
1852
2637
  */
1853
- async function readUpgrade(httpClient, params, fetchOptions) {
1854
- const { extensionId, runId } = require_utils.parseOrThrow(FindAttemptParamsSchema, params);
1855
- return await readAndParseBody(AttemptStatusSchema, httpClient.get(`${upgradesPath(extensionId)}/${encodeURIComponent(runId)}`, fetchOptions));
2638
+ function createCamsWorkspaceApiClient(params) {
2639
+ const httpClient = new CamsHttpClient(params);
2640
+ return { getWorkspaceExtension: getWorkspaceExtension.bind(void 0, httpClient) };
2641
+ }
2642
+ /**
2643
+ * Creates a CAMS API client for the operations on the extensions of a Commerce instance, which send
2644
+ * the Commerce instance headers.
2645
+ *
2646
+ * @param params - The parameters to build the HTTP client that will communicate with CAMS.
2647
+ */
2648
+ function createCamsInstanceApiClient(params) {
2649
+ const httpClient = new CamsHttpClient(params);
2650
+ return {
2651
+ createAssociation: createAssociation.bind(void 0, httpClient),
2652
+ deleteExtension: deleteExtension.bind(void 0, httpClient),
2653
+ followInstallationRun: followInstallationRun.bind(void 0, httpClient),
2654
+ followUninstallationRun: followUninstallationRun.bind(void 0, httpClient),
2655
+ followUpgradeRun: followUpgradeRun.bind(void 0, httpClient),
2656
+ getAllExtensions: getAllExtensions.bind(void 0, httpClient),
2657
+ getExtensionById: getExtensionById.bind(void 0, httpClient),
2658
+ getInstallationRun: getInstallationRun.bind(void 0, httpClient),
2659
+ getLatestUpgradeRun: getLatestUpgradeRun.bind(void 0, httpClient),
2660
+ getUninstallationRun: getUninstallationRun.bind(void 0, httpClient),
2661
+ getUpgradeRun: getUpgradeRun.bind(void 0, httpClient),
2662
+ previewAssociation: previewAssociation.bind(void 0, httpClient),
2663
+ previewInstallation: previewInstallation.bind(void 0, httpClient),
2664
+ previewUninstallation: previewUninstallation.bind(void 0, httpClient),
2665
+ previewUpgrade: previewUpgrade.bind(void 0, httpClient),
2666
+ startInstallation: startInstallation.bind(void 0, httpClient),
2667
+ startUninstallation: startUninstallation.bind(void 0, httpClient),
2668
+ startUpgrade: startUpgrade$1.bind(void 0, httpClient),
2669
+ syncExtensionScopes: syncExtensionScopes.bind(void 0, httpClient),
2670
+ syncInstallationRun: syncInstallationRun.bind(void 0, httpClient),
2671
+ syncUninstallationRun: syncUninstallationRun.bind(void 0, httpClient),
2672
+ syncUpgradeRun: syncUpgradeRun.bind(void 0, httpClient),
2673
+ updateExtension: updateExtension.bind(void 0, httpClient)
2674
+ };
2675
+ }
2676
+
2677
+ // ../../packages-private/scripting-utils/source/process/liveness.ts
2678
+ /** Whether a process with the pid exists. A process we may not signal still exists. */
2679
+ function isProcessAlive(pid) {
2680
+ try {
2681
+ process.kill(pid, 0);
2682
+ return true;
2683
+ } catch (error) {
2684
+ return error.code === "EPERM";
2685
+ }
1856
2686
  }
2687
+ /** The environment variable that holds the pid of the process that started a detached process. */
2688
+ const OWNER_PID_ENV = "__AIO_COMMERCE_SDK_DETACHED_OWNER_PID";
2689
+ /**
2690
+ * The environment variable that holds the file descriptor of the liveness pipe of a detached
2691
+ * process. It is only set when that descriptor is such a pipe.
2692
+ */
2693
+ const LIVENESS_FD_ENV = "__AIO_COMMERCE_SDK_DETACHED_LIVENESS_FD";
2694
+ /** How often the owner pid is checked. */
2695
+ const LIVENESS_CHECK_INTERVAL_MS = 1e3;
2696
+ /** Opens the read end of the liveness pipe, or returns `undefined` when there is none. */
2697
+ function openLivenessPipe() {
2698
+ const fd = Number(process.env[LIVENESS_FD_ENV]);
2699
+ if (!Number.isInteger(fd) || fd <= 0) return;
2700
+ try {
2701
+ const pipe = new net.default.Socket({
2702
+ fd,
2703
+ readable: true,
2704
+ writable: false
2705
+ });
2706
+ pipe.on("error", () => pipe.destroy());
2707
+ pipe.unref();
2708
+ return pipe;
2709
+ } catch {
2710
+ return;
2711
+ }
2712
+ }
2713
+ /**
2714
+ * Resolves when the process that started this one is gone. Does nothing else until then.
2715
+ *
2716
+ * It only works in a process that {@link spawnDetached} started, which tells it the pid of the
2717
+ * owner and the file descriptor of the liveness pipe through the environment variables
2718
+ * {@link OWNER_PID_ENV} and {@link LIVENESS_FD_ENV}. Without the pipe it relies on the pid check
2719
+ * alone.
2720
+ *
2721
+ * @throws A `RangeError` if {@link OWNER_PID_ENV} is not set to a positive integer.
2722
+ *
2723
+ * Two signals:
2724
+ * 1. The pipe closes, which follows the end of the pipe. The kernel closes the owner's end when
2725
+ * the owner dies, so this is immediate and an owner that died but was not reaped yet still
2726
+ * counts as dead.
2727
+ * 2. The owner pid no longer exists, checked on a timer. It covers a missing or failed pipe, and
2728
+ * it is the weaker signal, because an owner that died but was not reaped still answers as alive.
2729
+ */
2730
+ async function waitForOwnerExit() {
2731
+ const ownerPid = Number(process.env[OWNER_PID_ENV]);
2732
+ if (!Number.isInteger(ownerPid) || ownerPid <= 0) throw new RangeError(`${OWNER_PID_ENV} must be a positive integer, got ${process.env[OWNER_PID_ENV]}`);
2733
+ const pipe = openLivenessPipe();
2734
+ return await new Promise((resolve) => {
2735
+ const finish = (signal) => {
2736
+ clearInterval(timer);
2737
+ resolve(signal);
2738
+ };
2739
+ const timer = setInterval(() => {
2740
+ if (!isProcessAlive(ownerPid)) finish("pid");
2741
+ }, LIVENESS_CHECK_INTERVAL_MS);
2742
+ let pipeFailed = false;
2743
+ pipe?.resume();
2744
+ pipe?.once("error", () => {
2745
+ pipeFailed = true;
2746
+ });
2747
+ pipe?.once("close", () => {
2748
+ if (!pipeFailed) finish("pipe");
2749
+ });
2750
+ });
2751
+ }
2752
+
2753
+ // ../../packages-private/scripting-utils/source/process/detached.ts
2754
+ /** The mode of a log file: read and write for its owner only. */
2755
+ const LOG_MODE = 384;
2756
+ /**
2757
+ * The path of a log file in the temp folder, for {@link SpawnDetachedOptions.logPath}.
2758
+ *
2759
+ * @param name - The name of the log. Characters that a file name should not hold become `_`.
2760
+ * @param directory - The folder of the file. Defaults to the temp folder of the system.
2761
+ */
2762
+ function getTempLogPath(name, directory = (0, os.tmpdir)()) {
2763
+ const filename = name.replaceAll(/[^\w-]/gu, (character) => "_".repeat(character.length));
2764
+ return (0, path.join)(directory, `${filename}.log`);
2765
+ }
2766
+ /** The file descriptor of the liveness pipe in the process that is started. */
2767
+ const LIVENESS_PIPE_FD = 3;
2768
+ /** Keeps the parent end of every liveness pipe referenced until its child exits. */
2769
+ const livenessPipes = [];
1857
2770
  /**
1858
- * Reads the latest upgrade attempt without changing anything. Attempts that ran another operation
1859
- * do not count.
2771
+ * Starts a Node.js script as a detached process that outlives this one.
1860
2772
  *
1861
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1862
- * @param params - The extension to read the latest attempt of.
1863
- * @param fetchOptions - The {@link Options} to use to make the request.
2773
+ * The process runs in its own session without a terminal, so Ctrl-C, a closed terminal and a kill
2774
+ * of this process do not reach it. Its standard input is closed, and its output goes to a log
2775
+ * file. A pipe on file descriptor 3 lets the process see this one die. The process tells it
2776
+ * through the environment variables {@link OWNER_PID_ENV}, with the pid of this process, and
2777
+ * {@link LIVENESS_FD_ENV}, with the file descriptor of the pipe, which {@link waitForOwnerExit}
2778
+ * reads.
1864
2779
  *
1865
- * @returns The attempt, or `null` when there is none.
1866
- * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1867
- * @throws An {@link HTTPError} If the status code is not 2XX.
1868
- */
1869
- async function readLatestUpgrade(httpClient, params, fetchOptions) {
1870
- const { extensionId } = require_utils.parseOrThrow(ExtensionParamsSchema, params);
1871
- const response = await httpClient.get(upgradesPath(extensionId), fetchOptions);
1872
- if (response.status === 204) return null;
1873
- return await readAndParseBody(AttemptStatusSchema, response);
1874
- }
1875
-
1876
- // source/commands/common/cams/http-client.ts
1877
- /** Header that carries the organization the request is made for. */
1878
- const ORG_HEADER = "x-org-id";
1879
- /** Headers that carry the Commerce instance the request is made for. */
1880
- const COMMERCE_URL_HEADER = "x-ac-url";
1881
- const COMMERCE_ENV_HEADER = "x-ac-env";
1882
- /**
1883
- * Builds a before request hook that sets the user token as a bearer token, the IMS organization
1884
- * id of the project and, when there is one, the Commerce instance.
2780
+ * Failures after the spawn, such as a missing node binary, arrive only through `onError`. A script
2781
+ * that does not exist shows up only in the log file.
1885
2782
  *
1886
- * @throws A {@link CamsClientError} If the token cannot be read.
2783
+ * @returns The process, or `undefined` when it could not start.
1887
2784
  */
1888
- function buildAuthHook(auth, commerceInstance) {
1889
- return async (request) => {
1890
- let token;
1891
- try {
1892
- token = await auth.getToken();
1893
- } catch (error) {
1894
- throw new CamsClientError((0, _adobe_aio_commerce_lib_core_error.stringifyError)(error), { cause: error });
1895
- }
1896
- request.headers.set("Authorization", `Bearer ${token}`);
1897
- request.headers.set(ORG_HEADER, auth.org.ims_org_id);
1898
- if (commerceInstance) {
1899
- request.headers.set(COMMERCE_URL_HEADER, commerceInstance.baseUrl);
1900
- request.headers.set(COMMERCE_ENV_HEADER, commerceInstance.env);
2785
+ function spawnDetached(options) {
2786
+ const { script, args = [], logPath, env, cwd, onError, spawnProcess = child_process.spawn } = options;
2787
+ let logFd;
2788
+ try {
2789
+ logFd = (0, fs.openSync)(logPath, "a", LOG_MODE);
2790
+ (0, fs.fchmodSync)(logFd, LOG_MODE);
2791
+ const child = spawnProcess(process.execPath, [script, ...args], {
2792
+ cwd,
2793
+ detached: true,
2794
+ env: {
2795
+ ...env ?? process.env,
2796
+ [LIVENESS_FD_ENV]: String(LIVENESS_PIPE_FD),
2797
+ [OWNER_PID_ENV]: String(process.pid)
2798
+ },
2799
+ stdio: [
2800
+ "ignore",
2801
+ logFd,
2802
+ logFd,
2803
+ "pipe"
2804
+ ],
2805
+ windowsHide: true
2806
+ });
2807
+ child.once("error", (error) => onError?.(error));
2808
+ const pipe = child.stdio[3];
2809
+ if (pipe) {
2810
+ pipe.on("error", () => void 0);
2811
+ pipe.unref();
2812
+ livenessPipes.push(pipe);
2813
+ child.once("exit", () => {
2814
+ pipe.destroy();
2815
+ livenessPipes.splice(livenessPipes.indexOf(pipe), 1);
2816
+ });
1901
2817
  }
1902
- };
2818
+ child.unref();
2819
+ return { child };
2820
+ } catch (error) {
2821
+ onError?.(error);
2822
+ } finally {
2823
+ if (logFd !== void 0) (0, fs.closeSync)(logFd);
2824
+ }
1903
2825
  }
1904
- /** Determines if an error is retryable based on the CAMS response. */
1905
- async function isRetryable(error) {
1906
- if (error instanceof CamsClientError) return error.retryable;
1907
- const isObject = (value) => typeof value === "object" && value !== null;
1908
- const isCamsResponseWithRetryable = (value) => isObject(value) && "retryable" in value && typeof value.retryable === "boolean";
1909
- if (error instanceof ky.HTTPError) return error.response.clone().json().then((body) => isCamsResponseWithRetryable(body) ? body.retryable : void 0).catch(() => void 0);
2826
+
2827
+ // ../../packages-private/scripting-utils/source/aio/app-config.ts
2828
+ const APP_CONFIG_FILE = "app.config.yaml";
2829
+ /** Values of the `web` action property that expose the action over HTTP. */
2830
+ const WEB_ACTION_VALUES = /* @__PURE__ */ new Set([
2831
+ true,
2832
+ "yes",
2833
+ "raw"
2834
+ ]);
2835
+ function asNode(value) {
2836
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1910
2837
  }
1911
2838
  /**
1912
- * A Ky-based HTTP client used to make requests to CAMS.
1913
- *
1914
- * It has the shape of the HTTP clients of `@adobe/aio-commerce-lib-api`, which do not export their
1915
- * base class.
1916
- * @see https://github.com/sindresorhus/ky
2839
+ * Lists the actions declared in the `runtimeManifest` of an extension, keyed as `<package>/<action>`.
2840
+ * Loads `app.config.yaml` with the same library the `aio` CLI uses, so `$include` directives and
2841
+ * `function` paths resolve exactly as they do at build time.
2842
+ * @param projectRoot - Resolved project root containing `app.config.yaml`.
2843
+ * @param extensionPointId - The extension point ID, e.g. "commerce/extensibility/1".
1917
2844
  */
1918
- var CamsHttpClient = class {
1919
- /** The actual HTTP client instance. */
1920
- httpClient;
1921
- /** The configuration used by the HTTP client, with its defaults applied. */
1922
- config;
1923
- get;
1924
- post;
1925
- put;
1926
- delete;
1927
- patch;
1928
- head;
1929
- retry;
1930
- stop;
1931
- /**
1932
- * Creates a new CAMS HTTP client instance.
1933
- * @param params - The authentication, configuration and fetch options.
1934
- */
1935
- constructor(params) {
1936
- const { auth, config, fetchOptions } = params;
1937
- this.config = Object.freeze({
1938
- baseUrl: config?.baseUrl ?? "https://app-management.api.commerce.adobe.com",
1939
- commerceInstance: config?.commerceInstance
1940
- });
1941
- const httpClient = ky.default.create({
1942
- hooks: { beforeRequest: [buildAuthHook(auth, this.config.commerceInstance)] },
1943
- prefixUrl: this.config.baseUrl,
1944
- retry: { async shouldRetry({ error }) {
1945
- return isRetryable(error);
1946
- } },
1947
- timeout: CAMS_REQUEST_TIMEOUT_MS
2845
+ async function listExtensionRuntimeActions(projectRoot, extensionPointId) {
2846
+ const appConfigPath = (0, path.join)(projectRoot, APP_CONFIG_FILE);
2847
+ const { config, includeIndex } = await (0, _adobe_aio_cli_lib_app_config.coalesce)(appConfigPath, { absolutePaths: true });
2848
+ const extensionKey = `extensions.${extensionPointId}`;
2849
+ const manifest = asNode(asNode(asNode(config.extensions)[extensionPointId]).runtimeManifest);
2850
+ const actions = /* @__PURE__ */ new Map();
2851
+ for (const [packageName, pkg] of Object.entries(asNode(manifest.packages))) for (const [actionName, rawAction] of Object.entries(asNode(asNode(pkg).actions))) {
2852
+ const action = asNode(rawAction);
2853
+ const actionKey = `${extensionKey}.runtimeManifest.packages.${packageName}.actions.${actionName}`;
2854
+ const fn = typeof action.function === "string" ? action.function : "";
2855
+ actions.set(`${packageName}/${actionName}`, {
2856
+ function: fn || void 0,
2857
+ isWebAction: WEB_ACTION_VALUES.has(action.web),
2858
+ source: includeIndex[actionKey]?.file ?? appConfigPath
1948
2859
  });
1949
- this.httpClient = Object.freeze(fetchOptions ? httpClient.extend(fetchOptions) : httpClient);
1950
- this.get = this.httpClient.get.bind(this.httpClient);
1951
- this.post = this.httpClient.post.bind(this.httpClient);
1952
- this.put = this.httpClient.put.bind(this.httpClient);
1953
- this.delete = this.httpClient.delete.bind(this.httpClient);
1954
- this.patch = this.httpClient.patch.bind(this.httpClient);
1955
- this.head = this.httpClient.head.bind(this.httpClient);
1956
- this.retry = this.httpClient.retry.bind(this.httpClient);
1957
- this.stop = this.httpClient.stop;
1958
2860
  }
1959
- };
1960
-
1961
- // source/commands/common/cams/api-client.ts
1962
- /** Turns a failure of a call into a {@link CamsClientError}. Validation errors pass through. */
1963
- async function toCamsError(error) {
1964
- if (error instanceof CamsClientError || error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) return error;
1965
- if (error instanceof ky.HTTPError) return await toCamsResponseError(error);
1966
- if (error instanceof ky.TimeoutError) return new CamsClientError(`The Commerce App Management Service did not answer within ${CAMS_REQUEST_TIMEOUT_MS / 1e3} seconds`, {
1967
- cause: error,
1968
- retryable: true
1969
- });
1970
- return new CamsClientError("The Commerce App Management Service could not be reached", {
1971
- cause: error,
1972
- retryable: true
1973
- });
1974
- }
1975
- /** Binds an endpoint to the HTTP client and reports its failures as {@link CamsClientError}. */
1976
- function bind(httpClient, endpoint) {
1977
- return async (...args) => {
1978
- try {
1979
- return await endpoint(httpClient, ...args);
1980
- } catch (error) {
1981
- throw await toCamsError(error);
1982
- }
1983
- };
1984
- }
1985
- /** Binds a failsafe version of the poll upgrade endpoint that falls back to a normal read upgrade. */
1986
- function bindFailsafePollUpgrade(httpClient) {
1987
- return async (params, options) => {
1988
- try {
1989
- return await pollUpgrade(httpClient, params, options);
1990
- } catch (error) {
1991
- if (error instanceof ky.HTTPError && error.response?.status === 409) {
1992
- const { code } = await readAnswer(error.response);
1993
- if (code === "attempt-not-open") return await bind(httpClient, readUpgrade)(params, {
1994
- ...options,
1995
- retry: 0
1996
- });
1997
- }
1998
- throw await toCamsError(error);
1999
- }
2000
- };
2861
+ return actions;
2001
2862
  }
2863
+ const ActionSchema = valibot.looseObject({ web: valibot.optional(valibot.unknown()) });
2864
+ /** The part of the config that aio's loader returns that holds the runtime actions. */
2865
+ const LoadedAppConfigSchema = valibot.looseObject({ all: valibot.record(valibot.string(), valibot.looseObject({ manifest: valibot.optional(valibot.looseObject({ full: valibot.optional(valibot.looseObject({ packages: valibot.optional(valibot.record(valibot.string(), valibot.looseObject({ actions: valibot.optional(valibot.record(valibot.string(), ActionSchema)) }))) })) })) })) });
2866
+
2867
+ // ../../packages-private/scripting-utils/source/aio/context.ts
2002
2868
  /**
2003
- * Creates a CAMS client for workspace operations without Commerce instance headers.
2004
- * @param params - The parameters to build the HTTP client that will communicate with CAMS.
2869
+ * Reads the current App Builder project and Runtime namespace from the local AIO CLI config.
2870
+ * @throws If either the project or the runtime namespace is not configured.
2005
2871
  */
2006
- function createCamsWorkspaceClient(params) {
2007
- return { findExtension: bind(new CamsHttpClient(params), findExtension) };
2872
+ function getAioProjectContext() {
2873
+ const project = _adobe_aio_lib_core_config.default.get("project");
2874
+ const namespace = _adobe_aio_lib_core_config.default.get("runtime.namespace");
2875
+ if (!(project && namespace)) throw new Error("The current App Builder project and Runtime namespace are required");
2876
+ return {
2877
+ namespace,
2878
+ project
2879
+ };
2880
+ }
2881
+ /** Reads the configured AIO CLI environment, defaulting to `"prod"`. */
2882
+ function getAioCliEnv() {
2883
+ return _adobe_aio_lib_core_config.default.get("cli.env") === "stage" ? "stage" : "prod";
2008
2884
  }
2885
+
2886
+ // source/deprecated/commands/common/cams/config.ts
2887
+ /** Environment variable that overrides the CAMS base URL. */
2888
+ const CAMS_URL_ENV_VAR = "AIO_COMMERCE_APP_MANAGEMENT_SERVICE_URL";
2889
+ /** Environment variable that selects the AIO CLI environment. */
2890
+ const AIO_CLI_ENV_VAR = "AIO_CLI_ENV";
2891
+ const URL_SCHEME_PATTERN = /^[hH][tT][tT][pP][sS]?:\/\//u;
2009
2892
  /**
2010
- * Creates a CAMS client for operations targeting a Commerce instance.
2011
- * @param params - The authentication, configuration and fetch options.
2012
- * @param commerceInstance - The Commerce instance to target.
2893
+ * Resolves the base URL of the Commerce App Management Service (CAMS).
2894
+ *
2895
+ * The override variable wins. A value without a scheme is read as an https URL.
2896
+ * Otherwise `AIO_CLI_ENV` (`stage` or `prod`) selects the host, falling back to `env`.
2897
+ *
2898
+ * @param env - The configured AIO CLI environment, used when `AIO_CLI_ENV` is unset or unknown.
2899
+ * @param variables - The environment variables to read the override from.
2013
2900
  */
2014
- function createCamsInstanceClient(params, commerceInstance) {
2015
- const httpClient = new CamsHttpClient({
2016
- ...params,
2017
- config: {
2018
- ...params.config,
2019
- commerceInstance
2020
- }
2021
- });
2022
- return {
2023
- planUpgrade: bind(httpClient, planUpgrade$1),
2024
- pollUpgrade: bindFailsafePollUpgrade(httpClient),
2025
- readLatestUpgrade: bind(httpClient, readLatestUpgrade),
2026
- readUpgrade: bind(httpClient, readUpgrade),
2027
- startUpgrade: bind(httpClient, startUpgrade$1)
2028
- };
2901
+ function resolveCamsBaseUrl(env, variables = process.env) {
2902
+ const override = variables[CAMS_URL_ENV_VAR]?.trim();
2903
+ if (override) return URL_SCHEME_PATTERN.test(override) ? override : `https://${override}`;
2904
+ const cliEnv = variables[AIO_CLI_ENV_VAR]?.trim();
2905
+ return (cliEnv === "stage" || cliEnv === "prod" ? cliEnv : env) === "stage" ? STAGE_CAMS_URL : PROD_CAMS_URL;
2029
2906
  }
2030
2907
 
2031
- // source/commands/common/cams/context.ts
2908
+ // source/deprecated/commands/common/cams/context.ts
2909
+ /** Gets an IMS access token for the current CLI IMS context. */
2910
+ async function getUserToken() {
2911
+ const contextName = await _adobe_aio_lib_ims.default.context.getCurrent() ?? "cli";
2912
+ return _adobe_aio_lib_ims.default.getToken(contextName, {});
2913
+ }
2032
2914
  /**
2033
2915
  * Reads the current App Builder project and supplies lazy CAMS client factories.
2034
2916
  * @param getToken - Reads the user token before every request. Defaults to the AIO CLI token.
@@ -2039,20 +2921,26 @@ function createCamsContext(getToken = getUserToken) {
2039
2921
  const params = {
2040
2922
  auth: {
2041
2923
  getToken,
2042
- org: project.org
2924
+ orgId: project.org.ims_org_id
2043
2925
  },
2044
2926
  config: { baseUrl }
2045
2927
  };
2046
2928
  return {
2047
2929
  baseUrl,
2048
- createInstanceClient: (commerceInstance) => createCamsInstanceClient(params, commerceInstance),
2049
- createWorkspaceClient: () => createCamsWorkspaceClient(params),
2930
+ createInstanceClient: (commerceInstance) => createCamsInstanceApiClient({
2931
+ ...params,
2932
+ config: {
2933
+ ...params.config,
2934
+ commerceInstance
2935
+ }
2936
+ }),
2937
+ createWorkspaceClient: () => createCamsWorkspaceApiClient(params),
2050
2938
  project
2051
2939
  };
2052
2940
  }
2053
2941
  /** Finds the extension associated with the current workspace without changing the context. */
2054
2942
  async function findWorkspaceExtension(context, fetchOptions) {
2055
- return await context.createWorkspaceClient().findExtension({ workspaceId: context.project.workspace.id }, fetchOptions);
2943
+ return await context.createWorkspaceClient().getWorkspaceExtension({ workspaceId: context.project.workspace.id }, fetchOptions);
2056
2944
  }
2057
2945
  /**
2058
2946
  * Reads the Commerce instance from an extension's explicit scope fields.
@@ -2068,7 +2956,7 @@ function requireCommerceInstance(extension) {
2068
2956
  };
2069
2957
  }
2070
2958
 
2071
- // source/commands/common/cams/report.ts
2959
+ // source/deprecated/commands/common/cams/report.ts
2072
2960
  /** How many causes {@link findCamsError} follows. */
2073
2961
  const MAX_CAUSE_DEPTH = 5;
2074
2962
  /** Finds the failure of the service that caused an error: the error itself or one of its causes. */
@@ -2093,6 +2981,13 @@ function describeCamsFailure(error) {
2093
2981
  ].filter(Boolean);
2094
2982
  return facts.length > 0 ? `Details: ${facts.join(", ")}` : void 0;
2095
2983
  }
2984
+ const PROJECT_ACCESS_HINT = "Hint: the credential cannot access the project. Add the I/O Management API to the workspace credential.";
2985
+ const COMMERCE_ACCESS_HINT = "Hint: the credential cannot access the Commerce instance. On SaaS, add the Adobe Commerce as a Cloud Service API to the credential and assign it a profile for the instance. On PaaS, create its technical account as an admin user in the instance.";
2986
+ /** The hint for the access failures that a credential without the right access causes. */
2987
+ function hintFor(error) {
2988
+ if (error.code === "project-access-denied") return PROJECT_ACCESS_HINT;
2989
+ if (error.code === "commerce-access-denied") return COMMERCE_ACCESS_HINT;
2990
+ }
2096
2991
  /**
2097
2992
  * Prints a failure. A failure of the service is one block, the message and one line of details
2098
2993
  * without a stack, and the whole chain of causes goes to the debug log, which `DEBUG=1` shows.
@@ -2112,11 +3007,16 @@ function reportFailure(error, message) {
2112
3007
  }
2113
3008
  const details = describeCamsFailure(cams);
2114
3009
  const headline = message ?? (error instanceof Error ? error.message : String(error));
2115
- consola.consola.error(details ? `${headline}\n${details}` : headline);
3010
+ const hint = hintFor(cams);
3011
+ consola.consola.error([
3012
+ headline,
3013
+ details,
3014
+ hint
3015
+ ].filter(Boolean).join("\n"));
2116
3016
  consola.consola.debug(error);
2117
3017
  }
2118
3018
 
2119
- // source/commands/hooks/post-app-deploy/interrupt.ts
3019
+ // source/deprecated/commands/hooks/post-app-deploy/interrupt.ts
2120
3020
  /** The exit code of a process that stopped because of Ctrl+C. */
2121
3021
  const SIGINT_EXIT_CODE = 130;
2122
3022
  /**
@@ -2159,60 +3059,47 @@ function noticeInterrupt(statusCommand) {
2159
3059
  };
2160
3060
  }
2161
3061
 
2162
- // source/commands/upgrade/poll.ts
2163
- /** How long to wait between two polls. */
2164
- const POLL_INTERVAL_MS = 2e3;
3062
+ // source/deprecated/commands/upgrade/poll.ts
2165
3063
  /**
2166
- * How many transient failures in a row end the loop.
3064
+ * Syncs an upgrade run until it is settled. Retryable failures are retried up to
3065
+ * {@link DEFAULT_MAX_CONSECUTIVE_FAILURES} times in a row; any other failure ends the loop.
2167
3066
  *
2168
- * The service marks an overdue attempt as failed, so a healthy service always ends the loop. This
2169
- * limit is for the other case: without it, a service that stays down means polling forever.
2170
- */
2171
- const MAX_CONSECUTIVE_FAILURES = 10;
2172
- /** Whether the attempt will not change anymore. */
2173
- function isSettled(status) {
2174
- return status.status === "succeeded" || status.status === "failed";
2175
- }
2176
- /**
2177
- * Polls an attempt every {@link POLL_INTERVAL_MS} until it is settled.
3067
+ * @param client - The CAMS client of the Commerce instance.
3068
+ * @param run - The extension and the run to follow.
3069
+ * @param handlers - What to call with each answer and each retry.
2178
3070
  *
2179
- * The loop keeps going through the failures that can pass, which are network failures and a 502 or
2180
- * 503 from the service, and gives up after {@link MAX_CONSECUTIVE_FAILURES} of them in a row. Any
2181
- * answer resets the count. Any other failure ends the loop at once, because repeating the request
2182
- * cannot fix it, as with a refused token.
3071
+ * @returns How following ended: `finished` with the final status, `unreachable` after too many
3072
+ * retryable failures in a row, or `failed` with any other failure.
2183
3073
  */
2184
- async function pollUntilSettled(options) {
2185
- const { poll, onStatus, onRetry, sleep: wait = timers_promises.setTimeout } = options;
2186
- let failures = 0;
2187
- while (true) {
2188
- try {
2189
- const status = await poll();
2190
- failures = 0;
3074
+ async function followUntilSettled(client, run, handlers = {}) {
3075
+ const { onStatus, onRetry } = handlers;
3076
+ try {
3077
+ for await (const status of client.followUpgradeRun(run, { onRetry })) {
2191
3078
  onStatus?.(status);
2192
- if (isSettled(status)) return {
3079
+ if (isRunFinished(status)) return {
2193
3080
  kind: "finished",
2194
3081
  status
2195
3082
  };
2196
- } catch (error) {
2197
- if (!(error instanceof CamsClientError && error.retryable)) return {
2198
- error,
2199
- kind: "failed"
2200
- };
2201
- failures += 1;
2202
- if (failures >= 10) return {
2203
- error,
2204
- kind: "unreachable"
2205
- };
2206
- onRetry?.(error);
2207
3083
  }
2208
- await wait(POLL_INTERVAL_MS);
3084
+ } catch (error) {
3085
+ return error instanceof CamsClientError && error.retryable ? {
3086
+ error,
3087
+ kind: "unreachable"
3088
+ } : {
3089
+ error,
3090
+ kind: "failed"
3091
+ };
2209
3092
  }
3093
+ throw new Error(`The upgrade run ${run.runId} ended without a final status.`);
2210
3094
  }
2211
- /** Wraps a callback so that it runs once per change of an unsettled status, such as `pending` to `in-progress`. */
3095
+ /**
3096
+ * Wraps a callback so that it runs once per change of an unsettled status, such as `pending` to
3097
+ * `in-progress`.
3098
+ */
2212
3099
  function whenStatusChanges(report) {
2213
3100
  let previous;
2214
3101
  return (status) => {
2215
- if (!isSettled(status) && status.status !== previous) {
3102
+ if (!isRunFinished(status) && status.status !== previous) {
2216
3103
  previous = status.status;
2217
3104
  report(status);
2218
3105
  }
@@ -2251,42 +3138,50 @@ function describeOutcome(result, runId) {
2251
3138
  };
2252
3139
  }
2253
3140
 
2254
- // source/commands/hooks/post-app-deploy/main.ts
3141
+ // source/deprecated/commands/hooks/post-app-deploy/main.ts
2255
3142
  const SKIP_MESSAGES = {
2256
3143
  "already-current": "The app is already up to date.",
2257
3144
  "in-progress": "An upgrade is already in progress.",
2258
3145
  "not-associated": "The app is not associated with a Commerce instance. Nothing to upgrade.",
2259
- "not-installed": "The app is not installed on the Commerce instance. Nothing to upgrade."
3146
+ "not-installed": "The app is not installed on the Commerce instance. Nothing to upgrade.",
3147
+ "upgrade-conflict": "Another upgrade of this app is in progress or an automatic upgrade is pending. Try again in a few minutes."
2260
3148
  };
2261
- function isSkipCode(code) {
2262
- return code === "already-current" || code === "not-associated" || code === "not-installed" || code === "in-progress";
2263
- }
2264
3149
  /**
2265
3150
  * Asks the service to plan the upgrade.
2266
3151
  * @returns The plan, or the code of the reason the upgrade does not apply.
2267
3152
  */
2268
3153
  async function planUpgrade(client, extensionId) {
3154
+ let preview;
2269
3155
  try {
2270
- return await client.planUpgrade({ extensionId });
3156
+ preview = await client.previewUpgrade({ extensionId });
2271
3157
  } catch (error) {
2272
- if (error instanceof CamsConflictError) {
2273
- if (isSkipCode(error.code)) return error.code;
2274
- throw new Error(`The upgrade was not planned: ${error.message}`, { cause: error });
2275
- }
3158
+ if (error instanceof CamsClientError && error.status === _adobe_aio_commerce_lib_core_responses.HTTP_CONFLICT) throw new Error(`The upgrade was not planned: ${error.message}`, { cause: error });
2276
3159
  throw error;
2277
3160
  }
3161
+ switch (preview.kind) {
3162
+ case "planned": return preview.preview.plan;
3163
+ case "already-current":
3164
+ case "in-progress":
3165
+ case "not-associated":
3166
+ case "not-installed":
3167
+ case "upgrade-conflict": return preview.kind;
3168
+ default: throw new Error(`The upgrade was not planned: ${preview.message}`);
3169
+ }
2278
3170
  }
2279
- /** Starts the planned upgrade and returns the status of the new run. */
3171
+ /** Starts the planned upgrade and returns the new run. */
2280
3172
  async function startUpgrade(client, extensionId, plan) {
3173
+ let started;
2281
3174
  try {
2282
- return await client.startUpgrade({
3175
+ started = await client.startUpgrade({
2283
3176
  extensionId,
2284
3177
  planId: plan.id
2285
3178
  });
2286
3179
  } catch (error) {
2287
- if (error instanceof CamsConflictError) throw new Error(`The upgrade was not started: ${error.message}`, { cause: error });
3180
+ if (error instanceof CamsClientError && error.status === _adobe_aio_commerce_lib_core_responses.HTTP_CONFLICT) throw new Error(`The upgrade was not started: ${error.message}`, { cause: error });
2288
3181
  throw error;
2289
3182
  }
3183
+ if (started.kind !== "started") throw new Error(`The upgrade was not started: ${started.message}`);
3184
+ return started.run;
2290
3185
  }
2291
3186
  /**
2292
3187
  * Starts the watcher that follows the run if this process stops. The run goes on without the
@@ -2323,16 +3218,15 @@ function startBackgroundWatcher(extensionId, started) {
2323
3218
  }
2324
3219
  /** Polls the run and prints its progress until it settles. Throws when it does not succeed. */
2325
3220
  async function followRun(client, extensionId, started) {
2326
- const result = await pollUntilSettled({
3221
+ const result = await followUntilSettled(client, {
3222
+ extensionId,
3223
+ runId: started.id
3224
+ }, {
2327
3225
  onRetry: (error) => {
2328
3226
  consola.consola.warn(`${error.message}. Trying again.`);
2329
3227
  },
2330
3228
  onStatus: whenStatusChanges((status) => {
2331
3229
  consola.consola.start(`App upgrade is ${consola_utils.colors.yellow(status.status)}.`);
2332
- }),
2333
- poll: () => client.pollUpgrade({
2334
- extensionId,
2335
- runId: started.id
2336
3230
  })
2337
3231
  });
2338
3232
  const outcome = describeOutcome(result, started.id);
@@ -2344,12 +3238,12 @@ async function followRun(client, extensionId, started) {
2344
3238
  * when the package manager cannot be detected.
2345
3239
  */
2346
3240
  async function getStatusCommand() {
2347
- const packageManager = await require_index_node.detectPackageManager(process.cwd()).catch(() => "npm");
2348
- return `${require_index_node.getExecCommand(packageManager)} aio-commerce-lib-app upgrade status`;
3241
+ const packageManager = await require_parser.detectPackageManager(process.cwd()).catch(() => "npm");
3242
+ return `${require_parser.getExecCommand(packageManager)} aio-commerce-lib-app upgrade status`;
2349
3243
  }
2350
3244
  /** Plans, starts and follows the upgrade. Tells `interrupt` the run id once the run exists. */
2351
3245
  async function runHook(interrupt) {
2352
- const { upgradeMode } = (await require_index_node.parseCommerceAppConfig()).metadata;
3246
+ const { upgradeMode } = (await require_parser.parseCommerceAppConfig()).metadata;
2353
3247
  console.log("");
2354
3248
  consola.consola.start("Checking the status of the app...");
2355
3249
  const context = createCamsContext();
@@ -2429,7 +3323,7 @@ async function exec$7() {
2429
3323
  }
2430
3324
  }
2431
3325
 
2432
- // source/commands/common/extension-points.ts
3326
+ // source/deprecated/commands/common/extension-points.ts
2433
3327
  /** Extension points in the order they must appear in app.config.yaml. Extensibility must be last. */
2434
3328
  const EXTENSION_POINT_ORDER = [
2435
3329
  BACKEND_UI_V2_EXTENSION_POINT_ID,
@@ -2464,7 +3358,7 @@ function isSorted(extensions) {
2464
3358
  * @returns True if the file was rewritten.
2465
3359
  */
2466
3360
  async function ensureExtensionPointsOrder(projectRoot) {
2467
- const path$4 = (0, path.join)(projectRoot, APP_CONFIG_FILE);
3361
+ const path$4 = (0, path.join)(projectRoot, APP_CONFIG_FILE$1);
2468
3362
  if (!(0, fs.existsSync)(path$4)) return false;
2469
3363
  const doc = await readYamlFile(path$4);
2470
3364
  const extensions = getExtensionsMap(doc.contents);
@@ -2483,9 +3377,57 @@ async function ensureExtensionPointsOrder(projectRoot) {
2483
3377
  return true;
2484
3378
  }
2485
3379
 
2486
- // source/commands/hooks/postinstall.ts
3380
+ // source/deprecated/commands/hooks/postinstall.ts
3381
+ /** What the hook commands that `aio commerce app sync` writes contain. */
3382
+ const PLUGIN_HOOK_COMMAND = "aio commerce app hooks";
3383
+ const POSTINSTALL_COMMAND = "aio-commerce-lib-app hooks postinstall";
3384
+ const COMMAND_SEPARATOR_PATTERN = /\s*&&\s*/u;
3385
+ const SHELL_OPERATOR_PATTERN = /[;|&]/u;
3386
+ /** The hooks of an `ext.config.yaml`. An empty file, key or hook has none. */
3387
+ const ExtConfigHooksSchema = valibot.nullish(valibot.object({ hooks: valibot.nullish(valibot.record(valibot.string(), valibot.nullish(valibot.string()))) }));
3388
+ /**
3389
+ * Whether the `aio commerce app` plugin manages the project, which it shows by writing its own hook
3390
+ * commands into an `ext.config.yaml`.
3391
+ *
3392
+ * @param projectRoot - Resolved project root.
3393
+ */
3394
+ async function isManagedByPlugin(projectRoot) {
3395
+ return (await Promise.all([
3396
+ BACKEND_UI_V2_EXTENSION_POINT_ID,
3397
+ CONFIGURATION_EXTENSION_POINT_ID,
3398
+ EXTENSIBILITY_EXTENSION_POINT_ID
3399
+ ].map(async (id) => {
3400
+ const path$2 = (0, path.join)(projectRoot, getExtConfigPath(id));
3401
+ const contents = await readOptionalFile(path$2);
3402
+ return contents === void 0 ? void 0 : require_utils.parseOrThrow(ExtConfigHooksSchema, (0, yaml.parse)(contents), `Invalid hooks in ${path$2}`);
3403
+ }))).some((extConfig) => Object.values(extConfig?.hooks ?? {}).some((command) => command?.includes(PLUGIN_HOOK_COMMAND)));
3404
+ }
3405
+ /**
3406
+ * Removes this hook's command from the `postinstall` script, and the script when nothing else is
3407
+ * left in it.
3408
+ *
3409
+ * @param projectRoot - Resolved project root containing package.json.
3410
+ *
3411
+ * @returns `false` when the command shares a segment of the `&&` chain with other shell commands,
3412
+ * which stay untouched, and `true` otherwise, also when there is no package.json.
3413
+ */
3414
+ async function removePostinstallScript(projectRoot) {
3415
+ const pkg = await require_parser.loadPackageJson(projectRoot);
3416
+ if (pkg === null) return true;
3417
+ const commands = (pkg.content.scripts?.postinstall ?? "").split(COMMAND_SEPARATOR_PATTERN);
3418
+ if (commands.some((command) => command.includes(POSTINSTALL_COMMAND) && SHELL_OPERATOR_PATTERN.test(command))) return false;
3419
+ const remaining = commands.filter((command) => !command.includes(POSTINSTALL_COMMAND)).join(require_parser.COMMAND_SEPARATOR);
3420
+ const scripts = Object.fromEntries(Object.entries({
3421
+ ...pkg.content.scripts,
3422
+ postinstall: remaining
3423
+ }).filter(([name]) => name !== "postinstall" || remaining !== ""));
3424
+ pkg.update({ scripts });
3425
+ await pkg.save();
3426
+ return true;
3427
+ }
2487
3428
  /**
2488
3429
  * Regenerates project artifacts after dependencies are installed.
3430
+ *
2489
3431
  * @param appManifest - Validated app configuration used for generation.
2490
3432
  * @param projectRoot - Resolved project root where artifacts are generated.
2491
3433
  * @param templatesDir - Optional directory containing generation templates.
@@ -2496,11 +3438,19 @@ async function run$5(appManifest, projectRoot, templatesDir) {
2496
3438
  await run$7(appManifest, projectRoot);
2497
3439
  await ensureExtensionPointsOrder(projectRoot);
2498
3440
  }
2499
- /** Runs the postinstall hook */
3441
+ /**
3442
+ * Regenerates the project artifacts, or, once the `aio commerce app` plugin manages the project,
3443
+ * removes the hook from `package.json`.
3444
+ */
2500
3445
  async function exec$6() {
2501
3446
  consola.default.debug("Running lib-app postinstall hook");
2502
3447
  try {
2503
- const projectRoot = await require_index_node.getProjectRootDirectory();
3448
+ const projectRoot = await require_parser.getProjectRootDirectory();
3449
+ if (await isManagedByPlugin(projectRoot)) {
3450
+ if (await removePostinstallScript(projectRoot)) consola.default.info("The aio commerce app plugin manages this project, so the postinstall hook removed itself from package.json.");
3451
+ else consola.default.warn(`The aio commerce app plugin manages this project. Remove "${POSTINSTALL_COMMAND}" from the postinstall script in package.json.`);
3452
+ return;
3453
+ }
2504
3454
  await run$5(await loadAppManifest(projectRoot), projectRoot);
2505
3455
  } catch (error) {
2506
3456
  if (error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) consola.default.error(error.display());
@@ -2514,37 +3464,63 @@ async function exec$6() {
2514
3464
  * This module exports shared environment utilities for the AIO Commerce SDK.
2515
3465
  * @packageDocumentation
2516
3466
  */
2517
- const { context } = _adobe_aio_lib_ims.default;
2518
- const IMS_KEYS = {
2519
- client_id: "AIO_COMMERCE_AUTH_IMS_CLIENT_ID",
2520
- client_secrets: "AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS",
2521
- ims_org_id: "AIO_COMMERCE_AUTH_IMS_ORG_ID",
2522
- scopes: "AIO_COMMERCE_AUTH_IMS_SCOPES",
2523
- technical_account_email: "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL",
2524
- technical_account_id: "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID"
2525
- };
3467
+ const UNQUOTED_VALUE = /^[^\s#"'`]*$/u;
3468
+ /** The credentials of the workspace in aio's config, as `aio app use` wrote them. */
3469
+ const WorkspaceCredentialsSchema = valibot.nullish(valibot.array(valibot.object({
3470
+ integration_type: valibot.nullish(valibot.string()),
3471
+ name: valibot.nullish(valibot.string())
3472
+ })), []);
3473
+ /** A field of an IMS context: a text, or a list that the `.env` file holds comma-separated. */
3474
+ const ImsContextFieldSchema = valibot.optional(valibot.pipe(valibot.union([valibot.string(), valibot.array(valibot.string())]), valibot.transform((value) => Array.isArray(value) ? value.join(",") : value)));
3475
+ /** The fields of an OAuth Server-to-Server IMS context that the legacy variables hold. */
3476
+ const ImsContextSchema = valibot.nullish(valibot.object({ data: valibot.nullish(valibot.object({
3477
+ client_id: ImsContextFieldSchema,
3478
+ client_secrets: ImsContextFieldSchema,
3479
+ ims_org_id: ImsContextFieldSchema,
3480
+ scopes: ImsContextFieldSchema,
3481
+ technical_account_email: ImsContextFieldSchema,
3482
+ technical_account_id: ImsContextFieldSchema
3483
+ })) }));
3484
+ /**
3485
+ * Reads the variables of a `.env` file.
3486
+ *
3487
+ * @param envPath - The path of the `.env` file.
3488
+ *
3489
+ * @returns The variables, or `undefined` when there is no file.
3490
+ */
3491
+ async function readEnvFile(envPath) {
3492
+ const contents = await readOptionalFile(envPath);
3493
+ return contents === void 0 ? void 0 : (0, util.parseEnv)(contents);
3494
+ }
2526
3495
  /**
2527
- * Replaces or creates an environment variable in a .env file
2528
- * @param filePath - The path to the .env file
2529
- * @param key - The environment variable key to replace or create
2530
- * @param value - The new value for the environment variable
2531
- */
2532
- function replaceEnvVar(filePath, key, value) {
2533
- const envPath = path.default.resolve(filePath);
2534
- const envLines = (0, fs.readFileSync)(envPath, "utf8").split("\n");
2535
- const formattedValue = value.includes(" ") ? `"${value}"` : value;
2536
- let keyExists = false;
2537
- const updatedLines = envLines.map((line) => {
2538
- if (line.trim().startsWith("#") || !line.includes("=")) return line;
2539
- const [currentKey] = line.split("=");
2540
- if (currentKey === key) {
2541
- keyExists = true;
2542
- return `${key}=${formattedValue}`;
3496
+ * Quotes a value so a `.env` file reads it back as written: as is when it needs no quotes, else in
3497
+ * single quotes, else in double quotes when it holds a single quote.
3498
+ */
3499
+ function envValue(value) {
3500
+ if (UNQUOTED_VALUE.test(value)) return value;
3501
+ return value.includes("'") ? JSON.stringify(value) : `'${value}'`;
3502
+ }
3503
+ /**
3504
+ * Writes variables to a `.env` file, each in place of every line that sets it or at the end, and
3505
+ * creates the file when it doesn't exist. The file is read and written once.
3506
+ *
3507
+ * @param envPath - The path of the `.env` file.
3508
+ * @param values - The value of each variable, by name.
3509
+ */
3510
+ async function writeEnvValues(envPath, values) {
3511
+ const entries = Object.entries(values);
3512
+ if (entries.length === 0) return;
3513
+ let contents = await readOptionalFile(envPath) ?? "";
3514
+ for (const [name, value] of entries) {
3515
+ const line = `${name}=${envValue(value)}`;
3516
+ const lines = contents.split("\n");
3517
+ if (lines.some((existing) => existing.startsWith(`${name}=`))) contents = lines.map((existing) => existing.startsWith(`${name}=`) ? `${line}${existing.endsWith("\r") ? "\r" : ""}` : existing).join("\n");
3518
+ else {
3519
+ const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
3520
+ contents = `${contents}${separator}${line}\n`;
2543
3521
  }
2544
- return line;
2545
- });
2546
- if (!keyExists) updatedLines.push(`${key}=${formattedValue}`);
2547
- (0, fs.writeFileSync)(envPath, updatedLines.join("\n"), "utf8");
3522
+ }
3523
+ await (0, fs_promises.writeFile)(envPath, contents);
2548
3524
  }
2549
3525
  /**
2550
3526
  * Sets the `NODE_ENV` environment variable in the app `.env` file, so the web
@@ -2552,44 +3528,120 @@ function replaceEnvVar(filePath, key, value) {
2552
3528
  * @param mode - The environment mode to write into `NODE_ENV`.
2553
3529
  * @param projectRoot - Resolved project root containing the `.env` file.
2554
3530
  */
2555
- function setNodeEnv(mode, projectRoot) {
2556
- const envPath = path.default.join(projectRoot, ".env");
2557
- if (!(0, fs.existsSync)(envPath)) (0, fs.writeFileSync)(envPath, "", "utf8");
2558
- replaceEnvVar(envPath, "NODE_ENV", mode);
2559
- }
2560
- /** Resolves the IMS server to server context from the project workspace credentials. */
2561
- function resolveImsS2SContext() {
2562
- const [credential] = (_adobe_aio_lib_core_config.default.get("project.workspace.details.credentials") ?? []).filter(({ integration_type }) => integration_type === "oauth_server_to_server").map(({ name }) => name);
2563
- if (!credential) return Promise.resolve(null);
2564
- return context.get(credential);
3531
+ async function setNodeEnv(mode, projectRoot) {
3532
+ await writeEnvValues((0, path.join)(projectRoot, ".env"), { NODE_ENV: mode });
2565
3533
  }
2566
3534
  /**
2567
- * Syncs the IMS credentials environment variables from the configured IMS context in
2568
- * the .env file, in a way that is compatible with `@adobe/aio-commerce-lib-auth`.
3535
+ * Copies the workspace's OAuth Server-to-Server credential from its IMS context to the legacy
3536
+ * `AIO_COMMERCE_AUTH_IMS_*` variables of the project's `.env` file, which
3537
+ * `@adobe/aio-commerce-lib-auth` reads.
3538
+ *
2569
3539
  * @param projectRoot - Resolved project root containing the `.env` file.
3540
+ *
3541
+ * @throws A {@link CommerceSdkValidationError} If the workspace credentials or the IMS context in
3542
+ * aio's config are invalid.
2570
3543
  */
2571
3544
  async function syncImsCredentials(projectRoot) {
2572
- const envPath = path.default.join(projectRoot, ".env");
2573
- if (!(0, fs.existsSync)(envPath)) return {
3545
+ const envPath = (0, path.join)(projectRoot, ".env");
3546
+ const variables = await readEnvFile(envPath);
3547
+ if (variables === void 0) return {
2574
3548
  ok: false,
2575
3549
  reason: "missing-env"
2576
3550
  };
2577
- const envVars = dotenv.default.parse((0, fs.readFileSync)(envPath, "utf8"));
2578
- const imsContext = await resolveImsS2SContext();
2579
- if (!imsContext) return {
3551
+ const name = require_utils.parseOrThrow(WorkspaceCredentialsSchema, _adobe_aio_lib_core_config.default.get("project.workspace.details.credentials"), "The workspace credentials in aio's config are invalid.").find((credential) => credential.integration_type === "oauth_server_to_server")?.name;
3552
+ if (!name) return {
2580
3553
  ok: false,
2581
3554
  reason: "no-ims-context"
2582
3555
  };
2583
- const { data } = imsContext;
2584
- for (const [key, value] of Object.entries(data)) {
2585
- const oauthKey = IMS_KEYS[key];
2586
- if (!oauthKey) continue;
2587
- if (!envVars[oauthKey] || envVars[oauthKey] !== value) replaceEnvVar(envPath, oauthKey, value);
2588
- }
3556
+ const context = require_utils.parseOrThrow(ImsContextSchema, await _adobe_aio_lib_ims.default.context.get(name), `The ${name} IMS context in aio's config is invalid.`);
3557
+ if (!context) return {
3558
+ ok: false,
3559
+ reason: "no-ims-context"
3560
+ };
3561
+ const { data } = context;
3562
+ const values = {
3563
+ AIO_COMMERCE_AUTH_IMS_CLIENT_ID: data?.client_id,
3564
+ AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS: data?.client_secrets,
3565
+ AIO_COMMERCE_AUTH_IMS_ORG_ID: data?.ims_org_id,
3566
+ AIO_COMMERCE_AUTH_IMS_SCOPES: data?.scopes,
3567
+ AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL: data?.technical_account_email,
3568
+ AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID: data?.technical_account_id
3569
+ };
3570
+ const changed = {};
3571
+ for (const [variable, value] of Object.entries(values)) if (value !== void 0 && variables[variable] !== value) changed[variable] = value;
3572
+ await writeEnvValues(envPath, changed);
2589
3573
  return { ok: true };
2590
3574
  }
2591
3575
 
2592
- // source/commands/hooks/pre-app-build.ts
3576
+ // source/deprecated/commands/common/runtime-actions.ts
3577
+ /** Sections whose referenced actions must be web actions. */
3578
+ const WEB_ACTION_SECTIONS = /* @__PURE__ */ new Set(["webhooks"]);
3579
+ function isNode(value) {
3580
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3581
+ }
3582
+ /**
3583
+ * Finds every `runtimeAction` and `runtimeActions` value nested in a config value.
3584
+ * @param value - The config value to search.
3585
+ * @param path - Dotted config path of `value`.
3586
+ */
3587
+ function* findReferences(value, path) {
3588
+ if (Array.isArray(value)) {
3589
+ for (const [index, item] of value.entries()) yield* findReferences(item, `${path}.${index}`);
3590
+ return;
3591
+ }
3592
+ if (!isNode(value)) return;
3593
+ for (const [key, child] of Object.entries(value)) {
3594
+ const childPath = `${path}.${key}`;
3595
+ if (key === "runtimeAction" && typeof child === "string") yield {
3596
+ name: child,
3597
+ path: childPath
3598
+ };
3599
+ else if (key === "runtimeActions" && Array.isArray(child)) {
3600
+ for (const [index, name] of child.entries()) if (typeof name === "string") yield {
3601
+ name,
3602
+ path: `${childPath}.${index}`
3603
+ };
3604
+ } else yield* findReferences(child, childPath);
3605
+ }
3606
+ }
3607
+ /**
3608
+ * Returns why a reference does not resolve to a usable declared action, or `undefined` if it does.
3609
+ * @param name - The referenced `<package>/<action>`.
3610
+ * @param declared - Actions the reference may resolve to.
3611
+ * @param location - Project-relative path of the ext.config.yaml they are declared in.
3612
+ * @param requireWebAction - Whether the referenced action must be a web action.
3613
+ * @param projectRoot - Resolved project root, used to report paths relative to it.
3614
+ */
3615
+ function checkReference(name, declared, location, requireWebAction, projectRoot) {
3616
+ const action = declared.get(name);
3617
+ if (!action) return `Runtime action "${name}" is not declared under "runtimeManifest.packages" in ${location}`;
3618
+ const source = (0, path.relative)(projectRoot, action.source);
3619
+ if (!(action.function && (0, fs.existsSync)(action.function))) return action.function ? `Runtime action "${name}" points to "${(0, path.relative)(projectRoot, action.function)}" in ${source}, which does not exist` : `Runtime action "${name}" has no "function" in ${source}`;
3620
+ if (requireWebAction && !action.isWebAction) return `Runtime action "${name}" must be a web action (set "web: yes" in ${source})`;
3621
+ }
3622
+ /**
3623
+ * Validates that every `runtimeAction`/`runtimeActions` value in the given config sections is
3624
+ * declared in the extension's runtime manifest and that its `function` exists on disk. Webhook actions must
3625
+ * also be web actions.
3626
+ * @param sections - The config sections whose references are validated.
3627
+ * @param manifest - The extension whose runtime manifest the references must resolve against.
3628
+ * @throws {Error} If any reference does not resolve to a declared action.
3629
+ */
3630
+ async function validateRuntimeActionReferences(sections, manifest) {
3631
+ const references = Object.entries(sections).flatMap(([section, value]) => [...findReferences(value, section)].map((reference) => ({
3632
+ ...reference,
3633
+ section
3634
+ })));
3635
+ if (references.length === 0) return;
3636
+ const declared = await listExtensionRuntimeActions(manifest.projectRoot, manifest.extensionPointId);
3637
+ const errors = references.flatMap(({ name, path, section }) => {
3638
+ const message = checkReference(name, declared, manifest.path, WEB_ACTION_SECTIONS.has(section), manifest.projectRoot);
3639
+ return message ? [`${path}: ${message}`] : [];
3640
+ });
3641
+ if (errors.length > 0) throw new Error(`Invalid runtime action references in ${manifest.path}:\n- ${errors.join("\n- ")}`);
3642
+ }
3643
+
3644
+ // source/deprecated/commands/hooks/pre-app-build.ts
2593
3645
  /**
2594
3646
  * Runs the pre-app-build hook for the given extension.
2595
3647
  * @param extension - The extension to run the hook for.
@@ -2597,13 +3649,22 @@ async function syncImsCredentials(projectRoot) {
2597
3649
  * @param templatesDir - Directory containing action templates.
2598
3650
  */
2599
3651
  async function run$4(extension, projectRoot, templatesDir = TEMPLATES_DIR) {
2600
- if (await ensureExtensionPointsOrder(projectRoot)) consola.default.warn(`The extension points in ${APP_CONFIG_FILE} were reordered (${EXTENSION_POINT_ORDER.join(", ")}) to ensure an upgrade works reliably. This is a one-off change.`);
3652
+ if (await ensureExtensionPointsOrder(projectRoot)) consola.default.warn(`The extension points in ${APP_CONFIG_FILE$1} were reordered (${EXTENSION_POINT_ORDER.join(", ")}) to ensure an upgrade works reliably. This is a one-off change.`);
2601
3653
  const appManifest = await loadAppManifest(projectRoot);
2602
3654
  await run$8(appManifest, projectRoot);
2603
3655
  await prepareRuntimeAppConfigModule(appManifest, projectRoot);
2604
3656
  if (extension === "extensibility/1") {
2605
3657
  const { doc: extensibilityExtConfig } = await readExtConfig(EXTENSIBILITY_EXTENSION_POINT_ID, projectRoot);
2606
- await generateActionFiles(appManifest, getRuntimeActions(extensibilityExtConfig.toJS(), "app-management"), EXTENSIBILITY_EXTENSION_POINT_ID, templatesDir, projectRoot);
3658
+ const extensibilityConfig = extensibilityExtConfig.toJS();
3659
+ await validateRuntimeActionReferences({
3660
+ eventing: appManifest.eventing,
3661
+ webhooks: appManifest.webhooks
3662
+ }, {
3663
+ extensionPointId: EXTENSIBILITY_EXTENSION_POINT_ID,
3664
+ path: getExtConfigPath(EXTENSIBILITY_EXTENSION_POINT_ID),
3665
+ projectRoot
3666
+ });
3667
+ await generateActionFiles(appManifest, getRuntimeActions(extensibilityConfig, "app-management"), EXTENSIBILITY_EXTENSION_POINT_ID, templatesDir, projectRoot);
2607
3668
  consola.default.info("Syncing IMS credentials...");
2608
3669
  consola.default.warn("Deprecated: if your actions use AIO_COMMERCE_AUTH_IMS_* inputs for OAuth Server-to-Server credentials, replace them with the `include-ims-credentials: true` action annotation. This hook still syncs legacy credentials for compatibility; that sync will be removed in a future major release.");
2609
3670
  await syncImsCredentials(projectRoot);
@@ -2617,6 +3678,11 @@ async function run$4(extension, projectRoot, templatesDir = TEMPLATES_DIR) {
2617
3678
  }
2618
3679
  if (extension === "backend-ui/2") {
2619
3680
  if (require_webhooks.hasBackendUiV2Components(appManifest)) {
3681
+ await validateRuntimeActionReferences({ adminUi: appManifest.adminUi }, {
3682
+ extensionPointId: BACKEND_UI_V2_EXTENSION_POINT_ID,
3683
+ path: getExtConfigPath(BACKEND_UI_V2_EXTENSION_POINT_ID),
3684
+ projectRoot
3685
+ });
2620
3686
  const extConfig = await updateExtConfig(appManifest, BACKEND_UI_V2_EXTENSION_POINT_ID, projectRoot);
2621
3687
  if (extConfig.operations?.view) {
2622
3688
  await prepareWebSourceImportAlias(extConfig, projectRoot);
@@ -2634,7 +3700,7 @@ async function exec$5() {
2634
3700
  const rawExtension = process.env.EXTENSION;
2635
3701
  try {
2636
3702
  if (!rawExtension) throw new Error("EXTENSION environment variable is not set");
2637
- await run$4(rawExtension, await require_index_node.getProjectRootDirectory());
3703
+ await run$4(rawExtension, await require_parser.getProjectRootDirectory());
2638
3704
  } catch (error) {
2639
3705
  if (error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) consola.default.error(error.display());
2640
3706
  else consola.default.error(error);
@@ -2642,7 +3708,7 @@ async function exec$5() {
2642
3708
  }
2643
3709
  }
2644
3710
 
2645
- // source/commands/hooks/pre-app-dev.ts
3711
+ // source/deprecated/commands/hooks/pre-app-dev.ts
2646
3712
  /**
2647
3713
  * Resets the web build back to development by writing `NODE_ENV` to the project `.env`.
2648
3714
  * @param projectRoot - Resolved project root containing the `.env` file.
@@ -2654,7 +3720,7 @@ async function run$3(projectRoot) {
2654
3720
  async function exec$4() {
2655
3721
  consola.default.debug("Running lib-app pre-app-dev hook");
2656
3722
  try {
2657
- await run$3(await require_index_node.getProjectRootDirectory());
3723
+ await run$3(await require_parser.getProjectRootDirectory());
2658
3724
  } catch (error) {
2659
3725
  if (error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) consola.default.error(error.display());
2660
3726
  else consola.default.error(error);
@@ -2662,7 +3728,7 @@ async function exec$4() {
2662
3728
  }
2663
3729
  }
2664
3730
 
2665
- // source/commands/hooks/pre-app-run.ts
3731
+ // source/deprecated/commands/hooks/pre-app-run.ts
2666
3732
  /**
2667
3733
  * Resets the web build back to development by writing `NODE_ENV` to the project `.env`.
2668
3734
  * @param projectRoot - Resolved project root containing the `.env` file.
@@ -2674,7 +3740,7 @@ async function run$2(projectRoot) {
2674
3740
  async function exec$3() {
2675
3741
  consola.default.debug("Running lib-app pre-app-run hook");
2676
3742
  try {
2677
- await run$2(await require_index_node.getProjectRootDirectory());
3743
+ await run$2(await require_parser.getProjectRootDirectory());
2678
3744
  } catch (error) {
2679
3745
  if (error instanceof _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError) consola.default.error(error.display());
2680
3746
  else consola.default.error(error);
@@ -2682,86 +3748,7 @@ async function exec$3() {
2682
3748
  }
2683
3749
  }
2684
3750
 
2685
- // source/commands/init/constants.ts
2686
- /** The default values for the features of the commerce app config. */
2687
- const DOMAIN_DEFAULTS = {
2688
- businessConfig: { schema: [{
2689
- default: ["a"],
2690
- label: "Sample List",
2691
- name: "sampleList",
2692
- options: [{
2693
- label: "Option A",
2694
- value: "a"
2695
- }, {
2696
- label: "Option B",
2697
- value: "b"
2698
- }],
2699
- selectionMode: "multiple",
2700
- type: "list"
2701
- }, {
2702
- default: "Hello, world!",
2703
- label: "Sample Text",
2704
- name: "sampleText",
2705
- type: "text"
2706
- }] },
2707
- "eventing.commerce": [{
2708
- events: [{
2709
- description: "Use case description for the event.",
2710
- fields: [{ name: "*" }],
2711
- label: "Sample Event",
2712
- name: "plugin.sample_event",
2713
- runtimeActions: ["my-package/handle-sample-event"]
2714
- }],
2715
- provider: {
2716
- description: "A description for your Commerce Events provider.",
2717
- label: "Commerce Events Provider"
2718
- }
2719
- }],
2720
- "eventing.external": [{
2721
- events: [{
2722
- description: "Use case description for the event.",
2723
- label: "Sample Event",
2724
- name: "be-observer.sample_event",
2725
- runtimeActions: ["my-package/handle-sample-event"]
2726
- }],
2727
- provider: {
2728
- description: "A description for your External Events provider.",
2729
- label: "External Events Provider"
2730
- }
2731
- }],
2732
- "installation.customInstallationSteps": [{
2733
- description: "Use case description for the step.",
2734
- name: "sample-step",
2735
- script: "./path/to/script.js"
2736
- }],
2737
- webhooks: [{
2738
- category: "modification",
2739
- description: "A sample Commerce Webhook handler.",
2740
- label: "Sample Webhook",
2741
- runtimeAction: "my-package/handle-webhook",
2742
- webhook: {
2743
- batch_name: "my_app",
2744
- hook_name: "sample_hook",
2745
- method: "POST",
2746
- webhook_method: "plugin.sample.event",
2747
- webhook_type: "after"
2748
- }
2749
- }, {
2750
- category: "modification",
2751
- description: "A sample Commerce Webhook handler using an explicit URL.",
2752
- label: "Sample Webhook with URL",
2753
- webhook: {
2754
- batch_name: "my_app",
2755
- hook_name: "sample_hook_url",
2756
- method: "POST",
2757
- url: "https://example.com/webhook",
2758
- webhook_method: "plugin.sample.event",
2759
- webhook_type: "after"
2760
- }
2761
- }]
2762
- };
2763
-
2764
- // source/commands/init/utils.ts
3751
+ // source/deprecated/commands/init/utils.ts
2765
3752
  /**
2766
3753
  * Convert the given init options to answers for scaffolding the app config. This is useful for non-interactive use cases, such as running the command with a config file or from another script.
2767
3754
  * @param flags - The initialization options
@@ -2800,28 +3787,10 @@ async function promptForCommerceAppConfig() {
2800
3787
  const featuresToAdd = await consola.default.prompt(`What features do you want to add to your app? ${(0, consola_utils.colorize)("gray", "Space to select/deselect, Enter to submit")}`, {
2801
3788
  cancel: "reject",
2802
3789
  initial: [],
2803
- options: [
2804
- {
2805
- label: "Business Configuration",
2806
- value: "businessConfig.schema"
2807
- },
2808
- {
2809
- label: "Commerce Events",
2810
- value: "eventing.commerce"
2811
- },
2812
- {
2813
- label: "Commerce Webhooks",
2814
- value: "webhooks"
2815
- },
2816
- {
2817
- label: "External Events",
2818
- value: "eventing.external"
2819
- },
2820
- {
2821
- label: "Custom Installation Steps",
2822
- value: "installation.customInstallationSteps"
2823
- }
2824
- ],
3790
+ options: Object.entries(require_index_node.COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS).map(([value, { label }]) => ({
3791
+ label,
3792
+ value
3793
+ })),
2825
3794
  required: true,
2826
3795
  type: "multiselect"
2827
3796
  });
@@ -2837,7 +3806,7 @@ async function promptForCommerceAppConfig() {
2837
3806
  }
2838
3807
  /** Create the default commerce app config file content */
2839
3808
  async function getDefaultCommerceAppConfig(cwd, { appName, configFormat, domains }) {
2840
- const needsESM = await require_index_node.isESM(cwd) || configFormat === "ts";
3809
+ const needsESM = await require_parser.isESM(cwd) || configFormat === "ts";
2841
3810
  const exportKeyword = needsESM ? "export default" : "module.exports =";
2842
3811
  const importStatement = needsESM ? "import { defineConfig } from \"@adobe/aio-commerce-lib-app/config\";" : "const { defineConfig } = require(\"@adobe/aio-commerce-lib-app/config\");";
2843
3812
  const defaultConfig = { metadata: {
@@ -2846,17 +3815,17 @@ async function getDefaultCommerceAppConfig(cwd, { appName, configFormat, domains
2846
3815
  id: appName.toLowerCase().replace(/ /gu, "-"),
2847
3816
  version: "1.0.0"
2848
3817
  } };
2849
- if (domains.has("businessConfig.schema")) defaultConfig.businessConfig = { schema: DOMAIN_DEFAULTS.businessConfig.schema };
3818
+ if (domains.has("businessConfig.schema")) defaultConfig.businessConfig = { schema: require_index_node.COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["businessConfig.schema"].value };
2850
3819
  if (domains.has("eventing.commerce")) defaultConfig.eventing = {
2851
3820
  ...defaultConfig.eventing,
2852
- commerce: DOMAIN_DEFAULTS["eventing.commerce"]
3821
+ commerce: require_index_node.COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["eventing.commerce"].value
2853
3822
  };
2854
3823
  if (domains.has("eventing.external")) defaultConfig.eventing = {
2855
3824
  ...defaultConfig.eventing,
2856
- external: DOMAIN_DEFAULTS["eventing.external"]
3825
+ external: require_index_node.COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["eventing.external"].value
2857
3826
  };
2858
- if (domains.has("installation.customInstallationSteps")) defaultConfig.installation = { customInstallationSteps: DOMAIN_DEFAULTS["installation.customInstallationSteps"] };
2859
- if (domains.has("webhooks")) defaultConfig.webhooks = DOMAIN_DEFAULTS.webhooks;
3827
+ if (domains.has("installation.customInstallationSteps")) defaultConfig.installation = { customInstallationSteps: require_index_node.COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["installation.customInstallationSteps"].value };
3828
+ if (domains.has("webhooks")) defaultConfig.webhooks = require_index_node.COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS.webhooks.value;
2860
3829
  return [
2861
3830
  importStatement,
2862
3831
  "",
@@ -2870,24 +3839,24 @@ async function getDefaultCommerceAppConfig(cwd, { appName, configFormat, domains
2870
3839
  * @param commentBefore - The comment to add before the extension point include pair.
2871
3840
  */
2872
3841
  async function addExtensionPointToAppConfig(extensionPointId, rootDirectory, commentBefore) {
2873
- const appConfigPath = (0, path.join)(rootDirectory, APP_CONFIG_FILE);
3842
+ const appConfigPath = (0, path.join)(rootDirectory, APP_CONFIG_FILE$1);
2874
3843
  let doc;
2875
3844
  const includePath = (0, path.relative)(rootDirectory, (0, path.join)(rootDirectory, getExtConfigPath(extensionPointId)));
2876
3845
  try {
2877
3846
  doc = await readYamlFile(appConfigPath);
2878
3847
  } catch (error) {
2879
3848
  const fallbackContent = `extensions:\n ${extensionPointId}:\n $include: "${includePath}"`;
2880
- throw new Error(`Failed to parse ${APP_CONFIG_FILE}. \nPlease add manually: \n\n${fallbackContent}`, { cause: error });
3849
+ throw new Error(`Failed to parse ${APP_CONFIG_FILE$1}. \nPlease add manually: \n\n${fallbackContent}`, { cause: error });
2881
3850
  }
2882
3851
  if (doc.getIn([
2883
3852
  "extensions",
2884
3853
  extensionPointId,
2885
3854
  "$include"
2886
3855
  ]) === includePath) {
2887
- consola.default.success(`Extension "${extensionPointId}" already configured in ${APP_CONFIG_FILE}`);
3856
+ consola.default.success(`Extension "${extensionPointId}" already configured in ${APP_CONFIG_FILE$1}`);
2888
3857
  return;
2889
3858
  }
2890
- consola.default.info(`Adding extension "${extensionPointId}" to ${APP_CONFIG_FILE}...`);
3859
+ consola.default.info(`Adding extension "${extensionPointId}" to ${APP_CONFIG_FILE$1}...`);
2891
3860
  const extensions = getOrCreateMap(doc, ["extensions"]);
2892
3861
  getOrCreateMap(doc, ["extensions", extensionPointId], { onBeforeCreate: (pair) => {
2893
3862
  pair.key.spaceBefore = extensions.items.length > 0;
@@ -2924,7 +3893,7 @@ async function addExtensionPointToInstallYaml(extensionPointId, rootDirectory, c
2924
3893
  await (0, fs_promises.writeFile)(installYamlPath, doc.toString(), "utf-8");
2925
3894
  }
2926
3895
 
2927
- // source/commands/init/lib.ts
3896
+ // source/deprecated/commands/init/lib.ts
2928
3897
  /**
2929
3898
  * Ensures a valid app configuration exists, creating one when requested.
2930
3899
  * @param projectRoot - Resolved project root containing the app configuration.
@@ -2932,14 +3901,14 @@ async function addExtensionPointToInstallYaml(extensionPointId, rootDirectory, c
2932
3901
  * @param flags - Non-interactive answers; prompts are used when omitted.
2933
3902
  */
2934
3903
  async function ensureCommerceAppConfig(projectRoot, formatConfig = true, flags) {
2935
- const configFilePath = await require_index_node.resolveCommerceAppConfig(projectRoot);
3904
+ const configFilePath = await require_parser.resolveCommerceAppConfig(projectRoot);
2936
3905
  if (configFilePath !== null) try {
2937
- const config = await require_index_node.readCommerceAppConfig(projectRoot);
3906
+ const config = await require_parser.readCommerceAppConfig(projectRoot);
2938
3907
  const validatedConfig = require_validate.validateCommerceAppConfig(config);
2939
3908
  consola.consola.success(`${COMMERCE_APP_CONFIG_FILE} found and is valid. Continuing...`);
2940
3909
  return {
2941
3910
  config: validatedConfig,
2942
- configFormat: require_index_node.isTypeScriptConfig(configFilePath) ? "ts" : "js",
3911
+ configFormat: require_parser.isTypeScriptConfig(configFilePath) ? "ts" : "js",
2943
3912
  domains: require_validate.getConfigDomains(validatedConfig)
2944
3913
  };
2945
3914
  } catch (error) {
@@ -2956,13 +3925,13 @@ async function ensureCommerceAppConfig(projectRoot, formatConfig = true, flags)
2956
3925
  const answers = flags ? initFlagsToScaffoldAppAnswers(flags) : await promptForCommerceAppConfig();
2957
3926
  try {
2958
3927
  const configContent = await getDefaultCommerceAppConfig(projectRoot, answers);
2959
- const path$2 = (0, path.join)(projectRoot, answers.configFile);
3928
+ const path$1 = (0, path.join)(projectRoot, answers.configFile);
2960
3929
  consola.consola.info(`Creating ${answers.configFile}...`);
2961
3930
  if (formatConfig) {
2962
- const formattedConfig = await prettierFormat(configContent, path$2);
2963
- await (0, fs_promises.writeFile)(path$2, formattedConfig, "utf-8");
2964
- } else await (0, fs_promises.writeFile)(path$2, configContent, "utf-8");
2965
- const createdConfig = await require_index_node.parseCommerceAppConfig(projectRoot);
3931
+ const formattedConfig = await prettierFormat(configContent, path$1);
3932
+ await (0, fs_promises.writeFile)(path$1, formattedConfig, "utf-8");
3933
+ } else await (0, fs_promises.writeFile)(path$1, configContent, "utf-8");
3934
+ const createdConfig = await require_parser.parseCommerceAppConfig(projectRoot);
2966
3935
  consola.consola.success(`Created ${answers.configFile}`);
2967
3936
  return {
2968
3937
  config: createdConfig,
@@ -2978,7 +3947,7 @@ async function ensureCommerceAppConfig(projectRoot, formatConfig = true, flags)
2978
3947
  * @param cwd - Directory in which to create or discover package.json.
2979
3948
  */
2980
3949
  async function ensurePackageJson(cwd = process.cwd()) {
2981
- const existing = await require_index_node.readPackageJson(cwd);
3950
+ const existing = await require_parser.readPackageJson(cwd);
2982
3951
  let packageJson;
2983
3952
  if (existing) packageJson = existing;
2984
3953
  else {
@@ -2991,10 +3960,10 @@ async function ensurePackageJson(cwd = process.cwd()) {
2991
3960
  await (0, fs_promises.writeFile)((0, path.join)((0, path.resolve)(cwd), PACKAGE_JSON_FILE), JSON.stringify(packageJson, null, 2), "utf-8");
2992
3961
  consola.consola.success("Wrote package.json");
2993
3962
  }
2994
- const projectRoot = await require_index_node.getProjectRootDirectory(cwd);
2995
- const packageManager = await require_index_node.detectPackageManager(projectRoot);
3963
+ const projectRoot = await require_parser.getProjectRootDirectory(cwd);
3964
+ const packageManager = await require_parser.detectPackageManager(projectRoot);
2996
3965
  return {
2997
- execCommand: require_index_node.getExecCommand(packageManager),
3966
+ execCommand: require_parser.getExecCommand(packageManager),
2998
3967
  packageJson,
2999
3968
  packageManager,
3000
3969
  projectRoot
@@ -3007,14 +3976,14 @@ async function ensurePackageJson(cwd = process.cwd()) {
3007
3976
  */
3008
3977
  async function writePostinstallHook(execCommand, projectRoot) {
3009
3978
  const postinstallScript = `${execCommand} aio-commerce-lib-app hooks postinstall`;
3010
- const pkg = await require_index_node.loadPackageJson(projectRoot);
3979
+ const pkg = await require_parser.loadPackageJson(projectRoot);
3011
3980
  if (pkg === null) throw new Error("Could not find package.json.");
3012
3981
  const existing = pkg.content.scripts?.postinstall;
3013
3982
  if (existing === postinstallScript || existing?.includes(postinstallScript)) {
3014
3983
  consola.consola.success(`postinstall script already configured in ${PACKAGE_JSON_FILE}`);
3015
3984
  return;
3016
3985
  }
3017
- const nextPostinstall = require_index_node.appendCommand(existing, postinstallScript);
3986
+ const nextPostinstall = require_parser.appendCommand(existing, postinstallScript);
3018
3987
  if (existing) consola.consola.warn(`${PACKAGE_JSON_FILE} already has a postinstall script. Adding a new one...`);
3019
3988
  else consola.consola.info(`Adding postinstall script to ${PACKAGE_JSON_FILE}...`);
3020
3989
  pkg.update({ scripts: {
@@ -3044,7 +4013,7 @@ async function ensureAppConfig(domains, config, projectRoot) {
3044
4013
  */
3045
4014
  function installDependencies(packageManager, domains, projectRoot) {
3046
4015
  const packages = [];
3047
- if (domains.has("businessConfig.schema")) packages.push(`@adobe/aio-commerce-lib-config@^1.9.0`);
4016
+ if (domains.has("businessConfig.schema")) packages.push(`@adobe/aio-commerce-lib-config@^1.10.0-alpha-20261203134759`);
3048
4017
  if (packages.length === 0) {
3049
4018
  consola.consola.info("No additional domain dependencies to install.");
3050
4019
  return;
@@ -3078,8 +4047,8 @@ async function ensureInstallYaml(domains, config, projectRoot) {
3078
4047
  await addExtensionPointToInstallYaml(EXTENSIBILITY_EXTENSION_POINT_ID, projectRoot, " This extension is required for app management. Do not remove.");
3079
4048
  }
3080
4049
 
3081
- // source/commands/init/main.ts
3082
- const REQUIRED_DEPENDENCIES = ["@adobe/aio-commerce-sdk", `@adobe/aio-commerce-lib-app@2.2.0`];
4050
+ // source/deprecated/commands/init/main.ts
4051
+ const REQUIRED_DEPENDENCIES = ["@adobe/aio-commerce-sdk", `@adobe/aio-commerce-lib-app@2.3.0-alpha-20261203134759`];
3083
4052
  /**
3084
4053
  * Initializes a Commerce App project.
3085
4054
  * @param flags - Non-interactive initialization answers.
@@ -3094,7 +4063,7 @@ async function run$1(flags, extraOptions) {
3094
4063
  const isTypeScriptProject = configFormat === "ts";
3095
4064
  installDependencies(packageManager, domains, projectRoot);
3096
4065
  if (isTypeScriptProject) await scaffoldTypeScriptProject(packageManager, projectRoot);
3097
- const pkg = await require_index_node.loadPackageJson(projectRoot);
4066
+ const pkg = await require_parser.loadPackageJson(projectRoot);
3098
4067
  if (pkg === null) throw new Error("Could not find package.json.");
3099
4068
  pkg.update({
3100
4069
  description: config.metadata.description,
@@ -3125,7 +4094,7 @@ async function exec$2() {
3125
4094
  }
3126
4095
  }
3127
4096
 
3128
- // source/commands/upgrade/status/main.ts
4097
+ // source/deprecated/commands/upgrade/status/main.ts
3129
4098
  /**
3130
4099
  * Reads the arguments of `upgrade status`.
3131
4100
  * @returns The options, or a message that tells what is wrong with the arguments.
@@ -3145,11 +4114,11 @@ function parseStatusArgs(argv) {
3145
4114
  */
3146
4115
  async function resolveRun(client, extensionId, runId) {
3147
4116
  if (runId) return runId;
3148
- return (await client.readLatestUpgrade({ extensionId }))?.id;
4117
+ return (await client.getLatestUpgradeRun({ extensionId }))?.id;
3149
4118
  }
3150
4119
  /** Prints how a run stands now. */
3151
4120
  function printStatus(status) {
3152
- if (!isSettled(status)) {
4121
+ if (!isRunFinished(status)) {
3153
4122
  consola.consola.info(`The app upgrade (run ${status.id}) is ${status.status}.`);
3154
4123
  return;
3155
4124
  }
@@ -3183,7 +4152,7 @@ async function run(options) {
3183
4152
  return 0;
3184
4153
  }
3185
4154
  try {
3186
- const status = await client.pollUpgrade({
4155
+ const status = await client.syncUpgradeRun({
3187
4156
  extensionId,
3188
4157
  runId: targetRunId
3189
4158
  });
@@ -3214,7 +4183,7 @@ async function exec$1(...argv) {
3214
4183
  }
3215
4184
  }
3216
4185
 
3217
- // source/commands/upgrade/watcher/main.ts
4186
+ // source/deprecated/commands/upgrade/watcher/main.ts
3218
4187
  /** How long the watcher waits for a token before it gives up. */
3219
4188
  const TOKEN_TIMEOUT_MS = 3e4;
3220
4189
  /**
@@ -3258,17 +4227,12 @@ function parseWatcherArgs(argv) {
3258
4227
  * @returns The exit code: 0 when the run succeeded, 1 otherwise.
3259
4228
  */
3260
4229
  async function runWatcher(args, dependencies) {
3261
- const { log, createClient, sleep } = dependencies;
4230
+ const { log, createClient } = dependencies;
3262
4231
  log(`The hook is gone (${await waitForOwnerExit()}). Following the run ${args.runId}.`);
3263
4232
  const client = await createClient();
3264
- const result = await pollUntilSettled({
4233
+ const result = await followUntilSettled(client, args, {
3265
4234
  onRetry: (error) => log(`${error.message}. Trying again.`),
3266
- onStatus: (status) => log(`Status ${status.status}.`),
3267
- poll: () => client.pollUpgrade({
3268
- extensionId: args.extensionId,
3269
- runId: args.runId
3270
- }),
3271
- sleep
4235
+ onStatus: (status) => log(`Status ${status.status}.`)
3272
4236
  });
3273
4237
  const outcome = describeOutcome(result, args.runId);
3274
4238
  log(outcome.message);
@@ -3306,7 +4270,7 @@ async function exec(...argv) {
3306
4270
  process.exit();
3307
4271
  }
3308
4272
 
3309
- // source/commands/index.ts
4273
+ // source/deprecated/commands/index.ts
3310
4274
  const NAMESPACE = "@adobe/aio-commerce-lib-app";
3311
4275
  const [command, subcommand, ...targetArgs] = process.argv.slice(2);
3312
4276
  const USAGE = `