scripting-cli 1.2.5 → 1.4.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.
@@ -0,0 +1,172 @@
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.EDITORS = void 0;
7
+ exports.getEditor = getEditor;
8
+ exports.isEditorAvailable = isEditorAvailable;
9
+ exports.detectAvailableEditors = detectAvailableEditors;
10
+ exports.openFileInEditor = openFileInEditor;
11
+ exports.writeEditorSettings = writeEditorSettings;
12
+ const child_process_1 = __importDefault(require("child_process"));
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const os_1 = __importDefault(require("os"));
15
+ const path_1 = __importDefault(require("path"));
16
+ const chalk_1 = __importDefault(require("chalk"));
17
+ const util_1 = require("./util");
18
+ exports.EDITORS = [
19
+ { key: 'vscode', displayName: 'Visual Studio Code', command: 'code', macAppName: 'Visual Studio Code.app', settingsTarget: 'vscode' },
20
+ { key: 'vscode-insiders', displayName: 'VSCode Insiders', command: 'code-insiders', macAppName: 'Visual Studio Code - Insiders.app', settingsTarget: 'vscode' },
21
+ { key: 'vscodium', displayName: 'VSCodium', command: 'codium', macAppName: 'VSCodium.app', settingsTarget: 'vscode' },
22
+ { key: 'cursor', displayName: 'Cursor', command: 'cursor', macAppName: 'Cursor.app', settingsTarget: 'vscode' },
23
+ { key: 'windsurf', displayName: 'Windsurf', command: 'windsurf', macAppName: 'Windsurf.app', settingsTarget: 'vscode' },
24
+ { key: 'trae', displayName: 'Trae', command: 'trae', macAppName: 'Trae.app', settingsTarget: 'vscode' },
25
+ { key: 'zed', displayName: 'Zed', command: 'zed', macAppName: 'Zed.app', settingsTarget: 'zed' },
26
+ { key: 'webstorm', displayName: 'WebStorm', command: 'webstorm', macAppName: 'WebStorm.app', settingsTarget: 'idea' },
27
+ { key: 'idea', displayName: 'IntelliJ IDEA', command: 'idea', macAppName: 'IntelliJ IDEA.app', settingsTarget: 'idea' },
28
+ { key: 'fleet', displayName: 'Fleet', command: 'fleet', macAppName: 'Fleet.app', settingsTarget: null },
29
+ { key: 'sublime', displayName: 'Sublime Text', command: 'subl', macAppName: 'Sublime Text.app', settingsTarget: null },
30
+ { key: 'nova', displayName: 'Nova', command: 'nova', macAppName: 'Nova.app', settingsTarget: null },
31
+ { key: 'vim', displayName: 'Vim (terminal)', command: 'vim', settingsTarget: null, terminalApp: true },
32
+ { key: 'nvim', displayName: 'Neovim (terminal)', command: 'nvim', settingsTarget: null, terminalApp: true },
33
+ { key: 'emacs', displayName: 'Emacs', command: 'emacs', settingsTarget: null, terminalApp: true },
34
+ { key: 'custom', displayName: 'Custom command', command: null, settingsTarget: null },
35
+ { key: 'none', displayName: 'Do not open files', command: null, settingsTarget: null },
36
+ ];
37
+ function getEditor(key) {
38
+ return exports.EDITORS.find(e => e.key === key);
39
+ }
40
+ const detectionCache = new Map();
41
+ function commandExists(command) {
42
+ if (detectionCache.has(command)) {
43
+ return detectionCache.get(command);
44
+ }
45
+ const isWin = os_1.default.platform() === 'win32';
46
+ const probe = isWin ? `where ${command}` : `command -v ${command}`;
47
+ try {
48
+ child_process_1.default.execSync(probe, { stdio: 'ignore', shell: isWin ? undefined : process.env.SHELL });
49
+ detectionCache.set(command, true);
50
+ return true;
51
+ }
52
+ catch {
53
+ detectionCache.set(command, false);
54
+ return false;
55
+ }
56
+ }
57
+ function macAppExists(appName) {
58
+ const candidates = [
59
+ path_1.default.join('/Applications', appName),
60
+ path_1.default.join(os_1.default.homedir(), 'Applications', appName),
61
+ ];
62
+ return candidates.some(p => fs_1.default.existsSync(p));
63
+ }
64
+ /**
65
+ * Whether this editor should be marked as "detected" in the picker.
66
+ *
67
+ * Intentionally returns false for:
68
+ * - "custom" / "none": meta options, not real editors
69
+ * - terminal editors (vim/nvim/emacs): typically system-bundled on macOS/Linux,
70
+ * so detection is meaningless — listing them as detected would mislead users
71
+ * into thinking they're their primary editor.
72
+ *
73
+ * GUI editors are detected via PATH command first, then macOS app bundle as fallback.
74
+ */
75
+ function isEditorAvailable(editor) {
76
+ if (editor.key === 'custom' || editor.key === 'none')
77
+ return false;
78
+ if (editor.terminalApp)
79
+ return false;
80
+ if (editor.command && commandExists(editor.command))
81
+ return true;
82
+ if (os_1.default.platform() === 'darwin' && editor.macAppName && macAppExists(editor.macAppName))
83
+ return true;
84
+ return false;
85
+ }
86
+ function detectAvailableEditors() {
87
+ const set = new Set();
88
+ for (const e of exports.EDITORS) {
89
+ if (isEditorAvailable(e))
90
+ set.add(e.key);
91
+ }
92
+ return set;
93
+ }
94
+ function openFileInEditor(filePath, config) {
95
+ const editor = getEditor(config.editor);
96
+ if (!editor || editor.key === 'none')
97
+ return;
98
+ const command = config.editorCommand ?? editor.command;
99
+ const args = config.editorArgs ?? [];
100
+ if (!command) {
101
+ if (editor.key === 'custom') {
102
+ console.log(chalk_1.default.yellow(`[editor] "custom" requires editorCommand to be set in scripting.config.*`));
103
+ }
104
+ return;
105
+ }
106
+ if (editor.terminalApp) {
107
+ // Don't hijack the server TTY with a terminal editor
108
+ console.log(chalk_1.default.gray(`[editor] Skipping auto-open for terminal editor "${editor.displayName}". File: ${filePath}`));
109
+ return;
110
+ }
111
+ try {
112
+ const platform = os_1.default.platform();
113
+ if (platform === 'win32') {
114
+ child_process_1.default.spawn('cmd.exe', ['/c', command, ...args, filePath], { stdio: 'ignore', detached: true }).unref();
115
+ return;
116
+ }
117
+ // Try the CLI command first
118
+ if (commandExists(command)) {
119
+ child_process_1.default.spawn(command, [...args, filePath], { stdio: 'ignore', detached: true }).unref();
120
+ return;
121
+ }
122
+ // macOS fallback: open -a "App Name"
123
+ if (platform === 'darwin' && editor.macAppName) {
124
+ child_process_1.default.spawn('open', ['-a', editor.macAppName, filePath], { stdio: 'ignore', detached: true }).unref();
125
+ return;
126
+ }
127
+ console.log(chalk_1.default.yellow(`[editor] Command "${command}" not found in PATH. Cannot open ${filePath}.`));
128
+ }
129
+ catch (err) {
130
+ console.log(chalk_1.default.red(`[editor] Failed to open file: ${err}`));
131
+ }
132
+ }
133
+ const VSCODE_SETTINGS = `{
134
+ "typescript.format.semicolons": "remove",
135
+ "typescript.preferences.jsxAttributeCompletionStyle": "braces"
136
+ }`;
137
+ const ZED_SETTINGS = `{
138
+ "languages": {
139
+ "TypeScript": {
140
+ "format_on_save": "on"
141
+ },
142
+ "TSX": {
143
+ "format_on_save": "on"
144
+ }
145
+ }
146
+ }`;
147
+ function writeEditorSettings(config) {
148
+ const editor = getEditor(config.editor);
149
+ if (!editor || !editor.settingsTarget)
150
+ return;
151
+ if (editor.settingsTarget === 'vscode') {
152
+ writeIfAbsent('.vscode/settings.json', VSCODE_SETTINGS);
153
+ }
154
+ else if (editor.settingsTarget === 'zed') {
155
+ writeIfAbsent('.zed/settings.json', ZED_SETTINGS);
156
+ }
157
+ else if (editor.settingsTarget === 'idea') {
158
+ // JetBrains projects need full .idea/ structure (IDE generates it on first open).
159
+ // We intentionally don't seed it here.
160
+ }
161
+ }
162
+ function writeIfAbsent(relative, content) {
163
+ const filePath = (0, util_1.getPath)(relative);
164
+ (0, util_1.ensureDirectoryExistence)(filePath);
165
+ if (!fs_1.default.existsSync(filePath)) {
166
+ fs_1.default.writeFileSync(filePath, content);
167
+ console.log(chalk_1.default.green(`${relative} created.`));
168
+ }
169
+ else {
170
+ console.log(chalk_1.default.gray(`${relative} already exists.`));
171
+ }
172
+ }
@@ -0,0 +1,2 @@
1
+ import express from 'express';
2
+ export declare function initHttpRouter(app: express.Express): void;
@@ -71,6 +71,44 @@ const getFileData = (req, res) => {
71
71
  res.sendFile(result.filePath);
72
72
  });
