hoosat-create 1.4.7 → 1.5.0

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 (4) hide show
  1. package/LICENSE.txt +16 -16
  2. package/README.md +167 -152
  3. package/index.js +256 -226
  4. package/package.json +31 -23
package/LICENSE.txt CHANGED
@@ -1,17 +1,17 @@
1
- ISC License
2
-
3
- Copyright 2023 Hoosat Oy
4
-
5
- Permission to use, copy, modify, and/or distribute this software
6
- for any purpose with or without fee is hereby granted, provided
7
- that the above copyright notice and this permission notice appear
8
- in all copies.
9
-
10
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
11
- WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
12
- WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
13
- AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
14
- CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
15
- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
16
- NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1
+ ISC License
2
+
3
+ Copyright 2023 Hoosat Oy
4
+
5
+ Permission to use, copy, modify, and/or distribute this software
6
+ for any purpose with or without fee is hereby granted, provided
7
+ that the above copyright notice and this permission notice appear
8
+ in all copies.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
11
+ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
12
+ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
13
+ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
14
+ CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
15
+ OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
16
+ NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
17
17
  CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,152 +1,167 @@
1
- # Hoosat Create
2
-
3
- Hoosat create is a `npx` script that creates React 18.2 full-stack server side rendering ESM project for you, where you can use Typescript to build web applications. It uses [@Hoosat-Oy/hoosat-template](https://github.com/Hoosat-Oy/hoosat-template) to build React project with SSR and Typescript.
4
-
5
- ## Command to run
6
-
7
- ```
8
- npx hoosat-create@latest
9
- ```
10
-
11
- ### Commandline arguments
12
- - `submodule`
13
- - `--destination`
14
- - `--author`
15
- - `--license`
16
- - `--keywords`
17
- - `--keywoordsList`
18
- - `--gitInit`
19
- - `--hoosatui`
20
-
21
- For example:
22
-
23
- ```
24
- npx hoosat-create@latest --destination "new_project" --author "Toni Lukkaroinen" --gitInit Y --hoosatui Y
25
- ```
26
-
27
- Now it will ask the rest like `license` in the process. Which you can default just by pressing enter.
28
-
29
- ### Submodule creation
30
-
31
- The following command creates an empty git submodule for you to start working on code that will be shared with another project later.
32
- ```
33
- npx hoosat-create@latest submodule --destination "src/client/submodule"
34
- ```
35
-
36
- ## Technologies Used
37
-
38
- - React-helmet-async 1.3
39
- - React 18.2
40
- - TypeScript 4.9.2
41
- - Webpack 5
42
- - Jest 27
43
-
44
- ## Features
45
-
46
- - Full-stack TypeScript application using React and Node HTTP/HTTPS.
47
- - Includes working server side SEO with `react-helmet-async`
48
- - Supports ES modules for server-side and client-side ```.
49
- - Configured with Webpack for production builds.
50
- - Includes Jest for unit testing.
51
- - Includes example components and routes for getting started.
52
- - Includes HoosatUI as optional dependancy as git submodule.
53
-
54
- ## Scripts
55
-
56
- - `npm run dev`: Builds and runs the development version.
57
- - This script concurrently executes the following commands:
58
- - `npm run dev:build:client`: Builds the client in development mode and watches for file changes.
59
- - `npm run dev:build:server`: Builds the server in development mode and watches for file changes.
60
- - `npm run dev:run`: Starts the server with Nodemon to automatically restart it on file changes.
61
-
62
- - `npm run build`: Builds the production version.
63
- - This script sequentially executes the following commands:
64
- - `npm run build:client`: Builds the client in production mode.
65
- - `npm run build:server`: Builds the server in production mode.
66
-
67
- - `npm run start`: Runs the production version.
68
- - This script starts the server using the compiled production files.
69
-
70
- - `npm run test`: Runs test units with Jest.
71
- - This script executes the test units using Jest.
72
-
73
- ## File structure
74
-
75
- - `src/client`: Contains client-side ``` (React components, styles, etc.).
76
- - `src/server`: Contains server-side ``` (Node HTTP/HTTPS routes, API routes, etc.).
77
- - `src/common`: Contains common ```.
78
- - `public`: Contains the bundle.js client ``` and public files for the project.
79
- - `dist`: Contains production build output of server.
80
-
81
- ## Node HTTP/HTTP server with server side router.
82
-
83
- `src/server/core/server.ts` contains the source ```, it supports middlewares, wildcard routes and specific routes. There are middlewares currently for setting cors and static files.
84
-
85
- ### Basic example
86
-
87
- ```
88
- import { createRouter, createServer, listen } from './core/server';
89
- import { cors } from './core/cors';
90
- import { assets } from './core/assets';
91
- // Creating the router
92
- const router = createRouter();
93
-
94
- // Adding static file middleware
95
- router.Middleware(assets("./public"));
96
-
97
- // Creating a ping route
98
- // For request and response we dont use wrappers for node http types and methods.
99
- router.Get("/ping", (req: HoosatRequest, res: HoosatResponse) => {
100
- res.status(200).json("pong!");
101
- });
102
-
103
- // Now that the middleware and routes have been set the server must be created that handles the routes.
104
- const server = createServer(router);
105
-
106
- // Start listening on port 3000
107
- const port = parseInt(process.env.PORT || "8080");
108
- listen(server, port, () => {
109
- console.log(`Server is running on port ${port.toString()}`);
110
- });
111
- ```
112
-
113
-
114
- ## License
115
- This template is licensed under the ISC License. Feel free to use it for your own projects or as a starting point for your own templates.
116
-
117
- ## Message
118
-
119
- I just dropped some dependancies from the repository and this will keep happening. With our own ``` we can keep it up to date with React and Node versions more easily.
120
- Though for now the only goal seems to be to drop `react-helmet-async`.
121
-
122
- ## Release changes
123
-
124
- ### 1.4.5 -> 1.4.6
125
- - Use submodule for server, make cloning of template recursive.
126
-
127
- ### 1.4.4 -> 1.4.5
128
- - One small document change in server code example, to make your life easier.
129
- - Add support for command line arguments.
130
- - Add support for npx hoosat-create submodule
131
-
132
- ### 1.4.3 -> 1.4.4
133
- - Why the heck I removed that #!/usr/bin/env node.. Now it's back.
134
-
135
- ### 1.4.2 -> 1.4.3
136
- - Update package.json to contain metadata
137
-
138
- ### 1.4.1 -> 1.4.2
139
- - Remove download-git-repo dependancy from hoosat-create
140
- - Do input validation in hoosat-create. Which means following characters do not work in project name.
141
- - ';', '|', '&&', '>', '<', '`', '$(', '$()'
142
-
143
- ### 1.4.0 -> 1.4.1
144
- - Changed createServer to include options argument for changing server protocol and to include SSL certificate information.
145
- - JSDoc has been added and more documentation work.
146
-
147
- ### 1.3.5 -> 1.4.0
148
- - Dropped Express.js and Babel from dependancies.
149
- - Updated package.json scripts to use concurrently and nodemon.
150
-
151
- ## Join us
152
- [https://discord.gg/UXPFcPaPBg](Discord)
1
+ # Hoosat Create
2
+
3
+ Hoosat create is a `npx` script that creates React 19 full-stack server side rendering ESM project for you, where you can use Typescript to build web applications. It uses [@Hoosat-Oy/hoosat-template](https://github.com/Hoosat-Oy/hoosat-template) to build React project with SSR and Typescript.
4
+
5
+ ## Requirements
6
+
7
+ Node.js 22, 24 or 26 (any supported LTS line). Node.js 20 and older are end-of-life and not supported. Git is needed for cloning the template.
8
+
9
+ ## Command to run
10
+
11
+ ```
12
+ npx hoosat-create@latest
13
+ ```
14
+
15
+ ### Commandline arguments
16
+ - `submodule`
17
+ - `--destination`
18
+ - `--author`
19
+ - `--license`
20
+ - `--keywords`
21
+ - `--keywoordsList`
22
+ - `--gitInit`
23
+ - `--hoosatui`
24
+
25
+ For example:
26
+
27
+ ```
28
+ npx hoosat-create@latest --destination "new_project" --author "Toni Lukkaroinen" --gitInit Y --hoosatui Y
29
+ ```
30
+
31
+ Now it will ask the rest like `license` in the process. Which you can default just by pressing enter.
32
+
33
+ ### Submodule creation
34
+
35
+ The following command creates an empty git submodule for you to start working on code that will be shared with another project later.
36
+ ```
37
+ npx hoosat-create@latest submodule --destination "src/client/submodule"
38
+ ```
39
+
40
+ ## Technologies Used
41
+
42
+ - React 19
43
+ - React Router 8
44
+ - React-helmet-async 3
45
+ - i18next 27 / react-i18next 18
46
+ - TypeScript 6
47
+ - Webpack 5
48
+ - Jest 30
49
+
50
+ ## Features
51
+
52
+ - Full-stack TypeScript application using React and Node HTTP/HTTPS.
53
+ - Includes working server side SEO with `react-helmet-async`
54
+ - Supports ES modules for server-side and client-side ```.
55
+ - Configured with Webpack for production builds.
56
+ - Includes Jest for unit testing.
57
+ - Includes example components and routes for getting started.
58
+ - Includes HoosatUI as optional dependancy as git submodule.
59
+
60
+ ## Scripts
61
+
62
+ - `npm run dev`: Builds and runs the development version.
63
+ - This script concurrently executes the following commands:
64
+ - `npm run dev:build:client`: Builds the client in development mode and watches for file changes.
65
+ - `npm run dev:build:server`: Builds the server in development mode and watches for file changes.
66
+ - `npm run dev:run`: Starts the server with Nodemon to automatically restart it on file changes.
67
+
68
+ - `npm run build`: Builds the production version.
69
+ - This script sequentially executes the following commands:
70
+ - `npm run build:client`: Builds the client in production mode.
71
+ - `npm run build:server`: Builds the server in production mode.
72
+
73
+ - `npm run start`: Runs the production version.
74
+ - This script starts the server using the compiled production files.
75
+
76
+ - `npm run test`: Runs test units with Jest.
77
+ - This script executes the test units using Jest.
78
+
79
+ ## File structure
80
+
81
+ - `src/client`: Contains client-side ``` (React components, styles, etc.).
82
+ - `src/server`: Contains server-side ``` (Node HTTP/HTTPS routes, API routes, etc.).
83
+ - `src/common`: Contains common ```.
84
+ - `public`: Contains the bundle.js client ``` and public files for the project.
85
+ - `dist`: Contains production build output of server.
86
+
87
+ ## Node HTTP/HTTP server with server side router.
88
+
89
+ `src/server/core/server.ts` contains the source ```, it supports middlewares, wildcard routes and specific routes. There are middlewares currently for setting cors and static files.
90
+
91
+ ### Basic example
92
+
93
+ ```
94
+ import { createRouter, createServer, listen } from './core/server';
95
+ import { cors } from './core/cors';
96
+ import { assets } from './core/assets';
97
+ // Creating the router
98
+ const router = createRouter();
99
+
100
+ // Adding static file middleware
101
+ router.Middleware(assets("./public"));
102
+
103
+ // Creating a ping route
104
+ // For request and response we dont use wrappers for node http types and methods.
105
+ router.Get("/ping", (req: HoosatRequest, res: HoosatResponse) => {
106
+ res.status(200).json("pong!");
107
+ });
108
+
109
+ // Now that the middleware and routes have been set the server must be created that handles the routes.
110
+ const server = createServer(router);
111
+
112
+ // Start listening on port 3000
113
+ const port = parseInt(process.env.PORT || "8080");
114
+ listen(server, port, () => {
115
+ console.log(`Server is running on port ${port.toString()}`);
116
+ });
117
+ ```
118
+
119
+
120
+ ## License
121
+ This template is licensed under the ISC License. Feel free to use it for your own projects or as a starting point for your own templates.
122
+
123
+ ## Message
124
+
125
+ I just dropped some dependancies from the repository and this will keep happening. With our own ``` we can keep it up to date with React and Node versions more easily.
126
+ Though for now the only goal seems to be to drop `react-helmet-async`.
127
+
128
+ ## Release changes
129
+
130
+ ### 1.4.7 -> 1.5.0
131
+ - Requires Node.js 22 or newer (Node.js 20 is end-of-life), template is tested on Node.js 22, 24 and 26.
132
+ - Clone the template and its submodule over HTTPS, so no GitHub SSH key is needed.
133
+ - Run git and npm without a shell and with argument lists, so project names can not be interpreted as shell commands.
134
+ - Fix `--gitInit n` and `--hoosatui n` being treated as yes.
135
+ - Stop when cloning the template fails instead of continuing in the wrong directory.
136
+ - Fix `submodule` command on Windows and with git 2.38.1+.
137
+ - Template: React 19, React Router 8, TypeScript 6, Jest 30, i18next 27, security fixes in server core and all dependency vulnerabilities resolved.
138
+
139
+ ### 1.4.5 -> 1.4.6
140
+ - Use submodule for server, make cloning of template recursive.
141
+
142
+ ### 1.4.4 -> 1.4.5
143
+ - One small document change in server code example, to make your life easier.
144
+ - Add support for command line arguments.
145
+ - Add support for npx hoosat-create submodule
146
+
147
+ ### 1.4.3 -> 1.4.4
148
+ - Why the heck I removed that #!/usr/bin/env node.. Now it's back.
149
+
150
+ ### 1.4.2 -> 1.4.3
151
+ - Update package.json to contain metadata
152
+
153
+ ### 1.4.1 -> 1.4.2
154
+ - Remove download-git-repo dependancy from hoosat-create
155
+ - Do input validation in hoosat-create. Which means following characters do not work in project name.
156
+ - ';', '|', '&&', '>', '<', '`', '$(', '$()'
157
+
158
+ ### 1.4.0 -> 1.4.1
159
+ - Changed createServer to include options argument for changing server protocol and to include SSL certificate information.
160
+ - JSDoc has been added and more documentation work.
161
+
162
+ ### 1.3.5 -> 1.4.0
163
+ - Dropped Express.js and Babel from dependancies.
164
+ - Updated package.json scripts to use concurrently and nodemon.
165
+
166
+ ## Join us
167
+ [https://discord.gg/UXPFcPaPBg](Discord)
package/index.js CHANGED
@@ -1,226 +1,256 @@
1
- #!/usr/bin/env node
2
- import fs from 'fs';
3
- import { spawn } from 'child_process';
4
- import { createInterface } from 'readline';
5
- import { readFileSync, writeFileSync } from 'fs';
6
- import { join } from 'path';
7
-
8
- const repository = 'https://github.com/Hoosat-Oy/hoosat-template.git';
9
- const rl = createInterface({
10
- input: process.stdin,
11
- output: process.stdout
12
- });
13
-
14
- async function run() {
15
- const command = process.argv[2];
16
-
17
- if (command === 'submodule') {
18
- console.log('Creating a submodule for project.');
19
- const rootDirectory = process.cwd();
20
- //const name = getValueFromArgument('name') || (await askQuestion('Enter name for new submodule: '));
21
- const destination = getValueFromArgument('destination') || (await askQuestion('Enter relative destination for new submodule: '));
22
- try {
23
- await runCommand(`git rev-parse --is-inside-work-tree`, "Current working directory is not git repository.");
24
- } catch (error) {
25
- console.error(error.message);
26
- throw error;
27
- }
28
- // mkdir submodule-destination
29
- try {
30
- await fs.promises.mkdir(destination, { recursive: true });
31
- console.log("Created submodule folder.");
32
- } catch (error) {
33
- console.error(error.message);
34
- }
35
- // cd submodule-destination
36
- // git init
37
- // cd back to root of project
38
- // git commit -m 'Added empty submodule'
39
- process.chdir(destination);
40
- try {
41
- await runCommand(`git init`, 'Failed to initialize git for submodule.');
42
- console.log("Initialized git repository.");
43
- } catch (error) {
44
- console.error(error, error.message);
45
- }
46
- try {
47
- await runCommand(`touch ./README.md`, 'Failed to create README.md file');
48
- console.log("CreatedREADME.md file for commit.");
49
- } catch (error) {
50
- console.error(error.message);
51
- }
52
- try {
53
- await runCommand(`git add ./README.md`, 'Failed to stage README.md.');
54
- console.log("Staged README.md");
55
- } catch (error) {
56
- console.error(error.message);
57
- }
58
- try {
59
- await runCommand(`git commit -m 'Add readme.'`, 'Failed to commit.');
60
- console.log("Committed readme.");
61
- } catch (error) {
62
- console.error(error.message);
63
- }
64
- // Change back to the root of the project
65
- process.chdir(rootDirectory);
66
- // git submodule add ./submodule-destination submodule-name
67
- try {
68
- await runCommand(`git submodule add ./${destination}`, 'Failed to add the new local repository as git submodule');
69
- console.log("Added local repository as git submodule to parent git repository.");
70
- } catch (error) {
71
- console.error(error, error.message);
72
- }
73
- // git commit -m 'Added empty submodule'
74
- // try {
75
- // await runCommand(`git commit -m 'Added ${name} submodule into ${destination}'`, 'Failed to commit changes, do it manually');
76
- // console.log("Committed changes in parent repository.");
77
- // } catch (error) {
78
- // console.error(error, error.message);
79
- // }
80
- console.log("Now commit your changes to git.");
81
- rl.close();
82
- } else {
83
- console.log('Creating a new project from Hoosat React SSR Template.');
84
- const destination = getValueFromArgument('destination') || (await askQuestion('Enter destination project name: '));
85
- const description = getValueFromArgument('description') || (await askQuestion('Enter project description: '));
86
- const author = getValueFromArgument('author') || (await askQuestion('Enter project author: '));
87
- const license = getValueFromArgument('license') || (await askQuestion('Enter project license: '));
88
- const keywords = getValueFromArgument('keywords') || (await askQuestion('Enter project keywords (comma-separated): '));
89
- const keywordList = keywords.split(',').map(k => k.trim()).filter(k => k !== '');
90
- const gitInit = getValueFromArgument('gitInit') || (await askYesNoQuestion('Do you want to initialize a git repository? [Y/n] '));
91
- let installHoosatUI = undefined;
92
- if (gitInit) {
93
- installHoosatUI = getValueFromArgument('hoosatui') || await askYesNoQuestion('Do you want to install HoosatUI? [Y/n] ');
94
- }
95
- try {
96
- // Clone git repository.
97
- try {
98
- await runCommand(`git clone --recursive ${repository} ${destination}`, 'Failed to clone project.', { stdio: 'inherit' });
99
- console.log('Project cloned successfully.');
100
- } catch (error) {
101
- console.error(error.message);
102
- }
103
- // Change directory to the project directory
104
- process.chdir(destination);
105
- // Modify the package.json
106
- const packageJsonPath = join(process.cwd(), 'package.json');
107
- const packageJsonContent = readFileSync(packageJsonPath, 'utf8');
108
- const packageJson = JSON.parse(packageJsonContent);
109
- packageJson.name = destination;
110
- packageJson.description = description;
111
- packageJson.author = author;
112
- packageJson.license = license;
113
- packageJson.keywords = keywordList;
114
- writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
115
- console.log('Project package.json has been modified.');
116
- // Do NPM install for dependencies.
117
- try {
118
- await runCommand('npm install', 'Failed to install project template dependencies.', { stdio: 'inherit' });
119
- console.log('Project template dependancies installed with npm.');
120
- } catch (error) {
121
- console.error(error.message);
122
- }
123
- if (gitInit) {
124
- // Initialize git repository
125
- try {
126
- await runCommand('git init', 'Failed to initialize git repository.', { stdio: 'inherit' });
127
- await runCommand('git remote rm origin', 'Failed to remove origin remote from git repository.', { stdio: 'inherit' });
128
- console.log('Git has been initialized.');
129
- } catch (error) {
130
- console.error(error.message);
131
- }
132
- console.log('Git repository initialized.');
133
- if (installHoosatUI) {
134
- // Change directory to the client directory
135
- process.chdir('src/client');
136
- // Clone HoosatUI repository
137
- try {
138
- await runCommand('git submodule add https://github.com/hoosat-oy/HoosatUI', 'Failed to add submodule HoosatUI.', { stdio: 'inherit' });
139
- console.log('HoosatUI cloned successfully as submodule in src/client/HoosatUI.');
140
- } catch (error) {
141
- console.error(error.message);
142
- }
143
- // Install necessary dev-dependencies
144
- try {
145
- await runCommand('npm install --save-dev @testing-library/jest-dom @testing-library/react', 'Failed to install HoosatUI devDependancies.', { stdio: 'inherit' });
146
- console.log('npm HoosatUI devDependencies installed successfully.');
147
- } catch (error) {
148
- console.error(error.message);
149
- }
150
- // Install necessary dependencies.
151
- try {
152
- await runCommand('npm install react-markdown rehype-highlight remark-gfm', 'Failed to install HoosatUI dependencies.', { stdio: 'inherit' });
153
- console.log('npm HoosatUI dependencies installed successfully.');
154
- } catch (error) {
155
- console.error(error.message);
156
- }
157
- }
158
- }
159
- } catch (err) {
160
- console.error(`Failed to clone project: ${err}`);
161
- } finally {
162
- rl.close();
163
- }
164
- }
165
- }
166
-
167
- async function runCommand(commandString, errorMessage, spawnOptions) {
168
- return new Promise((resolve, reject) => {
169
- const commandProcess = spawn(commandString, [], { shell: true, ...spawnOptions });
170
- commandProcess.on('close', code => {
171
- if (code === 0) {
172
- resolve();
173
- } else {
174
- reject(new Error(commandString + "\r\n" + errorMessage));
175
- }
176
- });
177
- });
178
- }
179
-
180
-
181
- function getValueFromArgument(argName) {
182
- const argIndex = process.argv.findIndex(arg => arg === `--${argName}`);
183
- if (argIndex !== -1 && argIndex + 1 < process.argv.length) {
184
- return process.argv[argIndex + 1];
185
- }
186
- return undefined;
187
- }
188
-
189
- function askQuestion(question) {
190
- return new Promise((resolve, reject) => {
191
- rl.question(question, answer => {
192
- if (!containsInvalidCharacters(answer)) {
193
- resolve(answer);
194
- } else {
195
- reject(new Error('Invalid input. The answer contains invalid characters.'));
196
- }
197
- });
198
- });
199
- }
200
-
201
- function askYesNoQuestion(question) {
202
- return new Promise((resolve, reject) => {
203
- rl.question(question, answer => {
204
- const normalizedAnswer = answer.trim().toLowerCase();
205
- if (normalizedAnswer === '' || normalizedAnswer === 'y' || normalizedAnswer === 'yes') {
206
- resolve(true);
207
- } else if (normalizedAnswer === 'n' || normalizedAnswer === 'no') {
208
- resolve(false);
209
- } else {
210
- reject(new Error('Invalid input. Please provide a valid yes/no answer (Y/n).'));
211
- }
212
- });
213
- });
214
- }
215
-
216
- function containsInvalidCharacters(input) {
217
- // Define the list of invalid characters or commands
218
- const invalidCharacters = [';', '|', '&&', '>', '<', '`', '$(', '$()'];
219
- // Check if the input contains any invalid characters or commands
220
- return invalidCharacters.some(character => input.includes(character));
221
- }
222
-
223
- run();
224
-
225
- // Export the askQuestion function for testing purposes
226
- export default { askQuestion };
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import { spawn } from 'node:child_process';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { join } from 'node:path';
6
+
7
+ const repository = 'https://github.com/TMKCodes/hoosat-template.git';
8
+ const hoosatUIRepository = 'https://github.com/hoosat-oy/HoosatUI';
9
+ const minimumNodeMajor = 22;
10
+
11
+ const rl = createInterface({
12
+ input: process.stdin,
13
+ output: process.stdout
14
+ });
15
+
16
+ async function run() {
17
+ const nodeMajor = Number(process.versions.node.split('.')[0]);
18
+ if (nodeMajor < minimumNodeMajor) {
19
+ console.warn(`Warning: Node.js ${process.versions.node} is not supported anymore. Please use Node.js ${minimumNodeMajor} or newer (https://nodejs.org).`);
20
+ }
21
+
22
+ const command = process.argv[2];
23
+
24
+ if (command === 'submodule') {
25
+ console.log('Creating a submodule for project.');
26
+ const rootDirectory = process.cwd();
27
+ const destination = getValueFromArgument('destination') || (await askQuestion('Enter relative destination for new submodule: '));
28
+ try {
29
+ await runCommand('git', ['rev-parse', '--is-inside-work-tree'], 'Current working directory is not git repository.');
30
+ } catch (error) {
31
+ console.error(error.message);
32
+ throw error;
33
+ }
34
+ // mkdir submodule-destination
35
+ try {
36
+ await fs.promises.mkdir(destination, { recursive: true });
37
+ console.log("Created submodule folder.");
38
+ } catch (error) {
39
+ console.error(error.message);
40
+ }
41
+ // cd submodule-destination, git init, commit a README and cd back to root of project
42
+ process.chdir(destination);
43
+ try {
44
+ await runCommand('git', ['init'], 'Failed to initialize git for submodule.');
45
+ console.log("Initialized git repository.");
46
+ } catch (error) {
47
+ console.error(error.message);
48
+ }
49
+ try {
50
+ if (!fs.existsSync('./README.md')) {
51
+ fs.writeFileSync('./README.md', '');
52
+ }
53
+ console.log("Created README.md file for commit.");
54
+ } catch (error) {
55
+ console.error('Failed to create README.md file', error.message);
56
+ }
57
+ try {
58
+ await runCommand('git', ['add', './README.md'], 'Failed to stage README.md.');
59
+ console.log("Staged README.md");
60
+ } catch (error) {
61
+ console.error(error.message);
62
+ }
63
+ try {
64
+ await runCommand('git', ['commit', '-m', 'Add readme.'], 'Failed to commit.');
65
+ console.log("Committed readme.");
66
+ } catch (error) {
67
+ console.error(error.message);
68
+ }
69
+ // Change back to the root of the project
70
+ process.chdir(rootDirectory);
71
+ // git submodule add ./submodule-destination submodule-destination
72
+ // Giving the path registers the existing repository in place. Without it git tries to clone it
73
+ // over the "file" transport, which git 2.38.1+ blocks by default (CVE-2022-39253).
74
+ try {
75
+ await runCommand('git', ['submodule', 'add', `./${destination}`, destination], 'Failed to add the new local repository as git submodule');
76
+ console.log("Added local repository as git submodule to parent git repository.");
77
+ } catch (error) {
78
+ console.error(error.message);
79
+ }
80
+ console.log("Now commit your changes to git.");
81
+ rl.close();
82
+ } else {
83
+ console.log('Creating a new project from Hoosat React SSR Template.');
84
+ const destination = getValueFromArgument('destination') || (await askQuestion('Enter destination project name: '));
85
+ const description = getValueFromArgument('description') || (await askQuestion('Enter project description: '));
86
+ const author = getValueFromArgument('author') || (await askQuestion('Enter project author: '));
87
+ const license = getValueFromArgument('license') || (await askQuestion('Enter project license: '));
88
+ const keywords = getValueFromArgument('keywords') || (await askQuestion('Enter project keywords (comma-separated): '));
89
+ const keywordList = keywords.split(',').map(k => k.trim()).filter(k => k !== '');
90
+ const gitInit = getYesNoFromArgument('gitInit') ?? (await askYesNoQuestion('Do you want to initialize a git repository? [Y/n] '));
91
+ let installHoosatUI = false;
92
+ if (gitInit) {
93
+ installHoosatUI = getYesNoFromArgument('hoosatui') ?? (await askYesNoQuestion('Do you want to install HoosatUI? [Y/n] '));
94
+ }
95
+ try {
96
+ // Clone git repository.
97
+ await runCommand('git', ['clone', '--recursive', repository, destination], 'Failed to clone project.', { stdio: 'inherit' });
98
+ console.log('Project cloned successfully.');
99
+ // Change directory to the project directory
100
+ process.chdir(destination);
101
+ // Modify the package.json
102
+ const packageJsonPath = join(process.cwd(), 'package.json');
103
+ const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf8');
104
+ const packageJson = JSON.parse(packageJsonContent);
105
+ packageJson.name = destination;
106
+ packageJson.description = description;
107
+ packageJson.author = author;
108
+ packageJson.license = license;
109
+ packageJson.keywords = keywordList;
110
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n');
111
+ console.log('Project package.json has been modified.');
112
+ // Do NPM install for dependencies.
113
+ try {
114
+ await runCommand('npm', ['install'], 'Failed to install project template dependencies.', { stdio: 'inherit' });
115
+ console.log('Project template dependencies installed with npm.');
116
+ } catch (error) {
117
+ console.error(error.message);
118
+ }
119
+ if (gitInit) {
120
+ // Initialize git repository
121
+ try {
122
+ await runCommand('git', ['init'], 'Failed to initialize git repository.', { stdio: 'inherit' });
123
+ await runCommand('git', ['remote', 'rm', 'origin'], 'Failed to remove origin remote from git repository.', { stdio: 'inherit' });
124
+ console.log('Git has been initialized.');
125
+ } catch (error) {
126
+ console.error(error.message);
127
+ }
128
+ console.log('Git repository initialized.');
129
+ if (installHoosatUI) {
130
+ // Change directory to the client directory
131
+ process.chdir('src/client');
132
+ // Clone HoosatUI repository
133
+ try {
134
+ await runCommand('git', ['submodule', 'add', hoosatUIRepository], 'Failed to add submodule HoosatUI.', { stdio: 'inherit' });
135
+ console.log('HoosatUI cloned successfully as submodule in src/client/HoosatUI.');
136
+ } catch (error) {
137
+ console.error(error.message);
138
+ }
139
+ // Install necessary dev-dependencies
140
+ try {
141
+ await runCommand('npm', ['install', '--save-dev', '@testing-library/jest-dom', '@testing-library/react', '@testing-library/dom'], 'Failed to install HoosatUI devDependencies.', { stdio: 'inherit' });
142
+ console.log('npm HoosatUI devDependencies installed successfully.');
143
+ } catch (error) {
144
+ console.error(error.message);
145
+ }
146
+ // Install necessary dependencies.
147
+ try {
148
+ await runCommand('npm', ['install', 'react-markdown', 'rehype-highlight', 'remark-gfm'], 'Failed to install HoosatUI dependencies.', { stdio: 'inherit' });
149
+ console.log('npm HoosatUI dependencies installed successfully.');
150
+ } catch (error) {
151
+ console.error(error.message);
152
+ }
153
+ }
154
+ }
155
+ } catch (err) {
156
+ console.error(`Failed to create project: ${err.message}`);
157
+ process.exitCode = 1;
158
+ } finally {
159
+ rl.close();
160
+ }
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Runs a command without a shell, so arguments (like the project name) can never be
166
+ * interpreted as shell syntax. Only npm on Windows needs a shell, because it is a .cmd file
167
+ * and Node.js refuses to spawn those without one; its arguments are always static strings here.
168
+ */
169
+ function runCommand(command, args, errorMessage, spawnOptions = {}) {
170
+ const needsShell = process.platform === 'win32' && command === 'npm';
171
+ return new Promise((resolve, reject) => {
172
+ const commandProcess = needsShell
173
+ ? spawn([command, ...args].join(' '), { ...spawnOptions, shell: true })
174
+ : spawn(command, args, { ...spawnOptions, shell: false });
175
+ const fail = (reason) => reject(new Error(`${command} ${args.join(' ')}\r\n${errorMessage}${reason ? ` (${reason})` : ''}`));
176
+ commandProcess.on('error', (error) => fail(error.message));
177
+ commandProcess.on('close', code => {
178
+ if (code === 0) {
179
+ resolve();
180
+ } else {
181
+ fail(`exit code ${code}`);
182
+ }
183
+ });
184
+ });
185
+ }
186
+
187
+ function getValueFromArgument(argName) {
188
+ const argIndex = process.argv.findIndex(arg => arg === `--${argName}`);
189
+ if (argIndex !== -1 && argIndex + 1 < process.argv.length) {
190
+ const value = process.argv[argIndex + 1];
191
+ if (containsInvalidCharacters(value)) {
192
+ throw new Error(`Invalid value for --${argName}. The value contains invalid characters.`);
193
+ }
194
+ return value;
195
+ }
196
+ return undefined;
197
+ }
198
+
199
+ /**
200
+ * Reads a yes/no command line argument, for example `--gitInit Y` or `--gitInit n`.
201
+ * @returns {boolean | undefined} undefined when the argument was not given.
202
+ */
203
+ function getYesNoFromArgument(argName) {
204
+ const value = getValueFromArgument(argName);
205
+ if (value === undefined) {
206
+ return undefined;
207
+ }
208
+ const answer = parseYesNo(value);
209
+ if (answer === undefined) {
210
+ throw new Error(`Invalid value for --${argName}. Please provide a valid yes/no answer (Y/n).`);
211
+ }
212
+ return answer;
213
+ }
214
+
215
+ function parseYesNo(value) {
216
+ const normalized = value.trim().toLowerCase();
217
+ if (normalized === '' || normalized === 'y' || normalized === 'yes' || normalized === 'true') {
218
+ return true;
219
+ }
220
+ if (normalized === 'n' || normalized === 'no' || normalized === 'false') {
221
+ return false;
222
+ }
223
+ return undefined;
224
+ }
225
+
226
+ async function askQuestion(question) {
227
+ const answer = await rl.question(question);
228
+ if (containsInvalidCharacters(answer)) {
229
+ throw new Error('Invalid input. The answer contains invalid characters.');
230
+ }
231
+ return answer;
232
+ }
233
+
234
+ async function askYesNoQuestion(question) {
235
+ const answer = parseYesNo(await rl.question(question));
236
+ if (answer === undefined) {
237
+ throw new Error('Invalid input. Please provide a valid yes/no answer (Y/n).');
238
+ }
239
+ return answer;
240
+ }
241
+
242
+ function containsInvalidCharacters(input) {
243
+ // Define the list of invalid characters or commands
244
+ const invalidCharacters = [';', '|', '&&', '>', '<', '`', '$(', '$()'];
245
+ // Check if the input contains any invalid characters or commands
246
+ return invalidCharacters.some(character => input.includes(character));
247
+ }
248
+
249
+ run().catch((error) => {
250
+ console.error(error.message);
251
+ rl.close();
252
+ process.exitCode = 1;
253
+ });
254
+
255
+ // Export the askQuestion function for testing purposes
256
+ export default { askQuestion };
package/package.json CHANGED
@@ -1,23 +1,31 @@
1
- {
2
- "name": "hoosat-create",
3
- "type": "module",
4
- "version": "1.4.7",
5
- "description": "Hoosat - React & Typescript SSR project template.",
6
- "homepage": "https://example.com",
7
- "author": "Toni Lukkaroinen @ Hoosat Oy",
8
- "license": "ISC",
9
- "bugs": {
10
- "url": "https://github.com/Hoosat-Oy/hoosat-create/issues"
11
- },
12
- "repository": {
13
- "type": "git",
14
- "url": "https://github.com/Hoosat-Oy/hoosat-create"
15
- },
16
- "main": "index.js",
17
- "bin": {
18
- "hoosat-create": "index.js"
19
- },
20
- "scripts": {
21
- "test": "node index.js"
22
- }
23
- }
1
+ {
2
+ "name": "hoosat-create",
3
+ "type": "module",
4
+ "version": "1.5.0",
5
+ "description": "Hoosat - React & Typescript SSR project template.",
6
+ "homepage": "https://example.com",
7
+ "author": "Toni Lukkaroinen @ Hoosat Oy",
8
+ "license": "ISC",
9
+ "bugs": {
10
+ "url": "https://github.com/Hoosat-Oy/hoosat-create/issues"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/Hoosat-Oy/hoosat-create.git"
15
+ },
16
+ "engines": {
17
+ "node": ">=22"
18
+ },
19
+ "main": "index.js",
20
+ "bin": {
21
+ "hoosat-create": "index.js"
22
+ },
23
+ "files": [
24
+ "index.js",
25
+ "README.md",
26
+ "LICENSE.txt"
27
+ ],
28
+ "scripts": {
29
+ "test": "node index.js"
30
+ }
31
+ }