@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,35 +13,37 @@
13
13
  * governing permissions and limitations under the License.
14
14
  */
15
15
 
16
- import { _ as makeOutputDirFor, a as resolveCommerceAppConfig, c as getExecCommand, d as getPackageExecutionCommand, f as getProjectInstallCommand, g as loadPackageJson, h as isESM, i as readCommerceAppConfig, l as getInstallCommand, m as getRunScriptCommand, n as isTypeScriptConfig, o as appendCommand, p as getProjectRootDirectory, r as parseCommerceAppConfig, s as detectPackageManager, t as hasNamedCommerceAppConfigExports, u as getPackageDependencyInstallPlan, v as mergePackageJsonDependencies, y as readPackageJson } from "../index.node-CURztkP5.mjs";
17
- import { a as hasCustomInstallationSteps, d as ADMIN_UI_MASS_ACTION_ENTITIES, f as ADMIN_UI_VIEW_BUTTON_ENTITIES, h as hasBackendUiV2Components, u as ADMIN_UI_GRID_COLUMN_ENTITIES } from "../webhooks-HBe_DEKA.mjs";
18
- import { o as getConfigDomains, t as validateCommerceAppConfig, u as hasBusinessConfigSchema } from "../validate-xS9Dc-4m.mjs";
19
- import { t as parseOrThrow } from "../utils-G-EDWmew.mjs";
20
- import { r as nonEmptyStringValueSchema } from "../schemas-DYMNbFdX.mjs";
21
- import { t as inspect } from "../logging-B1xb568A.mjs";
22
- import { hasDynamicSchema } from "@adobe/aio-commerce-lib-config";
23
16
  import { CommerceSdkErrorBase, CommerceSdkValidationError, stringifyError } from "@adobe/aio-commerce-lib-core/error";
24
- import * as v from "valibot";
25
17
  import consola$1, { consola } from "consola";
26
- import { closeSync, constants, existsSync, openSync, readFileSync, writeFileSync } from "fs";
18
+ import { _ as isESM, a as resolveCommerceAppConfig, b as mergePackageJsonDependencies, c as appendCommand, d as getInstallCommand, f as getPackageDependencyInstallPlan, g as getRunScriptCommand, h as getProjectRootDirectory, i as readCommerceAppConfig, l as detectPackageManager, m as getProjectInstallCommand, n as isTypeScriptConfig, p as getPackageExecutionCommand, r as parseCommerceAppConfig, s as COMMAND_SEPARATOR, t as hasNamedCommerceAppConfigExports, u as getExecCommand, v as loadPackageJson, x as readPackageJson, y as makeOutputDirFor } from "../../parser-DdhiGXVf.mjs";
19
+ import { a as hasCustomInstallationSteps, d as ADMIN_UI_MASS_ACTION_ENTITIES, f as ADMIN_UI_VIEW_BUTTON_ENTITIES, g as hasBackendUiV2Components, u as ADMIN_UI_GRID_COLUMN_ENTITIES } from "../../webhooks-Ba-OdU8e.mjs";
20
+ import { f as hasBusinessConfigSchema, s as getConfigDomains, t as validateCommerceAppConfig } from "../../validate-CYWj7Nzp.mjs";
21
+ import { closeSync, constants, existsSync, fchmodSync, openSync } from "fs";
27
22
  import { access, copyFile, mkdir, readFile, readdir, rm, writeFile } from "fs/promises";
28
- import path, { basename, dirname, extname, join, relative, resolve, sep } from "path";
23
+ import { basename, dirname, extname, join, relative, resolve, sep } from "path";
29
24
  import { colorize, colors, formatTree } from "consola/utils";
30
25
  import { fileURLToPath } from "url";
31
26
  import { execSync, spawn, spawnSync } from "child_process";
27
+ import { hasDynamicSchema } from "@adobe/aio-commerce-lib-config";
32
28
  import * as prettier from "prettier";
33
- import { Document, YAMLMap, YAMLSeq, isMap, isNode, isPair, isScalar, isSeq, parseDocument } from "yaml";
29
+ import { Document, YAMLMap, YAMLSeq, isMap, isNode as isNode$1, isScalar, isSeq, parse as parse$1, parseDocument } from "yaml";
34
30
  import { stringify as stringify$1 } from "safe-stable-stringify";
31
+ import { HTTP_CONFLICT, HTTP_NO_CONTENT, HTTP_OK } from "@adobe/aio-commerce-lib-core/responses";
35
32
  import { tmpdir } from "os";
36
33
  import net from "net";
37
34
  import aioIms from "@adobe/aio-lib-ims";
38
- import config from "@adobe/aio-lib-core-config";
35
+ import { t as parseOrThrow } from "../../utils-G-EDWmew.mjs";
36
+ import * as v from "valibot";
39
37
  import ky, { HTTPError, TimeoutError } from "ky";
40
- import { HTTP_CONFLICT } from "@adobe/aio-commerce-lib-core/responses";
41
- import { setTimeout as setTimeout$1 } from "timers/promises";
42
- import dotenv from "dotenv";
38
+ import { r as nonEmptyStringValueSchema } from "../../schemas-DYMNbFdX.mjs";
39
+ import { CommerceEnvSchema } from "@adobe/aio-commerce-lib-core/commerce";
40
+ import config from "@adobe/aio-lib-core-config";
41
+ import { parseEnv } from "util";
42
+ import { coalesce } from "@adobe/aio-cli-lib-app-config";
43
+ import { t as inspect } from "../../logging-B1xb568A.mjs";
44
+ import { t as COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS } from "../../index.node-DipCrOq_.mjs";
43
45
 
44
- // source/commands/constants.ts
46
+ // source/deprecated/commands/constants.ts
45
47
  /** The name of the package containing all the generated runtime actions */
46
48
  const PACKAGE_NAME = "app-management";
47
49
  /** The path to the directory containing the generated files */
@@ -87,7 +89,7 @@ const CONFIG_SCHEMA_FILE_NAME = "configuration-schema.json";
87
89
  /** The name of the project package file */
88
90
  const PACKAGE_JSON_FILE = "package.json";
89
91
  /** The name of the app configuration file */
90
- const APP_CONFIG_FILE = "app.config.yaml";
92
+ const APP_CONFIG_FILE$1 = "app.config.yaml";
91
93
  /** The name of the install configuration file */
92
94
  const INSTALL_YAML_FILE = "install.yaml";
93
95
  /** Get the path to the extension point folder */
@@ -95,16 +97,14 @@ function getExtensionPointFolderPath(extensionPointId) {
95
97
  return `src/${extensionPointId.replaceAll("/", "-")}`;
96
98
  }
97
99
 
98
- // source/commands/generate/actions/constants.ts
99
- const __filename = fileURLToPath(import.meta.url);
100
- const __dirname = dirname(__filename);
101
- /** The path to the action templates directory, sibling to this file. */
102
- const TEMPLATES_DIR = join(__dirname, "templates");
103
- const CUSTOM_IMPORTS_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_IMPORTS}}";
104
- const CUSTOM_SCRIPTS_MAP_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_MAP}}";
105
- const CUSTOM_SCRIPTS_LOADER_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_LOADER}}";
100
+ // source/deprecated/commands/templates-dir.ts
101
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
102
+ /** The generation templates. */
103
+ const TEMPLATES_DIR = join(MODULE_DIR, "..", "..", "project", "templates");
104
+ /** The TypeScript build templates, which only the deprecated commands use. */
105
+ const TYPESCRIPT_TEMPLATES_DIR = join(MODULE_DIR, "templates", "typescript");
106
106
 
107
- // source/commands/utils.ts
107
+ // source/deprecated/commands/utils.ts
108
108
  /** Format file content using prettier, inferring the parser from the file path. */
109
109
  function prettierFormat(content, filepath) {
110
110
  return prettier.format(content, {
@@ -228,7 +228,7 @@ function getSchemaPath() {
228
228
  return join(getGeneratedDir(CONFIGURATION_EXTENSION_POINT_ID), CONFIG_SCHEMA_FILE_NAME);
229
229
  }
230
230
 
231
- // source/commands/typescript.ts
231
+ // source/deprecated/commands/typescript.ts
232
232
  const WEBPACK_CONFIG_PATTERN = /^webpack-config\.(?:cjs|js)$/u;
233
233
  const WEBPACK_CONFIG_FILE = "webpack-config.cjs";
234
234
  const TSCONFIG_FILE = "tsconfig.json";
@@ -275,7 +275,7 @@ async function scaffoldWebpackConfig(projectRoot) {
275
275
  consola.info(`Found ${existingConfig.name}; leaving it unchanged.`);
276
276
  return;
277
277
  }
278
- await copyFile(join(TEMPLATES_DIR, "typescript", WEBPACK_CONFIG_FILE), join(projectRoot, WEBPACK_CONFIG_FILE));
278
+ await copyFile(join(TYPESCRIPT_TEMPLATES_DIR, WEBPACK_CONFIG_FILE), join(projectRoot, WEBPACK_CONFIG_FILE));
279
279
  }
280
280
  /**
281
281
  * Create the Runtime actions TypeScript configuration when it does not exist.
@@ -344,7 +344,7 @@ async function syncWebSourceTypecheckScript(projectRoot) {
344
344
  await syncTypecheckScript(WEB_SOURCE_TYPECHECK_SCRIPT, WEB_SOURCE_TYPECHECK_COMMAND, projectRoot);
345
345
  }
346
346
 
347
- // source/commands/generate/web-src.ts
347
+ // source/deprecated/commands/generate/web-src.ts
348
348
  const JSX_FILE_EXTENSION = ".jsx";
349
349
  const TSX_FILE_EXTENSION = ".tsx";
350
350
  const APP_TITLE_PLACEHOLDER = "APP_TITLE";
@@ -357,7 +357,7 @@ const LEADING_DOT_SLASH_PATTERN$1 = /^\.\//u;
357
357
  const WEB_SOURCE_DEPENDENCIES = [
358
358
  {
359
359
  name: "@adobe/aio-commerce-lib-admin-ui",
360
- version: "^1.3.0"
360
+ version: "^1.3.1-alpha-20261203134759"
361
361
  },
362
362
  {
363
363
  name: "react",
@@ -591,7 +591,7 @@ async function generateWebSrc(extConfig, appName, projectRoot, templatesDir = TE
591
591
  }
592
592
  }
593
593
 
594
- // source/commands/generate/actions/config.ts
594
+ // source/deprecated/commands/generate/actions/config.ts
595
595
  /**
596
596
  * Creates a runtime action configuration.
597
597
  * @param actionName - The name of the action.
@@ -808,10 +808,7 @@ function getOrCreateMap(doc, path, options) {
808
808
  function getExistingInputs(existingAction) {
809
809
  const inputs = existingAction?.get("inputs");
810
810
  if (!isMap(inputs)) return {};
811
- return Object.fromEntries(inputs.items.map((item) => {
812
- if (!isPair(item)) return [];
813
- return [String(item.key), isScalar(item.value) ? item.value.value : item.value];
814
- }));
811
+ return Object.fromEntries(inputs.items.map((item) => [String(item.key), isScalar(item.value) ? item.value.value : item.value]));
815
812
  }
816
813
  /**
817
814
  * Read a string field from an existing YAML action definition. Used by codegen
@@ -1005,7 +1002,12 @@ async function writeExtConfig(configPath, doc) {
1005
1002
  await writeFile(configPath, yamlContent, "utf-8");
1006
1003
  }
1007
1004
 
1008
- // source/commands/generate/actions/lib.ts
1005
+ // source/deprecated/commands/generate/actions/constants.ts
1006
+ const CUSTOM_IMPORTS_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_IMPORTS}}";
1007
+ const CUSTOM_SCRIPTS_MAP_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_MAP}}";
1008
+ const CUSTOM_SCRIPTS_LOADER_PLACEHOLDER = "// {{CUSTOM_SCRIPTS_LOADER}}";
1009
+
1010
+ // source/deprecated/commands/generate/actions/lib.ts
1009
1011
  const ESBUILD_PACKAGE = "esbuild@0.28.0";
1010
1012
  const LEADING_DOT_SLASH_PATTERN = /^\.\//u;
1011
1013
  /** Normalize a path for use as an ESM import specifier. */
@@ -1266,7 +1268,7 @@ async function generateCustomScriptsTemplate(template, appManifest, projectRoot)
1266
1268
  return template.replace(CUSTOM_IMPORTS_PLACEHOLDER, importStatements).replace(CUSTOM_SCRIPTS_MAP_PLACEHOLDER, scriptMap);
1267
1269
  }
1268
1270
 
1269
- // source/commands/generate/actions/main.ts
1271
+ // source/deprecated/commands/generate/actions/main.ts
1270
1272
  /**
1271
1273
  * Generates extension configs, runtime actions, and Admin UI web source for the configured domains.
1272
1274
  * @param appManifest - App configuration used to determine the generated content.
@@ -1301,7 +1303,7 @@ async function exec$10() {
1301
1303
  }
1302
1304
  }
1303
1305
 
1304
- // source/commands/generate/manifest/main.ts
1306
+ // source/deprecated/commands/generate/manifest/main.ts
1305
1307
  /**
1306
1308
  * Generates or removes the static app manifest as required by the app config.
1307
1309
  * @param appConfig - Validated app configuration to serialize.
@@ -1338,6 +1340,21 @@ async function exec$9() {
1338
1340
 
1339
1341
  // ../../packages-private/scripting-utils/source/filesystem/helpers.ts
1340
1342
  /**
1343
+ * Reads a text file that may not exist.
1344
+ *
1345
+ * @param filePath - The path of the file to read.
1346
+ *
1347
+ * @returns The content, or `undefined` when there is no file.
1348
+ */
1349
+ async function readOptionalFile(filePath) {
1350
+ try {
1351
+ return await readFile(filePath, "utf-8");
1352
+ } catch (error) {
1353
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
1354
+ throw error;
1355
+ }
1356
+ }
1357
+ /**
1341
1358
  * Touch a file, creating it if it doesn't exist.
1342
1359
  * @param filePath The path of the file to touch
1343
1360
  */
@@ -1347,7 +1364,7 @@ async function touch(filePath) {
1347
1364
  });
1348
1365
  }
1349
1366
 
1350
- // source/commands/generate/schema/main.ts
1367
+ // source/deprecated/commands/generate/schema/main.ts
1351
1368
  /**
1352
1369
  * Generates the business configuration schema and prepares encryption when needed.
1353
1370
  * @param appConfig - Validated app configuration containing the schema.
@@ -1393,220 +1410,72 @@ async function exec$8() {
1393
1410
  }
1394
1411
  }
1395
1412
 
1396
- // ../../packages-private/scripting-utils/source/process/liveness.ts
1397
- /** Whether a process with the pid exists. A process we may not signal still exists. */
1398
- function isProcessAlive(pid) {
1399
- try {
1400
- process.kill(pid, 0);
1401
- return true;
1402
- } catch (error) {
1403
- return error.code === "EPERM";
1404
- }
1405
- }
1406
- /** The environment variable that holds the pid of the process that started a detached process. */
1407
- const OWNER_PID_ENV = "__AIO_COMMERCE_SDK_DETACHED_OWNER_PID";
1408
- /**
1409
- * The environment variable that holds the file descriptor of the liveness pipe of a detached
1410
- * process. It is only set when that descriptor is such a pipe.
1411
- */
1412
- const LIVENESS_FD_ENV = "__AIO_COMMERCE_SDK_DETACHED_LIVENESS_FD";
1413
- /** How often the owner pid is checked. */
1414
- const LIVENESS_CHECK_INTERVAL_MS = 1e3;
1415
- /** Opens the read end of the liveness pipe, or returns `undefined` when there is none. */
1416
- function openLivenessPipe() {
1417
- const fd = Number(process.env[LIVENESS_FD_ENV]);
1418
- if (!Number.isInteger(fd) || fd <= 0) return;
1419
- try {
1420
- const pipe = new net.Socket({
1421
- fd,
1422
- readable: true,
1423
- writable: false
1424
- });
1425
- pipe.on("error", () => pipe.destroy());
1426
- pipe.unref();
1427
- return pipe;
1428
- } catch {
1429
- return;
1430
- }
1431
- }
1413
+ // ../../packages-private/cams-client/source/lib/answer.ts
1414
+ /** The content type of an answer about a problem of CAMS itself. */
1415
+ const PROBLEM_CONTENT_TYPE = "application/problem+json";
1432
1416
  /**
1433
- * Resolves when the process that started this one is gone. Does nothing else until then.
1434
- *
1435
- * It only works in a process that {@link spawnDetached} started, which tells it the pid of the
1436
- * owner and the file descriptor of the liveness pipe through the environment variables
1437
- * {@link OWNER_PID_ENV} and {@link LIVENESS_FD_ENV}. Without the pipe it relies on the pid check
1438
- * alone.
1439
- *
1440
- * @throws A `RangeError` if {@link OWNER_PID_ENV} is not set to a positive integer.
1441
- *
1442
- * Two signals:
1443
- * 1. The pipe closes, which follows the end of the pipe. The kernel closes the owner's end when
1444
- * the owner dies, so this is immediate and an owner that died but was not reaped yet still
1445
- * counts as dead.
1446
- * 2. The owner pid no longer exists, checked on a timer. It covers a missing or failed pipe, and
1447
- * it is the weaker signal, because an owner that died but was not reaped still answers as alive.
1417
+ * The HTTP statuses that can succeed when the same request is sent again, as CAMS counts them when
1418
+ * it calls an app.
1448
1419
  */
1449
- async function waitForOwnerExit() {
1450
- const ownerPid = Number(process.env[OWNER_PID_ENV]);
1451
- if (!Number.isInteger(ownerPid) || ownerPid <= 0) throw new RangeError(`${OWNER_PID_ENV} must be a positive integer, got ${process.env[OWNER_PID_ENV]}`);
1452
- const pipe = openLivenessPipe();
1453
- return await new Promise((resolve) => {
1454
- const finish = (signal) => {
1455
- clearInterval(timer);
1456
- resolve(signal);
1457
- };
1458
- const timer = setInterval(() => {
1459
- if (!isProcessAlive(ownerPid)) finish("pid");
1460
- }, LIVENESS_CHECK_INTERVAL_MS);
1461
- let pipeFailed = false;
1462
- pipe?.resume();
1463
- pipe?.once("error", () => {
1464
- pipeFailed = true;
1465
- });
1466
- pipe?.once("close", () => {
1467
- if (!pipeFailed) finish("pipe");
1468
- });
1469
- });
1470
- }
1471
-
1472
- // ../../packages-private/scripting-utils/source/process/detached.ts
1420
+ const RETRYABLE_STATUSES = [
1421
+ 408,
1422
+ 425,
1423
+ 429,
1424
+ 500,
1425
+ 502,
1426
+ 503,
1427
+ 504
1428
+ ];
1473
1429
  /**
1474
- * The path of a log file in the temp folder, for {@link SpawnDetachedOptions.logPath}.
1475
- *
1476
- * @param name - The name of the log. Characters that a file name should not hold become `_`.
1477
- * @param directory - The folder of the file. Defaults to the temp folder of the system.
1430
+ * The JSON object of an error answer, with the fields that CAMS problems and app errors carry typed
1431
+ * and the rest kept as they came. A field of another type counts as absent.
1478
1432
  */
