@parnniti/snow 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +134 -2
- package/bin/snow.js +4 -0
- package/package.json +40 -4
- package/skills/snow/SKILL.md +84 -0
- package/skills/snow/references/encoded-queries.md +27 -0
- package/src/args.js +49 -0
- package/src/auth.js +171 -0
- package/src/cli.js +368 -0
- package/src/config.js +58 -0
- package/src/http.js +61 -0
- package/src/output.js +46 -0
- package/src/records.js +157 -0
- package/src/skills.js +169 -0
- package/src/table.js +63 -0
- package/src/tokenstore.js +60 -0
- package/src/user.js +19 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { GLOBAL_OPTIONS, orderClause, joinQuery, outputMode, parseSets, readData, splitFields } from './args.js';
|
|
5
|
+
import { BIN, loadConfig, normalizeInstance, resolveContext, saveConfig } from './config.js';
|
|
6
|
+
import { CLIENT_ID, LoginRequired, finishLogin, getSession, openBrowser, promptCode, startLogin } from './auth.js';
|
|
7
|
+
import { deleteTokens, loadTokens, storeName } from './tokenstore.js';
|
|
8
|
+
import { request } from './http.js';
|
|
9
|
+
import { create, get, list, update } from './table.js';
|
|
10
|
+
import { printJSON, printRecord, printTable, printTotalNote } from './output.js';
|
|
11
|
+
import { currentUser } from './user.js';
|
|
12
|
+
import { recordCommands } from './records.js';
|
|
13
|
+
import { AGENTS, bundledSkills, destinations, installSkills, skillStatus, uninstallSkills } from './skills.js';
|
|
14
|
+
|
|
15
|
+
const log = (msg) => process.stderr.write(`${msg}\n`);
|
|
16
|
+
|
|
17
|
+
const HELP = `${BIN} — ServiceNow CLI with browser/SSO login (OAuth 2.0 authorization code + PKCE)
|
|
18
|
+
|
|
19
|
+
Usage: ${BIN} [-c CONTEXT] [-o table|json] <command> [args]
|
|
20
|
+
|
|
21
|
+
Setup
|
|
22
|
+
context add NAME INSTANCE e.g. ${BIN} context add prod acme
|
|
23
|
+
login [--print-url] [--code CODE] [--no-browser] sign in through the browser (SSO/MFA as configured)
|
|
24
|
+
|
|
25
|
+
Auth
|
|
26
|
+
logout revoke + forget the stored token
|
|
27
|
+
whoami signed-in user, instance, token expiry
|
|
28
|
+
token [--header] print a live access token (for curl)
|
|
29
|
+
|
|
30
|
+
Contexts
|
|
31
|
+
context [list] | current | use NAME | add NAME INSTANCE | remove NAME
|
|
32
|
+
|
|
33
|
+
Records
|
|
34
|
+
incident|inc list | get | create | update | comment
|
|
35
|
+
change|chg list | get | create | update | comment
|
|
36
|
+
ritm list | get | update | comment
|
|
37
|
+
sctask|task list | get | update | comment
|
|
38
|
+
|
|
39
|
+
Generic
|
|
40
|
+
table list|get|create|update TABLE ... any table via the Table API
|
|
41
|
+
api METHOD PATH [-q k=v]... [-d JSON|@file|-] raw REST call, JSON out
|
|
42
|
+
|
|
43
|
+
Agents
|
|
44
|
+
skills [list] | get NAME | install [NAME...] | uninstall [NAME...]
|
|
45
|
+
install the bundled agent skill (~/.agents/skills)
|
|
46
|
+
|
|
47
|
+
Context precedence: -c flag > SNOW_CONTEXT > current context.
|
|
48
|
+
Run "${BIN} <command> -h" for command flags.`;
|
|
49
|
+
|
|
50
|
+
const ctxOf = (opts) => resolveContext(loadConfig(), opts.context);
|
|
51
|
+
|
|
52
|
+
const fmtExpiry = (ms) => {
|
|
53
|
+
const s = Math.round((ms - Date.now()) / 1000);
|
|
54
|
+
return s <= 0 ? 'expired (refreshes on next call)' : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const commands = {
|
|
58
|
+
login: {
|
|
59
|
+
usage: `Usage: ${BIN} login [-c CONTEXT] [--no-browser]
|
|
60
|
+
${BIN} login [-c CONTEXT] --print-url step 1: print authorize URL only
|
|
61
|
+
${BIN} login [-c CONTEXT] --code CODE step 2: finish with the code from the browser
|
|
62
|
+
|
|
63
|
+
Opens the instance's OAuth consent page. Sign in the way the instance requires (SSO, MFA, ...).
|
|
64
|
+
The page /sdk-oauth.do then shows a one-time code; paste it back (the "CODE&state=..." form is fine).
|
|
65
|
+
OAuth client: ${CLIENT_ID} (override with SNOW_OAUTH_CLIENT_ID).`,
|
|
66
|
+
options: { code: { type: 'string' }, 'print-url': { type: 'boolean' }, 'no-browser': { type: 'boolean' } },
|
|
67
|
+
async run(_, opts) {
|
|
68
|
+
const ctx = ctxOf(opts);
|
|
69
|
+
let code = opts.code;
|
|
70
|
+
if (!code) {
|
|
71
|
+
const url = startLogin(ctx);
|
|
72
|
+
if (opts['print-url']) {
|
|
73
|
+
process.stdout.write(url + '\n');
|
|
74
|
+
log(`Open the URL, sign in, then run: ${BIN} login -c ${ctx.name} --code <CODE>`);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
log(`Signing in to ${ctx.name} (${ctx.instance})`);
|
|
78
|
+
if (opts['no-browser'] || !openBrowser(url)) log(`Open this URL in your browser:\n${url}`);
|
|
79
|
+
else log(`Browser opened. If nothing appeared, open:\n${url}`);
|
|
80
|
+
code = await promptCode();
|
|
81
|
+
if (!code) throw new Error('no code entered');
|
|
82
|
+
}
|
|
83
|
+
await finishLogin(ctx, code);
|
|
84
|
+
const user = await currentUser(ctx, { refresh: true });
|
|
85
|
+
log(`Logged in to ${ctx.name} (${ctx.instance}) as ${user.name} <${user.user_name}>`);
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
logout: {
|
|
90
|
+
usage: `Usage: ${BIN} logout [-c CONTEXT]`,
|
|
91
|
+
options: {},
|
|
92
|
+
async run(_, opts) {
|
|
93
|
+
const ctx = ctxOf(opts);
|
|
94
|
+
const rec = loadTokens(ctx.name);
|
|
95
|
+
if (rec?.refresh_token || rec?.access_token) {
|
|
96
|
+
// Best effort server-side revoke; local removal happens regardless.
|
|
97
|
+
await fetch(`${ctx.instance}/oauth_revoke_token.do`, {
|
|
98
|
+
method: 'POST',
|
|
99
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
100
|
+
body: new URLSearchParams({ client_id: CLIENT_ID, token: rec.refresh_token || rec.access_token }),
|
|
101
|
+
}).catch(() => {});
|
|
102
|
+
}
|
|
103
|
+
deleteTokens(ctx.name);
|
|
104
|
+
log(`Logged out of ${ctx.name}`);
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
whoami: {
|
|
109
|
+
usage: `Usage: ${BIN} whoami [-c CONTEXT] [-o json]`,
|
|
110
|
+
options: {},
|
|
111
|
+
async run(_, opts) {
|
|
112
|
+
const ctx = ctxOf(opts);
|
|
113
|
+
const user = await currentUser(ctx, { refresh: true });
|
|
114
|
+
const session = await getSession(ctx);
|
|
115
|
+
const info = {
|
|
116
|
+
context: ctx.name,
|
|
117
|
+
instance: ctx.instance,
|
|
118
|
+
user_name: user.user_name,
|
|
119
|
+
name: user.name,
|
|
120
|
+
email: user.email,
|
|
121
|
+
sys_id: user.sys_id,
|
|
122
|
+
access_token_expires: fmtExpiry(session.expires_at),
|
|
123
|
+
logged_in_at: new Date(session.logged_in_at).toISOString(),
|
|
124
|
+
token_store: storeName(),
|
|
125
|
+
};
|
|
126
|
+
return outputMode(opts, 'table') === 'json' ? printJSON(info) : printRecord(info, { first: Object.keys(info) });
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
token: {
|
|
131
|
+
usage: `Usage: ${BIN} token [-c CONTEXT] [--header]
|
|
132
|
+
Prints a live access token to stdout (refreshing it first if needed). Treat it as a secret.
|
|
133
|
+
curl -H "$(${BIN} token --header)" https://<instance>.service-now.com/api/now/table/incident?sysparm_limit=1`,
|
|
134
|
+
options: { header: { type: 'boolean' } },
|
|
135
|
+
async run(_, opts) {
|
|
136
|
+
const session = await getSession(ctxOf(opts));
|
|
137
|
+
process.stdout.write(`${opts.header ? 'Authorization: Bearer ' : ''}${session.access_token}\n`);
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
context: {
|
|
142
|
+
usage: `Usage: ${BIN} context [list]
|
|
143
|
+
${BIN} context current
|
|
144
|
+
${BIN} context use NAME
|
|
145
|
+
${BIN} context add NAME INSTANCE INSTANCE: "acme", "acme.service-now.com" or a URL
|
|
146
|
+
${BIN} context remove NAME
|
|
147
|
+
The first context added becomes the current one.`,
|
|
148
|
+
options: {},
|
|
149
|
+
async run(_, opts, [sub = 'list', name, instance]) {
|
|
150
|
+
const cfg = loadConfig();
|
|
151
|
+
switch (sub) {
|
|
152
|
+
case 'list': {
|
|
153
|
+
const rows = Object.entries(cfg.contexts).map(([n, c]) => {
|
|
154
|
+
const tok = loadTokens(n);
|
|
155
|
+
return {
|
|
156
|
+
current: n === cfg.current_context ? '*' : '',
|
|
157
|
+
name: n,
|
|
158
|
+
instance: normalizeInstance(c.instance),
|
|
159
|
+
user: tok?.user?.user_name ?? (tok ? '(logged in)' : ''),
|
|
160
|
+
};
|
|
161
|
+
});
|
|
162
|
+
if (!rows.length && outputMode(opts, 'table') === 'table') {
|
|
163
|
+
log(`no contexts; run: ${BIN} context add NAME INSTANCE`);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
return outputMode(opts, 'table') === 'json' ? printJSON(rows) : printTable(rows, ['current', 'name', 'instance', 'user']);
|
|
167
|
+
}
|
|
168
|
+
case 'current':
|
|
169
|
+
process.stdout.write(`${resolveContext(cfg, opts.context).name}\n`);
|
|
170
|
+
return;
|
|
171
|
+
case 'use':
|
|
172
|
+
if (!cfg.contexts[name]) throw new Error(`unknown context "${name}"`);
|
|
173
|
+
cfg.current_context = name;
|
|
174
|
+
saveConfig(cfg);
|
|
175
|
+
log(`Current context: ${name}`);
|
|
176
|
+
return;
|
|
177
|
+
case 'add':
|
|
178
|
+
if (!name || !instance) throw new Error(`usage: ${BIN} context add NAME INSTANCE`);
|
|
179
|
+
cfg.contexts[name] = { instance: normalizeInstance(instance) };
|
|
180
|
+
if (!cfg.current_context) cfg.current_context = name;
|
|
181
|
+
saveConfig(cfg);
|
|
182
|
+
log(`Added ${name} → ${cfg.contexts[name].instance}${cfg.current_context === name ? ' (current)' : ''}`);
|
|
183
|
+
return;
|
|
184
|
+
case 'remove':
|
|
185
|
+
if (!cfg.contexts[name]) throw new Error(`unknown context "${name}"`);
|
|
186
|
+
delete cfg.contexts[name];
|
|
187
|
+
if (cfg.current_context === name) cfg.current_context = Object.keys(cfg.contexts)[0] ?? null;
|
|
188
|
+
saveConfig(cfg);
|
|
189
|
+
deleteTokens(name);
|
|
190
|
+
log(`Removed ${name}`);
|
|
191
|
+
return;
|
|
192
|
+
default:
|
|
193
|
+
throw new Error(`unknown subcommand "${sub}"\n\n${commands.context.usage}`);
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
|
|
198
|
+
api: {
|
|
199
|
+
usage: `Usage: ${BIN} api METHOD PATH [-q key=value]... [-d JSON|@file|-]
|
|
200
|
+
${BIN} api GET /api/now/table/sys_user_group -q sysparm_query=name=Service\\ Desk -q sysparm_fields=sys_id,name
|
|
201
|
+
${BIN} api POST /api/now/table/incident -d '{"short_description":"test"}'`,
|
|
202
|
+
options: { query: { type: 'string', short: 'q', multiple: true }, data: { type: 'string', short: 'd' } },
|
|
203
|
+
async run(_, opts, [method, path]) {
|
|
204
|
+
if (!method || !path) throw new Error(commands.api.usage);
|
|
205
|
+
const res = await request(ctxOf(opts), method.toUpperCase(), path, { query: parseSets(opts.query), body: readData(opts.data) });
|
|
206
|
+
if (typeof res.data === 'string') process.stdout.write(res.data.endsWith('\n') ? res.data : `${res.data}\n`);
|
|
207
|
+
else printJSON(res.data);
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
|
|
211
|
+
table: {
|
|
212
|
+
usage: `Usage:
|
|
213
|
+
${BIN} table list TABLE [-q QUERY] [-f FIELDS] [-l N] [--offset N] [--order [-]FIELD] [--raw]
|
|
214
|
+
${BIN} table get TABLE <sys_id|NUMBER> [-f FIELDS] [--all-fields] [--raw]
|
|
215
|
+
${BIN} table create TABLE [-s k=v]... [-d JSON]
|
|
216
|
+
${BIN} table update TABLE <sys_id|NUMBER> [-s k=v]... [-d JSON]
|
|
217
|
+
--raw returns stored values (sys_ids, choice values) instead of display values.`,
|
|
218
|
+
options: {
|
|
219
|
+
query: { type: 'string', short: 'q' },
|
|
220
|
+
fields: { type: 'string', short: 'f' },
|
|
221
|
+
limit: { type: 'string', short: 'l' },
|
|
222
|
+
offset: { type: 'string' },
|
|
223
|
+
order: { type: 'string' },
|
|
224
|
+
raw: { type: 'boolean' },
|
|
225
|
+
'all-fields': { type: 'boolean' },
|
|
226
|
+
set: { type: 'string', short: 's', multiple: true },
|
|
227
|
+
data: { type: 'string', short: 'd' },
|
|
228
|
+
},
|
|
229
|
+
async run(_, opts, [sub, table, id]) {
|
|
230
|
+
if (!sub || !table) throw new Error(commands.table.usage);
|
|
231
|
+
const ctx = ctxOf(opts);
|
|
232
|
+
const displayValue = !opts.raw;
|
|
233
|
+
const fields = splitFields(opts.fields);
|
|
234
|
+
const body = () => {
|
|
235
|
+
const b = { ...(readData(opts.data) || {}), ...parseSets(opts.set) };
|
|
236
|
+
if (!Object.keys(b).length) throw new Error('no fields given (-s k=v or -d JSON)');
|
|
237
|
+
return b;
|
|
238
|
+
};
|
|
239
|
+
const show = (rec) => (outputMode(opts, 'table') === 'json' ? printJSON(rec) : printRecord(rec, { first: ['number', 'sys_id'], all: opts['all-fields'] }));
|
|
240
|
+
switch (sub) {
|
|
241
|
+
case 'list': {
|
|
242
|
+
const query = joinQuery(opts.query, orderClause(opts.order));
|
|
243
|
+
const { rows, total } = await list(ctx, table, { query, fields, limit: opts.limit ?? 20, offset: opts.offset, displayValue });
|
|
244
|
+
if (outputMode(opts, 'table') === 'json') return printJSON(rows);
|
|
245
|
+
printTable(rows, fields);
|
|
246
|
+
printTotalNote(rows.length, total);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
case 'get':
|
|
250
|
+
if (!id) throw new Error(`usage: ${BIN} table get TABLE <sys_id|NUMBER>`);
|
|
251
|
+
return show(await get(ctx, table, id, { fields, displayValue }));
|
|
252
|
+
case 'create':
|
|
253
|
+
return show(await create(ctx, table, body()));
|
|
254
|
+
case 'update':
|
|
255
|
+
if (!id) throw new Error(`usage: ${BIN} table update TABLE <sys_id|NUMBER> -s k=v`);
|
|
256
|
+
return show(await update(ctx, table, id, body()));
|
|
257
|
+
default:
|
|
258
|
+
throw new Error(`unknown subcommand "${sub}"\n\n${commands.table.usage}`);
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
skills: {
|
|
264
|
+
usage: `Usage: ${BIN} skills [list] bundled skills and where they are installed
|
|
265
|
+
${BIN} skills get NAME [FILE] print a skill (or one of its files) without installing
|
|
266
|
+
${BIN} skills install [NAME...] [--agent claude] [--all-agents] [--local] [--dir DIR] [--force] [--dry-run]
|
|
267
|
+
${BIN} skills uninstall [NAME...] [--local] [--dir DIR] [--dry-run]
|
|
268
|
+
|
|
269
|
+
install copies skills to ~/.agents/skills/<name> (Codex, Cursor, Gemini, Copilot and other
|
|
270
|
+
.agents-compatible agents). --agent claude also links ~/.claude/skills/<name> (Claude Code).
|
|
271
|
+
--local uses ./.agents/skills and ./.claude/skills in the current project; --dir sets the .agents root.
|
|
272
|
+
Re-run install after upgrading ${BIN} to refresh the copies. Directories ${BIN} did not install are
|
|
273
|
+
left alone unless --force. No NAME means every bundled skill.`,
|
|
274
|
+
options: {
|
|
275
|
+
agent: { type: 'string', multiple: true },
|
|
276
|
+
'all-agents': { type: 'boolean' },
|
|
277
|
+
local: { type: 'boolean' },
|
|
278
|
+
dir: { type: 'string' },
|
|
279
|
+
force: { type: 'boolean' },
|
|
280
|
+
'dry-run': { type: 'boolean' },
|
|
281
|
+
},
|
|
282
|
+
async run(_, opts, [sub = 'list', ...names]) {
|
|
283
|
+
const all = bundledSkills();
|
|
284
|
+
const dests = destinations({ local: opts.local, dir: opts.dir });
|
|
285
|
+
const pick = (list) => {
|
|
286
|
+
if (!list.length) return all;
|
|
287
|
+
return list.map((n) => {
|
|
288
|
+
const s = all.find((x) => x.name === n);
|
|
289
|
+
if (!s) throw new Error(`no bundled skill "${n}" (have: ${all.map((x) => x.name).join(', ')})`);
|
|
290
|
+
return s;
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
const report = (results) => {
|
|
294
|
+
if (outputMode(opts, 'table') === 'json') return printJSON(results);
|
|
295
|
+
printTable(results, ['action', 'skill', 'path']);
|
|
296
|
+
if (results.some((r) => r.action === 'skipped-foreign')) {
|
|
297
|
+
log(`Some paths exist but were not installed by ${BIN}; left untouched. Use --force to replace them.`);
|
|
298
|
+
process.exitCode = 1;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
switch (sub) {
|
|
302
|
+
case 'list': {
|
|
303
|
+
const rows = all.map((s) => {
|
|
304
|
+
const st = skillStatus(s, dests);
|
|
305
|
+
return { name: s.name, canonical: st.canonical, ...st.agents, path: path.join(dests.canonical, s.name), description: s.description };
|
|
306
|
+
});
|
|
307
|
+
return outputMode(opts, 'table') === 'json' ? printJSON(rows) : printTable(rows, ['name', 'canonical', ...AGENTS, 'path']);
|
|
308
|
+
}
|
|
309
|
+
case 'get': {
|
|
310
|
+
if (!names[0]) throw new Error(`usage: ${BIN} skills get NAME [FILE]`);
|
|
311
|
+
const [skill] = pick(names.slice(0, 1));
|
|
312
|
+
const file = path.resolve(skill.dir, names[1] ?? 'SKILL.md');
|
|
313
|
+
if (!file.startsWith(skill.dir + path.sep)) throw new Error('FILE must be inside the skill directory');
|
|
314
|
+
process.stdout.write(fs.readFileSync(file, 'utf8'));
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
case 'install': {
|
|
318
|
+
const agents = opts['all-agents'] ? AGENTS : [...new Set(opts.agent ?? [])];
|
|
319
|
+
const bad = agents.filter((a) => !AGENTS.includes(a));
|
|
320
|
+
if (bad.length) throw new Error(`unsupported --agent ${bad.join(', ')} (supported: ${AGENTS.join(', ')}; ~/.agents/skills covers the rest)`);
|
|
321
|
+
return report(installSkills(pick(names), { dests, agents, force: opts.force, dryRun: opts['dry-run'] }));
|
|
322
|
+
}
|
|
323
|
+
case 'uninstall':
|
|
324
|
+
return report(uninstallSkills(pick(names), { dests, dryRun: opts['dry-run'] }));
|
|
325
|
+
default:
|
|
326
|
+
throw new Error(`unknown subcommand "${sub}"\n\n${commands.skills.usage}`);
|
|
327
|
+
}
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
...recordCommands(),
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
export async function main(argv) {
|
|
335
|
+
// Pass 1: find the command word (global flags may precede it).
|
|
336
|
+
const first = parseArgs({ args: argv, options: GLOBAL_OPTIONS, allowPositionals: true, strict: false });
|
|
337
|
+
const name = first.positionals[0];
|
|
338
|
+
if (!name) {
|
|
339
|
+
process.stdout.write(HELP + '\n');
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
if (name === 'help') {
|
|
343
|
+
const target = commands[first.positionals[1]];
|
|
344
|
+
process.stdout.write((target ? target.usage : HELP) + '\n');
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const cmd = commands[name];
|
|
348
|
+
if (!cmd) throw new Error(`unknown command "${name}"; run: ${BIN} help`);
|
|
349
|
+
|
|
350
|
+
// Pass 2: strict parse with the command's own options.
|
|
351
|
+
const { values, positionals } = parseArgs({ args: argv, options: { ...GLOBAL_OPTIONS, ...cmd.options }, allowPositionals: true, strict: true });
|
|
352
|
+
if (values.help) {
|
|
353
|
+
process.stdout.write(cmd.usage + '\n');
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
positionals.splice(positionals.indexOf(name), 1);
|
|
357
|
+
await cmd.run(null, values, positionals);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function handleError(err) {
|
|
361
|
+
// Programming errors keep their stack; everything else (API, auth, usage, network) prints the message only.
|
|
362
|
+
const network = err instanceof TypeError && err.message === 'fetch failed';
|
|
363
|
+
const expected = network || !(err instanceof TypeError || err instanceof ReferenceError);
|
|
364
|
+
const text = network ? `network error: ${err.cause?.code || err.cause?.message || 'fetch failed'}` : err?.message;
|
|
365
|
+
const msg = process.env.SNOW_DEBUG || !expected ? err?.stack || String(err) : text;
|
|
366
|
+
process.stderr.write(`${BIN}: ${msg}\n`);
|
|
367
|
+
process.exitCode = 1;
|
|
368
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const BIN = 'snow';
|
|
6
|
+
|
|
7
|
+
export function configDir() {
|
|
8
|
+
return process.env.SNOW_CONFIG_DIR || path.join(os.homedir(), '.config', 'snow');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function configPath() {
|
|
12
|
+
return path.join(configDir(), 'config.json');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function writePrivateFile(file, content) {
|
|
16
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
17
|
+
fs.writeFileSync(file, content, { mode: 0o600 });
|
|
18
|
+
fs.chmodSync(file, 0o600);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function loadConfig() {
|
|
22
|
+
const file = configPath();
|
|
23
|
+
if (!fs.existsSync(file)) return { current_context: null, contexts: {} };
|
|
24
|
+
const cfg = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
25
|
+
cfg.contexts ??= {};
|
|
26
|
+
return cfg;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function saveConfig(cfg) {
|
|
30
|
+
writePrivateFile(configPath(), JSON.stringify(cfg, null, 2) + '\n');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Accepts "acme", "acme.service-now.com" or a full URL; returns "https://host". */
|
|
34
|
+
export function normalizeInstance(value) {
|
|
35
|
+
let v = String(value).trim().replace(/\/+$/, '');
|
|
36
|
+
if (!v.includes('.') && !v.includes('://')) v = `${v}.service-now.com`;
|
|
37
|
+
if (!/^https?:\/\//.test(v)) v = `https://${v}`;
|
|
38
|
+
const u = new URL(v);
|
|
39
|
+
return `${u.protocol}//${u.host}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Context precedence: --context flag > SNOW_CONTEXT env > current_context. */
|
|
43
|
+
export function resolveContext(cfg, flag) {
|
|
44
|
+
const name = flag || process.env.SNOW_CONTEXT || cfg.current_context;
|
|
45
|
+
if (!name) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
Object.keys(cfg.contexts).length
|
|
48
|
+
? `no context selected; run: ${BIN} context use <name>`
|
|
49
|
+
: `no instance configured; run: ${BIN} context add <name> <instance>`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
const ctx = cfg.contexts[name];
|
|
53
|
+
if (!ctx) {
|
|
54
|
+
const known = Object.keys(cfg.contexts).join(', ') || 'none';
|
|
55
|
+
throw new Error(`unknown context "${name}" (known: ${known})`);
|
|
56
|
+
}
|
|
57
|
+
return { name, instance: normalizeInstance(ctx.instance) };
|
|
58
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { getSession, LoginRequired } from './auth.js';
|
|
2
|
+
|
|
3
|
+
export class ApiError extends Error {
|
|
4
|
+
constructor(status, message, data) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'ApiError';
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.data = data;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function buildUrl(ctx, apiPath, query) {
|
|
13
|
+
const u = /^https?:\/\//.test(apiPath) ? new URL(apiPath) : new URL(apiPath.startsWith('/') ? apiPath : `/${apiPath}`, ctx.instance);
|
|
14
|
+
if (u.origin !== new URL(ctx.instance).origin) throw new Error(`refusing to send token to ${u.origin}; context instance is ${ctx.instance}`);
|
|
15
|
+
for (const [k, v] of Object.entries(query || {})) {
|
|
16
|
+
if (v === undefined || v === null || v === '') continue;
|
|
17
|
+
u.searchParams.set(k, String(v));
|
|
18
|
+
}
|
|
19
|
+
return u;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function send(url, method, token, body, headers) {
|
|
23
|
+
return fetch(url, {
|
|
24
|
+
method,
|
|
25
|
+
headers: {
|
|
26
|
+
Accept: 'application/json',
|
|
27
|
+
Authorization: `Bearer ${token}`,
|
|
28
|
+
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
29
|
+
...headers,
|
|
30
|
+
},
|
|
31
|
+
body: body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Authenticated call to the instance. Returns { status, headers, data }. Throws ApiError on non-2xx. */
|
|
36
|
+
export async function request(ctx, method, apiPath, { query, body, headers } = {}) {
|
|
37
|
+
const url = buildUrl(ctx, apiPath, query);
|
|
38
|
+
let session = await getSession(ctx);
|
|
39
|
+
let res = await send(url, method, session.access_token, body, headers);
|
|
40
|
+
if (res.status === 401) {
|
|
41
|
+
// Token revoked or expired early: refresh once, then give up.
|
|
42
|
+
session = await getSession(ctx, { forceRefresh: true });
|
|
43
|
+
res = await send(url, method, session.access_token, body, headers);
|
|
44
|
+
if (res.status === 401) throw new LoginRequired(ctx, 'instance rejected the access token');
|
|
45
|
+
}
|
|
46
|
+
const text = await res.text();
|
|
47
|
+
let data = text;
|
|
48
|
+
if ((res.headers.get('content-type') || '').includes('json') && text) {
|
|
49
|
+
try {
|
|
50
|
+
data = JSON.parse(text);
|
|
51
|
+
} catch {
|
|
52
|
+
/* keep text */
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (!res.ok) {
|
|
56
|
+
const e = data?.error;
|
|
57
|
+
const msg = e ? [e.message, e.detail].filter(Boolean).join(': ') : String(text).slice(0, 300) || res.statusText;
|
|
58
|
+
throw new ApiError(res.status, `${method} ${url.pathname} → HTTP ${res.status}: ${msg}`, data);
|
|
59
|
+
}
|
|
60
|
+
return { status: res.status, headers: res.headers, data };
|
|
61
|
+
}
|
package/src/output.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const MAX_COL = 60;
|
|
2
|
+
|
|
3
|
+
export function fmtValue(v) {
|
|
4
|
+
if (v === null || v === undefined) return '';
|
|
5
|
+
if (typeof v === 'string') return v;
|
|
6
|
+
if (typeof v === 'object' && 'display_value' in v) return fmtValue(v.display_value);
|
|
7
|
+
return typeof v === 'object' ? JSON.stringify(v) : String(v);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const oneLine = (s) => s.replace(/\s+/g, ' ').trim();
|
|
11
|
+
const clip = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
12
|
+
|
|
13
|
+
export function printJSON(data) {
|
|
14
|
+
process.stdout.write(JSON.stringify(data, null, 2) + '\n');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function printTable(rows, cols) {
|
|
18
|
+
if (!rows.length) {
|
|
19
|
+
process.stderr.write('(no records)\n');
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
cols = cols?.length ? cols : Object.keys(rows[0]);
|
|
23
|
+
const cells = rows.map((r) => cols.map((c) => clip(oneLine(fmtValue(r[c])), MAX_COL)));
|
|
24
|
+
const widths = cols.map((c, i) => Math.max(c.length, ...cells.map((row) => row[i].length)));
|
|
25
|
+
const line = (vals) => vals.map((v, i) => v.padEnd(widths[i])).join(' ').trimEnd();
|
|
26
|
+
const out = [line(cols), line(widths.map((w) => '-'.repeat(w))), ...cells.map(line)];
|
|
27
|
+
process.stdout.write(out.join('\n') + '\n');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Vertical key: value view. `first` fields print first, in order; empty values hidden unless all. */
|
|
31
|
+
export function printRecord(rec, { first = [], all = false } = {}) {
|
|
32
|
+
const keys = [...first.filter((k) => k in rec), ...Object.keys(rec).filter((k) => !first.includes(k)).sort()];
|
|
33
|
+
const shown = keys.filter((k) => all || fmtValue(rec[k]) !== '');
|
|
34
|
+
const w = Math.max(...shown.map((k) => k.length));
|
|
35
|
+
const out = shown.map((k) => {
|
|
36
|
+
const v = fmtValue(rec[k]);
|
|
37
|
+
return `${k.padEnd(w)} ${v.includes('\n') ? v.replace(/\n/g, `\n${' '.repeat(w + 2)}`) : v}`;
|
|
38
|
+
});
|
|
39
|
+
process.stdout.write(out.join('\n') + '\n');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** X-Total-Count counts matches before row-level ACLs, so "0 shown, N total" means ACL-hidden rows. */
|
|
43
|
+
export function printTotalNote(shown, total) {
|
|
44
|
+
if (total === undefined || total <= shown) return;
|
|
45
|
+
process.stderr.write(shown === 0 ? `(0 visible of ${total} matching; rows hidden by ACLs)\n` : `(${shown} of ${total}; use -l / --offset)\n`);
|
|
46
|
+
}
|