@yunsoft/yuncms 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yunsoft Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @yunsoft/yuncms
2
+
3
+ Command-line setup and runtime launcher for YunCMS.
4
+
5
+ ```bash
6
+ npm install @yunsoft/yuncms
7
+ npx yuncms init
8
+ npx yuncms start
9
+ ```
10
+
11
+ YunCMS requires Node.js 24 LTS and MySQL for V1. See the [project repository](https://github.com/Yunsoft-Software/yuncms) for setup, deployment and API documentation.
package/bin/yuncms.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { loadEnvFileIfPresent } from '@yunsoft/yuncms-core';
4
+ import { runCli } from '../src/cli.js';
5
+
6
+ loadEnvFileIfPresent();
7
+
8
+ runCli().catch((error) => {
9
+ console.error(`YunCMS CLI failed${error?.code ? ` [${error.code}]` : ''}: ${error?.message ?? error}`);
10
+ process.exitCode = 1;
11
+ });
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@yunsoft/yuncms",
3
+ "version": "0.1.0",
4
+ "description": "Command-line setup and runtime launcher for YunCMS.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=24 <25"
9
+ },
10
+ "bin": {
11
+ "yuncms": "./bin/yuncms.js"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/Yunsoft-Software/yuncms.git",
20
+ "directory": "packages/cli"
21
+ },
22
+ "homepage": "https://github.com/Yunsoft-Software/yuncms#readme",
23
+ "bugs": {
24
+ "url": "https://github.com/Yunsoft-Software/yuncms/issues"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "test": "node --test"
31
+ },
32
+ "dependencies": {
33
+ "@yunsoft/yuncms-api": "0.1.0",
34
+ "@yunsoft/yuncms-core": "0.1.0"
35
+ }
36
+ }
@@ -0,0 +1,32 @@
1
+ import {
2
+ bootstrapDatabase,
3
+ closeDatabasePool,
4
+ createDatabasePool,
5
+ loadConfig,
6
+ pingDatabase,
7
+ } from '@yunsoft/yuncms-core';
8
+
9
+ export async function runBootstrapCommand({ env = process.env, output = console } = {}) {
10
+ const config = loadConfig(env);
11
+ const pool = createDatabasePool(config.database);
12
+
13
+ try {
14
+ const connected = await pingDatabase(pool);
15
+ if (!connected) {
16
+ const error = new Error('MySQL connection check returned an unexpected result');
17
+ error.code = 'DATABASE_UNAVAILABLE';
18
+ throw error;
19
+ }
20
+
21
+ const result = await bootstrapDatabase(pool);
22
+ output.log?.(
23
+ result.newlyApplied.length > 0
24
+ ? `YunCMS bootstrap applied: ${result.newlyApplied.join(', ')}`
25
+ : 'YunCMS database is already bootstrapped',
26
+ );
27
+ output.log?.(`Schema version: ${result.schemaVersion}`);
28
+ return result;
29
+ } finally {
30
+ await closeDatabasePool(pool);
31
+ }
32
+ }
package/src/cli.js ADDED
@@ -0,0 +1,54 @@
1
+ import { runBootstrapCommand } from './bootstrap-command.js';
2
+ import { runInitCommand } from './init-command.js';
3
+ import { runStartCommand } from './start-command.js';
4
+
5
+ function assertSupportedNode(version = process.versions.node) {
6
+ const major = Number(String(version).split('.')[0]);
7
+ if (major !== 24) {
8
+ const error = new Error(`YunCMS requires Node.js 24 LTS; current runtime is ${version}`);
9
+ error.code = 'UNSUPPORTED_NODE_VERSION';
10
+ throw error;
11
+ }
12
+ }
13
+
14
+ function printHelp(output) {
15
+ output.log?.(`YunCMS CLI\n\nCommands:\n yuncms init Configure MySQL, bootstrap schema and create the first administrator\n yuncms bootstrap Apply required core database migrations\n yuncms start Start the YunCMS API using the current project environment\n yuncms help Show this help`);
16
+ }
17
+
18
+ export async function runCli(argv = process.argv.slice(2), {
19
+ output = console,
20
+ env = process.env,
21
+ cwd = process.cwd(),
22
+ prompts,
23
+ startCommand = runStartCommand,
24
+ } = {}) {
25
+ assertSupportedNode();
26
+ const [command = 'help', ...rest] = argv;
27
+
28
+ if (rest.length > 0) {
29
+ const error = new Error(`Unexpected arguments for ${command}: ${rest.join(' ')}`);
30
+ error.code = 'INVALID_CLI_ARGUMENTS';
31
+ throw error;
32
+ }
33
+
34
+ switch (command) {
35
+ case 'init':
36
+ return runInitCommand({ env, cwd, output, ...(prompts ? { prompts } : {}) });
37
+ case 'bootstrap':
38
+ return runBootstrapCommand({ env, output });
39
+ case 'start':
40
+ return startCommand({ env, cwd, output });
41
+ case 'help':
42
+ case '--help':
43
+ case '-h':
44
+ printHelp(output);
45
+ return null;
46
+ default: {
47
+ const error = new Error(`Unknown YunCMS command: ${command}`);
48
+ error.code = 'UNKNOWN_CLI_COMMAND';
49
+ throw error;
50
+ }
51
+ }
52
+ }
53
+
54
+ export { assertSupportedNode };
@@ -0,0 +1,25 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+
3
+ function encodeEnvValue(value) {
4
+ const text = String(value ?? '');
5
+ if (text.includes('\n') || text.includes('\r') || text.includes('\0')) {
6
+ const error = new Error('Environment values cannot contain newlines or null bytes');
7
+ error.code = 'INVALID_ENV_VALUE';
8
+ throw error;
9
+ }
10
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
11
+ }
12
+
13
+ export function serializeEnv(values) {
14
+ return `${Object.entries(values)
15
+ .map(([key, value]) => `${key}=${encodeEnvValue(value)}`)
16
+ .join('\n')}\n`;
17
+ }
18
+
19
+ export async function writeEnvFile(path, values) {
20
+ await writeFile(path, serializeEnv(values), {
21
+ encoding: 'utf8',
22
+ mode: 0o600,
23
+ flag: 'wx',
24
+ });
25
+ }
@@ -0,0 +1,112 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ import {
5
+ bootstrapDatabase,
6
+ closeDatabasePool,
7
+ createDatabasePool,
8
+ createInitialAdmin,
9
+ findExistingAdmin,
10
+ loadConfig,
11
+ pingDatabase,
12
+ } from '@yunsoft/yuncms-core';
13
+
14
+ import { writeEnvFile } from './env-file.js';
15
+ import { createInteractivePrompts } from './prompts.js';
16
+
17
+ async function collectEnvironment(prompts) {
18
+ const DB_HOST = await prompts.line('MySQL host', { defaultValue: '127.0.0.1' });
19
+ const DB_PORT = await prompts.line('MySQL port', { defaultValue: '3306' });
20
+ const DB_DATABASE = await prompts.line('MySQL database', { defaultValue: 'yuncms' });
21
+ const DB_USER = await prompts.line('MySQL user', { defaultValue: 'yuncms' });
22
+ const DB_PASSWORD = await prompts.secret('MySQL password');
23
+ const DB_SSL = await prompts.line('Use MySQL TLS (true/false)', { defaultValue: 'false' });
24
+
25
+ return {
26
+ HOST: '127.0.0.1',
27
+ PORT: '8055',
28
+ STUDIO_ORIGIN: 'http://localhost:5173',
29
+ DB_HOST,
30
+ DB_PORT,
31
+ DB_DATABASE,
32
+ DB_USER,
33
+ DB_PASSWORD,
34
+ DB_CONNECTION_LIMIT: '10',
35
+ DB_SSL,
36
+ };
37
+ }
38
+
39
+ async function collectAdmin(prompts) {
40
+ const email = await prompts.line('Administrator email');
41
+ const password = await prompts.secret('Administrator password');
42
+ const confirmation = await prompts.secret('Confirm administrator password');
43
+
44
+ if (password !== confirmation) {
45
+ const error = new Error('Administrator passwords do not match');
46
+ error.code = 'PASSWORD_CONFIRMATION_MISMATCH';
47
+ throw error;
48
+ }
49
+
50
+ return { email, password };
51
+ }
52
+
53
+ export async function runInitCommand({
54
+ env = process.env,
55
+ cwd = process.cwd(),
56
+ output = console,
57
+ prompts = createInteractivePrompts(),
58
+ } = {}) {
59
+ const envPath = join(cwd, '.env');
60
+ const workingEnv = { ...env };
61
+
62
+ if (!existsSync(envPath)) {
63
+ output.log?.('YunCMS setup: database configuration');
64
+ const collected = await collectEnvironment(prompts);
65
+ const config = loadConfig(collected);
66
+ void config;
67
+ await writeEnvFile(envPath, collected);
68
+ Object.assign(workingEnv, collected);
69
+ output.log?.(`Created ${envPath}`);
70
+ } else {
71
+ output.log?.(`Using existing ${envPath}`);
72
+ }
73
+
74
+ const config = loadConfig(workingEnv);
75
+ const pool = createDatabasePool(config.database);
76
+
77
+ try {
78
+ const connected = await pingDatabase(pool);
79
+ if (!connected) {
80
+ const error = new Error('MySQL connection check returned an unexpected result');
81
+ error.code = 'DATABASE_UNAVAILABLE';
82
+ throw error;
83
+ }
84
+ output.log?.('MySQL connection verified');
85
+
86
+ const bootstrap = await bootstrapDatabase(pool);
87
+ output.log?.(
88
+ bootstrap.newlyApplied.length > 0
89
+ ? `Applied migrations: ${bootstrap.newlyApplied.join(', ')}`
90
+ : 'Database migrations are already current',
91
+ );
92
+
93
+ const existingAdmin = await findExistingAdmin(pool);
94
+ if (existingAdmin) {
95
+ output.log?.(`Administrator already exists: ${existingAdmin.email}`);
96
+ output.log?.(`YunCMS API: http://${config.server.host}:${config.server.port}`);
97
+ output.log?.(`YunCMS Studio: ${config.server.studioOrigin}`);
98
+ return { bootstrap, admin: existingAdmin, existingAdmin: true };
99
+ }
100
+
101
+ output.log?.('YunCMS setup: first administrator');
102
+ const adminInput = await collectAdmin(prompts);
103
+ const admin = await createInitialAdmin(pool, adminInput);
104
+ output.log?.(`Created administrator: ${admin.email}`);
105
+ output.log?.(`YunCMS API: http://${config.server.host}:${config.server.port}`);
106
+ output.log?.(`YunCMS Studio: ${config.server.studioOrigin}`);
107
+
108
+ return { bootstrap, admin, existingAdmin: false };
109
+ } finally {
110
+ await closeDatabasePool(pool);
111
+ }
112
+ }
package/src/prompts.js ADDED
@@ -0,0 +1,99 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+
3
+ export async function promptLine(message, {
4
+ defaultValue = null,
5
+ input = process.stdin,
6
+ output = process.stdout,
7
+ } = {}) {
8
+ const suffix = defaultValue == null ? ': ' : ` [${defaultValue}]: `;
9
+ const readline = createInterface({ input, output });
10
+
11
+ try {
12
+ const answer = await readline.question(`${message}${suffix}`);
13
+ const trimmed = answer.trim();
14
+ return trimmed === '' && defaultValue != null ? String(defaultValue) : trimmed;
15
+ } finally {
16
+ readline.close();
17
+ }
18
+ }
19
+
20
+ export async function promptSecret(message, {
21
+ input = process.stdin,
22
+ output = process.stdout,
23
+ } = {}) {
24
+ if (!input.isTTY || !output.isTTY || typeof input.setRawMode !== 'function') {
25
+ const error = new Error('Secret prompts require an interactive TTY');
26
+ error.code = 'INTERACTIVE_TTY_REQUIRED';
27
+ throw error;
28
+ }
29
+
30
+ output.write(`${message}: `);
31
+ const previousRaw = input.isRaw === true;
32
+ const wasPaused = typeof input.isPaused === 'function' ? input.isPaused() : false;
33
+ const previousEncoding = input.readableEncoding ?? null;
34
+
35
+ return new Promise((resolve, reject) => {
36
+ let value = '';
37
+ let finished = false;
38
+
39
+ function onError(error) {
40
+ finish(error);
41
+ }
42
+
43
+ function cleanup() {
44
+ input.off('data', onData);
45
+ input.off('error', onError);
46
+ input.setRawMode(previousRaw);
47
+ if (previousEncoding) input.setEncoding(previousEncoding);
48
+ if (wasPaused) input.pause();
49
+ }
50
+
51
+ function finish(error = null) {
52
+ if (finished) return;
53
+ finished = true;
54
+ cleanup();
55
+ output.write('\n');
56
+ if (error) reject(error);
57
+ else resolve(value);
58
+ }
59
+
60
+ function onData(chunk) {
61
+ for (const character of String(chunk)) {
62
+ if (character === '\u0003') {
63
+ const error = new Error('Prompt cancelled');
64
+ error.code = 'PROMPT_CANCELLED';
65
+ finish(error);
66
+ return;
67
+ }
68
+ if (character === '\r' || character === '\n') {
69
+ finish();
70
+ return;
71
+ }
72
+ if (character === '\u007f' || character === '\b') {
73
+ if (value.length > 0) {
74
+ value = value.slice(0, -1);
75
+ output.write('\b \b');
76
+ }
77
+ continue;
78
+ }
79
+ if (character >= ' ') {
80
+ value += character;
81
+ output.write('*');
82
+ }
83
+ }
84
+ }
85
+
86
+ input.setEncoding('utf8');
87
+ input.setRawMode(true);
88
+ input.resume();
89
+ input.on('data', onData);
90
+ input.once('error', onError);
91
+ });
92
+ }
93
+
94
+ export function createInteractivePrompts(options = {}) {
95
+ return {
96
+ line: (message, promptOptions = {}) => promptLine(message, { ...options, ...promptOptions }),
97
+ secret: (message, promptOptions = {}) => promptSecret(message, { ...options, ...promptOptions }),
98
+ };
99
+ }
@@ -0,0 +1,59 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ export async function runStartCommand({
5
+ env = process.env,
6
+ cwd = process.cwd(),
7
+ output = console,
8
+ spawnProcess = spawn,
9
+ signalSource = process,
10
+ } = {}) {
11
+ const serverUrl = import.meta.resolve('@yunsoft/yuncms-api/server');
12
+ const serverPath = fileURLToPath(serverUrl);
13
+
14
+ output.log?.(`Starting YunCMS API from ${cwd}`);
15
+
16
+ const child = spawnProcess(process.execPath, [serverPath], {
17
+ cwd,
18
+ env: { ...env },
19
+ stdio: 'inherit',
20
+ detached: process.platform !== 'win32',
21
+ });
22
+
23
+ return new Promise((resolve, reject) => {
24
+ let forwardedSignal = null;
25
+ const signalHandlers = new Map(
26
+ ['SIGINT', 'SIGTERM'].map((signal) => [signal, () => {
27
+ if (forwardedSignal || child.exitCode != null || child.signalCode != null) return;
28
+ forwardedSignal = signal;
29
+ child.kill(signal);
30
+ }]),
31
+ );
32
+ const cleanup = () => {
33
+ for (const [signal, handler] of signalHandlers) signalSource.off(signal, handler);
34
+ };
35
+ for (const [signal, handler] of signalHandlers) signalSource.on(signal, handler);
36
+
37
+ child.once('error', (error) => {
38
+ cleanup();
39
+ error.code ||= 'API_START_FAILED';
40
+ reject(error);
41
+ });
42
+ child.once('exit', (code, signal) => {
43
+ cleanup();
44
+ if (code === 0 || (signal && signal === forwardedSignal)) {
45
+ resolve({ code: 0, signal });
46
+ return;
47
+ }
48
+ const error = new Error(
49
+ signal
50
+ ? `YunCMS API exited after signal ${signal}`
51
+ : `YunCMS API exited with code ${code}`,
52
+ );
53
+ error.code = 'API_EXITED';
54
+ error.exitCode = code;
55
+ error.signal = signal;
56
+ reject(error);
57
+ });
58
+ });
59
+ }