1479
- function getTempLogPath(name, directory = tmpdir()) {
1480
- const filename = name.replaceAll(/[^\w-]/gu, (character) => "_".repeat(character.length));
1481
- return join(directory, `${filename}.log`);
1482
- }
1483
- /** The file descriptor of the liveness pipe in the process that is started. */
1484
- const LIVENESS_PIPE_FD = 3;
1485
- /** Keeps the parent end of every liveness pipe referenced until its child exits. */
1486
- const livenessPipes = [];
1433
+ const ErrorBodySchema = v.looseObject({
1434
+ code: v.fallback(v.optional(v.string()), void 0),
1435
+ detail: v.fallback(v.optional(v.string()), void 0),
1436
+ message: v.fallback(v.optional(v.string()), void 0),
1437
+ retryable: v.fallback(v.optional(v.boolean()), void 0)
1438
+ });
1439
+ /** The text of an error answer, read as the JSON object of {@link ErrorBodySchema}. */
1440
+ const ErrorBodyTextSchema = v.pipe(v.string(), v.parseJson(), ErrorBodySchema);
1487
1441
  /**
1488
- * Starts a Node.js script as a detached process that outlives this one.
1489
- *
1490
- * The process runs in its own session without a terminal, so Ctrl-C, a closed terminal and a kill
1491
- * of this process do not reach it. Its standard input is closed, and its output goes to a log
1492
- * file. A pipe on file descriptor 3 lets the process see this one die. The process tells it
1493
- * through the environment variables {@link OWNER_PID_ENV}, with the pid of this process, and
1494
- * {@link LIVENESS_FD_ENV}, with the file descriptor of the pipe, which {@link waitForOwnerExit}
1495
- * reads.
1496
- *
1497
- * Failures after the spawn, such as a missing node binary, arrive only through `onError`. A script
1498
- * that does not exist shows up only in the log file.
1442
+ * Reads the error answer of a response with an error status.
1499
1443
  *
1500
- * @returns The process, or `undefined` when it could not start.
1501
- */
1502
- function spawnDetached(options) {
1503
- const { script, args = [], logPath, env, cwd, onError, spawnProcess = spawn } = options;
1504
- let logFd;
1505
- try {
1506
- logFd = openSync(logPath, "a");
1507
- const child = spawnProcess(process.execPath, [script, ...args], {
1508
- cwd,
1509
- detached: true,
1510
- env: {
1511
- ...env ?? process.env,
1512
- [LIVENESS_FD_ENV]: String(LIVENESS_PIPE_FD),
1513
- [OWNER_PID_ENV]: String(process.pid)
1514
- },
1515
- stdio: [
1516
- "ignore",
1517
- logFd,
1518
- logFd,
1519
- "pipe"
1520
- ],
1521
- windowsHide: true
1522
- });
1523
- child.once("error", (error) => onError?.(error));
1524
- const pipe = child.stdio[3];
1525
- if (pipe) {
1526
- pipe.on("error", () => void 0);
1527
- pipe.unref();
1528
- livenessPipes.push(pipe);
1529
- child.once("exit", () => {
1530
- pipe.destroy();
1531
- livenessPipes.splice(livenessPipes.indexOf(pipe), 1);
1532
- });
1533
- }
1534
- child.unref();
1535
- return { child };
1536
- } catch (error) {
1537
- onError?.(error);
1538
- } finally {
1539
- if (logFd !== void 0) closeSync(logFd);
1540
- }
1541
- }
1542
-
1543
- // ../../packages-private/scripting-utils/source/aio/auth.ts
1544
- const { context: context$1, getToken } = aioIms;
1545
- /** Gets an IMS access token for the current CLI IMS context. */
1546
- async function getUserToken() {
1547
- const contextName = await context$1.getCurrent() ?? "cli";
1548
- return getToken(contextName, {});
1549
- }
1550
-
1551
- // ../../packages-private/scripting-utils/source/aio/context.ts
1552
- /**
1553
- * Reads the current App Builder project and Runtime namespace from the local AIO CLI config.
1554
- * @throws If either the project or the runtime namespace is not configured.
1444
+ * @param response - The response, which stays readable: its body is read from a clone.
1555
1445
  */
