@future-unknown/known 0.0.0-stage → 0.2.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.
@@ -0,0 +1,68 @@
1
+ require("@colors/colors")
2
+ const config = require("../config")
3
+ const output = require("../output")
4
+ const { accountLabel } = require("../helpers")
5
+
6
+ function age(session) {
7
+ if (!session.created_at) return "signed in"
8
+ return "signed in " + output.timeAgo(new Date(session.created_at))
9
+ }
10
+
11
+ function health(session) {
12
+ if (!session.expires_at) return null
13
+ const live = new Date(session.expires_at).getTime() > Date.now()
14
+ if (live) return null
15
+ return session.refresh_token ? "token stale" : "expired"
16
+ }
17
+
18
+ // Render every session on the machine, grouped by the environment it belongs to.
19
+ // There is no "current" environment to highlight — a session's endpoint travels
20
+ // with its token, and `--org` picks both at once.
21
+ function render() {
22
+ const envs = config.listEnvironments()
23
+
24
+ if (output.isJson()) {
25
+ return output.data({
26
+ environments: envs.map((env) => ({
27
+ endpoint: env.endpoint,
28
+ alias: env.alias,
29
+ sessions: env.sessions.map((s) => ({
30
+ label: s.label,
31
+ org: s.key,
32
+ org_id: (s.org && s.org.id) || null,
33
+ org_name: (s.org && s.org.name) || null,
34
+ account: accountLabel(s.account),
35
+ role: s.role || null,
36
+ created_at: s.created_at || null,
37
+ expires_at: s.expires_at || null
38
+ }))
39
+ }))
40
+ })
41
+ }
42
+
43
+ if (!envs.length) {
44
+ return output.info("not signed in — run `known login`".grey)
45
+ }
46
+
47
+ console.log()
48
+ let first = true
49
+ for (const env of envs) {
50
+ if (!first) console.log()
51
+ first = false
52
+ console.log((" " + env.endpoint + (env.alias ? " (" + env.alias + ")" : "")).green)
53
+
54
+ const width = env.sessions.reduce((w, s) => Math.max(w, s.key.length), 0)
55
+ for (const s of env.sessions) {
56
+ const gap = " ".repeat(width - s.key.length + 3)
57
+ const detail = [accountLabel(s.account), s.role, age(s), health(s)].filter(Boolean).join(" · ")
58
+ console.log(" " + s.key + gap + detail.grey)
59
+ }
60
+ }
61
+ console.log()
62
+ }
63
+
64
+ module.exports = function (argv) {
65
+ render()
66
+ process.exit(0)
67
+ }
68
+ module.exports.render = render
@@ -0,0 +1,300 @@
1
+ require("@colors/colors")
2
+ const output = require("../output")
3
+ const { getClient, sessionFor, confirm, run, unwrap } = require("../helpers")
4
+
5
+ /**
6
+ * `known <org> sites` — the sites that sign the org's people in with Known.
7
+ *
8
+ * A site belongs to a wiki, its home (`--wiki`): whoever can read that wiki
9
+ * may sign in, and its admins and the org's owners add, change and remove the
10
+ * site. It has a name, a client id, the exact redirect URIs a sign-in may
11
+ * return to, the addresses it is published at, the wikis attached to it — its
12
+ * home and any others — and where its code lives (`--source`, shown only to
13
+ * whoever manages the site: one of the org's code trees, `code:<tree>`, which
14
+ * must exist, or a repository's address, never checked; with no `--source`, a
15
+ * new site gets a tree of its short name). A site whose source is a code tree
16
+ * publishes it (`publish`) to its own address, `<site>-<org>` on Known's site
17
+ * domain; `--change` publishes an earlier change, to roll back. Attaching
18
+ * another wiki is that wiki's admins' (and org owners') business: for writing
19
+ * — the site does there what the person signed in may, pages and records —
20
+ * unless `--read` attaches it read-only; attaching again with `--read` or
21
+ * `--write` switches it. The home stays attached: `update --wiki` moves it.
22
+ *
23
+ * known acme sites
24
+ * known acme sites create "Capital" --wiki capital
25
+ * known acme sites create "Capital" --wiki capital --read --redirect https://capital.known.vision/callback
26
+ * known acme sites update capital --wiki deals
27
+ * known acme sites update capital --source code:capital
28
+ * known acme sites update capital --source "$(git remote get-url origin)"
29
+ * known acme sites update capital --no-source
30
+ * known acme sites publish capital
31
+ * known acme sites publish capital --change 4
32
+ * known acme sites attach capital labs
33
+ * known acme sites attach capital board --read
34
+ * known acme sites detach capital labs
35
+ * known acme sites rm capital
36
+ *
37
+ * A site is named by its short name — its name lowercased, accents dropped,
38
+ * other characters made hyphens ("Deal Flow" is deal-flow), unique in the
39
+ * org — or by its client id.
40
+ */
41
+ const verbs = { list, get, create, update, publish, rm, attach, detach }
42
+
43
+ module.exports = function (argv, ref, rest) {
44
+ const verb = rest && rest[0]
45
+ if (argv.help) return showMenu(ref)
46
+ if (!verb) return list(argv, ref, [])
47
+ const handler = verbs[verb]
48
+ if (!handler) {
49
+ output.info(require("../helpers").unknownCommand("sites", verb, Object.keys(verbs)).grey)
50
+ return showMenu(ref)
51
+ }
52
+ return handler(argv, ref, rest.slice(1))
53
+ }
54
+
55
+ function showMenu(ref) {
56
+ const org = ref || "<org>"
57
+ console.log()
58
+ console.log(" known ".cyan + org.cyan + " sites".cyan + " sites that sign the org's people in with Known".grey)
59
+ console.log()
60
+ output.commands([
61
+ [org + " sites", "the org's sites — their home wikis, where they are published, the wikis they read (read, or read and write), client ids; name one by its short name or client id"],
62
+ [org + " sites get <site>", "one site in full"],
63
+ [org + " sites create <name> --wiki <wiki>", "add a site to a wiki, its home: whoever reads the wiki may sign in (--read for read-only; --redirect <uri>, --site <origin>, repeatable; --source code:<tree> or a repository's address, else a tree of its short name)"],
64
+ [org + " sites update <site>", "change it (--name, --redirect, --site, --source, --no-source, or --wiki to move its home, --read if it doesn't read that wiki yet and should only read)"],
65
+ [org + " sites publish <site>", "publish its code tree (source code:<tree>) at its address; --change <id> publishes an earlier change, to roll back"],
66
+ [org + " sites rm <site>", "remove it; its sign-ins and tokens stop at once"],
67
+ [org + " sites attach <site> <wiki>", "let the site work in a wiki as the person signed in: read and write, or read only with --read; --write switches back (its admins or an org owner)"],
68
+ [org + " sites detach <site> <wiki>", "take a wiki away from the site (never its home)"]
69
+ ])
70
+ console.log()
71
+ process.exit(0)
72
+ }
73
+
74
+ // ---- verbs -----------------------------------------------------------------
75
+
76
+ function list(argv, ref) {
77
+ return run(async () => {
78
+ const session = sessionFor(argv, ref)
79
+ const client = getClient(argv, { session })
80
+ const sites = unwrap(await client.site.list({}))
81
+ if (output.isJson()) return output.data(sites)
82
+ if (!sites.length) return output.info("no sites yet — `known " + ref + " sites create <name> --wiki <wiki>`".grey)
83
+ const orgName = orgNameOf(session)
84
+ const names = await namesFor(client, sites)
85
+ output.cards(sites.map((site) => card(site, names)), {
86
+ heading: (orgName + " · " + sites.length + (sites.length === 1 ? " site" : " sites")).bold,
87
+ footer: [
88
+ "One in full: known " + ref + " sites get <site>",
89
+ "Attach a wiki: known " + ref + " sites attach <site> <wiki>"
90
+ ]
91
+ })
92
+ })
93
+ }
94
+
95
+ function get(argv, ref, rest) {
96
+ return run(async () => {
97
+ const id = siteRef(rest[0], "get")
98
+ const session = sessionFor(argv, ref)
99
+ const client = getClient(argv, { session })
100
+ await show(unwrap(await client.site.get({ id })), client)
101
+ })
102
+ }
103
+
104
+ function create(argv, ref, rest) {
105
+ return run(async () => {
106
+ const name = rest[0]
107
+ if (!name || !String(name).trim()) throw friendly("name the site — `known <org> sites create <name> --wiki <wiki>`")
108
+ if (!argv.wiki || argv.wiki === true) throw friendly("a site belongs to a wiki — `known <org> sites create <name> --wiki <wiki>`")
109
+ const fields = changes(argv)
110
+ const session = sessionFor(argv, ref)
111
+ const site = unwrap(await getClient(argv, { session }).site.create({ name: String(name), ...fields }))
112
+ if (output.isJson()) return output.data(site)
113
+ output.status("created", site.name, (site.slug ? site.slug + " · " : "") + site.clientId)
114
+ })
115
+ }
116
+
117
+ function update(argv, ref, rest) {
118
+ return run(async () => {
119
+ const id = siteRef(rest[0], "update")
120
+ const fields = changes(argv)
121
+ if (argv.name !== undefined) fields.name = String(argv.name)
122
+ if (!Object.keys(fields).length) throw friendly("nothing to change — pass --name, --redirect, --site, --source, or --wiki")
123
+ const session = sessionFor(argv, ref)
124
+ const client = getClient(argv, { session })
125
+ await show(unwrap(await client.site.update({ id, ...fields })), client)
126
+ })
127
+ }
128
+
129
+ function publish(argv, ref, rest) {
130
+ return run(async () => {
131
+ const id = siteRef(rest[0], "publish")
132
+ const params = { id }
133
+ if (argv.change !== undefined) {
134
+ const change = Number(argv.change)
135
+ if (!Number.isInteger(change) || change < 1) throw friendly("--change takes a change number, as `known <org> code changes <tree>:` lists them")
136
+ params.changeId = change
137
+ }
138
+ const session = sessionFor(argv, ref)
139
+ const site = unwrap(await getClient(argv, { session }).site.publish(params))
140
+ if (output.isJson()) return output.data(site)
141
+ const was = site.previous ? " (was change " + site.previous.changeId + ")" : ""
142
+ output.status("published", site.name, "change " + site.published.changeId + " is live at " + site.published.url + was)
143
+ })
144
+ }
145
+
146
+ function rm(argv, ref, rest) {
147
+ return run(async () => {
148
+ const id = siteRef(rest[0], "rm")
149
+ const session = sessionFor(argv, ref)
150
+ const client = getClient(argv, { session })
151
+ const site = unwrap(await client.site.get({ id }))
152
+ if (!(await confirm("Remove " + site.name + "? Everyone signed in to it is signed out.", argv))) {
153
+ return output.info("left as it was".grey)
154
+ }
155
+ const res = unwrap(await client.site.remove({ id }))
156
+ if (output.isJson()) return output.data(res)
157
+ output.status("removed", site.name, id)
158
+ })
159
+ }
160
+
161
+ function attach(argv, ref, rest) {
162
+ return run(async () => {
163
+ const id = siteRef(rest[0], "attach")
164
+ const wiki = wikiName(rest[1], "attach")
165
+ if (argv.read && argv.write) throw friendly("pass --read or --write, not both")
166
+ const params = { id, wiki }
167
+ if (argv.read) params.capabilities = ["read"]
168
+ if (argv.write) params.capabilities = ["read", "write"]
169
+ const session = sessionFor(argv, ref)
170
+ const client = getClient(argv, { session })
171
+ const site = unwrap(await client.site.attach(params))
172
+ if (output.isJson()) return output.data(site)
173
+ const attached = (site.wikis || []).find((entry) => entry.name === wiki)
174
+ const writes = attached && attached.capabilities.includes("write")
175
+ output.status("attached", wiki, "to " + site.name + (attached ? (writes ? " for reading and writing" : " read-only") : ""))
176
+ })
177
+ }
178
+
179
+ function detach(argv, ref, rest) {
180
+ return run(async () => {
181
+ const id = siteRef(rest[0], "detach")
182
+ const wiki = wikiName(rest[1], "detach")
183
+ const session = sessionFor(argv, ref)
184
+ const site = unwrap(await getClient(argv, { session }).site.detach({ id, wiki }))
185
+ if (output.isJson()) return output.data(site)
186
+ output.status("detached", wiki, "from " + site.name)
187
+ })
188
+ }
189
+
190
+ // ---- helpers ---------------------------------------------------------------
191
+
192
+ const WIKI_NAME = /^[a-z0-9][a-z0-9-]*$/
193
+
194
+ function friendly(message) {
195
+ const e = new Error(message)
196
+ e.friendly = true
197
+ return e
198
+ }
199
+
200
+ // A site by its short name (deal-flow) or its client id (app_…).
201
+ function siteRef(value, verb) {
202
+ if (value === undefined || value === true || !String(value).trim()) {
203
+ throw friendly("name the site — `known <org> sites " + verb + " <site>`, by its short name or client id")
204
+ }
205
+ return String(value)
206
+ }
207
+
208
+ function wikiName(value, verb) {
209
+ if (!value || !WIKI_NAME.test(String(value))) {
210
+ throw friendly("name the wiki — `known <org> sites " + verb + " <site> <wiki>`")
211
+ }
212
+ return String(value)
213
+ }
214
+
215
+ // Who may use a site follows its home wiki, so --user and --everyone are
216
+ // gone, and say so rather than pass unnoticed. --wiki names its home.
217
+ // Redirect URIs and addresses replace the site's list when given. --source says where the code lives (one of the
218
+ // org's code trees, code:<tree>, or an https URL or ssh address, as
219
+ // `git remote get-url` prints it); --no-source (or an empty --source "")
220
+ // clears it.
221
+ function changes(argv) {
222
+ const out = {}
223
+ if (argv.redirect !== undefined) out.redirectUris = [].concat(argv.redirect).map(String)
224
+ if (argv.site !== undefined) out.sites = [].concat(argv.site).map(String)
225
+ if (argv.user !== undefined || argv.everyone) throw friendly("who may use a site follows its home wiki — grant people the wiki: `known <org> wiki grant`")
226
+ if (argv.wiki !== undefined) {
227
+ if (argv.read && argv.write) throw friendly("--read or --write, not both")
228
+ out.wiki = String(argv.wiki)
229
+ if (argv.read) out.capabilities = ["read"]
230
+ }
231
+ if (argv.source !== undefined) out.source = sourceFlag(argv.source)
232
+ return out
233
+ }
234
+
235
+ function sourceFlag(value) {
236
+ if (value === false || value === "") return null
237
+ if (value === true) throw friendly("--source takes where the site's code lives, e.g. code:capital, https://github.com/acme/capital or git@github.com:acme/capital.git")
238
+ return String(value)
239
+ }
240
+
241
+ // A site as a box (output.cards): its name, and what the caller may do with
242
+ // it, in the top border; its client id; then its home and what it reads;
243
+ // then how it is wired — where sign-ins return, where its code lives,
244
+ // who registered it.
245
+ function card(app, names) {
246
+ return {
247
+ title: app.name.cyan.bold,
248
+ aside: app.manage ? "you manage".grey : app.mayUse ? "you may use".grey : "not open to you".yellow,
249
+ fields: [
250
+ ["short name", app.slug],
251
+ ["client id", app.clientId],
252
+ null,
253
+ ["live", app.published ? host(app.published.url) + (" · change " + app.published.changeId + " · " + output.timeAgo(new Date(app.published.publishedAt))).grey : null],
254
+ ["published", (app.sites || []).map(host)],
255
+ // no home: it reads no wiki, or none this reader may see
256
+ ["home", app.homeWiki || null],
257
+ ["wikis", aligned((app.wikis || []).map((wiki) => [wiki.name, wiki.capabilities.join(", ")]))],
258
+ null,
259
+ ["returns to", app.redirectUris || []],
260
+ // only those who manage the site are told where its code lives
261
+ ...(app.source !== undefined ? [["source", app.source ? host(app.source) : null]] : []),
262
+ ["registered", app.createdAt ? output.timeAgo(new Date(app.createdAt)) + (app.createdBy ? " by " + (names.people[app.createdBy] || app.createdBy) : "") : null]
263
+ ]
264
+ }
265
+ }
266
+
267
+ // Pairs as two columns, the second greyed: "capital read".
268
+ function aligned(pairs) {
269
+ const width = pairs.reduce((w, [left]) => Math.max(w, left.length), 0)
270
+ return pairs.map(([left, right]) => left + " ".repeat(width - left.length + 2) + String(right).grey)
271
+ }
272
+
273
+ // An address without its scheme or trailing slash, as people say it:
274
+ // https://github.com/acme/site → github.com/acme/site.
275
+ function host(address) {
276
+ return String(address).replace(/^[a-z]+:\/\//, "").replace(/\/$/, "")
277
+ }
278
+
279
+ function orgNameOf(session) {
280
+ return (session.org && (session.org.name || session.org.slug)) || "the organization"
281
+ }
282
+
283
+ // The people behind the ids a site names (who registered it). Best-effort:
284
+ // without an answer the ids print as themselves.
285
+ async function namesFor(client, apps) {
286
+ const people = {}
287
+ const ids = [...new Set(apps.map((app) => app.createdBy).filter(Boolean))]
288
+ if (ids.length) {
289
+ try {
290
+ const answer = unwrap(await client.actors.resolve({ ids }))
291
+ for (const [id, actor] of Object.entries(answer.actors || {})) if (actor && actor.name) people[id] = actor.name
292
+ } catch (e) {}
293
+ }
294
+ return { people }
295
+ }
296
+
297
+ async function show(app, client) {
298
+ if (output.isJson()) return output.data(app)
299
+ output.cards([card(app, await namesFor(client, [app]))])
300
+ }
@@ -0,0 +1,269 @@
1
+ require("@colors/colors")
2
+ const output = require("../output")
3
+ const { getClient, sessionFor, confirmByName, run, unwrap, actorNames, person, friendly } = require("../helpers")
4
+
5
+ /**
6
+ * `known <org> teams` — the org's teams.
7
+ *
8
+ * A team is some of the org's people under a short name (its slug), with a
9
+ * name and a description. Its point is the wikis it is granted: a grant to a
10
+ * team (`wiki grant labs team:<slug>:write`) follows its roster, so joining a
11
+ * team opens its wikis and leaving closes them. On a team a person is a
12
+ * member or a maintainer.
13
+ *
14
+ * Every member of the org sees every team, creates one (and is its first
15
+ * maintainer; an org owner keeps every team already, and is not put on one by
16
+ * creating it), and leaves any they are on. A team's maintainers and the
17
+ * org's owners rename it and change its roster; org owners delete teams.
18
+ *
19
+ * known acme teams
20
+ * known acme teams get design
21
+ * known acme teams create "Design" --description "Brand, product and web"
22
+ * known acme teams update design --name "Design studio"
23
+ * known acme teams add design @ada
24
+ * known acme teams maintainer design @ada
25
+ * known acme teams maintainer design @ada --off
26
+ * known acme teams remove design ada@acme.com
27
+ * known acme teams leave design
28
+ * known acme teams delete design --confirm design
29
+ *
30
+ * A team is named by its slug or its id (team_…); a person by user id,
31
+ * @handle, or email address.
32
+ */
33
+ const verbs = { list, get, create, update, delete: destroy, add, remove, maintainer, leave }
34
+
35
+ module.exports = function (argv, ref, rest) {
36
+ const verb = rest && rest[0]
37
+ if (argv.help) return showMenu(ref)
38
+ if (!verb) return list(argv, ref, [])
39
+ const handler = verbs[verb]
40
+ if (!handler) {
41
+ output.info(require("../helpers").unknownCommand("teams", verb, Object.keys(verbs)).grey)
42
+ return showMenu(ref)
43
+ }
44
+ return handler(argv, ref, rest.slice(1))
45
+ }
46
+
47
+ // Bare (`known teams`), the org comes from the project binding, so the menu
48
+ // drops the org from every invocation.
49
+ function showMenu(ref) {
50
+ const org = ref ? ref + " " : ""
51
+ console.log()
52
+ console.log((" known " + org + "teams").cyan + " the org's teams — people grouped to be granted wikis together".grey)
53
+ console.log()
54
+ output.commands([
55
+ [org + "teams", "the org's teams — their people, and whether you are on each"],
56
+ [org + "teams get <slug>", "one team: its people with their roles (member, maintainer) and the wikis it reaches"],
57
+ [org + "teams create <name>", "create a team (--description); its slug is the name lowercased and hyphenated; any member, who maintains it"],
58
+ [org + "teams update <slug>", "rename or describe it (--name, --description; its maintainers and org owners)"],
59
+ [org + "teams delete <slug>", "delete it and its grants on wikis — type its slug, or --confirm <slug> (org owners)"],
60
+ [org + "teams add <slug> <person>", "put a member of the org on the team (its maintainers and org owners)"],
61
+ [org + "teams remove <slug> <person>", "take someone off the team"],
62
+ [org + "teams maintainer <slug> <person>", "make someone on the team a maintainer; --off makes them a member again"],
63
+ [org + "teams leave <slug>", "leave a team you are on"]
64
+ ])
65
+ console.log()
66
+ process.exit(0)
67
+ }
68
+
69
+ // ---- verbs -----------------------------------------------------------------
70
+
71
+ function list(argv, ref) {
72
+ return run(async () => {
73
+ const session = sessionFor(argv, ref)
74
+ const teams = unwrap(await getClient(argv, { session }).team.list({}))
75
+ if (output.isJson()) return output.data(teams)
76
+ const me = session.account && session.account.id
77
+ output.table(teams.map((team) => {
78
+ const seat = (team.members || []).find((member) => member.userId === me)
79
+ return {
80
+ team: team.slug.cyan,
81
+ name: team.title,
82
+ people: String((team.members || []).length),
83
+ wikis: String((team.wikis || []).length),
84
+ you: seat ? roleOf(seat) : "",
85
+ about: team.description ? clamp(team.description) : "—".grey
86
+ }
87
+ }))
88
+ })
89
+ }
90
+
91
+ // One team in full: its roster, each person with their role, and the wikis
92
+ // it is granted, as the API answers them: those the caller can see, so a
93
+ // restricted wiki hidden from them is not named here either.
94
+ function get(argv, ref, rest) {
95
+ return run(async () => {
96
+ const params = teamRef(rest[0], "get <slug>")
97
+ const session = sessionFor(argv, ref)
98
+ const client = getClient(argv, { session })
99
+ const team = unwrap(await client.team.get(params))
100
+ const wikis = team.wikis || []
101
+ if (output.isJson()) return output.data(team)
102
+ const me = session.account && session.account.id
103
+ const seat = team.members.find((member) => member.userId === me)
104
+ const by = await actorNames(client, [...team.members.map((member) => ({ id: member.userId })), { id: team.createdBy }])
105
+ output.cards([{
106
+ title: team.slug.cyan.bold,
107
+ aside: (seat && seat.maintainer ? "you maintain" : team.maintainer ? "you may change it (org owner)" : seat ? "you are on it" : "").grey,
108
+ body: team.description || "No description yet.",
109
+ muted: !team.description,
110
+ fields: [
111
+ ["name", team.title],
112
+ ["id", team.id],
113
+ null,
114
+ ["people", aligned(team.members.map((member) => [by({ id: member.userId }), roleOf(member)]))],
115
+ ["wikis", aligned(wikis.map((wiki) => [wiki.name, wiki.level]))],
116
+ null,
117
+ ["created", team.createdAt ? output.timeAgo(new Date(team.createdAt)) + (team.createdBy ? " by " + by({ id: team.createdBy }) : "") : null]
118
+ ]
119
+ }])
120
+ })
121
+ }
122
+
123
+ function create(argv, ref, rest) {
124
+ return run(async () => {
125
+ const name = rest[0] === undefined || rest[0] === true ? "" : String(rest[0]).trim()
126
+ if (!name) throw friendly("name the team — `known <org> teams create <name> [--description \"…\"]`")
127
+ const slug = slugOf(name)
128
+ if (!slug) throw friendly("a team's slug comes from its name, and “" + name + "” leaves none — use letters or digits")
129
+ const session = sessionFor(argv, ref)
130
+ const team = unwrap(await getClient(argv, { session }).team.create({
131
+ slug,
132
+ title: name,
133
+ ...(argv.description !== undefined ? { description: String(argv.description) } : {})
134
+ }))
135
+ if (output.isJson()) return output.data(team)
136
+ output.status("created", team.slug, team.title + " · " + team.id)
137
+ })
138
+ }
139
+
140
+ function update(argv, ref, rest) {
141
+ return run(async () => {
142
+ const params = teamRef(rest[0], "update <slug>")
143
+ const changes = {
144
+ ...(argv.name !== undefined ? { title: String(argv.name) } : {}),
145
+ ...(argv.description !== undefined ? { description: String(argv.description) } : {})
146
+ }
147
+ if (!Object.keys(changes).length) throw friendly("nothing to change — pass --name or --description")
148
+ const session = sessionFor(argv, ref)
149
+ const team = unwrap(await getClient(argv, { session }).team.update({ ...params, ...changes }))
150
+ if (output.isJson()) return output.data(team)
151
+ const said = [
152
+ changes.title !== undefined ? "is named " + team.title : null,
153
+ changes.description !== undefined ? (team.description ? "says what it is for" : "has no description") : null
154
+ ].filter(Boolean)
155
+ output.status("updated", team.slug, said.join(", "))
156
+ })
157
+ }
158
+
159
+ // Deleting a team strikes it from every wiki's grants, so it is confirmed by
160
+ // the team's slug: typed at a terminal, or --confirm <slug> from a script.
161
+ function destroy(argv, ref, rest) {
162
+ return run(async () => {
163
+ const params = teamRef(rest[0], "delete <slug>")
164
+ const session = sessionFor(argv, ref)
165
+ const client = getClient(argv, { session })
166
+ const team = unwrap(await client.team.get(params))
167
+ const typed = await confirmByName("Delete the " + team.slug + " team (" + team.members.length + (team.members.length === 1 ? " person" : " people") + ")? Its grants on wikis go with it. Type its slug to confirm:", argv)
168
+ if (typed.value !== team.slug) {
169
+ if (typed.asked) return output.status("kept", team.slug, null, "muted")
170
+ throw friendly("to delete the " + team.slug + " team, confirm its slug — --confirm " + team.slug)
171
+ }
172
+ const res = unwrap(await client.team.remove({ id: team.id }))
173
+ if (output.isJson()) return output.data(res)
174
+ output.status("deleted", team.slug, res.wikis && res.wikis.length ? "its grants on " + res.wikis.join(", ") + " went with it" : null, "danger")
175
+ })
176
+ }
177
+
178
+ function add(argv, ref, rest) {
179
+ return run(async () => {
180
+ const params = teamRef(rest[0], "add <slug> <person>")
181
+ needPerson(rest[1], "add")
182
+ const session = sessionFor(argv, ref)
183
+ const client = getClient(argv, { session })
184
+ const who = await person(client, rest[1])
185
+ const team = unwrap(await client.team.addMember({ ...params, userId: who.id }))
186
+ if (output.isJson()) return output.data(team)
187
+ output.status("added", who.name || who.id, "to " + team.slug)
188
+ })
189
+ }
190
+
191
+ function remove(argv, ref, rest) {
192
+ return run(async () => {
193
+ const params = teamRef(rest[0], "remove <slug> <person>")
194
+ needPerson(rest[1], "remove")
195
+ const session = sessionFor(argv, ref)
196
+ const client = getClient(argv, { session })
197
+ const who = await person(client, rest[1])
198
+ const team = unwrap(await client.team.removeMember({ ...params, userId: who.id }))
199
+ if (output.isJson()) return output.data(team)
200
+ output.status("removed", who.name || who.id, "from " + team.slug, "muted")
201
+ })
202
+ }
203
+
204
+ function maintainer(argv, ref, rest) {
205
+ return run(async () => {
206
+ const params = teamRef(rest[0], "maintainer <slug> <person>")
207
+ needPerson(rest[1], "maintainer")
208
+ const session = sessionFor(argv, ref)
209
+ const client = getClient(argv, { session })
210
+ const who = await person(client, rest[1])
211
+ const team = unwrap(await client.team.setMaintainer({ ...params, userId: who.id, maintainer: !argv.off }))
212
+ if (output.isJson()) return output.data(team)
213
+ output.status(argv.off ? "member" : "maintainer", who.name || who.id, (argv.off ? "no longer maintains " : "maintains ") + team.slug, argv.off ? "muted" : undefined)
214
+ })
215
+ }
216
+
217
+ // Leaving is taking oneself off the roster: anyone may, of a team they are on.
218
+ function leave(argv, ref, rest) {
219
+ return run(async () => {
220
+ const params = teamRef(rest[0], "leave <slug>")
221
+ const session = sessionFor(argv, ref)
222
+ const me = session.account && session.account.id
223
+ if (!me) throw friendly("this session does not say who you are — run `known login` again")
224
+ const team = unwrap(await getClient(argv, { session }).team.removeMember({ ...params, userId: me }))
225
+ if (output.isJson()) return output.data(team)
226
+ output.status("left", team.slug, "the wikis it reaches are closed to you unless you hold them another way", "muted")
227
+ })
228
+ }
229
+
230
+ // ---- helpers ---------------------------------------------------------------
231
+
232
+ const TEAM_SLUG = /^[a-z0-9][a-z0-9-]*$/
233
+ const TEAM_ID = /^team_[A-Za-z0-9_-]+$/
234
+ const ABOUT_MAX = 60
235
+
236
+ // A team by its slug (design) or its id (team_…), as the API addresses one.
237
+ function teamRef(value, usage) {
238
+ const text = value === undefined || value === true ? "" : String(value)
239
+ if (TEAM_ID.test(text)) return { id: text }
240
+ if (TEAM_SLUG.test(text)) return { slug: text }
241
+ throw friendly("name the team by its slug — `known <org> teams " + usage + "`")
242
+ }
243
+
244
+ function needPerson(value, verb) {
245
+ if (value === undefined || value === true || !String(value).trim()) {
246
+ throw friendly("name the person — `known <org> teams " + verb + " <slug> <person>`, by user id, @handle, or email address")
247
+ }
248
+ }
249
+
250
+ // A team's slug from its name: lowercased, accents dropped, other characters
251
+ // made hyphens ("Design Studio" is design-studio) — as a site's short name is.
252
+ function slugOf(name) {
253
+ return String(name).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "")
254
+ }
255
+
256
+ function roleOf(member) {
257
+ return member.maintainer ? "maintainer" : "member"
258
+ }
259
+
260
+ function clamp(text) {
261
+ const line = String(text).replace(/\s+/g, " ").trim()
262
+ return line.length > ABOUT_MAX ? line.slice(0, ABOUT_MAX - 1) + "…" : line
263
+ }
264
+
265
+ // Pairs as two columns, the second greyed: "Ada Lovelace maintainer".
266
+ function aligned(pairs) {
267
+ const width = pairs.reduce((w, [left]) => Math.max(w, left.length), 0)
268
+ return pairs.map(([left, right]) => left + " ".repeat(width - left.length + 2) + String(right).grey)
269
+ }