@contrail/cli 2.0.18 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@ $ npm install -g @contrail/cli
15
15
  $ contrail COMMAND
16
16
  running command...
17
17
  $ contrail (--version)
18
- @contrail/cli/2.0.18 darwin-arm64 node-v18.13.0
18
+ @contrail/cli/2.1.1 darwin-arm64 node-v18.13.0
19
19
  $ contrail --help [COMMAND]
20
20
  USAGE
21
21
  $ contrail COMMAND
@@ -121,10 +121,10 @@ Get an api key for an app
121
121
 
122
122
  ```
123
123
  USAGE
124
- $ contrail app getApiKey [--appIdentifier <value>]
124
+ $ contrail app getApiKey [-a <value>]
125
125
 
126
126
  FLAGS
127
- --appIdentifier=<value> The app identifier
127
+ -a, --appIdentifier=<value> The app identifier
128
128
 
129
129
  DESCRIPTION
130
130
  Get an api key for an app
@@ -159,11 +159,12 @@ Publish the app
159
159
 
160
160
  ```
161
161
  USAGE
162
- $ contrail app publish [-u] [-d]
162
+ $ contrail app publish [-u] [-v] [-d]
163
163
 
164
164
  FLAGS
165
- -d, --debug Debug the app deployment step and do not remove the intermediate build artifacts.
165
+ -d, --dryRun Dry run the upgrade without actually updating the app.
166
166
  -u, --upgrade In addition to deploying, upgrade the installed version of the app in this org to the latest one.
167
+ -v, --verbose Debug the app deployment step and do not remove the intermediate build artifacts.
167
168
 
168
169
  DESCRIPTION
169
170
  Publish the app
@@ -49,7 +49,8 @@ class CreateApp extends core_1.Command {
49
49
  publisher: answers.appPublisher,
50
50
  public: false,
51
51
  hidden: false,
52
- description: answers.appDescription
52
+ description: answers.appDescription,
53
+ frameworkVersion: 2,
53
54
  };
54
55
  try {
55
56
  await new sdk_1.Entities().create({ entityName: 'app', object: newApp });
@@ -22,7 +22,7 @@ class GetAPIKeyApp extends core_1.Command {
22
22
  })
23
23
  }];
24
24
  const answers = await inquirer_1.default.prompt(questions);
25
- console.log(`App API key: ${answers.appApiKey}`);
25
+ console.log(`App API key: (app:${answers.appApiKey})`);
26
26
  }
27
27
  else {
28
28
  const appFound = installedApps.find(x => x.app.identifier === flags.appIdentifier);
@@ -30,7 +30,7 @@ class GetAPIKeyApp extends core_1.Command {
30
30
  console.log('You do not have such an app installed');
31
31
  return;
32
32
  }
33
- console.log(`App API key: ${appFound.apiKey.apiKey}`);
33
+ console.log(`App API key: (app:${appFound.apiKey.apiKey})`);
34
34
  }
35
35
  }
36
36
  }