1556
- function getAioProjectContext() {
1557
- const project = config.get("project");
1558
- const namespace = config.get("runtime.namespace");
1559
- if (!(project && namespace)) throw new Error("The current App Builder project and Runtime namespace are required");
1446
+ async function readErrorAnswer(response) {
1447
+ const text = await response.clone().text().then((body) => body.trim()).catch(() => "");
1448
+ const parsed = v.safeParse(ErrorBodyTextSchema, text);
1449
+ const json = parsed.success ? parsed.output : void 0;
1450
+ const { code, detail, message, retryable } = json ?? {};
1451
+ const isProblem = (response.headers.get("content-type") ?? "").includes(PROBLEM_CONTENT_TYPE);
1452
+ let origin;
1453
+ if (isProblem) origin = "service";
1454
+ else if (code !== void 0 && message !== void 0) origin = "app";
1560
1455
  return {
1561
- namespace,
1562
- project
1456
+ body: json ?? {},
1457
+ code,
1458
+ message: json ? message ?? detail ?? "" : text,
1459
+ origin,
1460
+ retryable: retryable ?? RETRYABLE_STATUSES.includes(response.status),
1461
+ status: response.status
1563
1462
  };
1564
1463
  }
1565
- /** Reads the configured AIO CLI environment, defaulting to `"prod"`. */
1566
- function getAioCliEnv() {
1567
- return config.get("cli.env") === "stage" ? "stage" : "prod";
1568
- }
1569
1464
 
1570
- // source/commands/common/cams/config.ts
1571
- /** Environment variable that overrides the CAMS base URL. */
1572
- const CAMS_URL_ENV_VAR = "AIO_COMMERCE_APP_MANAGEMENT_SERVICE_URL";
1573
- /** Environment variable that selects the AIO CLI environment. */
1574
- const AIO_CLI_ENV_VAR = "AIO_CLI_ENV";
1465
+ // ../../packages-private/cams-client/source/lib/config.ts
1575
1466
  /** The CAMS host for the stage environment. */
1576
1467
  const STAGE_CAMS_URL = "https://app-management-stage.api.commerce.adobe.com";
1577
1468
  /** The CAMS host for the production environment. */
1578
1469
  const PROD_CAMS_URL = "https://app-management.api.commerce.adobe.com";
1579
- /**
1580
- * The time in milliseconds a CAMS request may take before it fails with a timeout.
1581
- *
1582
- * CAMS calls the app on Adobe I/O Runtime for some requests, for example to plan an upgrade, and a
1583
- * cold start after a deploy can take longer than ky's 10 second default.
1584
- */
1470
+ /** The time in milliseconds a CAMS request may take before it fails with a timeout. */
1585
1471
  const CAMS_REQUEST_TIMEOUT_MS = 6e4;
1586
- const URL_SCHEME_PATTERN = /^[hH][tT][tT][pP][sS]?:\/\//u;
1587
- /**
1588
- * Resolves the base URL of the Commerce App Management Service (CAMS).
1589
- *
1590
- * The override variable wins. A value without a scheme is read as an https URL.
1591
- * Otherwise `AIO_CLI_ENV` (`stage` or `prod`) selects the host, falling back to `env`.
1592
- *
1593
- * @param env - The configured AIO CLI environment, used when `AIO_CLI_ENV` is unset or unknown.
1594
- * @param variables - The environment variables to read the override from.
1595
- */
1596
- function resolveCamsBaseUrl(env, variables = process.env) {
1597
- const override = variables[CAMS_URL_ENV_VAR]?.trim();
1598
- if (override) return URL_SCHEME_PATTERN.test(override) ? override : `https://${override}`;
1599
- const cliEnv = variables[AIO_CLI_ENV_VAR]?.trim();
1600
- return (cliEnv === "stage" || cliEnv === "prod" ? cliEnv : env) === "stage" ? STAGE_CAMS_URL : PROD_CAMS_URL;
1601
- }
1602
1472
 
1603
- // source/commands/common/cams/errors.ts
1604
- const HTTP_BAD_GATEWAY = 502;
1605
- const HTTP_SERVICE_UNAVAILABLE = 503;
1473
+ // ../../packages-private/cams-client/source/lib/errors.ts
1606
1474
  /**
1607
1475
  * Error of every failure while talking to the Commerce App Management Service (CAMS): the user
1608
- * token cannot be read, CAMS cannot be reached, it answers with an error status, or its answer
1609
- * does not have the expected shape.
1476
+ * token cannot be read, CAMS cannot be reached or does not answer in time, it answers with an error
1477
+ * that is not one of the documented outcomes of the call, or its answer does not have the expected
1478
+ * shape.
1610
1479
  */
1611
1480
  var CamsClientError = class extends CommerceSdkErrorBase {
1612
1481
  /** Whether repeating the same request later can succeed. */
@@ -1615,410 +1484,1425 @@ var CamsClientError = class extends CommerceSdkErrorBase {
1615
1484
  status;
1616
1485
  /** The machine-readable code of the answer, when it has one. */
1617
1486
  code;
1487
+ /**
1488
+ * Whether CAMS refused the request itself (`service`, an `application/problem+json` answer) or
1489
+ * passed through an error of the app (`app`, an `application/json` answer). `undefined` when the
1490
+ * answer is neither, for example a gateway error.
1491
+ */
1492
+ origin;
1618
1493
  /** The request that CAMS answered with an error, when CAMS answered. */
1619
1494
  request;
1620
1495
  constructor(message, options = {}) {
1621
- const { retryable = false, status, code, request, ...rest } = options;
1496
+ const { retryable = false, status, code, origin, request, ...rest } = options;
1622
1497
  super(message, rest);
1623
1498
  this.retryable = retryable;
1624
1499
  this.status = status;
1625
1500
  this.code = code;
1501
+ this.origin = origin;
1626
1502
  this.request = request;
1627
1503
  }
1628
1504
  };
1629
- /** Thrown when CAMS refuses a request with a 409. Its `code` tells why. */
1630
- var CamsConflictError = class extends CamsClientError {};
1631
- /** The `code` and text of an error answer, plus retryability when provided. */
1632
- async function readAnswer(response) {
1633
- const body = (await response.clone().text().catch(() => "")).trim();
1634
- try {
1635
- const json = JSON.parse(body);
1636
- if (typeof json === "object" && json !== null) {
1637
- const { code, message, detail, retryable } = json;
1638
- const text = [message, detail].find((value) => typeof value === "string");
1639
- return {
1640
- code: typeof code === "string" ? code : void 0,
1641
- retryable: typeof retryable === "boolean" ? retryable : void 0,
1642
- text: typeof text === "string" ? text : ""
1643
- };
1644
- }
1645
- } catch {}
1646
- return {
1647
- code: void 0,
1648
- retryable: void 0,
1649
- text: body
1650
- };
1651
- }
1652
1505
  /**
1653
- * Builds the error for an answer with an error status. The backend retryable flag takes precedence;
1654
- * older responses fall back to treating 502 and 503 as retryable.
1506
+ * Builds the error for an answer with an error status.
1507
+ *
1508
+ * @param error - The error ky threw for the answer.
1509
+ * @param answer - The error answer read from its body.
1655
1510
  */
1656
- async function toCamsResponseError(error) {
1511
+ function toCamsResponseError(error, answer) {
1657
1512
  const { status, statusText } = error.response;
1658
- const { code, retryable: backendRetryable, text } = await readAnswer(error.response);
1659
- const retryable = backendRetryable ?? (status === HTTP_BAD_GATEWAY || status === HTTP_SERVICE_UNAVAILABLE);
1660
- const answer = [status, statusText].filter(Boolean).join(" ");
1661
- const message = text || `The Commerce App Management Service answered with HTTP ${answer}`;
1662
- const options = {
1513
+ const answered = [status, statusText].filter(Boolean).join(" ");
1514
+ const message = answer.message || `The Commerce App Management Service answered with HTTP ${answered}`;
1515
+ return new CamsClientError(message, {
1663
1516
  cause: error,
1664
- code,
1517
+ code: answer.code,
1518
+ origin: answer.origin,
1665
1519
  request: {
1666
1520
  method: error.request.method,
1667
1521
  path: new URL(error.request.url).pathname
1668
1522
  },
1669
- retryable,
1523
+ retryable: answer.retryable,
1670
1524
  status
1671
- };
1672
- if (status === HTTP_CONFLICT) return new CamsConflictError(message, options);
1673
- return new CamsClientError(message, options);
1525
+ });
1674
1526
  }
1675
1527
 
1676
- // source/commands/common/cams/schema.ts
1677
- /** The statuses a lifecycle attempt can have. */
1678
- const ATTEMPT_STATUSES = [
1679
- "pending",
1680
- "in-progress",
1681
- "succeeded",
1682
- "failed"
1683
- ];
1684
- /** An extension of the service, as listed for a workspace. */
1685
- const ExtensionSchema = v.object({
1686
- id: v.string(),
1687
- scope: v.optional(v.object({
1688
- commerceBaseUrl: v.optional(v.nullable(v.string())),
1689
- commerceEnv: v.optional(v.nullable(v.picklist(["paas", "saas"]))),
1690
- commerceId: v.optional(v.string()),
1691
- workspaceId: v.optional(v.string()),
1692
- workspaceName: v.optional(v.string())
1693
- }))
1694
- });
1695
- /** The answer of the service to a lookup by workspace. */
1696
- const ExtensionListSchema = v.array(ExtensionSchema);
1697
- /** The plan the service returns for review. */
1698
- const UpgradePlanAnswerSchema = v.object({ plan: v.looseObject({
1699
- id: v.string(),
1700
- issues: v.array(v.looseObject({ blocking: v.boolean() })),
1701
- operation: v.string(),
1702
- sourceVersion: v.optional(v.nullable(v.string())),
1703
- targetVersion: v.optional(v.nullable(v.string()))
1704
- }) });
1705
- /** The status of a lifecycle attempt, as the app reports it through the service. */
1706
- const AttemptStatusSchema = v.object({
1707
- activations: v.optional(v.object({
1708
- execution: v.optional(v.string()),
1709
- start: v.optional(v.string())
1710
- })),
1711
- error: v.optional(v.object({
1712
- key: v.string(),
1713
- message: v.optional(v.string())
1714
- })),
1715
- id: v.string(),
1716
- result: v.optional(v.nullable(v.object({
1717
- appVersion: v.string(),
1718
- snapshotId: v.string()
1719
- }))),
1720
- status: v.picklist(ATTEMPT_STATUSES)
1721
- });
1722
- /** The parameters to find the extension associated with a workspace. */
1723
- const FindExtensionParamsSchema = v.object({ workspaceId: nonEmptyStringValueSchema("workspaceId") });
1724
- /** The parameters of the calls that act on the upgrades of an extension. */
1725
- const ExtensionParamsSchema = v.object({ extensionId: nonEmptyStringValueSchema("extensionId") });
1726
- /** The parameters to find a specific upgrade attempt. */
1727
- const FindAttemptParamsSchema = v.object({
1728
- ...ExtensionParamsSchema.entries,
1729
- runId: nonEmptyStringValueSchema("runId")
1730
- });
1731
- /** The parameters to start a planned upgrade. */
1732
- const StartUpgradeParamsSchema = v.object({
1733
- ...ExtensionParamsSchema.entries,
1734
- planId: nonEmptyStringValueSchema("planId")
1735
- });
1736
-
1737
- // source/commands/common/cams/endpoints.ts
1738
- /** The path of the upgrades of an extension, relative to the base URL. */
1739
- function upgradesPath(extensionId) {
1740
- return `v1/extensions/${encodeURIComponent(extensionId)}/upgrades`;
1741
- }
1528
+ // ../../packages-private/cams-client/source/lib/response.ts
1742
1529
  /**
1743
- * Reads the JSON body of an answer and checks it against the schema.
1744
- * @throws A {@link CamsClientError} If the body is not JSON or does not match the schema.
1530
+ * Checks a value of an answer against the schema.
1531
+ *
1532
+ * @throws A {@link CamsClientError} If the value does not match the schema.
1745
1533
  */
1746
- async function parseBody(schema, body) {
1747
- const parsed = v.safeParse(schema, body);
1748
- if (!parsed.success) throw new CamsClientError("The Commerce App Management Service sent an unexpected answer", { cause: new v.ValiError(parsed.issues) });
1749
- return parsed.output;
1534
+ function parseBody(schema, body) {
1535
+ try {
1536
+ return parseOrThrow(schema, body);
1537
+ } catch (error) {
1538
+ throw new CamsClientError("The Commerce App Management Service sent an unexpected answer", { cause: error });
1539
+ }
1750
1540
  }
1751
1541
  /**
1752
1542
  * Reads the JSON body of a response and checks it against the schema.
1543
+ *
1753
1544
  * @throws A {@link CamsClientError} If the body is not JSON or does not match the schema.
1754
1545
  */
1755
- async function readAndParseBody(schema, request) {
1756
- const response = await request;
1546
+ async function readBody(schema, response) {
1547
+ let text;
1757
1548
  try {
1758
- return parseBody(schema, await response.json());
1549
+ text = await response.text();
1759
1550
  } catch (error) {
1760
- throw new CamsClientError("The Commerce App Management Service sent an answer that is not JSON", { cause: error });
1551
+ throw new CamsClientError("The answer of the Commerce App Management Service was cut off", {
1552
+ cause: error,
1553
+ retryable: true
1554
+ });
1761
1555
  }
1556
+ let body;
1557
+ try {
1558
+ body = JSON.parse(text);
1559
+ } catch (error) {
1560
+ throw new CamsClientError("The Commerce App Management Service sent an answer that is not JSON", { cause: error });
1561
+ }
1562
+ return parseBody(schema, body);
1762
1563
  }
1763
1564
  /**
1764
- * Finds the extension associated with a workspace.
1565
+ * Waits for the answer of a request and reads it. An error answer that `readError` turns into an
1566
+ * outcome is returned as that outcome.
1765
1567
  *
1766
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1767
- * @param params - The workspace to look the extension up by.
1768
- * @param fetchOptions - The {@link Options} to use to make the request.
1568
+ * @param request - The request sent with the HTTP client.
1569
+ * @param read - Reads an answer with a success status.
1570
+ * @param readError - Reads an error answer as an outcome, or returns `undefined` when it is not
1571
+ * one.
1769
1572
  *
1770
- * @returns The extension, or `null` when the workspace is not associated.
1573
+ * @throws A {@link CamsClientError} If the request got no answer, the answer is an error that is
1574
+ * not an outcome, or the answer does not have the expected shape.
1575
+ */
1576
+ async function send(request, read, readError) {
1577
+ let response;
1578
+ try {
1579
+ response = await request;
1580
+ } catch (error) {
1581
+ if (error instanceof TimeoutError) throw new CamsClientError(`The Commerce App Management Service did not answer within ${CAMS_REQUEST_TIMEOUT_MS / 1e3} seconds`, {
1582
+ cause: error,
1583
+ retryable: true
1584
+ });
1585
+ if (error instanceof TypeError) throw new CamsClientError("The Commerce App Management Service could not be reached", {
1586
+ cause: error,
1587
+ retryable: true
1588
+ });
1589
+ if (!(error instanceof HTTPError)) throw error;
1590
+ const answer = await readErrorAnswer(error.response);
1591
+ const outcome = readError?.(answer);
1592
+ if (outcome !== void 0) return outcome;
1593
+ throw toCamsResponseError(error, answer);
1594
+ }
1595
+ return await read(response);
1596
+ }
1597
+
1598
+ // ../../packages-private/cams-client/source/lib/schema.ts
1599
+ /** The statuses a lifecycle run and each of its steps can have. */
1600
+ const RUN_STATUSES = [
1601
+ "pending",
1602
+ "in-progress",
1603
+ "succeeded",
1604
+ "failed"
1605
+ ];
1606
+ /** The lifecycle operations a plan or a run can carry out. */
1607
+ const LIFECYCLE_OPERATIONS = [
1608
+ "install",
1609
+ "uninstall",
1610
+ "upgrade"
1611
+ ];
1612
+ /** The schema of {@link ExtensionParams}. */
1613
+ const ExtensionParamsSchema = v.object({ extensionId: nonEmptyStringValueSchema("extensionId") });
1614
+ /** The schema of {@link RunParams}. */
1615
+ const RunParamsSchema = v.object({
1616
+ ...ExtensionParamsSchema.entries,
1617
+ runId: nonEmptyStringValueSchema("runId")
1618
+ });
1619
+ /** The schema of {@link StartParams}. */
1620
+ const StartParamsSchema = v.object({
1621
+ ...ExtensionParamsSchema.entries,
1622
+ planId: v.optional(nonEmptyStringValueSchema("planId"))
1623
+ });
1624
+ /** The schema of {@link PlannedStartParams}. */
1625
+ const PlannedStartParamsSchema = v.object({
1626
+ ...ExtensionParamsSchema.entries,
1627
+ planId: nonEmptyStringValueSchema("planId")
1628
+ });
1629
+ /** The severities of the issues that planning or validating a lifecycle operation finds. */
1630
+ const ISSUE_SEVERITIES = [
1631
+ "error",
1632
+ "warning",
1633
+ "info"
1634
+ ];
1635
+ /** The schema of {@link PlanningIssue}. */
1636
+ const PlanningIssueSchema = v.looseObject({
1637
+ blocking: v.boolean(),
1638
+ code: v.string(),
1639
+ domain: v.string(),
1640
+ message: v.string(),
1641
+ path: v.optional(v.array(v.string())),
1642
+ severity: v.optional(v.picklist(ISSUE_SEVERITIES))
1643
+ });
1644
+ /** The schema of {@link Plan}. */
1645
+ const PlanSchema = v.looseObject({
1646
+ id: v.string(),
1647
+ issues: v.array(PlanningIssueSchema),
1648
+ operation: v.picklist(LIFECYCLE_OPERATIONS),
1649
+ sourceVersion: v.nullable(v.string()),
1650
+ targetVersion: v.nullable(v.string())
1651
+ });
1652
+ /** The label of a step and its description. */
1653
+ const StepMetaSchema = v.object({
1654
+ description: v.nullish(v.string()),
1655
+ label: v.string()
1656
+ });
1657
+ /** An issue that the validation of an app found. */
1658
+ const ValidationIssueSchema = v.object({
1659
+ code: v.string(),
1660
+ details: v.optional(v.unknown()),
1661
+ message: v.string(),
1662
+ severity: v.picklist(ISSUE_SEVERITIES)
1663
+ });
1664
+ /** The validation result of one step of an installation and of its children. */
1665
+ const StepResultSchema = v.object({
1666
+ children: v.array(v.lazy(() => StepResultSchema)),
1667
+ issues: v.array(ValidationIssueSchema),
1668
+ meta: StepMetaSchema,
1669
+ name: v.string(),
1670
+ path: v.array(v.string())
1671
+ });
1672
+ /** The schema of {@link Validation}. */
1673
+ const ValidationSchema = v.object({
1674
+ result: StepResultSchema,
1675
+ summary: v.object({
1676
+ errors: v.number(),
1677
+ totalIssues: v.number(),
1678
+ warnings: v.number()
1679
+ }),
1680
+ valid: v.boolean()
1681
+ });
1682
+ /** The schema of {@link PlanPreview}. */
1683
+ const PlanPreviewSchema = v.object({
1684
+ ...ValidationSchema.entries,
1685
+ plan: PlanSchema
1686
+ });
1687
+ /** One step of a lifecycle run and its children. */
1688
+ const RunStepSchema = v.object({
1689
+ children: v.array(v.lazy(() => RunStepSchema)),
1690
+ id: v.string(),
1691
+ meta: StepMetaSchema,
1692
+ name: v.string(),
1693
+ path: v.array(v.string()),
1694
+ status: v.picklist(RUN_STATUSES)
1695
+ });
1696
+ /** The schema of {@link RunStatus}. */
1697
+ const RunStatusSchema = v.object({
1698
+ activations: v.optional(v.object({
1699
+ execution: v.optional(v.string()),
1700
+ start: v.string()
1701
+ })),
1702
+ completedAt: v.nullish(v.string()),
1703
+ data: v.optional(v.unknown()),
1704
+ error: v.nullish(v.object({
1705
+ key: v.string(),
1706
+ message: v.nullish(v.string()),
1707
+ path: v.array(v.string()),
1708
+ payload: v.optional(v.unknown())
1709
+ })),
1710
+ executionDeadline: v.optional(v.string()),
1711
+ id: v.string(),
1712
+ operation: v.optional(v.picklist(LIFECYCLE_OPERATIONS)),
1713
+ plan: v.optional(PlanSchema),
1714
+ planDiff: v.optional(v.unknown()),
1715
+ planId: v.optional(v.string()),
1716
+ previousAttemptId: v.nullish(v.string()),
1717
+ previousPlanId: v.nullish(v.string()),
1718
+ result: v.nullish(v.object({
1719
+ appVersion: v.string(),
1720
+ snapshotId: v.string()
1721
+ })),
1722
+ startedAt: v.string(),
1723
+ status: v.picklist(RUN_STATUSES),
1724
+ step: RunStepSchema,
1725
+ targetConfig: v.optional(v.unknown())
1726
+ });
1727
+
1728
+ // ../../packages-private/cams-client/source/lib/refusals.ts
1729
+ /** The app is already at the version the operation would reach. */
1730
+ const AlreadyCurrentRefusalSchema = v.object({
1731
+ kind: v.literal("already-current"),
1732
+ message: v.string()
1733
+ });
1734
+ /** Another run is open. It carries the open `run` when the app named it, else `null`. */
1735
+ const InProgressRefusalSchema = v.object({
1736
+ kind: v.literal("in-progress"),
1737
+ message: v.string(),
1738
+ run: v.fallback(v.nullable(RunStatusSchema), null)
1739
+ });
1740
+ /** The configuration lacks required values. It carries the `fields` to set. */
1741
+ const MissingRequiredConfigurationRefusalSchema = v.object({
1742
+ fields: v.array(v.string()),
1743
+ kind: v.literal("missing-required-configuration"),
1744
+ message: v.string()
1745
+ });
1746
+ /** The app is not associated with the Commerce instance. */
1747
+ const NotAssociatedRefusalSchema = v.object({
1748
+ kind: v.literal("not-associated"),
1749
+ message: v.string()
1750
+ });
1751
+ /** The app is not installed on the Commerce instance. */
1752
+ const NotInstalledRefusalSchema = v.object({
1753
+ kind: v.literal("not-installed"),
1754
+ message: v.string()
1755
+ });
1756
+ /** Planning found blocking issues. It carries the `issues`. */
1757
+ const PlanBlockedRefusalSchema = v.object({
1758
+ issues: v.array(PlanningIssueSchema),
1759
+ kind: v.literal("plan-blocked"),
1760
+ message: v.string()
1761
+ });
1762
+ /** The plan to start is no longer the pending one. */
1763
+ const StalePlanRefusalSchema = v.object({
1764
+ kind: v.literal("stale-plan"),
1765
+ message: v.string()
1766
+ });
1767
+ /**
1768
+ * Reads an error answer as one of the refusals `refusals` lists: its code becomes the `kind`, and
1769
+ * the answer's message its `message`.
1770
+ *
1771
+ * @param answer - The error answer.
1772
+ * @param refusals - The variant of the refusals that the call documents.
1773
+ *
1774
+ * @returns The refusal, or `undefined` when the answer has none of their codes.
1775
+ * @throws A {@link CamsClientError} If the refusal does not carry what its code needs.
1776
+ */
1777
+ function readRefusal(answer, refusals) {
1778
+ const codes = refusals.options.map((refusal) => refusal.entries.kind.literal);
1779
+ if (answer.code === void 0 || !codes.includes(answer.code)) return;
1780
+ return parseBody(refusals, {
1781
+ ...answer.body,
1782
+ kind: answer.code,
1783
+ message: answer.message,
1784
+ run: answer.body.attempt
1785
+ });
1786
+ }
1787
+
1788
+ // ../../packages-private/cams-client/source/api/extensions/schema.ts
1789
+ /** The statuses an extension can have. */
1790
+ const EXTENSION_STATUSES = [
1791
+ "ASSOCIATED",
1792
+ "INSTALLING",
1793
+ "PARTIALLY_INSTALLED",
1794
+ "INSTALLED",
1795
+ "UNINSTALLING",
1796
+ "UNINSTALLED",
1797
+ "UNASSOCIATED",
1798
+ "UPGRADE_AVAILABLE",
1799
+ "UPGRADE_FAILED",
1800
+ "UPGRADE_SUCCEEDED",
1801
+ "UPGRADING"
1802
+ ];
1803
+ /** The workspace and the Commerce instance an extension is associated with. */
1804
+ const ExtensionScopeSchema = v.object({
1805
+ commerceBaseUrl: v.nullable(v.string()),
1806
+ commerceEnv: v.nullable(CommerceEnvSchema),
1807
+ commerceId: v.string(),
1808
+ workspaceId: v.string(),
1809
+ workspaceName: v.string()
1810
+ });
1811
+ /** One entry of the status history of an extension. */
1812
+ const StatusEntrySchema = v.object({
1813
+ attemptId: v.nullable(v.string()),
1814
+ error: v.nullable(v.object({
1815
+ code: v.nullable(v.string()),
1816
+ message: v.nullable(v.string())
1817
+ })),
1818
+ seq: v.number(),
1819
+ source: v.picklist([
1820
+ "USER",
1821
+ "S2S",
1822
+ "SYSTEM"
1823
+ ]),
1824
+ status: v.picklist(EXTENSION_STATUSES),
1825
+ timestamp: v.string(),
1826
+ upgradeMode: v.nullable(v.picklist(["auto", "manual"])),
1827
+ userDisplayName: v.nullable(v.string()),
1828
+ version: v.nullable(v.string())
1829
+ });
1830
+ /** The metadata of an app, with its display fields typed and the rest kept as the app wrote it. */
1831
+ const AppMetadataSchema = v.looseObject({
1832
+ description: v.optional(v.string()),
1833
+ displayName: v.optional(v.string()),
1834
+ version: v.optional(v.string())
1835
+ });
1836
+ /** The schema of {@link AppConfig}. */
1837
+ const AppConfigSchema = v.looseObject({ metadata: v.optional(AppMetadataSchema) });
1838
+ /** The schema of {@link Extension}. */
1839
+ const ExtensionSchema = v.object({
1840
+ configuration: v.object({
1841
+ appConfig: v.nullable(AppConfigSchema),
1842
+ icon: v.nullable(v.string()),
1843
+ project: v.unknown(),
1844
+ status: v.array(StatusEntrySchema),
1845
+ workspace: v.unknown()
1846
+ }),
1847
+ createdAt: v.nullable(v.string()),
1848
+ currentStatus: v.nullable(v.picklist(EXTENSION_STATUSES)),
1849
+ currentVersion: v.string(),
1850
+ description: v.nullable(v.string()),
1851
+ disabled: v.boolean(),
1852
+ expiresAt: v.nullable(v.string()),
1853
+ extId: v.string(),
1854
+ extName: v.string(),
1855
+ extensionPoints: v.unknown(),
1856
+ id: v.string(),
1857
+ name: v.string(),
1858
+ rowVersion: v.number(),
1859
+ scope: ExtensionScopeSchema,
1860
+ supportEmail: v.nullable(v.string()),
1861
+ title: v.string(),
1862
+ updatedAt: v.nullable(v.string())
1863
+ });
1864
+ /** The extensions on a Commerce instance. */
1865
+ const ExtensionListSchema = v.array(ExtensionSchema);
1866
+ /** The outcomes of a refresh of the scope tree that the scope sync route answers. */
1867
+ const SCOPE_SYNC_ROUTE_OUTCOMES = ["REFRESHED", "STALE"];
1868
+ /** The outcomes of a refresh of the scope tree that an association reports. */
1869
+ const SCOPE_SYNC_OUTCOMES = [
1870
+ ...SCOPE_SYNC_ROUTE_OUTCOMES,
1871
+ "FAILED",
1872
+ "UNKNOWN"
1873
+ ];
1874
+ /** The schema of {@link ScopeSync}. */
1875
+ const ScopeSyncSchema = v.object({
1876
+ outcome: v.picklist(SCOPE_SYNC_ROUTE_OUTCOMES),
1877
+ scopes: v.array(v.unknown())
1878
+ });
1879
+ /** The schema of {@link Unassociation}. */
1880
+ const UnassociationSchema = v.object({
1881
+ appCleanup: v.picklist(["DONE", "NOOP"]),
1882
+ extension: ExtensionSchema
1883
+ });
1884
+ /** The schema of {@link UpdateExtensionParams}. */
1885
+ const UpdateExtensionParamsSchema = v.object({
1886
+ ...ExtensionParamsSchema.entries,
1887
+ appConfig: v.optional(v.record(v.string(), v.unknown())),
1888
+ description: v.optional(v.string()),
1889
+ disabled: v.optional(v.boolean()),
1890
+ extensionPoints: v.optional(v.record(v.string(), v.unknown())),
1891
+ icon: v.optional(v.string()),
1892
+ ifMatch: v.optional(v.string()),
1893
+ supportEmail: v.optional(v.string()),
1894
+ title: v.optional(v.string())
1895
+ });
1896
+ /** The refusals of an update of an extension, by `kind`. */
1897
+ const UpdateRefusalSchema = v.variant("kind", [v.object({
1898
+ kind: v.literal("stale-config"),
1899
+ message: v.string()
1900
+ })]);
1901
+ /** The refusals of an unassociation, by `kind`. */
1902
+ const UnassociationRefusalSchema = v.variant("kind", [InProgressRefusalSchema, v.object({
1903
+ kind: v.literal("uninstall-required"),
1904
+ message: v.string()
1905
+ })]);
1906
+
1907
+ // ../../packages-private/cams-client/source/api/association/schema.ts
1908
+ /** The schema of {@link AssociationParams}. */
1909
+ const AssociationParamsSchema = v.object({
1910
+ projectId: nonEmptyStringValueSchema("projectId"),
1911
+ workspaceId: nonEmptyStringValueSchema("workspaceId")
1912
+ });
1913
+ /** The app that an association would create, flattened from its project, workspace and metadata. */
1914
+ const PreviewAppSchema = v.object({
1915
+ appId: v.string(),
1916
+ description: v.optional(v.string()),
1917
+ displayName: v.optional(v.string()),
1918
+ projectId: v.string(),
1919
+ projectName: v.string(),
1920
+ version: v.optional(v.string()),
1921
+ workspaceId: v.string(),
1922
+ workspaceName: v.string()
1923
+ });
1924
+ /** The fields of every verdict that refuses the association. */
1925
+ const RefusedPreviewSchema = v.object({
1926
+ canAssociate: v.literal(false),
1927
+ message: v.string()
1928
+ });
1929
+ /** The schema of {@link AssociationPreview}. */
1930
+ const AssociationPreviewSchema = v.variant("canAssociate", [v.object({
1931
+ app: PreviewAppSchema,
1932
+ appConfig: v.looseObject({ metadata: AppMetadataSchema }),
1933
+ canAssociate: v.literal(true)
1934
+ }), v.variant("reasonCode", [
1935
+ v.object({
1936
+ ...RefusedPreviewSchema.entries,
1937
+ reasonCode: v.picklist(["app-not-associable", "invalid-app-config"])
1938
+ }),
1939
+ v.object({
1940
+ ...RefusedPreviewSchema.entries,
1941
+ existingAssociationId: v.string(),
1942
+ reasonCode: v.literal("duplicate-association")
1943
+ }),
1944
+ v.object({
1945
+ ...RefusedPreviewSchema.entries,
1946
+ existingAssociationId: v.string(),
1947
+ existingCommerceId: v.string(),
1948
+ reasonCode: v.literal("workspace-already-associated")
1949
+ })
1950
+ ])]);
1951
+ /** The schema of {@link Association}. */
1952
+ const AssociationSchema = v.object({
1953
+ ...ExtensionSchema.entries,
1954
+ scopeSync: v.optional(v.picklist(SCOPE_SYNC_OUTCOMES))
1955
+ });
1956
+ /** The refusals of an association, by `kind`. */
1957
+ const AssociationRefusalSchema = v.variant("kind", [v.object({
1958
+ divergent: v.boolean(),
1959
+ existingId: v.optional(v.string()),
1960
+ kind: v.literal("duplicate-association"),
1961
+ message: v.string()
1962
+ }), v.object({
1963
+ commerceId: v.string(),
1964
+ existingId: v.string(),
1965
+ kind: v.literal("workspace-already-associated"),
1966
+ message: v.string()
1967
+ })]);
1968
+
1969
+ // ../../packages-private/cams-client/source/api/association/endpoints.ts
1970
+ /**
1971
+ * Tells whether a workspace can be associated with the Commerce instance of the HTTP client,
1972
+ * without changing anything.
1973
+ *
1974
+ * @param httpClient - The client the request goes through, with the user's token and organization.
1975
+ * @param params - The project and the workspace to associate.
1976
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1977
+ *
1978
+ * @returns The app that the association would create, or the reason it cannot be created.
1979
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1980
+ * @throws A {@link CamsClientError} If the request fails.
1981
+ */
1982
+ async function previewAssociation(httpClient, params, fetchOptions) {
1983
+ const json = parseOrThrow(AssociationParamsSchema, params);
1984
+ return await send(httpClient.post("v1/extensions/association/preview", {
1985
+ ...fetchOptions,
1986
+ json
1987
+ }), (response) => readBody(AssociationPreviewSchema, response));
1988
+ }
1989
+ /**
1990
+ * Associates a workspace with the Commerce instance of the HTTP client.
1991
+ *
1992
+ * @param httpClient - The client the request goes through, with the user's token and organization.
1993
+ * @param params - The project and the workspace to associate.
1994
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1995
+ *
1996
+ * @returns The created extension and how the refresh of its scope tree ended, or why the workspace
1997
+ * cannot be associated: `duplicate-association` when it already is with this instance, or
1998
+ * `workspace-already-associated` when it is with another one.
1999
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2000
+ * @throws A {@link CamsClientError} If the request fails.
2001
+ */
2002
+ async function createAssociation(httpClient, params, fetchOptions) {
2003
+ const json = parseOrThrow(AssociationParamsSchema, params);
2004
+ return await send(httpClient.post("v1/extensions/association", {
2005
+ ...fetchOptions,
2006
+ json
2007
+ }), async (response) => ({
2008
+ association: await readBody(AssociationSchema, response),
2009
+ kind: "associated"
2010
+ }), (answer) => readRefusal(answer, AssociationRefusalSchema));
2011
+ }
2012
+
2013
+ // ../../packages-private/cams-client/source/api/extensions/endpoints.ts
2014
+ /**
2015
+ * Lists the extensions on the Commerce instance of the HTTP client.
2016
+ *
2017
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2018
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2019
+ *
2020
+ * @throws A {@link CamsClientError} If the request fails.
2021
+ */
2022
+ async function getAllExtensions(httpClient, fetchOptions) {
2023
+ return await send(httpClient.get("v1/extensions", fetchOptions), (response) => readBody(ExtensionListSchema, response));
2024
+ }
2025
+ /**
2026
+ * Gets an extension by its id.
2027
+ *
2028
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2029
+ * @param params - The extension to get.
2030
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2031
+ *
2032
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2033
+ * @throws A {@link CamsClientError} If the request fails.
2034
+ */
2035
+ async function getExtensionById(httpClient, params, fetchOptions) {
2036
+ const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
2037
+ return await send(httpClient.get(`v1/extensions/${encodeURIComponent(extensionId)}`, fetchOptions), (response) => readBody(ExtensionSchema, response));
2038
+ }
2039
+ /**
2040
+ * Updates the given fields of an extension.
2041
+ *
2042
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2043
+ * @param params - The extension, the fields to change and, optionally, the version to change.
2044
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2045
+ *
2046
+ * @returns The updated extension, or `stale-config` when the version to change is not the current
2047
+ * one.
2048
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2049
+ * @throws A {@link CamsClientError} If the request fails.
2050
+ */
2051
+ async function updateExtension(httpClient, params, fetchOptions) {
2052
+ const { extensionId, ifMatch, ...fields } = parseOrThrow(UpdateExtensionParamsSchema, params);
2053
+ const headers = new Headers(fetchOptions?.headers);
2054
+ if (ifMatch !== void 0) headers.set("If-Match", ifMatch);
2055
+ return await send(httpClient.patch(`v1/extensions/${encodeURIComponent(extensionId)}`, {
2056
+ ...fetchOptions,
2057
+ headers,
2058
+ json: fields
2059
+ }), async (response) => ({
2060
+ extension: await readBody(ExtensionSchema, response),
2061
+ kind: "updated"
2062
+ }), (answer) => readRefusal(answer, UpdateRefusalSchema));
2063
+ }
2064
+ /**
2065
+ * Unassociates an extension that is not installed. It never uninstalls the app.
2066
+ *
2067
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2068
+ * @param params - The extension to unassociate.
2069
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2070
+ *
2071
+ * @returns The unassociated extension with the cleanup result, `already-unassociated`, or why it
2072
+ * was not unassociated: `uninstall-required` while the app is installed, or `in-progress` while a
2073
+ * run is open.
2074
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2075
+ * @throws A {@link CamsClientError} If the request fails, for example with `app-cleanup-failed`.
2076
+ */
2077
+ async function deleteExtension(httpClient, params, fetchOptions) {
2078
+ const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
2079
+ return await send(httpClient.delete(`v1/extensions/${encodeURIComponent(extensionId)}`, fetchOptions), async (response) => response.status === HTTP_NO_CONTENT ? { kind: "already-unassociated" } : {
2080
+ kind: "unassociated",
2081
+ unassociation: await readBody(UnassociationSchema, response)
2082
+ }, (answer) => readRefusal(answer, UnassociationRefusalSchema));
2083
+ }
2084
+ /**
2085
+ * Asks the app of an extension to refresh its scope tree from the Commerce instance.
2086
+ *
2087
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2088
+ * @param params - The extension to refresh the scopes of.
2089
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2090
+ *
2091
+ * @returns The outcome of the refresh and the scope tree.
2092
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2093
+ * @throws A {@link CamsClientError} If the request fails.
2094
+ */
2095
+ async function syncExtensionScopes(httpClient, params, fetchOptions) {
2096
+ const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
2097
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/scopes/sync`, fetchOptions), (response) => readBody(ScopeSyncSchema, response));
2098
+ }
2099
+
2100
+ // ../../packages-private/cams-client/source/lib/runs.ts
2101
+ /** How many retryable failures in a row following a run allows before it stops. */
2102
+ const DEFAULT_MAX_CONSECUTIVE_FAILURES = 10;
2103
+ /** The default milliseconds between two syncs of a followed run. */
2104
+ const POLL_INTERVAL_MS = 2e3;
2105
+ /** Waits for the given milliseconds, or rejects with the reason of the signal once it aborts. */
2106
+ async function wait(ms, signal) {
2107
+ await new Promise((resolve, reject) => {
2108
+ signal?.throwIfAborted();
2109
+ const onAbort = () => {
2110
+ clearTimeout(timer);
2111
+ reject(signal?.reason);
2112
+ };
2113
+ const timer = setTimeout(() => {
2114
+ signal?.removeEventListener("abort", onAbort);
2115
+ resolve();
2116
+ }, ms);
2117
+ signal?.addEventListener("abort", onAbort, { once: true });
2118
+ });
2119
+ }
2120
+ /** Whether the run will not change anymore: it succeeded or failed. */
2121
+ function isRunFinished(run) {
2122
+ return run.status === "succeeded" || run.status === "failed";
2123
+ }
2124
+ /**
2125
+ * Reads the run that a 409 `attempt-not-open` carries.
2126
+ *
2127
+ * @param answer - The error answer of a sync.
2128
+ *
2129
+ * @returns The run, or `undefined` for any other answer.
2130
+ * @throws A {@link CamsClientError} If the run does not have the expected shape.
2131
+ */
2132
+ function readRunNotOpen(answer) {
2133
+ return answer.status === HTTP_CONFLICT && answer.code === "attempt-not-open" && answer.body.attempt !== void 0 ? parseBody(RunStatusSchema, answer.body.attempt) : void 0;
2134
+ }
2135
+ /**
2136
+ * Builds the functions that sync, follow and read the runs of a lifecycle operation, with the
2137
+ * endpoint signature `(httpClient, params, options)`.
2138
+ *
2139
+ * @param operation - The path segment of the operation under an extension, such as `upgrades`.
2140
+ */
2141
+ function createRunEndpoints(operation) {
2142
+ function pathOf(params) {
2143
+ const { extensionId, runId } = parseOrThrow(RunParamsSchema, params);
2144
+ return `v1/extensions/${encodeURIComponent(extensionId)}/${operation}/${encodeURIComponent(runId)}`;
2145
+ }
2146
+ async function syncRun(httpClient, params, fetchOptions) {
2147
+ return await send(httpClient.post(`${pathOf(params)}/sync`, {
2148
+ ...fetchOptions,
2149
+ retry: 0
2150
+ }), (response) => readBody(RunStatusSchema, response), readRunNotOpen);
2151
+ }
2152
+ async function* followRun(httpClient, params, options = {}) {
2153
+ const { pollInterval = POLL_INTERVAL_MS, maxConsecutiveFailures = 10, onRetry, ...fetchOptions } = options;
2154
+ const { signal } = fetchOptions;
2155
+ let failures = 0;
2156
+ while (true) {
2157
+ try {
2158
+ const run = await syncRun(httpClient, params, fetchOptions);
2159
+ failures = 0;
2160
+ yield run;
2161
+ if (isRunFinished(run)) return;
2162
+ } catch (error) {
2163
+ signal?.throwIfAborted();
2164
+ failures += 1;
2165
+ if (!(error instanceof CamsClientError && error.retryable) || failures >= maxConsecutiveFailures) throw error;
2166
+ onRetry?.(error, failures);
2167
+ }
2168
+ await wait(pollInterval, signal);
2169
+ }
2170
+ }
2171
+ async function getRun(httpClient, params, fetchOptions) {
2172
+ return await send(httpClient.get(pathOf(params), fetchOptions), (response) => readBody(RunStatusSchema, response));
2173
+ }
2174
+ return {
2175
+ followRun,
2176
+ getRun,
2177
+ syncRun
2178
+ };
2179
+ }
2180
+
2181
+ // ../../packages-private/cams-client/source/api/installation/schema.ts
2182
+ /** The answer to an installation started without a plan, with the run under `installation`. */
2183
+ const InstallationRunSchema = v.object({ installation: RunStatusSchema });
2184
+ /** The answer to a preview: the validation, with the plan of an app that has lifecycle plans. */
2185
+ const InstallationPreviewSchema = v.object({
2186
+ ...ValidationSchema.entries,
2187
+ plan: v.optional(PlanSchema)
2188
+ });
2189
+ /** The schema of {@link NotInstallableRefusal}. */
2190
+ const NotInstallableRefusalSchema = v.object({
2191
+ kind: v.literal("not-installable"),
2192
+ message: v.string()
2193
+ });
2194
+ /** The refusals of an installation preview, by `kind`. */
2195
+ const InstallationPreviewRefusalSchema = v.variant("kind", [
2196
+ AlreadyCurrentRefusalSchema,
2197
+ InProgressRefusalSchema,
2198
+ NotAssociatedRefusalSchema,
2199
+ NotInstallableRefusalSchema,
2200
+ PlanBlockedRefusalSchema
2201
+ ]);
2202
+ /** The refusals of an installation start, by `kind`. */
2203
+ const InstallationStartRefusalSchema = v.variant("kind", [
2204
+ ...InstallationPreviewRefusalSchema.options,
2205
+ MissingRequiredConfigurationRefusalSchema,
2206
+ StalePlanRefusalSchema
2207
+ ]);
2208
+
2209
+ // ../../packages-private/cams-client/source/api/installation/endpoints.ts
2210
+ /**
2211
+ * Asks the app of an extension for an installation plan, without changing anything.
2212
+ *
2213
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2214
+ * @param params - The extension to plan the installation for.
2215
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2216
+ *
2217
+ * @returns The plan with its validation, or why there is none: `validated` with the validation of
2218
+ * an app without lifecycle plans, `no-plan` when the app validates nothing either, or a refusal,
2219
+ * for example `plan-blocked` with the blocking issues or `not-installable` when the app is already
2220
+ * installed.
2221
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2222
+ * @throws A {@link CamsClientError} If the request fails.
2223
+ */
2224
+ async function previewInstallation(httpClient, params, fetchOptions) {
2225
+ const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
2226
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/installation/preview`, fetchOptions), async (response) => {
2227
+ if (response.status === HTTP_NO_CONTENT) return { kind: "no-plan" };
2228
+ const { plan, ...validation } = await readBody(InstallationPreviewSchema, response);
2229
+ return plan === void 0 ? {
2230
+ kind: "validated",
2231
+ validation
2232
+ } : {
2233
+ kind: "planned",
2234
+ preview: {
2235
+ ...validation,
2236
+ plan
2237
+ }
2238
+ };
2239
+ }, (answer) => readRefusal(answer, InstallationPreviewRefusalSchema));
2240
+ }
2241
+ /**
2242
+ * Starts the installation with the plan, or without one for an app without lifecycle plans.
2243
+ *
2244
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2245
+ * @param params - The extension and the plan to start.
2246
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2247
+ *
2248
+ * @returns The new run, `installed` with the extension when a start without a plan had nothing to
2249
+ * run, or why it did not start: for example `stale-plan` when the plan is no longer the pending
2250
+ * one, or `in-progress` with the open run.
2251
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2252
+ * @throws A {@link CamsClientError} If the request fails.
2253
+ */
2254
+ async function startInstallation(httpClient, params, fetchOptions) {
2255
+ const { extensionId, planId } = parseOrThrow(StartParamsSchema, params);
2256
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/installation`, {
2257
+ ...fetchOptions,
2258
+ json: planId === void 0 ? void 0 : { planId }
2259
+ }), async (response) => {
2260
+ if (planId !== void 0) return {
2261
+ kind: "started",
2262
+ run: await readBody(RunStatusSchema, response)
2263
+ };
2264
+ if (response.status === HTTP_OK) return {
2265
+ extension: await readBody(ExtensionSchema, response),
2266
+ kind: "installed"
2267
+ };
2268
+ const { installation } = await readBody(InstallationRunSchema, response);
2269
+ return {
2270
+ kind: "started",
2271
+ run: installation
2272
+ };
2273
+ }, (answer) => readRefusal(answer, InstallationStartRefusalSchema));
2274
+ }
2275
+ /** The run endpoints of the installations. */
2276
+ const installationRuns = createRunEndpoints("installation");
2277
+ /**
2278
+ * Syncs an installation run once: CAMS reads it from the app and records its outcome once it ended.
2279
+ * A run that is no longer the open one comes back as the app reports it, and nothing is recorded.
2280
+ * The request is not retried.
2281
+ *
2282
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2283
+ * @throws A {@link CamsClientError} If the request fails.
2284
+ */
2285
+ const syncInstallationRun = installationRuns.syncRun;
2286
+ /**
2287
+ * Syncs an installation run until it succeeds or fails, and yields its status after each sync. A
2288
+ * retryable failure, such as a timeout or a 503, is synced again after the poll interval, until too
2289
+ * many syncs in a row failed. An aborted signal ends it with the signal's reason.
2290
+ *
2291
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2292
+ * @throws A {@link CamsClientError} If a sync fails with a failure that is not retryable, or too
2293
+ * many syncs in a row failed.
2294
+ */
2295
+ const followInstallationRun = installationRuns.followRun;
2296
+ /**
2297
+ * Reads an installation run without changing anything.
2298
+ *
2299
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2300
+ * @throws A {@link CamsClientError} If the request fails.
2301
+ */
2302
+ const getInstallationRun = installationRuns.getRun;
2303
+
2304
+ // ../../packages-private/cams-client/source/api/uninstallation/schema.ts
2305
+ /** The answer to an uninstallation started without a plan, with the run under `uninstallation`. */
2306
+ const UninstallationRunSchema = v.object({ uninstallation: RunStatusSchema });
2307
+ /** The answer to an uninstallation without a plan that needed no run. */
2308
+ const UninstallationResultSchema = v.object({ extension: ExtensionSchema });
2309
+ /** The refusals of an uninstallation preview, by `kind`. */
2310
+ const UninstallationPreviewRefusalSchema = v.variant("kind", [
2311
+ InProgressRefusalSchema,
2312
+ NotAssociatedRefusalSchema,
2313
+ PlanBlockedRefusalSchema
2314
+ ]);
2315
+ /** The refusals of an uninstallation start, by `kind`. */
2316
+ const UninstallationStartRefusalSchema = v.variant("kind", [
2317
+ ...UninstallationPreviewRefusalSchema.options,
2318
+ NotInstalledRefusalSchema,
2319
+ v.object({
2320
+ kind: v.literal("nothing-to-uninstall"),
2321
+ message: v.string()
2322
+ }),
2323
+ StalePlanRefusalSchema
2324
+ ]);
2325
+
2326
+ // ../../packages-private/cams-client/source/api/uninstallation/endpoints.ts
2327
+ /**
2328
+ * Asks the app of an extension for an uninstallation plan, without changing anything.
2329
+ *
2330
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2331
+ * @param params - The extension to plan the uninstallation for.
2332
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2333
+ *
2334
+ * @returns The plan with its validation, `no-plan` when the uninstallation needs none, or why there
2335
+ * is no plan: for example `plan-blocked` with the blocking issues.
1771
2336
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1772
- * @throws An {@link HTTPError} If the status code is not 2XX.
2337
+ * @throws A {@link CamsClientError} If the request fails.
1773
2338
  */
1774
- async function findExtension(httpClient, params, fetchOptions) {
1775
- const { workspaceId } = parseOrThrow(FindExtensionParamsSchema, params);
1776
- const [extension] = await readAndParseBody(ExtensionListSchema, httpClient.get(`v1/workspaces/${encodeURIComponent(workspaceId)}/extensions`, fetchOptions));
1777
- return extension ?? null;
2339
+ async function previewUninstallation(httpClient, params, fetchOptions) {
2340
+ const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
2341
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/uninstallation/preview`, fetchOptions), async (response) => response.status === HTTP_NO_CONTENT ? { kind: "no-plan" } : {
2342
+ kind: "planned",
2343
+ preview: await readBody(PlanPreviewSchema, response)
2344
+ }, (answer) => readRefusal(answer, UninstallationPreviewRefusalSchema));
1778
2345
  }
1779
2346
  /**
1780
- * Asks CAMS to plan an upgrade of the extension.
2347
+ * Starts the uninstallation with the plan, or without one when the preview returned `no-plan`. It
2348
+ * never unassociates the extension.
2349
+ *
2350
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2351
+ * @param params - The extension and the plan to start.
2352
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2353
+ *
2354
+ * @returns The new run, `uninstalled` with the extension when a start without a plan had nothing to
2355
+ * run, or why it did not start: for example `stale-plan` when the plan is no longer the pending
2356
+ * one, `nothing-to-uninstall` when the app needs a start without a plan, or `in-progress` with the
2357
+ * open run.
2358
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2359
+ * @throws A {@link CamsClientError} If the request fails.
2360
+ */
2361
+ async function startUninstallation(httpClient, params, fetchOptions) {
2362
+ const { extensionId, planId } = parseOrThrow(StartParamsSchema, params);
2363
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/uninstallation`, {
2364
+ ...fetchOptions,
2365
+ json: planId === void 0 ? void 0 : { planId }
2366
+ }), async (response) => {
2367
+ if (planId !== void 0) return {
2368
+ kind: "started",
2369
+ run: await readBody(RunStatusSchema, response)
2370
+ };
2371
+ if (response.status === HTTP_OK) {
2372
+ const { extension } = await readBody(UninstallationResultSchema, response);
2373
+ return {
2374
+ extension,
2375
+ kind: "uninstalled"
2376
+ };
2377
+ }
2378
+ const { uninstallation } = await readBody(UninstallationRunSchema, response);
2379
+ return {
2380
+ kind: "started",
2381
+ run: uninstallation
2382
+ };
2383
+ }, (answer) => readRefusal(answer, UninstallationStartRefusalSchema));
2384
+ }
2385
+ /** The run endpoints of the uninstallations. */
2386
+ const uninstallationRuns = createRunEndpoints("uninstallation");
2387
+ /**
2388
+ * Syncs an uninstallation run once: CAMS reads it from the app and records its outcome once it
2389
+ * ended. A run that is no longer the open one comes back as the app reports it, and nothing is
2390
+ * recorded. The request is not retried.
2391
+ *
2392
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2393
+ * @throws A {@link CamsClientError} If the request fails.
2394
+ */
2395
+ const syncUninstallationRun = uninstallationRuns.syncRun;
2396
+ /**
2397
+ * Syncs an uninstallation run until it succeeds or fails, and yields its status after each sync.
2398
+ * A retryable failure, such as a timeout or a 503, is synced again after the poll interval, until
2399
+ * too many syncs in a row failed. An aborted signal ends it with the signal's reason.
2400
+ *
2401
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2402
+ * @throws A {@link CamsClientError} If a sync fails with a failure that is not retryable, or too
2403
+ * many syncs in a row failed.
2404
+ */
2405
+ const followUninstallationRun = uninstallationRuns.followRun;
2406
+ /**
2407
+ * Reads an uninstallation run without changing anything.
2408
+ *
2409
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2410
+ * @throws A {@link CamsClientError} If the request fails.
2411
+ */
2412
+ const getUninstallationRun = uninstallationRuns.getRun;
2413
+
2414
+ // ../../packages-private/cams-client/source/api/upgrades/schema.ts
2415
+ /** The schema of {@link UpgradeConflictRefusal}. */
2416
+ const UpgradeConflictRefusalSchema = v.object({
2417
+ kind: v.literal("upgrade-conflict"),
2418
+ message: v.string()
2419
+ });
2420
+ /** The refusals of an upgrade preview, by `kind`. */
2421
+ const UpgradePreviewRefusalSchema = v.variant("kind", [
2422
+ AlreadyCurrentRefusalSchema,
2423
+ InProgressRefusalSchema,
2424
+ NotAssociatedRefusalSchema,
2425
+ NotInstalledRefusalSchema,
2426
+ PlanBlockedRefusalSchema,
2427
+ UpgradeConflictRefusalSchema
2428
+ ]);
2429
+ /** The refusals of an upgrade start, by `kind`. */
2430
+ const UpgradeStartRefusalSchema = v.variant("kind", [
2431
+ ...UpgradePreviewRefusalSchema.options,
2432
+ MissingRequiredConfigurationRefusalSchema,
2433
+ StalePlanRefusalSchema
2434
+ ]);
2435
+
2436
+ // ../../packages-private/cams-client/source/api/upgrades/endpoints.ts
2437
+ /**
2438
+ * Asks the app of an extension for an upgrade plan. CAMS records that an upgrade is available.
1781
2439
  *
1782
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
2440
+ * @param httpClient - The client the request goes through, with the user's token and organization.
1783
2441
  * @param params - The extension to plan the upgrade for.
1784
- * @param fetchOptions - The {@link Options} to use to make the request.
2442
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1785
2443
  *
2444
+ * @returns The plan with its validation, or why there is none: for example `already-current` when
2445
+ * the app is up to date, or `upgrade-conflict` while an upgrade runs.
1786
2446
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1787
- * @throws An {@link HTTPError} If the status code is not 2XX.
2447
+ * @throws A {@link CamsClientError} If the request fails.
1788
2448
  */
1789
- async function planUpgrade$1(httpClient, params, fetchOptions) {
2449
+ async function previewUpgrade(httpClient, params, fetchOptions) {
1790
2450
  const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
1791
- const { plan } = await readAndParseBody(UpgradePlanAnswerSchema, httpClient.post(`${upgradesPath(extensionId)}/preview`, fetchOptions));
1792
- return plan;
2451
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/upgrades/preview`, fetchOptions), async (response) => ({
2452
+ kind: "planned",
2453
+ preview: await readBody(PlanPreviewSchema, response)
2454
+ }), (answer) => readRefusal(answer, UpgradePreviewRefusalSchema));
1793
2455
  }
