at-builder 1.1.0 → 1.1.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.
@@ -2,31 +2,110 @@ const path = require("path");
2
2
  const fs = require("fs");
3
3
  var clc = require("cli-color");
4
4
 
5
-
6
- export const getVersion = () => {
5
+ /**
6
+ * Reads and returns the version from package.json
7
+ * @returns {Promise<string>} The version of the package
8
+ */
9
+ export const getVersion = async () => {
7
10
  const packageJSONPath = path.resolve(__dirname, "../../package.json");
8
- const content = fs.readFileSync(packageJSONPath, { encoding: "utf8" });
9
- const config = JSON.parse(content);
10
- return config.version;
11
+ try {
12
+ const content = await fs.promises.readFile(packageJSONPath, { encoding: "utf8" });
13
+ const config = JSON.parse(content);
14
+ return config.version;
15
+ } catch (error) {
16
+ console.error(clc.red("Error reading package.json or parsing JSON"));
17
+ process.exit(1); // Exit the process if package.json is not found or malformed
18
+ }
19
+ };
20
+
21
+ exports.getVersion = getVersion;
22
+
23
+ /**
24
+ * Helper function for formatting colorized text
25
+ * @param {string} text The text to format
26
+ * @param {string} color The color for the text
27
+ * @param {boolean} bold Whether to make the text bold
28
+ * @param {boolean} underline Whether to underline the text
29
+ * @returns {string} The formatted text
30
+ */
31
+ const formatText = (text, color = "white", bold = false, underline = false) => {
32
+ let formattedText = clc[color](text);
33
+ if (bold) formattedText = clc.bold(formattedText);
34
+ if (underline) formattedText = clc.underline(formattedText);
35
+ return formattedText;
11
36
  };
12
37
 
13
- const version = getVersion();
38
+ /**
39
+ * Returns help information with commands and usage
40
+ * @returns {Promise<string>} The help text
41
+ */
42
+ export const getHelpInfo = async () => {
43
+ const version = await getVersion();
14
44
 
15
- export const getHelpInfo = () => `
16
- ${clc.green.underline(`at-builder (version: ${version})`)}
45
+ return `
46
+ ${formatText(`at-builder (version: ${version})`, 'green', false, true)}
17
47
 
18
- ${clc.white.bold("A simple command to run adobe target builder.")}
48
+ ${formatText("A simple command to run Adobe Target builder.", 'white', true)}
19
49
 
20
- $ atb
50
+ Usage: \`atb\`
21
51
 
22
52
  Available Commands:
23
53
 
24
- ${clc.blue.underline.bold("new")} Creates a new activity
25
- ${clc.blue.underline.bold("build")} Create build
54
+ ${formatText("new", 'blue', true, true)} Creates a new activity
55
+ ${formatText("build", 'blue', true, true)} Create build
56
+ ${formatText("build -p", 'blue', true, true)} Create production build
26
57
 
27
58
  Example:
28
59
 
29
- atb -c new
30
- atb -c
31
- `;
60
+ atb -c new # Creates a new activity
61
+ atb -c build # Creates a build
62
+ atb -p -c build # Creates a build for production
63
+
64
+ For more information on a specific command, run \`atb <command> --help\`
65
+ `;
66
+ };
67
+
68
+
69
+ export const setupEnv = async (basePath) => {
70
+ // Path to the .env file
71
+ const envPath = path.join(basePath, '.env');
72
+
73
+ // Check if the .env file exists
74
+ if (!fs.existsSync(envPath)) {
75
+ // Define the content of the .env file
76
+ const envContent = `
77
+ ACTIVITY_FOLDER_NAME=""
78
+ PUPPETEER_LANDING_PAGE=""
79
+ TARGET_URL=""
80
+ LOGIN_URL=""
81
+ VARIATION="Variation-1"
82
+ NODE_ENV="development"
83
+ `;
84
+ // Write the content to the .env file
85
+ fs.writeFileSync(envPath, envContent.trim(), 'utf8');
86
+ console.log('.env file created successfully!');
87
+ } else {
88
+ console.log('.env file already exists!');
89
+ }
90
+ createWatchConfig(basePath);
91
+ }
92
+
93
+
94
+ const createWatchConfig = (basePath ) => {
95
+
96
+ // Path to the watch-config.json file
97
+ const watchConfigPath = path.join(basePath, 'watch-config.json');
98
+
99
+ // Default content for watch-config.json
100
+ const watchConfigContent = {
101
+ "VARIATION": "Variation-1"
102
+ };
32
103
 
104
+ // Check if the watch-config.json file already exists
105
+ if (!fs.existsSync(watchConfigPath)) {
106
+ fs.writeFileSync(watchConfigPath, JSON.stringify(watchConfigContent, null, 2), 'utf8');
107
+ console.log('watch-config.json file created successfully!');
108
+ } else {
109
+ console.log('watch-config.json file already exists!');
110
+ }
111
+ }
package/src/index.ts CHANGED
@@ -1,118 +1,199 @@
1
1
  #!/usr/bin/env node
2
-
3
2
  import { spawn } from "child_process";
4
- import { getHelpInfo } from "./constants/config";
5
- const path = require("path");
6
- const fs = require("fs");
7
- const readline = require('readline');
3
+ import path from "path";
4
+ import fs from "fs";
5
+ import inquirer from 'inquirer';
6
+ import { Command } from 'commander';
7
+ import { getVersion, getHelpInfo, setupEnv } from "./constants/config";
8
8
 
9
- import * as inquirer from 'inquirer';
9
+ /**
10
+ * Checks if the .env file exists at the current working directory
11
+ *
12
+ * @throws {Error} If the .env file is not found
13
+ */
14
+ const checkEnvFile = () => {
15
+ console.log("Checking if .env file exists at current working directory");
16
+ try {
17
+ // Check if the file exists and is readable
18
+ fs.accessSync(path.join(process.cwd(), ".env"), fs.constants.R_OK);
19
+ console.log(".env file found");
20
+ } catch (error) {
21
+ // If the file does not exist, throw an error
22
+ console.log(`Error: Couldn't find .env file at location ${process.cwd()}`);
23
+ throw error;
24
+ }
25
+ };
10
26
 
27
+ // Prepare environment for spawning processes
28
+ const productionEnv = {
29
+ ...process.env,
30
+ executionPath: process.cwd()
31
+ };
11
32
 
12
- // inquirer
13
- // .prompt([
14
-
15
- // ])
16
- // .then((answers) => {
17
- // // Use user feedback for... whatever!!
18
- // })
19
- // .catch((error) => {
20
- // if (error.isTtyError) {
21
- // // Prompt couldn't be rendered in the current environment
22
- // } else {
23
- // // Something else went wrong
24
- // }
25
- // });
26
-
27
-
28
- try {
29
- fs.accessSync(path.join(process.cwd(), ".env"), fs.constants.R_OK);
30
- } catch (error) {
31
- throw `Error : Couldn't find .env file at location ${process.cwd()}`;
32
- }
33
+ // Commander setup
34
+ const setupCommander = async () => {
35
+ console.log("Setting up commander");
36
+ const version = await getVersion();
37
+ console.log(`Version: ${version}`);
38
+ const program = new Command();
39
+ program
40
+ .version(version, "-V, --version")
41
+ .usage("[OPTIONS]...")
42
+ .option("-c, --command <value>")
43
+ .option("-p, --prod")
44
+ .option("-v, --verbose", "Enable verbose logging")
45
+ .parse(process.argv);
33
46
 
34
- const commander = require("commander");
35
- commander
36
- .version("1.0.0", "-v, --version")
37
- .usage("[OPTIONS]...")
38
- .option("-c, --command <value>")
39
- .option("-p, --prod")
40
- .parse(process.argv);
41
-
42
- const options = commander.opts();
43
- let userChoice = '';
44
- var productionEnv = Object.create(process.env);
45
- productionEnv.executionPath = process.cwd();
46
-
47
- console.log("OPTIONS COmmand", options.command)
48
- switch (options.command) {
49
- case "new": {
50
- spawn("npm", ["run", "new-activity"], {
51
- // env: { NODE_ENV: process.cwd() },
52
- env: productionEnv,
53
- cwd: path.join(__dirname, "../"),
54
- shell: true,
55
- stdio: "inherit",
56
- });
57
- break;
58
- }
59
- case "build": {
60
- if (options.prod) {
61
- process.env['NODE_ENV'] = 'production';
62
- }
47
+ console.log("Commander setup complete");
48
+ return program.opts();
49
+ };
50
+
51
+
52
+
53
+ /**
54
+ * Spawn a command using `npm` with the given command array and environment object.
55
+ *
56
+ * @param commandArr - The array of command strings to pass to `npm`.
57
+ * @param env - The environment object to pass to the spawned process.
58
+ */
59
+ const runCommand = (commandArr: string[], env: NodeJS.ProcessEnv): void => {
60
+ console.log(`Running npm command [${commandArr.join(", ")}]`);
61
+ console.log(`Current working directory: ${process.cwd()}`);
62
+ // console.log(`Environment variables: ${JSON.stringify(env, null, 2)}`);
63
+
64
+ // Spawn the command using `npm` with the given environment and current working directory.
65
+ spawn("npm", commandArr, {
66
+ cwd: path.join(__dirname, "../"),
67
+ env,
68
+ shell: true,
69
+ stdio: "inherit",
70
+ });
71
+ };
72
+
73
+ /**
74
+ * Handles the build process based on the given options.
75
+ *
76
+ * @param {boolean} prod - If true, runs the build with production environment.
77
+ * If false, runs the build with development environment.
78
+ */
79
+ const handleBuild = async (prod: boolean): Promise<void> => {
80
+ console.log(`Handling build with options: production=${prod}`);
81
+ if (prod) {
82
+ // Set production environment
83
+ process.env['NODE_ENV'] = 'production';
84
+ console.log("Running build with production environment");
85
+ // Run the build command
86
+ runCommand(['run', 'build-prod'], productionEnv);
87
+ } else {
88
+ console.log("Running build with development environment");
89
+ // Prompt the user to ask if they want to open the build in a browser tab
90
+ const { openInBrowser } = await inquirer.prompt([
91
+ {
92
+ type: 'confirm',
93
+ name: 'openInBrowser',
94
+ message: 'Do you want to open your build in a browser tab?',
95
+ default: false,
96
+ },
97
+ ]);
63
98
 
64
- if (!options.prod) {
65
- const rl = readline.createInterface({
66
- input: process.stdin,
67
- output: process.stdout
68
- });
69
- rl.question('Do you want open your build in a browser tab: Y/N ? ', function (ans) {
70
- console.log(`ANSWER ${ans}`)
71
- userChoice = ans;
72
- rl.close();
73
- });
74
-
75
- rl.on('close', function () {
76
- const commandArr = ['run', 'dev'];
77
- if (userChoice !== 'Y' && userChoice !== 'N') {
78
- return;
79
- }
80
- if (userChoice === 'Y') {
81
- const devIndex = commandArr.findIndex((val) => val === 'dev');
82
- commandArr[devIndex] = 'dev-puppeteer';
83
- }
84
- spawn("npm", commandArr, {
85
- cwd: path.join(__dirname, "../"),
86
- env: productionEnv,
87
- shell: true,
88
- stdio: "inherit",
89
- });
90
- process.exit(0);
91
- });
92
- } else {
93
- spawn("npm", ['run', 'dev'], {
94
- cwd: path.join(__dirname, "../"),
95
- env: productionEnv,
96
- shell: true,
97
- stdio: "inherit",
98
- });
99
+ console.log(`User opted for opening in browser: ${openInBrowser}`);
100
+ const commandArr = ['run', 'dev'];
101
+ if (openInBrowser) {
102
+ // If the user wants to open the build in a browser, run the build with
103
+ // puppeteer
104
+ commandArr[1] = 'dev-puppeteer';
99
105
  }
106
+
107
+ console.log(`Running command: ${commandArr.join(', ')}`);
108
+ // Run the build command
109
+ runCommand(commandArr, productionEnv);
100
110
  }
101
- }
111
+ };
102
112
 
113
+ // Command execution logic
103
114
  /**
104
- * Command Help
115
+ * Handles the command execution based on the given options.
116
+ *
117
+ * @returns {Promise<void>}
105
118
  */
106
- const printCommandHelp = () => {
107
- const help = getHelpInfo();
119
+ const executeCommand = async () => {
120
+ console.log("Entering executeCommand");
121
+ // Check if .env file is present
122
+ // Get the command options
123
+ const options = await setupCommander();
124
+
125
+ if (options.command !== 'init')
126
+ checkEnvFile();
127
+
128
+ console.log(`Options: ${JSON.stringify(options)}`);
129
+ /**
130
+ * Logs a message if verbose mode is enabled
131
+ * @param {string} message - The message to log
132
+ */
133
+ const verboseLog = (message: string) => {
134
+ if (options.verbose) {
135
+ console.log(`[VERBOSE] ${message}`);
136
+ }
137
+ };
138
+
139
+ switch (options.command) {
140
+ case "init":
141
+ // Initialize new .env file
142
+ verboseLog("Initializing new .env file");
143
+ runCommand(["init -y"], productionEnv);
144
+ setupEnv(process.cwd());
145
+ break;
146
+
147
+ case "new":
148
+ // Create new activity
149
+ verboseLog("Creating new activity");
150
+ runCommand(["run", "new-activity"], productionEnv);
151
+ break;
152
+
153
+ case "build":
154
+ // Build the application in production or development mode
155
+ verboseLog(`Building in ${options.prod ? 'production' : 'development'} mode`);
156
+ await handleBuild(options.prod);
157
+ break;
158
+
159
+ default:
160
+ // Print command help
161
+ printCommandHelp();
162
+ process.exit(0);
163
+ break;
164
+ }
165
+ console.log("Exiting executeCommand");
166
+ };
167
+
168
+ // Print command help
169
+ const printCommandHelp = async () => {
170
+ const help = await getHelpInfo();
108
171
  console.log(help);
172
+ process.exit(0);
109
173
  };
110
174
 
111
- const symbols = Object.keys(options);
175
+ /**
176
+ * Main program flow
177
+ *
178
+ * This function is the main entry point of the program. It attempts to execute
179
+ * the command specified by the user. If the command fails, it logs the error
180
+ * message and exits with code 1.
181
+ */
182
+ const main = async () => {
183
+ try {
184
+ // Execute the command specified by the user
185
+ await executeCommand();
186
+ } catch (error) {
187
+ // Log the error message if the command fails
188
+ console.error(error.message);
189
+ // Exit with code 1 if the command fails
190
+ process.exit(1);
191
+ }
192
+ };
112
193
 
113
194
  // Print help if no arguments
114
- if (symbols.length === 0) {
195
+ if (process.argv.length <= 2) {
115
196
  printCommandHelp();
116
- process.exit(0);
197
+ } else {
198
+ main();
117
199
  }
118
-
package/tsconfig.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "module": "commonjs",
4
- "target": "es2017",
3
+ "module": "CommonJS",
4
+ "moduleResolution": "Node",
5
+ "target": "ES2020",
5
6
  "lib": [
6
7
  "es2015"
7
8
  ],
8
- "moduleResolution": "node",
9
9
  "sourceMap": false,
10
10
  "outDir": "bin",
11
11
  "baseUrl": ".",
@@ -20,7 +20,9 @@
20
20
  },
21
21
  "emitDecoratorMetadata": true,
22
22
  "experimentalDecorators": true,
23
- "skipLibCheck": true
23
+ "skipLibCheck": true,
24
+ "esModuleInterop": true,
25
+ "resolveJsonModule": true,
24
26
  },
25
27
  "include": [
26
28
  "src/**/*",
package/webpack.config.js CHANGED
@@ -7,7 +7,7 @@ const TerserPlugin = require("terser-webpack-plugin");
7
7
  const ESLintPlugin = require('eslint-webpack-plugin');
8
8
  const postcssPresetEnv = require('postcss-preset-env');
9
9
  const AdobeTargetBuildGeneratorPlugin = require('./lib/at-build-generator');
10
- const commander = require("commander");
10
+ // const commander = require("commander");
11
11
 
12
12
  console.log(process.env.ACTIVITY_FOLDER_NAME)
13
13
 
@@ -28,15 +28,15 @@ if (process.env.NODE_ENV === PRODUCTION) {
28
28
  console.log("\x1b[36m%s\x1b[0m", "------ Running Development Build ------")
29
29
  }
30
30
 
31
- /**
32
- * commander
33
- */
34
- commander
35
- .version("1.0.0", "-v, --version")
36
- .option("-p, --path <value>", "Overwriting value.", process.cwd())
37
- .parse(process.argv);
31
+ // /**
32
+ // * commander
33
+ // */
34
+ // commander
35
+ // .version("1.0.0", "-v, --version")
36
+ // .option("-p, --path <value>", "Overwriting value.", process.cwd())
37
+ // .parse(process.argv);
38
38
 
39
- const options = commander.opts();
39
+ // const options = commander.opts();
40
40
 
41
41
  /**
42
42
  * Update folder name here if wanted to skip while transpilation
package/at-builder.zip DELETED
Binary file