@@ -41,5 +41,5 @@ GetAPIKeyApp.examples = [
41
41
  `,
42
42
  ];
43
43
  GetAPIKeyApp.flags = {
44
- appIdentifier: core_1.Flags.string({ description: 'The app identifier', required: false })
44
+ appIdentifier: core_1.Flags.string({ char: 'a', description: 'The app identifier', required: false })
45
45
  };
@@ -5,7 +5,8 @@ export default class PublishApp extends Command {
5
5
  static strict: boolean;
6
6
  static flags: {
7
7
  upgrade: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
8
- debug: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
8
+ verbose: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
9
+ dryRun: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
9
10
  };
10
11
  run(): Promise<void>;
11
12
  }
@@ -22,7 +22,7 @@ class PublishApp extends core_1.Command {
22
22
  console.log(`%s Deploying Application. ${appDeclaration.appIdentifier}`, chalk_1.default.blue.bold('START'));
23
23
  try {
24
24
  await (0, login_1.authUser)();
25
- const app = await new app_deployer_1.AppDeployer(flags.debug).deploy(appDeclaration);
25
+ const app = await new app_deployer_1.AppDeployer(flags.verbose, flags.dryRun).deploy(appDeclaration);
26
26
  if (flags.upgrade) {
27
27
  const installedApps = await (0, apps_1.getInstalledApps)();
28
28
  const installedAppOrg = installedApps.find(x => x.appId === app.id);
@@ -51,5 +51,6 @@ PublishApp.examples = [
51
51
  PublishApp.strict = true;
52
52
  PublishApp.flags = {
53
53
  upgrade: core_1.Flags.boolean({ char: 'u', description: 'In addition to deploying, upgrade the installed version of the app in this org to the latest one.', required: false }),
54
- debug: core_1.Flags.boolean({ char: 'd', description: 'Debug the app deployment step and do not remove the intermediate build artifacts.', required: false }),
54
+ verbose: core_1.Flags.boolean({ char: 'v', description: 'Debug the app deployment step and do not remove the intermediate build artifacts.', required: false }),
55
+ dryRun: core_1.Flags.boolean({ char: 'd', description: 'Dry run the upgrade without actually updating the app.', required: false }),
55
56
  };
@@ -1,11 +1,12 @@
1
1
  import { App, AppCodePackage, AppDeclaration } from '../../interfaces';
2
2
  export declare class AppDeployer {
3
3
  private debug;
4
- constructor(debug?: boolean);
4
+ private dryRun;
5
+ constructor(debug?: boolean, dryRun?: boolean);
5
6
  deploy(appDeclaration: AppDeclaration): Promise<App>;
6
7
  getExistingApp(appDeclaration: AppDeclaration): Promise<App>;
7
8
  private createNewApp;
8
9
  updateExistingApp(appDeclaration: AppDeclaration, existingApp: any): Promise<any>;
9
10
  remove(appDeclaration: AppDeclaration): Promise<void>;
10
11
  }
11
- export declare function createNodePackage(appIdentifier: string, debug: boolean): Promise<AppCodePackage>;
12
+ export declare function createNodePackage(appIdentifier: string, debug: boolean, dryRun: boolean): Promise<AppCodePackage>;
@@ -14,8 +14,9 @@ const axios_1 = tslib_1.__importDefault(require("axios"));
14
14
  const child_process = require('child_process');
15
15
  const fs = require('fs');
16
16
  class AppDeployer {
17
- constructor(debug = false) {
17
+ constructor(debug = false, dryRun = false) {
18
18
  this.debug = debug;
19
+ this.dryRun = dryRun;
19
20
  //pass
20
21
  }
21
22
  async deploy(appDeclaration) {
@@ -28,6 +29,10 @@ class AppDeployer {
28
29
  console.log('%s Updating existing app.', chalk_1.default.yellow.bold('APP'));
29
30
  app = await this.updateExistingApp(appDeclaration, app);
30
31
  }
32
+ if (this.dryRun) {
33
+ console.log('Dry run, skipping action and workflow template definition deployment.');
34
+ return {};
35
+ }
31
36
  await new actions_deployer_1.ActionsDeployer().deployActions(appDeclaration, app);
32
37
  await new workflow_template_definition_deployer_1.WorkflowTemplateDefinitionDeployer().deployWorkflowTemplateDefinitions(appDeclaration, app);
33
38
  return app;
@@ -51,7 +56,7 @@ class AppDeployer {
51
56
  const isDocker = Object.hasOwnProperty.call(appDeclaration, 'dockerImageRef');
52
57
  let appCodePackageId;
53
58
  if (!isDocker) { // this is the expected default behavior
54
- const appCodePackage = await createNodePackage(appDeclaration.appIdentifier, this.debug);
59
+ const appCodePackage = await createNodePackage(appDeclaration.appIdentifier, this.debug, this.dryRun);
55
60
  appCodePackageId = appCodePackage.id;
56
61
  }
57
62
  const newApp = {
@@ -68,7 +73,12 @@ class AppDeployer {
68
73
  triggerKeyDefinitions,
69
74
  dockerImageRef: (_a = appDeclaration.dockerImageRef) !== null && _a !== void 0 ? _a : null,
70
75
  appCodePackageId: appCodePackageId !== null && appCodePackageId !== void 0 ? appCodePackageId : null,
76
+ frameworkVersion: 2,
71
77
  };
78
+ if (this.dryRun) {
79
+ console.log('Dry run, not creating app');
80
+ return {};
81
+ }
72
82
  const app = await new sdk_1.Entities().create({ entityName: 'app', object: newApp });
73
83
  console.log(`%s Created new app: ${app.name}`, chalk_1.default.yellow.bold('APP'));
74
84
  return app;
@@ -87,7 +97,7 @@ class AppDeployer {
87
97
  const isDocker = Object.hasOwnProperty.call(appDeclaration, 'dockerImageRef');
88
98
  let appCodePackageId;
89
99
  if (!isDocker) { // this is the expected default behavior
90
- const appCodePackage = await createNodePackage(appDeclaration.appIdentifier, this.debug);
100
+ const appCodePackage = await createNodePackage(appDeclaration.appIdentifier, this.debug, this.dryRun);
91
101
  appCodePackageId = appCodePackage.id;
92
102
  }
93
103
  const updates = {
@@ -103,7 +113,12 @@ class AppDeployer {
103
113
  triggerKeyDefinitions,
104
114
  dockerImageRef: (_a = appDeclaration.dockerImageRef) !== null && _a !== void 0 ? _a : null,
105
115
  appCodePackageId: appCodePackageId !== null && appCodePackageId !== void 0 ? appCodePackageId : null,
116
+ frameworkVersion: 2,
106
117
  };
118
+ if (this.dryRun) {
119
+ console.log('Dry run, not creating app');
120
+ return {};
121
+ }
107
122
  const app = await new sdk_1.Entities().update({ entityName: 'app', id: existingApp.id, object: updates });
108
123
  console.log(`%s Updated app: ${app.name}`, chalk_1.default.yellow.bold('APP'));
109
124
  return app;
@@ -125,7 +140,7 @@ class AppDeployer {
125
140
  }
126
141
  }
127
142
  exports.AppDeployer = AppDeployer;
128
- async function createNodePackage(appIdentifier, debug) {
143
+ async function createNodePackage(appIdentifier, debug, dryRun) {
129
144
  // zip src code and package.json and package-lock.json files into a zip file
130
145
  // and upload as a code package.
131
146
  const entitiesClient = new sdk_1.Entities();
@@ -133,7 +148,6 @@ async function createNodePackage(appIdentifier, debug) {
133
148
  // clear and make temp directory
134
149
  fs.rmSync('tmp/', { recursive: true, force: true });
135
150
  fs.cpSync('package.json', 'tmp/package.json');
136
- fs.cpSync('app.yml', 'tmp/app.yml');
137
151
  //copy package-lock.json if it exists
138
152
  if (fs.existsSync('package-lock.json')) {
139
153
  fs.cpSync('package-lock.json', 'tmp/package-lock.json');
@@ -145,9 +159,15 @@ async function createNodePackage(appIdentifier, debug) {
145
159
  console.log('Building package...');
146
160
  child_process.execSync('npx tsc --outDir tmp/dist');
147
161
  console.log('Building package done.');
162
+ // including the app.yml file in the package at the dist level
163
+ fs.cpSync('app.yml', 'tmp/dist/app.yml');
148
164
  console.log('Zipping package...');
149
165
  await (0, zip_a_folder_1.zip)('tmp/', 'tmp.zip');
150
166
  console.log('Zipping package done.');
167
+ if (dryRun) {
168
+ console.log('Dry run, skipping cloud updates');
169
+ return {};
170
+ }
151
171
  console.log('Uploading package to S3...');
152
172
  let apps = await entitiesClient.get({ entityName: 'app', criteria: { hidden: true } });
153
173
  apps = apps.concat(await entitiesClient.get({ entityName: 'app', criteria: { private: true } }));
@@ -5,7 +5,6 @@ visibility: private # This should be private unless you want to develop an app
5
5
  hidden: false # can be used with a public app to prevent it from showing on the marketplace, but still installable by other orgs
6
6
  publisher: "Your company name" # Your company name, used for public apps
7
7
  version: 1.0
8
- # dockerImageRef: CHANGE_ME # Deprecated. For VibeIQ Deployment... for use by VibeIQ employees only
9
8
 
10
9
  # Properties you can configure when you install the app.
11
10
  # These property values will be available to all of your actions when they run
@@ -7,36 +7,22 @@
7
7
  "@contrail/contrail-cli": "bin/init",
8
8
  "contrail": "bin/init"
9
9
  },
10
- "config": {
11
- "wf": "/workflow-actions-prod"
12
- },
13
10
  "publishConfig": {
14
11
  "access": "public"
15
12
  },
16
13
  "scripts": {
17
14
  "build": "tsc",
18
- "start": "nodemon --watch \"src/**/*.ts\" --exec ts-node src/framework/mock-server.ts",
19
- "debug": "nodemon -r ts-node/register --inspect=127.0.0.1:60002 --watch 'actions/**/*.ts' --exec node src/framework/mock-server.ts",
15
+ "start": "nodemon --watch \"src/**/*.ts\" --exec ts-node src/module.ts",
16
+ "debug": "nodemon -r ts-node/register --inspect=127.0.0.1:60002 --watch 'actions/**/*.ts' --exec node src/module.ts",
20
17
  "lint": "eslint . --fix",
21
18
  "test": "jest",
22
- "test-watch": "jest --watch",
23
- "docker-build": "docker build . -t \"${npm_package_name}:${npm_package_version}\" --platform=linux/amd64",
24
- "docker-build:win": "docker build . -t \"%npm_package_name%:%npm_package_version%\" --platform=linux/amd64",
25
- "docker-run-entry": "docker run -it --entrypoint=/bin/bash \"${npm_package_name}:${npm_package_version}\"",
26
- "docker-run-entry:win": "docker run -it --entrypoint=/bin/bash \"%npm_package_name%:%npm_package_version%\"",
27
- "docker-run": "docker run --env CONTRAIL_CLI_ENV=DEV -p 9000:8080 \"${npm_package_name}:${npm_package_version}\"",
28
- "docker-run:win": "docker run --env CONTRAIL_CLI_ENV=DEV -p 9000:8080 \"%npm_package_name%:%npm_package_version%\"",
29
- "docker-ecr-login": "aws ecr get-login-password | docker login --username AWS --password-stdin ${AWS_REGISTRY}",
30
- "docker-ecr-login:win": "aws ecr get-login-password | docker login --username AWS --password-stdin %AWS_REGISTRY%",
31
- "docker-tag": "docker tag ${npm_package_name}:${npm_package_version} \"${AWS_REGISTRY}${npm_package_config_wf}:${npm_package_name}.${npm_package_version}\"",
32
- "docker-tag:win": "docker tag %npm_package_name%:%npm_package_version% %AWS_REGISTRY%%npm_package_config_wf%:%npm_package_name%.%npm_package_version%",
33
- "docker-push": "docker push \"${AWS_REGISTRY}${npm_package_config_wf}:${npm_package_name}.${npm_package_version}\"",
34
- "docker-push:win": "docker push \"%AWS_REGISTRY%%npm_package_config_wf%:%npm_package_name%.%npm_package_version%\""
19
+ "test-watch": "jest --watch"
35
20
  },
36
21
  "keywords": [],
37
22
  "author": "",
38
23
  "license": "ISC",
39
24
  "dependencies": {
25
+ "@contrail/app-framework": "^1.0.7",
40
26
  "@contrail/sdk": "^1.1.54",
41
27
  "chalk": "^4.0.0",
42
28
  "js-yaml": "^4.1.0"
@@ -44,6 +30,7 @@
44
30
  "devDependencies": {
45
31
  "@types/node": "^18.14.6",
46
32
  "body-parser": "^1.20.2",
33
+ "copyfiles": "^2.4.1",
47
34
  "express": "^4.18.2",
48
35
  "jest": "^29.2.2",
49
36
  "nodemon": "^1.19.4",
@@ -1,21 +1,24 @@
1
- import { Entities } from "@contrail/sdk";
2
- import { AppActionCallBack, AppActionCallbackStatus } from "../framework";
3
- import { Logger } from "../framework/logger";
1
+ import { Entities } from '@contrail/sdk';
2
+ import { Action, AppAction, AppActionCallBack, AppActionCallbackStatus, Logger } from '@contrail/app-framework';
4
3
 
5
- export async function execute(event, config: any, logger: Logger): Promise<AppActionCallBack> {
6
- logger.log('Starting Example Action');
7
- logger.log('Getting item from SDK');
4
+ export class LogItemAction implements AppAction {
8
5
 
9
- const item = await new Entities().get({
10
- entityName: 'item',
11
- id: event.id,
12
- });
13
- logger.log('Got item: ', item);
6
+ @Action('logItem')
7
+ public async execute(event, config: any, logger: Logger): Promise<AppActionCallBack> {
8
+ logger.log('Starting Example Action');
9
+ logger.log('Getting item from SDK');
14
10
 
15
- return {
16
- output: {
17
- item,
18
- },
19
- status: AppActionCallbackStatus.SUCCESS
20
- };
11
+ const item = await new Entities().get({
12
+ entityName: 'item',
13
+ id: event.id,
14
+ });
15
+ logger.log('Got item: ', item);
16
+
17
+ return {
18
+ output: {
19
+ item,
20
+ },
21
+ status: AppActionCallbackStatus.SUCCESS
22
+ };
23
+ }
21
24
  }
@@ -0,0 +1,41 @@
1
+ import { ContrailAppModule, loadAppConfig, registerAppInfo, runMockServer, AppActionRequest, AppActionResponse, ActionDispatcher } from '@contrail/app-framework';
2
+
3
+ // we can't use static import here. Require only
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+ const pJson = require('../package.json');
7
+
8
+ const APP_YML_LOCATION = path.resolve(path.join(__dirname, '..', 'app.yml'));
9
+ export class AppModule extends ContrailAppModule {
10
+
11
+ initModule() {
12
+ // register the app info
13
+ const appConfig = loadAppConfig(APP_YML_LOCATION);
14
+ registerAppInfo({
15
+ appName: appConfig.appIdentifier, //appName is required
16
+ packageVersion: pJson.version
17
+ });
18
+
19
+ // register app's actions
20
+ for (const file of fs.readdirSync(path.join(__dirname, 'actions'))) {
21
+ if (!file.endsWith('.js')) {
22
+ continue;
23
+ }
24
+ console.log('reading file', file);
25
+ require(path.join(__dirname, 'actions', file));
26
+ }
27
+ }
28
+ }
29
+
30
+ // If the module is being run directly, run the mock server
31
+ // https://nodejs.org/api/modules.html#accessing-the-main-module
32
+ if (require.main === module) {
33
+ runMockServer(new AppModule(), null);
34
+ }
35
+
36
+ // special handler for Lambda
37
+ export async function handle(data: AppActionRequest): Promise<AppActionResponse> {
38
+ // start the module
39
+ new AppModule().initModule();
40
+ return ActionDispatcher.dispatchActionRequest(data);
41
+ }
@@ -1,17 +1,9 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "commonjs",
5
3
  "declaration": true,
4
+ "emitDecoratorMetadata": true,
6
5
  "esModuleInterop": true,
7
- "outDir": "dist",
8
- "strict": false,
9
6
  "experimentalDecorators": true,
10
- "strictPropertyInitialization": false,
11
- "noImplicitAny": false,
12
- "emitDecoratorMetadata": true,
13
- "skipLibCheck": true,
14
- "moduleResolution": "node",
15
7
  "lib": [
16
8
  "es5",
17
9
  "ES2015",
@@ -21,8 +13,25 @@
21
13
  "dom",
22
14
  "esnext.asynciterable"
23
15
  ],
24
- "types": ["node"]
16
+ "module": "CommonJS",
17
+ // "moduleResolution": "node",
18
+ "noImplicitAny": false,
19
+ "outDir": "dist",
20
+ "resolveJsonModule": true,
21
+ "skipLibCheck": true,
22
+ "strict": false,
23
+ "strictPropertyInitialization": false,
24
+ "target": "ES2020",
25
+ "types": [
26
+ "node"
27
+ ]
25
28
  },
26
- "include": ["src"],
27
- "exclude": ["node_modules", "**/__tests__/*"]
28
- }
29
+ "exclude": [
30
+ "node_modules",
31
+ "**/__tests__/*"
32
+ ],
33
+ "include": [
34
+ "src",
35
+ "package.json"
36
+ ]
37
+ }
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.0.18",
2
+ "version": "2.1.1",
3
3
  "commands": {
4
4
  "app:create": {
5
5
  "id": "app:create",
@@ -44,6 +44,7 @@
44
44
  "appIdentifier": {
45
45
  "name": "appIdentifier",
46
46
  "type": "option",
47
+ "char": "a",
47
48
  "description": "The app identifier",
48
49
  "required": false,
49
50
  "multiple": false
@@ -110,13 +111,21 @@
110
111
  "required": false,
111
112
  "allowNo": false
112
113
  },
113
- "debug": {
114
- "name": "debug",
114
+ "verbose": {
115
+ "name": "verbose",
115
116
  "type": "boolean",
116
- "char": "d",
117
+ "char": "v",
117
118
  "description": "Debug the app deployment step and do not remove the intermediate build artifacts.",
118
119
  "required": false,
119
120
  "allowNo": false
121
+ },
122
+ "dryRun": {
123
+ "name": "dryRun",
124
+ "type": "boolean",
125
+ "char": "d",
126
+ "description": "Dry run the upgrade without actually updating the app.",
127
+ "required": false,
128
+ "allowNo": false
120
129
  }
121
130
  },
122
131
  "args": {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/cli",
3
- "version": "2.0.18",
3
+ "version": "2.1.1",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",
@@ -33,6 +33,7 @@
33
33
  "amazon-cognito-identity-js": "^5.2.3",
34
34
  "arg": "^4.0.1",
35
35
  "aws-sdk": "^2.1044.0",
36
+ "axios": "^1.3.5",
36
37
  "chalk": "^4.0.0",
37
38
  "command-line-usage": "^6.1.1",
38
39
  "csvtojson": "^2.0.10",
@@ -46,7 +47,6 @@
46
47
  "lodash": "^4.17.21",
47
48
  "ncp": "^2.0.0",
48
49
  "pkg-install": "^1.0.0",
49
- "axios": "^1.3.5",
50
50
  "zip-a-folder": "^1.1.5"
51
51
  },
52
52
  "devDependencies": {
@@ -1,15 +0,0 @@
1
- # docker build -t app-name .
2
- # docker run -p 9000:8080 app-name
3
- FROM public.ecr.aws/lambda/nodejs:16
4
-
5
- # Install NPM dependencies for function
6
- COPY package* ${LAMBDA_TASK_ROOT}
7
- COPY app.yml ${LAMBDA_TASK_ROOT}
8
- RUN npm install
9
-
10
- COPY tsconfig.json ${LAMBDA_TASK_ROOT}
11
- COPY src/ ${LAMBDA_TASK_ROOT}/src
12
-
13
- RUN npm run build
14
-
15
- CMD ["dist/framework/handler.execute"]
@@ -1 +0,0 @@
1
- npm run docker-ecr-login:win && npm version patch && npm run docker-build:win && npm run docker-tag:win && npm run docker-push:win
@@ -1,93 +0,0 @@
1
- /**
2
- * WARNING: Do not modify this file, it is part of the generic runtime handling logic
3
- * for VibeIQ app actions.
4
- */
5
-
6
-
7
- import { setAppCredentials } from "@contrail/sdk";
8
- import { loadAppConfig } from "./app-config";
9
- import { AppActionCallbackStatus, AppActionRequest, AppActionResponse } from "./interfaces";
10
- import { Logger } from "./logger";
11
- var pjson = require('../../package.json');
12
-
13
- const APP_CONFIG = loadAppConfig();
14
- const appName = APP_CONFIG.appIdentifier;
15
-
16
- export class ActionDispatcher {
17
-
18
- public static async dispatchActionRequest(data: AppActionRequest) : Promise<AppActionResponse> {
19
- // Sets the auth creds on the SDK
20
- await setAppCredentials(data.apiKey, data.orgSlug);
21
-
22
- const logger = new Logger();
23
- const event = (typeof data.event === 'string')
24
- ? JSON.parse(data.event)
25
- : data.event;
26
-
27
- logger.log(`App Info: `, pjson.name, ':', pjson.version);
28
- return ActionDispatcher.delegateToHandler(event, data, logger);
29
- }
30
-
31
- private static async delegateToHandler(event, data: AppActionRequest, logger: Logger) : Promise<AppActionResponse>{
32
- try {
33
- const handler = ActionDispatcher.getActionHandler(data);
34
- let actionResults = await handler(event, data, logger)
35
- let body: any = {
36
- logs: logger.allEntries,
37
- taskId: data.taskId,
38
- status: AppActionCallbackStatus.SUCCESS,
39
- };
40
-
41
- if(typeof actionResults === 'string'){
42
- body.output = { message: actionResults }
43
- } else if(typeof actionResults === 'object'){
44
- if(actionResults.output){
45
- body.output = actionResults.output;
46
- }
47
- if(actionResults.status) {
48
- body.status = actionResults.status;
49
- }
50
- }
51
- return {
52
- statusCode: 200,
53
- body
54
- }
55
- } catch (error) {
56
- console.log("Error caught in handling action, sending Failure status: ", error)
57
- return {
58
- statusCode: 200,
59
- body: {
60
- output: {
61
- errorMessage: error.message,
62
- errorDetails: error.details
63
- },
64
- taskId: data.taskId,
65
- logs: logger.allEntries,
66
- status: AppActionCallbackStatus.FAILURE,
67
- }
68
- }
69
- }
70
- }
71
-
72
- /** Retrives the handler function for the requested action
73
- */
74
- private static getActionHandler(data: AppActionRequest): (event, data, logger) => any {
75
- try {
76
- const actionPath = data.action;
77
- const actionName = actionPath.substring(appName.length + 1, actionPath.length);
78
- console.log('action: ', actionPath, actionName);
79
- const handlerFile = require(`../actions/${actionName}`);
80
- if(!handlerFile) {
81
- throw new Error(`Handler file could not be located for action : ${data.action}`);
82
- }
83
- const handlerFunction = handlerFile.execute;
84
- if(!handlerFunction) {
85
- throw new Error(`Handler function 'execute' could not be located for action : ${data.action}`);
86
- }
87
- return handlerFunction;
88
- } catch (error) {
89
- console.log("Error caught in getActionHandler: ", error)
90
- throw new Error(`Could not locate handler function for requested action: ${data.action}`);
91
- }
92
- }
93
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * WARNING: Do not modify this file, it is part of the generic runtime handling logic
3
- * for VibeIQ app actions.
4
- */
5
-
6
- import fs from 'fs';
7
- const yaml = require('js-yaml');
8
-
9
- export function loadAppConfig(){
10
- const TARGET_DIR = process.cwd();
11
- try {
12
- const separator = getSeparatorByPlatform();
13
- const doc = yaml.load(fs.readFileSync(TARGET_DIR + separator + 'app.yml', 'utf8'));
14
- return doc;
15
- } catch (e) {
16
- throw new Error(`ERROR PARSING YAML: ${e}`);
17
- }
18
- }
19
-
20
- export function getSeparatorByPlatform() {
21
- const isWin = process.platform === 'win32';
22
- const separator = isWin ? '\\' : '/';
23
- return separator;
24
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * WARNING: Do not modify this file, it is part of the generic runtime handling logic
3
- * for VibeIQ app actions.
4
- */
5
-
6
-
7
- import { AppActionRequest, AppActionResponse, ActionDispatcher } from '.';
8
-
9
- export async function execute(data: AppActionRequest): Promise<AppActionResponse> {
10
- return ActionDispatcher.dispatchActionRequest(data);
11
- }
@@ -1,3 +0,0 @@
1
- export * from './interfaces';
2
- export * from './action-dispatcher';
3
- export * from './logger';
@@ -1,32 +0,0 @@
1
- /**
2
- * WARNING: Do not modify this file, it is part of the generic runtime handling logic
3
- * for VibeIQ app actions.
4
- */
5
-
6
- export interface AppActionRequest {
7
- action: string;
8
- apiKey: string;
9
- orgSlug: string;
10
- taskId: string;
11
- event: any;
12
- [key:string] : any;
13
- }
14
-
15
-
16
- export interface AppActionResponse {
17
- statusCode: number;
18
- body: AppActionCallBack;
19
- }
20
-
21
- export interface AppActionCallBack {
22
- output?: any;
23
- status?: AppActionCallbackStatus;
24
- logs?: Array<string>;
25
- taskId?: string;
26
- }
27
-
28
-
29
- export enum AppActionCallbackStatus {
30
- FAILURE = 'FAILURE',
31
- SUCCESS = 'SUCCESS'
32
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * WARNING: Do not modify this file, it is part of the generic runtime handling logic
3
- * for VibeIQ app actions.
4
- */
5
-
6
-
7
- export class Logger {
8
- allEntries : Array<string> = [];
9
- public log(...args){
10
- console.log(...args);
11
- this.allEntries.push(new Date().toISOString() + ': ' + args.join(''));
12
- }
13
-
14
- public getEntries(){
15
- return this.allEntries.join('\n');
16
- }
17
-
18
- public clearEntries(){
19
- this.allEntries = [];
20
- }
21
- }
@@ -1,31 +0,0 @@
1
- /**
2
- * WARNING: Do not modify this file, it is part of the generic runtime handling logic
3
- * for VibeIQ app actions.
4
- */
5
-
6
-
7
- import { execute } from './handler';
8
-
9
- const express = require('express');
10
- const bodyParser = require('body-parser');
11
- const app = express();
12
- const port = 5050;
13
-
14
- // parse application/x-www-form-urlencoded
15
- app.use(bodyParser.urlencoded({ extended: false }));
16
- // parse application/json
17
- app.use(bodyParser.json());
18
-
19
- app.get('/health_check', (req, res) => {
20
- res.send('Hello World!');
21
- });
22
-
23
- // DO NOT CHANGE THIS IMPLEMENTATION
24
- app.post('/', async (req, res) => {
25
- const result = await execute(req.body);
26
- res.send(result);
27
- });
28
-
29
- app.listen(port, () => {
30
- console.log(`Mock server listening on port ${port}`);
31
- });