@sortlist/cli 0.37.0 → 0.39.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 +132 -17
- package/dist/index.js +1049 -383
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,13 +1,47 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { Command as
|
|
2
|
+
import { Command as Command8 } from "commander";
|
|
3
3
|
|
|
4
4
|
// src/commands/config.ts
|
|
5
5
|
import { Command } from "commander";
|
|
6
6
|
|
|
7
|
-
// src/lib/
|
|
7
|
+
// src/lib/application-session.ts
|
|
8
8
|
import fs from "fs";
|
|
9
9
|
import os from "os";
|
|
10
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";
|
|
11
45
|
|
|
12
46
|
// src/lib/output.ts
|
|
13
47
|
function colorEnabled() {
|
|
@@ -53,20 +87,20 @@ function hint(msg) {
|
|
|
53
87
|
}
|
|
54
88
|
|
|
55
89
|
// src/lib/auth.ts
|
|
56
|
-
var CREDENTIALS_PATH =
|
|
90
|
+
var CREDENTIALS_PATH = path2.join(os2.homedir(), ".sortlist", "credentials.json");
|
|
57
91
|
function ensureDir() {
|
|
58
|
-
const dir =
|
|
59
|
-
if (!
|
|
60
|
-
|
|
92
|
+
const dir = path2.dirname(CREDENTIALS_PATH);
|
|
93
|
+
if (!fs2.existsSync(dir)) {
|
|
94
|
+
fs2.mkdirSync(dir, { recursive: true });
|
|
61
95
|
}
|
|
62
96
|
}
|
|
63
97
|
function saveCredentials(creds) {
|
|
64
98
|
ensureDir();
|
|
65
|
-
|
|
99
|
+
fs2.writeFileSync(CREDENTIALS_PATH, JSON.stringify(creds, null, 2) + "\n", { mode: 384 });
|
|
66
100
|
}
|
|
67
101
|
function loadCredentials() {
|
|
68
102
|
try {
|
|
69
|
-
const raw =
|
|
103
|
+
const raw = fs2.readFileSync(CREDENTIALS_PATH, "utf-8");
|
|
70
104
|
return JSON.parse(raw);
|
|
71
105
|
} catch {
|
|
72
106
|
return null;
|
|
@@ -74,7 +108,7 @@ function loadCredentials() {
|
|
|
74
108
|
}
|
|
75
109
|
function clearCredentials() {
|
|
76
110
|
try {
|
|
77
|
-
|
|
111
|
+
fs2.unlinkSync(CREDENTIALS_PATH);
|
|
78
112
|
} catch {
|
|
79
113
|
}
|
|
80
114
|
}
|
|
@@ -92,22 +126,22 @@ function ensureAuthenticated() {
|
|
|
92
126
|
}
|
|
93
127
|
|
|
94
128
|
// src/lib/config.ts
|
|
95
|
-
import
|
|
96
|
-
import
|
|
97
|
-
import
|
|
98
|
-
var SORTLIST_DIR =
|
|
99
|
-
var CONFIG_PATH =
|
|
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");
|
|
100
134
|
var DEFAULT_CONFIG = {
|
|
101
135
|
endpoint: "https://federation.sortlist.com/graphql"
|
|
102
136
|
};
|
|
103
137
|
function ensureDir2() {
|
|
104
|
-
if (!
|
|
105
|
-
|
|
138
|
+
if (!fs3.existsSync(SORTLIST_DIR)) {
|
|
139
|
+
fs3.mkdirSync(SORTLIST_DIR, { recursive: true });
|
|
106
140
|
}
|
|
107
141
|
}
|
|
108
142
|
function loadConfig() {
|
|
109
143
|
try {
|
|
110
|
-
const raw =
|
|
144
|
+
const raw = fs3.readFileSync(CONFIG_PATH, "utf-8");
|
|
111
145
|
return { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
|
|
112
146
|
} catch {
|
|
113
147
|
return { ...DEFAULT_CONFIG };
|
|
@@ -117,18 +151,20 @@ function saveConfig(config) {
|
|
|
117
151
|
ensureDir2();
|
|
118
152
|
const current = loadConfig();
|
|
119
153
|
const merged = { ...current, ...config };
|
|
120
|
-
|
|
154
|
+
fs3.writeFileSync(CONFIG_PATH, JSON.stringify(merged, null, 2) + "\n");
|
|
121
155
|
}
|
|
122
156
|
function resetConfig() {
|
|
123
157
|
try {
|
|
124
|
-
|
|
158
|
+
fs3.unlinkSync(CONFIG_PATH);
|
|
125
159
|
} catch {
|
|
126
160
|
}
|
|
127
161
|
}
|
|
128
162
|
function clearIdentity() {
|
|
129
|
-
const { endpoint } = loadConfig();
|
|
163
|
+
const { endpoint, tokenEndpoint: tokenEndpoint2 } = loadConfig();
|
|
130
164
|
ensureDir2();
|
|
131
|
-
|
|
165
|
+
const kept = { endpoint };
|
|
166
|
+
if (tokenEndpoint2) kept.tokenEndpoint = tokenEndpoint2;
|
|
167
|
+
fs3.writeFileSync(CONFIG_PATH, JSON.stringify(kept, null, 2) + "\n");
|
|
132
168
|
}
|
|
133
169
|
function getEndpoint(override) {
|
|
134
170
|
if (override) return override;
|
|
@@ -137,48 +173,62 @@ function getEndpoint(override) {
|
|
|
137
173
|
}
|
|
138
174
|
function getUserContext() {
|
|
139
175
|
const config = loadConfig();
|
|
140
|
-
return {
|
|
141
|
-
oauthId: config.oauthId,
|
|
142
|
-
companyId: config.companyId
|
|
143
|
-
};
|
|
176
|
+
return { company: config.company };
|
|
144
177
|
}
|
|
145
178
|
|
|
146
179
|
// src/lib/env.ts
|
|
147
|
-
import
|
|
148
|
-
import
|
|
180
|
+
import fs5 from "fs";
|
|
181
|
+
import path5 from "path";
|
|
149
182
|
|
|
150
183
|
// src/lib/package-root.ts
|
|
151
|
-
import
|
|
152
|
-
import
|
|
184
|
+
import fs4 from "fs";
|
|
185
|
+
import path4 from "path";
|
|
153
186
|
import { fileURLToPath } from "url";
|
|
154
187
|
function findPackageRoot() {
|
|
155
|
-
let dir =
|
|
188
|
+
let dir = path4.dirname(fileURLToPath(import.meta.url));
|
|
156
189
|
while (true) {
|
|
157
|
-
const pkgPath =
|
|
158
|
-
if (
|
|
190
|
+
const pkgPath = path4.join(dir, "package.json");
|
|
191
|
+
if (fs4.existsSync(pkgPath)) {
|
|
159
192
|
try {
|
|
160
|
-
const parsed = JSON.parse(
|
|
193
|
+
const parsed = JSON.parse(fs4.readFileSync(pkgPath, "utf-8"));
|
|
161
194
|
if (parsed.name === "@sortlist/cli") return dir;
|
|
162
195
|
} catch {
|
|
163
196
|
}
|
|
164
197
|
}
|
|
165
|
-
const parent =
|
|
198
|
+
const parent = path4.dirname(dir);
|
|
166
199
|
if (parent === dir) throw new Error("Could not locate the @sortlist/cli package root");
|
|
167
200
|
dir = parent;
|
|
168
201
|
}
|
|
169
202
|
}
|
|
170
203
|
var packageRoot = findPackageRoot();
|
|
171
|
-
var pkg = JSON.parse(
|
|
204
|
+
var pkg = JSON.parse(fs4.readFileSync(path4.join(packageRoot, "package.json"), "utf-8"));
|
|
172
205
|
|
|
173
206
|
// src/lib/env.ts
|
|
174
|
-
var isLocalDev = !
|
|
207
|
+
var isLocalDev = !fs5.existsSync(path5.join(packageRoot, ".published"));
|
|
175
208
|
|
|
176
209
|
// src/commands/config.ts
|
|
177
|
-
var
|
|
178
|
-
|
|
179
|
-
|
|
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
|
+
];
|
|
180
230
|
var configCommand = new Command("config").summary("View or update CLI configuration").description(
|
|
181
|
-
"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"
|
|
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 sl config set company <slug|id> Act for that company on every command\n" + (isLocalDev ? " sl config set endpoint <url> Point to a custom endpoint\n" : "") + " sl config reset Clear all config and credentials"
|
|
182
232
|
);
|
|
183
233
|
configCommand.command("show").description("Show current configuration").action(function() {
|
|
184
234
|
const opts = this.optsWithGlobals();
|
|
@@ -186,18 +236,18 @@ configCommand.command("show").description("Show current configuration").action(f
|
|
|
186
236
|
if (isJsonMode(opts)) {
|
|
187
237
|
printJson(config);
|
|
188
238
|
} else {
|
|
189
|
-
info(`Endpoint:
|
|
190
|
-
if (config.
|
|
191
|
-
if (config.
|
|
239
|
+
info(`Endpoint: ${config.endpoint}`);
|
|
240
|
+
if (config.tokenEndpoint) info(`Token endpoint: ${config.tokenEndpoint}`);
|
|
241
|
+
if (config.company) info(`Company: ${config.company}`);
|
|
192
242
|
}
|
|
193
243
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if (!
|
|
244
|
+
var SETTABLE_KEYS = [...isLocalDev ? ["endpoint"] : [], "company", "tokenEndpoint"];
|
|
245
|
+
configCommand.command("set <key> <value>").description(`Set a config value (${SETTABLE_KEYS.join(", ")})`).action((key, value) => {
|
|
246
|
+
if (!SETTABLE_KEYS.includes(key)) {
|
|
197
247
|
error(`Unknown config key: "${key}".`);
|
|
198
248
|
info("");
|
|
199
249
|
info(" Allowed keys:");
|
|
200
|
-
for (const k of
|
|
250
|
+
for (const k of SETTABLE_KEYS) {
|
|
201
251
|
info(` ${k}`);
|
|
202
252
|
}
|
|
203
253
|
hint("Usage: sl config set <key> <value>");
|
|
@@ -207,25 +257,20 @@ configCommand.command("set <key> <value>").description(`Set a config value (${is
|
|
|
207
257
|
success(`Set ${key} = ${value}`);
|
|
208
258
|
});
|
|
209
259
|
if (isLocalDev) {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
hint("Run `sl login` to authenticate against staging.");
|
|
219
|
-
});
|
|
220
|
-
configCommand.command("use-local").description("Point CLI to local development (localhost:4020)").action(() => {
|
|
221
|
-
saveConfig({ endpoint: LOCAL_ENDPOINT });
|
|
222
|
-
success(`Endpoint set to ${LOCAL_ENDPOINT}`);
|
|
223
|
-
});
|
|
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
|
+
}
|
|
224
268
|
}
|
|
225
269
|
configCommand.command("reset").description("Reset all config and credentials").action(() => {
|
|
226
270
|
resetConfig();
|
|
227
271
|
clearCredentials();
|
|
228
|
-
|
|
272
|
+
clearApplicationSession();
|
|
273
|
+
success("Config, credentials and any application session cleared.");
|
|
229
274
|
hint("Run `sl login` to re-authenticate.");
|
|
230
275
|
});
|
|
231
276
|
|
|
@@ -245,6 +290,113 @@ import {
|
|
|
245
290
|
// src/graphql/client.ts
|
|
246
291
|
import { print } from "graphql";
|
|
247
292
|
|
|
293
|
+
// src/lib/token-claims.ts
|
|
294
|
+
function tokenClaims(accessToken) {
|
|
295
|
+
try {
|
|
296
|
+
const payload = accessToken.split(".")[1];
|
|
297
|
+
if (!payload) return null;
|
|
298
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
|
299
|
+
} catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function grantedScopes(accessToken) {
|
|
304
|
+
const scope = tokenClaims(accessToken)?.scope;
|
|
305
|
+
return typeof scope === "string" ? scope.split(" ").filter(Boolean) : [];
|
|
306
|
+
}
|
|
307
|
+
function servicesWithoutScope(requestedScope, accessToken) {
|
|
308
|
+
const serviceOf2 = (scope) => scope.includes("/") ? scope.split("/")[0] : null;
|
|
309
|
+
const granted = new Set(grantedScopes(accessToken).map(serviceOf2).filter(Boolean));
|
|
310
|
+
const requested = new Set(requestedScope.split(" ").map(serviceOf2).filter(Boolean));
|
|
311
|
+
return [...requested].filter((service) => !granted.has(service)).sort();
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// src/lib/client-credentials.ts
|
|
315
|
+
var cached = null;
|
|
316
|
+
function clientCredentials() {
|
|
317
|
+
const clientId = process.env.SORTLIST_CLIENT_ID;
|
|
318
|
+
const clientSecret = process.env.SORTLIST_CLIENT_SECRET;
|
|
319
|
+
if (!clientId || !clientSecret) return null;
|
|
320
|
+
return { clientId, clientSecret };
|
|
321
|
+
}
|
|
322
|
+
var CLAIM_NAMESPACE = "https://sortlist.com/";
|
|
323
|
+
function applicationIdentity(accessToken) {
|
|
324
|
+
try {
|
|
325
|
+
const claims = tokenClaims(accessToken);
|
|
326
|
+
if (!claims) return null;
|
|
327
|
+
return {
|
|
328
|
+
applicationId: String(claims[`${CLAIM_NAMESPACE}application_id`]),
|
|
329
|
+
credentialId: String(claims[`${CLAIM_NAMESPACE}credential_id`]),
|
|
330
|
+
companyId: String(claims[`${CLAIM_NAMESPACE}company_id`]),
|
|
331
|
+
sub: String(claims.sub),
|
|
332
|
+
expiresAt: new Date(Number(claims.exp) * 1e3)
|
|
333
|
+
};
|
|
334
|
+
} catch {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
function tokenEndpoint() {
|
|
339
|
+
const configured = process.env.SORTLIST_TOKEN_URL ?? loadConfig().tokenEndpoint;
|
|
340
|
+
if (!configured) {
|
|
341
|
+
throw new Error("No token endpoint configured. Set SORTLIST_TOKEN_URL or run: sl config set tokenEndpoint <url>");
|
|
342
|
+
}
|
|
343
|
+
return configured;
|
|
344
|
+
}
|
|
345
|
+
async function fetchClientCredentialsToken(credentials) {
|
|
346
|
+
if (cached && Date.now() < cached.expiresAt) return cached.accessToken;
|
|
347
|
+
const body = new URLSearchParams({
|
|
348
|
+
grant_type: "client_credentials",
|
|
349
|
+
client_id: credentials.clientId,
|
|
350
|
+
client_secret: credentials.clientSecret
|
|
351
|
+
});
|
|
352
|
+
const res = await fetch(tokenEndpoint(), {
|
|
353
|
+
method: "POST",
|
|
354
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
355
|
+
body: body.toString()
|
|
356
|
+
});
|
|
357
|
+
const json = await res.json().catch(() => ({}));
|
|
358
|
+
if (!res.ok || !json.access_token) {
|
|
359
|
+
const reason = json.error ?? `HTTP ${res.status}`;
|
|
360
|
+
throw new Error(`Token request failed: ${reason}`);
|
|
361
|
+
}
|
|
362
|
+
cached = {
|
|
363
|
+
accessToken: json.access_token,
|
|
364
|
+
// 60s of headroom, matching the interactive path's expiry check.
|
|
365
|
+
expiresAt: Date.now() + ((json.expires_in ?? 3600) - 60) * 1e3
|
|
366
|
+
};
|
|
367
|
+
return cached.accessToken;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/lib/company.ts
|
|
371
|
+
function isCompanyId(value) {
|
|
372
|
+
try {
|
|
373
|
+
return Buffer.from(value, "base64url").toString("utf8").startsWith("Company/");
|
|
374
|
+
} catch {
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
var COMPANY_BY_SLUG = `query CompanyBySlug($slug: String!) { company(slug: $slug) { id } }`;
|
|
379
|
+
var resolved = /* @__PURE__ */ new Map();
|
|
380
|
+
async function lookupCompanyId(slug) {
|
|
381
|
+
const data = await graphqlRaw(COMPANY_BY_SLUG, { slug }, { withoutCompany: true });
|
|
382
|
+
const id = data.company?.id;
|
|
383
|
+
if (typeof id === "string") return id;
|
|
384
|
+
error(`No company with slug "${slug}" among yours.`);
|
|
385
|
+
hint("`sl companies` lists the companies you belong to, with their slugs and ids.");
|
|
386
|
+
process.exit(2);
|
|
387
|
+
}
|
|
388
|
+
async function resolveCompanyId(opts) {
|
|
389
|
+
const value = opts.company ?? opts.ctx?.company;
|
|
390
|
+
if (!value) return void 0;
|
|
391
|
+
if (isCompanyId(value)) return value;
|
|
392
|
+
let pending = resolved.get(value);
|
|
393
|
+
if (!pending) {
|
|
394
|
+
pending = lookupCompanyId(value);
|
|
395
|
+
resolved.set(value, pending);
|
|
396
|
+
}
|
|
397
|
+
return pending;
|
|
398
|
+
}
|
|
399
|
+
|
|
248
400
|
// src/lib/sentry.ts
|
|
249
401
|
import * as Sentry from "@sentry/node";
|
|
250
402
|
var SENTRY_DSN = "https://306d2e4389b8baa0bf14e587c2ceff04@o27611.ingest.us.sentry.io/4511229468409856";
|
|
@@ -304,7 +456,7 @@ async function flushSentry(timeout = 2e3) {
|
|
|
304
456
|
}
|
|
305
457
|
|
|
306
458
|
// src/graphql/generated/graphql.ts
|
|
307
|
-
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": "
|
|
459
|
+
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" } }] } }] } }] };
|
|
308
460
|
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" } }] } }] };
|
|
309
461
|
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" } }] } }] } }] };
|
|
310
462
|
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" } }] } }] } }] };
|
|
@@ -312,7 +464,7 @@ var RefreshTokenDocument = { "kind": "Document", "definitions": [{ "kind": "Oper
|
|
|
312
464
|
|
|
313
465
|
// src/graphql/generated/gql.ts
|
|
314
466
|
var documents = {
|
|
315
|
-
"\n query Me {\n me {\n
|
|
467
|
+
"\n query Me {\n me {\n id\n email\n firstName\n lastName\n }\n }\n": MeDocument,
|
|
316
468
|
"\n query LogoutUrl {\n logoutUrl\n }\n": LogoutUrlDocument,
|
|
317
469
|
"\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,
|
|
318
470
|
"\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,
|
|
@@ -403,119 +555,275 @@ async function refreshAccessToken(creds, endpoint) {
|
|
|
403
555
|
saveCredentials(newCreds);
|
|
404
556
|
return newCreds;
|
|
405
557
|
}
|
|
558
|
+
function reportUnreachable(err, { endpoint, operationName, throwOnError }) {
|
|
559
|
+
const code = err.cause?.code;
|
|
560
|
+
const reason = code === "ECONNREFUSED" ? `nothing is listening on ${endpoint}` : err.message;
|
|
561
|
+
captureException2(err, { operationName, endpoint });
|
|
562
|
+
if (throwOnError) {
|
|
563
|
+
throw new GraphQLRequestError(`${operationName} could not reach the endpoint: ${reason}`, { operationName });
|
|
564
|
+
}
|
|
565
|
+
error(`Could not reach ${endpoint}: ${reason}`);
|
|
566
|
+
hint("Is the local stack running? Check the configured endpoint with `sl config show`.");
|
|
567
|
+
process.exit(3);
|
|
568
|
+
}
|
|
569
|
+
async function resolveAccessToken(options, attempt) {
|
|
570
|
+
const machine = options.asPerson ? null : clientCredentials();
|
|
571
|
+
if (machine) {
|
|
572
|
+
try {
|
|
573
|
+
return { token: await fetchClientCredentialsToken(machine), kind: "application" };
|
|
574
|
+
} catch (err) {
|
|
575
|
+
const message = err.message;
|
|
576
|
+
if (attempt.throwOnError) throw new GraphQLRequestError(message, { operationName: attempt.operationName });
|
|
577
|
+
error(message);
|
|
578
|
+
hint("Check SORTLIST_CLIENT_ID, SORTLIST_CLIENT_SECRET and the token endpoint.");
|
|
579
|
+
hint("The credential may also have been revoked, or its application deleted.");
|
|
580
|
+
process.exit(2);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
const session = options.asPerson ? null : loadApplicationSession();
|
|
584
|
+
if (session) return { token: session.accessToken, kind: "application" };
|
|
585
|
+
if (!options.asPerson && applicationSessionExpired()) {
|
|
586
|
+
error("The application session has expired.");
|
|
587
|
+
hint("Run `sl use application <id>` again, or `sl use me` to act as yourself.");
|
|
588
|
+
process.exit(2);
|
|
589
|
+
}
|
|
590
|
+
let creds = ensureAuthenticated();
|
|
591
|
+
if (isExpired(creds)) {
|
|
592
|
+
const refreshed = await refreshAccessToken(creds, attempt.endpoint);
|
|
593
|
+
if (!refreshed) {
|
|
594
|
+
if (attempt.throwOnError) {
|
|
595
|
+
throw new GraphQLRequestError("Session expired and could not be refreshed.", {
|
|
596
|
+
operationName: attempt.operationName
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
error("Your session has expired and could not be refreshed.");
|
|
600
|
+
hint("Run `sl login` to re-authenticate.");
|
|
601
|
+
process.exit(2);
|
|
602
|
+
}
|
|
603
|
+
creds = refreshed;
|
|
604
|
+
}
|
|
605
|
+
return { token: creds.accessToken, kind: "user" };
|
|
606
|
+
}
|
|
607
|
+
function reportHttpFailure(res, body, attempt) {
|
|
608
|
+
const { operationName, endpoint, throwOnError, verbose } = attempt;
|
|
609
|
+
captureException2(new Error(`${operationName} failed: HTTP ${res.status}`), {
|
|
610
|
+
operationName,
|
|
611
|
+
httpStatus: res.status,
|
|
612
|
+
endpoint
|
|
613
|
+
});
|
|
614
|
+
if (throwOnError) {
|
|
615
|
+
throw new GraphQLRequestError(`${operationName} failed: HTTP ${res.status} ${res.statusText}`, {
|
|
616
|
+
operationName,
|
|
617
|
+
httpStatus: res.status
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
error(`${operationName} failed: HTTP ${res.status} ${res.statusText}`);
|
|
621
|
+
hint("Check your network connection and endpoint: sl config show");
|
|
622
|
+
if (verbose) info(`[debug] Response body: ${body}`);
|
|
623
|
+
process.exit(3);
|
|
624
|
+
}
|
|
625
|
+
function hasFieldError(errors) {
|
|
626
|
+
return errors.some((e) => e.message.includes("Failed to implement") || e.message.includes("undefined method"));
|
|
627
|
+
}
|
|
628
|
+
function codeOf(errors) {
|
|
629
|
+
for (const { extensions } of errors) {
|
|
630
|
+
const code = extensions?.code;
|
|
631
|
+
if (typeof code === "string") return code;
|
|
632
|
+
}
|
|
633
|
+
return null;
|
|
634
|
+
}
|
|
635
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
636
|
+
function subrequestStatus(errors) {
|
|
637
|
+
for (const { extensions } of errors) {
|
|
638
|
+
const http = extensions?.http;
|
|
639
|
+
if (typeof http === "object" && http !== null && typeof http.status === "number") {
|
|
640
|
+
return http.status;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return null;
|
|
644
|
+
}
|
|
645
|
+
function humanise(code) {
|
|
646
|
+
const words = code.toLowerCase().replaceAll("_", " ");
|
|
647
|
+
return words.charAt(0).toUpperCase() + words.slice(1) + ".";
|
|
648
|
+
}
|
|
649
|
+
function detailLines(errors) {
|
|
650
|
+
const lines = [];
|
|
651
|
+
for (const { extensions } of errors) {
|
|
652
|
+
const details = extensions?.details;
|
|
653
|
+
if (typeof details !== "object" || details === null) continue;
|
|
654
|
+
for (const [attribute, codes] of Object.entries(details)) {
|
|
655
|
+
lines.push(`${attribute}: ${Array.isArray(codes) ? codes.join(", ") : String(codes)}`);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return lines;
|
|
659
|
+
}
|
|
660
|
+
var ROUTER_PLACEHOLDER = "Unexpected error";
|
|
661
|
+
function describe(errors) {
|
|
662
|
+
const code = codeOf(errors);
|
|
663
|
+
const details = detailLines(errors);
|
|
664
|
+
const messages = messageLines(errors);
|
|
665
|
+
if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
|
|
666
|
+
const explanation = details.length > 0 ? details : messages;
|
|
667
|
+
return explanation.length > 0 ? `${humanise(code)} ${explanation.join("; ")}` : humanise(code);
|
|
668
|
+
}
|
|
669
|
+
return messages.length > 0 ? messages.join("; ") : "the server gave no reason";
|
|
670
|
+
}
|
|
671
|
+
function messageLines(errors) {
|
|
672
|
+
return errors.map((e) => e.message).filter((message) => message !== ROUTER_PLACEHOLDER);
|
|
673
|
+
}
|
|
674
|
+
function serviceOf(errors) {
|
|
675
|
+
for (const { extensions } of errors) {
|
|
676
|
+
const service = extensions?.service;
|
|
677
|
+
if (typeof service === "string") return service;
|
|
678
|
+
}
|
|
679
|
+
return null;
|
|
680
|
+
}
|
|
681
|
+
function hasResolvedField(data) {
|
|
682
|
+
if (data === null || data === void 0) return false;
|
|
683
|
+
return Object.values(data).some((value) => value !== null);
|
|
684
|
+
}
|
|
685
|
+
function reportGraphqlErrors(errors, options, attempt) {
|
|
686
|
+
const { operationName, throwOnError, verbose } = attempt;
|
|
687
|
+
captureException2(new Error(`${operationName} GraphQL errors`), {
|
|
688
|
+
operationName,
|
|
689
|
+
errors: errors.map((e) => e.message)
|
|
690
|
+
});
|
|
691
|
+
if (throwOnError) {
|
|
692
|
+
throw new GraphQLRequestError(`${operationName} failed: ${describe(errors)}`, {
|
|
693
|
+
operationName,
|
|
694
|
+
graphqlErrors: errors
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
if (codeOf(errors) === "NOT_AUTHENTICATED") {
|
|
698
|
+
const service = serviceOf(errors);
|
|
699
|
+
const where = service === null ? "" : ` for ${service}`;
|
|
700
|
+
error(`Not authenticated${where}.`);
|
|
701
|
+
if (actingAsApplication()) {
|
|
702
|
+
hint("You are acting as an application. Hermes refuses the tokens it mints on its own");
|
|
703
|
+
hint("management API by design, so a leaked secret cannot mint more \u2014 `sl use me` switches back.");
|
|
704
|
+
} else {
|
|
705
|
+
hint("Run `sl login` to authenticate, or `sl whoami` to see what the CLI is acting as.");
|
|
706
|
+
}
|
|
707
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${gqlError.message}`);
|
|
708
|
+
process.exit(4);
|
|
709
|
+
}
|
|
710
|
+
if (subrequestStatus(errors) === 401) {
|
|
711
|
+
const service = serviceOf(errors);
|
|
712
|
+
const where = service ?? "The subgraph";
|
|
713
|
+
error(`${where} did not accept your token.`);
|
|
714
|
+
if (actingAsApplication()) {
|
|
715
|
+
hint("The application token has expired or was signed with a key Hermes no longer publishes");
|
|
716
|
+
hint("(a local Hermes mints a fresh key on every restart). Run `sl use application <id>` again.");
|
|
717
|
+
} else {
|
|
718
|
+
hint("Run `sl login` again; `sl whoami` shows what the CLI is acting as.");
|
|
719
|
+
}
|
|
720
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
|
|
721
|
+
process.exit(4);
|
|
722
|
+
}
|
|
723
|
+
if (subrequestStatus(errors) === 403) {
|
|
724
|
+
const service = serviceOf(errors);
|
|
725
|
+
const where = service ?? "The subgraph";
|
|
726
|
+
const company = options.company ?? getUserContext().company ?? options.companyId;
|
|
727
|
+
if (company && UUID.test(company)) {
|
|
728
|
+
error(`${where} refused ${company}: that is a raw uuid, not a company id.`);
|
|
729
|
+
hint("Pass its slug, or the id `sl companies` lists.");
|
|
730
|
+
} else if (company) {
|
|
731
|
+
error(`${where} refused to act for company ${company}.`);
|
|
732
|
+
hint("Your token does not list that company, or Hermes no longer knows you as one of its members.");
|
|
733
|
+
hint("`sl whoami` shows what the CLI is acting as;");
|
|
734
|
+
hint("pick one of your companies with --company or `sl config set company <slug|id>`.");
|
|
735
|
+
} else {
|
|
736
|
+
error(`${where} refused this request: it names no company to act for.`);
|
|
737
|
+
hint("Pick one of your companies with --company or `sl config set company <slug|id>`;");
|
|
738
|
+
hint("`sl companies` lists them. Join one first if the list is empty.");
|
|
739
|
+
}
|
|
740
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
|
|
741
|
+
process.exit(4);
|
|
742
|
+
}
|
|
743
|
+
const code = codeOf(errors);
|
|
744
|
+
if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
|
|
745
|
+
error(humanise(code));
|
|
746
|
+
const details = detailLines(errors);
|
|
747
|
+
const lines = details.length > 0 ? details : messageLines(errors);
|
|
748
|
+
for (const line of lines) info(` ${line}`);
|
|
749
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
|
|
750
|
+
process.exit(1);
|
|
751
|
+
}
|
|
752
|
+
error(`${operationName} failed:`);
|
|
753
|
+
for (const gqlError of errors) {
|
|
754
|
+
info(` ${gqlError.message}`);
|
|
755
|
+
if (verbose && gqlError.extensions) info(`[debug] Extensions: ${JSON.stringify(gqlError.extensions)}`);
|
|
756
|
+
}
|
|
757
|
+
if (hasFieldError(errors)) {
|
|
758
|
+
hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
|
|
759
|
+
hint(`Example: sl ${operationName.toLowerCase()} --fields id,title,status`);
|
|
760
|
+
}
|
|
761
|
+
process.exit(1);
|
|
762
|
+
}
|
|
763
|
+
function logRequest(query, variables, attempt) {
|
|
764
|
+
info(`[debug] ${attempt.operationName} \u2192 ${attempt.endpoint}`);
|
|
765
|
+
info(`[debug] Query:
|
|
766
|
+
${query}`);
|
|
767
|
+
if (variables) info(`[debug] Variables: ${JSON.stringify(variables, null, 2)}`);
|
|
768
|
+
}
|
|
406
769
|
async function executeQuery(query, variables, options = {}) {
|
|
407
|
-
const endpoint = getEndpoint(options.endpoint);
|
|
408
770
|
const authenticated = options.authenticated ?? true;
|
|
409
|
-
const
|
|
410
|
-
|
|
411
|
-
|
|
771
|
+
const attempt = {
|
|
772
|
+
endpoint: getEndpoint(options.endpoint),
|
|
773
|
+
operationName: extractOperationName(query),
|
|
774
|
+
throwOnError: options.throwOnError ?? false,
|
|
775
|
+
verbose: process.env.SL_DEBUG === "1"
|
|
776
|
+
};
|
|
412
777
|
addBreadcrumb2({
|
|
413
778
|
category: "graphql",
|
|
414
|
-
message: operationName,
|
|
415
|
-
data: { endpoint, authenticated },
|
|
779
|
+
message: attempt.operationName,
|
|
780
|
+
data: { endpoint: attempt.endpoint, authenticated },
|
|
416
781
|
level: "info"
|
|
417
782
|
});
|
|
418
|
-
if (verbose)
|
|
419
|
-
info(`[debug] ${operationName} \u2192 ${endpoint}`);
|
|
420
|
-
info(`[debug] Query:
|
|
421
|
-
${query}`);
|
|
422
|
-
if (variables) {
|
|
423
|
-
info(`[debug] Variables: ${JSON.stringify(variables, null, 2)}`);
|
|
424
|
-
}
|
|
425
|
-
}
|
|
783
|
+
if (attempt.verbose) logRequest(query, variables, attempt);
|
|
426
784
|
const headers = {
|
|
427
785
|
"Content-Type": "application/json",
|
|
428
786
|
"X-API-Client": "sl-cli"
|
|
429
787
|
};
|
|
430
788
|
if (authenticated) {
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
throw new GraphQLRequestError("Session expired and could not be refreshed.", { operationName });
|
|
437
|
-
}
|
|
438
|
-
error("Your session has expired and could not be refreshed.");
|
|
439
|
-
hint("Run `sl login` to re-authenticate.");
|
|
440
|
-
process.exit(2);
|
|
441
|
-
}
|
|
442
|
-
creds = refreshed;
|
|
443
|
-
}
|
|
444
|
-
headers["Authorization"] = `Bearer ${creds.accessToken}`;
|
|
445
|
-
if (verbose) {
|
|
446
|
-
info(`[debug] JWT: ...${creds.accessToken.slice(-8)}`);
|
|
447
|
-
}
|
|
789
|
+
const { token, kind } = await resolveAccessToken(options, attempt);
|
|
790
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
791
|
+
const companyId = options.withoutCompany ? void 0 : options.companyId ?? await resolveCompanyId({ ctx: getUserContext() });
|
|
792
|
+
if (companyId) headers["X-Company-Id"] = companyId;
|
|
793
|
+
if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
|
|
448
794
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
795
|
+
let res;
|
|
796
|
+
try {
|
|
797
|
+
res = await fetch(attempt.endpoint, {
|
|
798
|
+
method: "POST",
|
|
799
|
+
headers,
|
|
800
|
+
body: JSON.stringify({ query, variables })
|
|
801
|
+
});
|
|
802
|
+
} catch (err) {
|
|
803
|
+
reportUnreachable(err, {
|
|
804
|
+
endpoint: attempt.endpoint,
|
|
805
|
+
operationName: attempt.operationName,
|
|
806
|
+
throwOnError: attempt.throwOnError
|
|
460
807
|
});
|
|
461
|
-
if (throwOnError) {
|
|
462
|
-
throw new GraphQLRequestError(`${operationName} failed: HTTP ${res.status} ${res.statusText}`, {
|
|
463
|
-
operationName,
|
|
464
|
-
httpStatus: res.status
|
|
465
|
-
});
|
|
466
|
-
}
|
|
467
|
-
error(`${operationName} failed: HTTP ${res.status} ${res.statusText}`);
|
|
468
|
-
hint("Check your network connection and endpoint: sl config show");
|
|
469
|
-
if (verbose) {
|
|
470
|
-
info(`[debug] Response body: ${body}`);
|
|
471
|
-
}
|
|
472
|
-
process.exit(3);
|
|
473
808
|
}
|
|
809
|
+
if (!res.ok) reportHttpFailure(res, await res.text(), attempt);
|
|
474
810
|
const json = await res.json();
|
|
475
811
|
if (json.errors?.length) {
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
const hasFieldError2 = json.errors.some(
|
|
481
|
-
(e) => e.message.includes("Failed to implement") || e.message.includes("undefined method")
|
|
482
|
-
);
|
|
483
|
-
if (hasFieldError2) {
|
|
484
|
-
hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
|
|
485
|
-
}
|
|
486
|
-
return json.data;
|
|
487
|
-
}
|
|
488
|
-
captureException2(new Error(`${operationName} GraphQL errors`), {
|
|
489
|
-
operationName,
|
|
490
|
-
errors: json.errors.map((e) => e.message)
|
|
491
|
-
});
|
|
492
|
-
if (throwOnError) {
|
|
493
|
-
throw new GraphQLRequestError(`${operationName} failed: ${json.errors.map((e) => e.message).join("; ")}`, {
|
|
494
|
-
operationName,
|
|
495
|
-
graphqlErrors: json.errors
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
error(`${operationName} failed:`);
|
|
499
|
-
for (const gqlError of json.errors) {
|
|
500
|
-
info(` ${gqlError.message}`);
|
|
501
|
-
if (verbose && gqlError.extensions) {
|
|
502
|
-
info(`[debug] Extensions: ${JSON.stringify(gqlError.extensions)}`);
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
const hasFieldError = json.errors.some(
|
|
506
|
-
(e) => e.message.includes("Failed to implement") || e.message.includes("undefined method")
|
|
507
|
-
);
|
|
508
|
-
if (hasFieldError) {
|
|
812
|
+
const refused = !hasResolvedField(json.data);
|
|
813
|
+
if (refused) reportGraphqlErrors(json.errors, options, attempt);
|
|
814
|
+
for (const gqlError of json.errors) warn(gqlError.message);
|
|
815
|
+
if (hasFieldError(json.errors)) {
|
|
509
816
|
hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
|
|
510
|
-
hint(`Example: sl ${operationName.toLowerCase()} --fields id,title,status`);
|
|
511
817
|
}
|
|
512
|
-
|
|
818
|
+
return json.data;
|
|
513
819
|
}
|
|
514
820
|
if (!json.data) {
|
|
515
|
-
if (throwOnError) {
|
|
516
|
-
throw new GraphQLRequestError(`${operationName}: no data returned from API.`, {
|
|
821
|
+
if (attempt.throwOnError) {
|
|
822
|
+
throw new GraphQLRequestError(`${attempt.operationName}: no data returned from API.`, {
|
|
823
|
+
operationName: attempt.operationName
|
|
824
|
+
});
|
|
517
825
|
}
|
|
518
|
-
error(`${operationName}: no data returned from API.`);
|
|
826
|
+
error(`${attempt.operationName}: no data returned from API.`);
|
|
519
827
|
hint("This usually means the server returned an empty response.");
|
|
520
828
|
hint("Verify your endpoint: sl config show");
|
|
521
829
|
process.exit(1);
|
|
@@ -561,19 +869,10 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
|
|
|
561
869
|
const fields = type.getFields();
|
|
562
870
|
const lines = [];
|
|
563
871
|
const isPayload = PAYLOAD_TYPE_PATTERN.test(type.name);
|
|
564
|
-
if (type
|
|
872
|
+
if (isConnection(type)) {
|
|
565
873
|
const nodesType = unwrap(fields.nodes.type);
|
|
566
874
|
const nodeSelections = buildSelections(nodesType, schema, depth, exclude, `${prefix}nodes.`, new Set(visited));
|
|
567
|
-
|
|
568
|
-
lines.push(`nodes {`);
|
|
569
|
-
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
570
|
-
lines.push(`}`);
|
|
571
|
-
lines.push(`pageInfo {`);
|
|
572
|
-
lines.push(` hasNextPage`);
|
|
573
|
-
lines.push(` endCursor`);
|
|
574
|
-
lines.push(`}`);
|
|
575
|
-
if (fields.totalCount) lines.push(`totalCount`);
|
|
576
|
-
return lines;
|
|
875
|
+
return connectionSelections(type, nodeSelections);
|
|
577
876
|
}
|
|
578
877
|
for (const [name, field] of Object.entries(fields)) {
|
|
579
878
|
if (name.startsWith("__")) continue;
|
|
@@ -588,7 +887,7 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
|
|
|
588
887
|
} else if (isObjectType(namedType) && depth > 0) {
|
|
589
888
|
const subSelections = buildSelections(namedType, schema, depth - 1, exclude, `${fullPath}.`, new Set(visited));
|
|
590
889
|
if (subSelections.length > 0) {
|
|
591
|
-
lines.push(`${name} {`);
|
|
890
|
+
lines.push(`${fieldCall(name, field)} {`);
|
|
592
891
|
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
593
892
|
lines.push(`}`);
|
|
594
893
|
}
|
|
@@ -596,6 +895,95 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
|
|
|
596
895
|
}
|
|
597
896
|
return lines;
|
|
598
897
|
}
|
|
898
|
+
var NESTED_PAGE_SIZE = 10;
|
|
899
|
+
function fieldCall(name, field) {
|
|
900
|
+
const named = unwrap(field.type);
|
|
901
|
+
const pageable = isObjectType(named) && isConnection(named) && field.args.some((a) => a.name === "first");
|
|
902
|
+
return pageable ? `${name}(first: ${NESTED_PAGE_SIZE})` : name;
|
|
903
|
+
}
|
|
904
|
+
function isConnection(type) {
|
|
905
|
+
const fields = type.getFields();
|
|
906
|
+
return type.name.endsWith("Connection") && Boolean(fields.nodes) && Boolean(fields.pageInfo);
|
|
907
|
+
}
|
|
908
|
+
function selectableFields(type) {
|
|
909
|
+
return Object.values(type.getFields()).filter(
|
|
910
|
+
(field) => !field.name.startsWith("__") && !field.args.some((a) => isNonNullType(a.type) && a.defaultValue === void 0)
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
function edgeExtras(connection) {
|
|
914
|
+
const edgesField = connection.getFields().edges;
|
|
915
|
+
if (!edgesField) return null;
|
|
916
|
+
const edge = unwrap(edgesField.type);
|
|
917
|
+
if (!isObjectType(edge)) return null;
|
|
918
|
+
const lines = [];
|
|
919
|
+
for (const field of selectableFields(edge)) {
|
|
920
|
+
if (field.name === "node" || field.name === "cursor" || field.name === "id") continue;
|
|
921
|
+
const named = unwrap(field.type);
|
|
922
|
+
if (isLeaf(named)) {
|
|
923
|
+
lines.push(field.name);
|
|
924
|
+
} else if (isObjectType(named)) {
|
|
925
|
+
const leaves = selectableFields(named).filter((sub) => isLeaf(unwrap(sub.type))).map((sub) => sub.name);
|
|
926
|
+
if (leaves.length > 0) lines.push(`${field.name} { ${leaves.join(" ")} }`);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
return lines.length === 0 ? null : { edge, lines };
|
|
930
|
+
}
|
|
931
|
+
function connectionSelections(connection, nodeSelections) {
|
|
932
|
+
if (nodeSelections.length === 0) return [];
|
|
933
|
+
const lines = [];
|
|
934
|
+
const extras = edgeExtras(connection);
|
|
935
|
+
if (extras) {
|
|
936
|
+
lines.push("edges {");
|
|
937
|
+
lines.push(" node {");
|
|
938
|
+
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
939
|
+
lines.push(" }");
|
|
940
|
+
for (const extra of extras.lines) lines.push(` ${extra}`);
|
|
941
|
+
lines.push("}");
|
|
942
|
+
} else {
|
|
943
|
+
lines.push("nodes {");
|
|
944
|
+
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
945
|
+
lines.push("}");
|
|
946
|
+
}
|
|
947
|
+
lines.push("pageInfo {");
|
|
948
|
+
lines.push(" hasNextPage");
|
|
949
|
+
lines.push(" endCursor");
|
|
950
|
+
lines.push("}");
|
|
951
|
+
if (connection.getFields().totalCount) lines.push("totalCount");
|
|
952
|
+
for (const extra of connectionExtras(connection)) lines.push(extra);
|
|
953
|
+
return lines;
|
|
954
|
+
}
|
|
955
|
+
var CONNECTION_PLUMBING = /* @__PURE__ */ new Set(["edges", "nodes", "pageInfo", "totalCount", "approximateTotalCount"]);
|
|
956
|
+
function connectionExtras(connection) {
|
|
957
|
+
return selectableFields(connection).filter((field) => !CONNECTION_PLUMBING.has(field.name)).flatMap((field) => {
|
|
958
|
+
const named = unwrap(field.type);
|
|
959
|
+
if (isLeaf(named)) return [field.name];
|
|
960
|
+
if (!isObjectType(named)) return [];
|
|
961
|
+
const inner = selectableFields(named).flatMap((sub) => {
|
|
962
|
+
const subType = unwrap(sub.type);
|
|
963
|
+
if (isLeaf(subType)) return [sub.name];
|
|
964
|
+
if (!isObjectType(subType)) return [];
|
|
965
|
+
const leaves = selectableFields(subType).filter((leaf) => isLeaf(unwrap(leaf.type)));
|
|
966
|
+
return leaves.length === 0 ? [] : [`${sub.name} { ${leaves.map((leaf) => leaf.name).join(" ")} }`];
|
|
967
|
+
});
|
|
968
|
+
return inner.length === 0 ? [] : [`${field.name} { ${inner.join(" ")} }`];
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
var UnknownFieldError = class extends Error {
|
|
972
|
+
field;
|
|
973
|
+
suggestions;
|
|
974
|
+
constructor(field, type) {
|
|
975
|
+
const names = Object.keys(type.getFields()).filter((name) => !name.startsWith("__"));
|
|
976
|
+
const needle = field.toLowerCase();
|
|
977
|
+
const suggestions = names.filter((name) => {
|
|
978
|
+
const candidate = name.toLowerCase();
|
|
979
|
+
return candidate.includes(needle) || needle.includes(candidate);
|
|
980
|
+
});
|
|
981
|
+
super(`${type.name} has no field "${field}".`);
|
|
982
|
+
this.name = "UnknownFieldError";
|
|
983
|
+
this.field = field;
|
|
984
|
+
this.suggestions = suggestions.length > 0 ? suggestions : names;
|
|
985
|
+
}
|
|
986
|
+
};
|
|
599
987
|
function buildQuery(schema, kind, fieldName, variables, options = {}) {
|
|
600
988
|
const rootType = kind === "query" ? schema.getQueryType() : schema.getMutationType();
|
|
601
989
|
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
@@ -640,20 +1028,11 @@ ${selectionBody}
|
|
|
640
1028
|
function buildFieldsFromList(type, schema, fieldPaths) {
|
|
641
1029
|
if (!isObjectType(type)) return [];
|
|
642
1030
|
const fields = type.getFields();
|
|
643
|
-
if (type
|
|
1031
|
+
if (isConnection(type)) {
|
|
644
1032
|
const nodesType = unwrap(fields.nodes.type);
|
|
645
|
-
const
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
lines2.push("nodes {");
|
|
649
|
-
for (const sel of nodeSelections) lines2.push(` ${sel}`);
|
|
650
|
-
lines2.push("}");
|
|
651
|
-
lines2.push("pageInfo {");
|
|
652
|
-
lines2.push(" hasNextPage");
|
|
653
|
-
lines2.push(" endCursor");
|
|
654
|
-
lines2.push("}");
|
|
655
|
-
if (fields.totalCount) lines2.push("totalCount");
|
|
656
|
-
return lines2;
|
|
1033
|
+
const withId = isObjectType(nodesType) && nodesType.getFields().id && !fieldPaths.includes("id");
|
|
1034
|
+
const nodeSelections = buildFieldsFromList(nodesType, schema, withId ? ["id", ...fieldPaths] : fieldPaths);
|
|
1035
|
+
return connectionSelections(type, nodeSelections);
|
|
657
1036
|
}
|
|
658
1037
|
const lines = [];
|
|
659
1038
|
const grouped = /* @__PURE__ */ new Map();
|
|
@@ -664,14 +1043,14 @@ function buildFieldsFromList(type, schema, fieldPaths) {
|
|
|
664
1043
|
}
|
|
665
1044
|
for (const [name, subPaths] of grouped) {
|
|
666
1045
|
const field = fields[name];
|
|
667
|
-
if (!field)
|
|
1046
|
+
if (!field) throw new UnknownFieldError(name, type);
|
|
668
1047
|
const namedType = unwrap(field.type);
|
|
669
1048
|
if (isLeaf(namedType)) {
|
|
670
1049
|
lines.push(name);
|
|
671
1050
|
} else if (isObjectType(namedType) && subPaths.length > 0) {
|
|
672
1051
|
const subSelections = buildFieldsFromList(namedType, schema, subPaths);
|
|
673
1052
|
if (subSelections.length > 0) {
|
|
674
|
-
lines.push(`${name} {`);
|
|
1053
|
+
lines.push(`${fieldCall(name, field)} {`);
|
|
675
1054
|
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
676
1055
|
lines.push(`}`);
|
|
677
1056
|
}
|
|
@@ -680,15 +1059,127 @@ function buildFieldsFromList(type, schema, fieldPaths) {
|
|
|
680
1059
|
return lines;
|
|
681
1060
|
}
|
|
682
1061
|
|
|
683
|
-
// src/lib/
|
|
684
|
-
|
|
685
|
-
|
|
1062
|
+
// src/lib/render.ts
|
|
1063
|
+
var INDENT = " ";
|
|
1064
|
+
var CONNECTION_PLUMBING2 = /* @__PURE__ */ new Set([
|
|
1065
|
+
"edges",
|
|
1066
|
+
"nodes",
|
|
1067
|
+
"pageInfo",
|
|
1068
|
+
"totalCount",
|
|
1069
|
+
"approximateTotalCount",
|
|
1070
|
+
"__typename"
|
|
1071
|
+
]);
|
|
1072
|
+
function isRecord(value) {
|
|
1073
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1074
|
+
}
|
|
1075
|
+
function rowOf(edge) {
|
|
1076
|
+
if (!isRecord(edge) || !isRecord(edge.node)) return isRecord(edge) ? edge.node : edge;
|
|
1077
|
+
const { node, cursor: _cursor, __typename: _typename, ...extras } = edge;
|
|
1078
|
+
const said = Object.entries(extras).filter(
|
|
1079
|
+
([, value]) => value != null && !(Array.isArray(value) && value.length === 0)
|
|
1080
|
+
);
|
|
1081
|
+
return { ...node, ...Object.fromEntries(said) };
|
|
1082
|
+
}
|
|
1083
|
+
function asConnection(value) {
|
|
1084
|
+
if (!isRecord(value)) return null;
|
|
1085
|
+
if (Array.isArray(value.nodes)) return value;
|
|
1086
|
+
if (Array.isArray(value.edges)) return { ...value, nodes: value.edges.map(rowOf) };
|
|
1087
|
+
return null;
|
|
1088
|
+
}
|
|
1089
|
+
function formatScalar(value) {
|
|
1090
|
+
if (value === null || value === void 0) return "\u2014";
|
|
1091
|
+
if (typeof value === "boolean") return value ? "yes" : "no";
|
|
1092
|
+
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
|
|
1093
|
+
return value.slice(0, 19).replace("T", " ");
|
|
1094
|
+
}
|
|
1095
|
+
return String(value);
|
|
1096
|
+
}
|
|
1097
|
+
function isFlatRecord(value) {
|
|
1098
|
+
return isRecord(value) && Object.values(value).every((v) => !isRecord(v) && !Array.isArray(v));
|
|
1099
|
+
}
|
|
1100
|
+
var isDeadline = (key) => /Until$/.test(key);
|
|
1101
|
+
function formatDeadline(value) {
|
|
1102
|
+
return typeof value === "string" && value !== "" ? `until ${formatScalar(value)}` : "\u2014";
|
|
1103
|
+
}
|
|
1104
|
+
function formatFlatRows(rows, indent) {
|
|
1105
|
+
const keys = Object.keys(rows[0]).filter((key) => key !== "__typename");
|
|
1106
|
+
const ordered = [...keys.filter((key) => !isDeadline(key)), ...keys.filter(isDeadline)];
|
|
1107
|
+
const cells = rows.map(
|
|
1108
|
+
(row) => ordered.map((key) => isDeadline(key) ? formatDeadline(row[key]) : formatScalar(row[key]))
|
|
1109
|
+
);
|
|
1110
|
+
const widths = ordered.map((_, column) => Math.max(...cells.map((row) => (row[column] ?? "").length)));
|
|
1111
|
+
return cells.map(
|
|
1112
|
+
(row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")
|
|
1113
|
+
).join(`
|
|
1114
|
+
${indent}`);
|
|
1115
|
+
}
|
|
1116
|
+
function summarise(key, value) {
|
|
1117
|
+
const connection = asConnection(value);
|
|
1118
|
+
if (connection) {
|
|
1119
|
+
const count = connection.totalCount ?? connection.nodes.length;
|
|
1120
|
+
return `${count} ${count === 1 ? "entry" : "entries"}`;
|
|
1121
|
+
}
|
|
1122
|
+
if (Array.isArray(value)) return value.length === 0 ? "none" : `${value.length} items`;
|
|
1123
|
+
if (isRecord(value)) {
|
|
1124
|
+
const label = value.name ?? value.sub ?? value.id;
|
|
1125
|
+
return label === void 0 ? "{\u2026}" : formatScalar(label);
|
|
1126
|
+
}
|
|
1127
|
+
return null;
|
|
1128
|
+
}
|
|
1129
|
+
function titleOf(record) {
|
|
1130
|
+
return typeof record.id === "string" && record.id !== "" ? record.id : null;
|
|
1131
|
+
}
|
|
1132
|
+
function formatRecord(record, indent, titled = false) {
|
|
1133
|
+
const title = titled ? titleOf(record) : null;
|
|
1134
|
+
const isFlatRows = (value) => Array.isArray(value) && value.length > 0 && value.every(isFlatRecord);
|
|
1135
|
+
const entries = Object.entries(record).filter(([key]) => key !== "__typename" && (title === null || key !== "id")).sort(([, a], [, b]) => Number(Array.isArray(a)) - Number(Array.isArray(b)));
|
|
1136
|
+
const width = Math.max(0, ...entries.map(([key]) => key.length));
|
|
1137
|
+
const valueIndent = `${indent}${"".padEnd(width)} `;
|
|
1138
|
+
const body = entries.map(([key, value]) => {
|
|
1139
|
+
const rendered = isFlatRows(value) ? formatFlatRows(value, valueIndent) : summarise(key, value) ?? formatScalar(value);
|
|
1140
|
+
return `${indent}${key.padEnd(width)} ${rendered}`;
|
|
1141
|
+
}).join("\n");
|
|
1142
|
+
return title === null ? body : `${indent.slice(INDENT.length)}${title}
|
|
1143
|
+
${body}`;
|
|
1144
|
+
}
|
|
1145
|
+
function formatFooter(connection) {
|
|
1146
|
+
const shown = connection.nodes.length;
|
|
1147
|
+
const total = connection.totalCount;
|
|
1148
|
+
const more = connection.pageInfo?.hasNextPage === true;
|
|
1149
|
+
if (total === void 0 && !more) return null;
|
|
1150
|
+
if (total !== void 0 && total === shown && !more) return null;
|
|
1151
|
+
const counted = total === void 0 ? `${shown}` : `${shown} of ${total}`;
|
|
1152
|
+
return more ? `${counted} \u2014 more available, pass --after ${connection.pageInfo?.endCursor}` : counted;
|
|
1153
|
+
}
|
|
1154
|
+
function formatConnectionExtras(connection) {
|
|
1155
|
+
return Object.entries(connection).filter(([key, value]) => !CONNECTION_PLUMBING2.has(key) && value != null).map(
|
|
1156
|
+
([key, value]) => isRecord(value) ? `${key}
|
|
1157
|
+
${formatRecord(value, INDENT)}` : `${key} ${formatScalar(value)}`
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
function formatResult(result) {
|
|
1161
|
+
const connection = asConnection(result);
|
|
1162
|
+
if (connection) {
|
|
1163
|
+
if (connection.nodes.length === 0) return "No results.";
|
|
1164
|
+
const blocks = connection.nodes.map(
|
|
1165
|
+
(node) => isRecord(node) ? formatRecord(node, INDENT, true) : `${INDENT}${formatScalar(node)}`
|
|
1166
|
+
);
|
|
1167
|
+
const tail = [formatFooter(connection), ...formatConnectionExtras(result)].filter(
|
|
1168
|
+
(part) => part !== null
|
|
1169
|
+
);
|
|
1170
|
+
return [blocks.join("\n\n"), ...tail].join("\n\n");
|
|
1171
|
+
}
|
|
1172
|
+
if (Array.isArray(result)) {
|
|
1173
|
+
if (result.length === 0) return "No results.";
|
|
1174
|
+
return result.map((item) => isRecord(item) ? formatRecord(item, INDENT, true) : formatScalar(item)).join("\n\n");
|
|
1175
|
+
}
|
|
1176
|
+
if (isRecord(result)) return formatRecord(result, "");
|
|
1177
|
+
return result === null || result === void 0 ? null : formatScalar(result);
|
|
686
1178
|
}
|
|
687
1179
|
|
|
688
1180
|
// src/commands/dynamic.ts
|
|
689
1181
|
var CONTEXT_FIELDS = {
|
|
690
|
-
companyId: "companyId"
|
|
691
|
-
oauthId: "oauthId"
|
|
1182
|
+
companyId: "companyId"
|
|
692
1183
|
};
|
|
693
1184
|
var SKIP_FIELDS = /* @__PURE__ */ new Set(["node", "nodes", "id", "_entities", "_service"]);
|
|
694
1185
|
function unwrap2(type) {
|
|
@@ -699,9 +1190,6 @@ function unwrap2(type) {
|
|
|
699
1190
|
function kebab(s) {
|
|
700
1191
|
return s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
|
701
1192
|
}
|
|
702
|
-
function ucfirst2(s) {
|
|
703
|
-
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
704
|
-
}
|
|
705
1193
|
function getInputFields(field) {
|
|
706
1194
|
if (field.args.length !== 1) return null;
|
|
707
1195
|
const arg = field.args[0];
|
|
@@ -726,7 +1214,41 @@ function isStructuredInput(type) {
|
|
|
726
1214
|
if (isListType2(type)) return true;
|
|
727
1215
|
return isInputObjectType(type);
|
|
728
1216
|
}
|
|
1217
|
+
function enumListOf(type) {
|
|
1218
|
+
const listless = isNonNullType2(type) ? type.ofType : type;
|
|
1219
|
+
if (!isListType2(listless)) return null;
|
|
1220
|
+
const inner = unwrap2(listless.ofType);
|
|
1221
|
+
return isEnumType2(inner) ? inner : null;
|
|
1222
|
+
}
|
|
1223
|
+
function commonPrefix(values) {
|
|
1224
|
+
if (values.length < 2) return "";
|
|
1225
|
+
let prefix = values[0];
|
|
1226
|
+
for (const value of values) while (!value.startsWith(prefix)) prefix = prefix.slice(0, -1);
|
|
1227
|
+
const cut = prefix.lastIndexOf("_");
|
|
1228
|
+
return cut === -1 ? "" : prefix.slice(0, cut + 1);
|
|
1229
|
+
}
|
|
1230
|
+
function coerceEnumList(raw, enumType, flagName) {
|
|
1231
|
+
const names = enumType.getValues().map((value) => value.name);
|
|
1232
|
+
if (raw.trim() === "all") return names;
|
|
1233
|
+
if (raw.trim() === "none") return [];
|
|
1234
|
+
const prefix = commonPrefix(names);
|
|
1235
|
+
return raw.split(",").filter((part) => part.trim() !== "").map((part) => {
|
|
1236
|
+
const wanted = part.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
|
|
1237
|
+
const match = names.find((name) => name === wanted || name === `${prefix}${wanted}`);
|
|
1238
|
+
if (match === void 0) {
|
|
1239
|
+
const short = names.map(
|
|
1240
|
+
(name) => name.slice(prefix.length).toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
|
|
1241
|
+
);
|
|
1242
|
+
throw new Error(
|
|
1243
|
+
`--${flagName} does not know "${part.trim()}". One or more of: ${short.join(", ")}, all, or none.`
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
return match;
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
729
1249
|
function coerceValue(raw, type, flagName) {
|
|
1250
|
+
const enumList = enumListOf(type);
|
|
1251
|
+
if (enumList && !raw.trim().startsWith("[")) return coerceEnumList(raw, enumList, flagName);
|
|
730
1252
|
if (isStructuredInput(type)) {
|
|
731
1253
|
try {
|
|
732
1254
|
return JSON.parse(raw);
|
|
@@ -830,7 +1352,10 @@ function describeArg(arg) {
|
|
|
830
1352
|
const parts = [];
|
|
831
1353
|
if (arg.description) parts.push(arg.description.replace(/\s+/g, " ").trim());
|
|
832
1354
|
const typeSig = renderType(arg.type);
|
|
833
|
-
|
|
1355
|
+
const enumList = enumListOf(arg.type);
|
|
1356
|
+
parts.push(
|
|
1357
|
+
enumList ? `${typeSig} (comma-separated, all, or none)` : isStructuredInput(arg.type) ? `${typeSig} (JSON)` : typeSig
|
|
1358
|
+
);
|
|
834
1359
|
const named = unwrap2(arg.type);
|
|
835
1360
|
const shape = describeStructuredType(named);
|
|
836
1361
|
if (shape) parts.push(shape);
|
|
@@ -839,7 +1364,7 @@ function describeArg(arg) {
|
|
|
839
1364
|
}
|
|
840
1365
|
return parts.join(" \u2014 ");
|
|
841
1366
|
}
|
|
842
|
-
function buildCommand(schema, fieldName, kind, description) {
|
|
1367
|
+
function buildCommand(schema, fieldName, kind, description, service) {
|
|
843
1368
|
const rootType = kind === "query" ? schema.getQueryType() : schema.getMutationType();
|
|
844
1369
|
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
845
1370
|
const field = rootType.getFields()[fieldName];
|
|
@@ -853,9 +1378,9 @@ function buildCommand(schema, fieldName, kind, description) {
|
|
|
853
1378
|
description: a.description
|
|
854
1379
|
}));
|
|
855
1380
|
const cmd = new Command2(kebab(fieldName)).description(description);
|
|
856
|
-
const
|
|
1381
|
+
const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
|
|
857
1382
|
for (const a of cliArgs) {
|
|
858
|
-
const placeholder = isStructuredInput(a.type) ? "json" : kebab(a.name);
|
|
1383
|
+
const placeholder = enumListOf(a.type) ? "a,b|all|none..." : isStructuredInput(a.type) ? "json" : kebab(a.name);
|
|
859
1384
|
const flag = `--${kebab(a.name)} <${placeholder}>`;
|
|
860
1385
|
const isContext = a.name in CONTEXT_FIELDS;
|
|
861
1386
|
if (isContext) {
|
|
@@ -869,25 +1394,20 @@ function buildCommand(schema, fieldName, kind, description) {
|
|
|
869
1394
|
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");
|
|
870
1395
|
cmd.action(async function() {
|
|
871
1396
|
const opts = this.optsWithGlobals();
|
|
872
|
-
const
|
|
873
|
-
const
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
error("No company selected.");
|
|
881
|
-
hint("Pass --company-id <id> or set one with `sl config set companyId <id>`.");
|
|
882
|
-
process.exit(2);
|
|
883
|
-
}
|
|
884
|
-
opts.companyId = resolved;
|
|
1397
|
+
const ctx = getUserContext();
|
|
1398
|
+
const acting = typeof opts.company === "string" ? opts.company : void 0;
|
|
1399
|
+
const actingId = await resolveCompanyId({ company: acting, ctx });
|
|
1400
|
+
const argumentCompanyId = typeof opts.companyId === "string" ? await resolveCompanyId({ company: opts.companyId, ctx }) : actingId;
|
|
1401
|
+
if (requiresCompanyId && !argumentCompanyId) {
|
|
1402
|
+
error("No company selected.");
|
|
1403
|
+
hint("Pass --company-id <slug|id>, or act for one with --company or `sl config set company <slug|id>`.");
|
|
1404
|
+
process.exit(2);
|
|
885
1405
|
}
|
|
1406
|
+
if (argumentCompanyId) opts.companyId = argumentCompanyId;
|
|
886
1407
|
const collectArgs = () => {
|
|
887
1408
|
const out = {};
|
|
888
1409
|
for (const a of cliArgs) {
|
|
889
|
-
const raw = opts[a.name];
|
|
890
|
-
const ctxProp = CONTEXT_FIELDS[a.name];
|
|
1410
|
+
const raw = Array.isArray(opts[a.name]) ? opts[a.name].join(",") : opts[a.name];
|
|
891
1411
|
if (raw != null) {
|
|
892
1412
|
try {
|
|
893
1413
|
out[a.name] = coerceValue(raw, a.type, kebab(a.name));
|
|
@@ -896,53 +1416,50 @@ function buildCommand(schema, fieldName, kind, description) {
|
|
|
896
1416
|
hint("Run the command with --help to see the expected shape of each argument.");
|
|
897
1417
|
process.exit(2);
|
|
898
1418
|
}
|
|
899
|
-
} else if (ctxProp && ctx) {
|
|
900
|
-
out[a.name] = ctx[ctxProp];
|
|
901
1419
|
}
|
|
902
1420
|
}
|
|
903
1421
|
return out;
|
|
904
1422
|
};
|
|
905
1423
|
const variables = useInputWrapper ? { input: collectArgs() } : collectArgs();
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
1424
|
+
let built;
|
|
1425
|
+
try {
|
|
1426
|
+
built = buildQuery(schema, kind, fieldName, variables, {
|
|
1427
|
+
depth: opts.depth,
|
|
1428
|
+
fields: opts.fields?.split(","),
|
|
1429
|
+
exclude: opts.exclude?.split(",")
|
|
1430
|
+
});
|
|
1431
|
+
} catch (buildError) {
|
|
1432
|
+
if (!(buildError instanceof UnknownFieldError)) throw buildError;
|
|
1433
|
+
error(buildError.message);
|
|
1434
|
+
hint(`Did you mean: ${buildError.suggestions.join(", ")}?`);
|
|
1435
|
+
process.exit(2);
|
|
1436
|
+
}
|
|
1437
|
+
const { query, fieldName: fName } = built;
|
|
1438
|
+
const data = await graphqlRaw(query, variables, {
|
|
1439
|
+
endpoint: opts.endpoint,
|
|
1440
|
+
company: acting,
|
|
1441
|
+
companyId: actingId,
|
|
1442
|
+
subgraph: service
|
|
910
1443
|
});
|
|
911
|
-
const data = await graphqlRaw(query, variables, { endpoint: opts.endpoint });
|
|
912
1444
|
const result = data[fName];
|
|
913
1445
|
if (result == null) {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
1446
|
+
if (actingAsApplication()) {
|
|
1447
|
+
info(`${fieldName} answers for people, and you are acting as an application.`);
|
|
1448
|
+
hint("`sl whoami` reports what the token identifies; `sl use me` switches back.");
|
|
1449
|
+
} else {
|
|
1450
|
+
warn("No results returned.");
|
|
1451
|
+
hint("The query succeeded but the server returned null.");
|
|
1452
|
+
hint("Try different arguments or check that the resource exists.");
|
|
1453
|
+
}
|
|
1454
|
+
} else if (isJsonMode(opts)) {
|
|
918
1455
|
printJson(result);
|
|
1456
|
+
} else {
|
|
1457
|
+
const rendered = formatResult(result);
|
|
1458
|
+
if (rendered !== null) info(rendered);
|
|
919
1459
|
}
|
|
920
1460
|
});
|
|
921
1461
|
return cmd;
|
|
922
1462
|
}
|
|
923
|
-
var useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
924
|
-
var ansi2 = {
|
|
925
|
-
reset: "\x1B[0m",
|
|
926
|
-
bold: "\x1B[1m",
|
|
927
|
-
dim: "\x1B[2m",
|
|
928
|
-
cyan: "\x1B[36m",
|
|
929
|
-
yellow: "\x1B[33m"
|
|
930
|
-
};
|
|
931
|
-
function formatCommandList(commands) {
|
|
932
|
-
if (commands.length === 0) return "";
|
|
933
|
-
const maxLen = Math.max(...commands.map((c2) => c2.name().length + (c2.options.length > 0 ? 10 : 0)));
|
|
934
|
-
const padWidth = Math.max(maxLen, 20);
|
|
935
|
-
return commands.map((c2) => {
|
|
936
|
-
const name = c2.options.length > 0 ? `${c2.name()} [options]` : c2.name();
|
|
937
|
-
const desc = c2.description();
|
|
938
|
-
const padding = " ".repeat(Math.max(2, padWidth - name.length + 2));
|
|
939
|
-
if (desc) {
|
|
940
|
-
return ` ${name}${padding}${desc}`;
|
|
941
|
-
}
|
|
942
|
-
const noDesc = useColor ? `${ansi2.yellow}No description provided${ansi2.reset}` : "No description provided";
|
|
943
|
-
return ` ${name}${padding}${noDesc}`;
|
|
944
|
-
}).join("\n");
|
|
945
|
-
}
|
|
946
1463
|
function deriveServiceMap(schema, fieldServices) {
|
|
947
1464
|
const map = /* @__PURE__ */ new Map();
|
|
948
1465
|
function ensure(service) {
|
|
@@ -972,80 +1489,53 @@ function deriveServiceMap(schema, fieldServices) {
|
|
|
972
1489
|
}
|
|
973
1490
|
return map;
|
|
974
1491
|
}
|
|
975
|
-
|
|
976
|
-
atlas: "Atlas service (contacts, orgs)",
|
|
977
|
-
marketplace: "Marketplace service",
|
|
978
|
-
hermes: "Hermes service"
|
|
979
|
-
};
|
|
980
|
-
function serviceDescription(service) {
|
|
981
|
-
return SERVICE_DESCRIPTIONS[service] ?? `${ucfirst2(service)} service operations`;
|
|
982
|
-
}
|
|
983
|
-
function buildServiceCommands(schema, fieldServices) {
|
|
1492
|
+
function buildOperationCommands(schema, fieldServices) {
|
|
984
1493
|
const serviceMap = deriveServiceMap(schema, fieldServices);
|
|
985
|
-
const
|
|
986
|
-
const
|
|
1494
|
+
const operations = [];
|
|
1495
|
+
const nameCounts = /* @__PURE__ */ new Map();
|
|
987
1496
|
for (const entry of serviceMap.values()) {
|
|
988
1497
|
for (const op of [...entry.queries, ...entry.mutations]) {
|
|
989
|
-
|
|
1498
|
+
nameCounts.set(op.fieldName, (nameCounts.get(op.fieldName) ?? 0) + 1);
|
|
990
1499
|
}
|
|
991
1500
|
}
|
|
992
1501
|
for (const [service, entry] of serviceMap) {
|
|
993
|
-
const
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
}
|
|
1007
|
-
for (const op of entry.mutations) {
|
|
1008
|
-
try {
|
|
1009
|
-
const cmd = buildCommand(schema, op.fieldName, "mutation", op.description);
|
|
1010
|
-
if ((allNames.get(op.fieldName) ?? 0) > 1) {
|
|
1011
|
-
cmd.name(`${kebab(op.fieldName)}-mutation`);
|
|
1502
|
+
const kinds = [
|
|
1503
|
+
{ kind: "query", ops: entry.queries },
|
|
1504
|
+
{ kind: "mutation", ops: entry.mutations }
|
|
1505
|
+
];
|
|
1506
|
+
for (const { kind, ops } of kinds) {
|
|
1507
|
+
for (const op of ops) {
|
|
1508
|
+
try {
|
|
1509
|
+
const command = buildCommand(schema, op.fieldName, kind, op.description, service);
|
|
1510
|
+
if ((nameCounts.get(op.fieldName) ?? 0) > 1) {
|
|
1511
|
+
command.name(`${kebab(op.fieldName)}-${kind}`);
|
|
1512
|
+
}
|
|
1513
|
+
operations.push({ command, fieldName: op.fieldName, kind, service });
|
|
1514
|
+
} catch {
|
|
1012
1515
|
}
|
|
1013
|
-
subCmd.addCommand(cmd, { hidden: true });
|
|
1014
|
-
mutationCommands.push(cmd);
|
|
1015
|
-
} catch {
|
|
1016
1516
|
}
|
|
1017
1517
|
}
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
lines.push(`Options:`);
|
|
1036
|
-
lines.push(` -h, --help display help for command
|
|
1037
|
-
`);
|
|
1038
|
-
return lines.join("\n");
|
|
1039
|
-
}
|
|
1040
|
-
});
|
|
1041
|
-
if (queryCommands.length > 0 || mutationCommands.length > 0) {
|
|
1042
|
-
commands.set(service, {
|
|
1043
|
-
command: subCmd,
|
|
1044
|
-
exampleQuery: queryCommands[0]?.name() ?? null
|
|
1045
|
-
});
|
|
1518
|
+
}
|
|
1519
|
+
return operations.sort((a, b) => a.command.name().localeCompare(b.command.name()));
|
|
1520
|
+
}
|
|
1521
|
+
function formatOperationList(operations, search) {
|
|
1522
|
+
const needle = search?.toLowerCase();
|
|
1523
|
+
const matching = needle ? operations.filter((op) => op.command.name().includes(needle) || op.service.toLowerCase().includes(needle)) : operations;
|
|
1524
|
+
if (matching.length === 0) {
|
|
1525
|
+
return search ? `No operation matching "${search}".` : "No operations available. The endpoint is not a composed supergraph, so no subgraph mapping is exposed.";
|
|
1526
|
+
}
|
|
1527
|
+
const lines = [];
|
|
1528
|
+
for (const kind of ["query", "mutation"]) {
|
|
1529
|
+
const group = matching.filter((op) => op.kind === kind);
|
|
1530
|
+
if (group.length === 0) continue;
|
|
1531
|
+
const width = Math.max(...group.map((op) => op.command.name().length));
|
|
1532
|
+
lines.push(`${kind === "query" ? "Queries" : "Mutations"}:`);
|
|
1533
|
+
for (const op of group) {
|
|
1534
|
+
lines.push(` ${op.command.name().padEnd(width)} ${op.service}`);
|
|
1046
1535
|
}
|
|
1536
|
+
lines.push("");
|
|
1047
1537
|
}
|
|
1048
|
-
return
|
|
1538
|
+
return lines.join("\n");
|
|
1049
1539
|
}
|
|
1050
1540
|
|
|
1051
1541
|
// src/commands/login.ts
|
|
@@ -1055,7 +1545,7 @@ import { Command as Command3 } from "commander";
|
|
|
1055
1545
|
var Me = gql(`
|
|
1056
1546
|
query Me {
|
|
1057
1547
|
me {
|
|
1058
|
-
|
|
1548
|
+
id
|
|
1059
1549
|
email
|
|
1060
1550
|
firstName
|
|
1061
1551
|
lastName
|
|
@@ -1096,11 +1586,20 @@ async function setupUserContext(endpoint) {
|
|
|
1096
1586
|
const userData = await graphql(Me, void 0, { endpoint });
|
|
1097
1587
|
const user = userData.me;
|
|
1098
1588
|
if (!user) return;
|
|
1099
|
-
saveConfig({ oauthId: user.sub ?? void 0 });
|
|
1100
1589
|
info("");
|
|
1101
1590
|
info(` User: ${user.firstName} ${user.lastName} <${user.email}>`);
|
|
1102
1591
|
hint("Run `sl whoami` to verify.");
|
|
1103
1592
|
}
|
|
1593
|
+
function reportScopeGrant(requestedScope, accessToken) {
|
|
1594
|
+
const missing = servicesWithoutScope(requestedScope, accessToken);
|
|
1595
|
+
if (missing.length === 0) return;
|
|
1596
|
+
warn(`No scope granted for: ${missing.join(", ")}.`);
|
|
1597
|
+
info(" Their commands will not appear in `sl --help`, and their fields are");
|
|
1598
|
+
info(" filtered out of the schema this CLI builds itself from.");
|
|
1599
|
+
hint("Auth0 grants requested scopes by exact string match against your assigned");
|
|
1600
|
+
hint("permissions and drops the rest silently \u2014 this is a role assignment in the");
|
|
1601
|
+
hint("tenant you logged into, not a CLI setting. Ask an administrator, then re-run `sl login`.");
|
|
1602
|
+
}
|
|
1104
1603
|
var loginCommand = new Command3("login").summary("Log in to your Sortlist account").description(
|
|
1105
1604
|
"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"
|
|
1106
1605
|
).option("--scope <scope>", "OAuth scope", DEFAULT_SCOPE).option("--no-browser", "Print the login URL instead of opening a browser").action(async function() {
|
|
@@ -1173,6 +1672,7 @@ var loginCommand = new Command3("login").summary("Log in to your Sortlist accoun
|
|
|
1173
1672
|
expiresAt: Math.floor(Date.now() / 1e3) + token.expiresIn
|
|
1174
1673
|
});
|
|
1175
1674
|
success("Logged in successfully.");
|
|
1675
|
+
reportScopeGrant(opts.scope, token.accessToken);
|
|
1176
1676
|
await setupUserContext(opts.endpoint);
|
|
1177
1677
|
return;
|
|
1178
1678
|
}
|
|
@@ -1190,7 +1690,9 @@ var logoutCommand = new Command4("logout").summary("Log out and remove stored cr
|
|
|
1190
1690
|
const opts = this.optsWithGlobals();
|
|
1191
1691
|
clearCredentials();
|
|
1192
1692
|
clearIdentity();
|
|
1693
|
+
const hadSession = clearApplicationSession();
|
|
1193
1694
|
success("Logged out \u2014 credentials removed.");
|
|
1695
|
+
if (hadSession) info("The application session was cleared too.");
|
|
1194
1696
|
if (!opts.browser) {
|
|
1195
1697
|
hint("Run `sl login` to authenticate again.");
|
|
1196
1698
|
return;
|
|
@@ -1209,9 +1711,28 @@ var logoutCommand = new Command4("logout").summary("Log out and remove stored cr
|
|
|
1209
1711
|
|
|
1210
1712
|
// src/commands/token.ts
|
|
1211
1713
|
import { Command as Command5 } from "commander";
|
|
1212
|
-
var tokenCommand = new Command5("token").summary("Print
|
|
1213
|
-
|
|
1214
|
-
|
|
1714
|
+
var tokenCommand = new Command5("token").summary("Print the current access token to stdout").description(
|
|
1715
|
+
`Print the current access token to stdout
|
|
1716
|
+
|
|
1717
|
+
Prints the application credential's token when SORTLIST_CLIENT_ID and
|
|
1718
|
+
SORTLIST_CLIENT_SECRET are set, and yours otherwise \u2014 matching what every
|
|
1719
|
+
other command authenticates as.
|
|
1720
|
+
|
|
1721
|
+
Examples:
|
|
1722
|
+
sl token Print the token
|
|
1723
|
+
curl -H "Authorization: Bearer $(sl token)" ...`
|
|
1724
|
+
).action(async () => {
|
|
1725
|
+
const machine = clientCredentials();
|
|
1726
|
+
if (machine) {
|
|
1727
|
+
try {
|
|
1728
|
+
process.stdout.write(await fetchClientCredentialsToken(machine));
|
|
1729
|
+
} catch (err) {
|
|
1730
|
+
error(err.message);
|
|
1731
|
+
hint("Check SORTLIST_CLIENT_ID, SORTLIST_CLIENT_SECRET and the token endpoint.");
|
|
1732
|
+
process.exit(2);
|
|
1733
|
+
}
|
|
1734
|
+
return;
|
|
1735
|
+
}
|
|
1215
1736
|
const creds = ensureAuthenticated();
|
|
1216
1737
|
if (isExpired(creds)) {
|
|
1217
1738
|
error("Your access token has expired.");
|
|
@@ -1221,12 +1742,141 @@ var tokenCommand = new Command5("token").summary("Print your current access toke
|
|
|
1221
1742
|
process.stdout.write(creds.accessToken);
|
|
1222
1743
|
});
|
|
1223
1744
|
|
|
1224
|
-
// src/commands/
|
|
1745
|
+
// src/commands/use.ts
|
|
1225
1746
|
import { Command as Command6 } from "commander";
|
|
1226
|
-
var
|
|
1227
|
-
|
|
1747
|
+
var CREATE = `
|
|
1748
|
+
mutation UseApplication($applicationId: ID!, $name: String!) {
|
|
1749
|
+
createApplicationCredential(input: { applicationId: $applicationId, name: $name, session: true }) {
|
|
1750
|
+
clientId
|
|
1751
|
+
clientSecret
|
|
1752
|
+
credential { id }
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
`;
|
|
1756
|
+
var REVOKE = `
|
|
1757
|
+
mutation ReleaseSessionCredential($credentialId: ID!) {
|
|
1758
|
+
revokeApplicationCredential(input: { credentialId: $credentialId }) { revokedAt }
|
|
1759
|
+
}
|
|
1760
|
+
`;
|
|
1761
|
+
var useCommand = new Command6("use").summary("Act as an application, or go back to acting as yourself").description(
|
|
1762
|
+
"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"
|
|
1763
|
+
);
|
|
1764
|
+
useCommand.command("application <id>").description("Act as an application for one token lifetime").action(async function(id) {
|
|
1765
|
+
const opts = this.optsWithGlobals();
|
|
1766
|
+
const asPerson = { endpoint: opts.endpoint, throwOnError: true, asPerson: true };
|
|
1767
|
+
let credential = null;
|
|
1768
|
+
try {
|
|
1769
|
+
const issued = await graphqlRaw(CREATE, { applicationId: id, name: sessionName() }, asPerson);
|
|
1770
|
+
credential = issued.createApplicationCredential;
|
|
1771
|
+
} catch (err) {
|
|
1772
|
+
error(`Could not create a session credential: ${err.message}`);
|
|
1773
|
+
hint("`sl applications` lists the applications you can manage.");
|
|
1774
|
+
process.exit(1);
|
|
1775
|
+
}
|
|
1776
|
+
if (!credential) {
|
|
1777
|
+
error("The server did not return a session credential.");
|
|
1778
|
+
hint("`sl applications` lists the applications you can manage.");
|
|
1779
|
+
process.exit(1);
|
|
1780
|
+
}
|
|
1781
|
+
let accessToken = null;
|
|
1782
|
+
try {
|
|
1783
|
+
accessToken = await fetchClientCredentialsToken({
|
|
1784
|
+
clientId: credential.clientId,
|
|
1785
|
+
clientSecret: credential.clientSecret
|
|
1786
|
+
});
|
|
1787
|
+
} catch (err) {
|
|
1788
|
+
error(`Could not exchange the credential for a token: ${err.message}`);
|
|
1789
|
+
hint("`sl config use-local` / `use-staging` / `use-production` set the token endpoint.");
|
|
1790
|
+
} finally {
|
|
1791
|
+
await graphqlRaw(REVOKE, { credentialId: credential.credential.id }, asPerson);
|
|
1792
|
+
}
|
|
1793
|
+
if (!accessToken) process.exit(2);
|
|
1794
|
+
const identity = applicationIdentity(accessToken);
|
|
1795
|
+
if (!identity) {
|
|
1796
|
+
error("The token endpoint returned something this CLI could not read.");
|
|
1797
|
+
process.exit(1);
|
|
1798
|
+
}
|
|
1799
|
+
saveApplicationSession({
|
|
1800
|
+
accessToken,
|
|
1801
|
+
applicationId: identity.applicationId,
|
|
1802
|
+
expiresAt: identity.expiresAt.getTime()
|
|
1803
|
+
});
|
|
1804
|
+
success(`Now acting as application ${identity.applicationId}`);
|
|
1805
|
+
info(` until ${identity.expiresAt.toISOString()}`);
|
|
1806
|
+
hint("The credential behind this token is already revoked, so nothing reusable is stored.");
|
|
1807
|
+
hint("Managing companies, applications and credentials is now out of reach: Hermes refuses");
|
|
1808
|
+
hint("its own tokens on its management API. Run `sl use me` to act as yourself again.");
|
|
1809
|
+
});
|
|
1810
|
+
useCommand.command("me").description("Go back to acting as yourself").action(() => {
|
|
1811
|
+
if (clearApplicationSession()) {
|
|
1812
|
+
success("Now acting as yourself again.");
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
info("Already acting as yourself.");
|
|
1816
|
+
});
|
|
1817
|
+
function sessionName() {
|
|
1818
|
+
return `cli-session-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replace(/[:T]/g, "")}`;
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
// src/commands/whoami.ts
|
|
1822
|
+
import { Command as Command7 } from "commander";
|
|
1823
|
+
var whoamiCommand = new Command7("whoami").summary("Show what the CLI is currently acting as").description(
|
|
1824
|
+
"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"
|
|
1228
1825
|
).action(async function() {
|
|
1229
1826
|
const opts = this.optsWithGlobals();
|
|
1827
|
+
const session = loadApplicationSession();
|
|
1828
|
+
if (session) {
|
|
1829
|
+
const identity = applicationIdentity(session.accessToken);
|
|
1830
|
+
if (isJsonMode(opts)) {
|
|
1831
|
+
printJson({ kind: "application", via: "session", ...identity });
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
info("Acting as an application.\n");
|
|
1835
|
+
info(
|
|
1836
|
+
formatResult({
|
|
1837
|
+
application: session.applicationId,
|
|
1838
|
+
"acts for company": identity?.companyId,
|
|
1839
|
+
subject: identity?.sub,
|
|
1840
|
+
"token expires": new Date(session.expiresAt).toISOString(),
|
|
1841
|
+
source: "sl use application \u2014 its credential is already revoked"
|
|
1842
|
+
}) ?? ""
|
|
1843
|
+
);
|
|
1844
|
+
hint("Run `sl use me` to act as yourself again.");
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
const machine = clientCredentials();
|
|
1848
|
+
if (machine) {
|
|
1849
|
+
let identity;
|
|
1850
|
+
try {
|
|
1851
|
+
identity = applicationIdentity(await fetchClientCredentialsToken(machine));
|
|
1852
|
+
} catch (err) {
|
|
1853
|
+
error(err.message);
|
|
1854
|
+
hint("Check SORTLIST_CLIENT_ID, SORTLIST_CLIENT_SECRET and the token endpoint.");
|
|
1855
|
+
process.exit(2);
|
|
1856
|
+
}
|
|
1857
|
+
if (!identity) {
|
|
1858
|
+
error("The token endpoint returned something this CLI could not read.");
|
|
1859
|
+
process.exit(1);
|
|
1860
|
+
}
|
|
1861
|
+
if (isJsonMode(opts)) {
|
|
1862
|
+
printJson({ kind: "application", clientId: machine.clientId, ...identity });
|
|
1863
|
+
return;
|
|
1864
|
+
}
|
|
1865
|
+
info("Acting as an application.\n");
|
|
1866
|
+
info(
|
|
1867
|
+
formatResult({
|
|
1868
|
+
application: identity.applicationId,
|
|
1869
|
+
"acts for company": identity.companyId,
|
|
1870
|
+
subject: identity.sub,
|
|
1871
|
+
credential: `${identity.credentialId} (${machine.clientId})`,
|
|
1872
|
+
"token expires": identity.expiresAt.toISOString(),
|
|
1873
|
+
source: "SORTLIST_CLIENT_ID / SORTLIST_CLIENT_SECRET"
|
|
1874
|
+
}) ?? ""
|
|
1875
|
+
);
|
|
1876
|
+
hint("A credential carries no scopes, so scoped data stays out of reach.");
|
|
1877
|
+
hint("Unset both variables to act as yourself again.");
|
|
1878
|
+
return;
|
|
1879
|
+
}
|
|
1230
1880
|
let data;
|
|
1231
1881
|
try {
|
|
1232
1882
|
data = await graphql(Me, void 0, {
|
|
@@ -1252,29 +1902,36 @@ var whoamiCommand = new Command6("whoami").summary("Show who you're currently lo
|
|
|
1252
1902
|
process.exit(1);
|
|
1253
1903
|
}
|
|
1254
1904
|
if (isJsonMode(opts)) {
|
|
1255
|
-
printJson(user);
|
|
1905
|
+
printJson({ kind: "person", ...user });
|
|
1256
1906
|
return;
|
|
1257
1907
|
}
|
|
1258
|
-
info(
|
|
1908
|
+
info("Acting as yourself.\n");
|
|
1909
|
+
info(
|
|
1910
|
+
formatResult({
|
|
1911
|
+
name: [user.firstName, user.lastName].filter(Boolean).join(" ") || null,
|
|
1912
|
+
email: user.email,
|
|
1913
|
+
id: user.id
|
|
1914
|
+
}) ?? ""
|
|
1915
|
+
);
|
|
1259
1916
|
});
|
|
1260
1917
|
|
|
1261
1918
|
// src/graphql/introspection.ts
|
|
1262
1919
|
import { createHash } from "crypto";
|
|
1263
|
-
import
|
|
1264
|
-
import
|
|
1265
|
-
import
|
|
1920
|
+
import fs6 from "fs";
|
|
1921
|
+
import os4 from "os";
|
|
1922
|
+
import path6 from "path";
|
|
1266
1923
|
import { buildClientSchema, getIntrospectionQuery } from "graphql";
|
|
1267
|
-
var CACHE_DIR =
|
|
1268
|
-
var CACHE_PATH =
|
|
1924
|
+
var CACHE_DIR = path6.join(os4.homedir(), ".sortlist");
|
|
1925
|
+
var CACHE_PATH = path6.join(CACHE_DIR, "schema.json");
|
|
1269
1926
|
var CACHE_TTL_MS = 60 * 60 * 1e3;
|
|
1270
|
-
var
|
|
1927
|
+
var cached2 = null;
|
|
1271
1928
|
function tokenFingerprint(token) {
|
|
1272
1929
|
if (!token) return "anonymous";
|
|
1273
1930
|
return createHash("sha256").update(token).digest("hex").slice(0, 16);
|
|
1274
1931
|
}
|
|
1275
1932
|
function readCache(endpoint, token) {
|
|
1276
1933
|
try {
|
|
1277
|
-
const text =
|
|
1934
|
+
const text = fs6.readFileSync(CACHE_PATH, "utf-8");
|
|
1278
1935
|
const envelope = JSON.parse(text);
|
|
1279
1936
|
if (envelope.endpoint !== endpoint) return null;
|
|
1280
1937
|
if (envelope.tokenFingerprint !== tokenFingerprint(token)) return null;
|
|
@@ -1287,8 +1944,8 @@ function readCache(endpoint, token) {
|
|
|
1287
1944
|
}
|
|
1288
1945
|
function writeCache(endpoint, token, introspection, raw) {
|
|
1289
1946
|
try {
|
|
1290
|
-
if (!
|
|
1291
|
-
|
|
1947
|
+
if (!fs6.existsSync(CACHE_DIR)) {
|
|
1948
|
+
fs6.mkdirSync(CACHE_DIR, { recursive: true });
|
|
1292
1949
|
}
|
|
1293
1950
|
const envelope = {
|
|
1294
1951
|
endpoint,
|
|
@@ -1297,7 +1954,7 @@ function writeCache(endpoint, token, introspection, raw) {
|
|
|
1297
1954
|
introspection,
|
|
1298
1955
|
raw
|
|
1299
1956
|
};
|
|
1300
|
-
|
|
1957
|
+
fs6.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
|
|
1301
1958
|
} catch {
|
|
1302
1959
|
}
|
|
1303
1960
|
}
|
|
@@ -1347,46 +2004,58 @@ function currentAccessToken() {
|
|
|
1347
2004
|
return loadCredentials()?.accessToken ?? null;
|
|
1348
2005
|
}
|
|
1349
2006
|
async function getIntrospectedSchema(endpointOverride2) {
|
|
1350
|
-
if (
|
|
2007
|
+
if (cached2) return cached2;
|
|
1351
2008
|
const endpoint = getEndpoint(endpointOverride2);
|
|
1352
2009
|
const token = currentAccessToken();
|
|
1353
2010
|
const fromCache = readCache(endpoint, token);
|
|
1354
2011
|
if (fromCache) {
|
|
1355
|
-
const
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
return cached;
|
|
2012
|
+
const usable = build(fromCache.introspection, fromCache.raw);
|
|
2013
|
+
if (usable) {
|
|
2014
|
+
cached2 = usable;
|
|
2015
|
+
return cached2;
|
|
2016
|
+
}
|
|
2017
|
+
discardCache();
|
|
1362
2018
|
}
|
|
1363
2019
|
const { introspection, raw } = await fetchIntrospection(endpoint, token);
|
|
2020
|
+
const built = build(introspection, raw);
|
|
2021
|
+
if (!built) {
|
|
2022
|
+
throw new Error(
|
|
2023
|
+
"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."
|
|
2024
|
+
);
|
|
2025
|
+
}
|
|
1364
2026
|
writeCache(endpoint, token, introspection, raw);
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
schema: buildClientSchema(introspection),
|
|
1368
|
-
fieldServices,
|
|
1369
|
-
services
|
|
1370
|
-
};
|
|
1371
|
-
return cached;
|
|
2027
|
+
cached2 = built;
|
|
2028
|
+
return cached2;
|
|
1372
2029
|
}
|
|
1373
|
-
|
|
1374
|
-
cached = null;
|
|
2030
|
+
function build(introspection, raw) {
|
|
1375
2031
|
try {
|
|
1376
|
-
|
|
2032
|
+
const { fieldServices, services } = parseIntrospection(raw);
|
|
2033
|
+
return { schema: buildClientSchema(introspection), fieldServices, services };
|
|
1377
2034
|
} catch {
|
|
2035
|
+
return null;
|
|
1378
2036
|
}
|
|
2037
|
+
}
|
|
2038
|
+
function discardCache() {
|
|
2039
|
+
try {
|
|
2040
|
+
fs6.unlinkSync(CACHE_PATH);
|
|
2041
|
+
} catch {
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
async function refreshSchema(endpointOverride2) {
|
|
2045
|
+
cached2 = null;
|
|
2046
|
+
discardCache();
|
|
1379
2047
|
const endpoint = getEndpoint(endpointOverride2);
|
|
1380
2048
|
const token = currentAccessToken();
|
|
1381
2049
|
const { introspection, raw } = await fetchIntrospection(endpoint, token);
|
|
2050
|
+
const built = build(introspection, raw);
|
|
2051
|
+
if (!built) {
|
|
2052
|
+
throw new Error(
|
|
2053
|
+
"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."
|
|
2054
|
+
);
|
|
2055
|
+
}
|
|
1382
2056
|
writeCache(endpoint, token, introspection, raw);
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
schema: buildClientSchema(introspection),
|
|
1386
|
-
fieldServices,
|
|
1387
|
-
services
|
|
1388
|
-
};
|
|
1389
|
-
return cached;
|
|
2057
|
+
cached2 = built;
|
|
2058
|
+
return cached2;
|
|
1390
2059
|
}
|
|
1391
2060
|
|
|
1392
2061
|
// src/lib/version-check.ts
|
|
@@ -1456,8 +2125,8 @@ async function checkForUpdates() {
|
|
|
1456
2125
|
|
|
1457
2126
|
// src/index.ts
|
|
1458
2127
|
initSentry();
|
|
1459
|
-
var
|
|
1460
|
-
var
|
|
2128
|
+
var useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
2129
|
+
var ansi2 = {
|
|
1461
2130
|
reset: "\x1B[0m",
|
|
1462
2131
|
bold: "\x1B[1m",
|
|
1463
2132
|
dim: "\x1B[2m",
|
|
@@ -1466,10 +2135,10 @@ var ansi3 = {
|
|
|
1466
2135
|
green: "\x1B[32m"
|
|
1467
2136
|
};
|
|
1468
2137
|
function colorizeHelp(text) {
|
|
1469
|
-
if (!
|
|
2138
|
+
if (!useColor) return text;
|
|
1470
2139
|
return text.replace(
|
|
1471
2140
|
/^(Usage|Options|Commands|Arguments|Quick start|Services|Examples|Queries|Mutations):(.*)$/gm,
|
|
1472
|
-
`${
|
|
2141
|
+
`${ansi2.cyan}${ansi2.bold}$1:$2${ansi2.reset}`
|
|
1473
2142
|
);
|
|
1474
2143
|
}
|
|
1475
2144
|
var colorOutput = {
|
|
@@ -1483,35 +2152,33 @@ function applyColorToAllCommands(cmd) {
|
|
|
1483
2152
|
}
|
|
1484
2153
|
}
|
|
1485
2154
|
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";
|
|
1486
|
-
function buildRootDescription(
|
|
2155
|
+
function buildRootDescription(operationCount) {
|
|
1487
2156
|
const parts = [BASE_DESCRIPTION];
|
|
1488
|
-
if (
|
|
1489
|
-
const entries = [...services.entries()];
|
|
1490
|
-
const labels = entries.map(([name]) => `sl ${name} <operation>`);
|
|
1491
|
-
const pad = Math.max(...labels.map((l) => l.length));
|
|
2157
|
+
if (operationCount > 0) {
|
|
1492
2158
|
parts.push(
|
|
1493
|
-
|
|
2159
|
+
`Every federation operation is a command (${operationCount} available).
|
|
2160
|
+
Operation names are unique across the supergraph, so they are not namespaced:
|
|
2161
|
+
sl operations List them all
|
|
2162
|
+
sl operations --search company
|
|
2163
|
+
sl <operation> --help Flags for one operation`
|
|
2164
|
+
);
|
|
2165
|
+
parts.push(
|
|
2166
|
+
"Examples:\n sl organizations --limit 5\n sl create-application --name continuous-integration\n sl config show"
|
|
1494
2167
|
);
|
|
1495
|
-
const examples = [];
|
|
1496
|
-
for (const [name, info2] of entries) {
|
|
1497
|
-
if (info2.exampleQuery) examples.push(` sl ${name} ${info2.exampleQuery}`);
|
|
1498
|
-
if (examples.length >= 2) break;
|
|
1499
|
-
}
|
|
1500
|
-
examples.push(" sl config show View current endpoint and agency context");
|
|
1501
|
-
parts.push("Examples:\n" + examples.join("\n"));
|
|
1502
2168
|
}
|
|
1503
2169
|
return parts.join("\n\n");
|
|
1504
2170
|
}
|
|
1505
|
-
var program = new
|
|
2171
|
+
var program = new Command8().name("sl").configureOutput({
|
|
1506
2172
|
writeOut: (str) => process.stdout.write(colorizeHelp(str)),
|
|
1507
2173
|
writeErr: (str) => process.stderr.write(colorizeHelp(str))
|
|
1508
|
-
}).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");
|
|
2174
|
+
}).description(BASE_DESCRIPTION).version(pkg.version).option("--endpoint <url>", "Override the federation endpoint URL").option("--company <slug|id>", "Act for this company, by slug or id; must be one you belong to").option("--json", "Output as JSON (auto-enabled when stdout is not a TTY)").option("--no-color", "Disable colored output");
|
|
1509
2175
|
program.addCommand(loginCommand);
|
|
1510
2176
|
program.addCommand(logoutCommand);
|
|
1511
2177
|
program.addCommand(whoamiCommand);
|
|
1512
2178
|
program.addCommand(tokenCommand);
|
|
2179
|
+
program.addCommand(useCommand);
|
|
1513
2180
|
program.addCommand(configCommand);
|
|
1514
|
-
var schemaCommand = new
|
|
2181
|
+
var schemaCommand = new Command8("schema").description("Manage the cached GraphQL schema");
|
|
1515
2182
|
schemaCommand.command("refresh").description("Force-refresh the cached schema from the federation endpoint").action(async function() {
|
|
1516
2183
|
const opts = this.optsWithGlobals();
|
|
1517
2184
|
try {
|
|
@@ -1546,20 +2213,19 @@ var endpointIdx = process.argv.indexOf("--endpoint");
|
|
|
1546
2213
|
var endpointOverride = endpointIdx !== -1 ? process.argv[endpointIdx + 1] : void 0;
|
|
1547
2214
|
try {
|
|
1548
2215
|
const { schema, fieldServices } = await getIntrospectedSchema(endpointOverride);
|
|
1549
|
-
const
|
|
1550
|
-
const
|
|
1551
|
-
|
|
1552
|
-
const cmd = entry.command;
|
|
1553
|
-
program.addCommand(cmd);
|
|
1554
|
-
servicesForHelp.set(name, {
|
|
1555
|
-
exampleQuery: entry.exampleQuery,
|
|
1556
|
-
description: cmd.description()
|
|
1557
|
-
});
|
|
2216
|
+
const operations = buildOperationCommands(schema, fieldServices);
|
|
2217
|
+
for (const operation of operations) {
|
|
2218
|
+
program.addCommand(operation.command, { hidden: true });
|
|
1558
2219
|
}
|
|
1559
|
-
|
|
2220
|
+
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() {
|
|
2221
|
+
info(formatOperationList(operations, this.opts().search));
|
|
2222
|
+
});
|
|
2223
|
+
program.addCommand(operationsCommand);
|
|
2224
|
+
program.description(buildRootDescription(operations.length));
|
|
1560
2225
|
} catch (err) {
|
|
1561
2226
|
const message = err.message;
|
|
1562
|
-
|
|
2227
|
+
const offline = ["login", "logout", "config", "token", "whoami", "schema"];
|
|
2228
|
+
if (!process.argv.some((a) => offline.includes(a))) {
|
|
1563
2229
|
error(`Could not fetch schema: ${message}`);
|
|
1564
2230
|
hint("Check your network connection and endpoint: sl config show");
|
|
1565
2231
|
hint("You can still use: sl login, sl config, sl schema refresh");
|