@squiz/dxp-cli-next 5.14.0 → 5.15.0-develop.2

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 (75) hide show
  1. package/README.md +1 -0
  2. package/lib/__tests__/integration/main.spec.js +3 -2
  3. package/lib/cdp/index.js +3 -1
  4. package/lib/cmp/deploy.js +49 -2
  5. package/lib/cmp/edge-components/compiler.d.ts +13 -0
  6. package/lib/cmp/edge-components/compiler.js +55 -0
  7. package/lib/cmp/utils/definitions.d.ts +12 -0
  8. package/lib/cmp/utils/definitions.js +76 -0
  9. package/lib/datastore/index.js +1 -1
  10. package/lib/dxp.js +2 -0
  11. package/lib/porter/constants.d.ts +8 -0
  12. package/lib/porter/constants.js +11 -0
  13. package/lib/porter/index.d.ts +3 -0
  14. package/lib/porter/index.js +14 -0
  15. package/lib/porter/port/abort/abort.d.ts +3 -0
  16. package/lib/porter/port/abort/abort.js +77 -0
  17. package/lib/porter/port/abort/abort.spec.d.ts +1 -0
  18. package/lib/porter/port/abort/abort.spec.js +182 -0
  19. package/lib/porter/port/get/get.d.ts +3 -0
  20. package/lib/porter/port/get/get.js +94 -0
  21. package/lib/porter/port/get/get.spec.d.ts +1 -0
  22. package/lib/porter/port/get/get.spec.js +255 -0
  23. package/lib/porter/port/portCommand.d.ts +3 -0
  24. package/lib/porter/port/portCommand.js +19 -0
  25. package/lib/porter/port/start/start.d.ts +3 -0
  26. package/lib/porter/port/start/start.js +79 -0
  27. package/lib/porter/port/start/start.spec.d.ts +1 -0
  28. package/lib/porter/port/start/start.spec.js +198 -0
  29. package/lib/porter/project/add/add.d.ts +3 -0
  30. package/lib/porter/project/add/add.js +125 -0
  31. package/lib/porter/project/add/add.spec.d.ts +1 -0
  32. package/lib/porter/project/add/add.spec.js +270 -0
  33. package/lib/porter/project/get/get.d.ts +3 -0
  34. package/lib/porter/project/get/get.js +62 -0
  35. package/lib/porter/project/get/get.spec.d.ts +1 -0
  36. package/lib/porter/project/get/get.spec.js +185 -0
  37. package/lib/porter/project/projectCommand.d.ts +3 -0
  38. package/lib/porter/project/projectCommand.js +19 -0
  39. package/lib/porter/project/remove/remove.d.ts +3 -0
  40. package/lib/porter/project/remove/remove.js +66 -0
  41. package/lib/porter/project/remove/remove.spec.d.ts +1 -0
  42. package/lib/porter/project/remove/remove.spec.js +201 -0
  43. package/lib/porter/types.d.ts +5 -0
  44. package/lib/porter/types.js +2 -0
  45. package/lib/porter/utils/AuthUtils/CheckAuthorisation.d.ts +1 -0
  46. package/lib/porter/utils/AuthUtils/CheckAuthorisation.js +32 -0
  47. package/lib/porter/utils/AuthUtils/CheckAuthorisation.spec.d.ts +1 -0
  48. package/lib/porter/utils/AuthUtils/CheckAuthorisation.spec.js +77 -0
  49. package/lib/porter/utils/BuildPorterUrl/BuildPorterUrl.d.ts +1 -0
  50. package/lib/porter/utils/BuildPorterUrl/BuildPorterUrl.js +27 -0
  51. package/lib/porter/utils/BuildPorterUrl/BuildPorterUrl.spec.d.ts +1 -0
  52. package/lib/porter/utils/BuildPorterUrl/BuildPorterUrl.spec.js +59 -0
  53. package/lib/porter/utils/CoreUtils/CoreUtils.d.ts +2 -0
  54. package/lib/porter/utils/CoreUtils/CoreUtils.js +13 -0
  55. package/lib/porter/utils/CoreUtils/CoreUtils.spec.d.ts +1 -0
  56. package/lib/porter/utils/CoreUtils/CoreUtils.spec.js +36 -0
  57. package/lib/porter/utils/DoesPathExist/DoesPathExist.d.ts +1 -0
  58. package/lib/porter/utils/DoesPathExist/DoesPathExist.js +27 -0
  59. package/lib/porter/utils/DoesPathExist/DoesPathExist.spec.d.ts +1 -0
  60. package/lib/porter/utils/DoesPathExist/DoesPathExist.spec.js +40 -0
  61. package/lib/porter/utils/ErrorUtils/ErrorUtils.d.ts +4 -0
  62. package/lib/porter/utils/ErrorUtils/ErrorUtils.js +71 -0
  63. package/lib/porter/utils/ErrorUtils/ErrorUtils.spec.d.ts +1 -0
  64. package/lib/porter/utils/ErrorUtils/ErrorUtils.spec.js +190 -0
  65. package/lib/porter/utils/GetProjectConfig/GetProjectConfig.d.ts +2 -0
  66. package/lib/porter/utils/GetProjectConfig/GetProjectConfig.js +33 -0
  67. package/lib/porter/utils/GetProjectConfig/GetProjectConfig.spec.d.ts +1 -0
  68. package/lib/porter/utils/GetProjectConfig/GetProjectConfig.spec.js +50 -0
  69. package/lib/porter/utils/GetProjectName/GetProjectName.d.ts +4 -0
  70. package/lib/porter/utils/GetProjectName/GetProjectName.js +30 -0
  71. package/lib/porter/utils/GetProjectName/GetProjectName.spec.d.ts +1 -0
  72. package/lib/porter/utils/GetProjectName/GetProjectName.spec.js +91 -0
  73. package/lib/porter/utils/index.d.ts +7 -0
  74. package/lib/porter/utils/index.js +23 -0
  75. package/package.json +6 -3
