scripting-cli 1.2.4 → 1.3.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/src/controller.ts DELETED
@@ -1,393 +0,0 @@
1
-
2
- import chokidar, { FSWatcher } from 'chokidar';
3
- import { Socket } from 'socket.io';
4
- import { ensureDirectoryExistence, getRelativePath, getScriptPath, md5, tryOpenFileInVSCode, writeDtsFiles } from './util';
5
- import fs from 'fs';
6
- import chalk from 'chalk';
7
- import path from 'path';
8
- import { globalDtsFileName, scriptingDtsFileName } from './const';
9
-
10
- export class Controller {
11
-
12
- private static instances: Map<string, Controller> = new Map();
13
-
14
- static create(socket: Socket, noAutoOpen: boolean | undefined) {
15
- const ctrl = new Controller(socket, noAutoOpen);
16
- Controller.instances.set(socket.id, ctrl);
17
- return ctrl;
18
- }
19
-
20
- static get(socketId: string) {
21
- return Controller.instances.get(socketId);
22
- }
23
-
24
- watcher: FSWatcher | null = null;
25
- scriptName: string | null = null;
26
- socket: Socket | null = null;
27
- noAutoOpen: boolean | undefined;
28
-
29
- constructor(socket: Socket, noAutoOpen: boolean | undefined) {
30
- this.noAutoOpen = noAutoOpen;
31
- this.socket = socket;
32
-
33
- socket.emit("socketId", socket.id);
34
-
35
- // socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
36
-
37
- // socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
38
-
39
- // socket.on("getFileContent", this.handleGetFileContent);
40
-
41
- socket.on('stopDebugScript', this.handleStopDebugScript);
42
-
43
- socket.on("log", this.handleLog);
44
-
45
- socket.on("openFile", this.handleOpenFile)
46
-
47
- socket.on('disconnect', (reason) => {
48
- console.log(chalk.gray(`Client [${socket.id}] disconnected: ${reason}`));
49
- this.watcher?.close();
50
- this.watcher = null;
51
- this.scriptName = null;
52
- Controller.instances.delete(socket.id);
53
- socket.removeAllListeners();
54
- });
55
-
56
- fs.promises.readdir(getScriptPath()).then((files) => {
57
- const serverScriptNames = files.filter((filename) =>
58
- fs.statSync(getScriptPath(filename)).isDirectory()
59
- && !filename.startsWith('.')
60
- && filename !== 'dts'
61
- )
62
- socket.emit("serverScripts", serverScriptNames);
63
- })
64
- }
65
-
66
- createWatcher(scriptName: string) {
67
- const scriptDir = getScriptPath(scriptName)
68
- this.watcher = chokidar.watch(scriptDir, {
69
- ignored: /(^|[\/\\])\../,
70
- persistent: true,
71
- });
72
-
73
- const updateHandler = (filePath: string) => {
74
- if (filePath.match(/\.(js(x)?|ts(x)?|json|md|txt)$/)) {
75
- // send file content md5 hash to client
76
- // const content = fs.readFileSync(filePath, 'utf-8');
77
- fs.readFile(filePath, 'utf-8', (err, content) => {
78
- if (err) {
79
- console.log(chalk.red(`Error reading file: ${err}`));
80
- return;
81
- }
82
- const hash = md5(content);
83
- const relativePath = getRelativePath(scriptDir, filePath);
84
- console.log(
85
- `[${chalk.bold.blue(scriptName)}] File changed: [${hash}]${relativePath}`
86
- )
87
- this.socket?.emit('fileChange', {
88
- scriptName,
89
- filePath: relativePath,
90
- hash,
91
- });
92
- });
93
- } else {
94
- // Other file types, just notify the client to reload the file
95
- const relativePath = getRelativePath(scriptDir, filePath);
96
- console.log(
97
- `[${chalk.bold.blue(scriptName)}] File changed: ${relativePath}`
98
- )
99
- this.socket?.emit('otherFileChange', {
100
- scriptName,
101
- filePath: relativePath,
102
- });
103
- }
104
- };
105
-
106
- const deleteHandler = (filePath: string) => {
107
- const relativePath = getRelativePath(scriptDir, filePath);
108
- this.socket?.emit('deleteFile', {
109
- scriptName,
110
- filePath: relativePath,
111
- });
112
- };
113
-
114
- this.watcher
115
- .on('add', updateHandler)
116
- .on('change', updateHandler)
117
- .on('unlink', deleteHandler)
118
- .on('unlinkDir', deleteHandler)
119
- .on('error', error => console.log(chalk.bgRed(`Watcher error: ${error}`)))
120
- .on('ready', () => console.log(`[${chalk.bold.blue(scriptName)}] Watching files for changes`));
121
- }
122
-
123
- handleSyncScriptFromClient = async (data: {
124
- [globalDtsFileName]: string,
125
- [scriptingDtsFileName]: string,
126
- scriptName: string
127
- scriptFiles: Record<string, string>
128
- }, ack: (result: {
129
- error?: string
130
- success?: boolean
131
- }) => void) => {
132
-
133
- try {
134
- if (data.scriptName === this.scriptName) {
135
- ack({
136
- error: `Script [${data.scriptName}] is already initialized`,
137
- });
138
- return;
139
- }
140
-
141
- if (this.scriptName != null) {
142
- console.log(`Received new script, closing previous watcher`);
143
- this.watcher?.close();
144
- this.watcher = null;
145
- }
146
-
147
- await writeDtsFiles({
148
- [globalDtsFileName]: data[globalDtsFileName],
149
- [scriptingDtsFileName]: data[scriptingDtsFileName],
150
- });
151
-
152
- this.scriptName = data.scriptName;
153
-
154
- const scriptDir = getScriptPath(data.scriptName);
155
-
156
- ensureDirectoryExistence(scriptDir);
157
-
158
- await Promise.all(
159
- Object.entries(data.scriptFiles).map(async ([filename, content]) => {
160
- const filePath = path.join(scriptDir, filename);
161
- ensureDirectoryExistence(filePath);
162
- await fs.promises.writeFile(filePath, content);
163
- })
164
- );
165
-
166
- console.log(chalk.green(`${globalDtsFileName} and ${scriptingDtsFileName} and other script files saved.`));
167
-
168
- this.createWatcher(data.scriptName);
169
-
170
- ack({
171
- success: true,
172
- });
173
-
174
- if (!this.noAutoOpen) {
175
-
176
- // Open the entry file in VSCode after a delay
177
- // to ensure the response is sent. Because the open file command
178
- // may suspend the response and cause the client to not receive the ack.
179
- setTimeout(() => {
180
- const entryFilePath = path.join(scriptDir, "index.tsx")
181
- tryOpenFileInVSCode(entryFilePath);
182
- }, 1000);
183
- }
184
-
185
- } catch (e) {
186
- console.log(chalk.red(`Error: ${e}`));
187
- ack({
188
- error: `Failed to init and sync script files.\n${e}`,
189
- })
190
- }
191
-
192
- }
193
-
194
- handleSyncScriptFromServer = async (data: {
195
- 'global.d.ts': string,
196
- 'scripting.d.ts': string,
197
- scriptName: string,
198
- }, ack: (result: {
199
- error?: string,
200
- scriptFiles?: Record<string, {
201
- hash: string
202
- content: string
203
- }>
204
- otherFiles?: string[]
205
- }) => void) => {
206
- try {
207
- if (this.scriptName === data.scriptName) {
208
- ack({
209
- error: `Script ${data.scriptName} is already initialized`,
210
- });
211
- return;
212
- }
213
- if (this.scriptName != null) {
214
- console.log(`Received new script [${chalk.bold.blue(data.scriptName)}], closing previous watcher`);
215
- this.watcher?.close();
216
- this.watcher = null;
217
- }
218
-
219
- await writeDtsFiles({
220
- [globalDtsFileName]: data[globalDtsFileName],
221
- [scriptingDtsFileName]: data[scriptingDtsFileName],
222
- });
223
-
224
- const scriptDir = getScriptPath(data.scriptName);
225
-
226
- if (!fs.existsSync(scriptDir)) {
227
- ack({
228
- error: `Script directory ${scriptDir} does not exist`,
229
- });
230
- return;
231
- }
232
-
233
- const scriptFiles: Record<string, {
234
- hash: string
235
- content: string
236
- }> = {};
237
-
238
- const otherFiles: string[] = [];
239
-
240
- const readDir = async (dir: string) => {
241
- const files = await fs.promises.readdir(dir, { withFileTypes: true });
242
- await Promise.all(
243
- files.map(async (file) => {
244
- // ignore .git and .vscode directories
245
- if (file.name.startsWith('.git') || file.name.startsWith('.vscode')) {
246
- return;
247
- }
248
-
249
- // only read js, jsx, ts, tsx, json, md, txt files
250
- if (file.isFile()) {
251
- const filePath = path.join(dir, file.name);
252
- const relativePath = getRelativePath(scriptDir, filePath);
253
-
254
- if (file.name.match(/\.(js(x)?|ts(x)?|json|md|txt)$/)) {
255
- const content = await fs.promises.readFile(filePath, 'utf-8').catch((err) => {
256
- console.log(chalk.red(`Error reading file: ${err}`));
257
- });
258
- if (typeof content === "string") {
259
- scriptFiles[relativePath] = {
260
- hash: md5(content),
261
- content,
262
- };
263
- }
264
- } else {
265
- otherFiles.push(relativePath);
266
- }
267
- } else if (file.isDirectory()) {
268
- await readDir(path.join(dir, file.name));
269
- }
270
- })
271
- );
272
- };
273
-
274
- await readDir(scriptDir);
275
-
276
- this.scriptName = data.scriptName;
277
-
278
- ack({
279
- scriptFiles,
280
- otherFiles: otherFiles.length > 0 ? otherFiles : undefined,
281
- });
282
-
283
- this.createWatcher(data.scriptName);
284
-
285
- if (!this.noAutoOpen) {
286
- // Open the entry file in VSCode after a delay
287
- // to ensure the response is sent. Because the open file command
288
- // may suspend the response and cause the client to not receive the ack.
289
- setTimeout(() => {
290
- const entryFilePath = path.join(scriptDir, "index.tsx")
291
- tryOpenFileInVSCode(entryFilePath);
292
- }, 1000);
293
- }
294
- } catch (e) {
295
- ack({
296
- error: `Failed to init and pull script files.\n${e}`,
297
- });
298
- }
299
- }
300
-
301
- handleLog = (data: {
302
- scriptName: string
303
- content: string
304
- isError: boolean
305
- }) => {
306
- if (data.scriptName !== this.scriptName) {
307
- return;
308
- }
309
- console.log(`[${chalk.bold.blue(this.scriptName)}][${data.isError ? chalk.red("ERROR") : "LOG"
310
- }][${new Date().toLocaleTimeString()}] ${data.content}`);
311
- }
312
-
313
- handleOpenFile = async (data: {
314
- scriptName: string
315
- relativePath: string
316
- }) => {
317
- if (data.scriptName !== this.scriptName) {
318
- return;
319
- }
320
-
321
- const filePath = path.join(getScriptPath(this.scriptName), data.relativePath)
322
-
323
- if (!this.noAutoOpen && fs.existsSync(filePath)) {
324
- tryOpenFileInVSCode(filePath)
325
- }
326
-
327
- }
328
-
329
- handleStopDebugScript = (data: string, ack: (result: boolean) => void) => {
330
- if (data === this.scriptName) {
331
- console.log(`[${chalk.bold.blue(this.scriptName)}] Stop debug script`);
332
- this.watcher?.close();
333
- this.watcher = null;
334
- this.scriptName = null;
335
- ack(true);
336
- } else {
337
- ack(false);
338
- }
339
- }
340
-
341
- handleGetFileContent = async (data: {
342
- scriptName: string,
343
- relativePath: string
344
- }, ack: (result: {
345
- error?: string,
346
- content?: string
347
- }) => void) => {
348
- if (this.scriptName !== data.scriptName) {
349
- ack({
350
- error: `Script ${data.scriptName} is not initialized`,
351
- });
352
- return;
353
- }
354
-
355
- const filePath = path.join(getScriptPath(data.scriptName), data.relativePath);
356
- try {
357
- const content = await fs.promises.readFile(filePath, 'utf-8');
358
- ack({
359
- content,
360
- });
361
- } catch (e) {
362
- ack({
363
- error: `Failed to get file content.\n${e}`,
364
- });
365
- }
366
- }
367
-
368
- handleGetFilePath = async (data: {
369
- scriptName: string,
370
- relativePath: string
371
- }, ack: (result: {
372
- error?: string,
373
- filePath?: string
374
- }) => void) => {
375
- if (this.scriptName !== data.scriptName) {
376
- ack({
377
- error: `Script ${data.scriptName} is not initialized`,
378
- });
379
- return;
380
- }
381
-
382
- const filePath = path.join(getScriptPath(data.scriptName), data.relativePath);
383
- if (fs.existsSync(filePath)) {
384
- ack({
385
- filePath,
386
- });
387
- } else {
388
- ack({
389
- error: `File ${filePath} does not exist`,
390
- });
391
- }
392
- }
393
- }
@@ -1,168 +0,0 @@
1
- import express from 'express';
2
- import { Controller } from './controller';
3
- import chalk from 'chalk';
4
-
5
- const getFileContent: express.RequestHandler = (req, res) => {
6
- const {
7
- socketId,
8
- scriptName,
9
- relativePath,
10
- } = req.query as {
11
- scriptName: string;
12
- socketId: string;
13
- relativePath: string;
14
- };
15
-
16
- if (!socketId) {
17
- console.log(chalk.red(`Socket not found: ${socketId}`));
18
- }
19
-
20
- if (!scriptName || !relativePath) {
21
- res.json({
22
- error: "Missing parameters: scriptName or relativePath."
23
- });
24
- return;
25
- }
26
-
27
- const ctrl = Controller.get(socketId);
28
- if (!ctrl) {
29
- console.log(chalk.red(`Socket not found: ${socketId}`));
30
- res.json({
31
- error: "Socket not found."
32
- });
33
- return;
34
- }
35
-
36
- ctrl.handleGetFileContent({
37
- scriptName,
38
- relativePath,
39
- }, (result: any) => {
40
- if (result.error) {
41
- res.json({
42
- error: result.error
43
- });
44
- return;
45
- }
46
- res.json({
47
- content: result.content
48
- });
49
- })
50
- }
51
-
52
- const getFileData: express.RequestHandler = (req, res) => {
53
- const {
54
- socketId,
55
- scriptName,
56
- relativePath,
57
- } = req.query as {
58
- scriptName: string;
59
- socketId: string;
60
- relativePath: string;
61
- };
62
-
63
- if (!socketId) {
64
- console.log(chalk.red(`Socket not found: ${socketId}`));
65
- }
66
-
67
- if (!scriptName || !relativePath) {
68
- res.json({
69
- error: "Missing parameters: scriptName or relativePath."
70
- });
71
- return;
72
- }
73
-
74
- const ctrl = Controller.get(socketId);
75
- if (!ctrl) {
76
- console.log(chalk.red(`Socket not found: ${socketId}`));
77
- res.json({
78
- error: "Socket not found."
79
- });
80
- return;
81
- }
82
-
83
- ctrl.handleGetFilePath({
84
- scriptName,
85
- relativePath,
86
- }, (result: any) => {
87
- if (result.error) {
88
- res.status(500).send(result.error);
89
- return;
90
- }
91
- res.sendFile(result.filePath);
92
- })
93
- }
94
-
95
- const syncScriptFromClient: express.RequestHandler = (req, res) => {
96
- const params = req.body as {
97
- socketId: string;
98
- scriptName: string;
99
- scriptFiles: Record<string, string>;
100
- 'global.d.ts': string;
101
- 'scripting.d.ts': string;
102
- };
103
-
104
- const socketId = params.socketId;
105
-
106
- const ctrl = Controller.get(socketId);
107
-
108
- if (!ctrl) {
109
- console.log(chalk.red(`Socket not found: ${socketId}.`));
110
- res.json({
111
- error: "Socket not found."
112
- });
113
- return;
114
- }
115
-
116
- ctrl.handleSyncScriptFromClient(params, (result) => {
117
- if (result.error) {
118
- res.json({
119
- error: result.error
120
- });
121
- return;
122
- }
123
- res.json({
124
- success: true
125
- });
126
- })
127
- };
128
-
129
- const syncScriptFromServer: express.RequestHandler = (req, res) => {
130
- const params = req.body as {
131
- socketId: string;
132
- 'global.d.ts': string,
133
- 'scripting.d.ts': string,
134
- scriptName: string,
135
- };
136
-
137
- const socketId = params.socketId;
138
-
139
- const ctrl = Controller.get(socketId);
140
-
141
- if (!ctrl) {
142
- res.json({
143
- error: "Socket not found."
144
- });
145
- return;
146
- }
147
-
148
- ctrl.handleSyncScriptFromServer(params, (result) => {
149
- if (result.error) {
150
- res.json({
151
- error: result.error
152
- });
153
- return;
154
- }
155
- res.json({
156
- scriptFiles: result.scriptFiles
157
- });
158
- })
159
- };
160
-
161
- export function initHttpRouter(app: express.Express) {
162
- app.use(express.json({ limit: '50mb' }));
163
- app.use(express.urlencoded({ extended: true }));
164
- app.get("/getFileContent", getFileContent);
165
- app.get("/getFileData", getFileData);
166
- app.post("/syncScriptFromClient", syncScriptFromClient);
167
- app.post("/syncScriptFromServer", syncScriptFromServer);
168
- }
package/src/index.ts DELETED
@@ -1,80 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import yargs from 'yargs/yargs';
4
- import { hideBin } from 'yargs/helpers';
5
- import { startServer } from './start_server';
6
-
7
- yargs(hideBin(process.argv))
8
- .parserConfiguration({
9
- "boolean-negation": false
10
- })
11
- .command('start', 'Start the scripting-cli server', (yargs) => {
12
- return yargs
13
- .options({
14
- port: {
15
- alias: ["p"],
16
- describe: "The port the server listens on",
17
- type: "number",
18
- default: 3000,
19
- }
20
- })
21
- .usage("$0 start [--port=<port>]")
22
- .example([
23
- ["$0 start -p=8000", "Start server and listen on 8000"]
24
- ])
25
- .options({
26
- "no-auto-open": {
27
- type: "boolean",
28
- describe: "Do not open the index.tsx/widget.tsx file automatically",
29
- },
30
- })
31
- .usage("$0 start [--no-auto-open]")
32
- .example([
33
- ["$0 start --no-auto-open", "Start server without opening the index.tsx/widget.tsx file"],
34
- ["$0 start --no-auto-open -p=8000", "Start server without opening the index.tsx/widget.tsx file and listen on 8000"],
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
- ;
50
- }, (argv) => {
51
- startServer({
52
- port: argv.port,
53
- noAutoOpen: argv['no-auto-open'],
54
- startBonjourService: argv.bonjour,
55
- });
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
- })
68
- .showHelpOnFail(true)
69
- .option('help', {
70
- alias: 'h',
71
- describe: 'Show help',
72
- })
73
- .demandCommand()
74
- .parse();
75
-
76
-
77
-
78
- // if (require.main === module) {
79
- // startServer();
80
- // }