ubuntu-service-create 1.0.0 → 2.0.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.
package/README.md CHANGED
@@ -1,67 +1,85 @@
1
1
  # ubuntu-service-create
2
2
 
3
- [![npm version](https://img.shields.io/badge/npm-v1.0.0-orange.svg)](https://www.npmjs.com/package/ubuntu-service-create)
3
+ [![npm version](https://img.shields.io/badge/npm-v2.0.0-orange.svg)](https://www.npmjs.com/package/ubuntu-service-create)
4
4
  [![License: ISC](https://img.shields.io/badge/License-ISC-green.svg)](https://opensource.org/licenses/ISC)
5
5
  [![Docs Hub](https://img.shields.io/badge/docs-ubuntu--service--docs-sky.svg)](https://keshavsoft.github.io/ubuntu-service-docs/)
6
6
  [![Organization](https://img.shields.io/badge/org-KeshavSoft-purple.svg)](https://github.com/keshavsoft)
7
7
  [![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org)
8
8
 
9
- > **Author, validate, and write standard Ubuntu systemd service unit files matching KeshavSoft VPS conventions.**
10
- > The creation & birth engine of the `ubuntu-service` single-service family.
9
+ > **Strictly guarded systemd service unit author & creator for KeshavSoft VPS Node.js applications.**
10
+ > Ensures zero-conflict, `.env`-driven creation of `/etc/systemd/system/<subdomain>.service` files.
11
11
 
12
12
  ---
13
13
 
14
- ## 🎯 Purpose in the Service Lifecycle
14
+ ## 🎯 Architecture: V1 vs V2
15
15
 
16
- When deploying an application on an Ubuntu VPS, the lifecycle consists of four decoupled steps:
16
+ | Feature | V1 (Baseline) | V2 (Guarded & Production) |
17
+ | :--- | :--- | :--- |
18
+ | **Philosophy** | Raw manual CLI arguments | Strictly guarded `.env`-driven creation |
19
+ | **Subdomain** | Passed as 1st argument (optional) | **Mandatory 1st argument** |
20
+ | **Port** | Must be passed as 2nd argument | **Read strictly from `./.env` (Zero defaults)** |
21
+ | **Guards** | Minimal validation | **5 Strict Guards** (Folder, Port, File collision) |
22
+ | **Import** | `import { ... } from "ubuntu-service-create/v1"` | `import { ... } from "ubuntu-service-create"` *(or `/v2`)* |
17
23
 
18
- ```
19
- 1. CREATE ➔ ubuntu-service-create (Birth of .service file on VPS)
20
- 2. DETECT ➔ ubuntu-service-detect (Locates service belonging to cwd)
21
- 3. RESTART ➔ ubuntu-service-restart (Safely executes systemctl restart & poll)
22
- 4. NETWORK ➔ ubuntu-service-port (Maps and verifies active port assignments)
23
- ```
24
+ ---
25
+
26
+ ## 🛡️ V2 Strict Guards
27
+
28
+ Before any file is generated or written to `/etc/systemd/system/`, `usc` enforces:
24
29
 
25
- `ubuntu-service-create` is responsible for **Step 1**: generating valid systemd unit files conforming to KeshavSoft conventions (`EnvironmentFile=.env`, `ExecStart=node app.js`, `Restart=on-failure`, `PORT=<port>`), and optionally writing them directly to `/etc/systemd/system/` and activating them.
30
+ 1. 🛡️ **Subdomain Guard:** Validates that `<subdomain>` is supplied.
31
+ 2. 🛡️ **`.env` File Guard:** Verifies `./.env` exists in current working directory.
32
+ 3. 🛡️ **`PORT` Value Guard:** Extracts explicit `PORT=\d+` from `.env`. **No fallback default port is allowed.**
33
+ 4. 🛡️ **File Conflict Guard:** Rejects if `/etc/systemd/system/<subdomain>.service` already exists (unless `--force`).
34
+ 5. 🛡️ **Folder Conflict Guard:** Rejects if current directory is already managed by another systemd service.
35
+ 6. 🛡️ **Port Conflict Guard:** Rejects if port is already claimed by another systemd service.
26
36
 
27
37
  ---
28
38
 
29
- ## ⚡ Quick Start (CLI)
39
+ ## ⚡ Quick Start (CLI - V2)
30
40
 
31
- Run directly via `npx` with zero installation:
41
+ Stand inside your cloned repository (e.g. `/root/KeshavSoft/appointment-booking`):
32
42
 
33
43
  ```bash
34
- # 1. Inside your app directory (/root/KeshavSoft/appointment-booking):
35
- npx ubuntu-service-create 3004
44
+ # 1. Preview generated unit file (with all guards verified):
45
+ npx usc appointment.keshavsoft.com
36
46
 
37
- # 2. Or using the shortcut binary 'usc':
38
- npx usc appointment-booking 3004
47
+ # 2. Write file directly to /etc/systemd/system/appointment.keshavsoft.com.service:
48
+ npx usc appointment.keshavsoft.com --write
39
49
 
40
- # 3. Write directly to /etc/systemd/system/appointment-booking.service:
41
- npx usc appointment-booking 3004 --write
42
-
43
- # 4. Complete 1-shot deployment: write + reload daemon + enable & start now:
44
- npx usc appointment-booking 3004 --enable
50
+ # 3. Complete 1-shot deployment (Write + daemon-reload + enable --now):
51
+ npx usc appointment.keshavsoft.com --enable
45
52
  ```
46
53
 
47
54
  ---
48
55
 
49
- ## 📋 CLI Usage & Options
56
+ ## 📋 CLI Usage & Options (V2)
50
57
 
51
58
  ```text
52
- ubuntu-service-create (usc) — Author and create Ubuntu systemd services for KeshavSoft VPS apps
59
+ ubuntu-service-create (usc) — Guarded systemd service creator for KeshavSoft VPS apps
53
60
 
54
61
  Usage:
55
- npx ubuntu-service-create <name> <port> [workingDir] [options]
56
- npx ubuntu-service-create <port> [options]
62
+ npx usc <subdomain> [options]
63
+
64
+ Arguments:
65
+ <subdomain> Public subdomain/domain name (e.g. appointment.keshavsoft.com)
66
+ (Port is read automatically from .env in the current folder)
57
67
 
58
- Commands:
59
- (default) Generate service unit file content to stdout
60
- --write, -w Write the service unit file directly to /etc/systemd/system/
68
+ Commands / Actions:
69
+ (default) Verify guards and generate service unit to stdout
70
+ --write, -w Write service unit to /etc/systemd/system/<subdomain>.service
61
71
  --enable, -e Write file + run 'systemctl daemon-reload && systemctl enable --now'
62
72
 
73
+ Guards Enforced:
74
+ 🛡️ .env Guard Checks that .env exists in current working directory
75
+ 🛡️ PORT Guard Extracts explicit PORT from .env (no default/fallback allowed)
76
+ 🛡️ File Conflict Rejects if <subdomain>.service already exists (unless --force)
77
+ 🛡️ Folder Conflict Rejects if current directory is already used by another service
78
+ 🛡️ Port Conflict Rejects if port is already assigned to another service
79
+
63
80
  Options:
64
- --dir <path> Target directory (defaults to /etc/systemd/system)
81
+ --force, -f Overwrite existing service file if it already exists
82
+ --dir <path> Target systemd directory (defaults to /etc/systemd/system)
65
83
  --exec <cmd> Custom ExecStart command
66
84
  --user <user> Service user (defaults to 'root')
67
85
  --env <env> NODE_ENV value (defaults to 'production')
@@ -74,31 +92,30 @@ Options:
74
92
 
75
93
  ## 💻 Programmatic API
76
94
 
77
- ```bash
78
- npm install ubuntu-service-create
79
- ```
80
-
95
+ ### Modern V2 (Default):
81
96
  ```javascript
82
- import { generateServiceUnit, writeServiceUnit, createService } from "ubuntu-service-create";
97
+ import { createService, generateServiceUnit } from "ubuntu-service-create";
83
98
 
84
- // 1. Pure text generation (zero side-effects)
85
- const unitContent = generateServiceUnit({
86
- name: "appointment-booking",
87
- port: 3004,
88
- workingDirectory: "/root/KeshavSoft/appointment-booking"
99
+ // Automatically checks all guards and reads port from .env
100
+ const result = createService({
101
+ subdomain: "appointment.keshavsoft.com",
102
+ workingDirectory: process.cwd(),
103
+ write: true,
104
+ enable: true
89
105
  });
90
106
 
91
- console.log(unitContent);
107
+ console.log(result.unitName); // appointment.keshavsoft.com.service
108
+ console.log(result.port); // 3004 (read from .env)
109
+ ```
110
+
111
+ ### Baseline V1:
112
+ ```javascript
113
+ import { generateServiceUnit, createService } from "ubuntu-service-create/v1";
92
114
 
93
- // 2. High-level creator with direct write
94
- const result = createService({
115
+ const unit = generateServiceUnit({
95
116
  name: "appointment-booking",
96
- port: 3004,
97
- write: true,
98
- enable: true // Reloads daemon and starts service
117
+ port: 3004
99
118
  });
100
-
101
- console.log(result.path); // /etc/systemd/system/appointment-booking.service
102
119
  ```
103
120
 
104
121
  ---
@@ -107,7 +124,7 @@ console.log(result.path); // /etc/systemd/system/appointment-booking.service
107
124
 
108
125
  ```ini
109
126
  [Unit]
110
- Description=appointment-booking Node Service
127
+ Description=appointment.keshavsoft.com Node Service
111
128
  After=network.target
112
129
 
113
130
  [Service]
@@ -135,7 +152,7 @@ WantedBy=multi-user.target
135
152
 
136
153
  ## 🧪 Testing
137
154
 
138
- Run the native Node.js test suite:
155
+ Runs both V1 and V2 test suites (24 tests total):
139
156
 
140
157
  ```bash
141
158
  npm test
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "ubuntu-service-create",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "description": "Author, validate, and write standard Ubuntu systemd service unit files matching KeshavSoft VPS conventions.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
7
  "exports": {
8
8
  ".": "./src/index.js",
9
- "./v1": "./src/v1/index.js"
9
+ "./v1": "./src/v1/index.js",
10
+ "./v2": "./src/v2/index.js"
10
11
  },
11
12
  "bin": {
12
13
  "ubuntu-service-create": "bin/index.js",
@@ -28,6 +29,7 @@
28
29
  "service",
29
30
  "create",
30
31
  "generate",
32
+ "guards",
31
33
  "cli",
32
34
  "keshavsoft",
33
35
  "vps",
package/src/cli.js CHANGED
@@ -1,2 +1,3 @@
1
- export * from "./v1/cli.js";
2
- export { default } from "./v1/cli.js";
1
+ // Orchestrator: delegates CLI execution directly to latest version (v2)
2
+ export { runCli, printHelp } from "./v2/cli.js";
3
+ export default runCli;
package/src/index.js CHANGED
@@ -1,2 +1,3 @@
1
- export * from "./v1/index.js";
2
- export { default } from "./v1/index.js";
1
+ // Orchestrator: delegates directly to latest version (v2)
2
+ export * from "./v2/index.js";
3
+ export { default } from "./v2/index.js";
package/src/v1/cli.js CHANGED
@@ -1,166 +1,166 @@
1
- import { generateServiceUnit } from "./generator.js";
2
- import { writeServiceUnit, DEFAULT_SYSTEMD_DIR } from "./writer.js";
3
- import { basename } from "node:path";
4
-
5
- export function printHelp() {
6
- console.log(`
7
- ubuntu-service-create (usc) — Author and create Ubuntu systemd services for KeshavSoft VPS apps
8
-
9
- Usage:
10
- npx ubuntu-service-create <name> <port> [workingDir] [options]
11
- npx ubuntu-service-create <port> [options]
12
-
13
- Commands:
14
- (default) Generate service unit file content to stdout
15
- --write, -w Write the service unit file directly to /etc/systemd/system/
16
- --enable, -e Write file + run 'systemctl daemon-reload && systemctl enable --now'
17
-
18
- Options:
19
- --dir <path> Target directory (defaults to /etc/systemd/system)
20
- --exec <cmd> Custom ExecStart command
21
- --user <user> Service user (defaults to 'root')
22
- --env <env> NODE_ENV value (defaults to 'production')
23
- --json Output machine-readable JSON
24
- -h, --help Show this help message
25
- -v, --version Show version number
26
-
27
- Examples:
28
- # Stand in /root/KeshavSoft/appointment-booking and print unit file:
29
- npx usc 3004
30
-
31
- # Explicit name and port:
32
- npx usc appointment-booking 3004
33
-
34
- # Write unit file to /etc/systemd/system/appointment-booking.service:
35
- npx usc appointment-booking 3004 --write
36
-
37
- # Complete 1-shot deployment: write, reload daemon, and start immediately:
38
- npx usc appointment-booking 3004 --enable
39
- `);
40
- }
41
-
42
- export function runCli(argv = process.argv.slice(2)) {
43
- if (argv.includes("-h") || argv.includes("--help")) {
44
- printHelp();
45
- return 0;
46
- }
47
-
48
- if (argv.includes("-v") || argv.includes("--version")) {
49
- console.log("1.0.0");
50
- return 0;
51
- }
52
-
53
- const isJson = argv.includes("--json");
54
- const isWrite = argv.includes("-w") || argv.includes("--write");
55
- const isEnable = argv.includes("-e") || argv.includes("--enable");
56
-
57
- // Extract options
58
- let customDir = null;
59
- const dirIdx = argv.indexOf("--dir");
60
- if (dirIdx !== -1 && argv[dirIdx + 1]) {
61
- customDir = argv[dirIdx + 1];
62
- }
63
-
64
- let customExec = null;
65
- const execIdx = argv.indexOf("--exec");
66
- if (execIdx !== -1 && argv[execIdx + 1]) {
67
- customExec = argv[execIdx + 1];
68
- }
69
-
70
- let customUser = "root";
71
- const userIdx = argv.indexOf("--user");
72
- if (userIdx !== -1 && argv[userIdx + 1]) {
73
- customUser = argv[userIdx + 1];
74
- }
75
-
76
- let customEnv = "production";
77
- const envIdx = argv.indexOf("--env");
78
- if (envIdx !== -1 && argv[envIdx + 1]) {
79
- customEnv = argv[envIdx + 1];
80
- }
81
-
82
- // Filter out flags from positional arguments
83
- const positional = argv.filter((arg, i) => {
84
- if (["--json", "-h", "--help", "-v", "--version", "-w", "--write", "-e", "--enable"].includes(arg)) return false;
85
- if (["--dir", "--exec", "--user", "--env"].includes(arg)) return false;
86
- if (i > 0 && ["--dir", "--exec", "--user", "--env"].includes(argv[i - 1])) return false;
87
- return true;
88
- });
89
-
90
- if (positional.length === 0) {
91
- console.error("Error: Port number is required.");
92
- console.error("Example: npx usc 3004 or npx usc appointment-booking 3004");
93
- return 1;
94
- }
95
-
96
- let serviceName;
97
- let port;
98
- let workingDirectory = null;
99
-
100
- // Check if first arg is purely a port number (e.g. `usc 3004`)
101
- if (/^\d{2,5}$/.test(positional[0]) && positional.length === 1) {
102
- port = positional[0];
103
- serviceName = basename(process.cwd());
104
- } else {
105
- serviceName = positional[0];
106
- port = positional[1];
107
- if (positional[2]) {
108
- workingDirectory = positional[2];
109
- }
110
- }
111
-
112
- if (!port || isNaN(Number(port))) {
113
- console.error(`Error: A valid port number is required. Received: '${port}'`);
114
- return 1;
115
- }
116
-
117
- try {
118
- const unitContent = generateServiceUnit({
119
- name: serviceName,
120
- port,
121
- workingDirectory,
122
- execStart: customExec || undefined,
123
- user: customUser,
124
- nodeEnv: customEnv
125
- });
126
-
127
- if (isWrite || isEnable) {
128
- const writeResult = writeServiceUnit(serviceName, unitContent, {
129
- dir: customDir,
130
- enable: isEnable
131
- });
132
-
133
- if (isJson) {
134
- console.log(JSON.stringify(writeResult, null, 2));
135
- return writeResult.success ? 0 : 1;
136
- }
137
-
138
- console.log(`\n======================================================`);
139
- console.log(` ✅ Service Unit Created: ${writeResult.unitName}`);
140
- console.log(` Location: ${writeResult.path}`);
141
- if (isEnable) {
142
- console.log(` Status: ${writeResult.simulated ? "Simulated (Non-Linux)" : (writeResult.started ? "Enabled & Active" : "Failed to start")}`);
143
- }
144
- console.log(`======================================================\n`);
145
- return 0;
146
- }
147
-
148
- // Default: Print to stdout
149
- if (isJson) {
150
- console.log(JSON.stringify({
151
- serviceName,
152
- port,
153
- unitContent
154
- }, null, 2));
155
- return 0;
156
- }
157
-
158
- process.stdout.write(unitContent);
159
- return 0;
160
- } catch (err) {
161
- console.error(`Error: ${err.message}`);
162
- return 1;
163
- }
164
- }
165
-
166
- export default runCli;
1
+ import { generateServiceUnit } from "./generator.js";
2
+ import { writeServiceUnit, DEFAULT_SYSTEMD_DIR } from "./writer.js";
3
+ import { basename } from "node:path";
4
+
5
+ export function printHelp() {
6
+ console.log(`
7
+ ubuntu-service-create (usc) — Author and create Ubuntu systemd services for KeshavSoft VPS apps
8
+
9
+ Usage:
10
+ npx ubuntu-service-create <name> <port> [workingDir] [options]
11
+ npx ubuntu-service-create <port> [options]
12
+
13
+ Commands:
14
+ (default) Generate service unit file content to stdout
15
+ --write, -w Write the service unit file directly to /etc/systemd/system/
16
+ --enable, -e Write file + run 'systemctl daemon-reload && systemctl enable --now'
17
+
18
+ Options:
19
+ --dir <path> Target directory (defaults to /etc/systemd/system)
20
+ --exec <cmd> Custom ExecStart command
21
+ --user <user> Service user (defaults to 'root')
22
+ --env <env> NODE_ENV value (defaults to 'production')
23
+ --json Output machine-readable JSON
24
+ -h, --help Show this help message
25
+ -v, --version Show version number
26
+
27
+ Examples:
28
+ # Stand in /root/KeshavSoft/appointment-booking and print unit file:
29
+ npx usc 3004
30
+
31
+ # Explicit name and port:
32
+ npx usc appointment-booking 3004
33
+
34
+ # Write unit file to /etc/systemd/system/appointment-booking.service:
35
+ npx usc appointment-booking 3004 --write
36
+
37
+ # Complete 1-shot deployment: write, reload daemon, and start immediately:
38
+ npx usc appointment-booking 3004 --enable
39
+ `);
40
+ }
41
+
42
+ export function runCli(argv = process.argv.slice(2)) {
43
+ if (argv.includes("-h") || argv.includes("--help")) {
44
+ printHelp();
45
+ return 0;
46
+ }
47
+
48
+ if (argv.includes("-v") || argv.includes("--version")) {
49
+ console.log("1.0.0");
50
+ return 0;
51
+ }
52
+
53
+ const isJson = argv.includes("--json");
54
+ const isWrite = argv.includes("-w") || argv.includes("--write");
55
+ const isEnable = argv.includes("-e") || argv.includes("--enable");
56
+
57
+ // Extract options
58
+ let customDir = null;
59
+ const dirIdx = argv.indexOf("--dir");
60
+ if (dirIdx !== -1 && argv[dirIdx + 1]) {
61
+ customDir = argv[dirIdx + 1];
62
+ }
63
+
64
+ let customExec = null;
65
+ const execIdx = argv.indexOf("--exec");
66
+ if (execIdx !== -1 && argv[execIdx + 1]) {
67
+ customExec = argv[execIdx + 1];
68
+ }
69
+
70
+ let customUser = "root";
71
+ const userIdx = argv.indexOf("--user");
72
+ if (userIdx !== -1 && argv[userIdx + 1]) {
73
+ customUser = argv[userIdx + 1];
74
+ }
75
+
76
+ let customEnv = "production";
77
+ const envIdx = argv.indexOf("--env");
78
+ if (envIdx !== -1 && argv[envIdx + 1]) {
79
+ customEnv = argv[envIdx + 1];
80
+ }
81
+
82
+ // Filter out flags from positional arguments
83
+ const positional = argv.filter((arg, i) => {
84
+ if (["--json", "-h", "--help", "-v", "--version", "-w", "--write", "-e", "--enable"].includes(arg)) return false;
85
+ if (["--dir", "--exec", "--user", "--env"].includes(arg)) return false;
86
+ if (i > 0 && ["--dir", "--exec", "--user", "--env"].includes(argv[i - 1])) return false;
87
+ return true;
88
+ });
89
+
90
+ if (positional.length === 0) {
91
+ console.error("Error: Port number is required.");
92
+ console.error("Example: npx usc 3004 or npx usc appointment-booking 3004");
93
+ return 1;
94
+ }
95
+
96
+ let serviceName;
97
+ let port;
98
+ let workingDirectory = null;
99
+
100
+ // Check if first arg is purely a port number (e.g. `usc 3004`)
101
+ if (/^\d{2,5}$/.test(positional[0]) && positional.length === 1) {
102
+ port = positional[0];
103
+ serviceName = basename(process.cwd());
104
+ } else {
105
+ serviceName = positional[0];
106
+ port = positional[1];
107
+ if (positional[2]) {
108
+ workingDirectory = positional[2];
109
+ }
110
+ }
111
+
112
+ if (!port || isNaN(Number(port))) {
113
+ console.error(`Error: A valid port number is required. Received: '${port}'`);
114
+ return 1;
115
+ }
116
+
117
+ try {
118
+ const unitContent = generateServiceUnit({
119
+ name: serviceName,
120
+ port,
121
+ workingDirectory,
122
+ execStart: customExec || undefined,
123
+ user: customUser,
124
+ nodeEnv: customEnv
125
+ });
126
+
127
+ if (isWrite || isEnable) {
128
+ const writeResult = writeServiceUnit(serviceName, unitContent, {
129
+ dir: customDir,
130
+ enable: isEnable
131
+ });
132
+
133
+ if (isJson) {
134
+ console.log(JSON.stringify(writeResult, null, 2));
135
+ return writeResult.success ? 0 : 1;
136
+ }
137
+
138
+ console.log(`\n======================================================`);
139
+ console.log(` ✅ Service Unit Created: ${writeResult.unitName}`);
140
+ console.log(` Location: ${writeResult.path}`);
141
+ if (isEnable) {
142
+ console.log(` Status: ${writeResult.simulated ? "Simulated (Non-Linux)" : (writeResult.started ? "Enabled & Active" : "Failed to start")}`);
143
+ }
144
+ console.log(`======================================================\n`);
145
+ return 0;
146
+ }
147
+
148
+ // Default: Print to stdout
149
+ if (isJson) {
150
+ console.log(JSON.stringify({
151
+ serviceName,
152
+ port,
153
+ unitContent
154
+ }, null, 2));
155
+ return 0;
156
+ }
157
+
158
+ process.stdout.write(unitContent);
159
+ return 0;
160
+ } catch (err) {
161
+ console.error(`Error: ${err.message}`);
162
+ return 1;
163
+ }
164
+ }
165
+
166
+ export default runCli;
@@ -1,65 +1,65 @@
1
- /**
2
- * Systemd unit file generator for KeshavSoft VPS Node.js applications.
3
- * Zero external dependencies.
4
- */
5
-
6
- export function generateServiceUnit({
7
- name,
8
- port,
9
- workingDirectory,
10
- execStart = "/root/.nvm/versions/node/v24.13.0/bin/node app.js",
11
- user = "root",
12
- nodeEnv = "production",
13
- restartSec = 5,
14
- description
15
- }) {
16
- if (!name) {
17
- throw new Error("generateServiceUnit requires a service name / domain string.");
18
- }
19
-
20
- const cleanName = String(name).replace(/\.service$/i, "").trim();
21
- if (!cleanName) {
22
- throw new Error("Service name cannot be empty.");
23
- }
24
-
25
- const serviceDescription = description || `${cleanName} Node Service`;
26
- const cleanWorkingDir = workingDirectory || `/root/KeshavSoft/${cleanName}`;
27
-
28
- const lines = [
29
- "[Unit]",
30
- `Description=${serviceDescription}`,
31
- "After=network.target",
32
- "",
33
- "[Service]",
34
- "Type=simple",
35
- `User=${user}`,
36
- `WorkingDirectory=${cleanWorkingDir}`,
37
- "",
38
- `Environment=NODE_ENV=${nodeEnv}`
39
- ];
40
-
41
- if (port !== undefined && port !== null && port !== "") {
42
- const numPort = Number(port);
43
- if (isNaN(numPort) || numPort < 1 || numPort > 65535) {
44
- throw new Error(`Invalid port number: ${port}. Must be between 1 and 65535.`);
45
- }
46
- lines.push(`Environment=PORT=${numPort}`);
47
- }
48
-
49
- lines.push(
50
- `EnvironmentFile=${cleanWorkingDir}/.env`,
51
- "",
52
- `ExecStart=${execStart}`,
53
- "",
54
- "Restart=on-failure",
55
- `RestartSec=${restartSec}`,
56
- "",
57
- "StandardOutput=journal",
58
- "StandardError=journal",
59
- "",
60
- "[Install]",
61
- "WantedBy=multi-user.target"
62
- );
63
-
64
- return lines.join("\n") + "\n";
65
- }
1
+ /**
2
+ * Systemd unit file generator for KeshavSoft VPS Node.js applications.
3
+ * Zero external dependencies.
4
+ */
5
+
6
+ export function generateServiceUnit({
7
+ name,
8
+ port,
9
+ workingDirectory,
10
+ execStart = "/root/.nvm/versions/node/v24.13.0/bin/node app.js",
11
+ user = "root",
12
+ nodeEnv = "production",
13
+ restartSec = 5,
14
+ description
15
+ }) {
16
+ if (!name) {
17
+ throw new Error("generateServiceUnit requires a service name / domain string.");
18
+ }
19
+
20
+ const cleanName = String(name).replace(/\.service$/i, "").trim();
21
+ if (!cleanName) {
22
+ throw new Error("Service name cannot be empty.");
23
+ }
24
+
25
+ const serviceDescription = description || `${cleanName} Node Service`;
26
+ const cleanWorkingDir = workingDirectory || `/root/KeshavSoft/${cleanName}`;
27
+
28
+ const lines = [
29
+ "[Unit]",
30
+ `Description=${serviceDescription}`,
31
+ "After=network.target",
32
+ "",
33
+ "[Service]",
34
+ "Type=simple",
35
+ `User=${user}`,
36
+ `WorkingDirectory=${cleanWorkingDir}`,
37
+ "",
38
+ `Environment=NODE_ENV=${nodeEnv}`
39
+ ];
40
+
41
+ if (port !== undefined && port !== null && port !== "") {
42
+ const numPort = Number(port);
43
+ if (isNaN(numPort) || numPort < 1 || numPort > 65535) {
44
+ throw new Error(`Invalid port number: ${port}. Must be between 1 and 65535.`);
45
+ }
46
+ lines.push(`Environment=PORT=${numPort}`);
47
+ }
48
+
49
+ lines.push(
50
+ `EnvironmentFile=${cleanWorkingDir}/.env`,
51
+ "",
52
+ `ExecStart=${execStart}`,
53
+ "",
54
+ "Restart=on-failure",
55
+ `RestartSec=${restartSec}`,
56
+ "",
57
+ "StandardOutput=journal",
58
+ "StandardError=journal",
59
+ "",
60
+ "[Install]",
61
+ "WantedBy=multi-user.target"
62
+ );
63
+
64
+ return lines.join("\n") + "\n";
65
+ }
package/src/v1/index.js CHANGED
@@ -1,53 +1,53 @@
1
- import { generateServiceUnit } from "./generator.js";
2
- import { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
3
- import { basename } from "node:path";
4
-
5
- export { generateServiceUnit } from "./generator.js";
6
- export { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
7
-
8
- /**
9
- * High-level service creator. Combines generation and optional writing / enabling.
10
- */
11
- export function createService(options = {}) {
12
- const cwdName = basename(process.cwd());
13
- const name = options.name || cwdName;
14
- const port = options.port;
15
- const workingDirectory = options.workingDirectory || (process.platform === "linux" ? `/root/KeshavSoft/${name}` : process.cwd());
16
-
17
- const unitContent = generateServiceUnit({
18
- name,
19
- port,
20
- workingDirectory,
21
- execStart: options.execStart,
22
- user: options.user,
23
- nodeEnv: options.nodeEnv,
24
- restartSec: options.restartSec,
25
- description: options.description
26
- });
27
-
28
- if (options.write || options.enable) {
29
- const writeResult = writeServiceUnit(name, unitContent, {
30
- dir: options.dir,
31
- enable: options.enable
32
- });
33
- return {
34
- ...writeResult,
35
- content: unitContent
36
- };
37
- }
38
-
39
- return {
40
- success: true,
41
- unitName: `${String(name).replace(/\.service$/i, "")}.service`,
42
- content: unitContent,
43
- written: false
44
- };
45
- }
46
-
47
- export default {
48
- generateServiceUnit,
49
- writeServiceUnit,
50
- createService,
51
- isSystemctlAvailable,
52
- DEFAULT_SYSTEMD_DIR
53
- };
1
+ import { generateServiceUnit } from "./generator.js";
2
+ import { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
3
+ import { basename } from "node:path";
4
+
5
+ export { generateServiceUnit } from "./generator.js";
6
+ export { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
7
+
8
+ /**
9
+ * High-level service creator. Combines generation and optional writing / enabling.
10
+ */
11
+ export function createService(options = {}) {
12
+ const cwdName = basename(process.cwd());
13
+ const name = options.name || cwdName;
14
+ const port = options.port;
15
+ const workingDirectory = options.workingDirectory || (process.platform === "linux" ? `/root/KeshavSoft/${name}` : process.cwd());
16
+
17
+ const unitContent = generateServiceUnit({
18
+ name,
19
+ port,
20
+ workingDirectory,
21
+ execStart: options.execStart,
22
+ user: options.user,
23
+ nodeEnv: options.nodeEnv,
24
+ restartSec: options.restartSec,
25
+ description: options.description
26
+ });
27
+
28
+ if (options.write || options.enable) {
29
+ const writeResult = writeServiceUnit(name, unitContent, {
30
+ dir: options.dir,
31
+ enable: options.enable
32
+ });
33
+ return {
34
+ ...writeResult,
35
+ content: unitContent
36
+ };
37
+ }
38
+
39
+ return {
40
+ success: true,
41
+ unitName: `${String(name).replace(/\.service$/i, "")}.service`,
42
+ content: unitContent,
43
+ written: false
44
+ };
45
+ }
46
+
47
+ export default {
48
+ generateServiceUnit,
49
+ writeServiceUnit,
50
+ createService,
51
+ isSystemctlAvailable,
52
+ DEFAULT_SYSTEMD_DIR
53
+ };
package/src/v2/cli.js ADDED
@@ -0,0 +1,160 @@
1
+ import { createService, DEFAULT_SYSTEMD_DIR } from "./index.js";
2
+
3
+ export function printHelp() {
4
+ console.log(`
5
+ ubuntu-service-create (usc) — Guarded systemd service creator for KeshavSoft VPS apps
6
+
7
+ Usage:
8
+ npx usc <subdomain> [options]
9
+
10
+ Arguments:
11
+ <subdomain> Public subdomain/domain name (e.g. appointment.keshavsoft.com)
12
+ (Port is read automatically from .env in the current folder)
13
+
14
+ Commands / Actions:
15
+ (default) Verify guards and generate service unit to stdout
16
+ --write, -w Write service unit to /etc/systemd/system/<subdomain>.service
17
+ --enable, -e Write file + run 'systemctl daemon-reload && systemctl enable --now'
18
+
19
+ Guards Enforced:
20
+ 🛡️ .env Guard Checks that .env exists in current working directory
21
+ 🛡️ PORT Guard Extracts explicit PORT from .env (no default/fallback allowed)
22
+ 🛡️ File Conflict Rejects if <subdomain>.service already exists (unless --force)
23
+ 🛡️ Folder Conflict Rejects if current directory is already used by another service
24
+ 🛡️ Port Conflict Rejects if port is already assigned to another service
25
+
26
+ Options:
27
+ --force, -f Overwrite existing service file if it already exists
28
+ --dir <path> Target systemd directory (defaults to /etc/systemd/system)
29
+ --exec <cmd> Custom ExecStart command
30
+ --user <user> Service user (defaults to 'root')
31
+ --env <env> NODE_ENV value (defaults to 'production')
32
+ --json Output machine-readable JSON
33
+ -h, --help Show this help message
34
+ -v, --version Show version number
35
+
36
+ Examples:
37
+ # Stand in /root/KeshavSoft/appointment-booking (with .env containing PORT=3004):
38
+
39
+ # Preview unit file with guards verified:
40
+ npx usc appointment.keshavsoft.com
41
+
42
+ # 1-Shot VPS Deploy (Write + reload daemon + enable & start):
43
+ npx usc appointment.keshavsoft.com --enable
44
+ `);
45
+ }
46
+
47
+ export function runCli(argv = process.argv.slice(2)) {
48
+ if (argv.includes("-h") || argv.includes("--help")) {
49
+ printHelp();
50
+ return 0;
51
+ }
52
+
53
+ if (argv.includes("-v") || argv.includes("--version")) {
54
+ console.log("1.1.0");
55
+ return 0;
56
+ }
57
+
58
+ const isJson = argv.includes("--json");
59
+ const isWrite = argv.includes("-w") || argv.includes("--write");
60
+ const isEnable = argv.includes("-e") || argv.includes("--enable");
61
+ const isForce = argv.includes("-f") || argv.includes("--force");
62
+
63
+ // Extract options
64
+ let customDir = null;
65
+ const dirIdx = argv.indexOf("--dir");
66
+ if (dirIdx !== -1 && argv[dirIdx + 1]) {
67
+ customDir = argv[dirIdx + 1];
68
+ }
69
+
70
+ let customExec = null;
71
+ const execIdx = argv.indexOf("--exec");
72
+ if (execIdx !== -1 && argv[execIdx + 1]) {
73
+ customExec = argv[execIdx + 1];
74
+ }
75
+
76
+ let customUser = "root";
77
+ const userIdx = argv.indexOf("--user");
78
+ if (userIdx !== -1 && argv[userIdx + 1]) {
79
+ customUser = argv[userIdx + 1];
80
+ }
81
+
82
+ let customEnv = "production";
83
+ const envIdx = argv.indexOf("--env");
84
+ if (envIdx !== -1 && argv[envIdx + 1]) {
85
+ customEnv = argv[envIdx + 1];
86
+ }
87
+
88
+ // Filter out flags from positional arguments
89
+ const positional = argv.filter((arg, i) => {
90
+ if (["--json", "-h", "--help", "-v", "--version", "-w", "--write", "-e", "--enable", "-f", "--force"].includes(arg)) return false;
91
+ if (["--dir", "--exec", "--user", "--env"].includes(arg)) return false;
92
+ if (i > 0 && ["--dir", "--exec", "--user", "--env"].includes(argv[i - 1])) return false;
93
+ return true;
94
+ });
95
+
96
+ if (positional.length === 0) {
97
+ console.error("❌ Guard Error: Subdomain name is required.");
98
+ console.error("Usage: npx usc <subdomain> [--write | --enable]");
99
+ console.error("Example: npx usc appointment.keshavsoft.com --enable");
100
+ return 1;
101
+ }
102
+
103
+ const subdomain = positional[0];
104
+
105
+ try {
106
+ const result = createService({
107
+ subdomain,
108
+ workingDirectory: process.cwd(),
109
+ dir: customDir,
110
+ write: isWrite || isEnable,
111
+ enable: isEnable,
112
+ force: isForce,
113
+ execStart: customExec || undefined,
114
+ user: customUser,
115
+ nodeEnv: customEnv
116
+ });
117
+
118
+ if (isWrite || isEnable) {
119
+ if (isJson) {
120
+ console.log(JSON.stringify(result, null, 2));
121
+ return result.success ? 0 : 1;
122
+ }
123
+
124
+ console.log(`\n======================================================`);
125
+ console.log(` ✅ Service Unit Created: ${result.unitName}`);
126
+ console.log(` Subdomain: ${result.subdomain}`);
127
+ console.log(` Port: ${result.port} (from ${result.envPath})`);
128
+ console.log(` WorkingDir: ${result.workingDirectory}`);
129
+ console.log(` Location: ${result.path}`);
130
+ if (isEnable) {
131
+ console.log(` Status: ${result.simulated ? "Simulated (Non-Linux)" : (result.started ? "Enabled & Active" : "Failed to start")}`);
132
+ }
133
+ console.log(`======================================================\n`);
134
+ return 0;
135
+ }
136
+
137
+ // Default: Print to stdout
138
+ if (isJson) {
139
+ console.log(JSON.stringify({
140
+ subdomain: result.subdomain,
141
+ port: result.port,
142
+ workingDirectory: result.workingDirectory,
143
+ unitContent: result.content
144
+ }, null, 2));
145
+ return 0;
146
+ }
147
+
148
+ process.stdout.write(result.content);
149
+ return 0;
150
+ } catch (err) {
151
+ if (isJson) {
152
+ console.error(JSON.stringify({ error: err.message }, null, 2));
153
+ } else {
154
+ console.error(`\n❌ Guard Error: ${err.message}\n`);
155
+ }
156
+ return 1;
157
+ }
158
+ }
159
+
160
+ export default runCli;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Systemd unit file generator for KeshavSoft VPS Node.js applications.
3
+ * Zero external dependencies.
4
+ */
5
+
6
+ export function generateServiceUnit({
7
+ subdomain,
8
+ name, // alias for subdomain
9
+ port,
10
+ workingDirectory,
11
+ execStart = "/root/.nvm/versions/node/v24.13.0/bin/node app.js",
12
+ user = "root",
13
+ nodeEnv = "production",
14
+ restartSec = 5,
15
+ description
16
+ }) {
17
+ const domain = subdomain || name;
18
+ if (!domain) {
19
+ throw new Error("generateServiceUnit requires a subdomain / service name.");
20
+ }
21
+
22
+ const cleanDomain = String(domain).replace(/\.service$/i, "").trim();
23
+ if (!cleanDomain) {
24
+ throw new Error("Subdomain cannot be empty.");
25
+ }
26
+
27
+ if (port === undefined || port === null || port === "") {
28
+ throw new Error("generateServiceUnit requires an explicit port.");
29
+ }
30
+
31
+ const numPort = Number(port);
32
+ if (isNaN(numPort) || numPort < 1 || numPort > 65535) {
33
+ throw new Error(`Invalid port number: ${port}. Must be between 1 and 65535.`);
34
+ }
35
+
36
+ const serviceDescription = description || `${cleanDomain} Node Service`;
37
+ const cleanWorkingDir = workingDirectory || process.cwd();
38
+
39
+ const lines = [
40
+ "[Unit]",
41
+ `Description=${serviceDescription}`,
42
+ "After=network.target",
43
+ "",
44
+ "[Service]",
45
+ "Type=simple",
46
+ `User=${user}`,
47
+ `WorkingDirectory=${cleanWorkingDir}`,
48
+ "",
49
+ `Environment=NODE_ENV=${nodeEnv}`,
50
+ `Environment=PORT=${numPort}`,
51
+ `EnvironmentFile=${cleanWorkingDir}/.env`,
52
+ "",
53
+ `ExecStart=${execStart}`,
54
+ "",
55
+ "Restart=on-failure",
56
+ `RestartSec=${restartSec}`,
57
+ "",
58
+ "StandardOutput=journal",
59
+ "StandardError=journal",
60
+ "",
61
+ "[Install]",
62
+ "WantedBy=multi-user.target"
63
+ ];
64
+
65
+ return lines.join("\n") + "\n";
66
+ }
@@ -0,0 +1,159 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { resolve, join } from "node:path";
3
+
4
+ /**
5
+ * Normalizes a filesystem path for cross-platform comparison.
6
+ */
7
+ export function normalizePath(p) {
8
+ if (!p) return "";
9
+ let resolved = resolve(p).replace(/\\/g, "/");
10
+ if (resolved.endsWith("/")) {
11
+ resolved = resolved.slice(0, -1);
12
+ }
13
+ return resolved;
14
+ }
15
+
16
+ /**
17
+ * Guard 1: Validates that a non-empty subdomain is provided.
18
+ */
19
+ export function validateSubdomain(subdomain) {
20
+ if (!subdomain || typeof subdomain !== "string") {
21
+ throw new Error("Subdomain is required. Example: npx usc appointment.keshavsoft.com");
22
+ }
23
+
24
+ const clean = subdomain.replace(/\.service$/i, "").trim();
25
+ if (!clean) {
26
+ throw new Error("Subdomain cannot be empty.");
27
+ }
28
+
29
+ // Basic domain/subdomain format check (allows hyphens, dots, letters, numbers)
30
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9.-]*[a-zA-Z0-9]$/.test(clean) && !/^[a-zA-Z0-9]$/.test(clean)) {
31
+ throw new Error(`Invalid subdomain format: '${subdomain}'.`);
32
+ }
33
+
34
+ return clean;
35
+ }
36
+
37
+ /**
38
+ * Guard 2 & 3: Reads .env file in target directory and extracts PORT.
39
+ * Strictly throws if .env is missing or PORT is not defined. No defaults allowed.
40
+ */
41
+ export function readEnvPort(dir = process.cwd()) {
42
+ const envPath = join(dir, ".env");
43
+
44
+ if (!existsSync(envPath)) {
45
+ throw new Error(`Missing .env file in '${dir}'. Service creation requires an existing .env file.`);
46
+ }
47
+
48
+ let content = "";
49
+ try {
50
+ content = readFileSync(envPath, "utf-8");
51
+ } catch (err) {
52
+ throw new Error(`Failed to read .env file at '${envPath}': ${err.message}`);
53
+ }
54
+
55
+ // Look for PORT=<number>
56
+ const match = content.match(/^\s*PORT\s*=\s*(\d{2,5})\s*$/m);
57
+ if (!match) {
58
+ throw new Error(`PORT is not defined in '${envPath}'. Please define an explicit PORT in .env (e.g. PORT=3004). No default port is allowed.`);
59
+ }
60
+
61
+ const portNum = parseInt(match[1], 10);
62
+ if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
63
+ throw new Error(`Invalid PORT '${match[1]}' in '${envPath}'. Must be between 1 and 65535.`);
64
+ }
65
+
66
+ return {
67
+ port: portNum,
68
+ envPath
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Parses basic systemd unit file to extract WorkingDirectory and PORT.
74
+ */
75
+ export function parseUnitMetadata(filePath) {
76
+ if (!existsSync(filePath)) return null;
77
+
78
+ try {
79
+ const content = readFileSync(filePath, "utf-8");
80
+ const lines = content.split(/\r?\n/);
81
+ let workingDirectory = null;
82
+ let port = null;
83
+
84
+ for (const rawLine of lines) {
85
+ const line = rawLine.trim();
86
+ if (line.startsWith("WorkingDirectory=")) {
87
+ workingDirectory = line.slice("WorkingDirectory=".length).trim();
88
+ }
89
+ if (line.startsWith("Environment=")) {
90
+ const envMatch = line.match(/PORT\s*=\s*(\d{2,5})/i);
91
+ if (envMatch) {
92
+ port = parseInt(envMatch[1], 10);
93
+ }
94
+ }
95
+ }
96
+
97
+ return {
98
+ workingDirectory,
99
+ port
100
+ };
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Guard 4, 5 & 6: Checks for conflicts against existing systemd services.
108
+ * 1. Checks if <subdomain>.service already exists.
109
+ * 2. Checks if current directory is already managed by another service.
110
+ * 3. Checks if the port is already claimed by another service.
111
+ */
112
+ export function checkConflicts({ subdomain, port, workingDir, systemdDir = "/etc/systemd/system", force = false }) {
113
+ if (!existsSync(systemdDir)) {
114
+ // Systemd dir does not exist (e.g. non-linux / local testing without mock dir)
115
+ return { ok: true };
116
+ }
117
+
118
+ const unitFileName = `${subdomain}.service`;
119
+ const targetFilePath = join(systemdDir, unitFileName);
120
+
121
+ // Conflict 1: Service file with same subdomain already exists
122
+ if (existsSync(targetFilePath) && !force) {
123
+ throw new Error(`Service file '${unitFileName}' already exists in '${systemdDir}'. Use --force to overwrite.`);
124
+ }
125
+
126
+ // Scan all existing .service files in systemdDir
127
+ let files = [];
128
+ try {
129
+ files = readdirSync(systemdDir).filter(f => f.endsWith(".service"));
130
+ } catch {
131
+ return { ok: true };
132
+ }
133
+
134
+ const normWorkingDir = normalizePath(workingDir);
135
+
136
+ for (const file of files) {
137
+ // Skip comparing against self when --force is used
138
+ if (file === unitFileName && force) continue;
139
+
140
+ const filePath = join(systemdDir, file);
141
+ const meta = parseUnitMetadata(filePath);
142
+ if (!meta) continue;
143
+
144
+ // Conflict 2: Working directory already assigned to another service
145
+ if (meta.workingDirectory) {
146
+ const normUnitDir = normalizePath(meta.workingDirectory);
147
+ if (normUnitDir === normWorkingDir) {
148
+ throw new Error(`Current directory '${workingDir}' is already managed by existing service '${file}'.`);
149
+ }
150
+ }
151
+
152
+ // Conflict 3: Port already assigned to another service
153
+ if (meta.port && meta.port === port) {
154
+ throw new Error(`Port ${port} is already used by existing service '${file}'.`);
155
+ }
156
+ }
157
+
158
+ return { ok: true };
159
+ }
@@ -0,0 +1,82 @@
1
+ import { generateServiceUnit } from "./generator.js";
2
+ import { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
3
+ import { validateSubdomain, readEnvPort, checkConflicts } from "./guards.js";
4
+
5
+ export { generateServiceUnit } from "./generator.js";
6
+ export { writeServiceUnit, isSystemctlAvailable, DEFAULT_SYSTEMD_DIR } from "./writer.js";
7
+ export { validateSubdomain, readEnvPort, checkConflicts, normalizePath } from "./guards.js";
8
+
9
+ /**
10
+ * Fully guarded high-level service creator.
11
+ * 1. Validates supplied subdomain
12
+ * 2. Reads & verifies PORT from current folder's .env (zero defaults)
13
+ * 3. Checks existing services in /etc/systemd/system/ for folder/port/file conflicts
14
+ * 4. Generates standard unit file
15
+ * 5. Optionally writes and enables service
16
+ */
17
+ export function createService(options = {}) {
18
+ const workingDir = options.workingDirectory || process.cwd();
19
+ const cleanSubdomain = validateSubdomain(options.subdomain || options.name);
20
+ const { port, envPath } = readEnvPort(workingDir);
21
+
22
+ const systemdDir = options.dir || DEFAULT_SYSTEMD_DIR;
23
+
24
+ checkConflicts({
25
+ subdomain: cleanSubdomain,
26
+ port,
27
+ workingDir,
28
+ systemdDir,
29
+ force: Boolean(options.force)
30
+ });
31
+
32
+ const unitContent = generateServiceUnit({
33
+ subdomain: cleanSubdomain,
34
+ port,
35
+ workingDirectory: workingDir,
36
+ execStart: options.execStart,
37
+ user: options.user,
38
+ nodeEnv: options.nodeEnv,
39
+ restartSec: options.restartSec,
40
+ description: options.description
41
+ });
42
+
43
+ const shouldWrite = options.write || options.enable;
44
+
45
+ if (shouldWrite) {
46
+ const writeResult = writeServiceUnit(cleanSubdomain, unitContent, {
47
+ dir: systemdDir,
48
+ enable: options.enable
49
+ });
50
+
51
+ return {
52
+ ...writeResult,
53
+ subdomain: cleanSubdomain,
54
+ port,
55
+ workingDirectory: workingDir,
56
+ envPath,
57
+ content: unitContent
58
+ };
59
+ }
60
+
61
+ return {
62
+ success: true,
63
+ subdomain: cleanSubdomain,
64
+ unitName: `${cleanSubdomain}.service`,
65
+ port,
66
+ workingDirectory: workingDir,
67
+ envPath,
68
+ content: unitContent,
69
+ written: false
70
+ };
71
+ }
72
+
73
+ export default {
74
+ generateServiceUnit,
75
+ writeServiceUnit,
76
+ createService,
77
+ validateSubdomain,
78
+ readEnvPort,
79
+ checkConflicts,
80
+ isSystemctlAvailable,
81
+ DEFAULT_SYSTEMD_DIR
82
+ };
@@ -0,0 +1,66 @@
1
+ import { writeFileSync, mkdirSync, existsSync } from "node:fs";
2
+ import { resolve, join } from "node:path";
3
+ import { execSync } from "node:child_process";
4
+
5
+ export const DEFAULT_SYSTEMD_DIR = "/etc/systemd/system";
6
+
7
+ export function isSystemctlAvailable() {
8
+ if (process.platform !== "linux") return false;
9
+ try {
10
+ execSync("which systemctl 2>/dev/null", { stdio: "ignore" });
11
+ return true;
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+
17
+ export function writeServiceUnit(name, content, options = {}) {
18
+ if (!name) throw new Error("Service name is required to write unit file.");
19
+ if (!content) throw new Error("Unit content is required.");
20
+
21
+ const cleanName = String(name).replace(/\.service$/i, "").trim();
22
+ const unitFileName = `${cleanName}.service`;
23
+ const targetDir = options.dir ? resolve(options.dir) : DEFAULT_SYSTEMD_DIR;
24
+
25
+ if (!existsSync(targetDir)) {
26
+ mkdirSync(targetDir, { recursive: true });
27
+ }
28
+
29
+ const filePath = join(targetDir, unitFileName);
30
+ writeFileSync(filePath, content, "utf-8");
31
+
32
+ let enabled = false;
33
+ let started = false;
34
+ let simulated = false;
35
+
36
+ if (options.enable) {
37
+ if (!isSystemctlAvailable()) {
38
+ simulated = true;
39
+ } else {
40
+ try {
41
+ execSync("systemctl daemon-reload", { stdio: "inherit", timeout: 10000 });
42
+ execSync(`systemctl enable --now ${unitFileName}`, { stdio: "inherit", timeout: 15000 });
43
+ enabled = true;
44
+ started = true;
45
+ } catch (err) {
46
+ return {
47
+ success: true,
48
+ path: filePath,
49
+ unitName: unitFileName,
50
+ enabled: false,
51
+ started: false,
52
+ error: err.message
53
+ };
54
+ }
55
+ }
56
+ }
57
+
58
+ return {
59
+ success: true,
60
+ path: filePath,
61
+ unitName: unitFileName,
62
+ enabled: options.enable ? (simulated ? true : enabled) : false,
63
+ started: options.enable ? (simulated ? true : started) : false,
64
+ simulated
65
+ };
66
+ }