1794
2456
  /**
1795
2457
  * Starts the planned upgrade.
1796
2458
  *
1797
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
2459
+ * @param httpClient - The client the request goes through, with the user's token and organization.
1798
2460
  * @param params - The extension and the plan to start.
1799
- * @param fetchOptions - The {@link Options} to use to make the request.
2461
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1800
2462
  *
1801
- * @returns The status of the new attempt.
2463
+ * @returns The new run, or why it did not start: for example `stale-plan` when the plan is no
2464
+ * longer the pending one, or `in-progress` with the open run.
1802
2465
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1803
- * @throws An {@link HTTPError} If the status code is not 2XX.
2466
+ * @throws A {@link CamsClientError} If the request fails.
1804
2467
  */
1805
2468
  async function startUpgrade$1(httpClient, params, fetchOptions) {
1806
- const { extensionId, planId } = parseOrThrow(StartUpgradeParamsSchema, params);
1807
- return await readAndParseBody(AttemptStatusSchema, httpClient.post(upgradesPath(extensionId), {
2469
+ const { extensionId, planId } = parseOrThrow(PlannedStartParamsSchema, params);
2470
+ return await send(httpClient.post(`v1/extensions/${encodeURIComponent(extensionId)}/upgrades`, {
1808
2471
  ...fetchOptions,
1809
2472
  json: { planId }
1810
- }));
2473
+ }), async (response) => ({
2474
+ kind: "started",
2475
+ run: await readBody(RunStatusSchema, response)
2476
+ }), (answer) => readRefusal(answer, UpgradeStartRefusalSchema));
1811
2477
  }
