scripting-cli 1.1.12 → 1.2.1

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/src/controller.ts CHANGED
@@ -1,10 +1,11 @@
1
1
 
2
2
  import chokidar, { FSWatcher } from 'chokidar';
3
3
  import { Socket } from 'socket.io';
4
- import { ensureDirectoryExistence, getPath, getRelativePath, md5, tryOpenFileInVSCode, writeDtsFiles } from './util';
4
+ import { ensureDirectoryExistence, getRelativePath, getScriptPath, md5, tryOpenFileInVSCode, writeDtsFiles } from './util';
5
5
  import fs from 'fs';
6
6
  import chalk from 'chalk';
7
7
  import path from 'path';
8
+ import { globalDtsFileName, scriptingDtsFileName } from './const';
8
9
 
9
10
  export class Controller {
10
11
 
@@ -52,10 +53,10 @@ export class Controller {
52
53
  socket.removeAllListeners();
53
54
  });
54
55
 
55
- fs.promises.readdir(process.cwd()).then((files) => {
56
+ fs.promises.readdir(getScriptPath()).then((files) => {
56
57
  const serverScriptNames = files.filter((filename) =>
57
- fs.statSync(filename).isDirectory()
58
- && filename !== '.vscode'
58
+ fs.statSync(getScriptPath(filename)).isDirectory()
59
+ && !filename.startsWith('.')
59
60
  && filename !== 'dts'
60
61
  )
61
62
  socket.emit("serverScripts", serverScriptNames);
@@ -63,7 +64,7 @@ export class Controller {
63
64
  }
64
65
 
65
66
  createWatcher(scriptName: string) {
66
- const scriptDir = getPath(scriptName)
67
+ const scriptDir = getScriptPath(scriptName)
67
68
  this.watcher = chokidar.watch(scriptDir, {
68
69
  ignored: /(^|[\/\\])\../,
69
70
  persistent: true,
@@ -112,8 +113,8 @@ export class Controller {
112
113
  }
113
114
 
114
115
  handleSyncScriptFromClient = async (data: {
115
- 'global.d.ts': string,
116
- 'scripting.d.ts': string,
116
+ [globalDtsFileName]: string,
117
+ [scriptingDtsFileName]: string,
117
118
  scriptName: string
118
119
  scriptFiles: Record<string, string>
119
120
  }, ack: (result: {
@@ -136,22 +137,13 @@ export class Controller {
136
137
  }
137
138
 
138
139
  await writeDtsFiles({
139
- "global.d.ts": data["global.d.ts"],
140
- "scripting.d.ts": data["scripting.d.ts"],
140
+ [globalDtsFileName]: data[globalDtsFileName],
141
+ [scriptingDtsFileName]: data[scriptingDtsFileName],
141
142
  });
142
143
 
143
144
  this.scriptName = data.scriptName;
144
145
 
145
- const scriptName = data.scriptName;
146
-
147
- const scriptDir = getPath(data.scriptName);
148
-
149
- const tsconfig = require(getPath('tsconfig.json'));
150
-
151
- if (!tsconfig.include.includes(scriptName)) {
152
- tsconfig.include.push(scriptName);
153
- await fs.promises.writeFile(getPath('tsconfig.json'), JSON.stringify(tsconfig, null, 2))
154
- }
146
+ const scriptDir = getScriptPath(data.scriptName);
155
147
 
156
148
  ensureDirectoryExistence(scriptDir);
157
149
 
@@ -163,7 +155,7 @@ export class Controller {
163
155
  })
164
156
  );
165
157
 
166
- console.log(chalk.green('global.d.ts and scripting.d.ts and other script files saved.'));
158
+ console.log(chalk.green(`${globalDtsFileName} and ${scriptingDtsFileName} and other script files saved.`));
167
159
 
168
160
  this.createWatcher(data.scriptName);
169
161
 
@@ -216,11 +208,11 @@ export class Controller {
216
208
  }
217
209
 
218
210
  await writeDtsFiles({
219
- "global.d.ts": data["global.d.ts"],
220
- "scripting.d.ts": data["scripting.d.ts"],
211
+ globalDtsFileName: data[globalDtsFileName],
212
+ scriptingDtsFileName: data[scriptingDtsFileName],
221
213
  });
222
214
 
223
- const scriptDir = getPath(data.scriptName);
215
+ const scriptDir = getScriptPath(data.scriptName);
224
216
 
225
217
  if (!fs.existsSync(scriptDir)) {
226
218
  ack({
@@ -238,6 +230,10 @@ export class Controller {
238
230
  const files = await fs.promises.readdir(dir, { withFileTypes: true });
239
231
  await Promise.all(
240
232
  files.map(async (file) => {
233
+ // ignore .git and .vscode directories
234
+ if (file.name.startsWith('.git') || file.name.startsWith('.vscode')) {
235
+ return;
236
+ }
241
237
  if (file.isFile()) {
242
238
  const filePath = path.join(dir, file.name);
243
239
  const relativePath = getRelativePath(scriptDir, filePath);
@@ -303,7 +299,7 @@ export class Controller {
303
299
  return;
304
300
  }
305
301
 
306
- const filePath = path.join(getPath(this.scriptName), data.relativePath)
302
+ const filePath = path.join(getScriptPath(this.scriptName), data.relativePath)
307
303
 
308
304
  if (!this.noAutoOpen && fs.existsSync(filePath)) {
309
305
  tryOpenFileInVSCode(filePath)
@@ -337,7 +333,7 @@ export class Controller {
337
333
  return;
338
334
  }
339
335
 
340
- const filePath = path.join(getPath(data.scriptName), data.relativePath);
336
+ const filePath = path.join(getScriptPath(data.scriptName), data.relativePath);
341
337
  try {
342
338
  const content = await fs.promises.readFile(filePath, 'utf-8');
343
339
  ack({
package/src/index.ts CHANGED
@@ -32,13 +32,39 @@ yargs(hideBin(process.argv))
32
32
  .example([
33
33
  ["$0 start --no-auto-open", "Start server without opening the index.tsx/widget.tsx file"],
34
34
  ["$0 start --no-auto-open -p=8000", "Start server without opening the index.tsx/widget.tsx file and listen on 8000"],
35
- ]);
35
+ ])
36
+ .options({
37
+ "bonjour": {
38
+ type: "boolean",
39
+ describe: "Enable bonjour service",
40
+ },
41
+ })
42
+ .usage("$0 start [--bonjour]")
43
+ .example([
44
+ ["$0 start --bonjour", "Start server with bonjour service"],
45
+ ["$0 start --bonjour -p=8000", "Start server with bonjour service and listen on 8000"],
46
+ ["$0 start --bonjour --no-auto-open", "Start server with bonjour service without opening the index.tsx/widget.tsx file"],
47
+ ["$0 start --bonjour --no-auto-open -p=8000", "Start server with bonjour service without opening the index.tsx/widget.tsx file and listen on 8000"],
48
+ ])
49
+ ;
36
50
  }, (argv) => {
37
51
  startServer({
38
52
  port: argv.port,
39
- noAutoOpen: argv['no-auto-open'] as any,
53
+ noAutoOpen: argv['no-auto-open'],
54
+ startBonjourService: argv.bonjour,
40
55
  });
41
56
  })
57
+ .command('migrate', 'Migrate the scripts in the workspace root directory to the scripts directory.', (yargs) => {
58
+ return yargs
59
+ .usage("$0 migrate")
60
+ .example([
61
+ ["$0 migrate", "Migrate the scripts in the workspace root directory to the scripts directory."]
62
+ ]);
63
+ }, async () => {
64
+ const { migrateOldFiles } = await import('./util');
65
+ await migrateOldFiles();
66
+ process.exit(0);
67
+ })
42
68
  .showHelpOnFail(true)
43
69
  .option('help', {
44
70
  alias: 'h',
@@ -6,7 +6,7 @@ import ip from 'ip';
6
6
  import Bonjour from 'bonjour';
7
7
  import chalk from 'chalk';
8
8
  import qrcode from 'qrcode-terminal';
9
- import { createTsConfig, createVSCodeSettings, } from './util';
9
+ import { createTsConfig, createVSCodeSettings, ensureScriptsDirectory, } from './util';
10
10
  import { Controller } from './controller';
11
11
  import { initHttpRouter } from './http_router';
12
12
 
@@ -15,9 +15,10 @@ const server = http.createServer(app);
15
15
  const io = new SocketIOServer(server);
16
16
  const bonjour = Bonjour();
17
17
 
18
- export function startServer({ port, noAutoOpen }: {
18
+ export function startServer({ port, noAutoOpen, startBonjourService }: {
19
19
  port: number | undefined
20
20
  noAutoOpen: boolean | undefined
21
+ startBonjourService: boolean | undefined
21
22
  }) {
22
23
 
23
24
  // console.log("port", port, "noAutoOpen", noAutoOpen);
@@ -31,51 +32,63 @@ export function startServer({ port, noAutoOpen }: {
31
32
  console.log(chalk.blue(`Client [${socket.id}] connected`));
32
33
  });
33
34
 
34
- server.listen(PORT, () => {
35
+ server.listen(PORT, async () => {
35
36
  createTsConfig(); // Create tsconfig.json when the server starts
36
37
  createVSCodeSettings(); // Create vscode settings.json when the server starts
38
+ ensureScriptsDirectory(); // Ensure the scripts directory exists
39
+
40
+ // await migrateOldFiles(); // Migrate old files to the scripts directory
37
41
 
38
42
  const ipAddress = ip.address()
39
43
  const address = `http://${ipAddress}:${PORT}`;
40
44
 
41
- console.log(`Server listening on ${chalk.bold.blue(address)}\nYou can select this server in the Scripting app to connect.\n`);
45
+ if (startBonjourService) {
46
+ console.log(`Server listening on ${chalk.bold.blue(address)}\n\n${chalk.yellow('You can select this server in the Scripting app to connect')}.\n`);
47
+
48
+ console.log(`Alternatively, you can ${chalk.green.bold("use the Scripting app to scan")} the QR code and connect: `);
49
+ } else {
50
+ console.log(chalk.yellow.italic(`The bonjour service is not started, you can use \`--bonjour\` option to start it.`));
51
+ console.log(`Server listening on ${chalk.bold.blue(address)}\nYou can ${chalk.green.bold("use the Scripting app to scan")} the QR code and connect: `);
52
+ }
42
53
 
43
- console.log(`Alternatively, you can ${chalk.green.bold("use the Scripting app to scan")} the QR code and connect: `);
44
54
  qrcode.generate(address, { small: true });
45
55
 
46
- const service = bonjour.publish({
47
- name: 'Scripting-service',
48
- type: 'http',
49
- port: PORT,
50
- host: 'scripting-service.local',
51
- });
52
-
53
- // Register bonjour service error handler
54
- service.on('error', err => {
55
- console.error('Bonjour service error:', err);
56
- });
57
-
58
- ['SIGINT', 'SIGTERM'].forEach(sig =>
59
- process.once(sig, gracefulShutdown)
60
- );
61
-
62
- // Handle uncaught exceptions
63
- process.on('uncaughtException', err => {
64
- console.error('Uncaught exception:', err);
65
- gracefulShutdown();
66
- });
67
-
68
- function gracefulShutdown() {
69
- console.log('Shutting down Bonjour…');
70
- service.stop(() => {
71
- bonjour.unpublishAll(() => {
72
- // wait for 500ms,let goodbye message be sent completely
73
- setTimeout(() => {
74
- bonjour.destroy();
75
- console.log('Bonjour services have been shut down properly.');
76
- process.exit(0);
77
- }, 500);
56
+ if (startBonjourService) {
57
+
58
+ function gracefulShutdown() {
59
+ console.log('Shutting down Bonjour...');
60
+ service.stop(() => {
61
+ bonjour.unpublishAll(() => {
62
+ // wait for 500ms,let goodbye message be sent completely
63
+ setTimeout(() => {
64
+ bonjour.destroy();
65
+ console.log('Bonjour services have been shut down properly.');
66
+ process.exit(0);
67
+ }, 500);
68
+ });
78
69
  });
70
+ }
71
+
72
+ const service = bonjour.publish({
73
+ name: 'Scripting-service',
74
+ type: 'http',
75
+ port: PORT,
76
+ host: 'scripting-service.local',
77
+ });
78
+
79
+ // Register bonjour service error handler
80
+ service.on('error', err => {
81
+ console.error('Bonjour service error:', err);
82
+ });
83
+
84
+ ['SIGINT', 'SIGTERM'].forEach(sig =>
85
+ process.once(sig, gracefulShutdown)
86
+ );
87
+
88
+ // Handle uncaught exceptions
89
+ process.on('uncaughtException', err => {
90
+ console.error('Uncaught exception:', err);
91
+ gracefulShutdown();
79
92
  });
80
93
  }
81
94
 
package/src/util.ts CHANGED
@@ -4,6 +4,7 @@ import os from 'os';
4
4
  import childProcess from 'child_process';
5
5
  import fs from 'fs';
6
6
  import chalk from 'chalk';
7
+ import { globalDtsFileName, scriptingDtsFileName } from './const';
7
8
 
8
9
  export function md5(content: string): string {
9
10
  return crypto
@@ -16,6 +17,13 @@ export function getPath(filename: string) {
16
17
  return path.join(process.cwd(), filename);
17
18
  }
18
19
 
20
+ export function getScriptPath(filename?: string) {
21
+ if (filename != null) {
22
+ return path.join(process.cwd(), 'scripts', filename);
23
+ }
24
+ return path.join(process.cwd(), 'scripts');
25
+ }
26
+
19
27
  export function tryOpenFileInVSCode(filePath: string) {
20
28
  let cmd = `code "${filePath}"`;
21
29
  if (os.platform() === "win32") {
@@ -52,12 +60,13 @@ export function createTsConfig() {
52
60
  "jsxFragmentFactory": "Fragment",
53
61
  "paths": {
54
62
  "scripting": [
55
- "./dts/scripting.d.ts"
63
+ "./dts/${scriptingDtsFileName}"
56
64
  ]
57
65
  }
58
66
  },
59
67
  "include": [
60
- "./dts/global.d.ts"
68
+ "./dts/${globalDtsFileName}",
69
+ "scripts"
61
70
  ]
62
71
  }`;
63
72
 
@@ -68,7 +77,17 @@ export function createTsConfig() {
68
77
  fs.writeFileSync(filePath, tsconfigContent);
69
78
  console.log(chalk.green('tsconfig.json created.'));
70
79
  } else {
71
- console.log(chalk.gray('tsconfig.json already exists.'));
80
+ const tsconfig = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
81
+ if (tsconfig.include && !tsconfig.include.includes('scripts')) {
82
+ tsconfig.include = [
83
+ `./dts/${globalDtsFileName}`,
84
+ "scripts"
85
+ ];
86
+ fs.writeFileSync(filePath, JSON.stringify(tsconfig, null, 2));
87
+ console.log(chalk.yellow('tsconfig.json updated to include scripts directory.'));
88
+ } else {
89
+ console.log(chalk.gray('tsconfig.json already exists.'));
90
+ }
72
91
  }
73
92
  }
74
93
 
@@ -89,6 +108,16 @@ export function createVSCodeSettings() {
89
108
 
90
109
  }
91
110
 
111
+ export function ensureScriptsDirectory() {
112
+ const scriptsDir = getScriptPath();
113
+ if (!fs.existsSync(scriptsDir)) {
114
+ fs.mkdirSync(scriptsDir, { recursive: true });
115
+ console.log(chalk.green('Scripts directory created.'));
116
+ } else {
117
+ console.log(chalk.gray('Scripts directory already exists.'));
118
+ }
119
+ }
120
+
92
121
  export function ensureDirectoryExistence(filePath: string) {
93
122
  const dirname = path.dirname(filePath);
94
123
  if (!fs.existsSync(dirname)) {
@@ -116,3 +145,47 @@ export function getRelativePath(from: string, to: string) {
116
145
  const relativePath = path.relative(from, to);
117
146
  return relativePath.replaceAll("\\", "/");
118
147
  }
148
+
149
+ export async function migrateOldFiles() {
150
+ try {
151
+ const list = await fs.promises.readdir(process.cwd());
152
+ let hasMigrated = false;
153
+
154
+ for (const file of list) {
155
+
156
+ if (file === 'dts' || file == "scripts" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules' || file.startsWith('.')) {
157
+ continue;
158
+ }
159
+
160
+ const filePath = path.join(process.cwd(), file);
161
+
162
+ const stat = await fs.promises.stat(filePath);
163
+
164
+ if (!stat.isDirectory()) {
165
+ continue;
166
+ }
167
+
168
+ const newFilePath = path.join(process.cwd(), 'scripts', file);
169
+
170
+ if (fs.existsSync(newFilePath)) {
171
+ console.log(chalk.yellow(`File ${newFilePath} already exists, skipping...`));
172
+ continue;
173
+ }
174
+
175
+ hasMigrated = true;
176
+ console.log(chalk.blue(`Moving ${filePath} to ${newFilePath}`));
177
+ await fs.promises.rename(filePath, newFilePath);
178
+
179
+ }
180
+
181
+ if (hasMigrated) {
182
+ console.log(chalk.green('Old files migrated to the scripts directory.'));
183
+ } else {
184
+ console.log(chalk.gray('No old files to migrate.'));
185
+ }
186
+
187
+ } catch (err) {
188
+ console.log(`Failed to migrate old files: ${chalk.red(`${err}`)}`);
189
+ }
190
+
191
+ }