@theholocron/holocron-plugin-linear 0.0.0-stage → 5.0.0-alpha.132

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1265 @@
1
+ import { AuthError, CANONICAL_LABELS, ConfigError, ProviderApiError, connectionProbe, createResolveToken, pickByCreation, readKeysLimited, reportProgress } from "@theholocron/cli";
2
+ import { createLinearClient } from "@theholocron/linear-client";
3
+ import { errorMessage } from "@theholocron/misc-utils";
4
+ // src/auth.ts
5
+ /** Resolves the Linear token from `--token`, `HOLOCRON_LINEAR_TOKEN`, `LINEAR_API_KEY` or the keyring, and throws an `AuthError` when none is set. */
6
+ const resolveToken = createResolveToken({
7
+ envName: "HOLOCRON_LINEAR_TOKEN",
8
+ vendorEnvName: "LINEAR_API_KEY",
9
+ keyringService: "linear",
10
+ errorMessage: "no Linear API key found. Pass --token <KEY>, set HOLOCRON_LINEAR_TOKEN / LINEAR_API_KEY, or run: holocron auth set linear <KEY>"
11
+ });
12
+ /** Every token this plugin takes, for `holocron doctor tokens`. */
13
+ const tokens = [resolveToken.token];
14
+ // src/capabilities/mapping.ts
15
+ const TO_LINEAR = {
16
+ none: 0,
17
+ urgent: 1,
18
+ high: 2,
19
+ medium: 3,
20
+ low: 4
21
+ };
22
+ const FROM_LINEAR = [
23
+ "none",
24
+ "urgent",
25
+ "high",
26
+ "medium",
27
+ "low"
28
+ ];
29
+ /** Linear's number for a neutral priority. */
30
+ function toLinearPriority(priority) {
31
+ return priority ? TO_LINEAR[priority] : 0;
32
+ }
33
+ /** The neutral priority for Linear's number; `undefined` for none, so a record only carries one that was set. */
34
+ function fromLinearPriority(priority) {
35
+ const p = FROM_LINEAR[priority];
36
+ return p && p !== "none" ? p : void 0;
37
+ }
38
+ /** The `issues` capability's status category for a Linear state. */
39
+ function statusCategory(state) {
40
+ switch (state.type) {
41
+ case "triage":
42
+ case "backlog":
43
+ case "unstarted": return "open";
44
+ case "started": return /review/i.test(state.name) ? "in-review" : "in-progress";
45
+ case "completed":
46
+ case "canceled": return "done";
47
+ }
48
+ }
49
+ /** Whether the state ends an issue's life. */
50
+ function isClosed(type) {
51
+ return type === "completed" || type === "canceled";
52
+ }
53
+ /** The board category for a Linear state; a started state named like "Blocked" is `blocked`. */
54
+ function boardCategory(state) {
55
+ switch (state.type) {
56
+ case "triage":
57
+ case "backlog": return "backlog";
58
+ case "unstarted": return "planned";
59
+ case "started": return /block/i.test(state.name) ? "blocked" : "active";
60
+ case "completed":
61
+ case "canceled": return "done";
62
+ }
63
+ }
64
+ /** The Linear state type a new board status of this category is made as. */
65
+ function stateTypeFor(category) {
66
+ switch (category) {
67
+ case "backlog": return "backlog";
68
+ case "planned": return "unstarted";
69
+ case "active":
70
+ case "blocked": return "started";
71
+ case "done": return "completed";
72
+ }
73
+ }
74
+ /** The state an issue with this status category and name lands in: the name when the team has it, else the type's first. */
75
+ function pickState(states, want) {
76
+ const byName = want.name ? states.find((s) => s.name.toLowerCase() === want.name.toLowerCase()) : void 0;
77
+ if (byName) return byName;
78
+ const first = (...types) => {
79
+ for (const type of types) {
80
+ const found = states.find((s) => s.type === type);
81
+ if (found) return found;
82
+ }
83
+ };
84
+ if (want.closed || want.category === "done") return first("completed") ?? first("canceled");
85
+ if (want.category === "in-review") return states.find((s) => s.type === "started" && /review/i.test(s.name)) ?? first("started");
86
+ if (want.category === "in-progress") return first("started");
87
+ return first("unstarted", "backlog", "triage");
88
+ }
89
+ /** `ENG-42` from `ENG-42`, `42` or `#42`; the team key fills a bare number. */
90
+ function normalizeKey(key, teamKey) {
91
+ const trimmed = key.trim().replace(/^#/, "");
92
+ return /^\d+$/.test(trimmed) ? `${teamKey}-${trimmed}` : trimmed.toUpperCase();
93
+ }
94
+ // src/capabilities/issues-migration.ts
95
+ /**
96
+ * Export and import of Linear issues for `holocron migrate`.
97
+ *
98
+ * Linear holds more than GitHub (priority, estimates, relations, backdating), so a move into it loses little; a move
99
+ * back out loses what GitHub cannot hold, and that is `GitHubIssues.import`'s `dropped` list. What this side cannot
100
+ * keep is named in each result's `dropped`:
101
+ * - an assignee is matched by email; no match, no assignee;
102
+ * - a comment is posted by the token's user, so its author is named in the text;
103
+ * - a link to an issue outside the migrated set cannot be made (the target has no key for it).
104
+ * Each imported issue gets an attachment pointing at the source address, which is how a second run finds it.
105
+ * Fields Linear has and the neutral record does not (estimate, due date, cycle) are not exported.
106
+ */
107
+ /** The start of the title of the attachment that records where an issue was migrated from. */
108
+ const MIGRATED_TITLE_PREFIX = "Migrated from ";
109
+ /** The text a comment gets when it is copied: Linear posts as the token's user, so the author is named in the text. */
110
+ function renderComment(comment) {
111
+ return comment.author ? `**${comment.author}** wrote:\n\n${comment.body}` : comment.body;
112
+ }
113
+ /** The Linear user a record's assignee is, matched by email; undefined when there is none or no match. */
114
+ function assigneeFor(record, userIds) {
115
+ return record.assignee?.emailAddress ? userIds.get(record.assignee.emailAddress.toLowerCase()) : void 0;
116
+ }
117
+ /** What Linear cannot carry of this record, for the report. */
118
+ function droppedFor(record, assigneeId) {
119
+ const dropped = [];
120
+ if (record.assignee && !assigneeId) dropped.push("assignee (no Linear user with that email)");
121
+ if (record.comments.some((c) => c.author)) dropped.push("comment authors (named in the text)");
122
+ return dropped;
123
+ }
124
+ /** How many issues a limited export fetches at once when it reads an explicit list of keys. */
125
+ const EXPORT_CONCURRENCY = 4;
126
+ /**
127
+ * Reads the issues `selector` names, with their comments, priority, labels, parent and blockers.
128
+ *
129
+ * With `limit`, only that many survivors of the other filters are read, from the `order` end of the creation order. A
130
+ * list of keys is sorted by issue number (which rises with creation in one team) before anything is fetched, then
131
+ * fetched a few at a time until enough are kept; a listing already carries `createdAt`, so it is sorted on that and cut
132
+ * before the per-issue comment requests. `info.matched` receives how many the selection matched before the cut.
133
+ */
134
+ async function exportIssues(scope, selector, info = {}) {
135
+ const { client } = scope;
136
+ const team = await scope.team();
137
+ const since = selector.since ? Date.parse(selector.since) : void 0;
138
+ const survives = (issue) => !(selector.openOnly && isClosed(issue.state.type)) && (since === void 0 || Date.parse(issue.updatedAt) >= since);
139
+ const { limit, order = "oldest" } = selector;
140
+ let issues;
141
+ if (selector.keys) {
142
+ const fetch = (k) => client.issues.get(normalizeKey(k, scope.teamKey));
143
+ info.matched = selector.keys.length;
144
+ issues = limit === void 0 ? (await Promise.all(selector.keys.map(fetch))).filter(survives) : await readKeysLimited({
145
+ keys: selector.keys,
146
+ order,
147
+ limit,
148
+ concurrency: EXPORT_CONCURRENCY,
149
+ fetch,
150
+ keep: survives
151
+ });
152
+ } else {
153
+ let raw;
154
+ if (selector.milestone) {
155
+ const project = await findProject$1(scope, selector.milestone);
156
+ if (!project) throw new Error(`Project "${selector.milestone}" not found in Linear.`);
157
+ raw = await client.issues.list({ projectId: project.id });
158
+ } else if (selector.all) raw = await client.issues.list({ teamId: team.id });
159
+ else throw new Error("export needs keys, a milestone or all");
160
+ issues = raw.filter(survives);
161
+ info.matched = issues.length;
162
+ if (limit !== void 0) issues = pickByCreation(issues, (i) => i.createdAt, order, limit);
163
+ }
164
+ const records = [];
165
+ for (const issue of issues) {
166
+ reportProgress(info.onProgress, records.length, issues.length);
167
+ const closed = isClosed(issue.state.type);
168
+ const comments = await client.issues.comments(issue.id);
169
+ const priority = fromLinearPriority(issue.priority);
170
+ const migratedFrom = issue.attachments?.nodes.find((a) => a.title.startsWith(MIGRATED_TITLE_PREFIX))?.url;
171
+ records.push({
172
+ key: issue.identifier,
173
+ url: issue.url,
174
+ title: issue.title,
175
+ ...issue.description ? { body: issue.description } : {},
176
+ status: issue.state.name,
177
+ statusCategory: statusCategory(issue.state),
178
+ closed,
179
+ ...priority ? { priority } : {},
180
+ labels: issue.labels.nodes.map((l) => l.name),
181
+ ...issue.assignee ? { assignee: {
182
+ id: issue.assignee.id,
183
+ displayName: issue.assignee.displayName || issue.assignee.name,
184
+ ...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
185
+ } } : {},
186
+ ...issue.project ? { milestone: issue.project.name } : {},
187
+ ...issue.parent ? { parent: issue.parent.identifier } : {},
188
+ blockedBy: issue.inverseRelations.nodes.filter((r) => r.type === "blocks").map((r) => r.issue.identifier),
189
+ comments: comments.map((c) => ({
190
+ ...c.user ? { author: c.user.displayName || c.user.name } : {},
191
+ body: c.body,
192
+ createdAt: c.createdAt
193
+ })),
194
+ createdAt: issue.createdAt,
195
+ updatedAt: issue.updatedAt,
196
+ ...migratedFrom ? { migratedFrom } : {}
197
+ });
198
+ }
199
+ reportProgress(info.onProgress, records.length, issues.length);
200
+ return records;
201
+ }
202
+ /** Makes the records as issues in the team, then sets the parent and blocked-by links among them. `results` receives each record as it is done, so a caller that stops the run on an error still has the finished ones. */
203
+ async function importIssues(scope, records, options = {}, results = []) {
204
+ const { client } = scope;
205
+ const team = await scope.team();
206
+ const [states, labels, users] = await Promise.all([
207
+ client.teams.states(team.id),
208
+ client.teams.labels(team.id),
209
+ client.teams.users()
210
+ ]);
211
+ const labelIds = new Map(labels.map((l) => [l.name.toLowerCase(), l.id]));
212
+ const userIds = new Map(users.filter((u) => u.email).map((u) => [u.email.toLowerCase(), u.id]));
213
+ const projects = /* @__PURE__ */ new Map();
214
+ const projectId = async (name) => {
215
+ const key = name.toLowerCase();
216
+ if (!projects.has(key)) {
217
+ const found = await findProject$1(scope, name);
218
+ projects.set(key, found?.id ?? (await client.projects.create({
219
+ name,
220
+ teamIds: [team.id]
221
+ })).id);
222
+ }
223
+ return projects.get(key);
224
+ };
225
+ const made = /* @__PURE__ */ new Map();
226
+ const tick = () => reportProgress(options.onProgress, results.length, records.length);
227
+ for (const record of records) {
228
+ const existing = (await client.issues.attachmentsForUrl(record.url)).find((a) => a.issue.identifier.startsWith(`${team.key}-`));
229
+ if (existing) {
230
+ made.set(record.key, {
231
+ id: existing.issue.id,
232
+ created: false
233
+ });
234
+ results.push({
235
+ source: record.key,
236
+ key: existing.issue.identifier,
237
+ created: false,
238
+ dropped: []
239
+ });
240
+ tick();
241
+ continue;
242
+ }
243
+ const assigneeId = assigneeFor(record, userIds);
244
+ const dropped = droppedFor(record, assigneeId);
245
+ if (options.dryRun) {
246
+ results.push({
247
+ source: record.key,
248
+ created: true,
249
+ dropped
250
+ });
251
+ tick();
252
+ continue;
253
+ }
254
+ const state = pickState(states, {
255
+ ...record.status ? { name: record.status } : {},
256
+ category: record.statusCategory,
257
+ closed: record.closed
258
+ });
259
+ const ids = [];
260
+ for (const name of record.labels) {
261
+ let id = labelIds.get(name.toLowerCase());
262
+ if (!id) {
263
+ id = (await client.teams.createLabel({
264
+ name,
265
+ teamId: team.id
266
+ })).id;
267
+ labelIds.set(name.toLowerCase(), id);
268
+ }
269
+ ids.push(id);
270
+ }
271
+ const milestone = options.milestone ?? record.milestone;
272
+ const project = milestone ? await projectId(milestone) : void 0;
273
+ const issue = await client.issues.create({
274
+ teamId: team.id,
275
+ title: record.title,
276
+ ...record.body ? { description: record.body } : {},
277
+ priority: toLinearPriority(record.priority),
278
+ ...state ? { stateId: state.id } : {},
279
+ ...assigneeId ? { assigneeId } : {},
280
+ ...ids.length > 0 ? { labelIds: ids } : {},
281
+ ...project ? { projectId: project } : {},
282
+ createdAt: record.createdAt
283
+ });
284
+ await client.issues.attach(issue.id, record.url, `${MIGRATED_TITLE_PREFIX}${record.key}`);
285
+ for (const comment of record.comments) await client.issues.comment(issue.id, renderComment(comment), comment.createdAt);
286
+ made.set(record.key, {
287
+ id: issue.id,
288
+ created: true
289
+ });
290
+ results.push({
291
+ source: record.key,
292
+ key: issue.identifier,
293
+ created: true,
294
+ dropped
295
+ });
296
+ tick();
297
+ }
298
+ if (!options.dryRun) await linkIssues(scope, records, made, results);
299
+ return results;
300
+ }
301
+ /** Second pass: parent and blocked-by links among the issues this run made. */
302
+ async function linkIssues(scope, records, made, results) {
303
+ for (const record of records) {
304
+ const self = made.get(record.key);
305
+ const result = results.find((r) => r.source === record.key);
306
+ if (!self?.created || !result) continue;
307
+ if (record.parent) {
308
+ const parent = made.get(record.parent);
309
+ if (parent) await scope.client.issues.update(self.id, { parentId: parent.id });
310
+ else result.dropped.push(`parent ${record.parent} (not in this migration)`);
311
+ }
312
+ for (const blocker of record.blockedBy) {
313
+ const other = made.get(blocker);
314
+ if (other) await scope.client.issues.relate(other.id, self.id, "blocks");
315
+ else result.dropped.push(`blockedBy ${blocker} (not in this migration)`);
316
+ }
317
+ }
318
+ }
319
+ async function findProject$1(scope, ref) {
320
+ const team = await scope.team();
321
+ return (await scope.client.projects.list()).find((p) => !p.archivedAt && p.teams.nodes.some((t) => t.id === team.id) && (p.id === ref || p.name.toLowerCase() === ref.toLowerCase()));
322
+ }
323
+ // src/capabilities/issues-sync.ts
324
+ /** Whether Linear is asking to be left alone: a 429, or an error that says the rate limit was reached. */
325
+ function isRateLimited(err) {
326
+ return err instanceof ProviderApiError && (err.status === 429 || /rate ?limit/i.test(err.message));
327
+ }
328
+ const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
329
+ /** Makes the records missing from the team and updates the ones an earlier run made. See the file comment. */
330
+ async function syncIssues(scope, records, options = {}) {
331
+ const { client } = scope;
332
+ const results = /* @__PURE__ */ new Map();
333
+ const created = [];
334
+ const tick = () => reportProgress(options.onProgress, results.size, records.length);
335
+ try {
336
+ const team = await scope.team();
337
+ const existing = [];
338
+ const missing = [];
339
+ for (const record of records) {
340
+ const attached = (await client.issues.attachmentsForUrl(record.url)).find((a) => a.issue.identifier.startsWith(`${team.key}-`));
341
+ if (attached) existing.push({
342
+ record,
343
+ identifier: attached.issue.identifier
344
+ });
345
+ else missing.push(record);
346
+ }
347
+ try {
348
+ await importIssues(scope, missing, {
349
+ ...options,
350
+ onProgress: (done) => reportProgress(options.onProgress, done, records.length)
351
+ }, created);
352
+ } finally {
353
+ for (const r of created) results.set(r.source, {
354
+ ...r,
355
+ updated: false,
356
+ changes: []
357
+ });
358
+ }
359
+ if (existing.length > 0) {
360
+ const [states, labels, users] = await Promise.all([
361
+ client.teams.states(team.id),
362
+ client.teams.labels(team.id),
363
+ client.teams.users()
364
+ ]);
365
+ const labelIds = new Map(labels.map((l) => [l.name.toLowerCase(), l.id]));
366
+ const userIds = new Map(users.filter((u) => u.email).map((u) => [u.email.toLowerCase(), u.id]));
367
+ for (const { record, identifier } of existing) {
368
+ const issue = await client.issues.get(identifier);
369
+ const patch = {};
370
+ const changes = [];
371
+ if (issue.title !== record.title) {
372
+ patch.title = record.title;
373
+ changes.push("title");
374
+ }
375
+ if ((issue.description ?? "") !== (record.body ?? "")) {
376
+ patch.description = record.body ?? "";
377
+ changes.push("description");
378
+ }
379
+ if (issue.priority !== toLinearPriority(record.priority)) {
380
+ patch.priority = toLinearPriority(record.priority);
381
+ changes.push("priority");
382
+ }
383
+ const wanted = pickState(states, {
384
+ ...record.status ? { name: record.status } : {},
385
+ category: record.statusCategory,
386
+ closed: record.closed
387
+ });
388
+ const stateDiffers = record.status !== void 0 && wanted?.name.toLowerCase() === record.status.toLowerCase() ? wanted.id !== issue.state.id : statusCategory(issue.state) !== record.statusCategory;
389
+ if (wanted && stateDiffers) {
390
+ patch.stateId = wanted.id;
391
+ changes.push("state");
392
+ }
393
+ if (sorted(record.labels) !== sorted(issue.labels.nodes.map((l) => l.name))) {
394
+ changes.push("labels");
395
+ if (!options.dryRun) {
396
+ const ids = [];
397
+ for (const name of record.labels) {
398
+ let id = labelIds.get(name.toLowerCase());
399
+ if (!id) {
400
+ id = (await client.teams.createLabel({
401
+ name,
402
+ teamId: team.id
403
+ })).id;
404
+ labelIds.set(name.toLowerCase(), id);
405
+ }
406
+ ids.push(id);
407
+ }
408
+ patch.labelIds = ids;
409
+ }
410
+ }
411
+ const assigneeId = assigneeFor(record, userIds);
412
+ if (assigneeId && issue.assignee?.id !== assigneeId) {
413
+ patch.assigneeId = assigneeId;
414
+ changes.push("assignee");
415
+ }
416
+ const have = await client.issues.comments(issue.id);
417
+ const missingComments = record.comments.filter((c) => !have.some((h) => Date.parse(h.createdAt) === Date.parse(c.createdAt) || h.body === renderComment(c)));
418
+ if (missingComments.length > 0) changes.push("comments");
419
+ if (!options.dryRun) {
420
+ if (Object.keys(patch).length > 0) await client.issues.update(issue.id, patch);
421
+ for (const c of missingComments) await client.issues.comment(issue.id, renderComment(c), c.createdAt);
422
+ }
423
+ results.set(record.key, {
424
+ source: record.key,
425
+ key: issue.identifier,
426
+ created: false,
427
+ updated: changes.length > 0,
428
+ changes,
429
+ dropped: droppedFor(record, assigneeId)
430
+ });
431
+ tick();
432
+ }
433
+ }
434
+ } catch (err) {
435
+ if (!isRateLimited(err)) throw err;
436
+ }
437
+ return records.filter((r) => results.has(r.key)).map((r) => results.get(r.key));
438
+ }
439
+ // src/capabilities/issues.ts
440
+ function toUser(u) {
441
+ return {
442
+ id: u.id,
443
+ displayName: u.displayName || u.name,
444
+ ...u.email ? { emailAddress: u.email } : {}
445
+ };
446
+ }
447
+ /** The Linear implementation of the `issues` capability. */
448
+ var LinearIssues = class {
449
+ scope;
450
+ opts;
451
+ /** Capability key, always `"issues"`. */
452
+ key = "issues";
453
+ /** Provider name, always `"linear"`. */
454
+ providerName = "linear";
455
+ constructor(scope, opts = {}) {
456
+ this.scope = scope;
457
+ this.opts = opts;
458
+ }
459
+ /** The user the token belongs to. */
460
+ async getMyself() {
461
+ return toUser((await this.scope.client.teams.viewer()).user);
462
+ }
463
+ /** The team's issues, newest update first. */
464
+ async search(filter) {
465
+ const team = await this.scope.team();
466
+ const assigneeId = filter.assignee === "currentUser" ? (await this.scope.client.teams.viewer()).user.id : filter.assignee || void 0;
467
+ return (await this.scope.client.issues.list({
468
+ teamId: team.id,
469
+ ...assigneeId ? { assigneeId } : {},
470
+ ...filter.openOnly ? { openOnly: true } : {},
471
+ limit: filter.limit ?? 50
472
+ })).map(mapIssue);
473
+ }
474
+ /** One issue by its key. */
475
+ async get(key) {
476
+ return mapIssue(await this.scope.client.issues.get(normalizeKey(key, this.scope.teamKey)));
477
+ }
478
+ /** Makes an issue; labels the team lacks are made, and `milestone` is a project's name or id. */
479
+ async create(input) {
480
+ const { client } = this.scope;
481
+ const team = await this.scope.team();
482
+ const labelIds = input.labels?.length ? await this.labelIds(team.id, input.labels) : [];
483
+ let projectId;
484
+ if (input.milestone) {
485
+ const match = (await client.projects.list()).find((p) => p.id === input.milestone || p.name.toLowerCase() === input.milestone.toLowerCase());
486
+ if (!match) throw new Error(`Project "${input.milestone}" not found in Linear. Use the id or an exact name.`);
487
+ projectId = match.id;
488
+ }
489
+ return { key: (await client.issues.create({
490
+ teamId: team.id,
491
+ title: input.summary,
492
+ ...input.body ? { description: input.body } : {},
493
+ ...labelIds.length > 0 ? { labelIds } : {},
494
+ ...projectId ? { projectId } : {}
495
+ })).identifier };
496
+ }
497
+ /** Moves the issue to the state its slot names. Idempotent. */
498
+ async transition(key, slot) {
499
+ const team = await this.scope.team();
500
+ const issue = await this.scope.client.issues.get(normalizeKey(key, this.scope.teamKey));
501
+ const states = await this.scope.client.teams.states(team.id);
502
+ const target = this.stateFor(slot, states);
503
+ if (!target) throw new Error(`no Linear state for \`${slot}\` in team ${team.key}; name one with \`states.${slot}\` in the plugin options`);
504
+ if (issue.state.id === target.id) return {
505
+ transitioned: false,
506
+ status: target.name,
507
+ via: "already there"
508
+ };
509
+ await this.scope.client.issues.update(issue.id, { stateId: target.id });
510
+ return {
511
+ transitioned: true,
512
+ status: target.name,
513
+ via: `state set to ${target.name}`
514
+ };
515
+ }
516
+ /** Adds a comment to the issue. */
517
+ async comment(key, body) {
518
+ const issue = await this.scope.client.issues.get(normalizeKey(key, this.scope.teamKey));
519
+ await this.scope.client.issues.comment(issue.id, body);
520
+ }
521
+ /** Checks the user, the team and which states the lifecycle slots resolve to. */
522
+ async doctor() {
523
+ const { user } = await this.scope.client.teams.viewer();
524
+ const team = await this.scope.team();
525
+ const states = await this.scope.client.teams.states(team.id);
526
+ return {
527
+ authedAs: `${user.displayName} (${user.email ?? user.id})`,
528
+ projectLabel: `Team: ${team.key} (${team.name})`,
529
+ statuses: states.map((s) => ({
530
+ name: s.name,
531
+ category: statusCategory(s)
532
+ })),
533
+ lifecycle: [
534
+ "inProgress",
535
+ "inReview",
536
+ "done"
537
+ ].map((slot) => {
538
+ const state = this.stateFor(slot, states);
539
+ return {
540
+ slot,
541
+ value: state?.name ?? null,
542
+ resolved: state !== void 0,
543
+ note: state ? `state exists in team ${team.key}` : `no matching state; set \`states.${slot}\` in the plugin options`
544
+ };
545
+ })
546
+ };
547
+ }
548
+ /** Reads issues with comments, priority, labels, parent and blockers, for `holocron migrate`. */
549
+ export(selector, info) {
550
+ return exportIssues(this.scope, selector, info);
551
+ }
552
+ /** Makes the records as issues in the team; one already made by an earlier run is skipped. */
553
+ import(records, options) {
554
+ return importIssues(this.scope, records, options);
555
+ }
556
+ /** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
557
+ sync(records, options) {
558
+ return syncIssues(this.scope, records, options);
559
+ }
560
+ stateFor(slot, states) {
561
+ if (slot === "done") return pickState(states, { category: "done" });
562
+ const name = this.opts.states?.[slot];
563
+ return pickState(states, {
564
+ ...name ? { name } : {},
565
+ category: slot === "inReview" ? "in-review" : "in-progress"
566
+ });
567
+ }
568
+ async labelIds(teamId, names) {
569
+ const have = new Map((await this.scope.client.teams.labels(teamId)).map((l) => [l.name.toLowerCase(), l.id]));
570
+ const ids = [];
571
+ for (const name of names) {
572
+ let id = have.get(name.toLowerCase());
573
+ if (!id) {
574
+ id = (await this.scope.client.teams.createLabel({
575
+ name,
576
+ teamId
577
+ })).id;
578
+ have.set(name.toLowerCase(), id);
579
+ }
580
+ ids.push(id);
581
+ }
582
+ return ids;
583
+ }
584
+ };
585
+ function mapIssue(raw) {
586
+ return {
587
+ key: raw.identifier,
588
+ id: raw.id,
589
+ summary: raw.title,
590
+ ...raw.description ? { body: raw.description } : {},
591
+ status: raw.state.name,
592
+ statusCategory: statusCategory(raw.state),
593
+ assignee: raw.assignee ? toUser(raw.assignee) : null,
594
+ updated: raw.updatedAt,
595
+ url: raw.url
596
+ };
597
+ }
598
+ // src/capabilities/projects.ts
599
+ /** The names of the two automations the team settings expose, which a template's `rules` can ask for. */
600
+ const AUTO_ARCHIVE_RULE = "Auto-archive closed issues";
601
+ /** See {@link AUTO_ARCHIVE_RULE}. */
602
+ const AUTO_CLOSE_RULE = "Auto-close stale issues";
603
+ const PRIORITY_FIELD = {
604
+ name: "Priority",
605
+ type: "single_select",
606
+ options: [
607
+ "Urgent",
608
+ "High",
609
+ "Medium",
610
+ "Low"
611
+ ]
612
+ };
613
+ function toSummary(p) {
614
+ return {
615
+ id: p.id,
616
+ name: p.name,
617
+ url: p.url,
618
+ closed: p.archivedAt !== null
619
+ };
620
+ }
621
+ /** The Linear implementation of the `projects` capability, backed by Linear projects and the team's workflow. */
622
+ var LinearProjects = class {
623
+ scope;
624
+ /** Capability key, always `"projects"`. */
625
+ key = "projects";
626
+ /** Provider name, always `"linear"`. */
627
+ providerName = "linear";
628
+ constructor(scope) {
629
+ this.scope = scope;
630
+ }
631
+ /** Every project of the team, open and archived. The owner is the workspace, which the token already names. */
632
+ async list(_owner) {
633
+ const team = await this.scope.team();
634
+ return (await this.scope.client.projects.list()).filter((p) => p.teams.nodes.some((t) => t.id === team.id)).map(toSummary);
635
+ }
636
+ /** The open project with exactly this name. */
637
+ async find(owner, name) {
638
+ return (await this.list(owner)).find((b) => !b.closed && b.name === name);
639
+ }
640
+ /** Makes a project for the team and brings the team's statuses in line with the template. */
641
+ async create(owner, name, template) {
642
+ const team = await this.scope.team();
643
+ const board = toSummary(await this.scope.client.projects.create({
644
+ name,
645
+ teamIds: [team.id]
646
+ }));
647
+ await this.ensure(owner, board, template);
648
+ return board;
649
+ }
650
+ /** Archives the project. Reversible in Linear. */
651
+ async close(_owner, board) {
652
+ await this.scope.client.projects.archive(board.id);
653
+ }
654
+ /** The team's statuses, the built-in priority, and the team's automation. */
655
+ async read(_owner, board) {
656
+ const team = await this.scope.team();
657
+ const [states, automation] = await Promise.all([this.scope.client.teams.states(team.id), this.scope.client.teams.automation(team.id)]);
658
+ return {
659
+ board,
660
+ statuses: states.map((s) => s.name),
661
+ fields: [PRIORITY_FIELD],
662
+ views: [],
663
+ rules: rulesOf(automation)
664
+ };
665
+ }
666
+ /**
667
+ * Adds the template's missing statuses to the team (never removes or renames one). Everything Linear cannot
668
+ * create from the API is a `todo`.
669
+ */
670
+ async ensure(_owner, _board, template) {
671
+ const team = await this.scope.team();
672
+ const [states, automation] = await Promise.all([this.scope.client.teams.states(team.id), this.scope.client.teams.automation(team.id)]);
673
+ const changes = [];
674
+ const todos = [];
675
+ for (const want of template.statuses) {
676
+ if (states.some((s) => s.name.toLowerCase() === want.name.toLowerCase())) continue;
677
+ await this.scope.client.teams.createState(team.id, {
678
+ name: want.name,
679
+ type: stateTypeFor(want.category),
680
+ ...want.description ? { description: want.description } : {}
681
+ });
682
+ changes.push(`status ${want.name} added to team ${team.key}`);
683
+ }
684
+ for (const field of template.fields) {
685
+ if (field.name === PRIORITY_FIELD.name) continue;
686
+ todos.push(`field "${field.name}": Linear has no custom fields; use labels or put it in the description`);
687
+ }
688
+ for (const view of template.views) todos.push(`view "${view.name}": create it in Linear; views are not managed here`);
689
+ const rules = rulesOf(automation);
690
+ for (const rule of template.rules ?? []) {
691
+ const have = rules.find((r) => r.name.toLowerCase() === rule.toLowerCase());
692
+ if (!have) todos.push(`automation "${rule}": Linear has no such team setting`);
693
+ else if (!have.enabled) todos.push(`turn on "${rule}" in Linear: Settings → Teams → ${team.name} → Workflow`);
694
+ }
695
+ return {
696
+ created: false,
697
+ changes,
698
+ todos
699
+ };
700
+ }
701
+ /** The project's issues with status, whether they are open, priority and open blockers. */
702
+ async items(_owner, board, template) {
703
+ const categories = new Map(template.statuses.map((s) => [s.name.toLowerCase(), s.category]));
704
+ return (await this.scope.client.issues.list({ projectId: board.id })).map((issue) => {
705
+ const priority = fromLinearPriority(issue.priority);
706
+ return {
707
+ key: issue.identifier,
708
+ title: issue.title,
709
+ open: !isClosed(issue.state.type),
710
+ status: issue.state.name,
711
+ category: categories.get(issue.state.name.toLowerCase()) ?? boardCategory(issue.state),
712
+ blockedBy: issue.inverseRelations.nodes.filter((r) => r.type === "blocks" && !isClosed(r.issue.state.type)).map((r) => r.issue.identifier),
713
+ ...priority ? { priority } : {}
714
+ };
715
+ });
716
+ }
717
+ /** Puts an issue in the team state with this name; `transitioned` is false when it already is there. */
718
+ async setStatus(_owner, _board, key, status) {
719
+ const team = await this.scope.team();
720
+ const issue = await this.scope.client.issues.get(normalizeKey(key, this.scope.teamKey));
721
+ const target = (await this.scope.client.teams.states(team.id)).find((s) => s.name.toLowerCase() === status.toLowerCase());
722
+ if (!target) throw new Error(`team ${team.key} has no status "${status}"`);
723
+ if (issue.state.id === target.id) return {
724
+ transitioned: false,
725
+ status: target.name,
726
+ via: "already there"
727
+ };
728
+ await this.scope.client.issues.update(issue.id, { stateId: target.id });
729
+ return {
730
+ transitioned: true,
731
+ status: target.name
732
+ };
733
+ }
734
+ /**
735
+ * Moves the open issues of one project into another. An issue is in one project, so there is nothing to keep on the
736
+ * target; status and priority belong to the issue and travel with it. Closed issues stay where they are.
737
+ */
738
+ async move(_owner, from, to, _template) {
739
+ const issues = await this.scope.client.issues.list({ projectId: from.id });
740
+ const report = {
741
+ moved: [],
742
+ kept: [],
743
+ left: []
744
+ };
745
+ for (const issue of issues) {
746
+ if (isClosed(issue.state.type)) {
747
+ report.left.push(issue.identifier);
748
+ continue;
749
+ }
750
+ await this.scope.client.issues.update(issue.id, { projectId: to.id });
751
+ report.moved.push(issue.identifier);
752
+ }
753
+ return report;
754
+ }
755
+ /** A smoke check: how many projects the token can see for the team. */
756
+ async whoami() {
757
+ return {
758
+ ok: true,
759
+ boards: (await this.list("")).length
760
+ };
761
+ }
762
+ };
763
+ function rulesOf(a) {
764
+ return [{
765
+ name: AUTO_ARCHIVE_RULE,
766
+ enabled: (a.autoArchivePeriod ?? 0) > 0
767
+ }, {
768
+ name: AUTO_CLOSE_RULE,
769
+ enabled: (a.autoClosePeriod ?? 0) > 0
770
+ }];
771
+ }
772
+ // src/capabilities/team-scope.ts
773
+ /** Binds a client to a team key; the team is read on first use and kept. */
774
+ function createTeamScope(client, teamKey) {
775
+ let found;
776
+ return {
777
+ client,
778
+ teamKey,
779
+ team: () => found ??= client.teams.find(teamKey).then((team) => {
780
+ if (!team) throw new Error(`Linear team "${teamKey}" not found; check the \`team\` option and the token's access.`);
781
+ return team;
782
+ })
783
+ };
784
+ }
785
+ // src/provider/automation.ts
786
+ const months$1 = (n) => n ? `${n} month${n === 1 ? "" : "s"}` : "off";
787
+ /** Compares `autoClose` (period and state) with the team. */
788
+ function closeGap(want, have, states) {
789
+ const gap = {
790
+ problems: [],
791
+ patch: {},
792
+ unresolved: false
793
+ };
794
+ if ((have.autoClosePeriod ?? 0) !== want.months) {
795
+ gap.problems.push(`auto-close is ${months$1(have.autoClosePeriod)}, declared ${months$1(want.months)}`);
796
+ gap.patch.autoClosePeriod = want.months === 0 ? null : want.months;
797
+ }
798
+ if (want.state) {
799
+ const wanted = want.state.toLowerCase();
800
+ const state = states.find((s) => s.name.toLowerCase() === wanted);
801
+ if (!state) {
802
+ gap.unresolved = true;
803
+ gap.patch = {};
804
+ gap.problems.push(`the team has no state "${want.state}" to put auto-closed issues in`);
805
+ } else if (have.autoCloseState?.id !== state.id) {
806
+ gap.problems.push(`auto-close state is ${have.autoCloseState?.name ?? "not set"}, declared ${state.name}`);
807
+ gap.patch.autoCloseStateId = state.id;
808
+ }
809
+ }
810
+ return gap;
811
+ }
812
+ /** Compares `autoArchive` with the team. */
813
+ function archiveGap(want, have) {
814
+ if ((have.autoArchivePeriod ?? 0) === want.months) return {
815
+ problems: [],
816
+ patch: {},
817
+ unresolved: false
818
+ };
819
+ return {
820
+ problems: [`auto-archive is ${months$1(have.autoArchivePeriod)}, declared ${months$1(want.months)}`],
821
+ patch: { autoArchivePeriod: want.months },
822
+ unresolved: false
823
+ };
824
+ }
825
+ // src/provider/git-automation.ts
826
+ /** Whether a rule is the one for this event and branch; a regular-expression target never matches a literal name. */
827
+ function matches(rule, want) {
828
+ if (rule.event !== want.event) return false;
829
+ if (want.branch === void 0) return rule.targetBranch === null;
830
+ return rule.targetBranch !== null && !rule.targetBranch.isRegex && rule.targetBranch.branchPattern === want.branch;
831
+ }
832
+ /**
833
+ * Compares each declared git rule (`event`, `state`, optional literal target `branch`) with the team's rules. A rule is
834
+ * found by its event and branch, never by id, so one made by hand is adopted; its state is what is compared. Rules the
835
+ * block does not declare are never reported or touched.
836
+ */
837
+ function gitGaps(want, have, states) {
838
+ return want.map((rule) => {
839
+ const label = rule.branch === void 0 ? rule.event : `${rule.event}@${rule.branch}`;
840
+ const gap = {
841
+ id: `git:${label}`,
842
+ title: `git automation ${label}`,
843
+ problems: [],
844
+ unresolved: false
845
+ };
846
+ const wanted = rule.state.toLowerCase();
847
+ const state = states.find((s) => s.name.toLowerCase() === wanted);
848
+ if (!state) {
849
+ gap.unresolved = true;
850
+ gap.problems.push(`the team has no state "${rule.state}" for ${label}`);
851
+ return gap;
852
+ }
853
+ const found = have.find((r) => matches(r, rule));
854
+ if (!found) {
855
+ gap.problems.push(`no ${label} rule, declared ${state.name}`);
856
+ gap.action = {
857
+ kind: "create",
858
+ event: rule.event,
859
+ stateId: state.id,
860
+ ...rule.branch === void 0 ? {} : { branch: rule.branch }
861
+ };
862
+ } else if (found.state?.id !== state.id) {
863
+ gap.problems.push(`${label} moves to ${found.state?.name ?? "nothing"}, declared ${state.name}`);
864
+ gap.action = {
865
+ kind: "update",
866
+ ruleId: found.id,
867
+ stateId: state.id
868
+ };
869
+ }
870
+ return gap;
871
+ });
872
+ }
873
+ /** The id of each literal target branch some existing rule uses, by name, so setup does not make one twice. */
874
+ function knownBranches(have) {
875
+ const known = /* @__PURE__ */ new Map();
876
+ for (const r of have) if (r.targetBranch && !r.targetBranch.isRegex) known.set(r.targetBranch.branchPattern, r.targetBranch.id);
877
+ return known;
878
+ }
879
+ // src/provider/rows.ts
880
+ /** One row of a provider step. `problems` is for a failure: a line per thing that is wrong, or the fix. */
881
+ function row(id, title, status, detail, problems = []) {
882
+ return {
883
+ id,
884
+ title,
885
+ status,
886
+ detail,
887
+ problems
888
+ };
889
+ }
890
+ /** The message of a thrown value. */
891
+ const messageOf = (err) => err instanceof Error ? err.message : String(err);
892
+ /** What a failed write most likely means when the key cannot change team settings. */
893
+ const NEEDS_ADMIN = /forbidden|permission|not authori[sz]ed|admin|access/i;
894
+ /** A failed step as a row; a message about permissions also says which key is needed. */
895
+ function failure(id, title, err) {
896
+ const message = messageOf(err);
897
+ return row(id, title, "fail", message, NEEDS_ADMIN.test(message) ? ["needs a Linear key with write access to the team (admin for team settings)"] : []);
898
+ }
899
+ /** The open project of the team with exactly this name. */
900
+ async function findProject(scope, name) {
901
+ const team = await scope.team();
902
+ return (await scope.client.projects.list()).find((p) => p.archivedAt === null && p.name === name && p.teams.nodes.some((t) => t.id === team.id));
903
+ }
904
+ // src/provider/templates.ts
905
+ /**
906
+ * One skipped row per declared issue template. Linear's schema documents `templateData` only as "a JSON-encoded string
907
+ * containing the pre-filled attributes", with no shape for an issue (and `Template.content`, the markdown, is read-only),
908
+ * so a template cannot be written from a markdown file, nor read back and compared, with certainty. The declaration is
909
+ * validated and listed; the template is made in Linear: Settings → Templates.
910
+ */
911
+ function templateRows(config) {
912
+ return config.templates.map((t) => row(`template:${t.name}`, `template ${t.name}`, "skip", `${t.file}: not applied or compared (Linear does not document the issue templateData shape); make it in Settings → Templates`));
913
+ }
914
+ // src/provider/doctor.ts
915
+ const FIX = "run `holocron provider linear setup`";
916
+ /** `ok` with the detail when nothing differs, otherwise `fail` with a line per difference and the fix. */
917
+ const verdict = (id, title, detail, problems) => problems.length === 0 ? row(id, title, "ok", detail) : row(id, title, "fail", problems[0], [...problems, FIX]);
918
+ /**
919
+ * `provider linear doctor`: one row for the team and one for each label, the project, each auto-close and
920
+ * auto-archive setting and each git automation rule the block declares. Read-only; a row that fails names `provider linear setup` as the fix.
921
+ */
922
+ function linearDoctor(scope, config) {
923
+ return async () => {
924
+ let team;
925
+ try {
926
+ team = await scope.team();
927
+ } catch (err) {
928
+ return [failure("team", `team ${config.team}`, err)];
929
+ }
930
+ const rows = [row("team", `team ${config.team}`, "ok", team.name)];
931
+ if (config.labels.length > 0) try {
932
+ const existing = (await scope.client.teams.labels(team.id)).map((l) => l.name.toLowerCase());
933
+ for (const name of config.labels) {
934
+ const found = existing.includes(name.toLowerCase());
935
+ rows.push(verdict(`label:${name}`, `label ${name}`, "present", found ? [] : ["missing"]));
936
+ }
937
+ } catch (err) {
938
+ rows.push(failure("labels", "labels", err));
939
+ }
940
+ const name = config.project;
941
+ if (name) try {
942
+ const found = await findProject(scope, name);
943
+ rows.push(verdict("project", `project ${name}`, found?.url ?? "", found ? [] : ["no open project of the team has this name"]));
944
+ } catch (err) {
945
+ rows.push(failure("project", `project ${name}`, err));
946
+ }
947
+ if (config.autoClose || config.autoArchive) try {
948
+ const [have, states] = await Promise.all([scope.client.teams.automation(team.id), scope.client.teams.states(team.id)]);
949
+ if (config.autoClose) {
950
+ const { months, state } = config.autoClose;
951
+ rows.push(verdict("autoClose", "auto-close", `${months} months${state ? ` to ${state}` : ""}`, closeGap(config.autoClose, have, states).problems));
952
+ }
953
+ if (config.autoArchive) rows.push(verdict("autoArchive", "auto-archive", `${config.autoArchive.months} months`, archiveGap(config.autoArchive, have).problems));
954
+ } catch (err) {
955
+ rows.push(failure("automation", "automation", err));
956
+ }
957
+ if (config.git.length > 0) try {
958
+ const [have, states] = await Promise.all([scope.client.teams.gitAutomation(team.id), scope.client.teams.states(team.id)]);
959
+ for (const gap of gitGaps(config.git, have, states)) {
960
+ const detail = gap.title.replace("git automation ", "");
961
+ rows.push(verdict(gap.id, gap.title, detail, gap.problems));
962
+ }
963
+ } catch (err) {
964
+ rows.push(failure("git", "git automation", err));
965
+ }
966
+ rows.push(...templateRows(config));
967
+ return rows;
968
+ };
969
+ }
970
+ // src/provider/provider-config.ts
971
+ /** Linear's own names for the moments a git integration can move an issue. */
972
+ const GIT_EVENTS = [
973
+ "draft",
974
+ "review",
975
+ "start",
976
+ "mergeable",
977
+ "merge"
978
+ ];
979
+ const ROOT = "providers.issues";
980
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
981
+ function text(value, path) {
982
+ if (typeof value !== "string" || value.trim() === "") throw new ConfigError(`${path} must be a non-empty string`);
983
+ return value;
984
+ }
985
+ function months(value, path) {
986
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw new ConfigError(`${path} must be a non-negative integer (0 switches it off)`);
987
+ return value;
988
+ }
989
+ function section(parent, key) {
990
+ const value = parent[key];
991
+ if (value === void 0) return void 0;
992
+ if (!isObject(value)) throw new ConfigError(`${ROOT}.automation.${key} must be an object`);
993
+ return value;
994
+ }
995
+ function gitSetting(value, index) {
996
+ const path = `${ROOT}.automation.git[${index}]`;
997
+ if (!isObject(value)) throw new ConfigError(`${path} must be an object`);
998
+ const event = value.event;
999
+ if (!GIT_EVENTS.includes(event)) throw new ConfigError(`${path}.event must be one of ${GIT_EVENTS.join(", ")}`);
1000
+ return {
1001
+ event,
1002
+ state: text(value.state, `${path}.state`),
1003
+ ...value.branch !== void 0 ? { branch: text(value.branch, `${path}.branch`) } : {}
1004
+ };
1005
+ }
1006
+ /**
1007
+ * Reads the Linear block of the issues provider entry: `team` (required), `automation.autoClose` / `autoArchive` /
1008
+ * `git`, `templates`, `labels` and `project`. Anything of the wrong shape is a `ConfigError` naming the path.
1009
+ */
1010
+ function parseLinearSetup(raw) {
1011
+ const config = {
1012
+ team: text(raw.team, `${ROOT}.team`),
1013
+ git: [],
1014
+ labels: [],
1015
+ templates: []
1016
+ };
1017
+ if (raw.automation !== void 0) {
1018
+ if (!isObject(raw.automation)) throw new ConfigError(`${ROOT}.automation must be an object`);
1019
+ const autoClose = section(raw.automation, "autoClose");
1020
+ if (autoClose) config.autoClose = {
1021
+ months: months(autoClose.months, `${ROOT}.automation.autoClose.months`),
1022
+ ...autoClose.state !== void 0 ? { state: text(autoClose.state, `${ROOT}.automation.autoClose.state`) } : {}
1023
+ };
1024
+ const autoArchive = section(raw.automation, "autoArchive");
1025
+ if (autoArchive) config.autoArchive = { months: months(autoArchive.months, `${ROOT}.automation.autoArchive.months`) };
1026
+ const git = raw.automation.git;
1027
+ if (git !== void 0) {
1028
+ if (!Array.isArray(git)) throw new ConfigError(`${ROOT}.automation.git must be an array`);
1029
+ config.git = git.map(gitSetting);
1030
+ }
1031
+ }
1032
+ if (raw.labels !== void 0) {
1033
+ if (!Array.isArray(raw.labels)) throw new ConfigError(`${ROOT}.labels must be an array of names`);
1034
+ config.labels = [...new Set(raw.labels.map((name, i) => text(name, `${ROOT}.labels[${i}]`)))];
1035
+ }
1036
+ if (raw.templates !== void 0) {
1037
+ if (!Array.isArray(raw.templates)) throw new ConfigError(`${ROOT}.templates must be an array`);
1038
+ config.templates = raw.templates.map((t, i) => {
1039
+ const path = `${ROOT}.templates[${i}]`;
1040
+ if (!isObject(t)) throw new ConfigError(`${path} must be an object`);
1041
+ return {
1042
+ name: text(t.name, `${path}.name`),
1043
+ file: text(t.file, `${path}.file`)
1044
+ };
1045
+ });
1046
+ }
1047
+ if (raw.project !== void 0) config.project = text(raw.project, `${ROOT}.project`);
1048
+ return config;
1049
+ }
1050
+ /** Whether the block declares anything for setup or the doctor to act on. */
1051
+ function declaresAnything(config) {
1052
+ return Boolean(config.autoClose || config.autoArchive || config.git.length > 0 || config.templates.length > 0 || config.labels.length > 0 || config.project);
1053
+ }
1054
+ // src/provider/setup.ts
1055
+ /** The colour GitHub's label of this name has, as Linear spells a colour (`#d73a4a`), or undefined. */
1056
+ const colorOf = (name) => {
1057
+ const known = CANONICAL_LABELS.find((l) => l.name.toLowerCase() === name.toLowerCase());
1058
+ return known ? `#${known.color}` : void 0;
1059
+ };
1060
+ /** Runs one step; a throw is a failing row, not the end of the run. */
1061
+ async function attempt(id, title, step) {
1062
+ try {
1063
+ return await step();
1064
+ } catch (err) {
1065
+ return failure(id, title, err);
1066
+ }
1067
+ }
1068
+ async function labelRows(scope, team, names, dryRun) {
1069
+ let existing;
1070
+ try {
1071
+ existing = await scope.client.teams.labels(team.id);
1072
+ } catch (err) {
1073
+ return [failure("labels", "labels", err)];
1074
+ }
1075
+ const rows = [];
1076
+ for (const name of names) {
1077
+ const id = `label:${name}`;
1078
+ const title = `label ${name}`;
1079
+ rows.push(await attempt(id, title, async () => {
1080
+ if (existing.some((l) => l.name.toLowerCase() === name.toLowerCase())) return row(id, title, "ok", "already exists");
1081
+ if (dryRun) return row(id, title, "ok", "would create");
1082
+ const color = colorOf(name);
1083
+ await scope.client.teams.createLabel({
1084
+ name,
1085
+ teamId: team.id,
1086
+ ...color ? { color } : {}
1087
+ });
1088
+ return row(id, title, "ok", "created");
1089
+ }));
1090
+ }
1091
+ return rows;
1092
+ }
1093
+ async function automationRows(scope, team, config, dryRun) {
1094
+ let gaps;
1095
+ try {
1096
+ const [have, states] = await Promise.all([scope.client.teams.automation(team.id), scope.client.teams.states(team.id)]);
1097
+ gaps = [...config.autoClose ? [{
1098
+ id: "autoClose",
1099
+ title: "auto-close",
1100
+ gap: closeGap(config.autoClose, have, states)
1101
+ }] : [], ...config.autoArchive ? [{
1102
+ id: "autoArchive",
1103
+ title: "auto-archive",
1104
+ gap: archiveGap(config.autoArchive, have)
1105
+ }] : []];
1106
+ } catch (err) {
1107
+ return [failure("automation", "automation", err)];
1108
+ }
1109
+ const rows = [];
1110
+ for (const { id, title, gap } of gaps) rows.push(await attempt(id, title, async () => {
1111
+ if (gap.unresolved) return row(id, title, "fail", gap.problems.join("; "));
1112
+ if (gap.problems.length === 0) return row(id, title, "ok", "already set");
1113
+ if (dryRun) return row(id, title, "ok", `would change: ${gap.problems.join("; ")}`);
1114
+ await scope.client.teams.updateAutomation(team.id, gap.patch);
1115
+ return row(id, title, "ok", `changed: ${gap.problems.join("; ")}`);
1116
+ }));
1117
+ return rows;
1118
+ }
1119
+ async function gitRows(scope, team, config, dryRun) {
1120
+ let gaps;
1121
+ let branches;
1122
+ try {
1123
+ const [have, states] = await Promise.all([scope.client.teams.gitAutomation(team.id), scope.client.teams.states(team.id)]);
1124
+ gaps = gitGaps(config.git, have, states);
1125
+ branches = knownBranches(have);
1126
+ } catch (err) {
1127
+ return [failure("git", "git automation", err)];
1128
+ }
1129
+ const rows = [];
1130
+ for (const { id, title, problems, action, unresolved } of gaps) rows.push(await attempt(id, title, async () => {
1131
+ if (unresolved) return row(id, title, "fail", problems.join("; "));
1132
+ if (!action) return row(id, title, "ok", "already set");
1133
+ if (dryRun) return row(id, title, "ok", `would change: ${problems.join("; ")}`);
1134
+ if (action.kind === "update") await scope.client.teams.updateGitAutomation(action.ruleId, { stateId: action.stateId });
1135
+ else {
1136
+ let targetBranchId;
1137
+ if (action.branch !== void 0) {
1138
+ targetBranchId = branches.get(action.branch);
1139
+ if (!targetBranchId) {
1140
+ const made = await scope.client.teams.createGitTargetBranch({
1141
+ teamId: team.id,
1142
+ branchPattern: action.branch
1143
+ });
1144
+ targetBranchId = made.id;
1145
+ branches.set(action.branch, made.id);
1146
+ }
1147
+ }
1148
+ await scope.client.teams.createGitAutomation({
1149
+ teamId: team.id,
1150
+ event: action.event,
1151
+ stateId: action.stateId,
1152
+ ...targetBranchId ? { targetBranchId } : {}
1153
+ });
1154
+ }
1155
+ return row(id, title, "ok", `changed: ${problems.join("; ")}`);
1156
+ }));
1157
+ return rows;
1158
+ }
1159
+ /**
1160
+ * `provider linear setup`: makes the labels and the project the block declares, sets the team's auto-close and
1161
+ * auto-archive and makes or repoints each git automation rule it declares (issue templates are reported as skipped). Each step is a row and a step that fails does not stop the next. Nothing is deleted or reordered, an
1162
+ * existing label or project is left alone, and a team that already matches changes nothing, so a second run is all `ok`.
1163
+ */
1164
+ function linearSetup(scope, config) {
1165
+ return async ({ dryRun }) => {
1166
+ let team;
1167
+ try {
1168
+ team = await scope.team();
1169
+ } catch (err) {
1170
+ return [failure("team", `team ${config.team}`, err)];
1171
+ }
1172
+ const rows = [];
1173
+ if (config.labels.length > 0) rows.push(...await labelRows(scope, team, config.labels, dryRun));
1174
+ const name = config.project;
1175
+ if (name) rows.push(await attempt("project", `project ${name}`, async () => {
1176
+ const found = await findProject(scope, name);
1177
+ if (found) return row("project", `project ${name}`, "ok", found.url);
1178
+ if (dryRun) return row("project", `project ${name}`, "ok", "would create");
1179
+ const made = await scope.client.projects.create({
1180
+ name,
1181
+ teamIds: [team.id]
1182
+ });
1183
+ return row("project", `project ${name}`, "ok", `created: ${made.url}`);
1184
+ }));
1185
+ if (config.autoClose || config.autoArchive) rows.push(...await automationRows(scope, team, config, dryRun));
1186
+ if (config.git.length > 0) rows.push(...await gitRows(scope, team, config, dryRun));
1187
+ rows.push(...templateRows(config));
1188
+ return rows;
1189
+ };
1190
+ }
1191
+ // src/verify-token.ts
1192
+ /** Checks a Linear token by reading the viewer; the success subject names the user and workspace. */
1193
+ async function verifyToken(token, opts = {}) {
1194
+ const client = createLinearClient({
1195
+ token,
1196
+ baseUrl: opts.baseUrl,
1197
+ fetch: opts.fetch
1198
+ });
1199
+ try {
1200
+ const { user, organization } = await client.teams.viewer();
1201
+ return {
1202
+ ok: true,
1203
+ subject: `${user.displayName} @ ${organization.name}`
1204
+ };
1205
+ } catch (err) {
1206
+ return {
1207
+ ok: false,
1208
+ message: errorMessage(err)
1209
+ };
1210
+ }
1211
+ }
1212
+ // src/index.ts
1213
+ /** The client and team the capabilities share; the token is resolved when a capability is first built. */
1214
+ function createScope(options) {
1215
+ if (!options.team) throw new Error("the Linear plugin needs a `team` option (the team key, e.g. `ENG`)");
1216
+ return createTeamScope(createLinearClient({
1217
+ token: resolveToken(options),
1218
+ baseUrl: options.baseUrl,
1219
+ fetch: options.fetch
1220
+ }), options.team);
1221
+ }
1222
+ /** Builds the `issues` capability. */
1223
+ function issues(options) {
1224
+ return new LinearIssues(createScope(options), options.states ? { states: options.states } : {});
1225
+ }
1226
+ /** Builds the `projects` capability. */
1227
+ function projects(options) {
1228
+ return new LinearProjects(createScope(options));
1229
+ }
1230
+ /**
1231
+ * Reads the block under the issues entry, then runs a step against it. A block that declares nothing is one `skip` row,
1232
+ * not a silent success; a wrong shape is a `ConfigError` naming the path.
1233
+ */
1234
+ function providerAction(options, make) {
1235
+ return async (ctx) => {
1236
+ const config = parseLinearSetup(options);
1237
+ if (!declaresAnything(config)) return [row("linear", "linear", "skip", "nothing to do: declare `labels`, `project`, `templates` or `automation` under the issues provider's options")];
1238
+ return make(createScope(options), config)(ctx);
1239
+ };
1240
+ }
1241
+ /** Creates the plugin: a `connection` probe, `setup` and `doctor`, and the `issues` and `projects` capabilities. */
1242
+ function createPlugin(options) {
1243
+ return {
1244
+ name: "@theholocron/holocron-plugin-linear",
1245
+ probes: { connection: connectionProbe({
1246
+ provider: "Linear",
1247
+ url: options.baseUrl ?? "https://api.linear.app",
1248
+ fetch: options.fetch,
1249
+ token: () => resolveToken(options),
1250
+ verify: (token) => verifyToken(token, {
1251
+ baseUrl: options.baseUrl,
1252
+ fetch: options.fetch
1253
+ })
1254
+ }) },
1255
+ setup: providerAction(options, linearSetup),
1256
+ doctor: providerAction(options, linearDoctor),
1257
+ capabilities: {
1258
+ issues: () => issues(options),
1259
+ projects: () => projects(options)
1260
+ }
1261
+ };
1262
+ }
1263
+ /** One-line hint shown by `holocron auth set linear` when no token is given or the token is rejected. */
1264
+ const AUTH_HINT = "create a personal API key at https://linear.app/settings/account/security (API keys), then run: holocron auth set linear <KEY>";
1265
+ export { AUTH_HINT, AUTO_ARCHIVE_RULE, AUTO_CLOSE_RULE, AuthError, LinearIssues, LinearProjects, createLinearClient, createPlugin, issues, projects, resolveToken, tokens, verifyToken };