2478
+ /** The run endpoints of the upgrades. */
2479
+ const upgradeRuns = createRunEndpoints("upgrades");
1812
2480
  /**
1813
- * Reads the status of an attempt once.
2481
+ * Syncs an upgrade run once: CAMS reads it from the app and records its outcome once it ended. A
2482
+ * run that is no longer the open one comes back as the app reports it, and nothing is recorded. The
2483
+ * request is not retried.
1814
2484
  *
1815
- * The request is not retried, because the polling loop is the retry.
2485
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2486
+ * @throws A {@link CamsClientError} If the request fails.
2487
+ */
2488
+ const syncUpgradeRun = upgradeRuns.syncRun;
2489
+ /**
2490
+ * Syncs an upgrade run until it succeeds or fails, and yields its status after each sync. A
2491
+ * retryable failure, such as a timeout or a 503, is synced again after the poll interval, until too
2492
+ * many syncs in a row failed. An aborted signal ends it with the signal's reason.
1816
2493
  *
1817
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1818
- * @param params - The extension and the attempt to read.
1819
- * @param fetchOptions - The {@link Options} to use to make the request.
2494
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2495
+ * @throws A {@link CamsClientError} If a sync fails with a failure that is not retryable, or too
2496
+ * many syncs in a row failed.
2497
+ */
2498
+ const followUpgradeRun = upgradeRuns.followRun;
2499
+ /**
2500
+ * Reads an upgrade run without changing anything.
1820
2501
  *
1821
2502
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1822
- * @throws An {@link HTTPError} If the status code is not 2XX.
2503
+ * @throws A {@link CamsClientError} If the request fails.
1823
2504
  */