package/README.md CHANGED
@@ -25,4 +25,5 @@ Commands:
25
25
  job-runner Job Runner Service Commands
26
26
  datastore Datastore Service Commands
27
27
  cdp Customer Data Platform Service Commands
28
+ porter Porter Service Commands
28
29
  ```
@@ -15,8 +15,9 @@ describe('dxp', () => {
15
15
  'auth Authenticate into the DXP-Next CLI',
16
16
  'cmp Component Service Commands',
17
17
  'job-runner Job Runner Service Commands',
18
- 'datastore Datastore Commands',
19
- 'cdp CDP Commands',
18
+ 'datastore Datastore Service Commands',
19
+ 'cdp Customer Data Platform Service Commands',
20
+ 'porter Porter Service Commands',
20
21
  ]);
21
22
  });
22
23
  });
package/lib/cdp/index.js CHANGED
@@ -6,5 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const commander_1 = require("commander");
7
7
  const schemaCommand_1 = __importDefault(require("./schema/schemaCommand"));
8
8
  const cdpCommand = new commander_1.Command('cdp');
9
- cdpCommand.description('CDP Commands').addCommand((0, schemaCommand_1.default)());
9
+ cdpCommand
10
+ .description('Customer Data Platform Service Commands')
11
+ .addCommand((0, schemaCommand_1.default)());
10
12
  exports.default = cdpCommand;
package/lib/cmp/deploy.js CHANGED
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
27
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -18,11 +41,18 @@ const cli_color_1 = __importDefault(require("cli-color"));
18
41
  const ApiService_1 = require("../ApiService");
19
42
  const ApplicationStore_1 = require("../ApplicationStore");
20
43
  const ApplicationConfig_1 = require("../ApplicationConfig");
44
+ const compiler_1 = require("./edge-components/compiler");
45
+ const definitions_1 = require("./utils/definitions");
46
+ const fs = __importStar(require("node:fs/promises"));
47
+ const path = __importStar(require("node:path"));
21
48
  const deployCommand = new commander_1.Command()
22
49
  .name('deploy')
23
- .argument('<source>', 'folder/file path containing the template files to deploy')
50
+ .argument('<source>', 'folder containing a manifest.json file')
24
51
  .addOption(new commander_1.Option('-cu, --component-service-url <string>', 'Override the component service url from login').env('COMPONENT_SERVICE_URL'))
25
52
  .addOption(new commander_1.Option('-t, --tenant <string>', 'Tenant ID to deploy to. If not provided will use configured tenant from login'))
53
+ .addOption(new commander_1.Option('--type <type>', 'Type of component to deploy')
54
+ .choices(['edge', 'sandbox'])
55
+ .default('sandbox'))
26
56
  .action((source, options) => __awaiter(void 0, void 0, void 0, function* () {
27
57
  var _a, _b;
28
58
  if (process.env.COMPONENT_SERVICE_URL !== undefined) {
@@ -39,7 +69,24 @@ const deployCommand = new commander_1.Command()
39
69
  try {
40
70
  const componentServiceUrl = ((_b = options.componentServiceUrl) === null || _b === void 0 ? void 0 : _b.replace(/v1\/?$/, '')) ||
41
71
  (yield buildComponentServiceUrl(options.tenant));
42
- return yield (0, component_cli_lib_1.uploadComponentFolder)(apiService.client, componentServiceUrl, source);
72
+ if (options.type === 'sandbox') {
73
+ return yield (0, component_cli_lib_1.uploadComponentFolder)(apiService.client, componentServiceUrl, source);
74
+ }
75
+ if (options.type === 'edge') {
76
+ if (process.env.FEATURE_EDGE_COMPONENTS !== 'true') {
77
+ throw new Error('Component type "edge" is still in development. Run with environment variable "FEATURE_EDGE_COMPONENTS=true" to enable');
78
+ }
79
+ const def = yield definitions_1.ComponentDefinition.load(source);
80
+ if (!def) {
81
+ throw new Error('Invalid definition');
82
+ }
83
+ const dxpCacheDirPath = path.resolve(source, '.dxp');
84
+ yield fs.mkdir(dxpCacheDirPath, { recursive: true });
85
+ const outputDir = yield fs.mkdtemp(path.resolve(dxpCacheDirPath, 'cmp-'));
86
+ yield (0, compiler_1.compileUserCode)(def.mainEntryFilePath, path.join(outputDir, 'userCode.js'));
87
+ yield fs.copyFile(def.manifestPath, path.resolve(outputDir, 'manifest.json'));
88
+ return yield (0, component_cli_lib_1.uploadComponentFolder)(apiService, componentServiceUrl, outputDir);
89
+ }
43
90
  }
44
91
  catch (error) {
45
92
  if (!!process.env.DEBUG && error.stack) {
@@ -0,0 +1,13 @@
1
+ import * as esbuild from 'esbuild';
2
+ export declare function compileUserCode(codePath: string, outfile: string): Promise<esbuild.BuildResult<{
3
+ entryPoints: string[];
4
+ bundle: true;
5
+ outfile: string;
6
+ format: "esm";
7
+ loader: {
8
+ '.js': "jsx";
9
+ };
10
+ target: string;
11
+ minify: true;
12
+ sourcemap: true;
13
+ }>>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.compileUserCode = void 0;
36
+ const esbuild = __importStar(require("esbuild"));
37
+ function compileUserCode(codePath, outfile) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ // "esbuild --bundle --outfile=./src/userCode.actual.js --format=esm --loader:.js=jsx --target=es2022 --minify --sourcemap",
40
+ const output = yield esbuild.build({
41
+ entryPoints: [codePath],
42
+ bundle: true,
43
+ outfile,
44
+ format: 'esm',
45
+ loader: {
46
+ '.js': 'jsx',
47
+ },
48
+ target: 'es2022',
49
+ minify: true,
50
+ sourcemap: true,
51
+ });
52
+ return output;
53
+ });
54
+ }
55
+ exports.compileUserCode = compileUserCode;
@@ -0,0 +1,12 @@
1
+ export declare class ComponentDefinition {
2
+ private baseDir;
3
+ private definition;
4
+ static load(componentDirectory: string): Promise<ComponentDefinition | undefined>;
5
+ private constructor();
6
+ get mainEntryFilePath(): string;
7
+ get mainFunction(): {
8
+ name: string;
9
+ entry: string;
10
+ };
11
+ get manifestPath(): string;
12
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.ComponentDefinition = void 0;
36
+ const fs = __importStar(require("node:fs/promises"));
37
+ const path = __importStar(require("node:path"));
38
+ const zod_1 = require("zod");
39
+ class ComponentDefinition {
40
+ constructor(baseDir, definition) {
41
+ this.baseDir = baseDir;
42
+ this.definition = definition;
43
+ }
44
+ static load(componentDirectory) {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ try {
47
+ const manifest = yield fs.readFile(path.resolve(componentDirectory, 'manifest.json'), { encoding: 'utf-8' });
48
+ const definition = yield BasicDefinition.parseAsync(JSON.parse(manifest));
49
+ return new ComponentDefinition(componentDirectory, definition);
50
+ }
51
+ catch (e) {
52
+ console.error(e);
53
+ }
54
+ });
55
+ }
56
+ get mainEntryFilePath() {
57
+ return path.resolve(this.baseDir, this.mainFunction.entry);
58
+ }
59
+ get mainFunction() {
60
+ return this.definition.functions.find(fn => fn.name === this.definition.mainFunction);
61
+ }
62
+ get manifestPath() {
63
+ return path.resolve(this.baseDir, 'manifest.json');
64
+ }
65
+ }
66
+ exports.ComponentDefinition = ComponentDefinition;
67
+ const BasicDefinition = zod_1.z.object({
68
+ mainFunction: zod_1.z.string(),
69
+ functions: zod_1.z
70
+ .array(zod_1.z.object({
71
+ name: zod_1.z.string(),
72
+ entry: zod_1.z.string(),
73
+ }))
74
+ .refine(fns => new Set(fns.map(f => f.name)).size === fns.length),
75
+ type: zod_1.z.enum(['edge', 'sandbox']).optional().default('sandbox'),
76
+ });
@@ -9,7 +9,7 @@ const bundle_1 = __importDefault(require("./bundle/bundle"));
9
9
  const simulatorCommand_1 = __importDefault(require("./simulator/simulatorCommand"));
10
10
  const datastoreCommand = new commander_1.Command('datastore');
11
11
  datastoreCommand
12
- .description('Datastore Commands')
12
+ .description('Datastore Service Commands')
13
13
  .addCommand((0, blueprintCommand_1.default)())
14
14
  .addCommand((0, bundle_1.default)())
15
15
  .addCommand((0, simulatorCommand_1.default)());
package/lib/dxp.js CHANGED
@@ -16,6 +16,7 @@ const cmp_1 = __importDefault(require("./cmp"));
16
16
  const job_runner_1 = __importDefault(require("./job-runner"));
17
17
  const datastore_1 = __importDefault(require("./datastore"));
18
18
  const cdp_1 = __importDefault(require("./cdp"));
19
+ const porter_1 = __importDefault(require("./porter"));
19
20
  const program = new commander_1.default.Command();
20
21
  const packageJson = require('../package.json');
21
22
  const version = packageJson.version;
@@ -28,6 +29,7 @@ program
28
29
  .addCommand(job_runner_1.default)
29
30
  .addCommand(datastore_1.default)
30
31
  .addCommand(cdp_1.default)
32
+ .addCommand(porter_1.default)
31
33
  .action(() => {
32
34
  program.help();
33
35
  })
@@ -0,0 +1,8 @@
1
+ export declare const SQUIZ_ROOT_TENANT = "SquizRoot-0000";
2
+ export declare const PORTER_REGION = "au";
3
+ export declare const PORTER_ERRORS: {
4
+ projectAlreadyExists: string;
5
+ projectNameMissing: string;
6
+ projectDirectoryInvalid: string;
7
+ portIdBlankError: string;
8
+ };
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PORTER_ERRORS = exports.PORTER_REGION = exports.SQUIZ_ROOT_TENANT = void 0;
4
+ exports.SQUIZ_ROOT_TENANT = 'SquizRoot-0000';
5
+ exports.PORTER_REGION = 'au';
6
+ exports.PORTER_ERRORS = {
7
+ projectAlreadyExists: 'Project directory already exists. Please choose a project directory that does not exist',
8
+ projectNameMissing: 'Project name is missing from the config.json file',
9
+ projectDirectoryInvalid: 'You must be within a porter project directory to use this command',
10
+ portIdBlankError: 'Cannot be blank.',
11
+ };
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const porterCommand: Command;
3
+ export default porterCommand;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const commander_1 = require("commander");
7
+ const portCommand_1 = __importDefault(require("./port/portCommand"));
8
+ const projectCommand_1 = __importDefault(require("./project/projectCommand"));
9
+ const porterCommand = new commander_1.Command('porter');
10
+ porterCommand
11
+ .description('Porter Service Commands')
12
+ .addCommand((0, projectCommand_1.default)())
13
+ .addCommand((0, portCommand_1.default)());
14
+ exports.default = porterCommand;
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const createAbortPortCommand: () => Command;
3
+ export default createAbortPortCommand;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const commander_1 = require("commander");
16
+ const chalk_1 = __importDefault(require("chalk"));
17
+ const ora_1 = __importDefault(require("ora"));
18
+ const ApiService_1 = require("../../../ApiService");
19
+ const utils_1 = require("../../utils");
20
+ const constants_1 = require("../../constants");
21
+ const createAbortPortCommand = () => {
22
+ const getCommand = new commander_1.Command('abortPort')
23
+ .description('Aborts a running website port')
24
+ .configureOutput({
25
+ outputError(str, write) {
26
+ write(chalk_1.default.red(str));
27
+ },
28
+ })
29
+ .addArgument(new commander_1.Argument('UUID', 'ID of the port').argParser((portId) => {
30
+ const trimmedPortId = portId.trim();
31
+ if (!trimmedPortId) {
32
+ throw new commander_1.InvalidArgumentError(constants_1.PORTER_ERRORS.portIdBlankError);
33
+ }
34
+ return trimmedPortId;
35
+ }))
36
+ .action((uuid) => __awaiter(void 0, void 0, void 0, function* () {
37
+ var _a, _b, _c, _d;
38
+ yield (0, utils_1.throwErrorIfNotLoggedIn)(getCommand);
39
+ const baseUrl = yield (0, utils_1.buildPorterUrl)();
40
+ const portId = uuid;
41
+ let projectName = '';
42
+ const spinner = (0, ora_1.default)();
43
+ try {
44
+ projectName = yield (0, utils_1.getProjectName)();
45
+ spinner.start('Aborting port..');
46
+ const apiService = new ApiService_1.ApiService(utils_1.validateAxiosStatus, baseUrl);
47
+ const abortRequest = {
48
+ status: 'abort',
49
+ };
50
+ const response = yield apiService.client.patch(`/projects/${projectName}/ports/${portId}`, abortRequest);
51
+ const jsonResponse = response.data;
52
+ (0, utils_1.logDebug)(JSON.stringify(jsonResponse));
53
+ spinner.succeed();
54
+ console.log('');
55
+ console.log('Website port aborted');
56
+ }
57
+ catch (error) {
58
+ (0, utils_1.logDebug)(`ERROR: ${error instanceof Error ? `${error.message}` : JSON.stringify(error)}`);
59
+ if (spinner.isSpinning) {
60
+ spinner.fail();
61
+ }
62
+ if (((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.status) === 404) {
63
+ (0, utils_1.logDebug)(error.response.data);
64
+ const errorMessage = 'Website port execution not found';
65
+ return (0, utils_1.handleError)(getCommand, errorMessage);
66
+ }
67
+ if (((_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.status) === 409) {
68
+ (0, utils_1.logDebug)(error.response.data);
69
+ const errorMessage = 'Website port cannot be aborted as it is already not running';
70
+ return (0, utils_1.handleError)(getCommand, errorMessage);
71
+ }
72
+ (0, utils_1.handleCommandError)(getCommand, error);
73
+ }
74
+ }));
75
+ return getCommand;
76
+ };
77
+ exports.default = createAbortPortCommand;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ const axios_1 = require("axios");
36
+ const ApiService = __importStar(require("../../../ApiService"));
37
+ const PorterUtils = __importStar(require("../../utils"));
38
+ const constants_1 = require("../../constants");
39
+ const dxp_porter_shared_1 = require("@squiz/dxp-porter-shared");
40
+ const logSpy = jest.spyOn(global.console, 'log');
41
+ jest.mock('../../utils');
42
+ describe('abortPort', () => {
43
+ let projectName;
44
+ let portId;
45
+ let baseUrl;
46
+ let mockHandleCommandError;
47
+ let mockHandleError;
48
+ let mockBuildPorterUrl;
49
+ let mockResponse;
50
+ let mockClient;
51
+ beforeEach(() => {
52
+ jest.resetAllMocks();
53
+ jest.clearAllMocks();
54
+ projectName = 'mock-project';
55
+ portId = '1234-5678-1234-5678';
56
+ baseUrl = 'mock-url';
57
+ mockHandleCommandError = jest.fn(() => Promise.resolve());
58
+ mockHandleError = jest.fn();
59
+ mockBuildPorterUrl = jest.fn(() => Promise.resolve(baseUrl));
60
+ mockResponse = {
61
+ data: {},
62
+ status: 200,
63
+ };
64
+ mockClient = {
65
+ patch: jest.fn().mockImplementationOnce(() => mockResponse),
66
+ };
67
+ jest.spyOn(PorterUtils, 'throwErrorIfNotLoggedIn').mockImplementation();
68
+ jest
69
+ .spyOn(PorterUtils, 'buildPorterUrl')
70
+ .mockImplementationOnce(mockBuildPorterUrl);
71
+ jest
72
+ .spyOn(PorterUtils, 'getProjectName')
73
+ .mockImplementation(() => Promise.resolve(projectName));
74
+ jest
75
+ .spyOn(PorterUtils, 'handleCommandError')
76
+ .mockImplementationOnce(mockHandleCommandError);
77
+ jest
78
+ .spyOn(PorterUtils, 'handleError')
79
+ .mockImplementationOnce(mockHandleError);
80
+ jest.spyOn(process, 'exit').mockImplementation();
81
+ jest.spyOn(ApiService, 'ApiService').mockImplementationOnce(() => {
82
+ return {
83
+ client: mockClient,
84
+ };
85
+ });
86
+ });
87
+ it('should throw an error if port id is invalid', () => __awaiter(void 0, void 0, void 0, function* () {
88
+ const portIdInvalid = ' ';
89
+ const { default: createAbortCommand } = require('./abort');
90
+ const program = createAbortCommand();
91
+ yield expect(() => program.parseAsync(['port', 'abortPort', portIdInvalid])).rejects.toThrow(constants_1.PORTER_ERRORS.portIdBlankError);
92
+ }));
93
+ it('should throw an error if not logged in', () => __awaiter(void 0, void 0, void 0, function* () {
94
+ const mockError = new Error('Error not logged in');
95
+ jest
96
+ .spyOn(PorterUtils, 'throwErrorIfNotLoggedIn')
97
+ .mockImplementationOnce(() => {
98
+ throw mockError;
99
+ });
100
+ const { default: createAbortCommand } = require('./abort');
101
+ const program = createAbortCommand();
102
+ yield expect(() => program.parseAsync(['port', 'abortPort', portId])).rejects.toThrow(mockError);
103
+ const opts = program.opts();
104
+ expect(opts).toStrictEqual({});
105
+ expect(PorterUtils.buildPorterUrl).not.toHaveBeenCalled();
106
+ }));
107
+ it('should throw an error if project name could not be found', () => __awaiter(void 0, void 0, void 0, function* () {
108
+ jest.spyOn(PorterUtils, 'getProjectName').mockImplementationOnce(() => {
109
+ throw new Error();
110
+ });
111
+ const { default: createAbortCommand } = require('./abort');
112
+ const program = createAbortCommand();
113
+ yield program.parseAsync(['port', 'abortPort', portId]);
114
+ expect(PorterUtils.buildPorterUrl).toHaveBeenCalled();
115
+ expect(mockClient.patch).not.toHaveBeenCalled();
116
+ expect(PorterUtils.handleCommandError).toHaveBeenCalled();
117
+ }));
118
+ it('should handle 404 error when port cannot be found for project', () => __awaiter(void 0, void 0, void 0, function* () {
119
+ mockClient.patch = jest.fn(() => {
120
+ throw new axios_1.AxiosError('Port does not exist', '404', undefined, undefined, {
121
+ data: { status: 404 },
122
+ });
123
+ });
124
+ const { default: createAbortCommand } = require('./abort');
125
+ const program = createAbortCommand();
126
+ yield program.parseAsync(['port', 'abortPort', portId]);
127
+ expect(PorterUtils.buildPorterUrl).toHaveBeenCalled();
128
+ expect(mockClient.patch).toHaveBeenCalledWith(`/projects/${projectName}/ports/${portId}`, { status: 'abort' });
129
+ expect(PorterUtils.handleError).toHaveBeenCalled();
130
+ }));
131
+ it('should handle 409 error when port is already not running', () => __awaiter(void 0, void 0, void 0, function* () {
132
+ mockClient.patch = jest.fn(() => {
133
+ throw new axios_1.AxiosError('Port already not running', '409', undefined, undefined, {
134
+ data: { status: 409 },
135
+ });
136
+ });
137
+ const { default: createAbortCommand } = require('./abort');
138
+ const program = createAbortCommand();
139
+ yield program.parseAsync(['port', 'abortPort', portId]);
140
+ expect(PorterUtils.buildPorterUrl).toHaveBeenCalled();
141
+ expect(mockClient.patch).toHaveBeenCalledWith(`/projects/${projectName}/ports/${portId}`, { status: 'abort' });
142
+ expect(PorterUtils.handleError).toHaveBeenCalled();
143
+ }));
144
+ it('should handle unexpected errors', () => __awaiter(void 0, void 0, void 0, function* () {
145
+ mockClient.patch = jest.fn(() => {
146
+ throw new axios_1.AxiosError('Internal server error', '500', undefined, undefined, {
147
+ data: { status: 500 },
148
+ });
149
+ });
150
+ const { default: createAbortCommand } = require('./abort');
151
+ const program = createAbortCommand();
152
+ yield program.parseAsync(['port', 'abortPort', portId]);
153
+ expect(PorterUtils.buildPorterUrl).toHaveBeenCalled();
154
+ expect(mockClient.patch).toHaveBeenCalledWith(`/projects/${projectName}/ports/${portId}`, { status: 'abort' });
155
+ expect(PorterUtils.handleError).not.toHaveBeenCalled();
156
+ expect(PorterUtils.handleCommandError).toHaveBeenCalled();
157
+ }));
158
+ it('should successfully abort a running port', () => __awaiter(void 0, void 0, void 0, function* () {
159
+ // mockClient.patch = jest.fn(() => {
160
+ // });
161
+ const mockPatchResponse = {
162
+ portid: portId,
163
+ 'artifacts-link': null,
164
+ 'report-link': null,
165
+ 'stage-settings': {},
166
+ stages: {},
167
+ status: dxp_porter_shared_1.PortStatus.aborted,
168
+ };
169
+ mockResponse = {
170
+ data: mockPatchResponse,
171
+ status: 200,
172
+ };
173
+ const { default: createAbortCommand } = require('./abort');
174
+ const program = createAbortCommand();
175
+ yield program.parseAsync(['port', 'abortPort', portId]);
176
+ expect(PorterUtils.buildPorterUrl).toHaveBeenCalled();
177
+ expect(mockClient.patch).toHaveBeenCalledWith(`/projects/${projectName}/ports/${portId}`, { status: 'abort' });
178
+ expect(PorterUtils.handleError).not.toHaveBeenCalled();
179
+ expect(PorterUtils.handleCommandError).not.toHaveBeenCalled();
180
+ expect(logSpy).toHaveBeenCalledWith('Website port aborted');
181
+ }));
182
+ });
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const createGetPortCommand: () => Command;
3
+ export default createGetPortCommand;