@theholocron/cli 5.0.0-alpha.4 → 5.0.0-alpha.400

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 CHANGED
@@ -1,392 +1,555 @@
1
- import { CARDINALITY, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
2
- import { AuthError, createResolveToken as createResolveToken$1, createRestClient } from "@theholocron/http-client";
3
- import { createEnvLookup } from "@theholocron/env-utils";
1
+ import { CARDINALITY, ElevationRequiredError, MissingTokenError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
2
+ import { a as placeAreas, c as ConfigError, d as resolveEntry, f as resolvePluginPackage, i as loadConfig, l as credentialsEnvironment, n as compose, o as HOLOCRON_AREAS, r as defineConfig, s as SHARED_AREAS, t as ConfigFileError, u as resolveConfig } from "./config-system-CeVFoOau.mjs";
4
3
  import { Entry, findCredentials } from "@napi-rs/keyring";
5
- import { execFile } from "node:child_process";
6
- import { readFile } from "node:fs/promises";
7
- import { basename, dirname, join } from "node:path";
8
- import { promisify } from "node:util";
9
- import { loadTasksConfig } from "@theholocron/astromech/config";
10
- import { ConfigFileError, ConfigFileError as ConfigFileError$1, loadConfigFile } from "@theholocron/datapad";
11
- createEnvLookup();
4
+ import { AuthError, createFeatureResolver as createFeatureResolver$1, createKeyring, createResolveToken as createResolveToken$1, resolveValue } from "@theholocron/kyber/secrets";
5
+ import { describeError, style } from "@theholocron/kyber/ui";
6
+ import { errorMessage } from "@theholocron/misc-utils";
7
+ import { createRestClient } from "@theholocron/http-client";
8
+ import { connectionProbe as connectionProbe$1 } from "@theholocron/kyber/checks";
9
+ import { join } from "node:path";
10
+ import { readPackageJson } from "@theholocron/pkg-utils";
11
+ // src/auth/auth.ts
12
12
  /**
13
- * Create an injectable env for commands that accept a fake env in tests.
14
- * Pass `input.env` when available, falls back to `process.env`.
15
- */
16
- function makeEnv(source) {
17
- return createEnvLookup(source);
18
- }
19
- //#endregion
20
- //#region src/auth/keyring.ts
21
- /**
22
- * Keyring-backed bootstrap credential store.
23
- *
24
- * Every holocron plugin's bootstrap token (the one it needs before it
25
- * can talk to its vendor's API) can be stored in the OS keyring under
26
- * a single reverse-DNS service scope. Managed via `holocron auth`
27
- * subcommands; consulted at position 4 in every plugin's auth
28
- * precedence chain (after --token / HOLOCRON_<X>_TOKEN / <native>_TOKEN).
13
+ * The CLI's credentials: the OS keyring every plugin's bootstrap token lives in, and the two token resolvers built on
14
+ * it. Both are public, so a plugin's `src/auth.ts` is a one-line call.
29
15
  *
30
- * See `docs/wiki/specifications/tech-auth-bootstrap.spec.md` for the design rationale.
31
- *
32
- * Failure model: keyring access is best-effort. Platforms without a
33
- * supported credential store (some Linux CI images, sandboxed
34
- * environments) will throw from the underlying library. Every export
35
- * here catches and returns a null/empty result rather than propagating
36
- * — the plugin's precedence chain then falls through to
37
- * env-var-only paths, which is exactly how CI is meant to work.
16
+ * The keyring itself, with its best-effort failure model and its per-process cache, is `createKeyring` in
17
+ * `@theholocron/kyber/secrets`; this file only names the service. Managed via `holocron auth` subcommands and consulted
18
+ * last in every plugin's precedence chain (after --token / HOLOCRON_<X>_TOKEN / <native>_TOKEN). See
19
+ * `docs/wiki/specifications/tech-auth-bootstrap.spec.md`.
38
20
  */
39
- const SERVICE = "com.theholocron.cli";
40
21
  /**
41
- * Store or overwrite a bootstrap token for a provider. Returns true on
42
- * success, false when the underlying keyring is unsupported or errored.
22
+ * The holocron keyring: `get` answers `null` for "not stored" and for "keyring unavailable" alike, so callers fall
23
+ * through to env-var precedence, and remembers the answer for the process (`clearCache` forgets it); `set` and `delete`
24
+ * answer whether they did anything; `list` names the stored providers; `isAvailable` tells an outage from an empty keyring.
43
25
  */
44
- function setToken(provider, token) {
45
- try {
46
- new Entry(SERVICE, provider).setPassword(token);
47
- return true;
48
- } catch {
49
- return false;
26
+ const keyring = createKeyring({
27
+ service: "com.theholocron.cli",
28
+ binding: {
29
+ Entry,
30
+ findCredentials
50
31
  }
51
- }
32
+ });
52
33
  /**
53
- * Read the bootstrap token for a provider. Returns `null` for both
54
- * "not stored" and "keyring unavailable" — callers can treat them the
55
- * same way (fall through to env-var precedence).
34
+ * Kyber's `createResolveToken` with the keyring, the `HOLOCRON_ORG` variable and the `token` description
35
+ * `holocron doctor tokens` reads filled in, so a plugin stays at a one-liner call site. The chain is the flag, the
36
+ * plugin's variable, the vendor's variable, the `credentials` providers' variables, the keyring.
56
37
  */
57
- function getToken(provider) {
58
- try {
59
- return new Entry(SERVICE, provider).getPassword();
60
- } catch {
61
- return null;
62
- }
38
+ function createResolveToken(config) {
39
+ return Object.assign(createResolveToken$1({
40
+ ...config,
41
+ keyring: keyring.get,
42
+ orgEnvName: "HOLOCRON_ORG"
43
+ }), { token: {
44
+ envName: config.envName,
45
+ vendorEnvName: config.vendorEnvName,
46
+ keyringKey: config.keyringService
47
+ } });
63
48
  }
64
49
  /**
65
- * Delete a stored token. Returns true when a token was removed, false
66
- * when there was nothing to delete or the keyring is unavailable.
67
- * Distinguishing the two cases isn't worth the surface area — the
68
- * command output makes the situation clear either way.
50
+ * Kyber's `createFeatureResolver` for a strict, single-feature token: the flag, the feature's variable, the
51
+ * `credentials` providers' variable of that name, the keyring. No broad-token fallback; if the feature's token is absent
52
+ * the operation fails with a message naming the exact variable to set and `holocron auth set`.
69
53
  */
70
- function deleteToken(provider) {
71
- try {
72
- return new Entry(SERVICE, provider).deletePassword();
73
- } catch {
74
- return false;
75
- }
54
+ function createFeatureResolver(config) {
55
+ return Object.assign(createFeatureResolver$1({
56
+ ...config,
57
+ vendor: config.vendor ?? "GitHub",
58
+ setCommand: (key) => `holocron auth set ${key} <token>`,
59
+ keyring: keyring.get
60
+ }), { token: {
61
+ envName: config.envName,
62
+ keyringKey: config.keyringKey
63
+ } });
76
64
  }
65
+ // src/plugin/issues-provider/order-keys/order-keys.ts
77
66
  /**
78
- * List provider slugs with a stored token in this service scope.
79
- * Uses the library's `findCredentials(service)` — supported on all
80
- * platforms the underlying credential store supports.
67
+ * Puts issue keys in creation order without asking the tracker: issue numbers (`#12`, `ENG-12`) rise with creation inside
68
+ * one repository or team, so the trailing number is the order. `oldest` is ascending, `newest` descending; keys with the
69
+ * same number keep their place. A key with no trailing number is an error, because nothing can be said of its age.
81
70
  */
82
- function listStoredProviders() {
83
- try {
84
- return findCredentials(SERVICE).map((c) => c.account);
85
- } catch {
86
- return [];
87
- }
88
- }
89
- //#endregion
90
- //#region src/auth/auth-resolver.ts
91
- /** Wraps `createResolveToken` from `@theholocron/http` and injects the
92
- * system keyring so plugins stay at a one-liner call site. */
93
- function createResolveToken(config) {
94
- return createResolveToken$1({
95
- ...config,
96
- getKeyringToken: getToken
71
+ function orderKeys(keys, order) {
72
+ const numbered = keys.map((key, index) => {
73
+ const match = /(\d+)\s*$/.exec(key);
74
+ if (!match) throw new Error(`Cannot order "${key}" by creation: it has no issue number.`);
75
+ return {
76
+ key,
77
+ index,
78
+ n: Number(match[1])
79
+ };
97
80
  });
81
+ const sign = order === "newest" ? -1 : 1;
82
+ return numbered.sort((a, b) => sign * (a.n - b.n) || a.index - b.index).map((e) => e.key);
98
83
  }
84
+ // src/plugin/issues-provider/pick-by-creation/pick-by-creation.ts
99
85
  /**
100
- * Build a strict, single-feature token resolver.
101
- *
102
- * Resolution chain: `--token flag → envName env var → keyring(keyringKey)`.
103
- * No broad-token fallback — if the feature-specific token is absent the
104
- * operation fails with a message naming the exact env var to set.
86
+ * Keeps the first or last `limit` of a listing by creation time, returned oldest first. `createdAt` reads an item's
87
+ * ISO timestamp; items created in the same instant keep their listed order. The cut happens on what the listing already
88
+ * holds, so no request is spent on an item that is dropped.
105
89
  */
106
- function createFeatureResolver(config) {
107
- return function resolveFeatureToken(input = {}) {
108
- const env = makeEnv(input.env);
109
- const keyring = input.keyring ?? getToken;
110
- const token = input.cliToken || env.get(config.envName) || keyring(config.keyringKey);
111
- if (!token) throw new AuthError(`no GitHub token found for this operation. Pass --token <PAT>, set ${config.envName}, or run: holocron auth set ${config.keyringKey} <PAT>`);
112
- return token;
113
- };
90
+ function pickByCreation(items, createdAt, order, limit) {
91
+ const ascending = items.map((item, index) => ({
92
+ item,
93
+ index,
94
+ at: Date.parse(createdAt(item))
95
+ })).sort((a, b) => a.at - b.at || a.index - b.index).map((e) => e.item);
96
+ return order === "newest" ? ascending.slice(Math.max(ascending.length - limit, 0)) : ascending.slice(0, limit);
114
97
  }
115
- //#endregion
116
- //#region src/config/config.ts
117
- var ConfigError = class extends Error {
118
- name = "ConfigError";
119
- };
120
- const PLUGIN_PREFIX = "@theholocron/holocron-plugin-";
121
- const COMMUNITY_PREFIX = "holocron-plugin-";
98
+ // src/plugin/issues-provider/read-keys-limited/read-keys-limited.ts
122
99
  /**
123
- * Resolve `"github"` → `"@theholocron/holocron-plugin-github"`.
124
- * Fully-qualified names (scoped or not) are honored verbatim, which
125
- * is how third-party plugins published outside the org work.
100
+ * Reads an explicit list of issues in creation order until `limit` of them are kept. The keys are sorted by number first
101
+ * (see {@link orderKeys}), then fetched in small steps of at most `concurrency`, each step no bigger than the places
102
+ * still open, so an issue that is later skipped (a pull request, a closed one) is replaced by the next key and nothing
103
+ * beyond the budget is fetched unless a skip made room. Within a step the fetches run together; the results keep the key
104
+ * order. The kept items come back oldest first, whichever end was chosen.
126
105
  */
127
- function resolvePluginPackage(provider) {
128
- if (!provider) throw new ConfigError("provider name is empty");
129
- if (provider.startsWith("@")) return provider;
130
- if (provider.startsWith(COMMUNITY_PREFIX)) return provider;
131
- if (provider.includes("/")) return provider;
132
- return PLUGIN_PREFIX + provider;
106
+ async function readKeysLimited(input) {
107
+ const { keys, order, limit, concurrency, fetch, keep } = input;
108
+ const ordered = orderKeys(keys, order);
109
+ const kept = [];
110
+ let next = 0;
111
+ while (kept.length < limit && next < ordered.length) {
112
+ const step = ordered.slice(next, next + Math.min(concurrency, limit - kept.length));
113
+ next += step.length;
114
+ const fetched = await Promise.all(step.map((key) => fetch(key)));
115
+ for (const item of fetched) if (keep(item)) kept.push(item);
116
+ }
117
+ return order === "newest" ? kept.reverse() : kept;
133
118
  }
134
- /** A bare `[provider, options]` tuple, with both elements present? */
135
- function isOptionsTuple(value) {
136
- if (!Array.isArray(value)) return false;
137
- if (value.length !== 2) return false;
138
- if (typeof value[0] !== "string") return false;
139
- const opt = value[1];
140
- return typeof opt === "object" && opt !== null && !Array.isArray(opt);
119
+ // src/plugin/issues-provider/report-progress/report-progress.ts
120
+ /**
121
+ * Calls a provider's optional `onProgress` hook with how many items are done of how many. A hook that throws is
122
+ * ignored, because a progress counter must never change or stop the read or write it reports on.
123
+ *
124
+ * @param onProgress - The hook from `ExportInfo` or `ImportOptions`; nothing happens when it is not given.
125
+ * @param done - How many items are finished.
126
+ * @param total - How many items there are.
127
+ */
128
+ function reportProgress(onProgress, done, total) {
129
+ try {
130
+ onProgress?.(done, total);
131
+ } catch {}
141
132
  }
142
- function normalizeEntry(entry) {
143
- if (typeof entry === "string") return {
144
- provider: entry,
145
- packageName: resolvePluginPackage(entry),
146
- options: {}
147
- };
148
- const [provider, options] = entry;
149
- return {
150
- provider,
151
- packageName: resolvePluginPackage(provider),
152
- options
153
- };
133
+ // src/plugin/probes/connection-probe/connection-probe.ts
134
+ /**
135
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem. The checks are
136
+ * kyber's `connectionProbe`; this types the result as the plugin system's {@link Probe} and `verify` as `VerifyTokenResult`.
137
+ */
138
+ function connectionProbe(input) {
139
+ return connectionProbe$1(input);
154
140
  }
155
- function resolveEntry(key, raw) {
156
- const cardinality = CARDINALITY[key];
157
- if (typeof raw === "string") {
158
- if (cardinality === "many") throw new ConfigError(`\`${key}\` accepts multiple providers; wrap a single one in an array: ["${raw}"]`);
159
- return {
160
- cardinality: "single",
161
- tuple: normalizeEntry(raw)
162
- };
141
+ // src/commands/notifications-sync-roles/links.ts
142
+ const EMPTY_LINKS = {
143
+ version: 1,
144
+ links: []
145
+ };
146
+ const DIGITS = /^\d{1,20}$/;
147
+ /** Reads the file's text. Throws with a plain reason on anything that is not a links file, so a damaged one is never treated as empty. */
148
+ function parseLinks(text) {
149
+ let raw;
150
+ try {
151
+ raw = JSON.parse(text);
152
+ } catch {
153
+ throw new Error("the links file is not valid JSON");
163
154
  }
164
- if (!Array.isArray(raw)) throw new ConfigError(`\`${key}\` entry must be a string or array, got ${typeof raw}`);
165
- if (isOptionsTuple(raw)) {
166
- if (cardinality === "many") return {
167
- cardinality: "many",
168
- tuples: [normalizeEntry(raw)]
169
- };
155
+ const file = raw;
156
+ if (file.version !== 1) throw new Error(`the links file has version ${JSON.stringify(file.version)}; expected 1`);
157
+ if (!Array.isArray(file.links)) throw new Error("the links file has no `links` list");
158
+ const links = file.links.map((entry, i) => {
159
+ const e = entry;
160
+ if (typeof e.github !== "string" || !DIGITS.test(e.github)) throw new Error(`links[${i}]: \`github\` must be a numeric user id string`);
161
+ if (typeof e.member !== "string" || !DIGITS.test(e.member)) throw new Error(`links[${i}]: \`member\` must be a numeric id string`);
162
+ if (typeof e.login !== "string") throw new Error(`links[${i}]: \`login\` must be a string`);
170
163
  return {
171
- cardinality: "single",
172
- tuple: normalizeEntry(raw)
164
+ github: e.github,
165
+ login: e.login,
166
+ member: e.member
173
167
  };
168
+ });
169
+ for (const key of ["github", "member"]) {
170
+ const seen = /* @__PURE__ */ new Set();
171
+ for (const [i, link] of links.entries()) {
172
+ if (seen.has(link[key])) throw new Error(`links[${i}]: \`${key}\` ${link[key]} appears more than once`);
173
+ seen.add(link[key]);
174
+ }
174
175
  }
175
- if (cardinality === "single") throw new ConfigError(`\`${key}\` accepts exactly one provider; got a multi-provider list with ${raw.length} entries`);
176
176
  return {
177
- cardinality: "many",
178
- tuples: raw.map((entry, idx) => {
179
- if (typeof entry === "string") return normalizeEntry(entry);
180
- if (isOptionsTuple(entry)) return normalizeEntry(entry);
181
- throw new ConfigError(`\`${key}[${idx}]\` must be a provider string or [provider, options] tuple`);
182
- })
177
+ version: 1,
178
+ links
183
179
  };
184
180
  }
185
- function resolveConfig(raw) {
186
- if (!raw.name) throw new ConfigError("`name` is required");
187
- if (!raw.providers || typeof raw.providers !== "object") throw new ConfigError("`providers` block is required");
188
- const providers = {};
189
- for (const [key, entry] of Object.entries(raw.providers)) {
190
- if (entry === void 0) continue;
191
- providers[key] = resolveEntry(key, entry);
192
- }
193
- for (const required of REQUIRED_CAPABILITIES) if (!providers[required]) throw new ConfigError(`required capability \`${required}\` is missing from providers`);
194
- let docs;
195
- if (raw.docs !== void 0) {
196
- if (!raw.docs.build) throw new ConfigError("`docs.build` is required when `docs` is set");
197
- docs = raw.docs;
198
- }
199
- const homepage = raw.homepage ?? (docs?.domain ? `https://${docs.domain}/` : void 0);
181
+ /** Where the links file is: the layout's `links`, else `<org>/.github-private` and `notifications/<provider>-links.json`. */
182
+ function linksLocation(layout, org, provider) {
183
+ const repo = layout.links?.repo ?? (org ? `${org}/.github-private` : void 0);
184
+ if (!repo) throw new Error("no org to find the links file under — set `layout.links.repo` or `org` in holocron.config.ts");
200
185
  return {
201
- name: raw.name,
202
- description: raw.description,
203
- homepage,
204
- org: raw.org,
205
- domain: raw.domain,
206
- repo: raw.repo,
207
- tasks: raw.tasks,
208
- syncScripts: raw.syncScripts,
209
- holocronScript: raw.holocronScript,
210
- extraRequiredChecks: raw.extraRequiredChecks,
211
- hooks: raw.hooks,
212
- providers,
213
- apps: raw.apps ?? [],
214
- doctor: raw.doctor ?? {},
215
- agent: raw.agent,
216
- skills: raw.skills,
217
- docs,
218
- env: raw.env,
219
- log: raw.log,
220
- telemetry: raw.telemetry
186
+ repo,
187
+ path: layout.links?.path ?? `notifications/${provider.toLowerCase()}-links.json`
221
188
  };
222
189
  }
223
- //#endregion
224
- //#region src/config/compose.ts
225
- function taskName(e) {
226
- return typeof e === "string" ? e : e.name;
227
- }
190
+ // src/commands/notifications-sync-roles/plan.ts
228
191
  /**
229
- * Merge any number of capability fragments into a single preset object that
230
- * spreads directly into `defineConfig()`.
231
- *
232
- * - Accepts individual capabilities or nested arrays (for bundle presets).
233
- * - Deduplicates by `id` — when the same ID appears more than once, the last
234
- * occurrence wins. This lets callers override bundle defaults by listing an
235
- * explicit capability after the bundle.
236
- * - Validates all `requires` at call time and throws `ConfigError` if any are
237
- * unmet, listing every missing dependency in a single message.
238
- *
239
- * @example
240
- * // docs-only site — no typecheck
241
- * const preset = compose(node(), docs());
242
- *
243
- * // library with docs
244
- * const preset = compose(node(), typecheck(), docs());
245
- *
246
- * // nextjs() is a bundle that returns Capability[]
247
- * const preset = compose(node(), nextjs());
192
+ * What it takes to make a role's holders equal a team, given who is linked to whom. Pure: it decides, the
193
+ * caller acts. A holder is removed only when a link says they are a person who left the team; a holder
194
+ * nobody has linked is reported, never removed, so an empty or missing links file cannot strip the role from
195
+ * everyone.
248
196
  */
249
- function compose(...args) {
250
- const flat = args.flat();
251
- const byId = /* @__PURE__ */ new Map();
252
- for (const cap of flat) byId.set(cap.id, cap);
253
- const caps = [...byId.values()];
254
- const available = new Set(caps.map((c) => c.id));
255
- const errors = [];
256
- for (const cap of caps) for (const req of cap.requires ?? []) if (!available.has(req)) errors.push(`"${cap.id}" requires "${req}"`);
257
- if (errors.length > 0) throw new ConfigError(`compose(): unmet dependencies — ${errors.join(", ")}`);
258
- const taskMap = /* @__PURE__ */ new Map();
259
- for (const cap of caps) for (const entry of cap.tasks ?? []) taskMap.set(taskName(entry), entry);
260
- let providers = {};
261
- for (const cap of caps) if (cap.providers) providers = {
262
- ...providers,
263
- ...cap.providers
197
+ function planRoleSync(input) {
198
+ const byGithub = new Map(input.links.map((l) => [l.github, l]));
199
+ const byMember = new Map(input.links.map((l) => [l.member, l]));
200
+ const onTeam = new Set(input.team.map((m) => m.id));
201
+ const holding = new Set(input.holders.map((h) => h.id));
202
+ const plan = {
203
+ add: [],
204
+ remove: [],
205
+ unlinked: [],
206
+ unknownHolders: [],
207
+ inSync: 0
264
208
  };
265
- const checksSeen = /* @__PURE__ */ new Set();
266
- const extraRequiredChecks = [];
267
- for (const cap of caps) for (const check of cap.extraRequiredChecks ?? []) if (!checksSeen.has(check)) {
268
- checksSeen.add(check);
269
- extraRequiredChecks.push(check);
209
+ for (const person of input.team) {
210
+ const link = byGithub.get(person.id);
211
+ if (!link) plan.unlinked.push(person);
212
+ else if (holding.has(link.member)) plan.inSync++;
213
+ else plan.add.push({
214
+ member: link.member,
215
+ login: person.login
216
+ });
270
217
  }
271
- let repo = {};
272
- for (const cap of caps) {
273
- if (!cap.repo) continue;
274
- const { properties, topics, teams, ...scalars } = cap.repo;
275
- repo = {
276
- ...repo,
277
- ...scalars
278
- };
279
- if (properties) repo.properties = {
280
- ...repo.properties,
281
- ...properties
282
- };
283
- if (topics) {
284
- const merged = /* @__PURE__ */ new Set([...repo.topics ?? [], ...topics]);
285
- repo.topics = [...merged];
286
- }
287
- if (teams) {
288
- const teamMap = new Map((repo.teams ?? []).map((t) => [typeof t === "string" ? t : t.slug, t]));
289
- for (const t of teams) teamMap.set(typeof t === "string" ? t : t.slug, t);
290
- repo.teams = [...teamMap.values()];
291
- }
292
- }
293
- let org;
294
- let domain;
295
- let docs;
296
- for (const cap of caps) {
297
- if (cap.org !== void 0) org = cap.org;
298
- if (cap.domain !== void 0) domain = cap.domain;
299
- if (cap.docs !== void 0) docs = cap.docs;
218
+ for (const holder of input.holders) {
219
+ const link = byMember.get(holder.id);
220
+ if (!link) plan.unknownHolders.push({
221
+ member: holder.id,
222
+ ...holder.name ? { name: holder.name } : {}
223
+ });
224
+ else if (!onTeam.has(link.github)) plan.remove.push({
225
+ member: holder.id,
226
+ login: link.login
227
+ });
300
228
  }
301
- return {
302
- tasks: [...taskMap.values()],
303
- providers,
304
- repo,
305
- extraRequiredChecks,
306
- ...org !== void 0 ? { org } : {},
307
- ...domain !== void 0 ? { domain } : {},
308
- ...docs !== void 0 ? { docs } : {}
309
- };
229
+ return plan;
310
230
  }
311
- //#endregion
312
- //#region src/config/define-config.ts
313
- function defineConfig(config) {
314
- return config;
315
- }
316
- //#endregion
317
- //#region src/config/load-config.ts
318
231
  /**
319
- * `holocron.config.{ts,js,mjs,cjs,json}` loader.
320
- *
321
- * File discovery + module loading (typed configs via `tsx`, no build
322
- * step) is delegated to `@theholocron/datapad`. This module keeps the
323
- * holocron-specific parts: filling `name` / `repo.name` defaults and
324
- * running the config through `resolveConfig`.
325
- *
326
- * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
327
- * see ADR-0010 / issue #75 / #81.
232
+ * The first role the layout declares for two different teams, or undefined. Names compare ignoring case, as
233
+ * the server does; the role would be synced against one team and then the other, so the last would win.
328
234
  */
329
- const execFileAsync = promisify(execFile);
235
+ function roleTeamProblem(layout) {
236
+ const seen = /* @__PURE__ */ new Map();
237
+ for (const role of layout.roles ?? []) {
238
+ if (!role.team) continue;
239
+ const key = role.name.toLowerCase();
240
+ const earlier = seen.get(key);
241
+ if (earlier !== void 0 && earlier.toLowerCase() !== role.team.toLowerCase()) return `role \`${role.name}\` is declared for two teams (\`${earlier}\` and \`${role.team}\`); a role follows one team`;
242
+ seen.set(key, role.team);
243
+ }
244
+ }
245
+ // src/commands/notifications-sync-roles/sync-roles.ts
246
+ /** Reads the team and the role's holders and works out what has to change. */
247
+ async function planForRole(args) {
248
+ const [team, holders] = await Promise.all([args.source.teamMembers(args.team, args.org), args.notifications.roleMembers(args.role)]);
249
+ return planRoleSync({
250
+ team,
251
+ links: args.links.links,
252
+ holders
253
+ });
254
+ }
330
255
  /**
331
- * Read + parse + resolve `holocron.config.*` from the given directory.
332
- * Throws {@link ConfigFileError} when nothing is found or a file cannot
333
- * be loaded, or `ConfigError` when the config is invalid.
256
+ * Makes each role's holders equal its team, one role after another. This is the sync itself, with no setup in
257
+ * front of it: the caller has already picked the providers, read the links and checked the layout. `holocron
258
+ * notifications sync-roles` and Sentinel's role sync are two callers of it. A step that fails is recorded and the
259
+ * run goes on; nothing here throws for a provider error. Idempotent: a role that already matches changes nothing.
260
+ * Lines go to `input.print` when it is given, and nowhere otherwise.
334
261
  */
335
- async function loadConfig(cwd) {
336
- const found = await loadConfigFile({
337
- cwd,
338
- name: "holocron"
339
- });
340
- if (!found) throw new ConfigFileError$1(`no holocron.config.{ts,js,mjs,cjs,json} found in ${cwd}. Create one — see the README for the schema.`);
341
- return {
342
- resolved: resolveConfig(await deriveDefaults(dirname(found.filepath), found.config)),
343
- filepath: found.filepath
262
+ async function syncRoles(input) {
263
+ const print = input.print ?? (() => {});
264
+ const { notifications, source, links, dryRun, keep } = input;
265
+ const result = {
266
+ roles: [],
267
+ failures: [],
268
+ ok: 0,
269
+ skipped: 0
344
270
  };
345
- }
346
- async function deriveDefaults(configDir, raw) {
347
- const result = { ...raw };
348
- if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
349
- if (result.repo && !result.repo.name) {
350
- const repoName = await readGitRemote(configDir);
351
- if (repoName) result.repo = {
352
- ...result.repo,
353
- name: repoName
271
+ for (const role of input.roles) {
272
+ print(`\n${style.header(`${role.name} ← team ${role.team}`)}`);
273
+ const step = `role ${role.name}`;
274
+ let plan;
275
+ try {
276
+ plan = await planForRole({
277
+ notifications,
278
+ source,
279
+ role: role.name,
280
+ team: role.team,
281
+ ...input.org ? { org: input.org } : {},
282
+ links
283
+ });
284
+ } catch (err) {
285
+ const message = describeError(err);
286
+ print(` ${style.fail(`${step}: ${message}`)}`);
287
+ result.failures.push({
288
+ step,
289
+ message
290
+ });
291
+ continue;
292
+ }
293
+ const outcome = {
294
+ role: role.name,
295
+ team: role.team,
296
+ plan,
297
+ added: [],
298
+ removed: []
299
+ };
300
+ result.roles.push(outcome);
301
+ result.skipped += plan.inSync;
302
+ if (plan.inSync > 0) print(` ${style.skip(`${plan.inSync} already have it`)}`);
303
+ const act = async (verb, who) => {
304
+ const label = `${verb === "add" ? "gave" : "took"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})`;
305
+ if (dryRun || verb === "remove" && keep) {
306
+ print(` ${style.skip(`would ${verb === "add" ? "give" : "take"} ${role.name} ${verb === "add" ? "to" : "from"} ${who.login} (${who.member})${keep && verb === "remove" ? " (kept: --keep)" : ""}`)}`);
307
+ result.skipped++;
308
+ return;
309
+ }
310
+ try {
311
+ if (verb === "add") await notifications.addRoleMember(role.name, who.member);
312
+ else await notifications.removeRoleMember(role.name, who.member);
313
+ (verb === "add" ? outcome.added : outcome.removed).push(who.member);
314
+ print(` ${style.success(label)}`);
315
+ result.ok++;
316
+ } catch (err) {
317
+ const message = describeError(err);
318
+ print(` ${style.fail(`${step}: ${verb} ${who.login}: ${message}`)}`);
319
+ result.failures.push({
320
+ step: `${step} ${verb} ${who.login}`,
321
+ message
322
+ });
323
+ }
354
324
  };
325
+ for (const who of plan.add) await act("add", who);
326
+ for (const who of plan.remove) await act("remove", who);
327
+ for (const person of plan.unlinked) {
328
+ print(` ${style.skip(`${person.login} is on the team but has not linked their account`)}`);
329
+ result.skipped++;
330
+ }
331
+ for (const holder of plan.unknownHolders) {
332
+ print(` ${style.skip(`${holder.name ?? holder.member} holds ${role.name} but is not linked to anyone: left alone`)}`);
333
+ result.skipped++;
334
+ }
355
335
  }
356
- const manifest = await loadTasksConfig(configDir);
357
- if (manifest.tasks) result.tasks = manifest.tasks;
358
- if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
359
- if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
360
- if (manifest.hooks !== void 0) result.hooks = manifest.hooks;
361
- if (manifest.extraRequiredChecks) result.extraRequiredChecks = [...result.extraRequiredChecks ?? [], ...manifest.extraRequiredChecks];
362
336
  return result;
363
337
  }
364
- async function readPackageJsonName(dir) {
338
+ // src/commands/notifications-sync-roles/notifications-sync-roles.ts
339
+ /** What a source provider needs to be able to do to feed a role sync, or the reason it cannot. */
340
+ function sourceProblem(source) {
341
+ if (!source) return "no `source` provider is available to read the team and the links file";
342
+ if (!source.teamMembers) return `the \`${source.providerName}\` provider cannot list team members`;
343
+ if (!source.readFile) return `the \`${source.providerName}\` provider cannot read the links file`;
344
+ }
345
+ /** Reads the links file; a file that does not exist yet is an empty one, a damaged one throws. */
346
+ async function readLinks(source, layout, org, provider) {
347
+ const { repo, path } = linksLocation(layout, org, provider);
348
+ const file = await source.readFile(path, repo);
349
+ if (!file) return EMPTY_LINKS;
365
350
  try {
366
- const content = await readFile(join(dir, "package.json"), "utf8");
367
- const pkg = JSON.parse(content);
368
- return typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : void 0;
369
- } catch {
370
- return;
351
+ return parseLinks(file.content);
352
+ } catch (err) {
353
+ throw new Error(`${repo}/${path}: ${errorMessage(err)}`, { cause: err });
371
354
  }
372
355
  }
373
- async function readGitRemote(dir) {
374
- try {
375
- const { stdout } = await execFileAsync("git", [
376
- "remote",
377
- "get-url",
378
- "origin"
379
- ], { cwd: dir });
380
- return parseGitRemoteUrl(stdout.trim());
381
- } catch {
382
- return;
356
+ // src/commands/setup/derived-properties/derived-properties.ts
357
+ /**
358
+ * Repo archetype, in priority order:
359
+ * 1. `*-template` repo name → `template` (independent of package shape).
360
+ * 2. Monorepo whose primary published artifact is a CLI (some workspace
361
+ * package has `bin`) → `platform` — matches `holocron` itself: the CLI is
362
+ * the deliverable, the plugin packages are supporting infrastructure for
363
+ * it, not separate products.
364
+ * 3. Monorepo with no CLI but at least one non-private workspace package →
365
+ * `library` — matches `clients`/`configs`/`utils`/`themes`/
366
+ * `observability`: a family of published packages, none of them a CLI.
367
+ * Checked *before* falling into the root-package branch below, because
368
+ * these repos' own root `package.json` is private and often carries
369
+ * `@theholocron/astro-config` for a docs site built from the monorepo
370
+ * root — without this check they'd wrongly resolve to `docs` off that
371
+ * root-level signal alone, when the docs site is a secondary concern of
372
+ * a library collection, not what the repo fundamentally is.
373
+ * 4. Single-package repo with `package.json#bin` → `cli`.
374
+ * 5. Docs-only site (astro/starlight present, root package private, no
375
+ * publishable exports) → `docs`.
376
+ * 6. Private, non-publishable, non-docs → `app`.
377
+ * 7. Otherwise, a single publishable package → `library`.
378
+ */
379
+ function deriveProfile(input) {
380
+ if (/-template$/.test(input.repoName)) return "template";
381
+ if (input.isMonorepo) {
382
+ if (input.workspacePackageJsons.some((pkg) => Boolean(pkg.bin))) return "platform";
383
+ if (input.workspacePackageJsons.some((pkg) => pkg.private !== true)) return "library";
383
384
  }
385
+ const pkg = input.rootPackageJson;
386
+ if (pkg?.bin) return "cli";
387
+ const deps = {
388
+ ...pkg?.dependencies,
389
+ ...pkg?.devDependencies
390
+ };
391
+ const isDocsSite = Boolean(deps["@theholocron/astro-config"] || deps["astro"]);
392
+ if (pkg?.private && isDocsSite) return "docs";
393
+ if (pkg?.private) return "app";
394
+ return "library";
395
+ }
396
+ const KNOWN_STACK_DEPS = [
397
+ "next",
398
+ "vite",
399
+ "astro",
400
+ "tsdown",
401
+ "rollup",
402
+ "webpack",
403
+ "storybook",
404
+ "vitest",
405
+ "playwright",
406
+ "turbo"
407
+ ];
408
+ /**
409
+ * Detected build/framework tooling — the literal "does this repo need
410
+ * next/vite/tsdown" signal `holocron.config.ts` has no field for today
411
+ * (framework choice isn't a config concept, unlike `providers`/`tasks`).
412
+ * Curated table, not exhaustive by design — add to `KNOWN_STACK_DEPS` as new
413
+ * frameworks show up rather than trying to detect anything on npm.
414
+ */
415
+ function deriveStack(pkg) {
416
+ const deps = {
417
+ ...pkg?.dependencies,
418
+ ...pkg?.devDependencies
419
+ };
420
+ return KNOWN_STACK_DEPS.filter((name) => name in deps);
384
421
  }
385
- function parseGitRemoteUrl(url) {
386
- const httpsMatch = url.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
387
- if (httpsMatch) return httpsMatch[1];
388
- const sshMatch = url.match(/github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
389
- if (sshMatch) return sshMatch[1];
422
+ /** The provider capability keys actually wired in `providers: {}` — zero heuristics. */
423
+ function deriveCapabilities(providers) {
424
+ return Object.keys(providers ?? {}).sort();
390
425
  }
391
- //#endregion
392
- export { AuthError, CARDINALITY, ConfigError, ConfigFileError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, compose, createFeatureResolver, createResolveToken, createRestClient, defineConfig, deleteToken, getToken, isMulti, listStoredProviders, loadConfig, resolveConfig, resolveEntry, resolvePluginPackage, setToken };
426
+ /**
427
+ * `source` + `ci` are the minimal baseline every repo `holocron repo setup`
428
+ * touches wires — every `holocron.config.ts` in this org already satisfies
429
+ * this, so `non-compliant` here means drift (a provider manually removed
430
+ * after setup), not an unmet aspirational policy. Deliberately not a richer
431
+ * per-profile policy yet (e.g. "a `library` must have `deployment`") — that's
432
+ * a Phase B (GitHub App) refinement once it can post *why* on a check run.
433
+ */
434
+ const REQUIRED_BASELINE = ["source", "ci"];
435
+ /** Whether a repo's capabilities include the required baseline (`source` and `ci`); `non-compliant` means drift. */
436
+ function deriveCompliance(capabilities) {
437
+ return REQUIRED_BASELINE.every((key) => capabilities.includes(key)) ? "compliant" : "non-compliant";
438
+ }
439
+ /**
440
+ * The Phase B refinement `deriveCompliance()`'s own doc comment names —
441
+ * *why* a repo is non-compliant, not just that it is. `[]` when compliant.
442
+ * Same `REQUIRED_BASELINE` `deriveCompliance()` checks against — one
443
+ * table, not two independently-maintained baselines.
444
+ */
445
+ function missingCapabilities(capabilities) {
446
+ return REQUIRED_BASELINE.filter((key) => !capabilities.includes(key));
447
+ }
448
+ /**
449
+ * Reads each workspace package's actual `package.json` content (not just
450
+ * `readWorkspacePackages()`'s `{ slug, name, dir }` — `deriveProfile()`'s
451
+ * `platform` detection needs `bin`, which that helper doesn't carry).
452
+ * Missing/invalid files are skipped, matching `readWorkspacePackages()`'s
453
+ * own soft-fail behavior.
454
+ */
455
+ async function readWorkspacePackageJsons(repoRoot, workspacePackages) {
456
+ const results = [];
457
+ for (const { slug, dir = "packages", path } of workspacePackages) {
458
+ const pkg = await readPackageJson(join(repoRoot, path ?? join(dir, slug)));
459
+ if (pkg) results.push(pkg);
460
+ }
461
+ return results;
462
+ }
463
+ // src/commands/setup/labels.ts
464
+ /**
465
+ * The labels every repository gets from `repo setup`, with their GitHub colours (hex, no `#`) and descriptions. A
466
+ * plugin that makes labels of its own, such as Linear's setup, takes the colour of the one with the same name.
467
+ */
468
+ const CANONICAL_LABELS = [
469
+ {
470
+ name: "bug",
471
+ color: "d73a4a",
472
+ description: "Something isn't working"
473
+ },
474
+ {
475
+ name: "chore",
476
+ color: "ededed",
477
+ description: "Maintenance, no user-facing change"
478
+ },
479
+ {
480
+ name: "ci",
481
+ color: "0075ca",
482
+ description: "CI/CD pipeline changes"
483
+ },
484
+ {
485
+ name: "dependencies",
486
+ color: "0366d6",
487
+ description: "Dependency update"
488
+ },
489
+ {
490
+ name: "documentation",
491
+ color: "0075ca",
492
+ description: "Documentation only"
493
+ },
494
+ {
495
+ name: "duplicate",
496
+ color: "cfd3d7",
497
+ description: "Already reported"
498
+ },
499
+ {
500
+ name: "enhancement",
501
+ color: "a2eeef",
502
+ description: "New feature or request"
503
+ },
504
+ {
505
+ name: "good first issue",
506
+ color: "7057ff",
507
+ description: "Good for newcomers"
508
+ },
509
+ {
510
+ name: "help wanted",
511
+ color: "008672",
512
+ description: "Extra attention needed"
513
+ },
514
+ {
515
+ name: "invalid",
516
+ color: "e4e669",
517
+ description: "Doesn't seem right"
518
+ },
519
+ {
520
+ name: "performance",
521
+ color: "fbca04",
522
+ description: "Performance improvement"
523
+ },
524
+ {
525
+ name: "question",
526
+ color: "d876e3",
527
+ description: "Further information requested"
528
+ },
529
+ {
530
+ name: "refactor",
531
+ color: "cfd3d7",
532
+ description: "Code restructuring"
533
+ },
534
+ {
535
+ name: "released",
536
+ color: "ededed",
537
+ description: "Included in a release"
538
+ },
539
+ {
540
+ name: "test",
541
+ color: "bfd4f2",
542
+ description: "Test-related changes"
543
+ },
544
+ {
545
+ name: "triage",
546
+ color: "e4e669",
547
+ description: "Needs investigation"
548
+ },
549
+ {
550
+ name: "wontfix",
551
+ color: "ffffff",
552
+ description: "Won't be addressed"
553
+ }
554
+ ];
555
+ export { AuthError, CANONICAL_LABELS, CARDINALITY, ConfigError, ConfigFileError, ElevationRequiredError, HOLOCRON_AREAS, MissingTokenError, ProviderApiError, REQUIRED_CAPABILITIES, SHARED_AREAS, WebhookVerificationError, compose, connectionProbe, createFeatureResolver, createResolveToken, createRestClient, credentialsEnvironment, defineConfig, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, isMulti, keyring, loadConfig, missingCapabilities, orderKeys, pickByCreation, placeAreas, readKeysLimited, readLinks, readWorkspacePackageJsons, reportProgress, resolveConfig, resolveEntry, resolvePluginPackage, resolveValue, roleTeamProblem, sourceProblem, syncRoles };