@sortlist/cli 0.37.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/dist/index.js +736 -339
- 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,46 +173,60 @@ 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 { companyId: config.companyId };
|
|
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
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"
|
|
182
232
|
);
|
|
@@ -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.companyId) info(`Company ID:
|
|
239
|
+
info(`Endpoint: ${config.endpoint}`);
|
|
240
|
+
if (config.tokenEndpoint) info(`Token endpoint: ${config.tokenEndpoint}`);
|
|
241
|
+
if (config.companyId) info(`Company ID: ${config.companyId}`);
|
|
192
242
|
}
|
|
193
243
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if (!
|
|
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)) {
|
|
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,63 @@ import {
|
|
|
245
290
|
// src/graphql/client.ts
|
|
246
291
|
import { print } from "graphql";
|
|
247
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
|
+
|
|
248
350
|
// src/lib/sentry.ts
|
|
249
351
|
import * as Sentry from "@sentry/node";
|
|
250
352
|
var SENTRY_DSN = "https://306d2e4389b8baa0bf14e587c2ceff04@o27611.ingest.us.sentry.io/4511229468409856";
|
|
@@ -304,7 +406,7 @@ async function flushSentry(timeout = 2e3) {
|
|
|
304
406
|
}
|
|
305
407
|
|
|
306
408
|
// 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": "
|
|
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" } }] } }] } }] };
|
|
308
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" } }] } }] };
|
|
309
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" } }] } }] } }] };
|
|
310
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" } }] } }] } }] };
|
|
@@ -312,7 +414,7 @@ var RefreshTokenDocument = { "kind": "Document", "definitions": [{ "kind": "Oper
|
|
|
312
414
|
|
|
313
415
|
// src/graphql/generated/gql.ts
|
|
314
416
|
var documents = {
|
|
315
|
-
"\n query Me {\n me {\n
|
|
417
|
+
"\n query Me {\n me {\n id\n email\n firstName\n lastName\n }\n }\n": MeDocument,
|
|
316
418
|
"\n query LogoutUrl {\n logoutUrl\n }\n": LogoutUrlDocument,
|
|
317
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,
|
|
318
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,
|
|
@@ -403,119 +505,230 @@ async function refreshAccessToken(creds, endpoint) {
|
|
|
403
505
|
saveCredentials(newCreds);
|
|
404
506
|
return newCreds;
|
|
405
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
|
+
}
|
|
406
676
|
async function executeQuery(query, variables, options = {}) {
|
|
407
|
-
const endpoint = getEndpoint(options.endpoint);
|
|
408
677
|
const authenticated = options.authenticated ?? true;
|
|
409
|
-
const
|
|
410
|
-
|
|
411
|
-
|
|
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
|
+
};
|
|
412
684
|
addBreadcrumb2({
|
|
413
685
|
category: "graphql",
|
|
414
|
-
message: operationName,
|
|
415
|
-
data: { endpoint, authenticated },
|
|
686
|
+
message: attempt.operationName,
|
|
687
|
+
data: { endpoint: attempt.endpoint, authenticated },
|
|
416
688
|
level: "info"
|
|
417
689
|
});
|
|
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
|
-
}
|
|
690
|
+
if (attempt.verbose) logRequest(query, variables, attempt);
|
|
426
691
|
const headers = {
|
|
427
692
|
"Content-Type": "application/json",
|
|
428
693
|
"X-API-Client": "sl-cli"
|
|
429
694
|
};
|
|
430
695
|
if (authenticated) {
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
if (!refreshed) {
|
|
435
|
-
if (throwOnError) {
|
|
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
|
-
}
|
|
696
|
+
const { token, kind } = await resolveAccessToken(options, attempt);
|
|
697
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
698
|
+
if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
|
|
448
699
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
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
|
|
460
712
|
});
|
|
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
713
|
}
|
|
714
|
+
if (!res.ok) reportHttpFailure(res, await res.text(), attempt);
|
|
474
715
|
const json = await res.json();
|
|
475
716
|
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) {
|
|
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)) {
|
|
509
721
|
hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
|
|
510
|
-
hint(`Example: sl ${operationName.toLowerCase()} --fields id,title,status`);
|
|
511
722
|
}
|
|
512
|
-
|
|
723
|
+
return json.data;
|
|
513
724
|
}
|
|
514
725
|
if (!json.data) {
|
|
515
|
-
if (throwOnError) {
|
|
516
|
-
throw new GraphQLRequestError(`${operationName}: no data returned from API.`, {
|
|
726
|
+
if (attempt.throwOnError) {
|
|
727
|
+
throw new GraphQLRequestError(`${attempt.operationName}: no data returned from API.`, {
|
|
728
|
+
operationName: attempt.operationName
|
|
729
|
+
});
|
|
517
730
|
}
|
|
518
|
-
error(`${operationName}: no data returned from API.`);
|
|
731
|
+
error(`${attempt.operationName}: no data returned from API.`);
|
|
519
732
|
hint("This usually means the server returned an empty response.");
|
|
520
733
|
hint("Verify your endpoint: sl config show");
|
|
521
734
|
process.exit(1);
|
|
@@ -685,10 +898,76 @@ function resolveCompanyId(opts) {
|
|
|
685
898
|
return opts.companyId || opts.ctx?.companyId;
|
|
686
899
|
}
|
|
687
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
|
+
|
|
688
968
|
// src/commands/dynamic.ts
|
|
689
969
|
var CONTEXT_FIELDS = {
|
|
690
|
-
companyId: "companyId"
|
|
691
|
-
oauthId: "oauthId"
|
|
970
|
+
companyId: "companyId"
|
|
692
971
|
};
|
|
693
972
|
var SKIP_FIELDS = /* @__PURE__ */ new Set(["node", "nodes", "id", "_entities", "_service"]);
|
|
694
973
|
function unwrap2(type) {
|
|
@@ -699,9 +978,6 @@ function unwrap2(type) {
|
|
|
699
978
|
function kebab(s) {
|
|
700
979
|
return s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
|
701
980
|
}
|
|
702
|
-
function ucfirst2(s) {
|
|
703
|
-
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
704
|
-
}
|
|
705
981
|
function getInputFields(field) {
|
|
706
982
|
if (field.args.length !== 1) return null;
|
|
707
983
|
const arg = field.args[0];
|
|
@@ -839,7 +1115,7 @@ function describeArg(arg) {
|
|
|
839
1115
|
}
|
|
840
1116
|
return parts.join(" \u2014 ");
|
|
841
1117
|
}
|
|
842
|
-
function buildCommand(schema, fieldName, kind, description) {
|
|
1118
|
+
function buildCommand(schema, fieldName, kind, description, service) {
|
|
843
1119
|
const rootType = kind === "query" ? schema.getQueryType() : schema.getMutationType();
|
|
844
1120
|
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
845
1121
|
const field = rootType.getFields()[fieldName];
|
|
@@ -853,7 +1129,7 @@ function buildCommand(schema, fieldName, kind, description) {
|
|
|
853
1129
|
description: a.description
|
|
854
1130
|
}));
|
|
855
1131
|
const cmd = new Command2(kebab(fieldName)).description(description);
|
|
856
|
-
const
|
|
1132
|
+
const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
|
|
857
1133
|
for (const a of cliArgs) {
|
|
858
1134
|
const placeholder = isStructuredInput(a.type) ? "json" : kebab(a.name);
|
|
859
1135
|
const flag = `--${kebab(a.name)} <${placeholder}>`;
|
|
@@ -871,18 +1147,16 @@ function buildCommand(schema, fieldName, kind, description) {
|
|
|
871
1147
|
const opts = this.optsWithGlobals();
|
|
872
1148
|
const needsContext = cliArgs.some((a) => a.name in CONTEXT_FIELDS);
|
|
873
1149
|
const ctx = needsContext ? getUserContext() : void 0;
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
process.exit(2);
|
|
883
|
-
}
|
|
884
|
-
opts.companyId = resolved;
|
|
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);
|
|
885
1158
|
}
|
|
1159
|
+
if (resolvedCompanyId) opts.companyId = resolvedCompanyId;
|
|
886
1160
|
const collectArgs = () => {
|
|
887
1161
|
const out = {};
|
|
888
1162
|
for (const a of cliArgs) {
|
|
@@ -908,41 +1182,26 @@ function buildCommand(schema, fieldName, kind, description) {
|
|
|
908
1182
|
fields: opts.fields?.split(","),
|
|
909
1183
|
exclude: opts.exclude?.split(",")
|
|
910
1184
|
});
|
|
911
|
-
const data = await graphqlRaw(query, variables, { endpoint: opts.endpoint });
|
|
1185
|
+
const data = await graphqlRaw(query, variables, { endpoint: opts.endpoint, subgraph: service });
|
|
912
1186
|
const result = data[fName];
|
|
913
1187
|
if (result == null) {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
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)) {
|
|
918
1197
|
printJson(result);
|
|
1198
|
+
} else {
|
|
1199
|
+
const rendered = formatResult(result);
|
|
1200
|
+
if (rendered !== null) info(rendered);
|
|
919
1201
|
}
|
|
920
1202
|
});
|
|
921
1203
|
return cmd;
|
|
922
1204
|
}
|
|
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
1205
|
function deriveServiceMap(schema, fieldServices) {
|
|
947
1206
|
const map = /* @__PURE__ */ new Map();
|
|
948
1207
|
function ensure(service) {
|
|
@@ -972,80 +1231,53 @@ function deriveServiceMap(schema, fieldServices) {
|
|
|
972
1231
|
}
|
|
973
1232
|
return map;
|
|
974
1233
|
}
|
|
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) {
|
|
1234
|
+
function buildOperationCommands(schema, fieldServices) {
|
|
984
1235
|
const serviceMap = deriveServiceMap(schema, fieldServices);
|
|
985
|
-
const
|
|
986
|
-
const
|
|
1236
|
+
const operations = [];
|
|
1237
|
+
const nameCounts = /* @__PURE__ */ new Map();
|
|
987
1238
|
for (const entry of serviceMap.values()) {
|
|
988
1239
|
for (const op of [...entry.queries, ...entry.mutations]) {
|
|
989
|
-
|
|
1240
|
+
nameCounts.set(op.fieldName, (nameCounts.get(op.fieldName) ?? 0) + 1);
|
|
990
1241
|
}
|
|
991
1242
|
}
|
|
992
1243
|
for (const [service, entry] of serviceMap) {
|
|
993
|
-
const
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
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 {
|
|
1001
1257
|
}
|
|
1002
|
-
subCmd.addCommand(cmd, { hidden: true });
|
|
1003
|
-
queryCommands.push(cmd);
|
|
1004
|
-
} catch {
|
|
1005
1258
|
}
|
|
1006
1259
|
}
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
`);
|
|
1025
|
-
if (queryCommands.length > 0) {
|
|
1026
|
-
lines.push(`Queries:`);
|
|
1027
|
-
lines.push(formatCommandList(queryCommands));
|
|
1028
|
-
lines.push("");
|
|
1029
|
-
}
|
|
1030
|
-
if (mutationCommands.length > 0) {
|
|
1031
|
-
lines.push(`Mutations:`);
|
|
1032
|
-
lines.push(formatCommandList(mutationCommands));
|
|
1033
|
-
lines.push("");
|
|
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
|
-
});
|
|
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}`);
|
|
1046
1277
|
}
|
|
1278
|
+
lines.push("");
|
|
1047
1279
|
}
|
|
1048
|
-
return
|
|
1280
|
+
return lines.join("\n");
|
|
1049
1281
|
}
|
|
1050
1282
|
|
|
1051
1283
|
// src/commands/login.ts
|
|
@@ -1055,7 +1287,7 @@ import { Command as Command3 } from "commander";
|
|
|
1055
1287
|
var Me = gql(`
|
|
1056
1288
|
query Me {
|
|
1057
1289
|
me {
|
|
1058
|
-
|
|
1290
|
+
id
|
|
1059
1291
|
email
|
|
1060
1292
|
firstName
|
|
1061
1293
|
lastName
|
|
@@ -1096,7 +1328,6 @@ async function setupUserContext(endpoint) {
|
|
|
1096
1328
|
const userData = await graphql(Me, void 0, { endpoint });
|
|
1097
1329
|
const user = userData.me;
|
|
1098
1330
|
if (!user) return;
|
|
1099
|
-
saveConfig({ oauthId: user.sub ?? void 0 });
|
|
1100
1331
|
info("");
|
|
1101
1332
|
info(` User: ${user.firstName} ${user.lastName} <${user.email}>`);
|
|
1102
1333
|
hint("Run `sl whoami` to verify.");
|
|
@@ -1190,7 +1421,9 @@ var logoutCommand = new Command4("logout").summary("Log out and remove stored cr
|
|
|
1190
1421
|
const opts = this.optsWithGlobals();
|
|
1191
1422
|
clearCredentials();
|
|
1192
1423
|
clearIdentity();
|
|
1424
|
+
const hadSession = clearApplicationSession();
|
|
1193
1425
|
success("Logged out \u2014 credentials removed.");
|
|
1426
|
+
if (hadSession) info("The application session was cleared too.");
|
|
1194
1427
|
if (!opts.browser) {
|
|
1195
1428
|
hint("Run `sl login` to authenticate again.");
|
|
1196
1429
|
return;
|
|
@@ -1209,9 +1442,28 @@ var logoutCommand = new Command4("logout").summary("Log out and remove stored cr
|
|
|
1209
1442
|
|
|
1210
1443
|
// src/commands/token.ts
|
|
1211
1444
|
import { Command as Command5 } from "commander";
|
|
1212
|
-
var tokenCommand = new Command5("token").summary("Print
|
|
1213
|
-
|
|
1214
|
-
|
|
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
|
+
}
|
|
1215
1467
|
const creds = ensureAuthenticated();
|
|
1216
1468
|
if (isExpired(creds)) {
|
|
1217
1469
|
error("Your access token has expired.");
|
|
@@ -1221,12 +1473,141 @@ var tokenCommand = new Command5("token").summary("Print your current access toke
|
|
|
1221
1473
|
process.stdout.write(creds.accessToken);
|
|
1222
1474
|
});
|
|
1223
1475
|
|
|
1224
|
-
// src/commands/
|
|
1476
|
+
// src/commands/use.ts
|
|
1225
1477
|
import { Command as Command6 } from "commander";
|
|
1226
|
-
var
|
|
1227
|
-
|
|
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"
|
|
1228
1556
|
).action(async function() {
|
|
1229
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
|
+
}
|
|
1230
1611
|
let data;
|
|
1231
1612
|
try {
|
|
1232
1613
|
data = await graphql(Me, void 0, {
|
|
@@ -1252,29 +1633,36 @@ var whoamiCommand = new Command6("whoami").summary("Show who you're currently lo
|
|
|
1252
1633
|
process.exit(1);
|
|
1253
1634
|
}
|
|
1254
1635
|
if (isJsonMode(opts)) {
|
|
1255
|
-
printJson(user);
|
|
1636
|
+
printJson({ kind: "person", ...user });
|
|
1256
1637
|
return;
|
|
1257
1638
|
}
|
|
1258
|
-
info(
|
|
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
|
+
);
|
|
1259
1647
|
});
|
|
1260
1648
|
|
|
1261
1649
|
// src/graphql/introspection.ts
|
|
1262
1650
|
import { createHash } from "crypto";
|
|
1263
|
-
import
|
|
1264
|
-
import
|
|
1265
|
-
import
|
|
1651
|
+
import fs6 from "fs";
|
|
1652
|
+
import os4 from "os";
|
|
1653
|
+
import path6 from "path";
|
|
1266
1654
|
import { buildClientSchema, getIntrospectionQuery } from "graphql";
|
|
1267
|
-
var CACHE_DIR =
|
|
1268
|
-
var CACHE_PATH =
|
|
1655
|
+
var CACHE_DIR = path6.join(os4.homedir(), ".sortlist");
|
|
1656
|
+
var CACHE_PATH = path6.join(CACHE_DIR, "schema.json");
|
|
1269
1657
|
var CACHE_TTL_MS = 60 * 60 * 1e3;
|
|
1270
|
-
var
|
|
1658
|
+
var cached2 = null;
|
|
1271
1659
|
function tokenFingerprint(token) {
|
|
1272
1660
|
if (!token) return "anonymous";
|
|
1273
1661
|
return createHash("sha256").update(token).digest("hex").slice(0, 16);
|
|
1274
1662
|
}
|
|
1275
1663
|
function readCache(endpoint, token) {
|
|
1276
1664
|
try {
|
|
1277
|
-
const text =
|
|
1665
|
+
const text = fs6.readFileSync(CACHE_PATH, "utf-8");
|
|
1278
1666
|
const envelope = JSON.parse(text);
|
|
1279
1667
|
if (envelope.endpoint !== endpoint) return null;
|
|
1280
1668
|
if (envelope.tokenFingerprint !== tokenFingerprint(token)) return null;
|
|
@@ -1287,8 +1675,8 @@ function readCache(endpoint, token) {
|
|
|
1287
1675
|
}
|
|
1288
1676
|
function writeCache(endpoint, token, introspection, raw) {
|
|
1289
1677
|
try {
|
|
1290
|
-
if (!
|
|
1291
|
-
|
|
1678
|
+
if (!fs6.existsSync(CACHE_DIR)) {
|
|
1679
|
+
fs6.mkdirSync(CACHE_DIR, { recursive: true });
|
|
1292
1680
|
}
|
|
1293
1681
|
const envelope = {
|
|
1294
1682
|
endpoint,
|
|
@@ -1297,7 +1685,7 @@ function writeCache(endpoint, token, introspection, raw) {
|
|
|
1297
1685
|
introspection,
|
|
1298
1686
|
raw
|
|
1299
1687
|
};
|
|
1300
|
-
|
|
1688
|
+
fs6.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
|
|
1301
1689
|
} catch {
|
|
1302
1690
|
}
|
|
1303
1691
|
}
|
|
@@ -1347,46 +1735,58 @@ function currentAccessToken() {
|
|
|
1347
1735
|
return loadCredentials()?.accessToken ?? null;
|
|
1348
1736
|
}
|
|
1349
1737
|
async function getIntrospectedSchema(endpointOverride2) {
|
|
1350
|
-
if (
|
|
1738
|
+
if (cached2) return cached2;
|
|
1351
1739
|
const endpoint = getEndpoint(endpointOverride2);
|
|
1352
1740
|
const token = currentAccessToken();
|
|
1353
1741
|
const fromCache = readCache(endpoint, token);
|
|
1354
1742
|
if (fromCache) {
|
|
1355
|
-
const
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
return cached;
|
|
1743
|
+
const usable = build(fromCache.introspection, fromCache.raw);
|
|
1744
|
+
if (usable) {
|
|
1745
|
+
cached2 = usable;
|
|
1746
|
+
return cached2;
|
|
1747
|
+
}
|
|
1748
|
+
discardCache();
|
|
1362
1749
|
}
|
|
1363
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
|
+
}
|
|
1364
1757
|
writeCache(endpoint, token, introspection, raw);
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
schema: buildClientSchema(introspection),
|
|
1368
|
-
fieldServices,
|
|
1369
|
-
services
|
|
1370
|
-
};
|
|
1371
|
-
return cached;
|
|
1758
|
+
cached2 = built;
|
|
1759
|
+
return cached2;
|
|
1372
1760
|
}
|
|
1373
|
-
|
|
1374
|
-
|
|
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() {
|
|
1375
1770
|
try {
|
|
1376
|
-
|
|
1771
|
+
fs6.unlinkSync(CACHE_PATH);
|
|
1377
1772
|
} catch {
|
|
1378
1773
|
}
|
|
1774
|
+
}
|
|
1775
|
+
async function refreshSchema(endpointOverride2) {
|
|
1776
|
+
cached2 = null;
|
|
1777
|
+
discardCache();
|
|
1379
1778
|
const endpoint = getEndpoint(endpointOverride2);
|
|
1380
1779
|
const token = currentAccessToken();
|
|
1381
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
|
+
}
|
|
1382
1787
|
writeCache(endpoint, token, introspection, raw);
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
schema: buildClientSchema(introspection),
|
|
1386
|
-
fieldServices,
|
|
1387
|
-
services
|
|
1388
|
-
};
|
|
1389
|
-
return cached;
|
|
1788
|
+
cached2 = built;
|
|
1789
|
+
return cached2;
|
|
1390
1790
|
}
|
|
1391
1791
|
|
|
1392
1792
|
// src/lib/version-check.ts
|
|
@@ -1456,8 +1856,8 @@ async function checkForUpdates() {
|
|
|
1456
1856
|
|
|
1457
1857
|
// src/index.ts
|
|
1458
1858
|
initSentry();
|
|
1459
|
-
var
|
|
1460
|
-
var
|
|
1859
|
+
var useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
1860
|
+
var ansi2 = {
|
|
1461
1861
|
reset: "\x1B[0m",
|
|
1462
1862
|
bold: "\x1B[1m",
|
|
1463
1863
|
dim: "\x1B[2m",
|
|
@@ -1466,10 +1866,10 @@ var ansi3 = {
|
|
|
1466
1866
|
green: "\x1B[32m"
|
|
1467
1867
|
};
|
|
1468
1868
|
function colorizeHelp(text) {
|
|
1469
|
-
if (!
|
|
1869
|
+
if (!useColor) return text;
|
|
1470
1870
|
return text.replace(
|
|
1471
1871
|
/^(Usage|Options|Commands|Arguments|Quick start|Services|Examples|Queries|Mutations):(.*)$/gm,
|
|
1472
|
-
`${
|
|
1872
|
+
`${ansi2.cyan}${ansi2.bold}$1:$2${ansi2.reset}`
|
|
1473
1873
|
);
|
|
1474
1874
|
}
|
|
1475
1875
|
var colorOutput = {
|
|
@@ -1483,26 +1883,23 @@ function applyColorToAllCommands(cmd) {
|
|
|
1483
1883
|
}
|
|
1484
1884
|
}
|
|
1485
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";
|
|
1486
|
-
function buildRootDescription(
|
|
1886
|
+
function buildRootDescription(operationCount) {
|
|
1487
1887
|
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));
|
|
1888
|
+
if (operationCount > 0) {
|
|
1492
1889
|
parts.push(
|
|
1493
|
-
|
|
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"
|
|
1494
1898
|
);
|
|
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
1899
|
}
|
|
1503
1900
|
return parts.join("\n\n");
|
|
1504
1901
|
}
|
|
1505
|
-
var program = new
|
|
1902
|
+
var program = new Command8().name("sl").configureOutput({
|
|
1506
1903
|
writeOut: (str) => process.stdout.write(colorizeHelp(str)),
|
|
1507
1904
|
writeErr: (str) => process.stderr.write(colorizeHelp(str))
|
|
1508
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");
|
|
@@ -1510,8 +1907,9 @@ program.addCommand(loginCommand);
|
|
|
1510
1907
|
program.addCommand(logoutCommand);
|
|
1511
1908
|
program.addCommand(whoamiCommand);
|
|
1512
1909
|
program.addCommand(tokenCommand);
|
|
1910
|
+
program.addCommand(useCommand);
|
|
1513
1911
|
program.addCommand(configCommand);
|
|
1514
|
-
var schemaCommand = new
|
|
1912
|
+
var schemaCommand = new Command8("schema").description("Manage the cached GraphQL schema");
|
|
1515
1913
|
schemaCommand.command("refresh").description("Force-refresh the cached schema from the federation endpoint").action(async function() {
|
|
1516
1914
|
const opts = this.optsWithGlobals();
|
|
1517
1915
|
try {
|
|
@@ -1546,20 +1944,19 @@ var endpointIdx = process.argv.indexOf("--endpoint");
|
|
|
1546
1944
|
var endpointOverride = endpointIdx !== -1 ? process.argv[endpointIdx + 1] : void 0;
|
|
1547
1945
|
try {
|
|
1548
1946
|
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
|
-
});
|
|
1947
|
+
const operations = buildOperationCommands(schema, fieldServices);
|
|
1948
|
+
for (const operation of operations) {
|
|
1949
|
+
program.addCommand(operation.command, { hidden: true });
|
|
1558
1950
|
}
|
|
1559
|
-
|
|
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));
|
|
1560
1956
|
} catch (err) {
|
|
1561
1957
|
const message = err.message;
|
|
1562
|
-
|
|
1958
|
+
const offline = ["login", "logout", "config", "token", "whoami", "schema"];
|
|
1959
|
+
if (!process.argv.some((a) => offline.includes(a))) {
|
|
1563
1960
|
error(`Could not fetch schema: ${message}`);
|
|
1564
1961
|
hint("Check your network connection and endpoint: sl config show");
|
|
1565
1962
|
hint("You can still use: sl login, sl config, sl schema refresh");
|