@future-unknown/known 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1503 @@
1
+ require("@colors/colors")
2
+ const fs = require("fs")
3
+ const output = require("../output")
4
+ const { getClient, sessionFor, confirm, confirmByName, confirmStated, run, unwrap, actorNames, accessReasons, person } = require("../helpers")
5
+
6
+ /**
7
+ * `known <org> wiki` — the org's shared wiki.
8
+ *
9
+ * Every organization has a wiki named `general` and may hold more,
10
+ * including wikis another organization shares with it (marked in `wikis`
11
+ * with their home; addressed by this org's own name for them). Every path
12
+ * names its wiki: `general:docs.deploy` addresses that page in the general
13
+ * wiki, `labs:docs.deploy` (or `docs.deploy --wiki labs`) the same page in
14
+ * the org's `labs` wiki, and `labs:` the wiki's root. A path with no wiki is
15
+ * refused, never guessed. No path can reach
16
+ * outside the org's wikis. Content is Markdown.
17
+ *
18
+ * Pages are authored writing, and take the authoring verbs; records are
19
+ * data on a page, and take the data verbs:
20
+ *
21
+ * known acme wiki read general:docs.deploy
22
+ * known acme wiki write general:docs.deploy --file deploy.md --title "Deploying"
23
+ * known acme wiki edit general:docs.deploy --old "nightly" --new "hourly"
24
+ * git log -1 --format=%B | known acme wiki write general:notes.today
25
+ * known acme wiki tree general: --depth 2
26
+ * known acme wiki search "rollback" general:
27
+ * known acme wiki move general:docs.deploy general:runbooks.deploy
28
+ * known acme wiki rm general:scratch
29
+ * known acme wiki meta general:metrics.usage --text '{"retain": {"days": 90}}'
30
+ * known acme wiki records general:metrics.usage --latest
31
+ * known acme wiki get general:tasks/t-41
32
+ * known acme wiki set general:metrics.usage --text '{"requests": 1042}'
33
+ * known acme wiki del general:tasks/t-41
34
+ * known acme wiki history general:crm.contacts/jo
35
+ * known acme wiki diff general:crm.contacts/jo
36
+ * known acme wiki links general:crm.contacts/jo
37
+ * known acme wiki check capital:
38
+ * known acme wiki changes general:
39
+ * known acme wiki wikis
40
+ * known acme wiki create labs --title "Labs" --description "Experiments; nothing load-bearing"
41
+ * known acme wiki update labs --description "Experiments; nothing load-bearing"
42
+ * known acme wiki grant labs team:platform:write
43
+ * known acme wiki grant labs user:@ada:admin
44
+ * known acme wiki access labs
45
+ * known acme wiki rename labs research
46
+ * known acme wiki delete research
47
+ * known acme wiki deleted
48
+ * known acme wiki restore research
49
+ * known acme wiki share research globex --level write
50
+ * known globex wiki invitations
51
+ * known globex wiki accept acme/research --as acme-research
52
+ *
53
+ * Any member creates a wiki and is its admin; an org owner administers every
54
+ * wiki already, so one who creates a wiki gets no grant — unless it is
55
+ * restricted and they name nobody, when it is theirs. A wiki's admins and
56
+ * the org's owners rename it, delete it (nothing is destroyed: `restore`
57
+ * brings it back whole) and share it with another organization, whose owners
58
+ * accept it under a name of their own. Levels are read, write and admin.
59
+ *
60
+ * Every path the CLI prints is written the same way, so it pastes back.
61
+ * `wikis` says what each wiki is for and who reads it.
62
+ *
63
+ * A page with a key is a table (a record set adds or replaces the row with
64
+ * its key, and every version of each row is kept); a page without one is a
65
+ * log (a record set adds an entry). A record is addressed as its page, a
66
+ * slash, and its key: `general:crm.contacts/jo`.
67
+ *
68
+ * Every page revision is kept forever; `--change <id>` / `--at <iso>` read the
69
+ * wiki as it was. The safe edit loop for scripts and agents: change part of a
70
+ * page with `edit` (the exact text you read); to rewrite one, read with
71
+ * --json, keep `revisionId`, and write back with `--if-revision <id>`; a
72
+ * conflict means someone else changed the page — re-read, merge, retry.
73
+ * Missing parents (and the wiki itself, on first write) are created
74
+ * automatically.
75
+ */
76
+ const STDIN_MAX = 100000
77
+
78
+ const verbs = { read, write, edit, move, rm, tree, search, links, check, meta, records, get, set, del, history, diff, changes, notes, note, resolve, wikis, create, update, grant, revoke, access, rename, delete: destroy, deleted, restore, shares, share, unshare, invitations, accept, decline, leave }
79
+
80
+ module.exports = function (argv, ref, rest) {
81
+ const verb = rest && rest[0]
82
+ if (argv.help) return showMenu(ref)
83
+ if (!verb) return showMenu(ref)
84
+ const handler = verbs[verb]
85
+ if (!handler) {
86
+ output.info(require("../helpers").unknownCommand("wiki", verb, Object.keys(verbs)).grey)
87
+ return showMenu(ref)
88
+ }
89
+ return handler(argv, ref, rest.slice(1))
90
+ }
91
+
92
+ // Bare (`known wiki`), the org comes from the project binding, so the menu
93
+ // drops the org from every invocation.
94
+ function showMenu(ref) {
95
+ const org = ref ? ref + " " : ""
96
+ console.log()
97
+ console.log((" known " + org + "wiki").cyan + " the org's shared wikis — versioned, Markdown; every path names its wiki (general:docs.deploy)".grey)
98
+ console.log()
99
+ // Pages are authored writing; records are data on a page: each has its
100
+ // own verbs, so each has its own list, aligned to one column.
101
+ const groups = [
102
+ ["pages — writing", [
103
+ [org + "wiki read <wiki>:<path>", "print a page (raw content; --json for revision ids; --change, --at)"],
104
+ [org + "wiki write <wiki>:<path>", "write a page whole from --text, --file, or stdin (--if-revision)"],
105
+ [org + "wiki edit <wiki>:<path>", "replace --old with --new; refused unless --old occurs exactly once (--all)"],
106
+ [org + "wiki move <wiki>:<from> <wiki>:<to>", "move or rename a page and its subtree"],
107
+ [org + "wiki rm <wiki>:<path>", "delete a page (--recursive for a subtree; the wiki's admins and org owners)"],
108
+ [org + "wiki tree <wiki>:[path]", "the page hierarchy (--depth, --change, --at)"],
109
+ [org + "wiki search <query> <wiki>:[path]", "full-text search over pages and table records, optionally scoped to a subtree"],
110
+ [org + "wiki links <wiki>:<path>[/<key>]", "what links to a page or a record"],
111
+ [org + "wiki check <wiki>:[path]", "the links a wiki holds that point at nothing, and where each is"],
112
+ [org + "wiki meta <wiki>:<path>", "merge metadata declarations: key, schema, retain (null removes; --replace)"]
113
+ ]],
114
+ ["records — data on a page", [
115
+ [org + "wiki records <wiki>:<path>", "read records (--latest, --reverse, --since/--until, --limit, --cursor, --at)"],
116
+ [org + "wiki get <wiki>:<path>/<key>", "one record: a table's row by key, or a log entry by _id"],
117
+ [org + "wiki set <wiki>:<path>", "write a record (--text/--file/stdin; a table adds or replaces by key, --if-version; a log adds, --ts)"],
118
+ [org + "wiki del <wiki>:<path>/<key>", "delete one record"]
119
+ ]],
120
+ ["history, changes and notes", [
121
+ [org + "wiki history <wiki>:<path>[/<key>]", "a page's revisions, or a table row's versions, newest first"],
122
+ [org + "wiki diff <wiki>:<path>[/<key>]", "what the latest revision or version changed (--change, --revision; --version for a row)"],
123
+ [org + "wiki changes <wiki>:[path]", "what changed in a wiki, newest first, and the pages each change touched (--limit, --before)"],
124
+ [org + "wiki notes <wiki>:[path]", "the feedback queue (the wiki's root: all of it; --deep: a subtree)"],
125
+ [org + "wiki note <wiki>:<path>", "leave a note (--text/--file/stdin)"],
126
+ [org + "wiki resolve <wiki>:<path> <id>", "resolve a note"]
127
+ ]],
128
+ ["wikis", [
129
+ [org + "wiki wikis", "the org's wikis — what each is for, who reads it, what changed since you looked, your level (--json: everything)"],
130
+ [org + "wiki create <name>", "create a wiki (--description, --title, --restricted, --grant <kind>:<id>[:<level>], --member <person>; any member, who is its admin)"],
131
+ [org + "wiki update <wiki>", "say what it is for and retitle it (--description, --title); --restricted or --open (its admins and org owners)"],
132
+ [org + "wiki grant <wiki> <kind>:<id>[:<level>]", "grant a person (user:@handle, user:<email>, user:<id>) or a team (team:<slug>) a level: read, write, admin; again to change it"],
133
+ [org + "wiki revoke <wiki> <kind>:<id>", "take a grant away"],
134
+ [org + "wiki access <wiki>", "who has access, at what level, and why (the org, a direct grant, a team, owning the org)"],
135
+ [org + "wiki rename <wiki> <new-name>", "rename it (its admins and org owners; --yes); sites must be republished, agents use the new name"],
136
+ [org + "wiki delete <wiki>", "delete it — type its name, or --confirm <name>; it can be restored"],
137
+ [org + "wiki deleted", "the deleted wikis you could restore"],
138
+ [org + "wiki restore <wiki>", "bring a deleted wiki back whole"]
139
+ ]],
140
+ ["sharing with other organizations", [
141
+ [org + "wiki shares <wiki>", "the organizations a wiki is shared with, and where each share stands"],
142
+ [org + "wiki share <wiki> <org>", "invite another organization to it (--level read or write; read when unsaid)"],
143
+ [org + "wiki unshare <wiki> <org>", "end a share, waiting or accepted"],
144
+ [org + "wiki invitations", "wikis other organizations have offered this one (org owners)"],
145
+ [org + "wiki accept <org>/<wiki>", "accept an invitation (--as <name> to call it something else here)"],
146
+ [org + "wiki decline <org>/<wiki>", "decline an invitation"],
147
+ [org + "wiki leave <wiki>", "stop taking part in a wiki another organization shares"]
148
+ ]]
149
+ ]
150
+ const width = output.commandWidth(...groups.map(([, rows]) => rows))
151
+ for (const [title, rows] of groups) {
152
+ console.log(" " + title.bold)
153
+ output.commands(rows, width)
154
+ console.log()
155
+ }
156
+ process.exit(0)
157
+ }
158
+
159
+ // ---- verbs -----------------------------------------------------------------
160
+
161
+ function read(argv, ref, rest) {
162
+ return run(async () => {
163
+ // Validate the typed input before resolving a session, so bad flags are
164
+ // reported even with no credentials on disk — the same order `post` keeps.
165
+ const when = historical(argv)
166
+ if (recordAddress(rest[0]).key !== null) throw friendly("that is a record — read it with `known <org> wiki get <wiki>:<path>/<key>`")
167
+ const address = wikiAddress(argv, [rest[0]])
168
+ const session = sessionFor(argv, ref)
169
+ const client = getClient(argv, { session })
170
+ const scope = await wikiScope(address, argv, session, client)
171
+ const node = unwrap(await client.wiki.read({
172
+ path: scope.full(rest[0]),
173
+ ...when
174
+ }))
175
+ if (output.isJson()) return output.data(node)
176
+ output.raw(node.content)
177
+ })
178
+ }
179
+
180
+ function write(argv, ref, rest) {
181
+ return run(async () => {
182
+ const text = await resolveText(argv)
183
+ const metadata = argv.metadata !== undefined ? metadataFlag(argv.metadata) : undefined
184
+ const address = wikiAddress(argv, [rest[0]])
185
+ const session = sessionFor(argv, ref)
186
+ const client = getClient(argv, { session })
187
+ const scope = await wikiScope(address, argv, session, client)
188
+ const res = unwrap(await client.wiki.write({
189
+ path: scope.full(rest[0]),
190
+ content: text,
191
+ ...(argv.title ? { title: argv.title } : {}),
192
+ ...(metadata !== undefined ? { metadata } : {}),
193
+ ...(argv.message ? { message: argv.message } : {}),
194
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
195
+ }))
196
+ if (output.isJson()) return output.data(res)
197
+ if (!res.changed) output.status("unchanged", res.node.fullPath, "already this content", "muted")
198
+ else output.status(res.created ? "created" : "updated", res.node.fullPath, "revision " + res.node.revisionId)
199
+ reportProblems(res.problems)
200
+ })
201
+ }
202
+
203
+ // The links a write carried that point at nothing, a line each: the write
204
+ // stands, and what to fix is said where it was done.
205
+ function reportProblems(problems) {
206
+ if (!problems || !problems.length || output.isJson()) return
207
+ output.pad(() => {
208
+ for (const problem of problems) {
209
+ if (problem.link === null) console.log(" " + problem.message.grey)
210
+ else console.log(" " + "broken link".red + " " + ("[[" + problem.link + "]]").cyan + (" " + problem.message).grey)
211
+ }
212
+ })
213
+ }
214
+
215
+ // The links a move or removal left pointing at nothing, by where they are.
216
+ function reportLeftBroken(broken, scope, slug) {
217
+ if (!broken || !broken.total || output.isJson()) return
218
+ output.pad(() => {
219
+ for (const link of broken.links) {
220
+ const from = link.fullPath + (link.key ? "/" + link.key : "")
221
+ console.log(" " + "broken link".red + " " + from.cyan + (" still links to " + link.target.fullPath).grey)
222
+ }
223
+ if (broken.total > broken.links.length) console.log(" " + ((broken.total - broken.links.length) + " more — wiki check finds them all").grey)
224
+ })
225
+ }
226
+
227
+ // Every link a wiki — or a page and those beneath it — holds that points
228
+ // at nothing: the link, why, and the pages and records that carry it.
229
+ function check(argv, ref, rest) {
230
+ return run(async () => {
231
+ const target = rest[0]
232
+ if (!target) throw friendly("name the wiki or page — `known <org> wiki check <wiki>:[path]`")
233
+ const address = wikiAddress(argv, [target])
234
+ const session = sessionFor(argv, ref)
235
+ const client = getClient(argv, { session })
236
+ const scope = await wikiScope(address, argv, session, client)
237
+ const res = unwrap(await client.wiki.check({ path: scope.full(target) }))
238
+ if (output.isJson()) return output.data(res)
239
+ if (!res.problems.length) return output.empty("no broken links")
240
+ output.table(res.problems.map((problem) => ({
241
+ link: problem.link === null ? "" : ("[[" + problem.link + "]]").cyan,
242
+ problem: problem.message,
243
+ in: (problem.sources || []).map((source) => source.fullPath + (source.key ? "/" + source.key : "")).join(", ")
244
+ })))
245
+ })
246
+ }
247
+
248
+ // Change part of a page: one exact string for another, read and written in
249
+ // one step on the server, so nothing else on the page is touched and a
250
+ // change made meanwhile elsewhere on it survives. --old must occur exactly
251
+ // once (give more of the surrounding text), unless --all.
252
+ function edit(argv, ref, rest) {
253
+ return run(async () => {
254
+ const target = rest[0]
255
+ if (!target) throw friendly("name the page — `known <org> wiki edit <wiki>:<path> --old \"…\" --new \"…\"`")
256
+ if (!argv.old || argv.new === undefined) {
257
+ throw friendly("say what to replace and with what — `--old \"…\" --new \"…\"` (--new \"\" deletes)")
258
+ }
259
+ const address = wikiAddress(argv, [target])
260
+ const session = sessionFor(argv, ref)
261
+ const client = getClient(argv, { session })
262
+ const scope = await wikiScope(address, argv, session, client)
263
+ const res = unwrap(await client.wiki.edit({
264
+ path: scope.full(target),
265
+ oldString: String(argv.old),
266
+ newString: String(argv.new),
267
+ ...(argv.all ? { replaceAll: true } : {}),
268
+ ...(argv.message ? { message: argv.message } : {}),
269
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
270
+ }))
271
+ if (output.isJson()) return output.data(res)
272
+ output.status("edited", res.node.fullPath, res.replaced + (res.replaced === 1 ? " place" : " places") + " · revision " + res.node.revisionId)
273
+ reportProblems(res.problems)
274
+ })
275
+ }
276
+
277
+ function tree(argv, ref, rest) {
278
+ return run(async () => {
279
+ const when = historical(argv)
280
+ const depth = argv.depth ? { depth: intFlag(argv.depth, "--depth") } : {}
281
+ const address = wikiAddress(argv, [rest[0]])
282
+ const session = sessionFor(argv, ref)
283
+ const client = getClient(argv, { session })
284
+ const scope = await wikiScope(address, argv, session, client)
285
+ const root = unwrap(await client.wiki.tree({
286
+ path: scope.full(rest[0]),
287
+ ...depth,
288
+ ...when
289
+ }))
290
+ if (output.isJson()) return output.data(root)
291
+
292
+ const rows = [[root.fullPath, preview(root)]]
293
+ walk(root, "")
294
+ function walk(node, prefix) {
295
+ node.children.forEach((child, i) => {
296
+ const last = i === node.children.length - 1
297
+ rows.push([prefix + (last ? "└── " : "├── ") + child.slug, preview(child)])
298
+ walk(child, prefix + (last ? " " : "│ "))
299
+ })
300
+ }
301
+ console.log()
302
+ output.commands(rows)
303
+ console.log()
304
+ })
305
+ }
306
+
307
+ function search(argv, ref, rest) {
308
+ return run(async () => {
309
+ const query = rest[0]
310
+ if (!query) throw friendly("nothing to search for — `known <org> wiki search <query> <wiki>:`")
311
+ const address = wikiAddress(argv, [rest[1]])
312
+ const session = sessionFor(argv, ref)
313
+ const client = getClient(argv, { session })
314
+ const scope = await wikiScope(address, argv, session, client)
315
+ const results = unwrap(await client.wiki.search({
316
+ path: scope.full(rest[1]),
317
+ query,
318
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
319
+ }))
320
+ if (output.isJson()) return output.data(results)
321
+ if (!results.length) return output.empty("nothing matches “" + query + "”")
322
+ output.table(results.map((r) => ({
323
+ path: (r.fullPath + (r.key ? "/" + r.key : "")).cyan,
324
+ excerpt: (r.excerpt || "").replace(/\s+/g, " ")
325
+ })))
326
+ })
327
+ }
328
+
329
+ function history(argv, ref, rest) {
330
+ return run(async () => {
331
+ const address = wikiAddress(argv, [rest[0]])
332
+ const { page, key } = recordAddress(rest[0])
333
+ const session = sessionFor(argv, ref)
334
+ const client = getClient(argv, { session })
335
+ const scope = await wikiScope(address, argv, session, client)
336
+ if (key !== null) {
337
+ const res = unwrap(await client.wiki.history({
338
+ path: scope.full(page),
339
+ key,
340
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {}),
341
+ ...(argv.cursor ? { cursor: String(argv.cursor) } : {})
342
+ }))
343
+ if (output.isJson()) return output.data(res)
344
+ const by = await actorNames(client, res.versions.map((v) => v._actor))
345
+ output.table(res.versions.map((v) => ({
346
+ version: String(v._v),
347
+ when: v._ts,
348
+ by: by(v._actor),
349
+ change: v._change === "deleted" ? "deleted".red : v._change
350
+ })))
351
+ if (res.cursor) output.status("more", "continue with", "--cursor " + res.cursor, "muted")
352
+ return
353
+ }
354
+ if (argv.cursor) throw friendly("--cursor pages a row's versions — address one as <path>/<key>")
355
+ const entries = unwrap(await client.wiki.history({
356
+ path: scope.full(rest[0]),
357
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
358
+ }))
359
+ if (output.isJson()) return output.data(entries)
360
+ const by = await actorNames(client, entries.map((e) => e.change.actor))
361
+ output.table(entries.map((e) => ({
362
+ change: String(e.changeId),
363
+ revision: e.revisionId,
364
+ when: e.createdAt,
365
+ by: by(e.change.actor),
366
+ note: e.deleted ? "deleted".red : (e.change.message || "—".grey)
367
+ })))
368
+ })
369
+ }
370
+
371
+ // What one change did, against the one before it: a page revision as a
372
+ // unified diff of its Markdown (title and metadata changes first), or a
373
+ // table row's version as a unified diff of its fields (sorted JSON,
374
+ // stamps left out). The latest by default.
375
+ function diff(argv, ref, rest) {
376
+ return run(async () => {
377
+ const target = rest[0]
378
+ if (!target) throw friendly("name the page or record — `known <org> wiki diff <wiki>:<path>[/<key>]`")
379
+ const address = wikiAddress(argv, [target])
380
+ const { page, key } = recordAddress(target)
381
+ if (key !== null && (argv.change || argv.revision)) throw friendly("a row's versions take --version, not --change or --revision")
382
+ if (key === null && argv.version) throw friendly("--version reads a row — address one as <path>/<key>")
383
+ if (argv.change && argv.revision) throw friendly("pass --change or --revision, not both")
384
+ const session = sessionFor(argv, ref)
385
+ const client = getClient(argv, { session })
386
+ const scope = await wikiScope(address, argv, session, client)
387
+ const full = scope.full(page)
388
+
389
+ if (key !== null) {
390
+ let version = argv.version ? intFlag(argv.version, "--version") : null
391
+ if (version === null) {
392
+ const latest = unwrap(await client.wiki.history({ path: full, key, limit: 1 }))
393
+ version = latest.versions[0]._v
394
+ }
395
+ const res = unwrap(await client.wiki.getVersion({ path: full, key, version }))
396
+ if (output.isJson()) return output.data(res)
397
+ const by = await actorNames(client, [res.version._actor])
398
+ const before = res.previous && res.previous._change !== "deleted" ? res.previous : null
399
+ const after = res.version._change === "deleted" ? null : res.version
400
+ console.log()
401
+ console.log(" version " + res.version._v + " " + res.version._ts + " " + by(res.version._actor) + " " + res.version._change)
402
+ // Read the way a page revision is: other fields as before -> after,
403
+ // then the record's writing (its content) as a unified diff.
404
+ const from = otherFields(before)
405
+ const to = otherFields(after)
406
+ for (const name of [...new Set([...Object.keys(from), ...Object.keys(to)])].sort()) {
407
+ const a = name in from ? JSON.stringify(from[name]) : "null"
408
+ const b = name in to ? JSON.stringify(to[name]) : "null"
409
+ if (a !== b) console.log(" " + name + ": " + a + " -> " + b)
410
+ }
411
+ printPatch(full + "/" + key, before ? "v" + before._v : null, after ? "v" + after._v : null, writingOf(before), writingOf(after))
412
+ return
413
+ }
414
+
415
+ let revisionId = argv.revision ? String(argv.revision) : null
416
+ if (!revisionId) {
417
+ const node = unwrap(await client.wiki.read({ path: full, ...(argv.change ? { changeId: intFlag(argv.change, "--change") } : {}) }))
418
+ revisionId = node.revisionId
419
+ }
420
+ const revision = unwrap(await client.wiki.getRevision({ wiki: full.split(".")[0], revisionId }))
421
+ if (output.isJson()) return output.data(revision)
422
+ const by = await actorNames(client, [revision.change.actor])
423
+ const gone = revision.kind === "deleted"
424
+ const before = revision.previous && !revision.previous.deleted ? revision.previous : null
425
+ console.log()
426
+ console.log(" change " + revision.changeId + " " + revision.createdAt + " " + by(revision.change.actor) + " " + revision.kind +
427
+ (revision.change.message ? " " + revision.change.message : ""))
428
+ const field = (name, from, to) => {
429
+ if (from !== to) console.log(" " + name + ": " + JSON.stringify(from == null ? null : from) + " -> " + JSON.stringify(to == null ? null : to))
430
+ }
431
+ field("title", before ? before.title : null, gone ? null : revision.title)
432
+ const fromMeta = (before && before.metadata) || {}
433
+ const toMeta = gone ? {} : (revision.metadata || {})
434
+ for (const name of [...new Set([...Object.keys(fromMeta), ...Object.keys(toMeta)])].sort()) {
435
+ field("metadata." + name, fromMeta[name], toMeta[name])
436
+ }
437
+ printPatch(full, before ? "c" + before.changeId : null, gone ? null : "c" + revision.changeId,
438
+ before ? before.content : "", gone ? "" : revision.content)
439
+ })
440
+ }
441
+
442
+ // What links to a page or a table record: the pages whose content and the
443
+ // records that carry a wikilink to it, each by its address and heading.
444
+ function links(argv, ref, rest) {
445
+ return run(async () => {
446
+ const target = rest[0]
447
+ if (!target) throw friendly("name the page or record — `known <org> wiki links <wiki>:<path>[/<key>]`")
448
+ const address = wikiAddress(argv, [target])
449
+ const { page, key } = recordAddress(target)
450
+ const session = sessionFor(argv, ref)
451
+ const client = getClient(argv, { session })
452
+ const scope = await wikiScope(address, argv, session, client)
453
+ const res = unwrap(await client.wiki.links({
454
+ path: scope.full(page),
455
+ ...(key !== null ? { key } : {}),
456
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
457
+ }))
458
+ if (output.isJson()) return output.data(res)
459
+ if (!res.links.length) return output.empty("nothing links here")
460
+ output.table(res.links.map((link) => ({
461
+ from: (link.fullPath + (link.key ? "/" + link.key : "")).cyan,
462
+ title: link.title || ""
463
+ })))
464
+ })
465
+ }
466
+
467
+ function move(argv, ref, rest) {
468
+ return run(async () => {
469
+ const [from, to] = rest
470
+ if (!from || !to) throw friendly("both paths are needed — `known <org> wiki move <wiki>:<from> <wiki>:<to>`")
471
+ const address = wikiAddress(argv, [from, to])
472
+ const session = sessionFor(argv, ref)
473
+ const client = getClient(argv, { session })
474
+ const scope = await wikiScope(address, argv, session, client)
475
+ const node = unwrap(await client.wiki.move({
476
+ from: scope.full(from),
477
+ to: scope.full(to),
478
+ ...(argv.message ? { message: argv.message } : {}),
479
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
480
+ }))
481
+ if (output.isJson()) return output.data(node)
482
+ output.status("moved", node.fullPath, "from " + scope.full(from))
483
+ reportLeftBroken(node.brokenLinks, scope, session.org.slug)
484
+ })
485
+ }
486
+
487
+ function rm(argv, ref, rest) {
488
+ return run(async () => {
489
+ const target = rest[0]
490
+ if (!target) throw friendly("name the page to delete — `known <org> wiki rm <wiki>:<path>`")
491
+ const address = wikiAddress(argv, [target])
492
+ const session = sessionFor(argv, ref)
493
+ const client = getClient(argv, { session })
494
+ const scope = await wikiScope(address, argv, session, client)
495
+ const full = scope.full(target)
496
+
497
+ // Recursive deletion takes a whole subtree with it; pause for a human
498
+ // unless --yes or scripted. History survives either way.
499
+ if (argv.recursive && !(await confirm("delete the entire subtree at " + full + "?", argv))) {
500
+ return output.status("kept", full, null, "muted")
501
+ }
502
+
503
+ const res = unwrap(await client.wiki.remove({
504
+ path: full,
505
+ ...(argv.recursive ? { recursive: true } : {}),
506
+ ...(argv.message ? { message: argv.message } : {}),
507
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {}),
508
+ ...(argv["if-change"] ? { ifChange: intFlag(argv["if-change"], "--if-change") } : {})
509
+ }))
510
+ if (output.isJson()) return output.data(res)
511
+ output.status("deleted", res.deletedPaths.join(", "), "change " + res.changeId, "danger")
512
+ reportLeftBroken(res.brokenLinks, scope, session.org.slug)
513
+ })
514
+ }
515
+
516
+ // A wiki's root (`general:`, or --wiki general) is its whole feedback
517
+ // queue; a page narrows to that page exactly, and --deep widens a page to
518
+ // its whole subtree.
519
+ function notes(argv, ref, rest) {
520
+ return run(async () => {
521
+ const target = rest[0]
522
+ const subtree = !splitColon(target).rest || argv.deep === true
523
+ const address = wikiAddress(argv, [target])
524
+ const session = sessionFor(argv, ref)
525
+ const client = getClient(argv, { session })
526
+ const scope = await wikiScope(address, argv, session, client)
527
+ const entries = unwrap(await client.wiki.notes({
528
+ path: scope.full(target),
529
+ ...(subtree ? { subtree: true } : {}),
530
+ ...(argv.all ? { includeResolved: true } : {})
531
+ }))
532
+ if (output.isJson()) return output.data(entries)
533
+ if (!entries.length) return output.empty(argv.all ? "no notes" : "no open notes")
534
+ const by = await actorNames(client, entries.map((entry) => entry.author))
535
+ output.table(entries.map((entry) => ({
536
+ page: entry.fullPath.cyan,
537
+ note: preview({ content: entry.body }),
538
+ by: by(entry.author),
539
+ when: entry.createdAt,
540
+ status: entry.resolvedAt ? "resolved".grey : "open",
541
+ id: entry.id
542
+ })))
543
+ })
544
+ }
545
+
546
+ function note(argv, ref, rest) {
547
+ return run(async () => {
548
+ const target = rest[0]
549
+ if (!target) throw friendly("name the page — `known <org> wiki note <wiki>:<path>`")
550
+ if (argv.resolve) throw friendly("resolving is its own verb — `known <org> wiki resolve <wiki>:<path> <id>`")
551
+ const address = wikiAddress(argv, [target])
552
+ const body = await resolveText(argv)
553
+ const session = sessionFor(argv, ref)
554
+ const client = getClient(argv, { session })
555
+ const scope = await wikiScope(address, argv, session, client)
556
+ const added = unwrap(await client.wiki.addNote({
557
+ path: scope.full(target),
558
+ body
559
+ }))
560
+ if (output.isJson()) return output.data(added)
561
+ output.status("noted", added.fullPath, "note " + added.id)
562
+ })
563
+ }
564
+
565
+ function resolve(argv, ref, rest) {
566
+ return run(async () => {
567
+ const [target, id] = rest
568
+ if (!target || !id) throw friendly("name the page and the note — `known <org> wiki resolve <wiki>:<path> <id>`")
569
+ const address = wikiAddress(argv, [target])
570
+ const session = sessionFor(argv, ref)
571
+ const client = getClient(argv, { session })
572
+ const scope = await wikiScope(address, argv, session, client)
573
+ const resolved = unwrap(await client.wiki.resolveNote({
574
+ path: scope.full(target),
575
+ noteId: String(id)
576
+ }))
577
+ if (output.isJson()) return output.data(resolved)
578
+ output.status("resolved", resolved.fullPath, "note " + resolved.id, "muted")
579
+ })
580
+ }
581
+
582
+ // A record set is stamped (_actor, _ts, _v, _id) and is not one of the
583
+ // wiki's changes. The page's declarations decide the behavior — a table
584
+ // adds or replaces the row with its key and keeps every version
585
+ // (--if-version is the compare-and-swap), a log adds an entry (--ts
586
+ // backfills when it happened).
587
+ function set(argv, ref, rest) {
588
+ return run(async () => {
589
+ const target = rest[0]
590
+ if (!target) throw friendly("name the page — `known <org> wiki set <wiki>:<path>`")
591
+ if (recordAddress(target).key !== null) throw friendly("a record carries its key in its fields — `known <org> wiki set <wiki>:<path> --text '{…}'`")
592
+ const address = wikiAddress(argv, [target])
593
+ const value = parseJson(await resolveText(argv))
594
+ const session = sessionFor(argv, ref)
595
+ const client = getClient(argv, { session })
596
+ const scope = await wikiScope(address, argv, session, client)
597
+ const res = unwrap(await client.wiki.set({
598
+ path: scope.full(target),
599
+ value,
600
+ ...(argv.ts ? { ts: String(argv.ts) } : {}),
601
+ ...(argv["if-version"] ? { ifVersion: intFlag(argv["if-version"], "--if-version") } : {})
602
+ }))
603
+ if (output.isJson()) return output.data(res)
604
+ output.status("set", res.fullPath, res.record._id + " (version " + res.record._v + ")")
605
+ reportProblems(res.problems)
606
+ })
607
+ }
608
+
609
+ // One record by its address: a table's row by its key, a log entry by _id.
610
+ function get(argv, ref, rest) {
611
+ return run(async () => {
612
+ const target = rest[0]
613
+ const { page, key } = recordAddress(target)
614
+ if (!target || key === null) throw friendly("name the record — `known <org> wiki get <wiki>:<path>/<key>` (a page is read with `wiki read`)")
615
+ if (argv.latest || argv.since || argv.until || argv.limit || argv.cursor || argv.reverse || argv.at) {
616
+ throw friendly("one record stands alone — drop --latest/--since/--until/--limit/--cursor/--reverse/--at (a row at a moment is its version: `wiki history <wiki>:<path>/<key>`)")
617
+ }
618
+ const address = wikiAddress(argv, [page])
619
+ const session = sessionFor(argv, ref)
620
+ const client = getClient(argv, { session })
621
+ const scope = await wikiScope(address, argv, session, client)
622
+ const res = unwrap(await client.wiki.get({ path: scope.full(page), key }))
623
+ if (output.isJson()) return output.data(res)
624
+ output.raw(JSON.stringify(res.record, null, 2))
625
+ })
626
+ }
627
+
628
+ function del(argv, ref, rest) {
629
+ return run(async () => {
630
+ const target = rest[0]
631
+ const { page, key } = recordAddress(target)
632
+ if (!target || key === null || rest[1] !== undefined) throw friendly("name the record — `known <org> wiki del <wiki>:<path>/<key>` (a page is deleted with `wiki rm`)")
633
+ const address = wikiAddress(argv, [page])
634
+ const session = sessionFor(argv, ref)
635
+ const client = getClient(argv, { session })
636
+ const scope = await wikiScope(address, argv, session, client)
637
+ const res = unwrap(await client.wiki.del({
638
+ path: scope.full(page),
639
+ key
640
+ }))
641
+ if (output.isJson()) return output.data(res)
642
+ output.status("deleted", res.fullPath, String(res.record._id))
643
+ })
644
+ }
645
+
646
+ // Declarations are authored intent: meta merges fields into the page's
647
+ // versioned metadata without clobbering the rest. A null value removes
648
+ // its field; --replace swaps the whole object.
649
+ function meta(argv, ref, rest) {
650
+ return run(async () => {
651
+ const target = rest[0]
652
+ if (!target) throw friendly("name the page — `known <org> wiki meta <wiki>:<path>`")
653
+ const address = wikiAddress(argv, [target])
654
+ const patch = metadataFlag(await resolveText(argv))
655
+ const session = sessionFor(argv, ref)
656
+ const client = getClient(argv, { session })
657
+ const scope = await wikiScope(address, argv, session, client)
658
+ const res = unwrap(await client.wiki.updateMeta({
659
+ path: scope.full(target),
660
+ metadata: patch,
661
+ ...(argv.replace ? { replace: true } : {}),
662
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {}),
663
+ ...(argv.message ? { message: argv.message } : {})
664
+ }))
665
+ if (output.isJson()) return output.data(res)
666
+ if (!res.changed) return output.status("unchanged", res.node.fullPath, "already these declarations", "muted")
667
+ output.status("updated", res.node.fullPath, "revision " + res.node.revisionId)
668
+ })
669
+ }
670
+
671
+ function records(argv, ref, rest) {
672
+ return run(async () => {
673
+ const target = rest[0]
674
+ if (!target) throw friendly("name the page — `known <org> wiki records <wiki>:<path>`")
675
+ if (recordAddress(target).key !== null || rest[1] !== undefined) {
676
+ throw friendly("one record is read with `known <org> wiki get <wiki>:<path>/<key>` (and a row then is its version: `wiki history <wiki>:<path>/<key>`)")
677
+ }
678
+ const address = wikiAddress(argv, [target])
679
+ const range = recordRange(argv)
680
+ const session = sessionFor(argv, ref)
681
+ const client = getClient(argv, { session })
682
+ const scope = await wikiScope(address, argv, session, client)
683
+ const res = unwrap(await client.wiki.records({
684
+ path: scope.full(target),
685
+ ...range
686
+ }))
687
+ if (output.isJson()) return output.data(res)
688
+ if (res.unknown && res.unknown.length) output.status("unknown", "not kept at " + res.at, res.unknown.join(", "), "muted")
689
+ if (!res.records.length) return output.empty("no records")
690
+ output.table(res.records.map((record) => ({
691
+ when: record._ts,
692
+ record: JSON.stringify(recordFields(record)),
693
+ by: record._actor.onBehalfOf
694
+ ? record._actor.id + " for " + record._actor.onBehalfOf
695
+ : record._actor.id
696
+ })))
697
+ if (res.cursor) output.status("more", "continue with", "--cursor " + res.cursor, "muted")
698
+ })
699
+ }
700
+
701
+ // What changed in a wiki, newest first: each change with who made it, its
702
+ // note, and the pages it touched. A page narrows it to that subtree.
703
+ function changes(argv, ref, rest) {
704
+ return run(async () => {
705
+ const target = rest[0]
706
+ const address = wikiAddress(argv, [target])
707
+ const session = sessionFor(argv, ref)
708
+ const client = getClient(argv, { session })
709
+ const scope = await wikiScope(address, argv, session, client)
710
+ const entries = unwrap(await client.wiki.changes({
711
+ path: scope.full(target),
712
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {}),
713
+ ...(argv.before ? { before: intFlag(argv.before, "--before") } : {})
714
+ }))
715
+ if (output.isJson()) return output.data(entries)
716
+ if (!entries.length) return output.empty("nothing has changed here")
717
+ const by = await actorNames(client, entries.map((entry) => entry.actor))
718
+ output.table(entries.map((entry) => ({
719
+ change: String(entry.id),
720
+ when: output.timeAgo(new Date(entry.createdAt)),
721
+ by: by(entry.actor),
722
+ pages: entry.pages.map((page) => (page.kind === "updated" ? "" : page.kind + " ") + page.fullPath).join(", "),
723
+ note: entry.message || "—".grey
724
+ })))
725
+ const last = entries[entries.length - 1]
726
+ if (argv.limit && entries.length === intFlag(argv.limit, "--limit")) output.status("more", "continue with", "--before " + last.id, "muted")
727
+ })
728
+ }
729
+
730
+ // A record's caller fields, stamps stripped — for compact listings.
731
+ function recordFields(record) {
732
+ const fields = {}
733
+ for (const field of Object.keys(record)) {
734
+ if (field.indexOf("_") !== 0) fields[field] = record[field]
735
+ }
736
+ return fields
737
+ }
738
+
739
+ // The org's wiki registry: every wiki the caller can see. Restricted wikis
740
+ // someone holds no grant on are absent entirely — that is the point; an
741
+ // org owner sees them with no level and `admin` alone.
742
+ function wikis(argv, ref, rest) {
743
+ return run(async () => {
744
+ const session = sessionFor(argv, ref)
745
+ const entries = unwrap(await getClient(argv, { session }).wiki.list({}))
746
+ if (output.isJson()) return output.data(entries)
747
+ if (!entries.length) return output.empty("no wikis")
748
+ const orgName = (session.org && (session.org.name || session.org.slug)) || "the organization"
749
+ // One block per wiki, read top to bottom the way a wiki is chosen:
750
+ // what it is for, then who reads it and
751
+ // which sites, then how lately it changed. `new` is per caller: someone
752
+ // else wrote to it after this session last looked (the app marks wikis
753
+ // seen; the CLI only reads). --json carries everything.
754
+ const standIns = entries.filter((entry) => entry.descriptionFrom !== "declared" && entry.capabilities.includes("write"))
755
+ output.cards(entries.map((entry) => ({
756
+ title: entry.name.cyan.bold,
757
+ aside: asideOf(entry),
758
+ body: entry.description || (entry.capabilities.includes("read") ? "No description yet." : "Restricted: not granted to you."),
759
+ // the home page's first paragraph standing in is not the wiki's own word
760
+ muted: entry.descriptionFrom !== "declared",
761
+ fields: [
762
+ ["read by", readerLines(entry.readers, orgName)],
763
+ ...(entry.shared ? [["shared", "from " + entry.shared.home.slug + ", " + (entry.shared.ceiling === "write" ? "read and write" : "read only")]] : []),
764
+ ...(entry.sharing && !entry.shared ? [["shared", "with " + entry.sharing.guests.map((guest) => guest.name || guest.slug || guest.id).join(", ")]] : []),
765
+ ["sites", siteLines(entry)],
766
+ ["changed", entry.activity?.at
767
+ ? output.timeAgo(new Date(entry.activity.at)) + (entry.unseen ? " · ".grey + "new since you looked".green : "")
768
+ : "never"]
769
+ ]
770
+ })), {
771
+ heading: (orgName + " · " + entries.length + (entries.length === 1 ? " wiki" : " wikis")).bold,
772
+ footer: standIns.length ? [
773
+ listOf(standIns.map((entry) => entry.name)) + (standIns.length === 1 ? " has no description of its own" : " have no descriptions of their own") + "; grey text is the home page standing in. Say what belongs in one:",
774
+ "known " + (ref ? ref + " " : "") + "wiki update " + standIns[0].name + " --description \"…\""
775
+ ] : null
776
+ })
777
+ })
778
+ }
779
+
780
+ // Names as prose: "a", "a and b", "a, b and c".
781
+ function listOf(names) {
782
+ return names.length < 2 ? names.join("") : names.slice(0, -1).join(", ") + " and " + names[names.length - 1]
783
+ }
784
+
785
+ // The heading's right side: how the wiki is kept, then what the caller
786
+ // holds. An org owner not granted on a restricted wiki sees it to manage
787
+ // who is.
788
+ function asideOf(entry) {
789
+ const parts = []
790
+ if (entry.visibility === "restricted") parts.push("restricted".yellow)
791
+ if (entry.shared) parts.push("shared".magenta)
792
+ parts.push((entry.level || (entry.capabilities.includes("admin") ? "you manage access" : "")).grey)
793
+ return parts.filter((part) => require("@colors/colors").strip(part)).join(" · ".grey)
794
+ }
795
+
796
+ // Who reads a wiki, one per line: every member (and how many), or a
797
+ // restricted wiki's teams and people, each with their level.
798
+ function readerLines(readers, orgName) {
799
+ if (!readers || readers.everyone) return "every member of " + orgName + (readers && readers.count != null ? " (" + readers.count + ")" : "")
800
+ const named = [
801
+ ...(readers.teams || []).map((t) => ["team " + (t.title || t.slug || t.id), t.level]),
802
+ ...(readers.people || []).map((p) => [p.name || p.id, p.level])
803
+ ]
804
+ // levels in a column of their own, two spaces past the longest name
805
+ const width = named.reduce((w, [name]) => Math.max(w, name.length), 0)
806
+ const lines = named.map(([name, level]) => name + " ".repeat(width - name.length + 2) + String(level).grey)
807
+ const more = (readers.count != null ? readers.count : (readers.people || []).length) - (readers.people || []).length
808
+ if (more > 0) lines.push(("and " + more + " more").grey)
809
+ return lines
810
+ }
811
+
812
+ // The sites that read a wiki, each by name with where it is published
813
+ // beneath it: a wiki is published where its sites are.
814
+ function siteLines(entry) {
815
+ const lines = []
816
+ for (const site of entry.sites || []) {
817
+ lines.push(site.name)
818
+ for (const address of site.addresses || []) lines.push(" " + siteHost(address).grey)
819
+ }
820
+ return lines
821
+ }
822
+
823
+ // A front-end's host, for a line of facts; null when the wiki names none.
824
+ function siteHost(site) {
825
+ if (!site) return null
826
+ try {
827
+ return new URL(site).host
828
+ } catch (e) {
829
+ return site
830
+ }
831
+ }
832
+
833
+ // Any member creates a wiki and is its admin: the grant is theirs whatever
834
+ // else was asked. An org owner administers every wiki already, and gets no
835
+ // grant by creating one. A restricted wiki starts from its grants:
836
+ // --grant <kind>:<id>[:<level>] (repeatable; kind is user or team, level is
837
+ // read, write, or admin, write when unsaid) and --member <person>
838
+ // (repeatable; a person with write). A person is a user id, an @handle, or
839
+ // an email address (helpers.person).
840
+ const GRANT_KINDS = ["user", "team"]
841
+ const GRANT_LEVELS = ["read", "write", "admin"]
842
+ const DEFAULT_GRANT_LEVEL = "write"
843
+
844
+ function parseGrant(value) {
845
+ const [kind, id, level = DEFAULT_GRANT_LEVEL, ...extra] = String(value).split(":")
846
+ if (!GRANT_KINDS.includes(kind) || !id || !GRANT_LEVELS.includes(level) || extra.length) {
847
+ throw friendly("--grant takes <kind>:<id>[:<level>] — kind user or team, level read, write, or admin — got “" + value + "”")
848
+ }
849
+ return { kind, id, level }
850
+ }
851
+
852
+ function grantsOf(argv) {
853
+ const grants = []
854
+ if (argv.grant !== undefined) for (const value of [].concat(argv.grant)) grants.push(parseGrant(value))
855
+ if (argv.member !== undefined) for (const id of [].concat(argv.member)) grants.push({ kind: "user", id: String(id), level: DEFAULT_GRANT_LEVEL })
856
+ return grants.length ? grants : undefined
857
+ }
858
+
859
+ // A grant names who it is to by id on the wire. A person's @handle or email
860
+ // address is looked up first, and must be exactly one member; a team is
861
+ // named by its slug, as `teams` lists it, or by its id.
862
+ const TEAM_ID = /^team_/
863
+ async function namedGrant(client, grant) {
864
+ if (grant.kind === "user") return { ...grant, id: (await person(client, grant.id)).id }
865
+ if (TEAM_ID.test(grant.id)) return grant
866
+ const teams = unwrap(await client.team.list({}))
867
+ const team = teams.find((candidate) => candidate.slug === grant.id)
868
+ if (!team) throw friendly("no team named " + grant.id + " — `known <org> teams` lists them")
869
+ return { ...grant, id: team.id, named: team.slug }
870
+ }
871
+
872
+ function create(argv, ref, rest) {
873
+ return run(async () => {
874
+ const name = rest[0]
875
+ if (!name) throw friendly("name the wiki — `known <org> wiki create <name>`")
876
+ if (!WIKI_NAME.test(String(name))) {
877
+ throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
878
+ }
879
+ const grants = grantsOf(argv)
880
+ const session = sessionFor(argv, ref)
881
+ const client = getClient(argv, { session })
882
+ const named = []
883
+ for (const grant of grants || []) {
884
+ const { kind, id, level } = await namedGrant(client, grant)
885
+ named.push({ kind, id, level })
886
+ }
887
+ const entry = unwrap(await client.wiki.create({
888
+ name: String(name),
889
+ ...(argv.title ? { title: argv.title } : {}),
890
+ ...(argv.description ? { description: String(argv.description) } : {}),
891
+ ...(argv.restricted ? { visibility: "restricted" } : {}),
892
+ ...(grants ? { grants: named } : {})
893
+ }))
894
+ if (output.isJson()) return output.data(entry)
895
+ output.status(
896
+ "created",
897
+ entry.name,
898
+ (entry.visibility === "restricted" ? "restricted wiki — " : "wiki — ") + "address its pages as " + entry.name + ":<path>"
899
+ )
900
+ })
901
+ }
902
+
903
+ // A wiki's own words about itself, and who sees it: --description and
904
+ // --title are its root page's (any writer of the wiki), --restricted and
905
+ // --open its visibility (its admins and org owners). A wiki restricted
906
+ // keeps the grants it has; grant someone first.
907
+ function update(argv, ref, rest) {
908
+ return run(async () => {
909
+ const name = rest[0]
910
+ if (!name || !WIKI_NAME.test(String(name))) throw friendly("name the wiki — `known <org> wiki update <wiki> --description \"…\"`")
911
+ if (argv.restricted && argv.open) throw friendly("pass --restricted or --open, not both")
912
+ const changes = {
913
+ ...(argv.title !== undefined ? { title: String(argv.title) } : {}),
914
+ ...(argv.description !== undefined ? { description: String(argv.description) } : {}),
915
+ ...(argv.restricted ? { visibility: "restricted" } : {}),
916
+ ...(argv.open ? { visibility: "org" } : {})
917
+ }
918
+ if (!Object.keys(changes).length) throw friendly("nothing to change — pass --description, --title, --restricted, or --open")
919
+ const session = sessionFor(argv, ref)
920
+ const entry = unwrap(await getClient(argv, { session }).wiki.update({ wiki: String(name), ...changes }))
921
+ if (output.isJson()) return output.data(entry)
922
+ const said = [
923
+ changes.description !== undefined ? "says what it is for" : null,
924
+ changes.title !== undefined ? "is titled " + entry.title : null,
925
+ changes.visibility ? (entry.visibility === "restricted" ? "is restricted to its grants" : "is open to every member") : null
926
+ ].filter(Boolean)
927
+ output.status("updated", entry.name, said.join(", "))
928
+ })
929
+ }
930
+
931
+ // Grant a person or a team a level on a wiki; granting again changes the
932
+ // level. Its admins and org owners may.
933
+ function grant(argv, ref, rest) {
934
+ return run(async () => {
935
+ const [name, who] = rest
936
+ if (!name || !who) throw friendly("name the wiki and who — `known <org> wiki grant <wiki> <kind>:<id>[:<level>]`")
937
+ if (!WIKI_NAME.test(String(name))) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
938
+ const parsed = parseGrant(who)
939
+ const session = sessionFor(argv, ref)
940
+ const client = getClient(argv, { session })
941
+ const { kind, id, level, named } = await namedGrant(client, parsed)
942
+ const entry = unwrap(await client.wiki.grant({ wiki: String(name), kind, id, level }))
943
+ if (output.isJson()) return output.data(entry)
944
+ output.status("granted", entry.name, kind + " " + (named || id) + " · " + level)
945
+ })
946
+ }
947
+
948
+ function revoke(argv, ref, rest) {
949
+ return run(async () => {
950
+ const [name, who] = rest
951
+ if (!name || !who) throw friendly("name the wiki and who — `known <org> wiki revoke <wiki> <kind>:<id>`")
952
+ if (!WIKI_NAME.test(String(name))) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
953
+ const [kind, given, ...extra] = String(who).split(":")
954
+ if (!GRANT_KINDS.includes(kind) || !given || extra.length) throw friendly("revoke takes <kind>:<id> — kind user or team — got “" + who + "”")
955
+ const session = sessionFor(argv, ref)
956
+ const client = getClient(argv, { session })
957
+ const { id, named } = await namedGrant(client, { kind, id: given })
958
+ const entry = unwrap(await client.wiki.revoke({ wiki: String(name), kind, id }))
959
+ if (output.isJson()) return output.data(entry)
960
+ output.status("revoked", entry.name, kind + " " + (named || id), "muted")
961
+ })
962
+ }
963
+
964
+ // ---- access, renaming, deleting --------------------------------------------
965
+
966
+ // A wiki named on its own, as these verbs take it (no path).
967
+ function wikiArg(value, usage) {
968
+ if (value === undefined || value === true || !WIKI_NAME.test(String(value))) {
969
+ throw friendly("name the wiki — `known <org> wiki " + usage + "`")
970
+ }
971
+ return String(value)
972
+ }
973
+
974
+ // Who reaches a wiki, at what level, and why (the API's access.wiki): a row
975
+ // for everyone when the wiki is open to the org, one per team it is granted
976
+ // to, and one per person who holds it for a reason of their own — a direct
977
+ // grant, a team, owning the org. The reasons are muted.
978
+ function access(argv, ref, rest) {
979
+ return run(async () => {
980
+ const name = wikiArg(rest[0], "access <wiki>")
981
+ const session = sessionFor(argv, ref)
982
+ const client = getClient(argv, { session })
983
+ const res = unwrap(await client.access.wiki({ wiki: name }))
984
+ if (output.isJson()) return output.data(res)
985
+ const by = await actorNames(client, res.people.map((entry) => ({ id: entry.id })))
986
+ const teamName = (id) => {
987
+ const team = res.teams.find((candidate) => candidate.id === id)
988
+ return (team && (team.slug || team.title)) || id
989
+ }
990
+ const rows = [
991
+ ...(res.everyone ? [{
992
+ who: "every member" + (res.members != null ? " (" + res.members + ")" : ""),
993
+ level: res.everyoneLevel || "—".grey,
994
+ why: "open to the organization".grey
995
+ }] : []),
996
+ ...res.teams.map((team) => ({
997
+ who: "team " + (team.slug || team.title || team.id),
998
+ level: team.level,
999
+ why: ("granted to the team · " + team.members + (team.members === 1 ? " person" : " people")).grey
1000
+ })),
1001
+ ...res.people.map((entry) => ({
1002
+ who: by({ id: entry.id }),
1003
+ // an org owner with no grant on a restricted wiki holds no level:
1004
+ // they manage who has access, and read nothing
1005
+ level: entry.level || "—".grey,
1006
+ why: (accessReasons(entry.via, teamName).join(", ") + (entry.level ? "" : " — manages access only")).grey
1007
+ }))
1008
+ ]
1009
+ if (!rows.length) return output.empty("nobody has access to " + res.name)
1010
+ output.table(rows, { columns: ["who", "level", "why"] })
1011
+ if (res.shared && res.ceiling) {
1012
+ output.status("shared", res.name, "from another organization: nobody here holds more than " + res.ceiling, "muted")
1013
+ }
1014
+ })
1015
+ }
1016
+
1017
+ // Rename a wiki (the API's wiki.rename): its name is in every address of
1018
+ // every page, so the wiki's shares, sites and seen marks follow in one step.
1019
+ // Pages elsewhere that link to it by the old name keep those words and are
1020
+ // listed. A person at a terminal is asked first; --yes skips it.
1021
+ function rename(argv, ref, rest) {
1022
+ return run(async () => {
1023
+ if (rest[0] === undefined || rest[1] === undefined) throw friendly("name the wiki and its new name — `known <org> wiki rename <wiki> <new-name>`")
1024
+ const name = wikiArg(rest[0], "rename <wiki> <new-name>")
1025
+ const to = String(rest[1])
1026
+ if (!WIKI_NAME.test(to)) throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + to + "”")
1027
+ const session = sessionFor(argv, ref)
1028
+ const client = getClient(argv, { session })
1029
+ if (!(await confirmStated("Rename the " + name + " wiki to " + to + "? Every address of its pages changes.", argv))) {
1030
+ return output.status("kept", name, null, "muted")
1031
+ }
1032
+ const entry = unwrap(await client.wiki.rename({ wiki: name, name: to }))
1033
+ if (output.isJson()) return output.data(entry)
1034
+ output.status("renamed", entry.name, "was " + entry.renamedFrom)
1035
+ output.pad(() => {
1036
+ for (const link of entry.brokenLinks || []) {
1037
+ console.log(" " + "broken link".red + " " + (link.path + (link.key ? "/" + link.key : "")).cyan + (" still links to " + entry.renamedFrom).grey)
1038
+ }
1039
+ console.log(" " + ("Sites that read it must be republished, and agents must use the new name: " + entry.name + ":<path>.").grey)
1040
+ })
1041
+ })
1042
+ }
1043
+
1044
+ // Delete a wiki (the API's wiki.delete), confirmed by its name: typed at a
1045
+ // terminal, or --confirm <name> from a script. Nothing is destroyed — it
1046
+ // leaves every list, address, share and site at once, and `wiki restore`
1047
+ // brings it back whole. The server's refusal (a site still calls it home)
1048
+ // prints as it was said.
1049
+ function destroy(argv, ref, rest) {
1050
+ return run(async () => {
1051
+ const name = wikiArg(rest[0], "delete <wiki>")
1052
+ const session = sessionFor(argv, ref)
1053
+ const client = getClient(argv, { session })
1054
+ const typed = await confirmByName("Delete the " + name + " wiki? It leaves every list, share and site at once; it can be restored. Type its name to confirm:", argv)
1055
+ if (typed.asked && typed.value !== name) return output.status("kept", name, null, "muted")
1056
+ const res = unwrap(await client.wiki.delete({ wiki: name, confirm: typed.value }))
1057
+ if (output.isJson()) return output.data(res)
1058
+ output.status("deleted", res.name, "it can be restored: known " + (ref ? ref + " " : "") + "wiki restore " + res.name, "danger")
1059
+ })
1060
+ }
1061
+
1062
+ // The org's deleted wikis the caller could restore: those they
1063
+ // administered, which for an org owner is all of them.
1064
+ function deleted(argv, ref) {
1065
+ return run(async () => {
1066
+ const session = sessionFor(argv, ref)
1067
+ const client = getClient(argv, { session })
1068
+ const entries = unwrap(await client.wiki.deleted({}))
1069
+ if (output.isJson()) return output.data(entries)
1070
+ if (!entries.length) return output.empty("no deleted wikis")
1071
+ const by = await actorNames(client, entries.map((entry) => ({ id: entry.deletedBy })))
1072
+ output.table(entries.map((entry) => ({
1073
+ wiki: entry.name.cyan,
1074
+ deleted: entry.deletedAt ? output.timeAgo(new Date(entry.deletedAt)) : "",
1075
+ by: entry.deletedBy ? by({ id: entry.deletedBy }) : ""
1076
+ })))
1077
+ })
1078
+ }
1079
+
1080
+ function restore(argv, ref, rest) {
1081
+ return run(async () => {
1082
+ const name = wikiArg(rest[0], "restore <wiki>")
1083
+ const session = sessionFor(argv, ref)
1084
+ const entry = unwrap(await getClient(argv, { session }).wiki.restore({ wiki: name }))
1085
+ if (output.isJson()) return output.data(entry)
1086
+ output.status("restored", entry.name, "address its pages as " + entry.name + ":<path>")
1087
+ })
1088
+ }
1089
+
1090
+ // ---- sharing with other organizations --------------------------------------
1091
+
1092
+ // One organization owns a wiki and invites another by its slug, up to a
1093
+ // level (read or write, never admin). The other's owners see the invitation,
1094
+ // accept it under a name of their own or decline it, and may leave later;
1095
+ // the home ends a share whenever it likes (the API's share.*).
1096
+ const SHARE_LEVELS = ["read", "write"]
1097
+ const ORG_SLUG = /^[a-z0-9][a-z0-9-]*$/
1098
+ const ORG_ID = /^org_[A-Za-z0-9]+$/
1099
+
1100
+ function orgArg(value, usage) {
1101
+ const text = value === undefined || value === true ? "" : String(value)
1102
+ if (!ORG_SLUG.test(text) && !ORG_ID.test(text)) throw friendly("name the organization by its slug — `known <org> wiki " + usage + "`")
1103
+ return text
1104
+ }
1105
+
1106
+ function shares(argv, ref, rest) {
1107
+ return run(async () => {
1108
+ const name = wikiArg(rest[0], "shares <wiki>")
1109
+ const session = sessionFor(argv, ref)
1110
+ const client = getClient(argv, { session })
1111
+ const entries = unwrap(await client.share.list({ name }))
1112
+ if (output.isJson()) return output.data(entries)
1113
+ if (!entries.length) return output.empty(name + " is not shared with any organization")
1114
+ const by = await actorNames(client, entries.map((entry) => ({ id: entry.invitedBy })))
1115
+ output.table(entries.map((entry) => ({
1116
+ organization: ((entry.guest && (entry.guest.slug || entry.guest.name)) || entry.guestOrgId).cyan,
1117
+ level: entry.ceiling,
1118
+ status: ["invited", "accepted"].includes(entry.status) ? entry.status : entry.status.grey,
1119
+ called: entry.guestName || "—".grey,
1120
+ invited: output.timeAgo(new Date(entry.invitedAt)),
1121
+ by: by({ id: entry.invitedBy })
1122
+ })))
1123
+ })
1124
+ }
1125
+
1126
+ function share(argv, ref, rest) {
1127
+ return run(async () => {
1128
+ if (rest[0] === undefined || rest[1] === undefined) throw friendly("name the wiki and the organization — `known <org> wiki share <wiki> <org> [--level read|write]`")
1129
+ const name = wikiArg(rest[0], "share <wiki> <org>")
1130
+ const guest = orgArg(rest[1], "share <wiki> <org>")
1131
+ if (argv.level !== undefined && !SHARE_LEVELS.includes(argv.level)) throw friendly("--level is read or write — another organization never administers a shared wiki")
1132
+ const session = sessionFor(argv, ref)
1133
+ const entry = unwrap(await getClient(argv, { session }).share.invite({
1134
+ name,
1135
+ org: guest,
1136
+ ...(argv.level !== undefined ? { ceiling: argv.level } : {})
1137
+ }))
1138
+ if (output.isJson()) return output.data(entry)
1139
+ const slug = (entry.guest && entry.guest.slug) || guest
1140
+ output.status("invited", slug, "to " + name + " · " + entry.ceiling + " — its owners accept with `known " + slug + " wiki accept " + session.org.slug + "/" + name + "`")
1141
+ })
1142
+ }
1143
+
1144
+ function unshare(argv, ref, rest) {
1145
+ return run(async () => {
1146
+ if (rest[0] === undefined || rest[1] === undefined) throw friendly("name the wiki and the organization — `known <org> wiki unshare <wiki> <org>`")
1147
+ const name = wikiArg(rest[0], "unshare <wiki> <org>")
1148
+ const guest = orgArg(rest[1], "unshare <wiki> <org>")
1149
+ const session = sessionFor(argv, ref)
1150
+ const client = getClient(argv, { session })
1151
+ if (!(await confirmStated("Stop sharing the " + name + " wiki with " + guest + "? Its people lose it at once.", argv))) {
1152
+ return output.status("kept", name, null, "muted")
1153
+ }
1154
+ const entry = unwrap(await client.share.revoke({ name, org: guest }))
1155
+ if (output.isJson()) return output.data(entry)
1156
+ output.status("unshared", name, "no longer shared with " + ((entry.guest && entry.guest.slug) || guest), "muted")
1157
+ })
1158
+ }
1159
+
1160
+ // An invitation is named as it is listed: the inviting organization's slug,
1161
+ // a slash, the wiki's name there (acme/research).
1162
+ function invitationName(invite) {
1163
+ return (invite.homeSlug || invite.homeOrgId) + "/" + invite.name
1164
+ }
1165
+
1166
+ function invitations(argv, ref) {
1167
+ return run(async () => {
1168
+ const session = sessionFor(argv, ref)
1169
+ const pending = unwrap(await getClient(argv, { session }).share.pending({}))
1170
+ if (output.isJson()) return output.data(pending)
1171
+ if (!pending.length) return output.empty("no invitations waiting")
1172
+ output.table(pending.map((invite) => ({
1173
+ invitation: invitationName(invite).cyan,
1174
+ from: invite.homeName || invite.homeSlug || invite.homeOrgId,
1175
+ level: invite.ceiling,
1176
+ invited: output.timeAgo(new Date(invite.invitedAt))
1177
+ })))
1178
+ output.status("accept", "one with", "known " + (ref ? ref + " " : "") + "wiki accept <invitation> [--as <name>]", "muted")
1179
+ })
1180
+ }
1181
+
1182
+ // The waiting invitation a command names. The API takes the inviting
1183
+ // organization's id and the wiki's name there, so the words on the command
1184
+ // line (<org>/<wiki>, or the wiki alone when only one invitation carries
1185
+ // that name) are matched against what is waiting.
1186
+ async function invitationFor(client, value, verb) {
1187
+ const text = value === undefined || value === true ? "" : String(value)
1188
+ if (!text) throw friendly("name the invitation — `known <org> wiki " + verb + " <org>/<wiki>`, as `wiki invitations` lists them")
1189
+ const slash = text.indexOf("/")
1190
+ const home = slash === -1 ? null : text.slice(0, slash)
1191
+ const name = slash === -1 ? text : text.slice(slash + 1)
1192
+ const pending = unwrap(await client.share.pending({}))
1193
+ const matches = pending.filter((invite) => invite.name === name && (home === null || invite.homeSlug === home || invite.homeOrgId === home))
1194
+ if (matches.length === 1) return matches[0]
1195
+ const error = friendly((matches.length ? "several invitations are called " + text + " — name one as <org>/<wiki>" : "no invitation called " + text) + (pending.length ? "; waiting:" : ""))
1196
+ if (pending.length) error.fields = Object.fromEntries(pending.map((invite) => [invitationName(invite), (invite.homeName || invite.homeSlug || invite.homeOrgId) + " · " + invite.ceiling]))
1197
+ return Promise.reject(error)
1198
+ }
1199
+
1200
+ function accept(argv, ref, rest) {
1201
+ return run(async () => {
1202
+ if (argv.as !== undefined && !WIKI_NAME.test(String(argv.as))) throw friendly("--as takes the name the wiki has here: lowercase letters, digits, and hyphens")
1203
+ const session = sessionFor(argv, ref)
1204
+ const client = getClient(argv, { session })
1205
+ const invite = await invitationFor(client, rest[0], "accept")
1206
+ const res = unwrap(await client.share.accept({
1207
+ home: invite.homeOrgId,
1208
+ name: invite.name,
1209
+ ...(argv.as !== undefined ? { localName: String(argv.as) } : {})
1210
+ }))
1211
+ if (output.isJson()) return output.data(res)
1212
+ output.status("accepted", res.name, "from " + (invite.homeSlug || invite.homeOrgId) + " · " + res.share.ceiling + " — address its pages as " + res.name + ":<path>")
1213
+ })
1214
+ }
1215
+
1216
+ function decline(argv, ref, rest) {
1217
+ return run(async () => {
1218
+ const session = sessionFor(argv, ref)
1219
+ const client = getClient(argv, { session })
1220
+ const invite = await invitationFor(client, rest[0], "decline")
1221
+ const res = unwrap(await client.share.decline({ home: invite.homeOrgId, name: invite.name }))
1222
+ if (output.isJson()) return output.data(res)
1223
+ output.status("declined", invitationName(invite), null, "muted")
1224
+ })
1225
+ }
1226
+
1227
+ function leave(argv, ref, rest) {
1228
+ return run(async () => {
1229
+ const name = wikiArg(rest[0], "leave <wiki>")
1230
+ const session = sessionFor(argv, ref)
1231
+ const client = getClient(argv, { session })
1232
+ if (!(await confirmStated("Leave the " + name + " wiki? Everyone here loses it; its organization can invite this one again.", argv))) {
1233
+ return output.status("kept", name, null, "muted")
1234
+ }
1235
+ const res = unwrap(await client.share.leave({ name }))
1236
+ if (output.isJson()) return output.data(res)
1237
+ output.status("left", res.name, "it stays with its own organization", "muted")
1238
+ })
1239
+ }
1240
+
1241
+ // ---- path + flag helpers ---------------------------------------------------
1242
+
1243
+ // Every path on the command line names its wiki: a colon prefix
1244
+ // (`labs:docs.deploy`) or `--wiki labs`. A path without one is refused,
1245
+ // never sent to a wiki the caller did not name. The API spells paths the
1246
+ // same way, within the org the session is for.
1247
+
1248
+ const WIKI_NAME = /^[a-z0-9][a-z0-9-]*$/
1249
+
1250
+ function splitColon(arg) {
1251
+ if (arg == null) return { name: null, rest: arg }
1252
+ const text = String(arg)
1253
+ const i = text.indexOf(":")
1254
+ const slash = text.indexOf("/")
1255
+ // A colon past the first slash is part of a record's key, not a wiki name.
1256
+ if (i === -1 || (slash !== -1 && i > slash)) return { name: null, rest: text }
1257
+ return { name: text.slice(0, i), rest: text.slice(i + 1) }
1258
+ }
1259
+
1260
+ // A record's address: its page (wiki prefix kept), a slash, its key.
1261
+ // Slugs never contain a slash, so the first one is the boundary.
1262
+ function recordAddress(arg) {
1263
+ const text = String(arg == null ? "" : arg)
1264
+ const slash = text.indexOf("/")
1265
+ if (slash === -1) return { page: text, key: null }
1266
+ const key = text.slice(slash + 1)
1267
+ return { page: text.slice(0, slash), key: key === "" ? null : key }
1268
+ }
1269
+
1270
+ // A record's fields other than its writing, stamps left out.
1271
+ function otherFields(record) {
1272
+ const fields = record ? recordFields(record) : {}
1273
+ delete fields.content
1274
+ return fields
1275
+ }
1276
+
1277
+ // A record's writing: its content when that is a string.
1278
+ function writingOf(record) {
1279
+ return record && typeof record.content === "string" ? record.content : ""
1280
+ }
1281
+
1282
+ // A unified diff between two texts, colored, with a header naming both
1283
+ // sides (null for a side that does not exist).
1284
+ function printPatch(name, fromLabel, toLabel, fromText, toText) {
1285
+ if (fromText === toText) return
1286
+ const { createTwoFilesPatch } = require("diff")
1287
+ const patch = createTwoFilesPatch(fromLabel ? name + "@" + fromLabel : "/dev/null", toLabel ? name + "@" + toLabel : "/dev/null", fromText, toText, undefined, undefined, { context: 3 })
1288
+ const lines = patch.split("\n").filter((line) => !line.startsWith("====") && !line.startsWith("Index:"))
1289
+ console.log()
1290
+ for (const line of lines) {
1291
+ if (line.startsWith("+++") || line.startsWith("---")) console.log(" " + line.grey)
1292
+ else if (line.startsWith("+")) console.log(" " + line.green)
1293
+ else if (line.startsWith("-")) console.log(" " + line.red)
1294
+ else if (line.startsWith("@@")) console.log(" " + line.cyan)
1295
+ else console.log(" " + line)
1296
+ }
1297
+ }
1298
+
1299
+ // The pure half: which wiki does this command address? Validated before any
1300
+ // session is resolved, so conflicts and bad names report without credentials.
1301
+ function wikiAddress(argv, args) {
1302
+ const provided = args.filter((arg) => arg != null && String(arg).trim() !== "")
1303
+ const parsed = provided.map(splitColon)
1304
+ const prefixed = parsed.filter((p) => p.name !== null)
1305
+ const names = [...new Set(prefixed.map((p) => p.name))]
1306
+
1307
+ if (argv.wiki !== undefined && prefixed.length) {
1308
+ throw friendly("pass --wiki or a name: prefix, not both")
1309
+ }
1310
+ if (names.length > 1) {
1311
+ throw friendly("one wiki per command — the paths name " + names.join(" and "))
1312
+ }
1313
+ if (prefixed.length && prefixed.length !== parsed.length) {
1314
+ throw friendly("name the wiki on both paths, or pass --wiki")
1315
+ }
1316
+
1317
+ const name = argv.wiki !== undefined ? String(argv.wiki) : (names[0] ?? null)
1318
+ if (name === null) return { name: null, example: parsed[0] ? parsed[0].rest : null }
1319
+ if (!WIKI_NAME.test(name)) {
1320
+ throw friendly("wiki names are lowercase letters, digits, and hyphens — got “" + name + "”")
1321
+ }
1322
+ return { name }
1323
+ }
1324
+
1325
+ // The resolving half: the full path of each argument, in the wiki the
1326
+ // command names. `general` is every org's first wiki and needs no check;
1327
+ // another name is checked against the org's wikis, so a wrong one is
1328
+ // answered with the ones there are. A command that named no wiki is
1329
+ // refused here, once a session can say which wikis the caller has.
1330
+ const GENERAL = "general"
1331
+
1332
+ async function wikiScope(address, argv, session, client) {
1333
+ const slug = session.org && session.org.slug
1334
+ if (!slug) throw friendly("this session predates org slugs — run `known login` again")
1335
+
1336
+ if (address.name === null) throw await unnamed(address, slug, client)
1337
+
1338
+ if (address.name !== GENERAL) {
1339
+ const entries = unwrap(await client.wiki.list({}))
1340
+ if (!entries.some((e) => e.name === address.name)) {
1341
+ const names = entries.map((e) => e.name).join(", ")
1342
+ throw friendly("no wiki named " + address.name + " — you have: " + names)
1343
+ }
1344
+ }
1345
+
1346
+ return {
1347
+ full(arg) {
1348
+ const rest = splitColon(arg).rest
1349
+ return address.name + ":" + String(rest == null ? "" : rest).trim()
1350
+ }
1351
+ }
1352
+ }
1353
+
1354
+ // The refusal for a path that names no wiki: what to type instead, and the
1355
+ // wikis there are to name, each with what it is for, so the choice can be
1356
+ // made from the refusal alone. A path that
1357
+ // starts with a wiki's name and a dot (`labs.docs`) is the likeliest slip,
1358
+ // so it is answered with the colon (`labs:docs`). The list is best-effort;
1359
+ // the refusal is not.
1360
+ async function unnamed(address, slug, client) {
1361
+ let entries = []
1362
+ try {
1363
+ entries = unwrap(await client.wiki.list({}))
1364
+ } catch (e) {}
1365
+ const path = address.example ? String(address.example).trim() : ""
1366
+ const [first, ...rest] = path.split(".")
1367
+ const entry = entries.find((e) => e.name === first)
1368
+ const example = entry ? entry.name + ":" + rest.join(".") : GENERAL + ":" + path
1369
+ const error = friendly("name the wiki — " + example + " or --wiki " + (entry ? entry.name : GENERAL) + (entries.length ? "; the wikis you have:" : ""))
1370
+ if (entries.length) error.fields = Object.fromEntries(entries.map((e) => [e.name, aboutOf(e)]))
1371
+ return error
1372
+ }
1373
+
1374
+ // What a wiki is for, in a line: its description, else its title, else a
1375
+ // note that it says nothing yet.
1376
+ const ABOUT_MAX = 72
1377
+
1378
+ function aboutOf(entry) {
1379
+ const text = entry.description || entry.title || "no description yet"
1380
+ return text.length > ABOUT_MAX ? text.slice(0, ABOUT_MAX - 1) + "…" : text
1381
+ }
1382
+
1383
+ // One line to stand for a page in the tree: its title, else the first
1384
+ // non-empty content line, cleaned of heading marks and clamped.
1385
+ function preview(node) {
1386
+ let text = node.title || ""
1387
+ if (!text) {
1388
+ text = (node.content || "").split("\n").map((l) => l.trim()).find((l) => l) || ""
1389
+ text = text.replace(/^#+\s*/, "")
1390
+ }
1391
+ text = text.replace(/\s+/g, " ").trim()
1392
+ return text.length > 60 ? text.slice(0, 59) + "…" : text
1393
+ }
1394
+
1395
+ function historical(argv) {
1396
+ if (argv.change && argv.at) throw friendly("pass --change or --at, not both")
1397
+ if (argv.change) return { changeId: intFlag(argv.change, "--change") }
1398
+ if (argv.at) return { at: argv.at }
1399
+ return {}
1400
+ }
1401
+
1402
+ function intFlag(value, name) {
1403
+ const n = Number(value)
1404
+ if (!Number.isInteger(n) || n <= 0) throw friendly(name + " must be a positive integer")
1405
+ return n
1406
+ }
1407
+
1408
+ function recordRange(argv) {
1409
+ if (argv.latest && (argv.since || argv.until || argv.limit || argv.cursor || argv.reverse || argv.at)) {
1410
+ throw friendly("--latest stands alone — drop --since/--until/--limit/--cursor/--reverse/--at")
1411
+ }
1412
+ if (argv.latest) return { latest: true }
1413
+ if (argv.at && (argv.since || argv.until)) throw friendly("--at reads one moment — drop --since/--until")
1414
+ return {
1415
+ ...(argv.at ? { at: String(argv.at) } : {}),
1416
+ ...(argv.reverse ? { reverse: true } : {}),
1417
+ ...(argv.since ? { since: String(argv.since) } : {}),
1418
+ ...(argv.until ? { until: String(argv.until) } : {}),
1419
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {}),
1420
+ ...(argv.cursor ? { cursor: String(argv.cursor) } : {})
1421
+ }
1422
+ }
1423
+
1424
+ function parseJson(text) {
1425
+ try {
1426
+ return JSON.parse(text)
1427
+ } catch (e) {
1428
+ throw friendly("the payload is not valid JSON: " + e.message)
1429
+ }
1430
+ }
1431
+
1432
+ // Metadata replaces whole (omitting it preserves what's there), and the
1433
+ // server wants a plain object — reject anything else before the wire.
1434
+ function metadataFlag(value) {
1435
+ let parsed
1436
+ try {
1437
+ parsed = JSON.parse(value)
1438
+ } catch (e) {
1439
+ throw friendly("--metadata is not valid JSON: " + e.message)
1440
+ }
1441
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1442
+ throw friendly("--metadata must be a JSON object")
1443
+ }
1444
+ return parsed
1445
+ }
1446
+
1447
+ // ---- content input ---------------------------------------------------------
1448
+
1449
+ // The same input rules as `known post`: one source of text, named explicitly —
1450
+ // --text, --file, or piped stdin. Two at once is refused rather than resolved
1451
+ // by precedence, and stdin is only read when it isn't a terminal.
1452
+ async function resolveText(argv) {
1453
+ const piped = !process.stdin.isTTY
1454
+ const given = [
1455
+ argv.text !== undefined ? "--text" : null,
1456
+ argv.file ? "--file" : null,
1457
+ piped && argv.text === undefined && !argv.file ? "stdin" : null
1458
+ ].filter(Boolean)
1459
+
1460
+ if (given.length > 1) {
1461
+ throw friendly("pass only one of " + given.join(" or ") + " — not both")
1462
+ }
1463
+
1464
+ if (argv.text !== undefined) return required(String(argv.text))
1465
+
1466
+ if (argv.file) {
1467
+ try {
1468
+ return required(fs.readFileSync(argv.file, "utf8"))
1469
+ } catch (e) {
1470
+ throw friendly("cannot read " + argv.file + ": " + e.message)
1471
+ }
1472
+ }
1473
+
1474
+ if (piped) return required(await readStdin())
1475
+
1476
+ throw friendly("nothing to write — pass --text \"…\", --file <path>, or pipe content in")
1477
+ }
1478
+
1479
+ function required(text) {
1480
+ if (!text.trim()) throw friendly("nothing to write — the content is empty")
1481
+ return text
1482
+ }
1483
+
1484
+ function readStdin() {
1485
+ return new Promise((resolve, reject) => {
1486
+ let text = ""
1487
+ process.stdin.setEncoding("utf8")
1488
+ process.stdin.on("data", (chunk) => {
1489
+ text += chunk
1490
+ if (text.length > STDIN_MAX) {
1491
+ reject(friendly("input is too long — the maximum is " + STDIN_MAX + " characters"))
1492
+ }
1493
+ })
1494
+ process.stdin.on("end", () => resolve(text))
1495
+ process.stdin.on("error", reject)
1496
+ })
1497
+ }
1498
+
1499
+ function friendly(message) {
1500
+ const e = new Error(message)
1501
+ e.friendly = true
1502
+ return e
1503
+ }