@jacebenson/jsn 5.0.0 → 5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.0.0",
3
+ "version": "5.1.0",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import { getCurrentUser, getCurrentApplication } from '../context.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
+ import { runRepl } from '../eval-repl.js';
4
5
 
5
6
  // The whole command is a mutation surface (runs arbitrary server-side JS) —
6
7
  // declared as `['']` so the root `jsn eval` command are gated.
@@ -9,12 +10,13 @@ declareCapabilities('eval', { mutationSubcommands: [''] });
9
10
  export function evalCmd(wrap) {
10
11
  return {
11
12
  command: 'eval',
12
- describe: 'Execute background scripts on the instance',
13
+ describe: 'Execute background scripts on the instance (--repl for interactive mode)',
13
14
  builder: (yargs) => {
14
15
  return yargs
15
16
  .option('script', { alias: 's', type: 'string', describe: 'JavaScript code to execute (single-quote the script, double quotes inside: --script \'gs.log("Hello")\')' })
16
17
  .option('file', { alias: 'f', type: 'string', describe: 'Read script from file (avoids shell quoting issues)' })
17
18
  .option('stdin', { type: 'boolean', describe: 'Read script from stdin (pipe-friendly, e.g. cat script.js | jsn eval --stdin)' })
19
+ .option('repl', { type: 'boolean', default: false, describe: 'Interactive mode: type a script, submit with .exec (requires a terminal)' })
18
20
  .option('scope', { alias: null, type: 'string', describe: 'Scope name or sys_id to run the script under (default: active scope from banner)' })
19
21
  // Script-mode flags (issue #177) — map to the Script Background form checkboxes
20
22
  .option('rollback', { type: 'boolean', default: true, describe: 'Record rollback context (--no-rollback to skip)' })
@@ -51,6 +53,33 @@ export function evalCmd(wrap) {
51
53
  }
52
54
  }
53
55
 
56
+ if (argv.repl) {
57
+ const conflicts = [];
58
+ if (argv.script) conflicts.push('--script');
59
+ if (argv.file) conflicts.push('--file');
60
+ if (argv.stdin) conflicts.push('--stdin');
61
+ if (conflicts.length) {
62
+ throw new Error(`--repl cannot be combined with ${conflicts.join(', ')}`);
63
+ }
64
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
65
+ throw new Error('--repl needs an interactive terminal. Use --script, --file or --stdin for scripts and agents.');
66
+ }
67
+ await runRepl({
68
+ instance: app.getEffectiveInstance(),
69
+ scope: scope || 'global',
70
+ runScript: (text) => {
71
+ const withScope = scopeSysId ? `var $scopeSysId = '${scopeSysId}';\n${text}` : text;
72
+ return app.sdk.executeScript(withScope, scopeSysId || '', {
73
+ rollback: argv.rollback,
74
+ quotaManagedTransaction: argv.quotaManagedTransaction,
75
+ sandbox: argv.sandbox,
76
+ scriptlet: argv.scriptlet,
77
+ });
78
+ },
79
+ });
80
+ return;
81
+ }
82
+
54
83
  if (argv.file) {
55
84
  script = fs.readFileSync(argv.file, 'utf-8');
56
85
  } else if (argv.stdin) {
@@ -0,0 +1,156 @@
1
+ // Interactive background-script mode for `jsn eval --repl` (issue #397).
2
+ //
3
+ // The line-handling state machine lives here, apart from the readline/TTY
4
+ // plumbing, so it can be unit-tested without a terminal. Each `.exec`
5
+ // submission is a separate server request: variables do not carry over, and
6
+ // rollback context is recorded but never applied automatically.
7
+
8
+ import readline from 'node:readline';
9
+
10
+ export const REPL_COMMANDS = ['.exec', '.clear', '.help', '.exit'];
11
+
12
+ export const REPL_HELP = [
13
+ 'Interactive background-script mode.',
14
+ '',
15
+ ' .exec Run everything typed since the last submission',
16
+ ' .clear Throw away the current buffer without running it',
17
+ ' .help Show this help',
18
+ ' .exit Leave the REPL (Ctrl+D does the same)',
19
+ '',
20
+ 'A blank line keeps the buffer open; it never submits. Only .exec runs.',
21
+ 'Line starting with a dot is a REPL command, so a script line cannot begin',
22
+ 'with one.',
23
+ '',
24
+ 'Each .exec is its own server request. JavaScript variables do not persist',
25
+ 'between submissions, while database writes do. Rollback context is recorded',
26
+ 'on the instance; it is not an automatic undo.',
27
+ ].join('\n');
28
+
29
+ export function createReplState() {
30
+ return { script: '' };
31
+ }
32
+
33
+ // Returns one of:
34
+ // { action: 'continue' } line appended, keep reading
35
+ // { action: 'exec', script } run this script, buffer cleared
36
+ // { action: 'empty' } .exec with nothing to run
37
+ // { action: 'clear' } buffer discarded
38
+ // { action: 'help' } print REPL_HELP
39
+ // { action: 'exit' } leave the REPL
40
+ export function handleReplLine(state, line) {
41
+ const command = line.trim();
42
+
43
+ if (command === '.exec') {
44
+ if (!state.script.trim()) return { action: 'empty' };
45
+ const script = state.script;
46
+ state.script = '';
47
+ return { action: 'exec', script };
48
+ }
49
+ if (command === '.clear') {
50
+ state.script = '';
51
+ return { action: 'clear' };
52
+ }
53
+ if (command === '.help') return { action: 'help' };
54
+ if (command === '.exit') return { action: 'exit' };
55
+
56
+ // Every other line accumulates, blank lines included. A blank line must not
57
+ // submit a half-written script.
58
+ state.script = state.script === '' ? line : `${state.script}\n${line}`;
59
+ return { action: 'continue' };
60
+ }
61
+
62
+ export const REPL_BANNER_NOTE = 'One request per .exec. Variables do not persist; DB writes do.';
63
+
64
+ // TTY plumbing. `runScript` is supplied by the eval command so the REPL reuses
65
+ // the same execution path, scope resolution and mutation guards as --script.
66
+ export function runRepl({ runScript, instance, scope }) {
67
+ return new Promise((resolve) => {
68
+ const out = process.stdout;
69
+ const state = createReplState();
70
+
71
+ out.write(`jsn eval --repl · instance: ${instance} · scope: ${scope}\n`);
72
+ out.write(`${REPL_BANNER_NOTE}\n`);
73
+ out.write('.help for commands, .exec to run, Ctrl+D to exit.\n\n');
74
+
75
+ const rl = readline.createInterface({
76
+ input: process.stdin,
77
+ output: out,
78
+ terminal: true,
79
+ prompt: 'jsn> ',
80
+ });
81
+
82
+ // EOF (Ctrl+D) can close readline while a script is still in flight, so
83
+ // every prompt/resume has to check this. Calling resume() or prompt() on a
84
+ // closed interface throws ERR_USE_AFTER_CLOSE.
85
+ let closed = false;
86
+
87
+ const prompt = () => {
88
+ if (closed) return;
89
+ rl.setPrompt(state.script ? '...> ' : 'jsn> ');
90
+ rl.prompt();
91
+ };
92
+
93
+ rl.on('SIGINT', () => {
94
+ if (state.script) {
95
+ state.script = '';
96
+ out.write('\n(buffer cleared)\n');
97
+ prompt();
98
+ return;
99
+ }
100
+ out.write('\n');
101
+ rl.close();
102
+ });
103
+
104
+ rl.on('line', async (line) => {
105
+ if (closed) return;
106
+ const result = handleReplLine(state, line);
107
+
108
+ if (result.action === 'exit') {
109
+ rl.close();
110
+ return;
111
+ }
112
+ if (result.action === 'clear') {
113
+ out.write('(buffer cleared)\n');
114
+ prompt();
115
+ return;
116
+ }
117
+ if (result.action === 'help') {
118
+ out.write(`\n${REPL_HELP}\n\n`);
119
+ prompt();
120
+ return;
121
+ }
122
+ if (result.action === 'empty') {
123
+ out.write('(nothing to run)\n');
124
+ prompt();
125
+ return;
126
+ }
127
+ if (result.action === 'continue') {
128
+ prompt();
129
+ return;
130
+ }
131
+
132
+ // action === 'exec'
133
+ out.write('\n');
134
+ rl.pause();
135
+ try {
136
+ const output = await runScript(result.script);
137
+ out.write(`${output ?? ''}\n`);
138
+ } catch (err) {
139
+ out.write(`Error: ${err.message}\n`);
140
+ } finally {
141
+ if (!closed) {
142
+ rl.resume();
143
+ out.write('\n');
144
+ prompt();
145
+ }
146
+ }
147
+ });
148
+
149
+ rl.on('close', () => {
150
+ closed = true;
151
+ out.write('\n');
152
+ resolve();
153
+ });
154
+ });
155
+ }
156
+