73
73
  };
74
+ const putFileData = (req, res) => {
75
+ const { socketId, scriptName, relativePath, } = req.query;
76
+ if (!scriptName || !relativePath) {
77
+ res.json({
78
+ error: "Missing parameters: scriptName or relativePath."
79
+ });
80
+ return;
81
+ }
82
+ if (!Buffer.isBuffer(req.body)) {
83
+ res.json({
84
+ error: "Missing file data in request body."
85
+ });
86
+ return;
87
+ }
88
+ const ctrl = controller_1.Controller.get(socketId);
89
+ if (!ctrl) {
90
+ console.log(chalk_1.default.red(`Socket not found: ${socketId}`));
91
+ res.json({
92
+ error: "Socket not found."
93
+ });
94
+ return;
95
+ }
96
+ ctrl.handlePutFileData({
97
+ scriptName,
98
+ relativePath,
99
+ data: req.body,
100
+ }, (result) => {
101
+ if (result.error) {
102
+ res.json({
103
+ error: result.error
104
+ });
105
+ return;
106
+ }
107
+ res.json({
108
+ success: true
109
+ });
110
+ });
111
+ };
74
112
  const syncScriptFromClient = (req, res) => {
75
113
  const params = req.body;
76
114
  const socketId = params.socketId;
@@ -121,6 +159,7 @@ function initHttpRouter(app) {
121
159
  app.use(express_1.default.urlencoded({ extended: true }));
122
160
  app.get("/getFileContent", getFileContent);
123
161
  app.get("/getFileData", getFileData);
162
+ app.post("/putFileData", express_1.default.raw({ type: 'application/octet-stream', limit: '100mb' }), putFileData);
124
163
  app.post("/syncScriptFromClient", syncScriptFromClient);
125
164
  app.post("/syncScriptFromServer", syncScriptFromServer);
126
165
  }
@@ -0,0 +1,3 @@
1
+ import type { ScriptingConfig } from './types';
2
+ export type { ScriptingConfig, EditorKey, LogLevel, EditorDescriptor, ResolvedConfig, } from './types';
3
+ export declare function defineConfig(config: ScriptingConfig): ScriptingConfig;
package/dist/index.js CHANGED
@@ -1,112 +1,6 @@
1
- #!/usr/bin/env node
2
1
  "use strict";
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || (function () {
20
- var ownKeys = function(o) {
21
- ownKeys = Object.getOwnPropertyNames || function (o) {
22
- var ar = [];
23
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
- return ar;
25
- };
26
- return ownKeys(o);
27
- };
28
- return function (mod) {
29
- if (mod && mod.__esModule) return mod;
30
- var result = {};
31
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
- __setModuleDefault(result, mod);
33
- return result;
34
- };
35
- })();
36
- var __importDefault = (this && this.__importDefault) || function (mod) {
37
- return (mod && mod.__esModule) ? mod : { "default": mod };
38
- };
39
2
  Object.defineProperty(exports, "__esModule", { value: true });
40
- const yargs_1 = __importDefault(require("yargs/yargs"));
41
- const helpers_1 = require("yargs/helpers");
42
- const start_server_1 = require("./start_server");
43
- (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
44
- .parserConfiguration({
45
- "boolean-negation": false
46
- })
47
- .command('start', 'Start the scripting-cli server', (yargs) => {
48
- return yargs
49
- .options({
50
- port: {
51
- alias: ["p"],
52
- describe: "The port the server listens on",
53
- type: "number",
54
- default: 3000,
55
- }
56
- })
57
- .usage("$0 start [--port=<port>]")
58
- .example([
59
- ["$0 start -p=8000", "Start server and listen on 8000"]
60
- ])
61
- .options({
62
- "no-auto-open": {
63
- type: "boolean",
64
- describe: "Do not open the index.tsx/widget.tsx file automatically",
65
- },
66
- })
67
- .usage("$0 start [--no-auto-open]")
68
- .example([
69
- ["$0 start --no-auto-open", "Start server without opening the index.tsx/widget.tsx file"],
70
- ["$0 start --no-auto-open -p=8000", "Start server without opening the index.tsx/widget.tsx file and listen on 8000"],
71
- ])
72
- .options({
73
- "bonjour": {
74
- type: "boolean",
75
- describe: "Enable bonjour service",
76
- },
77
- })
78
- .usage("$0 start [--bonjour]")
79
- .example([
80
- ["$0 start --bonjour", "Start server with bonjour service"],
81
- ["$0 start --bonjour -p=8000", "Start server with bonjour service and listen on 8000"],
82
- ["$0 start --bonjour --no-auto-open", "Start server with bonjour service without opening the index.tsx/widget.tsx file"],
83
- ["$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"],
84
- ]);
85
- }, (argv) => {
86
- (0, start_server_1.startServer)({
87
- port: argv.port,
88
- noAutoOpen: argv['no-auto-open'],
89
- startBonjourService: argv.bonjour,
90
- });
91
- })
92
- .command('migrate', 'Migrate the scripts in the workspace root directory to the scripts directory.', (yargs) => {
93
- return yargs
94
- .usage("$0 migrate")
95
- .example([
96
- ["$0 migrate", "Migrate the scripts in the workspace root directory to the scripts directory."]
97
- ]);
98
- }, async () => {
99
- const { migrateOldFiles } = await Promise.resolve().then(() => __importStar(require('./util')));
100
- await migrateOldFiles();
101
- process.exit(0);
102
- })
103
- .showHelpOnFail(true)
104
- .option('help', {
105
- alias: 'h',
106
- describe: 'Show help',
107
- })
108
- .demandCommand()
109
- .parse();
110
- // if (require.main === module) {
111
- // startServer();
112
- // }
3
+ exports.defineConfig = defineConfig;
4
+ function defineConfig(config) {
5
+ return config;
6
+ }
@@ -0,0 +1,9 @@
1
+ import { EditorKey, ScriptingConfig } from './types';
2
+ export declare function isInteractive(): boolean;
3
+ interface EditorAnswers {
4
+ editor: EditorKey;
5
+ editorCommand?: string;
6
+ }
7
+ export declare function promptForEditor(): Promise<EditorAnswers | null>;
8
+ export type PromptedConfig = Partial<ScriptingConfig>;
9
+ export {};
package/dist/prompt.js ADDED
@@ -0,0 +1,52 @@
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.isInteractive = isInteractive;
7
+ exports.promptForEditor = promptForEditor;
8
+ const prompts_1 = __importDefault(require("prompts"));
9
+ const chalk_1 = __importDefault(require("chalk"));
10
+ const editors_1 = require("./editors");
11
+ function isInteractive() {
12
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
13
+ }
14
+ async function promptForEditor() {
15
+ if (!isInteractive()) {
16
+ console.log(chalk_1.default.yellow('[config] Non-interactive environment detected. Defaulting editor to "none". Edit scripting.config.json to change.'));
17
+ return { editor: 'none' };
18
+ }
19
+ const available = (0, editors_1.detectAvailableEditors)();
20
+ const choices = [...editors_1.EDITORS]
21
+ .sort((a, b) => {
22
+ const ax = available.has(a.key) ? 0 : 1;
23
+ const bx = available.has(b.key) ? 0 : 1;
24
+ return ax - bx;
25
+ })
26
+ .map(e => ({
27
+ title: `${available.has(e.key) ? chalk_1.default.green('✓') : ' '} ${e.displayName}`,
28
+ description: e.command ? `command: ${e.command}` : undefined,
29
+ value: e.key,
30
+ }));
31
+ const { editor } = await (0, prompts_1.default)({
32
+ type: 'select',
33
+ name: 'editor',
34
+ message: 'Which editor do you use?',
35
+ choices,
36
+ initial: 0,
37
+ }, { onCancel: () => process.exit(0) });
38
+ if (!editor)
39
+ return null;
40
+ if (editor === 'custom') {
41
+ const { editorCommand } = await (0, prompts_1.default)({
42
+ type: 'text',
43
+ name: 'editorCommand',
44
+ message: 'Enter the command to open files (e.g. "myeditor"):',
45
+ validate: v => v && v.trim().length > 0 ? true : 'command is required',
46
+ }, { onCancel: () => process.exit(0) });
47
+ if (!editorCommand)
48
+ return null;
49
+ return { editor, editorCommand: editorCommand.trim() };
50
+ }
51
+ return { editor };
52
+ }
@@ -0,0 +1,7 @@
1
+ export declare function startServer({ port, noAutoOpen, startBonjourService, editorOverride, reconfigure }: {
2
+ port: number | undefined;
3
+ noAutoOpen: boolean | undefined;
4
+ startBonjourService: boolean | undefined;
5
+ editorOverride?: string | undefined;
6
+ reconfigure?: boolean | undefined;
7
+ }): Promise<void>;
@@ -15,6 +15,8 @@ const qrcode_terminal_1 = __importDefault(require("qrcode-terminal"));
15
15
  const util_1 = require("./util");
16
16
  const controller_1 = require("./controller");
17
17
  const http_router_1 = require("./http_router");
18
+ const config_1 = require("./config");
19
+ const editors_1 = require("./editors");
18
20
  const app = (0, express_1.default)();
19
21
  const server = http_1.default.createServer(app);
20
22
  const io = new socket_io_1.Server(server);
@@ -91,19 +93,27 @@ function getLocalNetworkIP() {
91
93
  results.sort((a, b) => a.priority - b.priority);
92
94
  return results.length > 0 ? results[0].address : null;
93
95
  }
94
- function startServer({ port, noAutoOpen, startBonjourService }) {
95
- // console.log("port", port, "noAutoOpen", noAutoOpen);
96
- const PORT = port ?? 3000;
96
+ async function startServer({ port, noAutoOpen, startBonjourService, editorOverride, reconfigure }) {
97
+ const config = await (0, config_1.resolveConfig)({
98
+ port,
99
+ noAutoOpen,
100
+ editorOverride,
101
+ reconfigure,
102
+ });
103
+ const PORT = config.port;
104
+ const editor = (0, editors_1.getEditor)(config.editor);
105
+ console.log(chalk_1.default.gray(`Editor: ${editor?.displayName ?? config.editor}`));
97
106
  (0, http_router_1.initHttpRouter)(app);
98
107
  io.on('connection', (socket) => {
99
- controller_1.Controller.create(socket, noAutoOpen);
108
+ controller_1.Controller.create(socket, config);
100
109
  console.log(chalk_1.default.blue(`Client [${socket.id}] connected`));
101
110
  });
102
111
  server.listen(PORT, async () => {
103
- (0, util_1.createTsConfig)(); // Create tsconfig.json when the server starts
104
- (0, util_1.createVSCodeSettings)(); // Create vscode settings.json when the server starts
105
- (0, util_1.ensureScriptsDirectory)(); // Ensure the scripts directory exists
106
- // await migrateOldFiles(); // Migrate old files to the scripts directory
112
+ if (config.generateTsConfig) {
113
+ (0, util_1.createTsConfig)();
114
+ }
115
+ (0, editors_1.writeEditorSettings)(config);
116
+ (0, util_1.ensureScriptsDirectory)();
107
117
  const ipAddress = getLocalNetworkIP() ?? ip_1.default.address();
108
118
  const address = `http://${ipAddress}:${PORT}`;
109
119
  if (startBonjourService) {
@@ -0,0 +1,25 @@
1
+ export type EditorKey = 'vscode' | 'vscode-insiders' | 'vscodium' | 'cursor' | 'windsurf' | 'trae' | 'zed' | 'webstorm' | 'idea' | 'fleet' | 'sublime' | 'nova' | 'vim' | 'nvim' | 'emacs' | 'custom' | 'none';
2
+ export type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug';
3
+ export interface ScriptingConfig {
4
+ editor?: EditorKey;
5
+ editorCommand?: string;
6
+ editorArgs?: string[];
7
+ port?: number;
8
+ autoOpen?: boolean;
9
+ generateTsConfig?: boolean;
10
+ logLevel?: LogLevel;
11
+ /** Extra script-relative paths, directory/file names, or `*.ext` globs to exclude from syncing. */
12
+ ignore?: string[];
13
+ }
14
+ export type ResolvedConfig = Required<Omit<ScriptingConfig, 'editorCommand' | 'editorArgs'>> & {
15
+ editorCommand?: string;
16
+ editorArgs: string[];
17
+ };
18
+ export interface EditorDescriptor {
19
+ key: EditorKey;
20
+ displayName: string;
21
+ command: string | null;
22
+ macAppName?: string;
23
+ settingsTarget?: 'vscode' | 'zed' | 'idea' | null;
24
+ terminalApp?: boolean;
25
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/util.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export declare function md5(content: string): string;
2
+ export declare function isBinaryFile(filePath: string): boolean;
3
+ export declare function getPath(filename: string): string;
4
+ export declare function getScriptPath(filename?: string): string;
5
+ export declare function createTsConfig(): void;
6
+ export declare function ensureScriptsDirectory(): void;
7
+ export declare function ensureDirectoryExistence(filePath: string): void;
8
+ export declare function writeDtsFiles(files: Record<string, string>): Promise<void>;
9
+ export declare function getRelativePath(from: string, to: string): string;
10
+ export declare function isIgnoredPath(relativePath: string, patterns?: string[]): boolean;
11
+ export declare function migrateOldFiles(): Promise<void>;