react-client 1.0.28 → 1.0.31

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.
@@ -1,47 +1,41 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = initCmd;
7
- const path_1 = __importDefault(require("path"));
8
- const fs_extra_1 = __importDefault(require("fs-extra"));
9
- const prompts_1 = __importDefault(require("prompts"));
10
- const chalk_1 = __importDefault(require("chalk"));
11
- const child_process_1 = require("child_process");
12
- async function initCmd(name, opts) {
1
+ import path from 'path';
2
+ import fs from 'fs-extra';
3
+ import prompts from 'prompts';
4
+ import chalk from 'chalk';
5
+ import { execSync } from 'child_process';
6
+ export default async function initCmd(name, opts) {
13
7
  const root = process.cwd();
14
- const projectDir = path_1.default.resolve(root, name);
8
+ const projectDir = path.resolve(root, name);
15
9
  const template = opts.template || 'react-ts';
16
- console.log(chalk_1.default.cyan(`\nšŸ“¦ Creating new React Client app: ${chalk_1.default.bold(name)}`));
10
+ console.log(chalk.cyan(`\nšŸ“¦ Creating new React Client app: ${chalk.bold(name)}`));
17
11
  // 1ļøāƒ£ Check if directory exists
18
- if (fs_extra_1.default.existsSync(projectDir)) {
19
- const res = await (0, prompts_1.default)({
12
+ if (fs.existsSync(projectDir)) {
13
+ const res = await prompts({
20
14
  type: 'confirm',
21
15
  name: 'overwrite',
22
- message: chalk_1.default.yellow(`Directory "${name}" already exists. Overwrite?`),
16
+ message: chalk.yellow(`Directory "${name}" already exists. Overwrite?`),
23
17
  initial: false,
24
18
  });
25
19
  if (!res.overwrite) {
26
- console.log(chalk_1.default.red('āŒ Operation cancelled.'));
20
+ console.log(chalk.red('āŒ Operation cancelled.'));
27
21
  process.exit(1);
28
22
  }
29
- await fs_extra_1.default.remove(projectDir);
23
+ await fs.remove(projectDir);
30
24
  }
31
- await fs_extra_1.default.ensureDir(projectDir);
25
+ await fs.ensureDir(projectDir);
32
26
  // 2ļøāƒ£ Locate template
33
- const templateDir = path_1.default.resolve(__dirname, '../../../templates', template);
34
- if (!fs_extra_1.default.existsSync(templateDir)) {
35
- console.error(chalk_1.default.red(`āŒ Template not found: ${template}`));
27
+ const templateDir = path.resolve(__dirname, '../../../templates', template);
28
+ if (!fs.existsSync(templateDir)) {
29
+ console.error(chalk.red(`āŒ Template not found: ${template}`));
36
30
  process.exit(1);
37
31
  }
38
32
  // 3ļøāƒ£ Copy template
39
- console.log(chalk_1.default.gray(`\nšŸ“ Copying template: ${template}...`));
40
- await fs_extra_1.default.copy(templateDir, projectDir);
33
+ console.log(chalk.gray(`\nšŸ“ Copying template: ${template}...`));
34
+ await fs.copy(templateDir, projectDir);
41
35
  // 4ļøāƒ£ Optionally create react-client.config.js (not .ts)
42
36
  if (opts.withConfig) {
43
- const configPath = path_1.default.join(projectDir, 'react-client.config.js');
44
- if (!fs_extra_1.default.existsSync(configPath)) {
37
+ const configPath = path.join(projectDir, 'react-client.config.js');
38
+ if (!fs.existsSync(configPath)) {
45
39
  const configContent = `// react-client.config.js
46
40
  import { defineConfig } from 'react-client/config';
47
41
 
@@ -62,33 +56,33 @@ export default defineConfig({
62
56
  // šŸ’” Add plugins, aliases, etc.
63
57
  });
64
58
  `;
65
- await fs_extra_1.default.writeFile(configPath, configContent, 'utf8');
66
- console.log(chalk_1.default.green('šŸ“ Created react-client.config.js'));
59
+ await fs.writeFile(configPath, configContent, 'utf8');
60
+ console.log(chalk.green('šŸ“ Created react-client.config.js'));
67
61
  }
68
62
  }
69
63
  // 5ļøāƒ£ Initialize git repo
70
64
  try {
71
- (0, child_process_1.execSync)('git init', { cwd: projectDir, stdio: 'ignore' });
72
- console.log(chalk_1.default.gray('šŸ”§ Initialized Git repository.'));
65
+ execSync('git init', { cwd: projectDir, stdio: 'ignore' });
66
+ console.log(chalk.gray('šŸ”§ Initialized Git repository.'));
73
67
  }
74
68
  catch {
75
- console.warn(chalk_1.default.yellow('āš ļø Git init failed (skipping).'));
69
+ console.warn(chalk.yellow('āš ļø Git init failed (skipping).'));
76
70
  }
77
71
  // 6ļøāƒ£ Install dependencies
78
72
  const pkgManager = /yarn/.test(process.env.npm_execpath || '') ? 'yarn' : 'npm';
79
- console.log(chalk_1.default.gray(`\nšŸ“¦ Installing dependencies using ${pkgManager}...`));
73
+ console.log(chalk.gray(`\nšŸ“¦ Installing dependencies using ${pkgManager}...`));
80
74
  try {
81
- (0, child_process_1.execSync)(`${pkgManager} install`, { cwd: projectDir, stdio: 'inherit' });
75
+ execSync(`${pkgManager} install`, { cwd: projectDir, stdio: 'inherit' });
82
76
  }
83
77
  catch {
84
- console.warn(chalk_1.default.yellow('āš ļø Dependency installation failed, please run manually.'));
78
+ console.warn(chalk.yellow('āš ļø Dependency installation failed, please run manually.'));
85
79
  }
86
80
  // 7ļøāƒ£ Completion message
87
81
  console.log();
88
- console.log(chalk_1.default.green('āœ… Project setup complete!'));
89
- console.log(chalk_1.default.cyan(`\nNext steps:`));
90
- console.log(chalk_1.default.gray(` cd ${name}`));
91
- console.log(chalk_1.default.gray(` ${pkgManager === 'yarn' ? 'yarn dev' : 'npm run dev'}`));
82
+ console.log(chalk.green('āœ… Project setup complete!'));
83
+ console.log(chalk.cyan(`\nNext steps:`));
84
+ console.log(chalk.gray(` cd ${name}`));
85
+ console.log(chalk.gray(` ${pkgManager === 'yarn' ? 'yarn dev' : 'npm run dev'}`));
92
86
  console.log();
93
- console.log(chalk_1.default.dim('Happy coding! ⚔'));
87
+ console.log(chalk.dim('Happy coding! ⚔'));
94
88
  }
@@ -1,17 +1,11 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = preview;
7
- const http_1 = __importDefault(require("http"));
8
- const path_1 = __importDefault(require("path"));
9
- const fs_extra_1 = __importDefault(require("fs-extra"));
10
- const chalk_1 = __importDefault(require("chalk"));
11
- const detect_port_1 = __importDefault(require("detect-port"));
12
- const prompts_1 = __importDefault(require("prompts"));
13
- const open_1 = __importDefault(require("open"));
14
- const loadConfig_1 = require("../../utils/loadConfig");
1
+ import http from 'http';
2
+ import path from 'path';
3
+ import fs from 'fs-extra';
4
+ import chalk from 'chalk';
5
+ import detectPort from 'detect-port';
6
+ import prompts from 'prompts';
7
+ import open from 'open';
8
+ import { loadReactClientConfig } from '../../utils/loadConfig';
15
9
  const MIME = {
16
10
  '.html': 'text/html; charset=utf-8',
17
11
  '.js': 'application/javascript; charset=utf-8',
@@ -31,7 +25,7 @@ const MIME = {
31
25
  '.txt': 'text/plain; charset=utf-8',
32
26
  };
33
27
  function contentType(file) {
34
- return MIME[path_1.default.extname(file).toLowerCase()] || 'application/octet-stream';
28
+ return MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
35
29
  }
36
30
  function setCachingHeaders(res, stat) {
37
31
  // Short cache for preview by default, but set ETag/Last-Modified so browsers behave nicely
@@ -40,23 +34,23 @@ function setCachingHeaders(res, stat) {
40
34
  res.setHeader('Last-Modified', stat.mtime.toUTCString());
41
35
  res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate');
42
36
  }
43
- async function preview() {
37
+ export default async function preview() {
44
38
  const cwd = process.cwd();
45
- const config = await (0, loadConfig_1.loadReactClientConfig)(cwd);
46
- const appRoot = path_1.default.resolve(cwd, config.root || '.');
47
- const outDir = path_1.default.join(appRoot, config.build?.outDir || 'dist');
48
- const indexHtml = path_1.default.join(outDir, 'index.html');
49
- if (!(await fs_extra_1.default.pathExists(outDir))) {
50
- console.error(chalk_1.default.red(`āŒ Preview directory not found: ${outDir}`));
39
+ const config = await loadReactClientConfig(cwd);
40
+ const appRoot = path.resolve(cwd, config.root || '.');
41
+ const outDir = path.join(appRoot, config.build?.outDir || 'dist');
42
+ const indexHtml = path.join(outDir, 'index.html');
43
+ if (!(await fs.pathExists(outDir))) {
44
+ console.error(chalk.red(`āŒ Preview directory not found: ${outDir}`));
51
45
  process.exit(1);
52
46
  }
53
- if (!(await fs_extra_1.default.pathExists(indexHtml))) {
54
- console.warn(chalk_1.default.yellow(`āš ļø index.html not found in ${outDir}. SPA fallback will be disabled.`));
47
+ if (!(await fs.pathExists(indexHtml))) {
48
+ console.warn(chalk.yellow(`āš ļø index.html not found in ${outDir}. SPA fallback will be disabled.`));
55
49
  }
56
50
  const defaultPort = config.server?.port || 4173;
57
- const port = await (0, detect_port_1.default)(defaultPort);
51
+ const port = await detectPort(defaultPort);
58
52
  if (port !== defaultPort) {
59
- const r = await (0, prompts_1.default)({
53
+ const r = await prompts({
60
54
  type: 'confirm',
61
55
  name: 'useNewPort',
62
56
  initial: true,
@@ -67,7 +61,7 @@ async function preview() {
67
61
  process.exit(0);
68
62
  }
69
63
  }
70
- const server = http_1.default.createServer(async (req, res) => {
64
+ const server = http.createServer(async (req, res) => {
71
65
  try {
72
66
  const url = req.url || '/';
73
67
  // normalize and protect
@@ -77,13 +71,13 @@ async function preview() {
77
71
  return res.end('Invalid request');
78
72
  }
79
73
  // handle root -> index.html
80
- let filePath = path_1.default.join(outDir, relPath);
74
+ let filePath = path.join(outDir, relPath);
81
75
  const tryIndexFallback = async () => {
82
- if (await fs_extra_1.default.pathExists(indexHtml)) {
83
- const stat = await fs_extra_1.default.stat(indexHtml);
76
+ if (await fs.pathExists(indexHtml)) {
77
+ const stat = await fs.stat(indexHtml);
84
78
  setCachingHeaders(res, stat);
85
79
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
86
- return fs_extra_1.default.createReadStream(indexHtml).pipe(res);
80
+ return fs.createReadStream(indexHtml).pipe(res);
87
81
  }
88
82
  else {
89
83
  res.writeHead(404);
@@ -92,8 +86,8 @@ async function preview() {
92
86
  };
93
87
  // If the request path is a directory, try index.html inside it
94
88
  if (relPath.endsWith('/')) {
95
- const candidate = path_1.default.join(filePath, 'index.html');
96
- if (await fs_extra_1.default.pathExists(candidate)) {
89
+ const candidate = path.join(filePath, 'index.html');
90
+ if (await fs.pathExists(candidate)) {
97
91
  filePath = candidate;
98
92
  }
99
93
  else {
@@ -101,37 +95,37 @@ async function preview() {
101
95
  }
102
96
  }
103
97
  // If file doesn't exist, fallback to index.html for SPA routes
104
- if (!(await fs_extra_1.default.pathExists(filePath))) {
98
+ if (!(await fs.pathExists(filePath))) {
105
99
  // If request appears to be a static asset (has extension), return 404
106
- if (path_1.default.extname(filePath)) {
100
+ if (path.extname(filePath)) {
107
101
  res.writeHead(404);
108
102
  return res.end('Not found');
109
103
  }
110
104
  return tryIndexFallback();
111
105
  }
112
- const stat = await fs_extra_1.default.stat(filePath);
106
+ const stat = await fs.stat(filePath);
113
107
  if (!stat.isFile()) {
114
108
  return tryIndexFallback();
115
109
  }
116
110
  // Compression/Precompressed support: prefer brotli -> gzip -> raw
117
111
  const accept = (req.headers['accept-encoding'] || '');
118
112
  const tryPrecompressed = async () => {
119
- if (accept.includes('br') && (await fs_extra_1.default.pathExists(filePath + '.br'))) {
113
+ if (accept.includes('br') && (await fs.pathExists(filePath + '.br'))) {
120
114
  res.setHeader('Content-Encoding', 'br');
121
115
  res.setHeader('Content-Type', contentType(filePath));
122
116
  setCachingHeaders(res, stat);
123
- return fs_extra_1.default.createReadStream(filePath + '.br').pipe(res);
117
+ return fs.createReadStream(filePath + '.br').pipe(res);
124
118
  }
125
- if (accept.includes('gzip') && (await fs_extra_1.default.pathExists(filePath + '.gz'))) {
119
+ if (accept.includes('gzip') && (await fs.pathExists(filePath + '.gz'))) {
126
120
  res.setHeader('Content-Encoding', 'gzip');
127
121
  res.setHeader('Content-Type', contentType(filePath));
128
122
  setCachingHeaders(res, stat);
129
- return fs_extra_1.default.createReadStream(filePath + '.gz').pipe(res);
123
+ return fs.createReadStream(filePath + '.gz').pipe(res);
130
124
  }
131
125
  // default
132
126
  res.setHeader('Content-Type', contentType(filePath));
133
127
  setCachingHeaders(res, stat);
134
- return fs_extra_1.default.createReadStream(filePath).pipe(res);
128
+ return fs.createReadStream(filePath).pipe(res);
135
129
  };
136
130
  // ETag / If-None-Match handling
137
131
  const etag = `${stat.size}-${Date.parse(stat.mtime.toString())}`;
@@ -151,14 +145,14 @@ async function preview() {
151
145
  });
152
146
  server.listen(port, async () => {
153
147
  const url = `http://localhost:${port}`;
154
- console.log(chalk_1.default.cyan.bold('\nšŸ”Ž react-client preview'));
155
- console.log(chalk_1.default.gray('────────────────────────'));
156
- console.log(chalk_1.default.green(`Serving: ${outDir}`));
157
- console.log(chalk_1.default.green(`Open: ${url}`));
158
- await (0, open_1.default)(url, { newInstance: true });
148
+ console.log(chalk.cyan.bold('\nšŸ”Ž react-client preview'));
149
+ console.log(chalk.gray('────────────────────────'));
150
+ console.log(chalk.green(`Serving: ${outDir}`));
151
+ console.log(chalk.green(`Open: ${url}`));
152
+ await open(url, { newInstance: true });
159
153
  });
160
154
  process.on('SIGINT', () => {
161
- console.log(chalk_1.default.red('\nšŸ›‘ Shutting down preview...'));
155
+ console.log(chalk.red('\nšŸ›‘ Shutting down preview...'));
162
156
  server.close();
163
157
  process.exit(0);
164
158
  });
package/dist/cli/index.js CHANGED
@@ -1,100 +1,99 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- const commander_1 = require("commander");
8
- const path_1 = __importDefault(require("path"));
9
- const fs_extra_1 = __importDefault(require("fs-extra"));
10
- const chalk_1 = __importDefault(require("chalk"));
11
- const init_1 = __importDefault(require("./commands/init"));
12
- const dev_1 = __importDefault(require("./commands/dev"));
13
- const build_1 = __importDefault(require("./commands/build"));
14
- const preview_1 = __importDefault(require("./commands/preview"));
15
- // Load package.json version dynamically
16
- const pkgPath = path_1.default.resolve(__dirname, '../../package.json');
17
- const pkg = fs_extra_1.default.existsSync(pkgPath)
18
- ? JSON.parse(fs_extra_1.default.readFileSync(pkgPath, 'utf8'))
2
+ /**
3
+ * React Client CLI (Vite-like)
4
+ * ---------------------------------------
5
+ * Supports commands: init, dev, build, preview
6
+ * ESM-safe, works with NodeNext and global installs.
7
+ */
8
+ import { Command } from 'commander';
9
+ import path from 'path';
10
+ import fs from 'fs-extra';
11
+ import chalk from 'chalk';
12
+ import { fileURLToPath } from 'url';
13
+ import initCmd from './commands/init.js';
14
+ import devCmd from './commands/dev.js';
15
+ import buildCmd from './commands/build.js';
16
+ import previewCmd from './commands/preview.js';
17
+ // Resolve __dirname safely in ESM
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = path.dirname(__filename);
20
+ // Dynamically load version from package.json
21
+ const pkgPath = path.resolve(__dirname, '../../package.json');
22
+ const pkg = fs.existsSync(pkgPath)
23
+ ? JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
19
24
  : { version: '0.0.0' };
20
- // 🧠 Fancy startup banner
25
+ // 🧠 Banner Display
21
26
  function showBanner(cmd) {
22
- const title = chalk_1.default.bold.cyan('⚔ React Client');
23
- const version = chalk_1.default.gray(`v${pkg.version}`);
24
- const tagline = chalk_1.default.dim('Fast esbuild-based React CLI with HMR & Overlay');
25
- const line = chalk_1.default.gray('──────────────────────────────────────────────────────────────');
27
+ const title = chalk.bold.cyan('⚔ React Client');
28
+ const version = chalk.gray(`v${pkg.version}`);
29
+ const tagline = chalk.dim('Fast esbuild-based React CLI with HMR & Overlay');
30
+ const line = chalk.gray('──────────────────────────────────────────────────────────────');
26
31
  console.log(`\n${title} ${version}`);
27
32
  console.log(tagline);
28
33
  console.log(line);
29
34
  switch (cmd) {
30
35
  case 'init':
31
- console.log(chalk_1.default.cyan('šŸ“¦ Initializing new React project...\n'));
36
+ console.log(chalk.cyan('šŸ“¦ Initializing new React project...\n'));
32
37
  break;
33
38
  case 'dev':
34
- console.log(chalk_1.default.green('šŸš€ Starting development server...\n'));
39
+ console.log(chalk.green('šŸš€ Starting development server...\n'));
35
40
  break;
36
41
  case 'build':
37
- console.log(chalk_1.default.yellow('šŸ—ļø Building for production...\n'));
42
+ console.log(chalk.yellow('šŸ—ļø Building for production...\n'));
38
43
  break;
39
44
  case 'preview':
40
- console.log(chalk_1.default.blue('🌐 Starting production preview server...\n'));
45
+ console.log(chalk.blue('🌐 Starting production preview server...\n'));
41
46
  break;
42
47
  default:
43
48
  console.log();
44
49
  }
45
50
  }
46
- // 🧩 Commander setup
47
- const program = new commander_1.Command();
51
+ // CLI Setup
52
+ const program = new Command();
48
53
  program
49
54
  .name('react-client')
50
- .description('react-client CLI – A lightweight React toolkit for fast builds & dev server')
55
+ .description('react-client CLI – lightweight React toolkit for fast builds & dev server')
51
56
  .version(pkg.version, '-v, --version', 'display version information');
52
- // ------------------------------------------------------
53
- // CLI Commands
54
- // ------------------------------------------------------
57
+ // Commands
55
58
  program
56
59
  .command('init <name>')
57
60
  .option('-t, --template <template>', 'choose a template', 'react-ts')
58
61
  .option('--with-config', 'create a config file')
59
62
  .description('initialize a new React project')
60
- .action((name, opts) => {
63
+ .action(async (name, opts) => {
61
64
  showBanner('init');
62
- (0, init_1.default)(name, opts);
65
+ await initCmd(name, opts);
63
66
  });
64
67
  program
65
68
  .command('dev')
66
- .description('start dev server (with React Fast Refresh)')
67
- .action(() => {
69
+ .description('start development server (with React Fast Refresh)')
70
+ .action(async () => {
68
71
  showBanner('dev');
69
- (0, dev_1.default)();
72
+ await devCmd();
70
73
  });
71
74
  program
72
75
  .command('build')
73
76
  .description('build production assets')
74
- .action(() => {
77
+ .action(async () => {
75
78
  showBanner('build');
76
- (0, build_1.default)();
79
+ await buildCmd();
77
80
  });
78
81
  program
79
82
  .command('preview')
80
83
  .description('preview production build')
81
- .action(() => {
84
+ .action(async () => {
82
85
  showBanner('preview');
83
- (0, preview_1.default)();
86
+ await previewCmd();
84
87
  });
85
- // ------------------------------------------------------
86
- // Default / Unknown command handling
87
- // ------------------------------------------------------
88
+ // Handle unknown commands
88
89
  program.on('command:*', () => {
89
- console.error(chalk_1.default.red('āŒ Invalid command:'), program.args.join(' '));
90
+ console.error(chalk.red('āŒ Invalid command:'), program.args.join(' '));
90
91
  console.log();
91
92
  program.outputHelp();
92
93
  process.exit(1);
93
94
  });
94
- // ------------------------------------------------------
95
- // Entry point
96
- // ------------------------------------------------------
97
- if (require.main === module) {
95
+ // Entry Point (ESM-safe)
96
+ if (import.meta.url === `file://${process.argv[1]}`) {
98
97
  if (process.argv.length <= 2) {
99
98
  console.clear();
100
99
  showBanner();
@@ -104,4 +103,4 @@ if (require.main === module) {
104
103
  program.parse(process.argv);
105
104
  }
106
105
  }
107
- exports.default = program;
106
+ export default program;
package/dist/cli/types.js CHANGED
@@ -1,3 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = {};
1
+ export default {};
package/dist/index.js CHANGED
@@ -1,20 +1,2 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.defineConfig = void 0;
18
- const defineConfig = (c) => c;
19
- exports.defineConfig = defineConfig;
20
- __exportStar(require("./cli/index"), exports);
1
+ export const defineConfig = (c) => c;
2
+ export * from './cli/index';
@@ -1,39 +1,33 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BroadcastManager = void 0;
7
- const ws_1 = require("ws");
8
- const chalk_1 = __importDefault(require("chalk"));
1
+ import { WebSocketServer, WebSocket as NodeWebSocket } from 'ws';
2
+ import chalk from 'chalk';
9
3
  /**
10
4
  * BroadcastManager — Shared WebSocket utility for dev, preview, and SSR servers.
11
5
  * Generic over message type T which defaults to HMRMessage.
12
6
  */
13
- class BroadcastManager {
7
+ export class BroadcastManager {
14
8
  constructor(server) {
15
9
  this.clients = new Set();
16
- this.wss = new ws_1.WebSocketServer({ server });
10
+ this.wss = new WebSocketServer({ server });
17
11
  this.wss.on('connection', (ws) => {
18
12
  this.clients.add(ws);
19
13
  ws.on('close', () => {
20
14
  this.clients.delete(ws);
21
15
  });
22
16
  ws.on('error', (err) => {
23
- console.error(chalk_1.default.red('āš ļø WebSocket error:'), err.message);
17
+ console.error(chalk.red('āš ļø WebSocket error:'), err.message);
24
18
  });
25
19
  });
26
20
  }
27
21
  broadcast(msg) {
28
22
  const data = JSON.stringify(msg);
29
23
  for (const client of this.clients) {
30
- if (client.readyState === ws_1.WebSocket.OPEN) {
24
+ if (client.readyState === NodeWebSocket.OPEN) {
31
25
  client.send(data);
32
26
  }
33
27
  }
34
28
  }
35
29
  send(ws, msg) {
36
- if (ws.readyState === ws_1.WebSocket.OPEN) {
30
+ if (ws.readyState === NodeWebSocket.OPEN) {
37
31
  ws.send(JSON.stringify(msg));
38
32
  }
39
33
  }
@@ -41,7 +35,7 @@ class BroadcastManager {
41
35
  return this.clients.size;
42
36
  }
43
37
  close() {
44
- console.log(chalk_1.default.red('šŸ›‘ Closing WebSocket connections...'));
38
+ console.log(chalk.red('šŸ›‘ Closing WebSocket connections...'));
45
39
  this.wss.close();
46
40
  for (const ws of this.clients) {
47
41
  try {
@@ -54,4 +48,3 @@ class BroadcastManager {
54
48
  this.clients.clear();
55
49
  }
56
50
  }
57
- exports.BroadcastManager = BroadcastManager;