1824
- async function pollUpgrade(httpClient, params, fetchOptions) {
1825
- const { extensionId, runId } = parseOrThrow(FindAttemptParamsSchema, params);
1826
- return await readAndParseBody(AttemptStatusSchema, httpClient.post(`${upgradesPath(extensionId)}/${encodeURIComponent(runId)}/sync`, {
1827
- ...fetchOptions,
1828
- retry: 0
1829
- }));
2505
+ const getUpgradeRun = upgradeRuns.getRun;
2506
+ /**
2507
+ * Reads the latest upgrade run without changing anything. Runs of another operation do not count.
2508
+ *
2509
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2510
+ * @param params - The extension to read the latest run of.
2511
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
2512
+ *
2513
+ * @returns The run, or `null` when there is none.
2514
+ * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
2515
+ * @throws A {@link CamsClientError} If the request fails.
2516
+ */
2517
+ async function getLatestUpgradeRun(httpClient, params, fetchOptions) {
2518
+ const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
2519
+ return await send(httpClient.get(`v1/extensions/${encodeURIComponent(extensionId)}/upgrades`, fetchOptions), async (response) => response.status === HTTP_NO_CONTENT ? null : await readBody(RunStatusSchema, response));
1830
2520
  }
2521
+
2522
+ // ../../packages-private/cams-client/source/api/workspaces/schema.ts
2523
+ /** The schema of {@link WorkspaceParams}. */
2524
+ const WorkspaceParamsSchema = v.object({ workspaceId: nonEmptyStringValueSchema("workspaceId") });
2525
+ /** The extensions associated with a workspace, with only their id, status and scope. */
2526
+ const WorkspaceExtensionListSchema = v.array(v.pick(ExtensionSchema, [
2527
+ "currentStatus",
2528
+ "id",
2529
+ "scope"
2530
+ ]));
2531
+
2532
+ // ../../packages-private/cams-client/source/api/workspaces/endpoints.ts
1831
2533
  /**
1832
- * Reads the latest upgrade attempt without changing anything. Attempts that ran another operation
1833
- * do not count.
2534
+ * Gets the extension associated with a workspace. CAMS also lists the workspace's unassociated
2535
+ * extensions for a while, which this skips.
1834
2536
  *
1835
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1836
- * @param params - The extension to read the latest attempt of.
1837
- * @param fetchOptions - The {@link Options} to use to make the request.
2537
+ * @param httpClient - The client the request goes through, with the user's token and organization.
2538
+ * @param params - The workspace to look the extension up by.
2539
+ * @param fetchOptions - The ky options of this request only, such as a `signal`.
1838
2540
  *
1839
- * @returns The attempt, or `null` when there is none.
2541
+ * @returns The extension, or `null` when the workspace is not associated.
1840
2542
  * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1841
- * @throws An {@link HTTPError} If the status code is not 2XX.
2543
+ * @throws A {@link CamsClientError} If the request fails.
2544
+ */
2545
+ async function getWorkspaceExtension(httpClient, params, fetchOptions) {
2546
+ const { workspaceId } = parseOrThrow(WorkspaceParamsSchema, params);
2547
+ return (await send(httpClient.get(`v1/workspaces/${encodeURIComponent(workspaceId)}/extensions`, fetchOptions), (response) => readBody(WorkspaceExtensionListSchema, response))).find((extension) => extension.currentStatus !== "UNASSOCIATED") ?? null;
2548
+ }
2549
+
2550
+ // ../../packages-private/cams-client/source/lib/http-client.ts
2551
+ /**
2552
+ * Builds a before request hook that sets the user token as a bearer token, the IMS organization
2553
+ * id of the project and, when there is one, the Commerce instance.
2554
+ *
2555
+ * @param auth - The user token and the organization.
2556
+ * @param commerceInstance - The Commerce instance the requests act on, if any.
2557
+ *
2558
+ * @throws A {@link CamsClientError} If the token cannot be read.
2559
+ */
2560
+ function buildAuthHook(auth, commerceInstance) {
2561
+ return async (request) => {
2562
+ let token;
2563
+ try {
2564
+ token = await auth.getToken();
2565
+ } catch (error) {
2566
+ throw new CamsClientError(stringifyError(error), { cause: error });
2567
+ }
2568
+ request.headers.set("Authorization", `Bearer ${token}`);
2569
+ request.headers.set("x-org-id", auth.orgId);
2570
+ if (commerceInstance) {
2571
+ request.headers.set("x-ac-url", commerceInstance.baseUrl);
2572
+ request.headers.set("x-ac-env", commerceInstance.env);
2573
+ }
2574
+ };
2575
+ }
2576
+ /**
2577
+ * Tells ky not to retry a failure that is not retryable: a token that cannot be read, or an answer
2578
+ * whose `retryable` flag is `false`. ky retries the other answers when their status is one of
2579
+ * {@link RETRYABLE_STATUSES}.
2580
+ *
2581
+ * @param state - The failure of the last attempt.
1842
2582
  */
1843
- async function readUpgrade(httpClient, params, fetchOptions) {
1844
- const { extensionId, runId } = parseOrThrow(FindAttemptParamsSchema, params);
1845
- return await readAndParseBody(AttemptStatusSchema, httpClient.get(`${upgradesPath(extensionId)}/${encodeURIComponent(runId)}`, fetchOptions));
2583
+ async function shouldRetry({ error }) {
2584
+ if (error instanceof CamsClientError) return error.retryable;
2585
+ if (!(error instanceof HTTPError)) return;
2586
+ const { body } = await readErrorAnswer(error.response);
2587
+ return body.retryable === false ? false : void 0;
1846
2588
  }
1847
2589
  /**
1848
- * Reads the latest upgrade attempt without changing anything. Attempts that ran another operation
1849
- * do not count.
2590
+ * A Ky-based HTTP client used to make requests to CAMS.
2591
+ *
2592
+ * @see https://github.com/sindresorhus/ky
2593
+ */
2594
+ var CamsHttpClient = class {
2595
+ /** ky's `get` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2596
+ get;
2597
+ /** ky's `post` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2598
+ post;
2599
+ /** ky's `delete` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2600
+ delete;
2601
+ /** ky's `patch` with the CAMS URL, auth and retries; an error status throws `HTTPError`. */
2602
+ patch;
2603
+ /**
2604
+ * @param params - The authentication, configuration and fetch options.
2605
+ */
2606
+ constructor(params) {
2607
+ const { auth, config, fetchOptions } = params;
2608
+ const client = ky.create({
2609
+ hooks: { beforeRequest: [buildAuthHook(auth, config?.commerceInstance)] },
2610
+ prefixUrl: config?.baseUrl ?? "https://app-management.api.commerce.adobe.com",
2611
+ retry: {
2612
+ shouldRetry,
2613
+ statusCodes: RETRYABLE_STATUSES
2614
+ },
2615
+ timeout: CAMS_REQUEST_TIMEOUT_MS
2616
+ }).extend(fetchOptions ?? {});
2617
+ this.get = client.get.bind(client);
2618
+ this.post = client.post.bind(client);
2619
+ this.delete = client.delete.bind(client);
2620
+ this.patch = client.patch.bind(client);
2621
+ }
2622
+ };
2623
+
2624
+ // ../../packages-private/cams-client/source/lib/api-client.ts
2625
+ /**
2626
+ * Creates a CAMS API client for the workspace operations, which send no Commerce instance headers.
2627
+ *
2628
+ * @param params - The parameters to build the HTTP client that will communicate with CAMS.
2629
+ */
2630
+ function createCamsWorkspaceApiClient(params) {
2631
+ const httpClient = new CamsHttpClient(params);
2632
+ return { getWorkspaceExtension: getWorkspaceExtension.bind(void 0, httpClient) };
2633
+ }
2634
+ /**
2635
+ * Creates a CAMS API client for the operations on the extensions of a Commerce instance, which send
2636
+ * the Commerce instance headers.
2637
+ *
2638
+ * @param params - The parameters to build the HTTP client that will communicate with CAMS.
2639
+ */
2640
+ function createCamsInstanceApiClient(params) {
2641
+ const httpClient = new CamsHttpClient(params);
2642
+ return {
2643
+ createAssociation: createAssociation.bind(void 0, httpClient),
2644
+ deleteExtension: deleteExtension.bind(void 0, httpClient),
2645
+ followInstallationRun: followInstallationRun.bind(void 0, httpClient),
2646
+ followUninstallationRun: followUninstallationRun.bind(void 0, httpClient),
2647
+ followUpgradeRun: followUpgradeRun.bind(void 0, httpClient),
2648
+ getAllExtensions: getAllExtensions.bind(void 0, httpClient),
2649
+ getExtensionById: getExtensionById.bind(void 0, httpClient),
2650
+ getInstallationRun: getInstallationRun.bind(void 0, httpClient),
2651
+ getLatestUpgradeRun: getLatestUpgradeRun.bind(void 0, httpClient),
2652
+ getUninstallationRun: getUninstallationRun.bind(void 0, httpClient),
2653
+ getUpgradeRun: getUpgradeRun.bind(void 0, httpClient),
2654
+ previewAssociation: previewAssociation.bind(void 0, httpClient),
2655
+ previewInstallation: previewInstallation.bind(void 0, httpClient),
2656
+ previewUninstallation: previewUninstallation.bind(void 0, httpClient),
2657
+ previewUpgrade: previewUpgrade.bind(void 0, httpClient),
2658
+ startInstallation: startInstallation.bind(void 0, httpClient),
2659
+ startUninstallation: startUninstallation.bind(void 0, httpClient),
2660
+ startUpgrade: startUpgrade$1.bind(void 0, httpClient),
2661
+ syncExtensionScopes: syncExtensionScopes.bind(void 0, httpClient),
2662
+ syncInstallationRun: syncInstallationRun.bind(void 0, httpClient),
2663
+ syncUninstallationRun: syncUninstallationRun.bind(void 0, httpClient),
2664
+ syncUpgradeRun: syncUpgradeRun.bind(void 0, httpClient),
2665
+ updateExtension: updateExtension.bind(void 0, httpClient)
2666
+ };
2667
+ }
2668
+
2669
+ // ../../packages-private/scripting-utils/source/process/liveness.ts
2670
+ /** Whether a process with the pid exists. A process we may not signal still exists. */
2671
+ function isProcessAlive(pid) {
2672
+ try {
2673
+ process.kill(pid, 0);
2674
+ return true;
2675
+ } catch (error) {
2676
+ return error.code === "EPERM";
2677
+ }
2678
+ }
2679
+ /** The environment variable that holds the pid of the process that started a detached process. */
2680
+ const OWNER_PID_ENV = "__AIO_COMMERCE_SDK_DETACHED_OWNER_PID";
2681
+ /**
2682
+ * The environment variable that holds the file descriptor of the liveness pipe of a detached
2683
+ * process. It is only set when that descriptor is such a pipe.
2684
+ */
2685
+ const LIVENESS_FD_ENV = "__AIO_COMMERCE_SDK_DETACHED_LIVENESS_FD";
2686
+ /** How often the owner pid is checked. */
2687
+ const LIVENESS_CHECK_INTERVAL_MS = 1e3;
2688
+ /** Opens the read end of the liveness pipe, or returns `undefined` when there is none. */
2689
+ function openLivenessPipe() {
2690
+ const fd = Number(process.env[LIVENESS_FD_ENV]);
2691
+ if (!Number.isInteger(fd) || fd <= 0) return;
2692
+ try {
2693
+ const pipe = new net.Socket({
2694
+ fd,
2695
+ readable: true,
2696
+ writable: false
2697
+ });
2698
+ pipe.on("error", () => pipe.destroy());
2699
+ pipe.unref();
2700
+ return pipe;
2701
+ } catch {
2702
+ return;
2703
+ }
2704
+ }
2705
+ /**
2706
+ * Resolves when the process that started this one is gone. Does nothing else until then.
2707
+ *
2708
+ * It only works in a process that {@link spawnDetached} started, which tells it the pid of the
2709
+ * owner and the file descriptor of the liveness pipe through the environment variables
2710
+ * {@link OWNER_PID_ENV} and {@link LIVENESS_FD_ENV}. Without the pipe it relies on the pid check
2711
+ * alone.
2712
+ *
2713
+ * @throws A `RangeError` if {@link OWNER_PID_ENV} is not set to a positive integer.
2714
+ *
2715
+ * Two signals:
2716
+ * 1. The pipe closes, which follows the end of the pipe. The kernel closes the owner's end when
2717
+ * the owner dies, so this is immediate and an owner that died but was not reaped yet still
2718
+ * counts as dead.
2719
+ * 2. The owner pid no longer exists, checked on a timer. It covers a missing or failed pipe, and
2720
+ * it is the weaker signal, because an owner that died but was not reaped still answers as alive.
2721
+ */
2722
+ async function waitForOwnerExit() {
2723
+ const ownerPid = Number(process.env[OWNER_PID_ENV]);
2724
+ if (!Number.isInteger(ownerPid) || ownerPid <= 0) throw new RangeError(`${OWNER_PID_ENV} must be a positive integer, got ${process.env[OWNER_PID_ENV]}`);
2725
+ const pipe = openLivenessPipe();
2726
+ return await new Promise((resolve) => {
2727
+ const finish = (signal) => {
2728
+ clearInterval(timer);
2729
+ resolve(signal);
2730
+ };
2731
+ const timer = setInterval(() => {
2732
+ if (!isProcessAlive(ownerPid)) finish("pid");
2733
+ }, LIVENESS_CHECK_INTERVAL_MS);
2734
+ let pipeFailed = false;
2735
+ pipe?.resume();
2736
+ pipe?.once("error", () => {
2737
+ pipeFailed = true;
2738
+ });
2739
+ pipe?.once("close", () => {
2740
+ if (!pipeFailed) finish("pipe");
2741
+ });
2742
+ });
2743
+ }
2744
+
2745
+ // ../../packages-private/scripting-utils/source/process/detached.ts
2746
+ /** The mode of a log file: read and write for its owner only. */
2747
+ const LOG_MODE = 384;
2748
+ /**
2749
+ * The path of a log file in the temp folder, for {@link SpawnDetachedOptions.logPath}.
2750
+ *
2751
+ * @param name - The name of the log. Characters that a file name should not hold become `_`.
2752
+ * @param directory - The folder of the file. Defaults to the temp folder of the system.
2753
+ */
2754
+ function getTempLogPath(name, directory = tmpdir()) {
2755
+ const filename = name.replaceAll(/[^\w-]/gu, (character) => "_".repeat(character.length));
2756
+ return join(directory, `${filename}.log`);
2757
+ }
2758
+ /** The file descriptor of the liveness pipe in the process that is started. */
2759
+ const LIVENESS_PIPE_FD = 3;
2760
+ /** Keeps the parent end of every liveness pipe referenced until its child exits. */
2761
+ const livenessPipes = [];
2762
+ /**
2763
+ * Starts a Node.js script as a detached process that outlives this one.
1850
2764
  *
1851
- * @param httpClient - The {@link CamsHttpClient} to use to make the request.
1852
- * @param params - The extension to read the latest attempt of.
1853
- * @param fetchOptions - The {@link Options} to use to make the request.
2765
+ * The process runs in its own session without a terminal, so Ctrl-C, a closed terminal and a kill
2766
+ * of this process do not reach it. Its standard input is closed, and its output goes to a log
2767
+ * file. A pipe on file descriptor 3 lets the process see this one die. The process tells it
2768
+ * through the environment variables {@link OWNER_PID_ENV}, with the pid of this process, and
2769
+ * {@link LIVENESS_FD_ENV}, with the file descriptor of the pipe, which {@link waitForOwnerExit}
2770
+ * reads.
1854
2771
  *
1855
- * @returns The attempt, or `null` when there is none.
1856
- * @throws A {@link CommerceSdkValidationError} If the parameters are in the wrong format.
1857
- * @throws An {@link HTTPError} If the status code is not 2XX.
1858
- */
1859
- async function readLatestUpgrade(httpClient, params, fetchOptions) {
1860
- const { extensionId } = parseOrThrow(ExtensionParamsSchema, params);
1861
- const response = await httpClient.get(upgradesPath(extensionId), fetchOptions);
1862
- if (response.status === 204) return null;
1863
- return await readAndParseBody(AttemptStatusSchema, response);
1864
- }
1865
-
1866
- // source/commands/common/cams/http-client.ts
1867
- /** Header that carries the organization the request is made for. */
1868
- const ORG_HEADER = "x-org-id";
1869
- /** Headers that carry the Commerce instance the request is made for. */
1870
- const COMMERCE_URL_HEADER = "x-ac-url";
1871
- const COMMERCE_ENV_HEADER = "x-ac-env";
1872
- /**
1873
- * Builds a before request hook that sets the user token as a bearer token, the IMS organization
1874
- * id of the project and, when there is one, the Commerce instance.
2772
+ * Failures after the spawn, such as a missing node binary, arrive only through `onError`. A script
2773
+ * that does not exist shows up only in the log file.
1875
2774
  *
1876
- * @throws A {@link CamsClientError} If the token cannot be read.
2775
+ * @returns The process, or `undefined` when it could not start.
1877
2776
  */
1878
- function buildAuthHook(auth, commerceInstance) {
1879
- return async (request) => {
1880
- let token;
1881
- try {
1882
- token = await auth.getToken();
1883
- } catch (error) {
1884
- throw new CamsClientError(stringifyError(error), { cause: error });
1885
- }
1886
- request.headers.set("Authorization", `Bearer ${token}`);
1887
- request.headers.set(ORG_HEADER, auth.org.ims_org_id);
1888
- if (commerceInstance) {
1889
- request.headers.set(COMMERCE_URL_HEADER, commerceInstance.baseUrl);
1890
- request.headers.set(COMMERCE_ENV_HEADER, commerceInstance.env);
2777
+ function spawnDetached(options) {
2778
+ const { script, args = [], logPath, env, cwd, onError, spawnProcess = spawn } = options;
2779
+ let logFd;
2780
+ try {
2781
+ logFd = openSync(logPath, "a", LOG_MODE);
2782
+ fchmodSync(logFd, LOG_MODE);
2783
+ const child = spawnProcess(process.execPath, [script, ...args], {
2784
+ cwd,
2785
+ detached: true,
2786
+ env: {
2787
+ ...env ?? process.env,
2788
+ [LIVENESS_FD_ENV]: String(LIVENESS_PIPE_FD),
2789
+ [OWNER_PID_ENV]: String(process.pid)
2790
+ },
2791
+ stdio: [
2792
+ "ignore",
2793
+ logFd,
2794
+ logFd,
2795
+ "pipe"
2796
+ ],
2797
+ windowsHide: true
2798
+ });
2799
+ child.once("error", (error) => onError?.(error));
2800
+ const pipe = child.stdio[3];
2801
+ if (pipe) {
2802
+ pipe.on("error", () => void 0);
2803
+ pipe.unref();
2804
+ livenessPipes.push(pipe);
2805
+ child.once("exit", () => {
2806
+ pipe.destroy();
2807
+ livenessPipes.splice(livenessPipes.indexOf(pipe), 1);
2808
+ });
1891
2809
  }
1892
- };
2810
+ child.unref();
2811
+ return { child };
2812
+ } catch (error) {
2813
+ onError?.(error);
2814
+ } finally {
2815
+ if (logFd !== void 0) closeSync(logFd);
2816
+ }
1893
2817
  }
1894
- /** Determines if an error is retryable based on the CAMS response. */
1895
- async function isRetryable(error) {
1896
- if (error instanceof CamsClientError) return error.retryable;
1897
- const isObject = (value) => typeof value === "object" && value !== null;
1898
- const isCamsResponseWithRetryable = (value) => isObject(value) && "retryable" in value && typeof value.retryable === "boolean";
1899
- if (error instanceof HTTPError) return error.response.clone().json().then((body) => isCamsResponseWithRetryable(body) ? body.retryable : void 0).catch(() => void 0);
2818
+
2819
+ // ../../packages-private/scripting-utils/source/aio/app-config.ts
2820
+ const APP_CONFIG_FILE = "app.config.yaml";
2821
+ /** Values of the `web` action property that expose the action over HTTP. */
2822
+ const WEB_ACTION_VALUES = /* @__PURE__ */ new Set([
2823
+ true,
2824
+ "yes",
2825
+ "raw"
2826
+ ]);
2827
+ function asNode(value) {
2828
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1900
2829
  }
1901
2830
  /**
1902
- * A Ky-based HTTP client used to make requests to CAMS.
1903
- *
1904
- * It has the shape of the HTTP clients of `@adobe/aio-commerce-lib-api`, which do not export their
1905
- * base class.
1906
- * @see https://github.com/sindresorhus/ky
2831
+ * Lists the actions declared in the `runtimeManifest` of an extension, keyed as `<package>/<action>`.
2832
+ * Loads `app.config.yaml` with the same library the `aio` CLI uses, so `$include` directives and
2833
+ * `function` paths resolve exactly as they do at build time.
2834
+ * @param projectRoot - Resolved project root containing `app.config.yaml`.
2835
+ * @param extensionPointId - The extension point ID, e.g. "commerce/extensibility/1".
1907
2836
  */
1908
- var CamsHttpClient = class {
1909
- /** The actual HTTP client instance. */
1910
- httpClient;
1911
- /** The configuration used by the HTTP client, with its defaults applied. */
1912
- config;
1913
- get;
1914
- post;
1915
- put;
1916
- delete;
1917
- patch;
1918
- head;
1919
- retry;
1920
- stop;
1921
- /**
1922
- * Creates a new CAMS HTTP client instance.
1923
- * @param params - The authentication, configuration and fetch options.
1924
- */
1925
- constructor(params) {
1926
- const { auth, config, fetchOptions } = params;
1927
- this.config = Object.freeze({
1928
- baseUrl: config?.baseUrl ?? "https://app-management.api.commerce.adobe.com",
1929
- commerceInstance: config?.commerceInstance
1930
- });
1931
- const httpClient = ky.create({
1932
- hooks: { beforeRequest: [buildAuthHook(auth, this.config.commerceInstance)] },
1933
- prefixUrl: this.config.baseUrl,
1934
- retry: { async shouldRetry({ error }) {
1935
- return isRetryable(error);
1936
- } },
1937
- timeout: CAMS_REQUEST_TIMEOUT_MS
2837
+ async function listExtensionRuntimeActions(projectRoot, extensionPointId) {
2838
+ const appConfigPath = join(projectRoot, APP_CONFIG_FILE);
2839
+ const { config, includeIndex } = await coalesce(appConfigPath, { absolutePaths: true });
2840
+ const extensionKey = `extensions.${extensionPointId}`;
2841
+ const manifest = asNode(asNode(asNode(config.extensions)[extensionPointId]).runtimeManifest);
2842
+ const actions = /* @__PURE__ */ new Map();
2843
+ for (const [packageName, pkg] of Object.entries(asNode(manifest.packages))) for (const [actionName, rawAction] of Object.entries(asNode(asNode(pkg).actions))) {
2844
+ const action = asNode(rawAction);
2845
+ const actionKey = `${extensionKey}.runtimeManifest.packages.${packageName}.actions.${actionName}`;
2846
+ const fn = typeof action.function === "string" ? action.function : "";
2847
+ actions.set(`${packageName}/${actionName}`, {
2848
+ function: fn || void 0,
2849
+ isWebAction: WEB_ACTION_VALUES.has(action.web),
2850
+ source: includeIndex[actionKey]?.file ?? appConfigPath
1938
2851
  });
1939
- this.httpClient = Object.freeze(fetchOptions ? httpClient.extend(fetchOptions) : httpClient);
1940
- this.get = this.httpClient.get.bind(this.httpClient);
1941
- this.post = this.httpClient.post.bind(this.httpClient);
1942
- this.put = this.httpClient.put.bind(this.httpClient);
1943
- this.delete = this.httpClient.delete.bind(this.httpClient);
1944
- this.patch = this.httpClient.patch.bind(this.httpClient);
1945
- this.head = this.httpClient.head.bind(this.httpClient);
1946
- this.retry = this.httpClient.retry.bind(this.httpClient);
1947
- this.stop = this.httpClient.stop;
1948
2852
  }
1949
- };
1950
-
1951
- // source/commands/common/cams/api-client.ts
1952
- /** Turns a failure of a call into a {@link CamsClientError}. Validation errors pass through. */
1953
- async function toCamsError(error) {
1954
- if (error instanceof CamsClientError || error instanceof CommerceSdkValidationError) return error;
1955
- if (error instanceof HTTPError) return await toCamsResponseError(error);
1956
- if (error instanceof TimeoutError) return new CamsClientError(`The Commerce App Management Service did not answer within ${CAMS_REQUEST_TIMEOUT_MS / 1e3} seconds`, {
1957
- cause: error,
1958
- retryable: true
1959
- });
1960
- return new CamsClientError("The Commerce App Management Service could not be reached", {
1961
- cause: error,
1962
- retryable: true
1963
- });
1964
- }
1965
- /** Binds an endpoint to the HTTP client and reports its failures as {@link CamsClientError}. */
1966
- function bind(httpClient, endpoint) {
1967
- return async (...args) => {
1968
- try {
1969
- return await endpoint(httpClient, ...args);
1970
- } catch (error) {
1971
- throw await toCamsError(error);
1972
- }
1973
- };
1974
- }
1975
- /** Binds a failsafe version of the poll upgrade endpoint that falls back to a normal read upgrade. */
1976
- function bindFailsafePollUpgrade(httpClient) {
1977
- return async (params, options) => {
1978
- try {
1979
- return await pollUpgrade(httpClient, params, options);
1980
- } catch (error) {
1981
- if (error instanceof HTTPError && error.response?.status === 409) {
1982
- const { code } = await readAnswer(error.response);
1983
- if (code === "attempt-not-open") return await bind(httpClient, readUpgrade)(params, {
1984
- ...options,
1985
- retry: 0
1986
- });
1987
- }
1988
- throw await toCamsError(error);
1989
- }
1990
- };
2853
+ return actions;
1991
2854
  }
2855
+ const ActionSchema = v.looseObject({ web: v.optional(v.unknown()) });
2856
+ /** The part of the config that aio's loader returns that holds the runtime actions. */
2857
+ const LoadedAppConfigSchema = v.looseObject({ all: v.record(v.string(), v.looseObject({ manifest: v.optional(v.looseObject({ full: v.optional(v.looseObject({ packages: v.optional(v.record(v.string(), v.looseObject({ actions: v.optional(v.record(v.string(), ActionSchema)) }))) })) })) })) });
2858
+
2859
+ // ../../packages-private/scripting-utils/source/aio/context.ts
1992
2860
  /**
1993
- * Creates a CAMS client for workspace operations without Commerce instance headers.
1994
- * @param params - The parameters to build the HTTP client that will communicate with CAMS.
2861
+ * Reads the current App Builder project and Runtime namespace from the local AIO CLI config.
2862
+ * @throws If either the project or the runtime namespace is not configured.
1995
2863
  */
1996
- function createCamsWorkspaceClient(params) {
1997
- return { findExtension: bind(new CamsHttpClient(params), findExtension) };
2864
+ function getAioProjectContext() {
2865
+ const project = config.get("project");
2866
+ const namespace = config.get("runtime.namespace");
2867
+ if (!(project && namespace)) throw new Error("The current App Builder project and Runtime namespace are required");
2868
+ return {
2869
+ namespace,
2870
+ project
2871
+ };
2872
+ }
2873
+ /** Reads the configured AIO CLI environment, defaulting to `"prod"`. */
2874
+ function getAioCliEnv() {
2875
+ return config.get("cli.env") === "stage" ? "stage" : "prod";
1998
2876
  }
2877
+
2878
+ // source/deprecated/commands/common/cams/config.ts
2879
+ /** Environment variable that overrides the CAMS base URL. */
2880
+ const CAMS_URL_ENV_VAR = "AIO_COMMERCE_APP_MANAGEMENT_SERVICE_URL";
2881
+ /** Environment variable that selects the AIO CLI environment. */
2882
+ const AIO_CLI_ENV_VAR = "AIO_CLI_ENV";
2883
+ const URL_SCHEME_PATTERN = /^[hH][tT][tT][pP][sS]?:\/\//u;
1999
2884
  /**
2000
- * Creates a CAMS client for operations targeting a Commerce instance.
2001
- * @param params - The authentication, configuration and fetch options.
2002
- * @param commerceInstance - The Commerce instance to target.
2885
+ * Resolves the base URL of the Commerce App Management Service (CAMS).
2886
+ *
2887
+ * The override variable wins. A value without a scheme is read as an https URL.
2888
+ * Otherwise `AIO_CLI_ENV` (`stage` or `prod`) selects the host, falling back to `env`.
2889
+ *
2890
+ * @param env - The configured AIO CLI environment, used when `AIO_CLI_ENV` is unset or unknown.
2891
+ * @param variables - The environment variables to read the override from.
2003
2892
  */
2004
- function createCamsInstanceClient(params, commerceInstance) {
2005
- const httpClient = new CamsHttpClient({
2006
- ...params,
2007
- config: {
2008
- ...params.config,
2009
- commerceInstance
2010
- }
2011
- });
2012
- return {
2013
- planUpgrade: bind(httpClient, planUpgrade$1),
2014
- pollUpgrade: bindFailsafePollUpgrade(httpClient),
2015
- readLatestUpgrade: bind(httpClient, readLatestUpgrade),
2016
- readUpgrade: bind(httpClient, readUpgrade),
2017
- startUpgrade: bind(httpClient, startUpgrade$1)
2018
- };
2893
+ function resolveCamsBaseUrl(env, variables = process.env) {
2894
+ const override = variables[CAMS_URL_ENV_VAR]?.trim();
2895
+ if (override) return URL_SCHEME_PATTERN.test(override) ? override : `https://${override}`;
2896
+ const cliEnv = variables[AIO_CLI_ENV_VAR]?.trim();
2897
+ return (cliEnv === "stage" || cliEnv === "prod" ? cliEnv : env) === "stage" ? STAGE_CAMS_URL : PROD_CAMS_URL;
2019
2898
  }
2020
2899
 
2021
- // source/commands/common/cams/context.ts
2900
+ // source/deprecated/commands/common/cams/context.ts
2901
+ /** Gets an IMS access token for the current CLI IMS context. */
2902
+ async function getUserToken() {
2903
+ const contextName = await aioIms.context.getCurrent() ?? "cli";
2904
+ return aioIms.getToken(contextName, {});
2905
+ }
2022
2906
  /**
2023
2907
  * Reads the current App Builder project and supplies lazy CAMS client factories.
2024
2908
  * @param getToken - Reads the user token before every request. Defaults to the AIO CLI token.
@@ -2029,20 +2913,26 @@ function createCamsContext(getToken = getUserToken) {
2029
2913
  const params = {
2030
2914
  auth: {
2031
2915
  getToken,
2032
- org: project.org
2916
+ orgId: project.org.ims_org_id
2033
2917
  },
2034
2918
  config: { baseUrl }
2035
2919
  };
2036
2920
  return {
2037
2921
  baseUrl,
2038
- createInstanceClient: (commerceInstance) => createCamsInstanceClient(params, commerceInstance),
2039
- createWorkspaceClient: () => createCamsWorkspaceClient(params),
2922
+ createInstanceClient: (commerceInstance) => createCamsInstanceApiClient({
2923
+ ...params,
2924
+ config: {
2925
+ ...params.config,
2926
+ commerceInstance
2927
+ }
2928
+ }),
2929
+ createWorkspaceClient: () => createCamsWorkspaceApiClient(params),
2040
2930
  project
2041
2931
  };
2042
2932
  }
2043
2933
  /** Finds the extension associated with the current workspace without changing the context. */
2044
2934
  async function findWorkspaceExtension(context, fetchOptions) {
2045
- return await context.createWorkspaceClient().findExtension({ workspaceId: context.project.workspace.id }, fetchOptions);
2935
+ return await context.createWorkspaceClient().getWorkspaceExtension({ workspaceId: context.project.workspace.id }, fetchOptions);
2046
2936
  }
2047
2937
  /**
2048
2938
  * Reads the Commerce instance from an extension's explicit scope fields.
@@ -2058,7 +2948,7 @@ function requireCommerceInstance(extension) {
2058
2948
  };
2059
2949
  }
2060
2950
 
2061
- // source/commands/common/cams/report.ts
2951
+ // source/deprecated/commands/common/cams/report.ts
2062
2952
  /** How many causes {@link findCamsError} follows. */
2063
2953
  const MAX_CAUSE_DEPTH = 5;
2064
2954
  /** Finds the failure of the service that caused an error: the error itself or one of its causes. */
@@ -2083,6 +2973,13 @@ function describeCamsFailure(error) {
2083
2973
  ].filter(Boolean);
2084
2974
  return facts.length > 0 ? `Details: ${facts.join(", ")}` : void 0;
2085
2975
  }
2976
+ const PROJECT_ACCESS_HINT = "Hint: the credential cannot access the project. Add the I/O Management API to the workspace credential.";
2977
+ 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.";
2978
+ /** The hint for the access failures that a credential without the right access causes. */
2979
+ function hintFor(error) {
2980
+ if (error.code === "project-access-denied") return PROJECT_ACCESS_HINT;
2981
+ if (error.code === "commerce-access-denied") return COMMERCE_ACCESS_HINT;
2982
+ }
2086
2983
  /**
2087
2984
  * Prints a failure. A failure of the service is one block, the message and one line of details
2088
2985
  * without a stack, and the whole chain of causes goes to the debug log, which `DEBUG=1` shows.
@@ -2102,11 +2999,16 @@ function reportFailure(error, message) {
2102
2999
  }
2103
3000
  const details = describeCamsFailure(cams);
2104
3001
  const headline = message ?? (error instanceof Error ? error.message : String(error));
2105
- consola.error(details ? `${headline}\n${details}` : headline);
3002
+ const hint = hintFor(cams);
3003
+ consola.error([
3004
+ headline,
3005
+ details,
3006
+ hint
3007
+ ].filter(Boolean).join("\n"));
2106
3008
  consola.debug(error);
2107
3009
  }
2108
3010
 
2109
- // source/commands/hooks/post-app-deploy/interrupt.ts
3011
+ // source/deprecated/commands/hooks/post-app-deploy/interrupt.ts
2110
3012
  /** The exit code of a process that stopped because of Ctrl+C. */
2111
3013
  const SIGINT_EXIT_CODE = 130;
2112
3014
  /**
@@ -2149,60 +3051,47 @@ function noticeInterrupt(statusCommand) {
2149
3051
  };
2150
3052
  }
2151
3053
 
2152
- // source/commands/upgrade/poll.ts
2153
- /** How long to wait between two polls. */
2154
- const POLL_INTERVAL_MS = 2e3;
3054
+ // source/deprecated/commands/upgrade/poll.ts
2155
3055
  /**
2156
- * How many transient failures in a row end the loop.
3056
+ * Syncs an upgrade run until it is settled. Retryable failures are retried up to
3057
+ * {@link DEFAULT_MAX_CONSECUTIVE_FAILURES} times in a row; any other failure ends the loop.
2157
3058
  *
2158
- * The service marks an overdue attempt as failed, so a healthy service always ends the loop. This
2159
- * limit is for the other case: without it, a service that stays down means polling forever.
2160
- */
2161
- const MAX_CONSECUTIVE_FAILURES = 10;
2162
- /** Whether the attempt will not change anymore. */
2163
- function isSettled(status) {
2164
- return status.status === "succeeded" || status.status === "failed";
2165
- }
2166
- /**
2167
- * Polls an attempt every {@link POLL_INTERVAL_MS} until it is settled.
3059
+ * @param client - The CAMS client of the Commerce instance.
3060
+ * @param run - The extension and the run to follow.
3061
+ * @param handlers - What to call with each answer and each retry.
2168
3062
  *
2169
- * The loop keeps going through the failures that can pass, which are network failures and a 502 or
2170
- * 503 from the service, and gives up after {@link MAX_CONSECUTIVE_FAILURES} of them in a row. Any
2171
- * answer resets the count. Any other failure ends the loop at once, because repeating the request
2172
- * cannot fix it, as with a refused token.
3063
+ * @returns How following ended: `finished` with the final status, `unreachable` after too many
3064
+ * retryable failures in a row, or `failed` with any other failure.
2173
3065
  */
2174
- async function pollUntilSettled(options) {
2175
- const { poll, onStatus, onRetry, sleep: wait = setTimeout$1 } = options;
2176
- let failures = 0;
2177
- while (true) {
2178
- try {
2179
- const status = await poll();
2180
- failures = 0;
3066
+ async function followUntilSettled(client, run, handlers = {}) {
3067
+ const { onStatus, onRetry } = handlers;
3068
+ try {
3069
+ for await (const status of client.followUpgradeRun(run, { onRetry })) {
2181
3070
  onStatus?.(status);
2182
- if (isSettled(status)) return {
3071
+ if (isRunFinished(status)) return {
2183
3072
  kind: "finished",
2184
3073
  status
2185
3074
  };
2186
- } catch (error) {
2187
- if (!(error instanceof CamsClientError && error.retryable)) return {
2188
- error,
2189
- kind: "failed"
2190
- };
2191
- failures += 1;
2192
- if (failures >= 10) return {
2193
- error,
2194
- kind: "unreachable"
2195
- };
2196
- onRetry?.(error);
2197
3075
  }
2198
- await wait(POLL_INTERVAL_MS);
3076
+ } catch (error) {
3077
+ return error instanceof CamsClientError && error.retryable ? {
3078
+ error,
3079
+ kind: "unreachable"
3080
+ } : {
3081
+ error,
3082
+ kind: "failed"
3083
+ };
2199
3084
  }
3085
+ throw new Error(`The upgrade run ${run.runId} ended without a final status.`);
2200
3086
  }
2201
- /** Wraps a callback so that it runs once per change of an unsettled status, such as `pending` to `in-progress`. */
3087
+ /**
3088
+ * Wraps a callback so that it runs once per change of an unsettled status, such as `pending` to
3089
+ * `in-progress`.
3090
+ */
2202
3091
  function whenStatusChanges(report) {
2203
3092
  let previous;
2204
3093
  return (status) => {
2205
- if (!isSettled(status) && status.status !== previous) {
3094
+ if (!isRunFinished(status) && status.status !== previous) {
2206
3095
  previous = status.status;
2207
3096
  report(status);
2208
3097
  }
@@ -2241,42 +3130,50 @@ function describeOutcome(result, runId) {
2241
3130
  };
2242
3131
  }
2243
3132
 
2244
- // source/commands/hooks/post-app-deploy/main.ts
3133
+ // source/deprecated/commands/hooks/post-app-deploy/main.ts
2245
3134
  const SKIP_MESSAGES = {
2246
3135
  "already-current": "The app is already up to date.",
2247
3136
  "in-progress": "An upgrade is already in progress.",
2248
3137
  "not-associated": "The app is not associated with a Commerce instance. Nothing to upgrade.",
2249
- "not-installed": "The app is not installed on the Commerce instance. Nothing to upgrade."
3138
+ "not-installed": "The app is not installed on the Commerce instance. Nothing to upgrade.",
3139
+ "upgrade-conflict": "Another upgrade of this app is in progress or an automatic upgrade is pending. Try again in a few minutes."
2250
3140
  };
2251
- function isSkipCode(code) {
2252
- return code === "already-current" || code === "not-associated" || code === "not-installed" || code === "in-progress";
2253
- }
2254
3141
  /**
2255
3142
  * Asks the service to plan the upgrade.
2256
3143
  * @returns The plan, or the code of the reason the upgrade does not apply.
2257
3144
  */
2258
3145
  async function planUpgrade(client, extensionId) {
3146
+ let preview;
2259
3147
  try {
2260
- return await client.planUpgrade({ extensionId });
3148
+ preview = await client.previewUpgrade({ extensionId });
2261
3149
  } catch (error) {
2262
- if (error instanceof CamsConflictError) {
2263
- if (isSkipCode(error.code)) return error.code;
2264
- throw new Error(`The upgrade was not planned: ${error.message}`, { cause: error });
2265
- }
3150
+ if (error instanceof CamsClientError && error.status === HTTP_CONFLICT) throw new Error(`The upgrade was not planned: ${error.message}`, { cause: error });
2266
3151
  throw error;
2267
3152
  }
3153
+ switch (preview.kind) {
3154
+ case "planned": return preview.preview.plan;
3155
+ case "already-current":
3156
+ case "in-progress":
3157
+ case "not-associated":
3158
+ case "not-installed":
3159
+ case "upgrade-conflict": return preview.kind;
3160
+ default: throw new Error(`The upgrade was not planned: ${preview.message}`);
3161
+ }
2268
3162
  }
2269
- /** Starts the planned upgrade and returns the status of the new run. */
3163
+ /** Starts the planned upgrade and returns the new run. */
2270
3164
  async function startUpgrade(client, extensionId, plan) {
3165
+ let started;
2271
3166
  try {
2272
- return await client.startUpgrade({
3167
+ started = await client.startUpgrade({
2273
3168
  extensionId,
2274
3169
  planId: plan.id
2275
3170
  });
2276
3171
  } catch (error) {
2277
- if (error instanceof CamsConflictError) throw new Error(`The upgrade was not started: ${error.message}`, { cause: error });
3172
+ if (error instanceof CamsClientError && error.status === HTTP_CONFLICT) throw new Error(`The upgrade was not started: ${error.message}`, { cause: error });
2278
3173
  throw error;
2279
3174
  }
3175
+ if (started.kind !== "started") throw new Error(`The upgrade was not started: ${started.message}`);
3176
+ return started.run;
2280
3177
  }
2281
3178
  /**
2282
3179
  * Starts the watcher that follows the run if this process stops. The run goes on without the
@@ -2313,16 +3210,15 @@ function startBackgroundWatcher(extensionId, started) {
2313
3210
  }
2314
3211
  /** Polls the run and prints its progress until it settles. Throws when it does not succeed. */
2315
3212
  async function followRun(client, extensionId, started) {
2316
- const result = await pollUntilSettled({
3213
+ const result = await followUntilSettled(client, {
3214
+ extensionId,
3215
+ runId: started.id
3216
+ }, {
2317
3217
  onRetry: (error) => {
2318
3218
  consola.warn(`${error.message}. Trying again.`);
2319
3219
  },
2320
3220
  onStatus: whenStatusChanges((status) => {
2321
3221
  consola.start(`App upgrade is ${colors.yellow(status.status)}.`);
2322
- }),
2323
- poll: () => client.pollUpgrade({
2324
- extensionId,
2325
- runId: started.id
2326
3222
  })
2327
3223
  });
2328
3224
  const outcome = describeOutcome(result, started.id);
@@ -2419,7 +3315,7 @@ async function exec$7() {
2419
3315
  }
2420
3316
  }
2421
3317
 
2422
- // source/commands/common/extension-points.ts
3318
+ // source/deprecated/commands/common/extension-points.ts
2423
3319
  /** Extension points in the order they must appear in app.config.yaml. Extensibility must be last. */
2424
3320
  const EXTENSION_POINT_ORDER = [
2425
3321
  BACKEND_UI_V2_EXTENSION_POINT_ID,
@@ -2454,28 +3350,76 @@ function isSorted(extensions) {
2454
3350
  * @returns True if the file was rewritten.
2455
3351
  */
2456
3352
  async function ensureExtensionPointsOrder(projectRoot) {
2457
- const path = join(projectRoot, APP_CONFIG_FILE);
3353
+ const path = join(projectRoot, APP_CONFIG_FILE$1);
2458
3354
  if (!existsSync(path)) return false;
2459
3355
  const doc = await readYamlFile(path);
2460
3356
  const extensions = getExtensionsMap(doc.contents);
2461
3357
  if (extensions === void 0 || isSorted(extensions)) return false;
2462
3358
  const pairs = extensions.items;
2463
3359
  const [first, second] = pairs;
2464
- if (extensions.commentBefore && isNode(first.key)) {
3360
+ if (extensions.commentBefore && isNode$1(first.key)) {
2465
3361
  first.key.commentBefore = extensions.commentBefore;
2466
3362
  extensions.commentBefore = void 0;
2467
3363
  }
2468
3364
  pairs.sort((a, b) => getPairRank(a) - getPairRank(b));
2469
- const spaced = isNode(second?.key) && Boolean(second.key.spaceBefore);
2470
- if (isNode(first.key) && pairs[0] !== first) first.key.spaceBefore = spaced;
2471
- if (isNode(pairs[0].key)) pairs[0].key.spaceBefore = false;
3365
+ const spaced = isNode$1(second?.key) && Boolean(second.key.spaceBefore);
3366
+ if (isNode$1(first.key) && pairs[0] !== first) first.key.spaceBefore = spaced;
3367
+ if (isNode$1(pairs[0].key)) pairs[0].key.spaceBefore = false;
2472
3368
  await writeFile(path, doc.toString(), "utf-8");
2473
3369
  return true;
2474
3370
  }
2475
3371
 
2476
- // source/commands/hooks/postinstall.ts
3372
+ // source/deprecated/commands/hooks/postinstall.ts
3373
+ /** What the hook commands that `aio commerce app sync` writes contain. */
3374
+ const PLUGIN_HOOK_COMMAND = "aio commerce app hooks";
3375
+ const POSTINSTALL_COMMAND = "aio-commerce-lib-app hooks postinstall";
3376
+ const COMMAND_SEPARATOR_PATTERN = /\s*&&\s*/u;
3377
+ const SHELL_OPERATOR_PATTERN = /[;|&]/u;
3378
+ /** The hooks of an `ext.config.yaml`. An empty file, key or hook has none. */
3379
+ const ExtConfigHooksSchema = v.nullish(v.object({ hooks: v.nullish(v.record(v.string(), v.nullish(v.string()))) }));
3380
+ /**
3381
+ * Whether the `aio commerce app` plugin manages the project, which it shows by writing its own hook
3382
+ * commands into an `ext.config.yaml`.
3383
+ *
3384
+ * @param projectRoot - Resolved project root.
3385
+ */
3386
+ async function isManagedByPlugin(projectRoot) {
3387
+ return (await Promise.all([
3388
+ BACKEND_UI_V2_EXTENSION_POINT_ID,
3389
+ CONFIGURATION_EXTENSION_POINT_ID,
3390
+ EXTENSIBILITY_EXTENSION_POINT_ID
3391
+ ].map(async (id) => {
3392
+ const path = join(projectRoot, getExtConfigPath(id));
3393
+ const contents = await readOptionalFile(path);
3394
+ return contents === void 0 ? void 0 : parseOrThrow(ExtConfigHooksSchema, parse$1(contents), `Invalid hooks in ${path}`);
3395
+ }))).some((extConfig) => Object.values(extConfig?.hooks ?? {}).some((command) => command?.includes(PLUGIN_HOOK_COMMAND)));
3396
+ }
3397
+ /**
3398
+ * Removes this hook's command from the `postinstall` script, and the script when nothing else is
3399
+ * left in it.
3400
+ *
3401
+ * @param projectRoot - Resolved project root containing package.json.
3402
+ *
3403
+ * @returns `false` when the command shares a segment of the `&&` chain with other shell commands,
3404
+ * which stay untouched, and `true` otherwise, also when there is no package.json.
3405
+ */
3406
+ async function removePostinstallScript(projectRoot) {
3407
+ const pkg = await loadPackageJson(projectRoot);
3408
+ if (pkg === null) return true;
3409
+ const commands = (pkg.content.scripts?.postinstall ?? "").split(COMMAND_SEPARATOR_PATTERN);
3410
+ if (commands.some((command) => command.includes(POSTINSTALL_COMMAND) && SHELL_OPERATOR_PATTERN.test(command))) return false;
3411
+ const remaining = commands.filter((command) => !command.includes(POSTINSTALL_COMMAND)).join(COMMAND_SEPARATOR);
3412
+ const scripts = Object.fromEntries(Object.entries({
3413
+ ...pkg.content.scripts,
3414
+ postinstall: remaining
3415
+ }).filter(([name]) => name !== "postinstall" || remaining !== ""));
3416
+ pkg.update({ scripts });
3417
+ await pkg.save();
3418
+ return true;
3419
+ }
2477
3420
  /**
2478
3421
  * Regenerates project artifacts after dependencies are installed.
3422
+ *
2479
3423
  * @param appManifest - Validated app configuration used for generation.
2480
3424
  * @param projectRoot - Resolved project root where artifacts are generated.
2481
3425
  * @param templatesDir - Optional directory containing generation templates.
@@ -2486,11 +3430,19 @@ async function run$5(appManifest, projectRoot, templatesDir) {
2486
3430
  await run$7(appManifest, projectRoot);
2487
3431
  await ensureExtensionPointsOrder(projectRoot);
2488
3432
  }
2489
- /** Runs the postinstall hook */
3433
+ /**
3434
+ * Regenerates the project artifacts, or, once the `aio commerce app` plugin manages the project,
3435
+ * removes the hook from `package.json`.
3436
+ */
2490
3437
  async function exec$6() {
2491
3438
  consola$1.debug("Running lib-app postinstall hook");
2492
3439
  try {
2493
3440
  const projectRoot = await getProjectRootDirectory();
3441
+ if (await isManagedByPlugin(projectRoot)) {
3442
+ if (await removePostinstallScript(projectRoot)) consola$1.info("The aio commerce app plugin manages this project, so the postinstall hook removed itself from package.json.");
3443
+ else consola$1.warn(`The aio commerce app plugin manages this project. Remove "${POSTINSTALL_COMMAND}" from the postinstall script in package.json.`);
3444
+ return;
3445
+ }
2494
3446
  await run$5(await loadAppManifest(projectRoot), projectRoot);
2495
3447
  } catch (error) {
2496
3448
  if (error instanceof CommerceSdkValidationError) consola$1.error(error.display());
@@ -2504,37 +3456,63 @@ async function exec$6() {
2504
3456
  * This module exports shared environment utilities for the AIO Commerce SDK.
2505
3457
  * @packageDocumentation
2506
3458
  */
2507
- const { context } = aioIms;
2508
- const IMS_KEYS = {
2509
- client_id: "AIO_COMMERCE_AUTH_IMS_CLIENT_ID",
2510
- client_secrets: "AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS",
2511
- ims_org_id: "AIO_COMMERCE_AUTH_IMS_ORG_ID",
2512
- scopes: "AIO_COMMERCE_AUTH_IMS_SCOPES",
2513
- technical_account_email: "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL",
2514
- technical_account_id: "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID"
2515
- };
3459
+ const UNQUOTED_VALUE = /^[^\s#"'`]*$/u;
3460
+ /** The credentials of the workspace in aio's config, as `aio app use` wrote them. */
3461
+ const WorkspaceCredentialsSchema = v.nullish(v.array(v.object({
3462
+ integration_type: v.nullish(v.string()),
3463
+ name: v.nullish(v.string())
3464
+ })), []);
3465
+ /** A field of an IMS context: a text, or a list that the `.env` file holds comma-separated. */
3466
+ const ImsContextFieldSchema = v.optional(v.pipe(v.union([v.string(), v.array(v.string())]), v.transform((value) => Array.isArray(value) ? value.join(",") : value)));
3467
+ /** The fields of an OAuth Server-to-Server IMS context that the legacy variables hold. */
3468
+ const ImsContextSchema = v.nullish(v.object({ data: v.nullish(v.object({
3469
+ client_id: ImsContextFieldSchema,
3470
+ client_secrets: ImsContextFieldSchema,
3471
+ ims_org_id: ImsContextFieldSchema,
3472
+ scopes: ImsContextFieldSchema,
3473
+ technical_account_email: ImsContextFieldSchema,
3474
+ technical_account_id: ImsContextFieldSchema
3475
+ })) }));
3476
+ /**
3477
+ * Reads the variables of a `.env` file.
3478
+ *
3479
+ * @param envPath - The path of the `.env` file.
3480
+ *
3481
+ * @returns The variables, or `undefined` when there is no file.
3482
+ */
3483
+ async function readEnvFile(envPath) {
3484
+ const contents = await readOptionalFile(envPath);
3485
+ return contents === void 0 ? void 0 : parseEnv(contents);
3486
+ }
2516
3487
  /**
2517
- * Replaces or creates an environment variable in a .env file
2518
- * @param filePath - The path to the .env file
2519
- * @param key - The environment variable key to replace or create
2520
- * @param value - The new value for the environment variable
2521
- */
2522
- function replaceEnvVar(filePath, key, value) {
2523
- const envPath = path.resolve(filePath);
2524
- const envLines = readFileSync(envPath, "utf8").split("\n");
2525
- const formattedValue = value.includes(" ") ? `"${value}"` : value;
2526
- let keyExists = false;
2527
- const updatedLines = envLines.map((line) => {
2528
- if (line.trim().startsWith("#") || !line.includes("=")) return line;
2529
- const [currentKey] = line.split("=");
2530
- if (currentKey === key) {
2531
- keyExists = true;
2532
- return `${key}=${formattedValue}`;
3488
+ * Quotes a value so a `.env` file reads it back as written: as is when it needs no quotes, else in
3489
+ * single quotes, else in double quotes when it holds a single quote.
3490
+ */
3491
+ function envValue(value) {
3492
+ if (UNQUOTED_VALUE.test(value)) return value;
3493
+ return value.includes("'") ? JSON.stringify(value) : `'${value}'`;
3494
+ }
3495
+ /**
3496
+ * Writes variables to a `.env` file, each in place of every line that sets it or at the end, and
3497
+ * creates the file when it doesn't exist. The file is read and written once.
3498
+ *
3499
+ * @param envPath - The path of the `.env` file.
3500
+ * @param values - The value of each variable, by name.
3501
+ */
3502
+ async function writeEnvValues(envPath, values) {
3503
+ const entries = Object.entries(values);
3504
+ if (entries.length === 0) return;
3505
+ let contents = await readOptionalFile(envPath) ?? "";
3506
+ for (const [name, value] of entries) {
3507
+ const line = `${name}=${envValue(value)}`;
3508
+ const lines = contents.split("\n");
3509
+ if (lines.some((existing) => existing.startsWith(`${name}=`))) contents = lines.map((existing) => existing.startsWith(`${name}=`) ? `${line}${existing.endsWith("\r") ? "\r" : ""}` : existing).join("\n");
3510
+ else {
3511
+ const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
3512
+ contents = `${contents}${separator}${line}\n`;
2533
3513
  }
2534
- return line;
2535
- });
2536
- if (!keyExists) updatedLines.push(`${key}=${formattedValue}`);
2537
- writeFileSync(envPath, updatedLines.join("\n"), "utf8");
3514
+ }
3515
+ await writeFile(envPath, contents);
2538
3516
  }
2539
3517
  /**
2540
3518
  * Sets the `NODE_ENV` environment variable in the app `.env` file, so the web
@@ -2542,44 +3520,120 @@ function replaceEnvVar(filePath, key, value) {
2542
3520
  * @param mode - The environment mode to write into `NODE_ENV`.
2543
3521
  * @param projectRoot - Resolved project root containing the `.env` file.
2544
3522
  */
2545
- function setNodeEnv(mode, projectRoot) {
2546
- const envPath = path.join(projectRoot, ".env");
2547
- if (!existsSync(envPath)) writeFileSync(envPath, "", "utf8");
2548
- replaceEnvVar(envPath, "NODE_ENV", mode);
2549
- }
2550
- /** Resolves the IMS server to server context from the project workspace credentials. */
2551
- function resolveImsS2SContext() {
2552
- const [credential] = (config.get("project.workspace.details.credentials") ?? []).filter(({ integration_type }) => integration_type === "oauth_server_to_server").map(({ name }) => name);
2553
- if (!credential) return Promise.resolve(null);
2554
- return context.get(credential);
3523
+ async function setNodeEnv(mode, projectRoot) {
3524
+ await writeEnvValues(join(projectRoot, ".env"), { NODE_ENV: mode });
2555
3525
  }
2556
3526
  /**
2557
- * Syncs the IMS credentials environment variables from the configured IMS context in
2558
- * the .env file, in a way that is compatible with `@adobe/aio-commerce-lib-auth`.
3527
+ * Copies the workspace's OAuth Server-to-Server credential from its IMS context to the legacy
3528
+ * `AIO_COMMERCE_AUTH_IMS_*` variables of the project's `.env` file, which
3529
+ * `@adobe/aio-commerce-lib-auth` reads.
3530
+ *
2559
3531
  * @param projectRoot - Resolved project root containing the `.env` file.
3532
+ *
3533
+ * @throws A {@link CommerceSdkValidationError} If the workspace credentials or the IMS context in
3534
+ * aio's config are invalid.
2560
3535
  */
2561
3536
  async function syncImsCredentials(projectRoot) {
2562
- const envPath = path.join(projectRoot, ".env");
2563
- if (!existsSync(envPath)) return {
3537
+ const envPath = join(projectRoot, ".env");
3538
+ const variables = await readEnvFile(envPath);
3539
+ if (variables === void 0) return {
2564
3540
  ok: false,
2565
3541
  reason: "missing-env"
2566
3542
  };
2567
- const envVars = dotenv.parse(readFileSync(envPath, "utf8"));
2568
- const imsContext = await resolveImsS2SContext();
2569
- if (!imsContext) return {
3543
+ const name = parseOrThrow(WorkspaceCredentialsSchema, config.get("project.workspace.details.credentials"), "The workspace credentials in aio's config are invalid.").find((credential) => credential.integration_type === "oauth_server_to_server")?.name;
3544
+ if (!name) return {
2570
3545
  ok: false,
2571
3546
  reason: "no-ims-context"
2572
3547
  };
2573
- const { data } = imsContext;
2574
- for (const [key, value] of Object.entries(data)) {
2575
- const oauthKey = IMS_KEYS[key];
2576
- if (!oauthKey) continue;
2577
- if (!envVars[oauthKey] || envVars[oauthKey] !== value) replaceEnvVar(envPath, oauthKey, value);
2578
- }
3548
+ const context = parseOrThrow(ImsContextSchema, await aioIms.context.get(name), `The ${name} IMS context in aio's config is invalid.`);
3549
+ if (!context) return {
3550
+ ok: false,
3551
+ reason: "no-ims-context"
3552
+ };
3553
+ const { data } = context;
3554
+ const values = {
3555
+ AIO_COMMERCE_AUTH_IMS_CLIENT_ID: data?.client_id,
3556
+ AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS: data?.client_secrets,
3557
+ AIO_COMMERCE_AUTH_IMS_ORG_ID: data?.ims_org_id,
3558
+ AIO_COMMERCE_AUTH_IMS_SCOPES: data?.scopes,
3559
+ AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL: data?.technical_account_email,
3560
+ AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID: data?.technical_account_id
3561
+ };
3562
+ const changed = {};
3563
+ for (const [variable, value] of Object.entries(values)) if (value !== void 0 && variables[variable] !== value) changed[variable] = value;
3564
+ await writeEnvValues(envPath, changed);
2579
3565
  return { ok: true };
2580
3566
  }
2581
3567
 
2582
- // source/commands/hooks/pre-app-build.ts
3568
+ // source/deprecated/commands/common/runtime-actions.ts
3569
+ /** Sections whose referenced actions must be web actions. */
3570
+ const WEB_ACTION_SECTIONS = /* @__PURE__ */ new Set(["webhooks"]);
3571
+ function isNode(value) {
3572
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3573
+ }
3574
+ /**
3575
+ * Finds every `runtimeAction` and `runtimeActions` value nested in a config value.
3576
+ * @param value - The config value to search.
3577
+ * @param path - Dotted config path of `value`.
3578
+ */
3579
+ function* findReferences(value, path) {
3580
+ if (Array.isArray(value)) {
3581
+ for (const [index, item] of value.entries()) yield* findReferences(item, `${path}.${index}`);
3582
+ return;
3583
+ }
3584
+ if (!isNode(value)) return;
3585
+ for (const [key, child] of Object.entries(value)) {
3586
+ const childPath = `${path}.${key}`;
3587
+ if (key === "runtimeAction" && typeof child === "string") yield {
3588
+ name: child,
3589
+ path: childPath
3590
+ };
3591
+ else if (key === "runtimeActions" && Array.isArray(child)) {
3592
+ for (const [index, name] of child.entries()) if (typeof name === "string") yield {
3593
+ name,
3594
+ path: `${childPath}.${index}`
3595
+ };
3596
+ } else yield* findReferences(child, childPath);
3597
+ }
3598
+ }
3599
+ /**
3600
+ * Returns why a reference does not resolve to a usable declared action, or `undefined` if it does.
3601
+ * @param name - The referenced `<package>/<action>`.
3602
+ * @param declared - Actions the reference may resolve to.
3603
+ * @param location - Project-relative path of the ext.config.yaml they are declared in.
3604
+ * @param requireWebAction - Whether the referenced action must be a web action.
3605
+ * @param projectRoot - Resolved project root, used to report paths relative to it.
3606
+ */
3607
+ function checkReference(name, declared, location, requireWebAction, projectRoot) {
3608
+ const action = declared.get(name);
3609
+ if (!action) return `Runtime action "${name}" is not declared under "runtimeManifest.packages" in ${location}`;
3610
+ const source = relative(projectRoot, action.source);
3611
+ if (!(action.function && existsSync(action.function))) return action.function ? `Runtime action "${name}" points to "${relative(projectRoot, action.function)}" in ${source}, which does not exist` : `Runtime action "${name}" has no "function" in ${source}`;
3612
+ if (requireWebAction && !action.isWebAction) return `Runtime action "${name}" must be a web action (set "web: yes" in ${source})`;
3613
+ }
3614
+ /**
3615
+ * Validates that every `runtimeAction`/`runtimeActions` value in the given config sections is
3616
+ * declared in the extension's runtime manifest and that its `function` exists on disk. Webhook actions must
3617
+ * also be web actions.
3618
+ * @param sections - The config sections whose references are validated.
3619
+ * @param manifest - The extension whose runtime manifest the references must resolve against.
3620
+ * @throws {Error} If any reference does not resolve to a declared action.
3621
+ */
3622
+ async function validateRuntimeActionReferences(sections, manifest) {
3623
+ const references = Object.entries(sections).flatMap(([section, value]) => [...findReferences(value, section)].map((reference) => ({
3624
+ ...reference,
3625
+ section
3626
+ })));
3627
+ if (references.length === 0) return;
3628
+ const declared = await listExtensionRuntimeActions(manifest.projectRoot, manifest.extensionPointId);
3629
+ const errors = references.flatMap(({ name, path, section }) => {
3630
+ const message = checkReference(name, declared, manifest.path, WEB_ACTION_SECTIONS.has(section), manifest.projectRoot);
3631
+ return message ? [`${path}: ${message}`] : [];
3632
+ });
3633
+ if (errors.length > 0) throw new Error(`Invalid runtime action references in ${manifest.path}:\n- ${errors.join("\n- ")}`);
3634
+ }
3635
+
3636
+ // source/deprecated/commands/hooks/pre-app-build.ts
2583
3637
  /**
2584
3638
  * Runs the pre-app-build hook for the given extension.
2585
3639
  * @param extension - The extension to run the hook for.
@@ -2587,13 +3641,22 @@ async function syncImsCredentials(projectRoot) {
2587
3641
  * @param templatesDir - Directory containing action templates.
2588
3642
  */
2589
3643
  async function run$4(extension, projectRoot, templatesDir = TEMPLATES_DIR) {
2590
- if (await ensureExtensionPointsOrder(projectRoot)) consola$1.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.`);
3644
+ if (await ensureExtensionPointsOrder(projectRoot)) consola$1.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.`);
2591
3645
  const appManifest = await loadAppManifest(projectRoot);
2592
3646
  await run$8(appManifest, projectRoot);
2593
3647
  await prepareRuntimeAppConfigModule(appManifest, projectRoot);
2594
3648
  if (extension === "extensibility/1") {
2595
3649
  const { doc: extensibilityExtConfig } = await readExtConfig(EXTENSIBILITY_EXTENSION_POINT_ID, projectRoot);
2596
- await generateActionFiles(appManifest, getRuntimeActions(extensibilityExtConfig.toJS(), "app-management"), EXTENSIBILITY_EXTENSION_POINT_ID, templatesDir, projectRoot);
3650
+ const extensibilityConfig = extensibilityExtConfig.toJS();
3651
+ await validateRuntimeActionReferences({
3652
+ eventing: appManifest.eventing,
3653
+ webhooks: appManifest.webhooks
3654
+ }, {
3655
+ extensionPointId: EXTENSIBILITY_EXTENSION_POINT_ID,
3656
+ path: getExtConfigPath(EXTENSIBILITY_EXTENSION_POINT_ID),
3657
+ projectRoot
3658
+ });
3659
+ await generateActionFiles(appManifest, getRuntimeActions(extensibilityConfig, "app-management"), EXTENSIBILITY_EXTENSION_POINT_ID, templatesDir, projectRoot);
2597
3660
  consola$1.info("Syncing IMS credentials...");
2598
3661
  consola$1.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.");
2599
3662
  await syncImsCredentials(projectRoot);
@@ -2607,6 +3670,11 @@ async function run$4(extension, projectRoot, templatesDir = TEMPLATES_DIR) {
2607
3670
  }
2608
3671
  if (extension === "backend-ui/2") {
2609
3672
  if (hasBackendUiV2Components(appManifest)) {
3673
+ await validateRuntimeActionReferences({ adminUi: appManifest.adminUi }, {
3674
+ extensionPointId: BACKEND_UI_V2_EXTENSION_POINT_ID,
3675
+ path: getExtConfigPath(BACKEND_UI_V2_EXTENSION_POINT_ID),
3676
+ projectRoot
3677
+ });
2610
3678
  const extConfig = await updateExtConfig(appManifest, BACKEND_UI_V2_EXTENSION_POINT_ID, projectRoot);
2611
3679
  if (extConfig.operations?.view) {
2612
3680
  await prepareWebSourceImportAlias(extConfig, projectRoot);
@@ -2632,7 +3700,7 @@ async function exec$5() {
2632
3700
  }
2633
3701
  }
2634
3702
 
2635
- // source/commands/hooks/pre-app-dev.ts
3703
+ // source/deprecated/commands/hooks/pre-app-dev.ts
2636
3704
  /**
2637
3705
  * Resets the web build back to development by writing `NODE_ENV` to the project `.env`.
2638
3706
  * @param projectRoot - Resolved project root containing the `.env` file.
@@ -2652,7 +3720,7 @@ async function exec$4() {
2652
3720
  }
2653
3721
  }
2654
3722
 
2655
- // source/commands/hooks/pre-app-run.ts
3723
+ // source/deprecated/commands/hooks/pre-app-run.ts
2656
3724
  /**
2657
3725
  * Resets the web build back to development by writing `NODE_ENV` to the project `.env`.
2658
3726
  * @param projectRoot - Resolved project root containing the `.env` file.
@@ -2672,86 +3740,7 @@ async function exec$3() {
2672
3740
  }
2673
3741
  }
2674
3742
 
2675
- // source/commands/init/constants.ts
2676
- /** The default values for the features of the commerce app config. */
2677
- const DOMAIN_DEFAULTS = {
2678
- businessConfig: { schema: [{
2679
- default: ["a"],
2680
- label: "Sample List",
2681
- name: "sampleList",
2682
- options: [{
2683
- label: "Option A",
2684
- value: "a"
2685
- }, {
2686
- label: "Option B",
2687
- value: "b"
2688
- }],
2689
- selectionMode: "multiple",
2690
- type: "list"
2691
- }, {
2692
- default: "Hello, world!",
2693
- label: "Sample Text",
2694
- name: "sampleText",
2695
- type: "text"
2696
- }] },
2697
- "eventing.commerce": [{
2698
- events: [{
2699
- description: "Use case description for the event.",
2700
- fields: [{ name: "*" }],
2701
- label: "Sample Event",
2702
- name: "plugin.sample_event",
2703
- runtimeActions: ["my-package/handle-sample-event"]
2704
- }],
2705
- provider: {
2706
- description: "A description for your Commerce Events provider.",
2707
- label: "Commerce Events Provider"
2708
- }
2709
- }],
2710
- "eventing.external": [{
2711
- events: [{
2712
- description: "Use case description for the event.",
2713
- label: "Sample Event",
2714
- name: "be-observer.sample_event",
2715
- runtimeActions: ["my-package/handle-sample-event"]
2716
- }],
2717
- provider: {
2718
- description: "A description for your External Events provider.",
2719
- label: "External Events Provider"
2720
- }
2721
- }],
2722
- "installation.customInstallationSteps": [{
2723
- description: "Use case description for the step.",
2724
- name: "sample-step",
2725
- script: "./path/to/script.js"
2726
- }],
2727
- webhooks: [{
2728
- category: "modification",
2729
- description: "A sample Commerce Webhook handler.",
2730
- label: "Sample Webhook",
2731
- runtimeAction: "my-package/handle-webhook",
2732
- webhook: {
2733
- batch_name: "my_app",
2734
- hook_name: "sample_hook",
2735
- method: "POST",
2736
- webhook_method: "plugin.sample.event",
2737
- webhook_type: "after"
2738
- }
2739
- }, {
2740
- category: "modification",
2741
- description: "A sample Commerce Webhook handler using an explicit URL.",
2742
- label: "Sample Webhook with URL",
2743
- webhook: {
2744
- batch_name: "my_app",
2745
- hook_name: "sample_hook_url",
2746
- method: "POST",
2747
- url: "https://example.com/webhook",
2748
- webhook_method: "plugin.sample.event",
2749
- webhook_type: "after"
2750
- }
2751
- }]
2752
- };
2753
-
2754
- // source/commands/init/utils.ts
3743
+ // source/deprecated/commands/init/utils.ts
2755
3744
  /**
2756
3745
  * 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.
2757
3746
  * @param flags - The initialization options
@@ -2790,28 +3779,10 @@ async function promptForCommerceAppConfig() {
2790
3779
  const featuresToAdd = await consola$1.prompt(`What features do you want to add to your app? ${colorize("gray", "Space to select/deselect, Enter to submit")}`, {
2791
3780
  cancel: "reject",
2792
3781
  initial: [],
2793
- options: [
2794
- {
2795
- label: "Business Configuration",
2796
- value: "businessConfig.schema"
2797
- },
2798
- {
2799
- label: "Commerce Events",
2800
- value: "eventing.commerce"
2801
- },
2802
- {
2803
- label: "Commerce Webhooks",
2804
- value: "webhooks"
2805
- },
2806
- {
2807
- label: "External Events",
2808
- value: "eventing.external"
2809
- },
2810
- {
2811
- label: "Custom Installation Steps",
2812
- value: "installation.customInstallationSteps"
2813
- }
2814
- ],
3782
+ options: Object.entries(COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS).map(([value, { label }]) => ({
3783
+ label,
3784
+ value
3785
+ })),
2815
3786
  required: true,
2816
3787
  type: "multiselect"
2817
3788
  });
@@ -2836,17 +3807,17 @@ async function getDefaultCommerceAppConfig(cwd, { appName, configFormat, domains
2836
3807
  id: appName.toLowerCase().replace(/ /gu, "-"),
2837
3808
  version: "1.0.0"
2838
3809
  } };
2839
- if (domains.has("businessConfig.schema")) defaultConfig.businessConfig = { schema: DOMAIN_DEFAULTS.businessConfig.schema };
3810
+ if (domains.has("businessConfig.schema")) defaultConfig.businessConfig = { schema: COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["businessConfig.schema"].value };
2840
3811
  if (domains.has("eventing.commerce")) defaultConfig.eventing = {
2841
3812
  ...defaultConfig.eventing,
2842
- commerce: DOMAIN_DEFAULTS["eventing.commerce"]
3813
+ commerce: COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["eventing.commerce"].value
2843
3814
  };
2844
3815
  if (domains.has("eventing.external")) defaultConfig.eventing = {
2845
3816
  ...defaultConfig.eventing,
2846
- external: DOMAIN_DEFAULTS["eventing.external"]
3817
+ external: COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["eventing.external"].value
2847
3818
  };
2848
- if (domains.has("installation.customInstallationSteps")) defaultConfig.installation = { customInstallationSteps: DOMAIN_DEFAULTS["installation.customInstallationSteps"] };
2849
- if (domains.has("webhooks")) defaultConfig.webhooks = DOMAIN_DEFAULTS.webhooks;
3819
+ if (domains.has("installation.customInstallationSteps")) defaultConfig.installation = { customInstallationSteps: COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS["installation.customInstallationSteps"].value };
3820
+ if (domains.has("webhooks")) defaultConfig.webhooks = COMMERCE_APP_CONFIG_DOMAIN_DEFAULTS.webhooks.value;
2850
3821
  return [
2851
3822
  importStatement,
2852
3823
  "",
@@ -2860,24 +3831,24 @@ async function getDefaultCommerceAppConfig(cwd, { appName, configFormat, domains
2860
3831
  * @param commentBefore - The comment to add before the extension point include pair.
2861
3832
  */
2862
3833
  async function addExtensionPointToAppConfig(extensionPointId, rootDirectory, commentBefore) {
2863
- const appConfigPath = join(rootDirectory, APP_CONFIG_FILE);
3834
+ const appConfigPath = join(rootDirectory, APP_CONFIG_FILE$1);
2864
3835
  let doc;
2865
3836
  const includePath = relative(rootDirectory, join(rootDirectory, getExtConfigPath(extensionPointId)));
2866
3837
  try {
2867
3838
  doc = await readYamlFile(appConfigPath);
2868
3839
  } catch (error) {
2869
3840
  const fallbackContent = `extensions:\n ${extensionPointId}:\n $include: "${includePath}"`;
2870
- throw new Error(`Failed to parse ${APP_CONFIG_FILE}. \nPlease add manually: \n\n${fallbackContent}`, { cause: error });
3841
+ throw new Error(`Failed to parse ${APP_CONFIG_FILE$1}. \nPlease add manually: \n\n${fallbackContent}`, { cause: error });
2871
3842
  }
2872
3843
  if (doc.getIn([
2873
3844
  "extensions",
2874
3845
  extensionPointId,
2875
3846
  "$include"
2876
3847
  ]) === includePath) {
2877
- consola$1.success(`Extension "${extensionPointId}" already configured in ${APP_CONFIG_FILE}`);
3848
+ consola$1.success(`Extension "${extensionPointId}" already configured in ${APP_CONFIG_FILE$1}`);
2878
3849
  return;
2879
3850
  }
2880
- consola$1.info(`Adding extension "${extensionPointId}" to ${APP_CONFIG_FILE}...`);
3851
+ consola$1.info(`Adding extension "${extensionPointId}" to ${APP_CONFIG_FILE$1}...`);
2881
3852
  const extensions = getOrCreateMap(doc, ["extensions"]);
2882
3853
  getOrCreateMap(doc, ["extensions", extensionPointId], { onBeforeCreate: (pair) => {
2883
3854
  pair.key.spaceBefore = extensions.items.length > 0;
@@ -2914,7 +3885,7 @@ async function addExtensionPointToInstallYaml(extensionPointId, rootDirectory, c
2914
3885
  await writeFile(installYamlPath, doc.toString(), "utf-8");
2915
3886
  }
2916
3887
 
2917
- // source/commands/init/lib.ts
3888
+ // source/deprecated/commands/init/lib.ts
2918
3889
  /**
2919
3890
  * Ensures a valid app configuration exists, creating one when requested.
2920
3891
  * @param projectRoot - Resolved project root containing the app configuration.
@@ -3034,7 +4005,7 @@ async function ensureAppConfig(domains, config, projectRoot) {
3034
4005
  */
3035
4006
  function installDependencies(packageManager, domains, projectRoot) {
3036
4007
  const packages = [];
3037
- if (domains.has("businessConfig.schema")) packages.push(`@adobe/aio-commerce-lib-config@^1.9.0`);
4008
+ if (domains.has("businessConfig.schema")) packages.push(`@adobe/aio-commerce-lib-config@^1.10.0-alpha-20261203134759`);
3038
4009
  if (packages.length === 0) {
3039
4010
  consola.info("No additional domain dependencies to install.");
3040
4011
  return;
@@ -3068,8 +4039,8 @@ async function ensureInstallYaml(domains, config, projectRoot) {
3068
4039
  await addExtensionPointToInstallYaml(EXTENSIBILITY_EXTENSION_POINT_ID, projectRoot, " This extension is required for app management. Do not remove.");
3069
4040
  }
3070
4041
 
3071
- // source/commands/init/main.ts
3072
- const REQUIRED_DEPENDENCIES = ["@adobe/aio-commerce-sdk", `@adobe/aio-commerce-lib-app@2.2.0`];
4042
+ // source/deprecated/commands/init/main.ts
4043
+ const REQUIRED_DEPENDENCIES = ["@adobe/aio-commerce-sdk", `@adobe/aio-commerce-lib-app@2.3.0-alpha-20261203134759`];
3073
4044
  /**
3074
4045
  * Initializes a Commerce App project.
3075
4046
  * @param flags - Non-interactive initialization answers.
@@ -3115,7 +4086,7 @@ async function exec$2() {
3115
4086
  }
3116
4087
  }
3117
4088
 
3118
- // source/commands/upgrade/status/main.ts
4089
+ // source/deprecated/commands/upgrade/status/main.ts
3119
4090
  /**
3120
4091
  * Reads the arguments of `upgrade status`.
3121
4092
  * @returns The options, or a message that tells what is wrong with the arguments.
@@ -3135,11 +4106,11 @@ function parseStatusArgs(argv) {
3135
4106
  */
3136
4107
  async function resolveRun(client, extensionId, runId) {
3137
4108
  if (runId) return runId;
3138
- return (await client.readLatestUpgrade({ extensionId }))?.id;
4109
+ return (await client.getLatestUpgradeRun({ extensionId }))?.id;
3139
4110
  }
3140
4111
  /** Prints how a run stands now. */
3141
4112
  function printStatus(status) {
3142
- if (!isSettled(status)) {
4113
+ if (!isRunFinished(status)) {
3143
4114
  consola.info(`The app upgrade (run ${status.id}) is ${status.status}.`);
3144
4115
  return;
3145
4116
  }
@@ -3173,7 +4144,7 @@ async function run(options) {
3173
4144
  return 0;
3174
4145
  }
3175
4146
  try {
3176
- const status = await client.pollUpgrade({
4147
+ const status = await client.syncUpgradeRun({
3177
4148
  extensionId,
3178
4149
  runId: targetRunId
3179
4150
  });
@@ -3204,7 +4175,7 @@ async function exec$1(...argv) {
3204
4175
  }
3205
4176
  }
3206
4177
 
3207
- // source/commands/upgrade/watcher/main.ts
4178
+ // source/deprecated/commands/upgrade/watcher/main.ts
3208
4179
  /** How long the watcher waits for a token before it gives up. */
3209
4180
  const TOKEN_TIMEOUT_MS = 3e4;
3210
4181
  /**
@@ -3248,17 +4219,12 @@ function parseWatcherArgs(argv) {
3248
4219
  * @returns The exit code: 0 when the run succeeded, 1 otherwise.
3249
4220
  */
3250
4221
  async function runWatcher(args, dependencies) {
3251
- const { log, createClient, sleep } = dependencies;
4222
+ const { log, createClient } = dependencies;
3252
4223
  log(`The hook is gone (${await waitForOwnerExit()}). Following the run ${args.runId}.`);
3253
4224
  const client = await createClient();
3254
- const result = await pollUntilSettled({
4225
+ const result = await followUntilSettled(client, args, {
3255
4226
  onRetry: (error) => log(`${error.message}. Trying again.`),
3256
- onStatus: (status) => log(`Status ${status.status}.`),
3257
- poll: () => client.pollUpgrade({
3258
- extensionId: args.extensionId,
3259
- runId: args.runId
3260
- }),
3261
- sleep
4227
+ onStatus: (status) => log(`Status ${status.status}.`)
3262
4228
  });
3263
4229
  const outcome = describeOutcome(result, args.runId);
3264
4230
  log(outcome.message);
@@ -3296,7 +4262,7 @@ async function exec(...argv) {
3296
4262
  process.exit();
3297
4263
  }
3298
4264
 
3299
- // source/commands/index.ts
4265
+ // source/deprecated/commands/index.ts
3300
4266
  const NAMESPACE = "@adobe/aio-commerce-lib-app";
3301
4267
  const [command, subcommand, ...targetArgs] = process.argv.slice(2);
3302
4268
  const USAGE = `