@sortlist/cli 0.36.0 → 0.38.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/README.md +78 -13
- package/bin/sl.mjs +20 -7
- package/dist/index.js +1976 -0
- package/dist/index.js.map +1 -0
- package/package.json +8 -7
- package/src/codegen.ts +0 -34
- package/src/commands/config.ts +0 -95
- package/src/commands/dynamic.test.ts +0 -87
- package/src/commands/dynamic.ts +0 -569
- package/src/commands/login.ts +0 -155
- package/src/commands/logout.ts +0 -45
- package/src/commands/token.ts +0 -23
- package/src/commands/whoami.ts +0 -55
- package/src/graphql/client.ts +0 -259
- package/src/graphql/generated/gql.ts +0 -70
- package/src/graphql/generated/graphql.ts +0 -4757
- package/src/graphql/generated/index.ts +0 -1
- package/src/graphql/introspection.ts +0 -240
- package/src/graphql/operations/common.ts +0 -16
- package/src/graphql/operations/hermes.ts +0 -54
- package/src/graphql/query-builder.test.ts +0 -114
- package/src/graphql/query-builder.ts +0 -239
- package/src/index.ts +0 -186
- package/src/lib/auth.test.ts +0 -30
- package/src/lib/auth.ts +0 -58
- package/src/lib/browser.ts +0 -11
- package/src/lib/company.ts +0 -15
- package/src/lib/config.ts +0 -80
- package/src/lib/env.ts +0 -10
- package/src/lib/output.ts +0 -58
- package/src/lib/sentry.ts +0 -70
- package/src/lib/version-check.ts +0 -88
package/dist/index.js
ADDED
|
@@ -0,0 +1,1976 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { Command as Command8 } from "commander";
|
|
3
|
+
|
|
4
|
+
// src/commands/config.ts
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
|
|
7
|
+
// src/lib/application-session.ts
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
import os from "os";
|
|
10
|
+
import path from "path";
|
|
11
|
+
var SESSION_PATH = path.join(os.homedir(), ".sortlist", "application-session.json");
|
|
12
|
+
function loadApplicationSession() {
|
|
13
|
+
try {
|
|
14
|
+
const session = JSON.parse(fs.readFileSync(SESSION_PATH, "utf-8"));
|
|
15
|
+
if (Date.now() >= session.expiresAt) return null;
|
|
16
|
+
return session;
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function saveApplicationSession(session) {
|
|
22
|
+
fs.mkdirSync(path.dirname(SESSION_PATH), { recursive: true });
|
|
23
|
+
fs.writeFileSync(SESSION_PATH, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
|
|
24
|
+
}
|
|
25
|
+
function clearApplicationSession() {
|
|
26
|
+
try {
|
|
27
|
+
fs.unlinkSync(SESSION_PATH);
|
|
28
|
+
return true;
|
|
29
|
+
} catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function applicationSessionExpired() {
|
|
34
|
+
return fs.existsSync(SESSION_PATH) && loadApplicationSession() === null;
|
|
35
|
+
}
|
|
36
|
+
function actingAsApplication() {
|
|
37
|
+
if (process.env.SORTLIST_CLIENT_ID && process.env.SORTLIST_CLIENT_SECRET) return true;
|
|
38
|
+
return loadApplicationSession() !== null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// src/lib/auth.ts
|
|
42
|
+
import fs2 from "fs";
|
|
43
|
+
import os2 from "os";
|
|
44
|
+
import path2 from "path";
|
|
45
|
+
|
|
46
|
+
// src/lib/output.ts
|
|
47
|
+
function colorEnabled() {
|
|
48
|
+
return process.stderr.isTTY === true && !process.env.NO_COLOR;
|
|
49
|
+
}
|
|
50
|
+
var ansi = {
|
|
51
|
+
reset: "\x1B[0m",
|
|
52
|
+
dim: "\x1B[2m",
|
|
53
|
+
red: "\x1B[31m",
|
|
54
|
+
green: "\x1B[32m",
|
|
55
|
+
yellow: "\x1B[33m"
|
|
56
|
+
};
|
|
57
|
+
function c(code, text) {
|
|
58
|
+
if (!colorEnabled()) return text;
|
|
59
|
+
return `${ansi[code]}${text}${ansi.reset}`;
|
|
60
|
+
}
|
|
61
|
+
function isJsonMode(options) {
|
|
62
|
+
if (options.json) return true;
|
|
63
|
+
return !process.stdout.isTTY;
|
|
64
|
+
}
|
|
65
|
+
function printJson(data) {
|
|
66
|
+
process.stdout.write(JSON.stringify(data, null, 2) + "\n");
|
|
67
|
+
}
|
|
68
|
+
function info(msg) {
|
|
69
|
+
process.stderr.write(`${msg}
|
|
70
|
+
`);
|
|
71
|
+
}
|
|
72
|
+
function success(msg) {
|
|
73
|
+
process.stderr.write(`${c("green", "\u2713")} ${msg}
|
|
74
|
+
`);
|
|
75
|
+
}
|
|
76
|
+
function warn(msg) {
|
|
77
|
+
process.stderr.write(`${c("yellow", "\u26A0")} ${msg}
|
|
78
|
+
`);
|
|
79
|
+
}
|
|
80
|
+
function error(msg) {
|
|
81
|
+
process.stderr.write(`${c("red", "\u2717")} Error: ${msg}
|
|
82
|
+
`);
|
|
83
|
+
}
|
|
84
|
+
function hint(msg) {
|
|
85
|
+
process.stderr.write(`${c("dim", " " + msg)}
|
|
86
|
+
`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// src/lib/auth.ts
|
|
90
|
+
var CREDENTIALS_PATH = path2.join(os2.homedir(), ".sortlist", "credentials.json");
|
|
91
|
+
function ensureDir() {
|
|
92
|
+
const dir = path2.dirname(CREDENTIALS_PATH);
|
|
93
|
+
if (!fs2.existsSync(dir)) {
|
|
94
|
+
fs2.mkdirSync(dir, { recursive: true });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function saveCredentials(creds) {
|
|
98
|
+
ensureDir();
|
|
99
|
+
fs2.writeFileSync(CREDENTIALS_PATH, JSON.stringify(creds, null, 2) + "\n", { mode: 384 });
|
|
100
|
+
}
|
|
101
|
+
function loadCredentials() {
|
|
102
|
+
try {
|
|
103
|
+
const raw = fs2.readFileSync(CREDENTIALS_PATH, "utf-8");
|
|
104
|
+
return JSON.parse(raw);
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function clearCredentials() {
|
|
110
|
+
try {
|
|
111
|
+
fs2.unlinkSync(CREDENTIALS_PATH);
|
|
112
|
+
} catch {
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function isExpired(creds) {
|
|
116
|
+
return Date.now() >= (creds.expiresAt - 60) * 1e3;
|
|
117
|
+
}
|
|
118
|
+
function ensureAuthenticated() {
|
|
119
|
+
const creds = loadCredentials();
|
|
120
|
+
if (!creds) {
|
|
121
|
+
error("You are not logged in.");
|
|
122
|
+
hint("Run `sl login` to authenticate with your Sortlist account.");
|
|
123
|
+
process.exit(2);
|
|
124
|
+
}
|
|
125
|
+
return creds;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/lib/config.ts
|
|
129
|
+
import fs3 from "fs";
|
|
130
|
+
import os3 from "os";
|
|
131
|
+
import path3 from "path";
|
|
132
|
+
var SORTLIST_DIR = path3.join(os3.homedir(), ".sortlist");
|
|
133
|
+
var CONFIG_PATH = path3.join(SORTLIST_DIR, "config.json");
|
|
134
|
+
var DEFAULT_CONFIG = {
|
|
135
|
+
endpoint: "https://federation.sortlist.com/graphql"
|
|
136
|
+
};
|
|
137
|
+
function ensureDir2() {
|
|
138
|
+
if (!fs3.existsSync(SORTLIST_DIR)) {
|
|
139
|
+
fs3.mkdirSync(SORTLIST_DIR, { recursive: true });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function loadConfig() {
|
|
143
|
+
try {
|
|
144
|
+
const raw = fs3.readFileSync(CONFIG_PATH, "utf-8");
|
|
145
|
+
return { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
|
|
146
|
+
} catch {
|
|
147
|
+
return { ...DEFAULT_CONFIG };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function saveConfig(config) {
|
|
151
|
+
ensureDir2();
|
|
152
|
+
const current = loadConfig();
|
|
153
|
+
const merged = { ...current, ...config };
|
|
154
|
+
fs3.writeFileSync(CONFIG_PATH, JSON.stringify(merged, null, 2) + "\n");
|
|
155
|
+
}
|
|
156
|
+
function resetConfig() {
|
|
157
|
+
try {
|
|
158
|
+
fs3.unlinkSync(CONFIG_PATH);
|
|
159
|
+
} catch {
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function clearIdentity() {
|
|
163
|
+
const { endpoint, tokenEndpoint: tokenEndpoint2 } = loadConfig();
|
|
164
|
+
ensureDir2();
|
|
165
|
+
const kept = { endpoint };
|
|
166
|
+
if (tokenEndpoint2) kept.tokenEndpoint = tokenEndpoint2;
|
|
167
|
+
fs3.writeFileSync(CONFIG_PATH, JSON.stringify(kept, null, 2) + "\n");
|
|
168
|
+
}
|
|
169
|
+
function getEndpoint(override) {
|
|
170
|
+
if (override) return override;
|
|
171
|
+
if (process.env.SL_ENDPOINT) return process.env.SL_ENDPOINT;
|
|
172
|
+
return loadConfig().endpoint;
|
|
173
|
+
}
|
|
174
|
+
function getUserContext() {
|
|
175
|
+
const config = loadConfig();
|
|
176
|
+
return { companyId: config.companyId };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/lib/env.ts
|
|
180
|
+
import fs5 from "fs";
|
|
181
|
+
import path5 from "path";
|
|
182
|
+
|
|
183
|
+
// src/lib/package-root.ts
|
|
184
|
+
import fs4 from "fs";
|
|
185
|
+
import path4 from "path";
|
|
186
|
+
import { fileURLToPath } from "url";
|
|
187
|
+
function findPackageRoot() {
|
|
188
|
+
let dir = path4.dirname(fileURLToPath(import.meta.url));
|
|
189
|
+
while (true) {
|
|
190
|
+
const pkgPath = path4.join(dir, "package.json");
|
|
191
|
+
if (fs4.existsSync(pkgPath)) {
|
|
192
|
+
try {
|
|
193
|
+
const parsed = JSON.parse(fs4.readFileSync(pkgPath, "utf-8"));
|
|
194
|
+
if (parsed.name === "@sortlist/cli") return dir;
|
|
195
|
+
} catch {
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const parent = path4.dirname(dir);
|
|
199
|
+
if (parent === dir) throw new Error("Could not locate the @sortlist/cli package root");
|
|
200
|
+
dir = parent;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
var packageRoot = findPackageRoot();
|
|
204
|
+
var pkg = JSON.parse(fs4.readFileSync(path4.join(packageRoot, "package.json"), "utf-8"));
|
|
205
|
+
|
|
206
|
+
// src/lib/env.ts
|
|
207
|
+
var isLocalDev = !fs5.existsSync(path5.join(packageRoot, ".published"));
|
|
208
|
+
|
|
209
|
+
// src/commands/config.ts
|
|
210
|
+
var ENVIRONMENTS = [
|
|
211
|
+
{
|
|
212
|
+
name: "production",
|
|
213
|
+
label: "federation.sortlist.com",
|
|
214
|
+
endpoint: "https://federation.sortlist.com/graphql",
|
|
215
|
+
tokenEndpoint: "https://hermes.production.sortlist.cloud/oauth/token"
|
|
216
|
+
},
|
|
217
|
+
{
|
|
218
|
+
name: "staging",
|
|
219
|
+
label: "federation.sortlist-test.com",
|
|
220
|
+
endpoint: "https://federation.sortlist-test.com/graphql",
|
|
221
|
+
tokenEndpoint: "https://hermes.staging.sortlist.cloud/oauth/token"
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
name: "local",
|
|
225
|
+
label: "localhost:4020",
|
|
226
|
+
endpoint: "http://localhost:4020/graphql",
|
|
227
|
+
tokenEndpoint: "http://localhost:8003/oauth/token"
|
|
228
|
+
}
|
|
229
|
+
];
|
|
230
|
+
var configCommand = new Command("config").summary("View or update CLI configuration").description(
|
|
231
|
+
"View or update CLI configuration\n\nManage your company context and credentials.\n\nExamples:\n sl config show See current endpoint and company\n" + (isLocalDev ? " sl config set endpoint <url> Point to a custom endpoint\n" : "") + " sl config reset Clear all config and credentials"
|
|
232
|
+
);
|
|
233
|
+
configCommand.command("show").description("Show current configuration").action(function() {
|
|
234
|
+
const opts = this.optsWithGlobals();
|
|
235
|
+
const config = loadConfig();
|
|
236
|
+
if (isJsonMode(opts)) {
|
|
237
|
+
printJson(config);
|
|
238
|
+
} else {
|
|
239
|
+
info(`Endpoint: ${config.endpoint}`);
|
|
240
|
+
if (config.tokenEndpoint) info(`Token endpoint: ${config.tokenEndpoint}`);
|
|
241
|
+
if (config.companyId) info(`Company ID: ${config.companyId}`);
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
var SETTABLE_KEYS = [...isLocalDev ? ["endpoint"] : [], "companyId", "tokenEndpoint"];
|
|
245
|
+
configCommand.command("set <key> <value>").description(`Set a config value (${SETTABLE_KEYS.join(", ")})`).action((key, value) => {
|
|
246
|
+
if (!SETTABLE_KEYS.includes(key)) {
|
|
247
|
+
error(`Unknown config key: "${key}".`);
|
|
248
|
+
info("");
|
|
249
|
+
info(" Allowed keys:");
|
|
250
|
+
for (const k of SETTABLE_KEYS) {
|
|
251
|
+
info(` ${k}`);
|
|
252
|
+
}
|
|
253
|
+
hint("Usage: sl config set <key> <value>");
|
|
254
|
+
process.exit(1);
|
|
255
|
+
}
|
|
256
|
+
saveConfig({ [key]: value });
|
|
257
|
+
success(`Set ${key} = ${value}`);
|
|
258
|
+
});
|
|
259
|
+
if (isLocalDev) {
|
|
260
|
+
for (const environment of ENVIRONMENTS) {
|
|
261
|
+
configCommand.command(`use-${environment.name}`).description(`Point CLI to ${environment.name} (${environment.label})`).action(() => {
|
|
262
|
+
saveConfig({ endpoint: environment.endpoint, tokenEndpoint: environment.tokenEndpoint });
|
|
263
|
+
success(`Endpoint set to ${environment.endpoint}`);
|
|
264
|
+
info(`Token endpoint set to ${environment.tokenEndpoint}`);
|
|
265
|
+
hint(`Run \`sl login\` to authenticate against ${environment.name}.`);
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
configCommand.command("reset").description("Reset all config and credentials").action(() => {
|
|
270
|
+
resetConfig();
|
|
271
|
+
clearCredentials();
|
|
272
|
+
clearApplicationSession();
|
|
273
|
+
success("Config, credentials and any application session cleared.");
|
|
274
|
+
hint("Run `sl login` to re-authenticate.");
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
// src/commands/dynamic.ts
|
|
278
|
+
import { Command as Command2 } from "commander";
|
|
279
|
+
import {
|
|
280
|
+
isEnumType as isEnumType2,
|
|
281
|
+
isInputObjectType,
|
|
282
|
+
isInterfaceType as isInterfaceType2,
|
|
283
|
+
isListType as isListType2,
|
|
284
|
+
isNonNullType as isNonNullType2,
|
|
285
|
+
isObjectType as isObjectType2,
|
|
286
|
+
isScalarType as isScalarType2,
|
|
287
|
+
isUnionType as isUnionType2
|
|
288
|
+
} from "graphql";
|
|
289
|
+
|
|
290
|
+
// src/graphql/client.ts
|
|
291
|
+
import { print } from "graphql";
|
|
292
|
+
|
|
293
|
+
// src/lib/client-credentials.ts
|
|
294
|
+
var cached = null;
|
|
295
|
+
function clientCredentials() {
|
|
296
|
+
const clientId = process.env.SORTLIST_CLIENT_ID;
|
|
297
|
+
const clientSecret = process.env.SORTLIST_CLIENT_SECRET;
|
|
298
|
+
if (!clientId || !clientSecret) return null;
|
|
299
|
+
return { clientId, clientSecret };
|
|
300
|
+
}
|
|
301
|
+
var CLAIM_NAMESPACE = "https://sortlist.com/";
|
|
302
|
+
function applicationIdentity(accessToken) {
|
|
303
|
+
try {
|
|
304
|
+
const payload = accessToken.split(".")[1];
|
|
305
|
+
if (!payload) return null;
|
|
306
|
+
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
|
307
|
+
return {
|
|
308
|
+
applicationId: claims[`${CLAIM_NAMESPACE}application_id`],
|
|
309
|
+
credentialId: claims[`${CLAIM_NAMESPACE}credential_id`],
|
|
310
|
+
companyId: claims[`${CLAIM_NAMESPACE}company_id`],
|
|
311
|
+
sub: claims.sub,
|
|
312
|
+
expiresAt: new Date(claims.exp * 1e3)
|
|
313
|
+
};
|
|
314
|
+
} catch {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
function tokenEndpoint() {
|
|
319
|
+
const configured = process.env.SORTLIST_TOKEN_URL ?? loadConfig().tokenEndpoint;
|
|
320
|
+
if (!configured) {
|
|
321
|
+
throw new Error("No token endpoint configured. Set SORTLIST_TOKEN_URL or run: sl config set tokenEndpoint <url>");
|
|
322
|
+
}
|
|
323
|
+
return configured;
|
|
324
|
+
}
|
|
325
|
+
async function fetchClientCredentialsToken(credentials) {
|
|
326
|
+
if (cached && Date.now() < cached.expiresAt) return cached.accessToken;
|
|
327
|
+
const body = new URLSearchParams({
|
|
328
|
+
grant_type: "client_credentials",
|
|
329
|
+
client_id: credentials.clientId,
|
|
330
|
+
client_secret: credentials.clientSecret
|
|
331
|
+
});
|
|
332
|
+
const res = await fetch(tokenEndpoint(), {
|
|
333
|
+
method: "POST",
|
|
334
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
335
|
+
body: body.toString()
|
|
336
|
+
});
|
|
337
|
+
const json = await res.json().catch(() => ({}));
|
|
338
|
+
if (!res.ok || !json.access_token) {
|
|
339
|
+
const reason = json.error ?? `HTTP ${res.status}`;
|
|
340
|
+
throw new Error(`Token request failed: ${reason}`);
|
|
341
|
+
}
|
|
342
|
+
cached = {
|
|
343
|
+
accessToken: json.access_token,
|
|
344
|
+
// 60s of headroom, matching the interactive path's expiry check.
|
|
345
|
+
expiresAt: Date.now() + ((json.expires_in ?? 3600) - 60) * 1e3
|
|
346
|
+
};
|
|
347
|
+
return cached.accessToken;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/lib/sentry.ts
|
|
351
|
+
import * as Sentry from "@sentry/node";
|
|
352
|
+
var SENTRY_DSN = "https://306d2e4389b8baa0bf14e587c2ceff04@o27611.ingest.us.sentry.io/4511229468409856";
|
|
353
|
+
var SENTRY_ENVIRONMENT = process.env.SL_SENTRY_ENV ?? (isLocalDev ? "development" : "production");
|
|
354
|
+
var IGNORED_ERRORS = [
|
|
355
|
+
/Network Error/i,
|
|
356
|
+
/Failed to fetch/i,
|
|
357
|
+
/fetch failed/i,
|
|
358
|
+
/ECONNREFUSED/i,
|
|
359
|
+
/ENOTFOUND/i,
|
|
360
|
+
/ETIMEDOUT/i,
|
|
361
|
+
/Request aborted/i
|
|
362
|
+
];
|
|
363
|
+
function isIgnoredError(message) {
|
|
364
|
+
return IGNORED_ERRORS.some(
|
|
365
|
+
(pattern) => typeof pattern === "string" ? message.includes(pattern) : pattern.test(message)
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
function initSentry() {
|
|
369
|
+
if (isLocalDev) {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
Sentry.init({
|
|
373
|
+
dsn: SENTRY_DSN,
|
|
374
|
+
environment: SENTRY_ENVIRONMENT,
|
|
375
|
+
release: `${pkg.name}@${pkg.version}`,
|
|
376
|
+
tracesSampleRate: 0,
|
|
377
|
+
maxBreadcrumbs: 50,
|
|
378
|
+
attachStacktrace: true,
|
|
379
|
+
beforeSend(event) {
|
|
380
|
+
const message = event.exception?.values?.[0]?.value ?? "";
|
|
381
|
+
if (isIgnoredError(message)) {
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
return event;
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
Sentry.setTag("cli_version", pkg.version);
|
|
388
|
+
}
|
|
389
|
+
function captureException2(error2, extra) {
|
|
390
|
+
if (isLocalDev) {
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
Sentry.captureException(error2, extra ? { extra } : void 0);
|
|
394
|
+
}
|
|
395
|
+
function addBreadcrumb2(breadcrumb) {
|
|
396
|
+
if (isLocalDev) {
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
Sentry.addBreadcrumb(breadcrumb);
|
|
400
|
+
}
|
|
401
|
+
async function flushSentry(timeout = 2e3) {
|
|
402
|
+
if (isLocalDev) {
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
await Sentry.flush(timeout);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/graphql/generated/graphql.ts
|
|
409
|
+
var MeDocument = { "kind": "Document", "definitions": [{ "kind": "OperationDefinition", "operation": "query", "name": { "kind": "Name", "value": "Me" }, "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "me" }, "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "id" } }, { "kind": "Field", "name": { "kind": "Name", "value": "email" } }, { "kind": "Field", "name": { "kind": "Name", "value": "firstName" } }, { "kind": "Field", "name": { "kind": "Name", "value": "lastName" } }] } }] } }] };
|
|
410
|
+
var LogoutUrlDocument = { "kind": "Document", "definitions": [{ "kind": "OperationDefinition", "operation": "query", "name": { "kind": "Name", "value": "LogoutUrl" }, "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "logoutUrl" } }] } }] };
|
|
411
|
+
var DeviceAuthorizeDocument = { "kind": "Document", "definitions": [{ "kind": "OperationDefinition", "operation": "mutation", "name": { "kind": "Name", "value": "DeviceAuthorize" }, "variableDefinitions": [{ "kind": "VariableDefinition", "variable": { "kind": "Variable", "name": { "kind": "Name", "value": "input" } }, "type": { "kind": "NonNullType", "type": { "kind": "NamedType", "name": { "kind": "Name", "value": "DeviceAuthorizeInput" } } } }], "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "deviceAuthorize" }, "arguments": [{ "kind": "Argument", "name": { "kind": "Name", "value": "input" }, "value": { "kind": "Variable", "name": { "kind": "Name", "value": "input" } } }], "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "deviceCode" } }, { "kind": "Field", "name": { "kind": "Name", "value": "expiresIn" } }, { "kind": "Field", "name": { "kind": "Name", "value": "interval" } }, { "kind": "Field", "name": { "kind": "Name", "value": "userCode" } }, { "kind": "Field", "name": { "kind": "Name", "value": "verificationUri" } }, { "kind": "Field", "name": { "kind": "Name", "value": "verificationUriComplete" } }] } }] } }] };
|
|
412
|
+
var DeviceTokenDocument = { "kind": "Document", "definitions": [{ "kind": "OperationDefinition", "operation": "mutation", "name": { "kind": "Name", "value": "DeviceToken" }, "variableDefinitions": [{ "kind": "VariableDefinition", "variable": { "kind": "Variable", "name": { "kind": "Name", "value": "input" } }, "type": { "kind": "NonNullType", "type": { "kind": "NamedType", "name": { "kind": "Name", "value": "DeviceTokenInput" } } } }], "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "deviceToken" }, "arguments": [{ "kind": "Argument", "name": { "kind": "Name", "value": "input" }, "value": { "kind": "Variable", "name": { "kind": "Name", "value": "input" } } }], "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "accessToken" } }, { "kind": "Field", "name": { "kind": "Name", "value": "error" } }, { "kind": "Field", "name": { "kind": "Name", "value": "expiresIn" } }, { "kind": "Field", "name": { "kind": "Name", "value": "idToken" } }, { "kind": "Field", "name": { "kind": "Name", "value": "refreshToken" } }, { "kind": "Field", "name": { "kind": "Name", "value": "tokenType" } }] } }] } }] };
|
|
413
|
+
var RefreshTokenDocument = { "kind": "Document", "definitions": [{ "kind": "OperationDefinition", "operation": "mutation", "name": { "kind": "Name", "value": "RefreshToken" }, "variableDefinitions": [{ "kind": "VariableDefinition", "variable": { "kind": "Variable", "name": { "kind": "Name", "value": "input" } }, "type": { "kind": "NonNullType", "type": { "kind": "NamedType", "name": { "kind": "Name", "value": "RefreshTokenInput" } } } }], "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "refreshToken" }, "arguments": [{ "kind": "Argument", "name": { "kind": "Name", "value": "input" }, "value": { "kind": "Variable", "name": { "kind": "Name", "value": "input" } } }], "selectionSet": { "kind": "SelectionSet", "selections": [{ "kind": "Field", "name": { "kind": "Name", "value": "accessToken" } }, { "kind": "Field", "name": { "kind": "Name", "value": "error" } }, { "kind": "Field", "name": { "kind": "Name", "value": "expiresIn" } }, { "kind": "Field", "name": { "kind": "Name", "value": "idToken" } }, { "kind": "Field", "name": { "kind": "Name", "value": "refreshToken" } }, { "kind": "Field", "name": { "kind": "Name", "value": "tokenType" } }] } }] } }] };
|
|
414
|
+
|
|
415
|
+
// src/graphql/generated/gql.ts
|
|
416
|
+
var documents = {
|
|
417
|
+
"\n query Me {\n me {\n id\n email\n firstName\n lastName\n }\n }\n": MeDocument,
|
|
418
|
+
"\n query LogoutUrl {\n logoutUrl\n }\n": LogoutUrlDocument,
|
|
419
|
+
"\n mutation DeviceAuthorize($input: DeviceAuthorizeInput!) {\n deviceAuthorize(input: $input) {\n deviceCode\n expiresIn\n interval\n userCode\n verificationUri\n verificationUriComplete\n }\n }\n": DeviceAuthorizeDocument,
|
|
420
|
+
"\n mutation DeviceToken($input: DeviceTokenInput!) {\n deviceToken(input: $input) {\n accessToken\n error\n expiresIn\n idToken\n refreshToken\n tokenType\n }\n }\n": DeviceTokenDocument,
|
|
421
|
+
"\n mutation RefreshToken($input: RefreshTokenInput!) {\n refreshToken(input: $input) {\n accessToken\n error\n expiresIn\n idToken\n refreshToken\n tokenType\n }\n }\n": RefreshTokenDocument
|
|
422
|
+
};
|
|
423
|
+
function gql(source) {
|
|
424
|
+
return documents[source] ?? {};
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// src/graphql/operations/hermes.ts
|
|
428
|
+
var LogoutUrl = gql(`
|
|
429
|
+
query LogoutUrl {
|
|
430
|
+
logoutUrl
|
|
431
|
+
}
|
|
432
|
+
`);
|
|
433
|
+
var DeviceAuthorize = gql(`
|
|
434
|
+
mutation DeviceAuthorize($input: DeviceAuthorizeInput!) {
|
|
435
|
+
deviceAuthorize(input: $input) {
|
|
436
|
+
deviceCode
|
|
437
|
+
expiresIn
|
|
438
|
+
interval
|
|
439
|
+
userCode
|
|
440
|
+
verificationUri
|
|
441
|
+
verificationUriComplete
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
`);
|
|
445
|
+
var DeviceToken = gql(`
|
|
446
|
+
mutation DeviceToken($input: DeviceTokenInput!) {
|
|
447
|
+
deviceToken(input: $input) {
|
|
448
|
+
accessToken
|
|
449
|
+
error
|
|
450
|
+
expiresIn
|
|
451
|
+
idToken
|
|
452
|
+
refreshToken
|
|
453
|
+
tokenType
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
`);
|
|
457
|
+
var RefreshToken = gql(`
|
|
458
|
+
mutation RefreshToken($input: RefreshTokenInput!) {
|
|
459
|
+
refreshToken(input: $input) {
|
|
460
|
+
accessToken
|
|
461
|
+
error
|
|
462
|
+
expiresIn
|
|
463
|
+
idToken
|
|
464
|
+
refreshToken
|
|
465
|
+
tokenType
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
`);
|
|
469
|
+
|
|
470
|
+
// src/graphql/client.ts
|
|
471
|
+
function extractOperationName(query) {
|
|
472
|
+
const match = query.match(/(?:mutation|query|subscription)\s+(\w+)/);
|
|
473
|
+
return match?.[1] ?? "UnknownOperation";
|
|
474
|
+
}
|
|
475
|
+
var GraphQLRequestError = class extends Error {
|
|
476
|
+
operationName;
|
|
477
|
+
httpStatus;
|
|
478
|
+
graphqlErrors;
|
|
479
|
+
constructor(message, details) {
|
|
480
|
+
super(message);
|
|
481
|
+
this.name = "GraphQLRequestError";
|
|
482
|
+
this.operationName = details.operationName;
|
|
483
|
+
this.httpStatus = details.httpStatus;
|
|
484
|
+
this.graphqlErrors = details.graphqlErrors;
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
async function refreshAccessToken(creds, endpoint) {
|
|
488
|
+
const res = await fetch(endpoint, {
|
|
489
|
+
method: "POST",
|
|
490
|
+
headers: { "Content-Type": "application/json", "X-API-Client": "sl-cli" },
|
|
491
|
+
body: JSON.stringify({
|
|
492
|
+
query: print(RefreshToken),
|
|
493
|
+
variables: { input: { refreshToken: creds.refreshToken } }
|
|
494
|
+
})
|
|
495
|
+
});
|
|
496
|
+
const json = await res.json();
|
|
497
|
+
const token = json.data?.refreshToken;
|
|
498
|
+
if (!token || token.error) return null;
|
|
499
|
+
const newCreds = {
|
|
500
|
+
accessToken: token.accessToken,
|
|
501
|
+
refreshToken: token.refreshToken,
|
|
502
|
+
idToken: token.idToken,
|
|
503
|
+
expiresAt: Math.floor(Date.now() / 1e3) + token.expiresIn
|
|
504
|
+
};
|
|
505
|
+
saveCredentials(newCreds);
|
|
506
|
+
return newCreds;
|
|
507
|
+
}
|
|
508
|
+
function reportUnreachable(err, { endpoint, operationName, throwOnError }) {
|
|
509
|
+
const code = err.cause?.code;
|
|
510
|
+
const reason = code === "ECONNREFUSED" ? `nothing is listening on ${endpoint}` : err.message;
|
|
511
|
+
captureException2(err, { operationName, endpoint });
|
|
512
|
+
if (throwOnError) {
|
|
513
|
+
throw new GraphQLRequestError(`${operationName} could not reach the endpoint: ${reason}`, { operationName });
|
|
514
|
+
}
|
|
515
|
+
error(`Could not reach ${endpoint}: ${reason}`);
|
|
516
|
+
hint("Is the local stack running? Check the configured endpoint with `sl config show`.");
|
|
517
|
+
process.exit(3);
|
|
518
|
+
}
|
|
519
|
+
async function resolveAccessToken(options, attempt) {
|
|
520
|
+
const machine = options.asPerson ? null : clientCredentials();
|
|
521
|
+
if (machine) {
|
|
522
|
+
try {
|
|
523
|
+
return { token: await fetchClientCredentialsToken(machine), kind: "application" };
|
|
524
|
+
} catch (err) {
|
|
525
|
+
const message = err.message;
|
|
526
|
+
if (attempt.throwOnError) throw new GraphQLRequestError(message, { operationName: attempt.operationName });
|
|
527
|
+
error(message);
|
|
528
|
+
hint("Check SORTLIST_CLIENT_ID, SORTLIST_CLIENT_SECRET and the token endpoint.");
|
|
529
|
+
hint("The credential may also have been revoked, or its application deleted.");
|
|
530
|
+
process.exit(2);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
const session = options.asPerson ? null : loadApplicationSession();
|
|
534
|
+
if (session) return { token: session.accessToken, kind: "application" };
|
|
535
|
+
if (!options.asPerson && applicationSessionExpired()) {
|
|
536
|
+
error("The application session has expired.");
|
|
537
|
+
hint("Run `sl use application <id>` again, or `sl use me` to act as yourself.");
|
|
538
|
+
process.exit(2);
|
|
539
|
+
}
|
|
540
|
+
let creds = ensureAuthenticated();
|
|
541
|
+
if (isExpired(creds)) {
|
|
542
|
+
const refreshed = await refreshAccessToken(creds, attempt.endpoint);
|
|
543
|
+
if (!refreshed) {
|
|
544
|
+
if (attempt.throwOnError) {
|
|
545
|
+
throw new GraphQLRequestError("Session expired and could not be refreshed.", {
|
|
546
|
+
operationName: attempt.operationName
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
error("Your session has expired and could not be refreshed.");
|
|
550
|
+
hint("Run `sl login` to re-authenticate.");
|
|
551
|
+
process.exit(2);
|
|
552
|
+
}
|
|
553
|
+
creds = refreshed;
|
|
554
|
+
}
|
|
555
|
+
return { token: creds.accessToken, kind: "user" };
|
|
556
|
+
}
|
|
557
|
+
function reportHttpFailure(res, body, attempt) {
|
|
558
|
+
const { operationName, endpoint, throwOnError, verbose } = attempt;
|
|
559
|
+
captureException2(new Error(`${operationName} failed: HTTP ${res.status}`), {
|
|
560
|
+
operationName,
|
|
561
|
+
httpStatus: res.status,
|
|
562
|
+
endpoint
|
|
563
|
+
});
|
|
564
|
+
if (throwOnError) {
|
|
565
|
+
throw new GraphQLRequestError(`${operationName} failed: HTTP ${res.status} ${res.statusText}`, {
|
|
566
|
+
operationName,
|
|
567
|
+
httpStatus: res.status
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
error(`${operationName} failed: HTTP ${res.status} ${res.statusText}`);
|
|
571
|
+
hint("Check your network connection and endpoint: sl config show");
|
|
572
|
+
if (verbose) info(`[debug] Response body: ${body}`);
|
|
573
|
+
process.exit(3);
|
|
574
|
+
}
|
|
575
|
+
function hasFieldError(errors) {
|
|
576
|
+
return errors.some((e) => e.message.includes("Failed to implement") || e.message.includes("undefined method"));
|
|
577
|
+
}
|
|
578
|
+
function codeOf(errors) {
|
|
579
|
+
for (const { extensions } of errors) {
|
|
580
|
+
const code = extensions?.code;
|
|
581
|
+
if (typeof code === "string") return code;
|
|
582
|
+
}
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
function humanise(code) {
|
|
586
|
+
const words = code.toLowerCase().replaceAll("_", " ");
|
|
587
|
+
return words.charAt(0).toUpperCase() + words.slice(1) + ".";
|
|
588
|
+
}
|
|
589
|
+
function detailLines(errors) {
|
|
590
|
+
const lines = [];
|
|
591
|
+
for (const { extensions } of errors) {
|
|
592
|
+
const details = extensions?.details;
|
|
593
|
+
if (typeof details !== "object" || details === null) continue;
|
|
594
|
+
for (const [attribute, codes] of Object.entries(details)) {
|
|
595
|
+
lines.push(`${attribute}: ${Array.isArray(codes) ? codes.join(", ") : String(codes)}`);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return lines;
|
|
599
|
+
}
|
|
600
|
+
var ROUTER_PLACEHOLDER = "Unexpected error";
|
|
601
|
+
function describe(errors) {
|
|
602
|
+
const code = codeOf(errors);
|
|
603
|
+
const details = detailLines(errors);
|
|
604
|
+
const messages = messageLines(errors);
|
|
605
|
+
if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
|
|
606
|
+
const explanation = details.length > 0 ? details : messages;
|
|
607
|
+
return explanation.length > 0 ? `${humanise(code)} ${explanation.join("; ")}` : humanise(code);
|
|
608
|
+
}
|
|
609
|
+
return messages.length > 0 ? messages.join("; ") : "the server gave no reason";
|
|
610
|
+
}
|
|
611
|
+
function messageLines(errors) {
|
|
612
|
+
return errors.map((e) => e.message).filter((message) => message !== ROUTER_PLACEHOLDER);
|
|
613
|
+
}
|
|
614
|
+
function serviceOf(errors) {
|
|
615
|
+
for (const { extensions } of errors) {
|
|
616
|
+
const service = extensions?.service;
|
|
617
|
+
if (typeof service === "string") return service;
|
|
618
|
+
}
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
function hasResolvedField(data) {
|
|
622
|
+
if (data === null || data === void 0) return false;
|
|
623
|
+
return Object.values(data).some((value) => value !== null);
|
|
624
|
+
}
|
|
625
|
+
function reportGraphqlErrors(errors, options, attempt) {
|
|
626
|
+
const { operationName, throwOnError, verbose } = attempt;
|
|
627
|
+
captureException2(new Error(`${operationName} GraphQL errors`), {
|
|
628
|
+
operationName,
|
|
629
|
+
errors: errors.map((e) => e.message)
|
|
630
|
+
});
|
|
631
|
+
if (throwOnError) {
|
|
632
|
+
throw new GraphQLRequestError(`${operationName} failed: ${describe(errors)}`, {
|
|
633
|
+
operationName,
|
|
634
|
+
graphqlErrors: errors
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
if (codeOf(errors) === "NOT_AUTHENTICATED") {
|
|
638
|
+
const service = serviceOf(errors);
|
|
639
|
+
const where = service === null ? "" : ` for ${service}`;
|
|
640
|
+
error(`Not authenticated${where}.`);
|
|
641
|
+
if (actingAsApplication()) {
|
|
642
|
+
hint("You are acting as an application. Hermes refuses the tokens it mints on its own");
|
|
643
|
+
hint("management API by design, so a leaked secret cannot mint more \u2014 `sl use me` switches back.");
|
|
644
|
+
} else {
|
|
645
|
+
hint("Run `sl login` to authenticate, or `sl whoami` to see what the CLI is acting as.");
|
|
646
|
+
}
|
|
647
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${gqlError.message}`);
|
|
648
|
+
process.exit(4);
|
|
649
|
+
}
|
|
650
|
+
const code = codeOf(errors);
|
|
651
|
+
if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
|
|
652
|
+
error(humanise(code));
|
|
653
|
+
const details = detailLines(errors);
|
|
654
|
+
const lines = details.length > 0 ? details : messageLines(errors);
|
|
655
|
+
for (const line of lines) info(` ${line}`);
|
|
656
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
|
|
657
|
+
process.exit(1);
|
|
658
|
+
}
|
|
659
|
+
error(`${operationName} failed:`);
|
|
660
|
+
for (const gqlError of errors) {
|
|
661
|
+
info(` ${gqlError.message}`);
|
|
662
|
+
if (verbose && gqlError.extensions) info(`[debug] Extensions: ${JSON.stringify(gqlError.extensions)}`);
|
|
663
|
+
}
|
|
664
|
+
if (hasFieldError(errors)) {
|
|
665
|
+
hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
|
|
666
|
+
hint(`Example: sl ${operationName.toLowerCase()} --fields id,title,status`);
|
|
667
|
+
}
|
|
668
|
+
process.exit(1);
|
|
669
|
+
}
|
|
670
|
+
function logRequest(query, variables, attempt) {
|
|
671
|
+
info(`[debug] ${attempt.operationName} \u2192 ${attempt.endpoint}`);
|
|
672
|
+
info(`[debug] Query:
|
|
673
|
+
${query}`);
|
|
674
|
+
if (variables) info(`[debug] Variables: ${JSON.stringify(variables, null, 2)}`);
|
|
675
|
+
}
|
|
676
|
+
async function executeQuery(query, variables, options = {}) {
|
|
677
|
+
const authenticated = options.authenticated ?? true;
|
|
678
|
+
const attempt = {
|
|
679
|
+
endpoint: getEndpoint(options.endpoint),
|
|
680
|
+
operationName: extractOperationName(query),
|
|
681
|
+
throwOnError: options.throwOnError ?? false,
|
|
682
|
+
verbose: process.env.SL_DEBUG === "1"
|
|
683
|
+
};
|
|
684
|
+
addBreadcrumb2({
|
|
685
|
+
category: "graphql",
|
|
686
|
+
message: attempt.operationName,
|
|
687
|
+
data: { endpoint: attempt.endpoint, authenticated },
|
|
688
|
+
level: "info"
|
|
689
|
+
});
|
|
690
|
+
if (attempt.verbose) logRequest(query, variables, attempt);
|
|
691
|
+
const headers = {
|
|
692
|
+
"Content-Type": "application/json",
|
|
693
|
+
"X-API-Client": "sl-cli"
|
|
694
|
+
};
|
|
695
|
+
if (authenticated) {
|
|
696
|
+
const { token, kind } = await resolveAccessToken(options, attempt);
|
|
697
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
698
|
+
if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
|
|
699
|
+
}
|
|
700
|
+
let res;
|
|
701
|
+
try {
|
|
702
|
+
res = await fetch(attempt.endpoint, {
|
|
703
|
+
method: "POST",
|
|
704
|
+
headers,
|
|
705
|
+
body: JSON.stringify({ query, variables })
|
|
706
|
+
});
|
|
707
|
+
} catch (err) {
|
|
708
|
+
reportUnreachable(err, {
|
|
709
|
+
endpoint: attempt.endpoint,
|
|
710
|
+
operationName: attempt.operationName,
|
|
711
|
+
throwOnError: attempt.throwOnError
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
if (!res.ok) reportHttpFailure(res, await res.text(), attempt);
|
|
715
|
+
const json = await res.json();
|
|
716
|
+
if (json.errors?.length) {
|
|
717
|
+
const refused = !hasResolvedField(json.data);
|
|
718
|
+
if (refused) reportGraphqlErrors(json.errors, options, attempt);
|
|
719
|
+
for (const gqlError of json.errors) warn(gqlError.message);
|
|
720
|
+
if (hasFieldError(json.errors)) {
|
|
721
|
+
hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
|
|
722
|
+
}
|
|
723
|
+
return json.data;
|
|
724
|
+
}
|
|
725
|
+
if (!json.data) {
|
|
726
|
+
if (attempt.throwOnError) {
|
|
727
|
+
throw new GraphQLRequestError(`${attempt.operationName}: no data returned from API.`, {
|
|
728
|
+
operationName: attempt.operationName
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
error(`${attempt.operationName}: no data returned from API.`);
|
|
732
|
+
hint("This usually means the server returned an empty response.");
|
|
733
|
+
hint("Verify your endpoint: sl config show");
|
|
734
|
+
process.exit(1);
|
|
735
|
+
}
|
|
736
|
+
return json.data;
|
|
737
|
+
}
|
|
738
|
+
async function graphql(document, variables, options = {}) {
|
|
739
|
+
return executeQuery(print(document), variables, options);
|
|
740
|
+
}
|
|
741
|
+
async function graphqlRaw(query, variables, options = {}) {
|
|
742
|
+
return executeQuery(query, variables, options);
|
|
743
|
+
}
|
|
744
|
+
async function graphqlUnauthenticated(document, variables, endpoint) {
|
|
745
|
+
return graphql(document, variables, { endpoint, authenticated: false });
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// src/graphql/query-builder.ts
|
|
749
|
+
import {
|
|
750
|
+
isEnumType,
|
|
751
|
+
isInterfaceType,
|
|
752
|
+
isListType,
|
|
753
|
+
isNonNullType,
|
|
754
|
+
isObjectType,
|
|
755
|
+
isScalarType,
|
|
756
|
+
isUnionType
|
|
757
|
+
} from "graphql";
|
|
758
|
+
function unwrap(type) {
|
|
759
|
+
if (isNonNullType(type)) return unwrap(type.ofType);
|
|
760
|
+
if (isListType(type)) return unwrap(type.ofType);
|
|
761
|
+
return type;
|
|
762
|
+
}
|
|
763
|
+
function isLeaf(type) {
|
|
764
|
+
return isScalarType(type) || isEnumType(type);
|
|
765
|
+
}
|
|
766
|
+
function ucfirst(s) {
|
|
767
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
768
|
+
}
|
|
769
|
+
var PAYLOAD_TYPE_PATTERN = /(?:Response|Payload|MutationPayload)$/;
|
|
770
|
+
function buildSelections(type, schema, depth, exclude, prefix, visited) {
|
|
771
|
+
if (!isObjectType(type)) return [];
|
|
772
|
+
if (visited.has(type.name)) return [];
|
|
773
|
+
visited.add(type.name);
|
|
774
|
+
const fields = type.getFields();
|
|
775
|
+
const lines = [];
|
|
776
|
+
const isPayload = PAYLOAD_TYPE_PATTERN.test(type.name);
|
|
777
|
+
if (type.name.endsWith("Connection") && fields.nodes && fields.pageInfo) {
|
|
778
|
+
const nodesType = unwrap(fields.nodes.type);
|
|
779
|
+
const nodeSelections = buildSelections(nodesType, schema, depth, exclude, `${prefix}nodes.`, new Set(visited));
|
|
780
|
+
if (nodeSelections.length === 0) return [];
|
|
781
|
+
lines.push(`nodes {`);
|
|
782
|
+
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
783
|
+
lines.push(`}`);
|
|
784
|
+
lines.push(`pageInfo {`);
|
|
785
|
+
lines.push(` hasNextPage`);
|
|
786
|
+
lines.push(` endCursor`);
|
|
787
|
+
lines.push(`}`);
|
|
788
|
+
if (fields.totalCount) lines.push(`totalCount`);
|
|
789
|
+
return lines;
|
|
790
|
+
}
|
|
791
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
792
|
+
if (name.startsWith("__")) continue;
|
|
793
|
+
if (name === "id" && isPayload) continue;
|
|
794
|
+
const fullPath = `${prefix}${name}`;
|
|
795
|
+
if (exclude.has(fullPath) || exclude.has(name)) continue;
|
|
796
|
+
const hasRequiredArgs = field.args.some((a) => isNonNullType(a.type) && a.defaultValue === void 0);
|
|
797
|
+
if (hasRequiredArgs) continue;
|
|
798
|
+
const namedType = unwrap(field.type);
|
|
799
|
+
if (isLeaf(namedType)) {
|
|
800
|
+
lines.push(name);
|
|
801
|
+
} else if (isObjectType(namedType) && depth > 0) {
|
|
802
|
+
const subSelections = buildSelections(namedType, schema, depth - 1, exclude, `${fullPath}.`, new Set(visited));
|
|
803
|
+
if (subSelections.length > 0) {
|
|
804
|
+
lines.push(`${name} {`);
|
|
805
|
+
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
806
|
+
lines.push(`}`);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
return lines;
|
|
811
|
+
}
|
|
812
|
+
function buildQuery(schema, kind, fieldName, variables, options = {}) {
|
|
813
|
+
const rootType = kind === "query" ? schema.getQueryType() : schema.getMutationType();
|
|
814
|
+
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
815
|
+
const field = rootType.getFields()[fieldName];
|
|
816
|
+
if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
|
|
817
|
+
const depth = options.depth ?? 0;
|
|
818
|
+
const exclude = new Set(options.exclude ?? []);
|
|
819
|
+
const returnType = unwrap(field.type);
|
|
820
|
+
const allArgs = field.args;
|
|
821
|
+
const varDefsInner = allArgs.map((a) => `$${a.name}: ${a.type.toString()}`).join(", ");
|
|
822
|
+
const fieldArgsInner = allArgs.map((a) => `${a.name}: $${a.name}`).join(", ");
|
|
823
|
+
const varDefs = allArgs.length > 0 ? `(${varDefsInner})` : "";
|
|
824
|
+
const fieldArgs = allArgs.length > 0 ? `(${fieldArgsInner})` : "";
|
|
825
|
+
let selectionBody;
|
|
826
|
+
if (isLeaf(returnType) || isInterfaceType(returnType) || isUnionType(returnType)) {
|
|
827
|
+
selectionBody = ` ${fieldName}${fieldArgs}`;
|
|
828
|
+
} else {
|
|
829
|
+
let selections;
|
|
830
|
+
if (options.fields && options.fields.length > 0) {
|
|
831
|
+
selections = buildFieldsFromList(returnType, schema, options.fields);
|
|
832
|
+
} else {
|
|
833
|
+
selections = buildSelections(returnType, schema, depth, exclude, "", /* @__PURE__ */ new Set());
|
|
834
|
+
}
|
|
835
|
+
if (selections.length === 0) {
|
|
836
|
+
selectionBody = ` ${fieldName}${fieldArgs} {
|
|
837
|
+
__typename
|
|
838
|
+
}`;
|
|
839
|
+
} else {
|
|
840
|
+
const indent = " ";
|
|
841
|
+
const body = selections.map((s) => `${indent}${s}`).join("\n");
|
|
842
|
+
selectionBody = ` ${fieldName}${fieldArgs} {
|
|
843
|
+
${body}
|
|
844
|
+
}`;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
const opName = ucfirst(fieldName);
|
|
848
|
+
const query = `${kind} ${opName}${varDefs} {
|
|
849
|
+
${selectionBody}
|
|
850
|
+
}`;
|
|
851
|
+
return { query, variables, fieldName };
|
|
852
|
+
}
|
|
853
|
+
function buildFieldsFromList(type, schema, fieldPaths) {
|
|
854
|
+
if (!isObjectType(type)) return [];
|
|
855
|
+
const fields = type.getFields();
|
|
856
|
+
if (type.name.endsWith("Connection") && fields.nodes && fields.pageInfo) {
|
|
857
|
+
const nodesType = unwrap(fields.nodes.type);
|
|
858
|
+
const nodeSelections = buildFieldsFromList(nodesType, schema, fieldPaths);
|
|
859
|
+
if (nodeSelections.length === 0) return [];
|
|
860
|
+
const lines2 = [];
|
|
861
|
+
lines2.push("nodes {");
|
|
862
|
+
for (const sel of nodeSelections) lines2.push(` ${sel}`);
|
|
863
|
+
lines2.push("}");
|
|
864
|
+
lines2.push("pageInfo {");
|
|
865
|
+
lines2.push(" hasNextPage");
|
|
866
|
+
lines2.push(" endCursor");
|
|
867
|
+
lines2.push("}");
|
|
868
|
+
if (fields.totalCount) lines2.push("totalCount");
|
|
869
|
+
return lines2;
|
|
870
|
+
}
|
|
871
|
+
const lines = [];
|
|
872
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
873
|
+
for (const fp of fieldPaths) {
|
|
874
|
+
const [top, ...rest] = fp.split(".");
|
|
875
|
+
if (!grouped.has(top)) grouped.set(top, []);
|
|
876
|
+
if (rest.length > 0) grouped.get(top).push(rest.join("."));
|
|
877
|
+
}
|
|
878
|
+
for (const [name, subPaths] of grouped) {
|
|
879
|
+
const field = fields[name];
|
|
880
|
+
if (!field) continue;
|
|
881
|
+
const namedType = unwrap(field.type);
|
|
882
|
+
if (isLeaf(namedType)) {
|
|
883
|
+
lines.push(name);
|
|
884
|
+
} else if (isObjectType(namedType) && subPaths.length > 0) {
|
|
885
|
+
const subSelections = buildFieldsFromList(namedType, schema, subPaths);
|
|
886
|
+
if (subSelections.length > 0) {
|
|
887
|
+
lines.push(`${name} {`);
|
|
888
|
+
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
889
|
+
lines.push(`}`);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
return lines;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// src/lib/company.ts
|
|
897
|
+
function resolveCompanyId(opts) {
|
|
898
|
+
return opts.companyId || opts.ctx?.companyId;
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// src/lib/render.ts
|
|
902
|
+
var INDENT = " ";
|
|
903
|
+
function isRecord(value) {
|
|
904
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
905
|
+
}
|
|
906
|
+
function asConnection(value) {
|
|
907
|
+
if (!isRecord(value) || !Array.isArray(value.nodes)) return null;
|
|
908
|
+
return value;
|
|
909
|
+
}
|
|
910
|
+
function formatScalar(value) {
|
|
911
|
+
if (value === null || value === void 0) return "\u2014";
|
|
912
|
+
if (typeof value === "boolean") return value ? "yes" : "no";
|
|
913
|
+
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
|
|
914
|
+
return value.slice(0, 16).replace("T", " ");
|
|
915
|
+
}
|
|
916
|
+
return String(value);
|
|
917
|
+
}
|
|
918
|
+
function summarise(key, value) {
|
|
919
|
+
const connection = asConnection(value);
|
|
920
|
+
if (connection) {
|
|
921
|
+
const count = connection.totalCount ?? connection.nodes.length;
|
|
922
|
+
return `${count} ${count === 1 ? "entry" : "entries"}`;
|
|
923
|
+
}
|
|
924
|
+
if (Array.isArray(value)) return value.length === 0 ? "none" : `${value.length} items`;
|
|
925
|
+
if (isRecord(value)) {
|
|
926
|
+
const label = value.name ?? value.sub ?? value.id;
|
|
927
|
+
return label === void 0 ? "{\u2026}" : formatScalar(label);
|
|
928
|
+
}
|
|
929
|
+
return null;
|
|
930
|
+
}
|
|
931
|
+
function formatRecord(record, indent) {
|
|
932
|
+
const entries = Object.entries(record).filter(([key]) => key !== "__typename");
|
|
933
|
+
const width = Math.max(0, ...entries.map(([key]) => key.length));
|
|
934
|
+
return entries.map(([key, value]) => {
|
|
935
|
+
const rendered = summarise(key, value) ?? formatScalar(value);
|
|
936
|
+
return `${indent}${key.padEnd(width)} ${rendered}`;
|
|
937
|
+
}).join("\n");
|
|
938
|
+
}
|
|
939
|
+
function formatFooter(connection) {
|
|
940
|
+
const shown = connection.nodes.length;
|
|
941
|
+
const total = connection.totalCount;
|
|
942
|
+
const more = connection.pageInfo?.hasNextPage === true;
|
|
943
|
+
if (total === void 0 && !more) return null;
|
|
944
|
+
if (total !== void 0 && total === shown && !more) return null;
|
|
945
|
+
const counted = total === void 0 ? `${shown}` : `${shown} of ${total}`;
|
|
946
|
+
return more ? `${counted} \u2014 more available, pass --after ${connection.pageInfo?.endCursor}` : counted;
|
|
947
|
+
}
|
|
948
|
+
function formatResult(result) {
|
|
949
|
+
const connection = asConnection(result);
|
|
950
|
+
if (connection) {
|
|
951
|
+
if (connection.nodes.length === 0) return "No results.";
|
|
952
|
+
const blocks = connection.nodes.map(
|
|
953
|
+
(node) => isRecord(node) ? formatRecord(node, INDENT) : `${INDENT}${formatScalar(node)}`
|
|
954
|
+
);
|
|
955
|
+
const footer = formatFooter(connection);
|
|
956
|
+
return footer ? `${blocks.join("\n\n")}
|
|
957
|
+
|
|
958
|
+
${footer}` : blocks.join("\n\n");
|
|
959
|
+
}
|
|
960
|
+
if (Array.isArray(result)) {
|
|
961
|
+
if (result.length === 0) return "No results.";
|
|
962
|
+
return result.map((item) => isRecord(item) ? formatRecord(item, INDENT) : formatScalar(item)).join("\n\n");
|
|
963
|
+
}
|
|
964
|
+
if (isRecord(result)) return formatRecord(result, "");
|
|
965
|
+
return result === null || result === void 0 ? null : formatScalar(result);
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// src/commands/dynamic.ts
|
|
969
|
+
var CONTEXT_FIELDS = {
|
|
970
|
+
companyId: "companyId"
|
|
971
|
+
};
|
|
972
|
+
var SKIP_FIELDS = /* @__PURE__ */ new Set(["node", "nodes", "id", "_entities", "_service"]);
|
|
973
|
+
function unwrap2(type) {
|
|
974
|
+
if (isNonNullType2(type)) return unwrap2(type.ofType);
|
|
975
|
+
if (isListType2(type)) return unwrap2(type.ofType);
|
|
976
|
+
return type;
|
|
977
|
+
}
|
|
978
|
+
function kebab(s) {
|
|
979
|
+
return s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
|
980
|
+
}
|
|
981
|
+
function getInputFields(field) {
|
|
982
|
+
if (field.args.length !== 1) return null;
|
|
983
|
+
const arg = field.args[0];
|
|
984
|
+
if (arg.name !== "input") return null;
|
|
985
|
+
const argType = unwrap2(arg.type);
|
|
986
|
+
if (!argType || !isInputObjectType(argType)) return null;
|
|
987
|
+
const fields = argType.getFields();
|
|
988
|
+
return Object.entries(fields).map(([name, f]) => ({
|
|
989
|
+
name,
|
|
990
|
+
type: f.type,
|
|
991
|
+
required: isNonNullType2(f.type),
|
|
992
|
+
description: f.description
|
|
993
|
+
}));
|
|
994
|
+
}
|
|
995
|
+
function renderType(type) {
|
|
996
|
+
if (isNonNullType2(type)) return `${renderType(type.ofType)}!`;
|
|
997
|
+
if (isListType2(type)) return `[${renderType(type.ofType)}]`;
|
|
998
|
+
return type.name;
|
|
999
|
+
}
|
|
1000
|
+
function isStructuredInput(type) {
|
|
1001
|
+
if (isNonNullType2(type)) return isStructuredInput(type.ofType);
|
|
1002
|
+
if (isListType2(type)) return true;
|
|
1003
|
+
return isInputObjectType(type);
|
|
1004
|
+
}
|
|
1005
|
+
function coerceValue(raw, type, flagName) {
|
|
1006
|
+
if (isStructuredInput(type)) {
|
|
1007
|
+
try {
|
|
1008
|
+
return JSON.parse(raw);
|
|
1009
|
+
} catch (parseError) {
|
|
1010
|
+
throw new Error(
|
|
1011
|
+
`--${flagName} expects JSON for type ${renderType(type)}, but the value could not be parsed: ${parseError.message}`
|
|
1012
|
+
);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const typeName = unwrap2(type).name;
|
|
1016
|
+
if (typeName === "Int") {
|
|
1017
|
+
const parsed = parseInt(raw, 10);
|
|
1018
|
+
if (Number.isNaN(parsed)) throw new Error(`--${flagName} expects an integer, got "${raw}".`);
|
|
1019
|
+
return parsed;
|
|
1020
|
+
}
|
|
1021
|
+
if (typeName === "Float") {
|
|
1022
|
+
const parsed = parseFloat(raw);
|
|
1023
|
+
if (Number.isNaN(parsed)) throw new Error(`--${flagName} expects a number, got "${raw}".`);
|
|
1024
|
+
return parsed;
|
|
1025
|
+
}
|
|
1026
|
+
if (typeName === "Boolean") {
|
|
1027
|
+
if (raw !== "true" && raw !== "false") {
|
|
1028
|
+
throw new Error(`--${flagName} expects "true" or "false", got "${raw}".`);
|
|
1029
|
+
}
|
|
1030
|
+
return raw === "true";
|
|
1031
|
+
}
|
|
1032
|
+
return raw;
|
|
1033
|
+
}
|
|
1034
|
+
function describeStructuredType(named) {
|
|
1035
|
+
if (isInputObjectType(named)) {
|
|
1036
|
+
const fields = Object.values(named.getFields());
|
|
1037
|
+
const parts = fields.map((f) => `${f.name}: ${renderType(f.type)}`);
|
|
1038
|
+
return `{ ${parts.join(", ")} }`;
|
|
1039
|
+
}
|
|
1040
|
+
if (isEnumType2(named)) {
|
|
1041
|
+
const values = named.getValues().map((v) => v.name);
|
|
1042
|
+
return `one of: ${values.join(" | ")}`;
|
|
1043
|
+
}
|
|
1044
|
+
return null;
|
|
1045
|
+
}
|
|
1046
|
+
function isInspectable(named) {
|
|
1047
|
+
return isInputObjectType(named) || isEnumType2(named) || isObjectType2(named);
|
|
1048
|
+
}
|
|
1049
|
+
function oneLineDescription(text) {
|
|
1050
|
+
return (text ?? "").replace(/\s+/g, " ").trim();
|
|
1051
|
+
}
|
|
1052
|
+
function formatTypeInspection(schema, typeName) {
|
|
1053
|
+
const named = schema.getType(typeName);
|
|
1054
|
+
if (!named) return null;
|
|
1055
|
+
const lines = [];
|
|
1056
|
+
const suffix = oneLineDescription(named.description);
|
|
1057
|
+
const header = (kind) => {
|
|
1058
|
+
const label = kind ? `${kind} ${named.name}` : named.name;
|
|
1059
|
+
return suffix ? `${label} \u2014 ${suffix}` : label;
|
|
1060
|
+
};
|
|
1061
|
+
const pushFields = (entries) => {
|
|
1062
|
+
const width = Math.max(...entries.map((entry) => `${entry.name}: ${entry.typeSig}`.length), 0);
|
|
1063
|
+
for (const entry of entries) {
|
|
1064
|
+
const signature = `${entry.name}: ${entry.typeSig}`;
|
|
1065
|
+
const note = oneLineDescription(entry.description);
|
|
1066
|
+
lines.push(note ? ` ${signature.padEnd(width)} ${note}` : ` ${signature}`);
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
if (isInputObjectType(named) || isObjectType2(named)) {
|
|
1070
|
+
lines.push(header(isInputObjectType(named) ? "input" : "type"));
|
|
1071
|
+
pushFields(
|
|
1072
|
+
Object.values(named.getFields()).map((f) => ({
|
|
1073
|
+
name: f.name,
|
|
1074
|
+
typeSig: renderType(f.type),
|
|
1075
|
+
description: f.description
|
|
1076
|
+
}))
|
|
1077
|
+
);
|
|
1078
|
+
} else if (isEnumType2(named)) {
|
|
1079
|
+
lines.push(header("enum"));
|
|
1080
|
+
for (const value of named.getValues()) {
|
|
1081
|
+
const note = oneLineDescription(value.description);
|
|
1082
|
+
lines.push(note ? ` ${value.name.padEnd(20)} ${note}` : ` ${value.name}`);
|
|
1083
|
+
}
|
|
1084
|
+
} else if (isScalarType2(named)) {
|
|
1085
|
+
lines.push(header("scalar"));
|
|
1086
|
+
lines.push(" (scalar \u2014 pass a plain value)");
|
|
1087
|
+
} else {
|
|
1088
|
+
lines.push(header(""));
|
|
1089
|
+
}
|
|
1090
|
+
const nested = /* @__PURE__ */ new Set();
|
|
1091
|
+
if (isInputObjectType(named) || isObjectType2(named)) {
|
|
1092
|
+
for (const field of Object.values(named.getFields())) {
|
|
1093
|
+
const fieldType = unwrap2(field.type);
|
|
1094
|
+
if (isInspectable(fieldType) && fieldType.name !== named.name) nested.add(fieldType.name);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
if (nested.size > 0) {
|
|
1098
|
+
lines.push("");
|
|
1099
|
+
lines.push(
|
|
1100
|
+
`Inspect nested types: ${[...nested].sort().map((n) => `sl schema inspect ${n}`).join(", ")}`
|
|
1101
|
+
);
|
|
1102
|
+
}
|
|
1103
|
+
return lines.join("\n");
|
|
1104
|
+
}
|
|
1105
|
+
function describeArg(arg) {
|
|
1106
|
+
const parts = [];
|
|
1107
|
+
if (arg.description) parts.push(arg.description.replace(/\s+/g, " ").trim());
|
|
1108
|
+
const typeSig = renderType(arg.type);
|
|
1109
|
+
parts.push(isStructuredInput(arg.type) ? `${typeSig} (JSON)` : typeSig);
|
|
1110
|
+
const named = unwrap2(arg.type);
|
|
1111
|
+
const shape = describeStructuredType(named);
|
|
1112
|
+
if (shape) parts.push(shape);
|
|
1113
|
+
if (isInputObjectType(named) || isEnumType2(named)) {
|
|
1114
|
+
parts.push(`details: sl schema inspect ${named.name}`);
|
|
1115
|
+
}
|
|
1116
|
+
return parts.join(" \u2014 ");
|
|
1117
|
+
}
|
|
1118
|
+
function buildCommand(schema, fieldName, kind, description, service) {
|
|
1119
|
+
const rootType = kind === "query" ? schema.getQueryType() : schema.getMutationType();
|
|
1120
|
+
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
1121
|
+
const field = rootType.getFields()[fieldName];
|
|
1122
|
+
if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
|
|
1123
|
+
const inputFields = getInputFields(field);
|
|
1124
|
+
const useInputWrapper = inputFields != null;
|
|
1125
|
+
const cliArgs = useInputWrapper ? inputFields : field.args.map((a) => ({
|
|
1126
|
+
name: a.name,
|
|
1127
|
+
type: a.type,
|
|
1128
|
+
required: isNonNullType2(a.type),
|
|
1129
|
+
description: a.description
|
|
1130
|
+
}));
|
|
1131
|
+
const cmd = new Command2(kebab(fieldName)).description(description);
|
|
1132
|
+
const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
|
|
1133
|
+
for (const a of cliArgs) {
|
|
1134
|
+
const placeholder = isStructuredInput(a.type) ? "json" : kebab(a.name);
|
|
1135
|
+
const flag = `--${kebab(a.name)} <${placeholder}>`;
|
|
1136
|
+
const isContext = a.name in CONTEXT_FIELDS;
|
|
1137
|
+
if (isContext) {
|
|
1138
|
+
cmd.option(flag, `${describeArg(a)} (from context if omitted)`);
|
|
1139
|
+
} else if (a.required) {
|
|
1140
|
+
cmd.requiredOption(flag, describeArg(a));
|
|
1141
|
+
} else {
|
|
1142
|
+
cmd.option(flag, describeArg(a));
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
cmd.option("--depth <depth>", "Selection depth (default: 0)", parseInt).option("--fields <fields>", "Comma-separated fields to include").option("--exclude <fields>", "Comma-separated fields to exclude");
|
|
1146
|
+
cmd.action(async function() {
|
|
1147
|
+
const opts = this.optsWithGlobals();
|
|
1148
|
+
const needsContext = cliArgs.some((a) => a.name in CONTEXT_FIELDS);
|
|
1149
|
+
const ctx = needsContext ? getUserContext() : void 0;
|
|
1150
|
+
const resolvedCompanyId = resolveCompanyId({
|
|
1151
|
+
companyId: typeof opts.companyId === "string" ? opts.companyId : void 0,
|
|
1152
|
+
ctx
|
|
1153
|
+
});
|
|
1154
|
+
if (requiresCompanyId && !resolvedCompanyId) {
|
|
1155
|
+
error("No company selected.");
|
|
1156
|
+
hint("Pass --company-id <id> or set one with `sl config set companyId <id>`.");
|
|
1157
|
+
process.exit(2);
|
|
1158
|
+
}
|
|
1159
|
+
if (resolvedCompanyId) opts.companyId = resolvedCompanyId;
|
|
1160
|
+
const collectArgs = () => {
|
|
1161
|
+
const out = {};
|
|
1162
|
+
for (const a of cliArgs) {
|
|
1163
|
+
const raw = opts[a.name];
|
|
1164
|
+
const ctxProp = CONTEXT_FIELDS[a.name];
|
|
1165
|
+
if (raw != null) {
|
|
1166
|
+
try {
|
|
1167
|
+
out[a.name] = coerceValue(raw, a.type, kebab(a.name));
|
|
1168
|
+
} catch (coerceError) {
|
|
1169
|
+
error(coerceError.message);
|
|
1170
|
+
hint("Run the command with --help to see the expected shape of each argument.");
|
|
1171
|
+
process.exit(2);
|
|
1172
|
+
}
|
|
1173
|
+
} else if (ctxProp && ctx) {
|
|
1174
|
+
out[a.name] = ctx[ctxProp];
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
return out;
|
|
1178
|
+
};
|
|
1179
|
+
const variables = useInputWrapper ? { input: collectArgs() } : collectArgs();
|
|
1180
|
+
const { query, fieldName: fName } = buildQuery(schema, kind, fieldName, variables, {
|
|
1181
|
+
depth: opts.depth,
|
|
1182
|
+
fields: opts.fields?.split(","),
|
|
1183
|
+
exclude: opts.exclude?.split(",")
|
|
1184
|
+
});
|
|
1185
|
+
const data = await graphqlRaw(query, variables, { endpoint: opts.endpoint, subgraph: service });
|
|
1186
|
+
const result = data[fName];
|
|
1187
|
+
if (result == null) {
|
|
1188
|
+
if (actingAsApplication()) {
|
|
1189
|
+
info(`${fieldName} answers for people, and you are acting as an application.`);
|
|
1190
|
+
hint("`sl whoami` reports what the token identifies; `sl use me` switches back.");
|
|
1191
|
+
} else {
|
|
1192
|
+
warn("No results returned.");
|
|
1193
|
+
hint("The query succeeded but the server returned null.");
|
|
1194
|
+
hint("Try different arguments or check that the resource exists.");
|
|
1195
|
+
}
|
|
1196
|
+
} else if (isJsonMode(opts)) {
|
|
1197
|
+
printJson(result);
|
|
1198
|
+
} else {
|
|
1199
|
+
const rendered = formatResult(result);
|
|
1200
|
+
if (rendered !== null) info(rendered);
|
|
1201
|
+
}
|
|
1202
|
+
});
|
|
1203
|
+
return cmd;
|
|
1204
|
+
}
|
|
1205
|
+
function deriveServiceMap(schema, fieldServices) {
|
|
1206
|
+
const map = /* @__PURE__ */ new Map();
|
|
1207
|
+
function ensure(service) {
|
|
1208
|
+
if (!map.has(service)) map.set(service, { queries: [], mutations: [] });
|
|
1209
|
+
return map.get(service);
|
|
1210
|
+
}
|
|
1211
|
+
const rootTypes = [
|
|
1212
|
+
{ kind: "queries", type: schema.getQueryType() },
|
|
1213
|
+
{ kind: "mutations", type: schema.getMutationType() }
|
|
1214
|
+
];
|
|
1215
|
+
for (const { kind, type } of rootTypes) {
|
|
1216
|
+
if (!type) continue;
|
|
1217
|
+
const services = fieldServices.get(type.name);
|
|
1218
|
+
if (!services) continue;
|
|
1219
|
+
for (const [fieldName, field] of Object.entries(type.getFields())) {
|
|
1220
|
+
if (SKIP_FIELDS.has(fieldName) || fieldName.startsWith("__")) continue;
|
|
1221
|
+
const returnType = unwrap2(field.type);
|
|
1222
|
+
if (isInterfaceType2(returnType) || isUnionType2(returnType)) continue;
|
|
1223
|
+
const service = services.get(fieldName);
|
|
1224
|
+
if (!service) continue;
|
|
1225
|
+
ensure(service)[kind].push({ fieldName, description: field.description ?? "" });
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
for (const entry of map.values()) {
|
|
1229
|
+
entry.queries.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
|
|
1230
|
+
entry.mutations.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
|
|
1231
|
+
}
|
|
1232
|
+
return map;
|
|
1233
|
+
}
|
|
1234
|
+
function buildOperationCommands(schema, fieldServices) {
|
|
1235
|
+
const serviceMap = deriveServiceMap(schema, fieldServices);
|
|
1236
|
+
const operations = [];
|
|
1237
|
+
const nameCounts = /* @__PURE__ */ new Map();
|
|
1238
|
+
for (const entry of serviceMap.values()) {
|
|
1239
|
+
for (const op of [...entry.queries, ...entry.mutations]) {
|
|
1240
|
+
nameCounts.set(op.fieldName, (nameCounts.get(op.fieldName) ?? 0) + 1);
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
for (const [service, entry] of serviceMap) {
|
|
1244
|
+
const kinds = [
|
|
1245
|
+
{ kind: "query", ops: entry.queries },
|
|
1246
|
+
{ kind: "mutation", ops: entry.mutations }
|
|
1247
|
+
];
|
|
1248
|
+
for (const { kind, ops } of kinds) {
|
|
1249
|
+
for (const op of ops) {
|
|
1250
|
+
try {
|
|
1251
|
+
const command = buildCommand(schema, op.fieldName, kind, op.description, service);
|
|
1252
|
+
if ((nameCounts.get(op.fieldName) ?? 0) > 1) {
|
|
1253
|
+
command.name(`${kebab(op.fieldName)}-${kind}`);
|
|
1254
|
+
}
|
|
1255
|
+
operations.push({ command, fieldName: op.fieldName, kind, service });
|
|
1256
|
+
} catch {
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
return operations.sort((a, b) => a.command.name().localeCompare(b.command.name()));
|
|
1262
|
+
}
|
|
1263
|
+
function formatOperationList(operations, search) {
|
|
1264
|
+
const needle = search?.toLowerCase();
|
|
1265
|
+
const matching = needle ? operations.filter((op) => op.command.name().includes(needle) || op.service.toLowerCase().includes(needle)) : operations;
|
|
1266
|
+
if (matching.length === 0) {
|
|
1267
|
+
return search ? `No operation matching "${search}".` : "No operations available. The endpoint is not a composed supergraph, so no subgraph mapping is exposed.";
|
|
1268
|
+
}
|
|
1269
|
+
const lines = [];
|
|
1270
|
+
for (const kind of ["query", "mutation"]) {
|
|
1271
|
+
const group = matching.filter((op) => op.kind === kind);
|
|
1272
|
+
if (group.length === 0) continue;
|
|
1273
|
+
const width = Math.max(...group.map((op) => op.command.name().length));
|
|
1274
|
+
lines.push(`${kind === "query" ? "Queries" : "Mutations"}:`);
|
|
1275
|
+
for (const op of group) {
|
|
1276
|
+
lines.push(` ${op.command.name().padEnd(width)} ${op.service}`);
|
|
1277
|
+
}
|
|
1278
|
+
lines.push("");
|
|
1279
|
+
}
|
|
1280
|
+
return lines.join("\n");
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
// src/commands/login.ts
|
|
1284
|
+
import { Command as Command3 } from "commander";
|
|
1285
|
+
|
|
1286
|
+
// src/graphql/operations/common.ts
|
|
1287
|
+
var Me = gql(`
|
|
1288
|
+
query Me {
|
|
1289
|
+
me {
|
|
1290
|
+
id
|
|
1291
|
+
email
|
|
1292
|
+
firstName
|
|
1293
|
+
lastName
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
`);
|
|
1297
|
+
|
|
1298
|
+
// src/lib/browser.ts
|
|
1299
|
+
import { execFile } from "child_process";
|
|
1300
|
+
function openBrowser(url) {
|
|
1301
|
+
if (process.platform === "win32") {
|
|
1302
|
+
execFile("cmd", ["/c", "start", "", url], () => {
|
|
1303
|
+
});
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
const cmd = process.platform === "darwin" ? "open" : "xdg-open";
|
|
1307
|
+
execFile(cmd, [url], () => {
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// src/commands/login.ts
|
|
1312
|
+
var API_SCOPES = [
|
|
1313
|
+
"atlas/*:*",
|
|
1314
|
+
"atlas/*:read",
|
|
1315
|
+
"core/*:*",
|
|
1316
|
+
"core/*:read",
|
|
1317
|
+
"signals/*:*",
|
|
1318
|
+
"signals/*:read",
|
|
1319
|
+
"billing/*:*",
|
|
1320
|
+
"billing/*:read",
|
|
1321
|
+
"billing/offer:*"
|
|
1322
|
+
];
|
|
1323
|
+
var DEFAULT_SCOPE = `openid profile email offline_access ${API_SCOPES.join(" ")}`;
|
|
1324
|
+
function sleep(ms) {
|
|
1325
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1326
|
+
}
|
|
1327
|
+
async function setupUserContext(endpoint) {
|
|
1328
|
+
const userData = await graphql(Me, void 0, { endpoint });
|
|
1329
|
+
const user = userData.me;
|
|
1330
|
+
if (!user) return;
|
|
1331
|
+
info("");
|
|
1332
|
+
info(` User: ${user.firstName} ${user.lastName} <${user.email}>`);
|
|
1333
|
+
hint("Run `sl whoami` to verify.");
|
|
1334
|
+
}
|
|
1335
|
+
var loginCommand = new Command3("login").summary("Log in to your Sortlist account").description(
|
|
1336
|
+
"Log in to your Sortlist account\n\nOpens a browser to complete authentication, then saves your\ncredentials locally. If you belong to multiple companies, you'll\nbe prompted to pick one.\n\nExamples:\n sl login Log in with default settings\n sl login --no-browser Print the login URL instead of opening it"
|
|
1337
|
+
).option("--scope <scope>", "OAuth scope", DEFAULT_SCOPE).option("--no-browser", "Print the login URL instead of opening a browser").action(async function() {
|
|
1338
|
+
const opts = this.optsWithGlobals();
|
|
1339
|
+
info("Starting device authorization...");
|
|
1340
|
+
const authData = await graphqlUnauthenticated(DeviceAuthorize, { input: { scope: opts.scope } }, opts.endpoint);
|
|
1341
|
+
const device = authData.deviceAuthorize;
|
|
1342
|
+
if (!device) {
|
|
1343
|
+
error("Device authorization failed \u2014 the server returned an empty response.");
|
|
1344
|
+
hint("Check your network connection and try again.");
|
|
1345
|
+
hint("If the problem persists, verify the endpoint: sl config show");
|
|
1346
|
+
process.exit(2);
|
|
1347
|
+
}
|
|
1348
|
+
const url = device.verificationUriComplete ?? device.verificationUri;
|
|
1349
|
+
info("");
|
|
1350
|
+
info(` Open this URL in your browser:`);
|
|
1351
|
+
info(` ${url}`);
|
|
1352
|
+
info("");
|
|
1353
|
+
info(` Enter code: ${device.userCode}`);
|
|
1354
|
+
info("");
|
|
1355
|
+
if (opts.browser) {
|
|
1356
|
+
openBrowser(url);
|
|
1357
|
+
info(" (Browser opened automatically)");
|
|
1358
|
+
info("");
|
|
1359
|
+
}
|
|
1360
|
+
info("Waiting for you to complete login in the browser...");
|
|
1361
|
+
let interval = device.interval * 1e3;
|
|
1362
|
+
const deadline = Date.now() + device.expiresIn * 1e3;
|
|
1363
|
+
while (Date.now() < deadline) {
|
|
1364
|
+
await sleep(interval);
|
|
1365
|
+
const tokenData = await graphqlUnauthenticated(
|
|
1366
|
+
DeviceToken,
|
|
1367
|
+
{ input: { deviceCode: device.deviceCode } },
|
|
1368
|
+
opts.endpoint
|
|
1369
|
+
);
|
|
1370
|
+
const token = tokenData.deviceToken;
|
|
1371
|
+
if (!token) {
|
|
1372
|
+
error("Token exchange failed \u2014 the server returned an empty response.");
|
|
1373
|
+
hint("Try running `sl login` again.");
|
|
1374
|
+
process.exit(2);
|
|
1375
|
+
}
|
|
1376
|
+
if (token.error === "authorization_pending") {
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
if (token.error === "slow_down") {
|
|
1380
|
+
interval += 5e3;
|
|
1381
|
+
continue;
|
|
1382
|
+
}
|
|
1383
|
+
if (token.error === "expired_token") {
|
|
1384
|
+
error("The login code expired before you completed authentication.");
|
|
1385
|
+
hint("Run `sl login` to generate a new code.");
|
|
1386
|
+
process.exit(2);
|
|
1387
|
+
}
|
|
1388
|
+
if (token.error === "access_denied") {
|
|
1389
|
+
error("Access was denied during authentication.");
|
|
1390
|
+
hint("Make sure you approved the request in the browser.");
|
|
1391
|
+
hint("If you denied it by mistake, run `sl login` to try again.");
|
|
1392
|
+
process.exit(2);
|
|
1393
|
+
}
|
|
1394
|
+
if (token.error) {
|
|
1395
|
+
error(`Authentication failed (${token.error}).`);
|
|
1396
|
+
hint("Run `sl login` to try again.");
|
|
1397
|
+
process.exit(2);
|
|
1398
|
+
}
|
|
1399
|
+
if (token.accessToken && token.refreshToken && token.idToken && token.expiresIn) {
|
|
1400
|
+
saveCredentials({
|
|
1401
|
+
accessToken: token.accessToken,
|
|
1402
|
+
refreshToken: token.refreshToken,
|
|
1403
|
+
idToken: token.idToken,
|
|
1404
|
+
expiresAt: Math.floor(Date.now() / 1e3) + token.expiresIn
|
|
1405
|
+
});
|
|
1406
|
+
success("Logged in successfully.");
|
|
1407
|
+
await setupUserContext(opts.endpoint);
|
|
1408
|
+
return;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
error("Authentication timed out \u2014 no response from the browser.");
|
|
1412
|
+
hint("Run `sl login` to start a new session.");
|
|
1413
|
+
process.exit(2);
|
|
1414
|
+
});
|
|
1415
|
+
|
|
1416
|
+
// src/commands/logout.ts
|
|
1417
|
+
import { Command as Command4 } from "commander";
|
|
1418
|
+
var logoutCommand = new Command4("logout").summary("Log out and remove stored credentials").description(
|
|
1419
|
+
"Log out and remove stored credentials\n\nDeletes the saved tokens from ~/.sortlist/credentials.json and\nopens the Auth0 logout URL in your browser so the next `sl login`\ndoesn't silently reuse the previous account.\n\nExamples:\n sl logout Clear credentials and log out of Auth0\n sl logout --no-browser Only clear local credentials"
|
|
1420
|
+
).option("--no-browser", "Skip opening the Auth0 logout URL in a browser").action(async function() {
|
|
1421
|
+
const opts = this.optsWithGlobals();
|
|
1422
|
+
clearCredentials();
|
|
1423
|
+
clearIdentity();
|
|
1424
|
+
const hadSession = clearApplicationSession();
|
|
1425
|
+
success("Logged out \u2014 credentials removed.");
|
|
1426
|
+
if (hadSession) info("The application session was cleared too.");
|
|
1427
|
+
if (!opts.browser) {
|
|
1428
|
+
hint("Run `sl login` to authenticate again.");
|
|
1429
|
+
return;
|
|
1430
|
+
}
|
|
1431
|
+
try {
|
|
1432
|
+
const data = await graphqlUnauthenticated(LogoutUrl, {}, opts.endpoint);
|
|
1433
|
+
if (data.logoutUrl) {
|
|
1434
|
+
openBrowser(data.logoutUrl);
|
|
1435
|
+
info("Opened Auth0 logout in your browser.");
|
|
1436
|
+
}
|
|
1437
|
+
} catch {
|
|
1438
|
+
warn("Could not fetch the Auth0 logout URL \u2014 skipped browser logout.");
|
|
1439
|
+
}
|
|
1440
|
+
hint("Run `sl login` to authenticate again.");
|
|
1441
|
+
});
|
|
1442
|
+
|
|
1443
|
+
// src/commands/token.ts
|
|
1444
|
+
import { Command as Command5 } from "commander";
|
|
1445
|
+
var tokenCommand = new Command5("token").summary("Print the current access token to stdout").description(
|
|
1446
|
+
`Print the current access token to stdout
|
|
1447
|
+
|
|
1448
|
+
Prints the application credential's token when SORTLIST_CLIENT_ID and
|
|
1449
|
+
SORTLIST_CLIENT_SECRET are set, and yours otherwise \u2014 matching what every
|
|
1450
|
+
other command authenticates as.
|
|
1451
|
+
|
|
1452
|
+
Examples:
|
|
1453
|
+
sl token Print the token
|
|
1454
|
+
curl -H "Authorization: Bearer $(sl token)" ...`
|
|
1455
|
+
).action(async () => {
|
|
1456
|
+
const machine = clientCredentials();
|
|
1457
|
+
if (machine) {
|
|
1458
|
+
try {
|
|
1459
|
+
process.stdout.write(await fetchClientCredentialsToken(machine));
|
|
1460
|
+
} catch (err) {
|
|
1461
|
+
error(err.message);
|
|
1462
|
+
hint("Check SORTLIST_CLIENT_ID, SORTLIST_CLIENT_SECRET and the token endpoint.");
|
|
1463
|
+
process.exit(2);
|
|
1464
|
+
}
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const creds = ensureAuthenticated();
|
|
1468
|
+
if (isExpired(creds)) {
|
|
1469
|
+
error("Your access token has expired.");
|
|
1470
|
+
hint("Run `sl login` to re-authenticate.");
|
|
1471
|
+
process.exit(2);
|
|
1472
|
+
}
|
|
1473
|
+
process.stdout.write(creds.accessToken);
|
|
1474
|
+
});
|
|
1475
|
+
|
|
1476
|
+
// src/commands/use.ts
|
|
1477
|
+
import { Command as Command6 } from "commander";
|
|
1478
|
+
var CREATE = `
|
|
1479
|
+
mutation UseApplication($applicationId: ID!, $name: String!) {
|
|
1480
|
+
createApplicationCredential(input: { applicationId: $applicationId, name: $name, session: true }) {
|
|
1481
|
+
clientId
|
|
1482
|
+
clientSecret
|
|
1483
|
+
credential { id }
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
`;
|
|
1487
|
+
var REVOKE = `
|
|
1488
|
+
mutation ReleaseSessionCredential($credentialId: ID!) {
|
|
1489
|
+
revokeApplicationCredential(input: { credentialId: $credentialId }) { revokedAt }
|
|
1490
|
+
}
|
|
1491
|
+
`;
|
|
1492
|
+
var useCommand = new Command6("use").summary("Act as an application, or go back to acting as yourself").description(
|
|
1493
|
+
"Act as an application, or go back to acting as yourself\n\nExamples:\n sl use application <id> Act as that application for one token lifetime\n sl use me Go back to acting as yourself"
|
|
1494
|
+
);
|
|
1495
|
+
useCommand.command("application <id>").description("Act as an application for one token lifetime").action(async function(id) {
|
|
1496
|
+
const opts = this.optsWithGlobals();
|
|
1497
|
+
const asPerson = { endpoint: opts.endpoint, throwOnError: true, asPerson: true };
|
|
1498
|
+
let credential = null;
|
|
1499
|
+
try {
|
|
1500
|
+
const issued = await graphqlRaw(CREATE, { applicationId: id, name: sessionName() }, asPerson);
|
|
1501
|
+
credential = issued.createApplicationCredential;
|
|
1502
|
+
} catch (err) {
|
|
1503
|
+
error(`Could not create a session credential: ${err.message}`);
|
|
1504
|
+
hint("`sl applications` lists the applications you can manage.");
|
|
1505
|
+
process.exit(1);
|
|
1506
|
+
}
|
|
1507
|
+
if (!credential) {
|
|
1508
|
+
error("The server did not return a session credential.");
|
|
1509
|
+
hint("`sl applications` lists the applications you can manage.");
|
|
1510
|
+
process.exit(1);
|
|
1511
|
+
}
|
|
1512
|
+
let accessToken = null;
|
|
1513
|
+
try {
|
|
1514
|
+
accessToken = await fetchClientCredentialsToken({
|
|
1515
|
+
clientId: credential.clientId,
|
|
1516
|
+
clientSecret: credential.clientSecret
|
|
1517
|
+
});
|
|
1518
|
+
} catch (err) {
|
|
1519
|
+
error(`Could not exchange the credential for a token: ${err.message}`);
|
|
1520
|
+
hint("`sl config use-local` / `use-staging` / `use-production` set the token endpoint.");
|
|
1521
|
+
} finally {
|
|
1522
|
+
await graphqlRaw(REVOKE, { credentialId: credential.credential.id }, asPerson);
|
|
1523
|
+
}
|
|
1524
|
+
if (!accessToken) process.exit(2);
|
|
1525
|
+
const identity = applicationIdentity(accessToken);
|
|
1526
|
+
if (!identity) {
|
|
1527
|
+
error("The token endpoint returned something this CLI could not read.");
|
|
1528
|
+
process.exit(1);
|
|
1529
|
+
}
|
|
1530
|
+
saveApplicationSession({
|
|
1531
|
+
accessToken,
|
|
1532
|
+
applicationId: identity.applicationId,
|
|
1533
|
+
expiresAt: identity.expiresAt.getTime()
|
|
1534
|
+
});
|
|
1535
|
+
success(`Now acting as application ${identity.applicationId}`);
|
|
1536
|
+
info(` until ${identity.expiresAt.toISOString()}`);
|
|
1537
|
+
hint("The credential behind this token is already revoked, so nothing reusable is stored.");
|
|
1538
|
+
hint("Managing companies, applications and credentials is now out of reach: Hermes refuses");
|
|
1539
|
+
hint("its own tokens on its management API. Run `sl use me` to act as yourself again.");
|
|
1540
|
+
});
|
|
1541
|
+
useCommand.command("me").description("Go back to acting as yourself").action(() => {
|
|
1542
|
+
if (clearApplicationSession()) {
|
|
1543
|
+
success("Now acting as yourself again.");
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
info("Already acting as yourself.");
|
|
1547
|
+
});
|
|
1548
|
+
function sessionName() {
|
|
1549
|
+
return `cli-session-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replace(/[:T]/g, "")}`;
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
// src/commands/whoami.ts
|
|
1553
|
+
import { Command as Command7 } from "commander";
|
|
1554
|
+
var whoamiCommand = new Command7("whoami").summary("Show what the CLI is currently acting as").description(
|
|
1555
|
+
"Show what the CLI is currently acting as\n\nReports a person or an application, matching what every command\nauthenticates as. Use --json for machine-readable output.\n\nExamples:\n sl whoami Show the current identity\n sl whoami --json Output the full object as JSON"
|
|
1556
|
+
).action(async function() {
|
|
1557
|
+
const opts = this.optsWithGlobals();
|
|
1558
|
+
const session = loadApplicationSession();
|
|
1559
|
+
if (session) {
|
|
1560
|
+
const identity = applicationIdentity(session.accessToken);
|
|
1561
|
+
if (isJsonMode(opts)) {
|
|
1562
|
+
printJson({ kind: "application", via: "session", ...identity });
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
info("Acting as an application.\n");
|
|
1566
|
+
info(
|
|
1567
|
+
formatResult({
|
|
1568
|
+
application: session.applicationId,
|
|
1569
|
+
"acts for company": identity?.companyId,
|
|
1570
|
+
subject: identity?.sub,
|
|
1571
|
+
"token expires": new Date(session.expiresAt).toISOString(),
|
|
1572
|
+
source: "sl use application \u2014 its credential is already revoked"
|
|
1573
|
+
}) ?? ""
|
|
1574
|
+
);
|
|
1575
|
+
hint("Run `sl use me` to act as yourself again.");
|
|
1576
|
+
return;
|
|
1577
|
+
}
|
|
1578
|
+
const machine = clientCredentials();
|
|
1579
|
+
if (machine) {
|
|
1580
|
+
let identity;
|
|
1581
|
+
try {
|
|
1582
|
+
identity = applicationIdentity(await fetchClientCredentialsToken(machine));
|
|
1583
|
+
} catch (err) {
|
|
1584
|
+
error(err.message);
|
|
1585
|
+
hint("Check SORTLIST_CLIENT_ID, SORTLIST_CLIENT_SECRET and the token endpoint.");
|
|
1586
|
+
process.exit(2);
|
|
1587
|
+
}
|
|
1588
|
+
if (!identity) {
|
|
1589
|
+
error("The token endpoint returned something this CLI could not read.");
|
|
1590
|
+
process.exit(1);
|
|
1591
|
+
}
|
|
1592
|
+
if (isJsonMode(opts)) {
|
|
1593
|
+
printJson({ kind: "application", clientId: machine.clientId, ...identity });
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
info("Acting as an application.\n");
|
|
1597
|
+
info(
|
|
1598
|
+
formatResult({
|
|
1599
|
+
application: identity.applicationId,
|
|
1600
|
+
"acts for company": identity.companyId,
|
|
1601
|
+
subject: identity.sub,
|
|
1602
|
+
credential: `${identity.credentialId} (${machine.clientId})`,
|
|
1603
|
+
"token expires": identity.expiresAt.toISOString(),
|
|
1604
|
+
source: "SORTLIST_CLIENT_ID / SORTLIST_CLIENT_SECRET"
|
|
1605
|
+
}) ?? ""
|
|
1606
|
+
);
|
|
1607
|
+
hint("A credential carries no scopes, so scoped data stays out of reach.");
|
|
1608
|
+
hint("Unset both variables to act as yourself again.");
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
let data;
|
|
1612
|
+
try {
|
|
1613
|
+
data = await graphql(Me, void 0, {
|
|
1614
|
+
endpoint: opts.endpoint,
|
|
1615
|
+
throwOnError: true
|
|
1616
|
+
});
|
|
1617
|
+
} catch (err) {
|
|
1618
|
+
if (err instanceof GraphQLRequestError) {
|
|
1619
|
+
error("Could not verify your identity \u2014 the API returned an error:");
|
|
1620
|
+
const messages = err.graphqlErrors?.map((e) => e.message) ?? [err.message];
|
|
1621
|
+
for (const message of messages) info(` ${message}`);
|
|
1622
|
+
hint("This is a server-side or authorization error, not necessarily an expired session.");
|
|
1623
|
+
hint("Retry in a moment; if it persists, re-run `sl login` or report it.");
|
|
1624
|
+
process.exit(1);
|
|
1625
|
+
}
|
|
1626
|
+
throw err;
|
|
1627
|
+
}
|
|
1628
|
+
const user = data.me;
|
|
1629
|
+
if (!user) {
|
|
1630
|
+
error("The API did not return your user identity.");
|
|
1631
|
+
hint("This is usually a temporary backend issue rather than an expired session.");
|
|
1632
|
+
hint("Retry in a moment; if it persists, re-run `sl login` or report it.");
|
|
1633
|
+
process.exit(1);
|
|
1634
|
+
}
|
|
1635
|
+
if (isJsonMode(opts)) {
|
|
1636
|
+
printJson({ kind: "person", ...user });
|
|
1637
|
+
return;
|
|
1638
|
+
}
|
|
1639
|
+
info("Acting as yourself.\n");
|
|
1640
|
+
info(
|
|
1641
|
+
formatResult({
|
|
1642
|
+
name: [user.firstName, user.lastName].filter(Boolean).join(" ") || null,
|
|
1643
|
+
email: user.email,
|
|
1644
|
+
id: user.id
|
|
1645
|
+
}) ?? ""
|
|
1646
|
+
);
|
|
1647
|
+
});
|
|
1648
|
+
|
|
1649
|
+
// src/graphql/introspection.ts
|
|
1650
|
+
import { createHash } from "crypto";
|
|
1651
|
+
import fs6 from "fs";
|
|
1652
|
+
import os4 from "os";
|
|
1653
|
+
import path6 from "path";
|
|
1654
|
+
import { buildClientSchema, getIntrospectionQuery } from "graphql";
|
|
1655
|
+
var CACHE_DIR = path6.join(os4.homedir(), ".sortlist");
|
|
1656
|
+
var CACHE_PATH = path6.join(CACHE_DIR, "schema.json");
|
|
1657
|
+
var CACHE_TTL_MS = 60 * 60 * 1e3;
|
|
1658
|
+
var cached2 = null;
|
|
1659
|
+
function tokenFingerprint(token) {
|
|
1660
|
+
if (!token) return "anonymous";
|
|
1661
|
+
return createHash("sha256").update(token).digest("hex").slice(0, 16);
|
|
1662
|
+
}
|
|
1663
|
+
function readCache(endpoint, token) {
|
|
1664
|
+
try {
|
|
1665
|
+
const text = fs6.readFileSync(CACHE_PATH, "utf-8");
|
|
1666
|
+
const envelope = JSON.parse(text);
|
|
1667
|
+
if (envelope.endpoint !== endpoint) return null;
|
|
1668
|
+
if (envelope.tokenFingerprint !== tokenFingerprint(token)) return null;
|
|
1669
|
+
if (Date.now() - envelope.fetchedAt > CACHE_TTL_MS) return null;
|
|
1670
|
+
if (!envelope.raw) return null;
|
|
1671
|
+
return { introspection: envelope.introspection, raw: envelope.raw };
|
|
1672
|
+
} catch {
|
|
1673
|
+
return null;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
function writeCache(endpoint, token, introspection, raw) {
|
|
1677
|
+
try {
|
|
1678
|
+
if (!fs6.existsSync(CACHE_DIR)) {
|
|
1679
|
+
fs6.mkdirSync(CACHE_DIR, { recursive: true });
|
|
1680
|
+
}
|
|
1681
|
+
const envelope = {
|
|
1682
|
+
endpoint,
|
|
1683
|
+
fetchedAt: Date.now(),
|
|
1684
|
+
tokenFingerprint: tokenFingerprint(token),
|
|
1685
|
+
introspection,
|
|
1686
|
+
raw
|
|
1687
|
+
};
|
|
1688
|
+
fs6.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
|
|
1689
|
+
} catch {
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
async function fetchIntrospection(endpoint, token) {
|
|
1693
|
+
const headers = {
|
|
1694
|
+
"Content-Type": "application/json",
|
|
1695
|
+
"X-API-Client": "sl-cli"
|
|
1696
|
+
};
|
|
1697
|
+
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
1698
|
+
const res = await fetch(endpoint, {
|
|
1699
|
+
method: "POST",
|
|
1700
|
+
headers,
|
|
1701
|
+
body: JSON.stringify({ query: getIntrospectionQuery() })
|
|
1702
|
+
});
|
|
1703
|
+
if (!res.ok) {
|
|
1704
|
+
throw new Error(`Introspection failed: HTTP ${res.status} ${res.statusText}`);
|
|
1705
|
+
}
|
|
1706
|
+
const json = await res.json();
|
|
1707
|
+
if (json.errors?.length) {
|
|
1708
|
+
throw new Error(`Introspection errors: ${json.errors.map((e) => e.message).join(", ")}`);
|
|
1709
|
+
}
|
|
1710
|
+
if (!json.data) {
|
|
1711
|
+
throw new Error("Introspection returned no data");
|
|
1712
|
+
}
|
|
1713
|
+
return { introspection: json.data, raw: json.data };
|
|
1714
|
+
}
|
|
1715
|
+
function parseIntrospection(raw) {
|
|
1716
|
+
const fieldServices = /* @__PURE__ */ new Map();
|
|
1717
|
+
const services = /* @__PURE__ */ new Set();
|
|
1718
|
+
for (const type of raw.__schema.types ?? []) {
|
|
1719
|
+
if (!type.fields?.length) continue;
|
|
1720
|
+
let fieldMap = null;
|
|
1721
|
+
for (const field of type.fields) {
|
|
1722
|
+
const directive = field.appliedDirectives?.find((d) => d.name === "join__field");
|
|
1723
|
+
if (!directive) continue;
|
|
1724
|
+
const graphArg = directive.args.find((a) => a.name === "graph");
|
|
1725
|
+
if (!graphArg || typeof graphArg.value !== "string") continue;
|
|
1726
|
+
services.add(graphArg.value);
|
|
1727
|
+
if (!fieldMap) fieldMap = /* @__PURE__ */ new Map();
|
|
1728
|
+
fieldMap.set(field.name, graphArg.value);
|
|
1729
|
+
}
|
|
1730
|
+
if (fieldMap) fieldServices.set(type.name, fieldMap);
|
|
1731
|
+
}
|
|
1732
|
+
return { fieldServices, services };
|
|
1733
|
+
}
|
|
1734
|
+
function currentAccessToken() {
|
|
1735
|
+
return loadCredentials()?.accessToken ?? null;
|
|
1736
|
+
}
|
|
1737
|
+
async function getIntrospectedSchema(endpointOverride2) {
|
|
1738
|
+
if (cached2) return cached2;
|
|
1739
|
+
const endpoint = getEndpoint(endpointOverride2);
|
|
1740
|
+
const token = currentAccessToken();
|
|
1741
|
+
const fromCache = readCache(endpoint, token);
|
|
1742
|
+
if (fromCache) {
|
|
1743
|
+
const usable = build(fromCache.introspection, fromCache.raw);
|
|
1744
|
+
if (usable) {
|
|
1745
|
+
cached2 = usable;
|
|
1746
|
+
return cached2;
|
|
1747
|
+
}
|
|
1748
|
+
discardCache();
|
|
1749
|
+
}
|
|
1750
|
+
const { introspection, raw } = await fetchIntrospection(endpoint, token);
|
|
1751
|
+
const built = build(introspection, raw);
|
|
1752
|
+
if (!built) {
|
|
1753
|
+
throw new Error(
|
|
1754
|
+
"The endpoint returned an introspection result this CLI could not build a schema from. Nothing was cached; retry, and check that every subgraph is up."
|
|
1755
|
+
);
|
|
1756
|
+
}
|
|
1757
|
+
writeCache(endpoint, token, introspection, raw);
|
|
1758
|
+
cached2 = built;
|
|
1759
|
+
return cached2;
|
|
1760
|
+
}
|
|
1761
|
+
function build(introspection, raw) {
|
|
1762
|
+
try {
|
|
1763
|
+
const { fieldServices, services } = parseIntrospection(raw);
|
|
1764
|
+
return { schema: buildClientSchema(introspection), fieldServices, services };
|
|
1765
|
+
} catch {
|
|
1766
|
+
return null;
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
function discardCache() {
|
|
1770
|
+
try {
|
|
1771
|
+
fs6.unlinkSync(CACHE_PATH);
|
|
1772
|
+
} catch {
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
async function refreshSchema(endpointOverride2) {
|
|
1776
|
+
cached2 = null;
|
|
1777
|
+
discardCache();
|
|
1778
|
+
const endpoint = getEndpoint(endpointOverride2);
|
|
1779
|
+
const token = currentAccessToken();
|
|
1780
|
+
const { introspection, raw } = await fetchIntrospection(endpoint, token);
|
|
1781
|
+
const built = build(introspection, raw);
|
|
1782
|
+
if (!built) {
|
|
1783
|
+
throw new Error(
|
|
1784
|
+
"The endpoint returned an introspection result this CLI could not build a schema from. Nothing was cached; retry, and check that every subgraph is up."
|
|
1785
|
+
);
|
|
1786
|
+
}
|
|
1787
|
+
writeCache(endpoint, token, introspection, raw);
|
|
1788
|
+
cached2 = built;
|
|
1789
|
+
return cached2;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
// src/lib/version-check.ts
|
|
1793
|
+
import { execFileSync } from "child_process";
|
|
1794
|
+
var PACKAGE_NAME = "@sortlist/cli";
|
|
1795
|
+
function getCurrentVersion() {
|
|
1796
|
+
return pkg.version;
|
|
1797
|
+
}
|
|
1798
|
+
async function fetchLatestVersion() {
|
|
1799
|
+
try {
|
|
1800
|
+
const controller = new AbortController();
|
|
1801
|
+
const timeout = setTimeout(() => controller.abort(), 3e3);
|
|
1802
|
+
const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(PACKAGE_NAME)}/latest`, {
|
|
1803
|
+
signal: controller.signal
|
|
1804
|
+
});
|
|
1805
|
+
clearTimeout(timeout);
|
|
1806
|
+
if (!res.ok) return null;
|
|
1807
|
+
const data = await res.json();
|
|
1808
|
+
return data.version;
|
|
1809
|
+
} catch {
|
|
1810
|
+
return null;
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
function parseSemver(version) {
|
|
1814
|
+
const [major, minor, patch] = version.split(".").map(Number);
|
|
1815
|
+
return [major ?? 0, minor ?? 0, patch ?? 0];
|
|
1816
|
+
}
|
|
1817
|
+
function autoUpdate(current, latest) {
|
|
1818
|
+
info(`Updating ${PACKAGE_NAME}: ${current} \u2192 ${latest}...`);
|
|
1819
|
+
try {
|
|
1820
|
+
const prefix = execFileSync("npm", ["prefix", "-g"], { stdio: "pipe", encoding: "utf-8" }).trim();
|
|
1821
|
+
const lastSlash = PACKAGE_NAME.lastIndexOf("/");
|
|
1822
|
+
const scope = lastSlash === -1 ? "" : `${PACKAGE_NAME.slice(0, lastSlash)}/`;
|
|
1823
|
+
const name = lastSlash === -1 ? PACKAGE_NAME : PACKAGE_NAME.slice(lastSlash + 1);
|
|
1824
|
+
const staleDir = `${prefix}/lib/node_modules/${scope}.${name}-`;
|
|
1825
|
+
execFileSync("sh", ["-c", `rm -rf "${staleDir}"* 2>/dev/null || true`], { stdio: "pipe" });
|
|
1826
|
+
execFileSync("npm", ["install", "-g", "--prefer-online", `${PACKAGE_NAME}@${latest}`], {
|
|
1827
|
+
stdio: "pipe"
|
|
1828
|
+
});
|
|
1829
|
+
success(`Updated to ${latest}. Restart \`sl\` to use the new version.`);
|
|
1830
|
+
} catch (err) {
|
|
1831
|
+
const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr).trim() : "";
|
|
1832
|
+
const detail = stderr ? ` (${stderr.split("\n")[0]})` : "";
|
|
1833
|
+
warn(`Auto-update failed${detail}.`);
|
|
1834
|
+
hint(`Run \`npm i -g ${PACKAGE_NAME}\` to update manually.`);
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
async function checkForUpdates() {
|
|
1838
|
+
if (isLocalDev) return;
|
|
1839
|
+
const current = getCurrentVersion();
|
|
1840
|
+
const latest = await fetchLatestVersion();
|
|
1841
|
+
if (!latest || latest === current) return;
|
|
1842
|
+
const [curMajor] = parseSemver(current);
|
|
1843
|
+
const [latMajor] = parseSemver(latest);
|
|
1844
|
+
if (latMajor > curMajor) {
|
|
1845
|
+
error(`Breaking update: ${current} \u2192 ${latest}`);
|
|
1846
|
+
info("");
|
|
1847
|
+
info(" Your CLI is incompatible with the current API.");
|
|
1848
|
+
info(" Update before continuing:");
|
|
1849
|
+
info("");
|
|
1850
|
+
info(` npm i -g ${PACKAGE_NAME}`);
|
|
1851
|
+
info("");
|
|
1852
|
+
process.exit(1);
|
|
1853
|
+
}
|
|
1854
|
+
autoUpdate(current, latest);
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
// src/index.ts
|
|
1858
|
+
initSentry();
|
|
1859
|
+
var useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
1860
|
+
var ansi2 = {
|
|
1861
|
+
reset: "\x1B[0m",
|
|
1862
|
+
bold: "\x1B[1m",
|
|
1863
|
+
dim: "\x1B[2m",
|
|
1864
|
+
cyan: "\x1B[36m",
|
|
1865
|
+
yellow: "\x1B[33m",
|
|
1866
|
+
green: "\x1B[32m"
|
|
1867
|
+
};
|
|
1868
|
+
function colorizeHelp(text) {
|
|
1869
|
+
if (!useColor) return text;
|
|
1870
|
+
return text.replace(
|
|
1871
|
+
/^(Usage|Options|Commands|Arguments|Quick start|Services|Examples|Queries|Mutations):(.*)$/gm,
|
|
1872
|
+
`${ansi2.cyan}${ansi2.bold}$1:$2${ansi2.reset}`
|
|
1873
|
+
);
|
|
1874
|
+
}
|
|
1875
|
+
var colorOutput = {
|
|
1876
|
+
writeOut: (str) => process.stdout.write(colorizeHelp(str)),
|
|
1877
|
+
writeErr: (str) => process.stderr.write(colorizeHelp(str))
|
|
1878
|
+
};
|
|
1879
|
+
function applyColorToAllCommands(cmd) {
|
|
1880
|
+
cmd.configureOutput(colorOutput);
|
|
1881
|
+
for (const sub of cmd.commands) {
|
|
1882
|
+
applyColorToAllCommands(sub);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
var BASE_DESCRIPTION = "Sortlist CLI \u2014 query and manage the Sortlist platform from your terminal\n\nQuick start:\n sl login Authenticate with your Sortlist account\n sl whoami Check who you're logged in as";
|
|
1886
|
+
function buildRootDescription(operationCount) {
|
|
1887
|
+
const parts = [BASE_DESCRIPTION];
|
|
1888
|
+
if (operationCount > 0) {
|
|
1889
|
+
parts.push(
|
|
1890
|
+
`Every federation operation is a command (${operationCount} available).
|
|
1891
|
+
Operation names are unique across the supergraph, so they are not namespaced:
|
|
1892
|
+
sl operations List them all
|
|
1893
|
+
sl operations --search company
|
|
1894
|
+
sl <operation> --help Flags for one operation`
|
|
1895
|
+
);
|
|
1896
|
+
parts.push(
|
|
1897
|
+
"Examples:\n sl organizations --limit 5\n sl create-application --name continuous-integration\n sl config show"
|
|
1898
|
+
);
|
|
1899
|
+
}
|
|
1900
|
+
return parts.join("\n\n");
|
|
1901
|
+
}
|
|
1902
|
+
var program = new Command8().name("sl").configureOutput({
|
|
1903
|
+
writeOut: (str) => process.stdout.write(colorizeHelp(str)),
|
|
1904
|
+
writeErr: (str) => process.stderr.write(colorizeHelp(str))
|
|
1905
|
+
}).description(BASE_DESCRIPTION).version(pkg.version).option("--endpoint <url>", "Override the federation endpoint URL").option("--json", "Output as JSON (auto-enabled when stdout is not a TTY)").option("--no-color", "Disable colored output");
|
|
1906
|
+
program.addCommand(loginCommand);
|
|
1907
|
+
program.addCommand(logoutCommand);
|
|
1908
|
+
program.addCommand(whoamiCommand);
|
|
1909
|
+
program.addCommand(tokenCommand);
|
|
1910
|
+
program.addCommand(useCommand);
|
|
1911
|
+
program.addCommand(configCommand);
|
|
1912
|
+
var schemaCommand = new Command8("schema").description("Manage the cached GraphQL schema");
|
|
1913
|
+
schemaCommand.command("refresh").description("Force-refresh the cached schema from the federation endpoint").action(async function() {
|
|
1914
|
+
const opts = this.optsWithGlobals();
|
|
1915
|
+
try {
|
|
1916
|
+
await refreshSchema(opts.endpoint);
|
|
1917
|
+
info("Schema refreshed successfully.");
|
|
1918
|
+
} catch (err) {
|
|
1919
|
+
error(`Failed to refresh schema: ${err.message}`);
|
|
1920
|
+
hint("Check your network connection and endpoint: sl config show");
|
|
1921
|
+
process.exit(1);
|
|
1922
|
+
}
|
|
1923
|
+
});
|
|
1924
|
+
schemaCommand.command("inspect <type>").description("Show the fields/values of a schema type (e.g. an input filter or enum)").action(async function(typeName) {
|
|
1925
|
+
const opts = this.optsWithGlobals();
|
|
1926
|
+
try {
|
|
1927
|
+
const { schema } = await getIntrospectedSchema(opts.endpoint);
|
|
1928
|
+
const formatted = formatTypeInspection(schema, typeName);
|
|
1929
|
+
if (!formatted) {
|
|
1930
|
+
error(`No type named "${typeName}" in the schema.`);
|
|
1931
|
+
hint("Type names are case-sensitive, e.g. `sl schema inspect OrganizationFilterInput`.");
|
|
1932
|
+
hint("Find argument types in any command\u2019s --help output.");
|
|
1933
|
+
process.exit(1);
|
|
1934
|
+
}
|
|
1935
|
+
info(formatted);
|
|
1936
|
+
} catch (err) {
|
|
1937
|
+
error(`Could not read the schema: ${err.message}`);
|
|
1938
|
+
hint("Check your network connection and endpoint: sl config show");
|
|
1939
|
+
process.exit(1);
|
|
1940
|
+
}
|
|
1941
|
+
});
|
|
1942
|
+
program.addCommand(schemaCommand);
|
|
1943
|
+
var endpointIdx = process.argv.indexOf("--endpoint");
|
|
1944
|
+
var endpointOverride = endpointIdx !== -1 ? process.argv[endpointIdx + 1] : void 0;
|
|
1945
|
+
try {
|
|
1946
|
+
const { schema, fieldServices } = await getIntrospectedSchema(endpointOverride);
|
|
1947
|
+
const operations = buildOperationCommands(schema, fieldServices);
|
|
1948
|
+
for (const operation of operations) {
|
|
1949
|
+
program.addCommand(operation.command, { hidden: true });
|
|
1950
|
+
}
|
|
1951
|
+
const operationsCommand = new Command8("operations").summary("List every federation operation available as a command").option("--search <text>", "Filter by operation or subgraph name").action(function() {
|
|
1952
|
+
info(formatOperationList(operations, this.opts().search));
|
|
1953
|
+
});
|
|
1954
|
+
program.addCommand(operationsCommand);
|
|
1955
|
+
program.description(buildRootDescription(operations.length));
|
|
1956
|
+
} catch (err) {
|
|
1957
|
+
const message = err.message;
|
|
1958
|
+
const offline = ["login", "logout", "config", "token", "whoami", "schema"];
|
|
1959
|
+
if (!process.argv.some((a) => offline.includes(a))) {
|
|
1960
|
+
error(`Could not fetch schema: ${message}`);
|
|
1961
|
+
hint("Check your network connection and endpoint: sl config show");
|
|
1962
|
+
hint("You can still use: sl login, sl config, sl schema refresh");
|
|
1963
|
+
process.exit(1);
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
applyColorToAllCommands(program);
|
|
1967
|
+
await checkForUpdates();
|
|
1968
|
+
try {
|
|
1969
|
+
await program.parseAsync(process.argv);
|
|
1970
|
+
} catch (err) {
|
|
1971
|
+
captureException2(err);
|
|
1972
|
+
await flushSentry();
|
|
1973
|
+
throw err;
|
|
1974
|
+
}
|
|
1975
|
+
await flushSentry();
|
|
1976
|
+
//# sourceMappingURL=index.js.map
|