@theholocron/cli 5.0.0-alpha.44 → 5.0.0-alpha.441

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,814 @@
1
+ import { CARDINALITY, REQUIRED_CAPABILITIES } from "./plugin/capabilities.mjs";
2
+ import { resolvePluginPackage } from "@theholocron/kyber/plugins";
3
+ import { ConfigError, ConfigError as ConfigError$1, ConfigFileError, createConfigSystem, lastWins, mergeByKey, shallowMerge, union } from "@theholocron/kyber/config";
4
+ import { readGitRemote } from "@theholocron/git-utils";
5
+ import { basename, dirname } from "node:path";
6
+ import { readPackageJson } from "@theholocron/pkg-utils";
7
+ import { resolveTaskName } from "@theholocron/astromech";
8
+ import { loadTasksConfig } from "@theholocron/astromech/config";
9
+ // src/credentials-environments/derives-environment/derives-environment.ts
10
+ /** The providers whose `credentials` entry may leave `environment` out and have it derived (#2063). */
11
+ const DERIVING = /* @__PURE__ */ new Set(["1password"]);
12
+ /** Whether a `credentials` provider with no `environment` option derives its Environment names. */
13
+ function derivesEnvironment(provider) {
14
+ return DERIVING.has(provider);
15
+ }
16
+ // src/credentials-environments/layer-environment/layer-environment.ts
17
+ /** The layer words, in the order the docs list them. */
18
+ const ENVIRONMENT_LAYERS = [
19
+ "local",
20
+ "dev",
21
+ "ci",
22
+ "prod"
23
+ ];
24
+ /** Whether `value` is exactly one of the layer words (case-sensitive: `Prod` is a literal Environment name). */
25
+ function isEnvironmentLayer(value) {
26
+ return typeof value === "string" && ENVIRONMENT_LAYERS.includes(value);
27
+ }
28
+ /**
29
+ * The Environment a layer of a repository is kept in: `<org/repo> - <layer>`. The one place the name is built, for the
30
+ * `credentials` providers (`environmentLayers()`) and for the config entries that name a `layer`.
31
+ */
32
+ function layerEnvironment(slug, layer) {
33
+ return `${slug} - ${layer}`;
34
+ }
35
+ // src/config/validate-environment-choice/validate-environment-choice.ts
36
+ /**
37
+ * Check that an entry names its vault Environment one way: a literal `environment`, or a `layer` the name is derived
38
+ * from (spec `tech-environment-layers`, #2069). Both together are an error, and so is a `layer` that is not a layer word
39
+ * or an `environment` that is blank. With neither, the entry is an error unless `required` is false.
40
+ *
41
+ * @param entry - The `environment` and `layer` the entry sets.
42
+ * @param what - How a message names the entry, e.g. "a `repo.secrets.deploy` entry".
43
+ * @param required - Whether the entry must name one of the two. Default true.
44
+ * @returns What the entry names (the environment, else the layer), for the rest of its messages; `undefined` for neither.
45
+ * @throws {ConfigError} Naming the entry and the problem.
46
+ */
47
+ function validateEnvironmentChoice(entry, what, required = true) {
48
+ const { environment, layer } = entry;
49
+ if (environment !== void 0 && layer !== void 0) throw new ConfigError(`${what} sets both \`layer\` and \`environment\`: name the Environment one way`);
50
+ if (layer !== void 0) {
51
+ if (!isEnvironmentLayer(layer)) throw new ConfigError(`${what} has \`layer\` ${JSON.stringify(layer)}: use ${ENVIRONMENT_LAYERS.map((l) => `"${l}"`).join(", ")}, or \`environment\` for a literal name`);
52
+ return layer;
53
+ }
54
+ if (environment !== void 0) {
55
+ if (typeof environment !== "string" || environment.trim() === "") throw new ConfigError(`${what} needs the name of a vault environment, got an empty \`environment\``);
56
+ return environment;
57
+ }
58
+ if (required) throw new ConfigError(`${what} needs the name of a vault environment (\`environment\`) or a \`layer\``);
59
+ }
60
+ // src/credentials-environments/repo-slug/repo-slug.ts
61
+ /**
62
+ * The `<org>/<repo>` of the repository at `cwd`, from its `origin` remote. A remote that is missing or cannot be
63
+ * parsed is a `ConfigError` that names the `environment` option as the fix.
64
+ */
65
+ async function repoSlug(cwd, exec) {
66
+ const remote = await readGitRemote(cwd, exec ? { exec } : {});
67
+ if (!remote) throw new ConfigError(`cannot derive the 1Password Environment name: the \`origin\` remote of ${cwd} is missing or not an owner/repo URL. Give the \`credentials\` provider an \`environment\` option to name it.`);
68
+ return remote.slug;
69
+ }
70
+ // src/credentials-environments/unsynced-layer/unsynced-layer.ts
71
+ /** The layers this machine reads for itself. They are never synced to GitHub, a deployment or a Worker (#2104). */
72
+ const UNSYNCED_LAYERS = ["local", "dev"];
73
+ /** Whether `layer` is one of {@link UNSYNCED_LAYERS}. */
74
+ function isUnsyncedLayer(layer) {
75
+ return isEnvironmentLayer(layer) && UNSYNCED_LAYERS.includes(layer);
76
+ }
77
+ /**
78
+ * The text of the error for an Environment of an unsynced layer, shared by the command and the config checks.
79
+ *
80
+ * @param what - What names the layer, e.g. "`sync secrets --env dev`" or "a `repo.secrets.sync` entry".
81
+ * @param layer - The unsynced layer.
82
+ */
83
+ function unsyncedLayerMessage(what, layer) {
84
+ return `${what} names the \`${layer}\` layer: \`local\` and \`dev\` are read by this machine and are never synced. Only ${ENVIRONMENT_LAYERS.filter((l) => !isUnsyncedLayer(l)).map((l) => `\`${l}\``).join(" and ")} can be synced`;
85
+ }
86
+ // src/config/validate-secrets-deploy/validate-secrets-deploy.ts
87
+ /**
88
+ * Check `repo.secrets.deploy`: each entry names a vault environment (or a `layer`) and at least one of a non-empty `keys` list and a
89
+ * non-empty `prefix`. An entry with neither would mean "all keys", which a deployment never gets (spec
90
+ * `tech-deployment-key-allowlist`, #2061), so it is an error here and not a silent skip.
91
+ *
92
+ * @param secrets - `repo.secrets`, if the config has it.
93
+ * @throws {ConfigError} Naming the first problem found.
94
+ */
95
+ function validateSecretsDeploy(secrets) {
96
+ for (const entry of secrets?.deploy ?? []) {
97
+ const named = validateEnvironmentChoice(entry, "a `repo.secrets.deploy` entry");
98
+ const label = `\`repo.secrets.deploy\` entry for ${JSON.stringify(named)}`;
99
+ if (isUnsyncedLayer(entry.layer)) throw new ConfigError(unsyncedLayerMessage(label, entry.layer));
100
+ const { keys, prefix } = entry;
101
+ if (keys !== void 0 && (!Array.isArray(keys) || keys.some((k) => typeof k !== "string" || k === ""))) throw new ConfigError(`${label} has \`keys\` that is not a list of key names`);
102
+ if (prefix !== void 0 && (typeof prefix !== "string" || prefix === "")) throw new ConfigError(`${label} has an empty \`prefix\``);
103
+ if ((keys === void 0 || keys.length === 0) && prefix === void 0) throw new ConfigError(`${label} needs \`keys\` (a list of names) or \`prefix\` (such as "SENTINEL_"): a deployment never receives every key`);
104
+ }
105
+ }
106
+ // src/config/validate-secrets-sync/validate-secrets-sync.ts
107
+ /**
108
+ * Check `repo.secrets.sync`: each entry names its vault environment one way, a literal `environment` or a `layer`
109
+ * (spec `tech-environment-layers`, #2069). An organization
110
+ * scope must say who can read the secrets: `visibility: "selected"` (or left out) and a non-empty `repos` list. A
111
+ * concealed value is never readable by every repository, so `visibility: "all"` and `"private"` are errors, and an
112
+ * entry with no list does not load (spec `tech-org-secret-visibility`, #2062). `repos` and `visibility` mean nothing
113
+ * on another scope, so they are errors there. A repository name is `name` or `<org>/name` of the scope's own
114
+ * organization, and one key may not be given two different reader lists at the same organization.
115
+ *
116
+ * @param secrets - `repo.secrets`, if the config has it.
117
+ * @throws {ConfigError} Naming the first problem found.
118
+ */
119
+ function validateSecretsSync(secrets) {
120
+ const readers = /* @__PURE__ */ new Map();
121
+ for (const entry of secrets?.sync ?? []) {
122
+ const named = validateEnvironmentChoice(entry, "a `repo.secrets.sync` entry");
123
+ const label = `\`repo.secrets.sync\` entry for ${JSON.stringify(named)}`;
124
+ if (isUnsyncedLayer(entry.layer)) throw new ConfigError(unsyncedLayerMessage(label, entry.layer));
125
+ const scope = entry.scope ?? "repo";
126
+ if (!scope.startsWith("org=")) {
127
+ if (entry.visibility !== void 0 || entry.repos !== void 0) throw new ConfigError(`${label} sets \`visibility\` or \`repos\` on scope ${JSON.stringify(scope)}: only an organization scope ("org=<name>") has readers to name`);
128
+ continue;
129
+ }
130
+ const org = scope.slice(4);
131
+ if (entry.visibility !== void 0 && entry.visibility !== "selected") throw new ConfigError(`${label} has visibility ${JSON.stringify(entry.visibility)}: a secret is never readable by every repository, so use "selected" with \`repos\``);
132
+ const { repos } = entry;
133
+ if (!Array.isArray(repos) || repos.length === 0 || repos.some((r) => typeof r !== "string" || !/^(?:[^/]+\/)?[^/]+$/.test(r))) throw new ConfigError(`${label} needs \`repos\`, a non-empty list of the repositories (\`name\` or \`<org>/name\`) that can read the secrets: an organization secret is never readable by every repository`);
134
+ const names = repos.map((r) => {
135
+ const slash = r.indexOf("/");
136
+ if ((slash < 0 ? org : r.slice(0, slash)) !== org) throw new ConfigError(`${label} lists repository ${JSON.stringify(r)}: use a name in ${JSON.stringify(org)}, such as "holocron"`);
137
+ return r.slice(slash + 1);
138
+ });
139
+ const list = [...new Set(names)].sort().join(", ");
140
+ for (const key of entry.keys ?? []) {
141
+ const id = `${org}/${key.toUpperCase()}`;
142
+ const seen = readers.get(id);
143
+ if (seen !== void 0 && seen !== list) throw new ConfigError(`${label} lists ${key}, which another \`repo.secrets.sync\` entry at org=${org} gives different readers [${seen}]: a secret has one reader list`);
144
+ readers.set(id, list);
145
+ }
146
+ }
147
+ }
148
+ // src/config/validate-variables-sync/validate-variables-sync.ts
149
+ /** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
150
+ const key = (name) => name.toUpperCase();
151
+ /**
152
+ * Check `repo.variables.sync`: each entry names a vault environment, one or more keys and a scope that is `repo` or
153
+ * `org=<name>`; a name may not also be a literal value of the same scope (one source per name); and `prune` cannot
154
+ * be combined with `sync`, because `setup` would delete the variables the sync wrote.
155
+ *
156
+ * @param variables - `repo.variables`, if the config has it.
157
+ * @throws {ConfigError} Naming the first problem found.
158
+ */
159
+ function validateVariablesSync(variables) {
160
+ const entries = variables?.sync;
161
+ if (!entries || entries.length === 0) return;
162
+ if (variables?.prune === true) throw new ConfigError("`repo.variables.prune` cannot be combined with `repo.variables.sync`: pruning would delete the variables the sync writes");
163
+ for (const entry of entries) {
164
+ const named = validateEnvironmentChoice(entry, "a `repo.variables.sync` entry");
165
+ const label = `\`repo.variables.sync\` entry for ${JSON.stringify(named)}`;
166
+ if (!Array.isArray(entry.keys) || entry.keys.length === 0 || entry.keys.some((k) => typeof k !== "string" || k === "")) throw new ConfigError(`${label} needs \`keys\`, a list of variable names`);
167
+ const scope = entry.scope ?? "repo";
168
+ const org = scope.startsWith("org=") ? scope.slice(4) : void 0;
169
+ if (scope !== "repo" && (org === void 0 || org === "")) throw new ConfigError(`${label} has scope ${JSON.stringify(scope)}: use "repo" or "org=<name>"`);
170
+ if (entry.visibility !== void 0 && entry.visibility !== "all" && entry.visibility !== "private") throw new ConfigError(`${label} has visibility ${JSON.stringify(entry.visibility)}: use "all" or "private"`);
171
+ const literal = new Set(Object.keys((org === void 0 ? variables?.repo : variables?.org) ?? {}).map(key));
172
+ const both = entry.keys.filter((k) => literal.has(key(k)));
173
+ if (both.length > 0) throw new ConfigError(`${label} lists ${both.join(", ")}, which \`repo.variables.${org === void 0 ? "repo" : "org"}\` also gives a value: keep one source per name`);
174
+ }
175
+ }
176
+ // src/config/config/config.ts
177
+ const PLUGIN_PREFIX = "@theholocron/holocron-plugin-";
178
+ const COMMUNITY_PREFIX = "holocron-plugin-";
179
+ /**
180
+ * Resolve `"github"` → `"@theholocron/holocron-plugin-github"`.
181
+ * Fully-qualified names (scoped or not) are honored verbatim, which
182
+ * is how third-party plugins published outside the org work.
183
+ */
184
+ function resolvePluginPackage$1(provider) {
185
+ if (!provider) throw new ConfigError$1("provider name is empty");
186
+ return resolvePluginPackage(provider, PLUGIN_PREFIX, COMMUNITY_PREFIX);
187
+ }
188
+ /** A bare `[provider, options]` tuple, with both elements present? */
189
+ function isOptionsTuple(value) {
190
+ if (!Array.isArray(value)) return false;
191
+ if (value.length !== 2) return false;
192
+ if (typeof value[0] !== "string") return false;
193
+ const opt = value[1];
194
+ return typeof opt === "object" && opt !== null && !Array.isArray(opt);
195
+ }
196
+ function normalizeEntry(entry) {
197
+ if (typeof entry === "string") return {
198
+ provider: entry,
199
+ packageName: resolvePluginPackage$1(entry),
200
+ options: {}
201
+ };
202
+ const [provider, options] = entry;
203
+ return {
204
+ provider,
205
+ packageName: resolvePluginPackage$1(provider),
206
+ options
207
+ };
208
+ }
209
+ /** Resolves one capability's raw provider entry into single or multiple resolved tuples, checking it against the capability's cardinality. */
210
+ function resolveEntry(key, raw) {
211
+ const cardinality = CARDINALITY[key];
212
+ if (typeof raw === "string") {
213
+ if (cardinality === "many") throw new ConfigError$1(`\`${key}\` accepts multiple providers; wrap a single one in an array: ["${raw}"]`);
214
+ return {
215
+ cardinality: "single",
216
+ tuple: normalizeEntry(raw)
217
+ };
218
+ }
219
+ if (!Array.isArray(raw)) throw new ConfigError$1(`\`${key}\` entry must be a string or array, got ${typeof raw}`);
220
+ if (isOptionsTuple(raw)) {
221
+ if (cardinality === "many") return {
222
+ cardinality: "many",
223
+ tuples: [normalizeEntry(raw)]
224
+ };
225
+ return {
226
+ cardinality: "single",
227
+ tuple: normalizeEntry(raw)
228
+ };
229
+ }
230
+ if (cardinality === "single") throw new ConfigError$1(`\`${key}\` accepts exactly one provider; got a multi-provider list with ${raw.length} entries`);
231
+ return {
232
+ cardinality: "many",
233
+ tuples: raw.map((entry, idx) => {
234
+ if (typeof entry === "string") return normalizeEntry(entry);
235
+ if (isOptionsTuple(entry)) return normalizeEntry(entry);
236
+ throw new ConfigError$1(`\`${key}[${idx}]\` must be a provider string or [provider, options] tuple`);
237
+ })
238
+ };
239
+ }
240
+ /** A DNS hostname of at least two labels: no scheme, port, path or space. */
241
+ const HOSTNAME = /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$/;
242
+ /** Throws a {@link ConfigError} naming the first thing wrong with the `githubApps` list. */
243
+ function validateGitHubApps(apps) {
244
+ if (!Array.isArray(apps)) throw new ConfigError$1("`githubApps` must be a list of { name, manifest, environment }");
245
+ apps.forEach((app, idx) => {
246
+ for (const key of ["name", "manifest"]) {
247
+ const value = app?.[key];
248
+ if (typeof value !== "string" || value.trim() === "") throw new ConfigError$1(`\`githubApps[${idx}].${key}\` must be a non-empty string`);
249
+ }
250
+ validateEnvironmentChoice(app, `\`githubApps[${idx}]\``);
251
+ });
252
+ }
253
+ /** Throws a {@link ConfigError} naming the first thing wrong with the `ideas` block. */
254
+ function validateIdeas(ideas) {
255
+ const nonEmpty = (value) => typeof value === "string" && value.trim() !== "";
256
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
257
+ if (!isObject(ideas)) throw new ConfigError$1("`ideas` must be an object: { states?, dir? (deprecated) }");
258
+ if (ideas.dir !== void 0 && !nonEmpty(ideas.dir)) throw new ConfigError$1("`ideas.dir` must be the path of the notes folder, got an empty value");
259
+ if (ideas.states !== void 0) {
260
+ if (!isObject(ideas.states)) throw new ConfigError$1("`ideas.states` must be an object: { file? }");
261
+ if (ideas.states.file !== void 0 && !nonEmpty(ideas.states.file)) throw new ConfigError$1("`ideas.states.file` must be a state name, got an empty value");
262
+ }
263
+ }
264
+ /** Throws a {@link ConfigError} naming the first thing wrong with the `dev` block. */
265
+ function validateDev(dev) {
266
+ const nonEmpty = (value) => typeof value === "string" && value.trim() !== "";
267
+ validateEnvironmentChoice(dev, "`dev`", false);
268
+ if (dev.tunnel !== void 0) {
269
+ if (!nonEmpty(dev.tunnel.name)) throw new ConfigError$1("`dev.tunnel.name` must be a name, got an empty value");
270
+ if (typeof dev.tunnel.hostname !== "string" || !HOSTNAME.test(dev.tunnel.hostname)) throw new ConfigError$1(`\`dev.tunnel.hostname\` must be a hostname such as sentinel-dev.example.dev (no scheme or path), got ${JSON.stringify(dev.tunnel.hostname)}`);
271
+ }
272
+ if (dev.port !== void 0 && !(Number.isInteger(dev.port) && dev.port >= 1 && dev.port <= 65535)) throw new ConfigError$1(`\`dev.port\` must be a port from 1 to 65535, got ${JSON.stringify(dev.port)}`);
273
+ if (dev.command !== void 0 && !(Array.isArray(dev.command) && dev.command.length > 0 && dev.command.every(nonEmpty))) throw new ConfigError$1("`dev.command` must be the program and its arguments, e.g. [\"pnpm\", \"run\", \"serve\"]");
274
+ if (dev.serve !== void 0) {
275
+ const { serve } = dev;
276
+ if (!nonEmpty(serve.handler)) throw new ConfigError$1("`dev.serve.handler` must be the path of the module that exports the handler");
277
+ if (serve.export !== void 0 && !nonEmpty(serve.export)) throw new ConfigError$1("`dev.serve.export` must be the name of the handler's export, got an empty value");
278
+ if (serve.required !== void 0 && !(Array.isArray(serve.required) && serve.required.every(nonEmpty))) throw new ConfigError$1("`dev.serve.required` must be a list of variable names");
279
+ if (serve.logging !== void 0 && !(nonEmpty(serve.logging.tokenVar) && nonEmpty(serve.logging.datasetVar))) throw new ConfigError$1("`dev.serve.logging` needs a `tokenVar` and a `datasetVar`, both variable names");
280
+ }
281
+ }
282
+ /** Throws a {@link ConfigError} when the `vault` entry's options name an Environment two ways, or a `layer` that is no layer word. */
283
+ function validateVaultLayer(entry) {
284
+ if (entry?.cardinality !== "single") return;
285
+ validateEnvironmentChoice(entry.tuple.options, "the `vault` provider's options", false);
286
+ }
287
+ /** The values `repoValidation.docsCoverage` accepts. */
288
+ const DOCS_COVERAGE_MODES = [
289
+ "off",
290
+ "warn",
291
+ "required"
292
+ ];
293
+ /**
294
+ * The environment a `credentials` provider reads: its own `environment` option when it has one, else the shared
295
+ * `credentials.environment`, else `undefined`. The option lets each of several providers name its own (a 1Password
296
+ * Environment and an AWS secret are not called the same thing) without the plugin storing the name.
297
+ */
298
+ function credentialsEnvironment(tuple, config) {
299
+ const own = tuple.options.environment;
300
+ return typeof own === "string" && own.trim() !== "" ? own : config.credentials?.environment;
301
+ }
302
+ /** Validates a raw `holocron.config` and resolves its provider entries; throws `ConfigError` when `name` or `providers` is missing or an entry is malformed. */
303
+ function resolveConfig(raw) {
304
+ if (!raw.name) throw new ConfigError$1("`name` is required");
305
+ if (!raw.providers || typeof raw.providers !== "object") throw new ConfigError$1("`providers` block is required");
306
+ const providers = {};
307
+ for (const [key, entry] of Object.entries(raw.providers)) {
308
+ if (entry === void 0) continue;
309
+ providers[key] = resolveEntry(key, entry);
310
+ }
311
+ for (const required of REQUIRED_CAPABILITIES) if (!providers[required]) throw new ConfigError$1(`required capability \`${required}\` is missing from providers`);
312
+ let docs;
313
+ if (raw.docs !== void 0) {
314
+ if (!raw.docs.build) throw new ConfigError$1("`docs.build` is required when `docs` is set");
315
+ docs = raw.docs;
316
+ }
317
+ const docsCoverage = raw.repoValidation?.docsCoverage;
318
+ if (docsCoverage !== void 0 && !DOCS_COVERAGE_MODES.includes(docsCoverage)) throw new ConfigError$1(`\`repoValidation.docsCoverage\` must be one of ${DOCS_COVERAGE_MODES.map((m) => `"${m}"`).join(", ")}, got ${JSON.stringify(docsCoverage)}`);
319
+ if (raw.credentials !== void 0) {
320
+ const environment = raw.credentials.environment;
321
+ if (typeof environment !== "string" || environment.trim() === "") throw new ConfigError$1("`credentials.environment` must be the name of an environment, got an empty value");
322
+ }
323
+ if (raw.dev !== void 0) validateDev(raw.dev);
324
+ if (raw.githubApps !== void 0) validateGitHubApps(raw.githubApps);
325
+ if (raw.ideas !== void 0) validateIdeas(raw.ideas);
326
+ validateVariablesSync(raw.repo?.variables);
327
+ validateSecretsDeploy(raw.repo?.secrets);
328
+ validateSecretsSync(raw.repo?.secrets);
329
+ validateVaultLayer(providers.vault);
330
+ const credentialsEntry = providers.credentials;
331
+ if (credentialsEntry?.cardinality === "many") for (const tuple of credentialsEntry.tuples) {
332
+ const own = tuple.options.environment;
333
+ if (own !== void 0 && (typeof own !== "string" || own.trim() === "")) throw new ConfigError$1(`the \`environment\` option of the \`${tuple.provider}\` credentials provider must be the name of an environment, got an empty value`);
334
+ if (credentialsEnvironment(tuple, raw) === void 0 && !derivesEnvironment(tuple.provider)) throw new ConfigError$1(`the \`${tuple.provider}\` credentials provider has no environment to read: give it an \`environment\` option or set \`credentials.environment\``);
335
+ }
336
+ const homepage = raw.homepage ?? (docs?.domain ? `https://${docs.domain}/` : void 0);
337
+ return {
338
+ name: raw.name,
339
+ description: raw.description,
340
+ homepage,
341
+ org: raw.org,
342
+ domain: raw.domain,
343
+ repo: raw.repo,
344
+ repoValidation: raw.repoValidation,
345
+ tasks: raw.tasks,
346
+ syncScripts: raw.syncScripts,
347
+ holocronScript: raw.holocronScript,
348
+ extraRequiredChecks: raw.extraRequiredChecks,
349
+ hooks: raw.hooks,
350
+ providers,
351
+ apps: raw.apps ?? [],
352
+ doctor: raw.doctor ?? {},
353
+ agent: raw.agent,
354
+ skills: raw.skills,
355
+ docs,
356
+ env: raw.env,
357
+ credentials: raw.credentials,
358
+ dev: raw.dev,
359
+ githubApps: raw.githubApps,
360
+ ideas: raw.ideas,
361
+ log: raw.log,
362
+ telemetry: raw.telemetry,
363
+ eslint: raw.eslint
364
+ };
365
+ }
366
+ // src/config/compose/merge-sync/merge-sync.ts
367
+ /**
368
+ * Merge two lists of `repo.secrets.sync` (or `repo.variables.sync`) entries. An entry is the same sync when its
369
+ * environment and scope match; the keys then add up, and an entry that names no keys (every key the vault holds) stays
370
+ * that way.
371
+ */
372
+ function mergeSync(a, b) {
373
+ const merged = /* @__PURE__ */ new Map();
374
+ for (const entry of [...a ?? [], ...b ?? []]) {
375
+ const id = JSON.stringify([
376
+ entry.environment,
377
+ entry.layer,
378
+ entry.scope ?? "repo"
379
+ ]);
380
+ const have = merged.get(id);
381
+ merged.set(id, have ? {
382
+ ...have,
383
+ ...have.keys && entry.keys ? { keys: [.../* @__PURE__ */ new Set([...have.keys, ...entry.keys])] } : { keys: void 0 }
384
+ } : { ...entry });
385
+ }
386
+ return [...merged.values()].map(({ keys, ...rest }) => keys ? {
387
+ ...rest,
388
+ keys
389
+ } : rest);
390
+ }
391
+ // src/config/compose/merge-repo/merge-repo.ts
392
+ const names = union();
393
+ const properties = shallowMerge();
394
+ const teamsByKey = mergeByKey((t) => typeof t === "string" ? t : t.slug);
395
+ /**
396
+ * Merge one capability's `repo` fragment onto what earlier ones gave. Scalars: last writer wins. `properties`: shallow
397
+ * merge. `variables`: merged per scope (`repo`, `org`), and `sync` entries by environment and scope. `secrets`: each name list is a union, and `sync` entries merge by
398
+ * environment and scope. `topics`: union. `teams`: merged by slug.
399
+ */
400
+ function mergeRepo(prev, next) {
401
+ const { properties: nextProperties, topics, teams, variables, secrets, ...scalars } = next;
402
+ const repo = {
403
+ ...prev,
404
+ ...scalars
405
+ };
406
+ if (nextProperties) repo.properties = properties.merge(repo.properties ?? {}, nextProperties);
407
+ if (variables) repo.variables = {
408
+ ...repo.variables,
409
+ ...variables,
410
+ ...repo.variables?.repo || variables.repo ? { repo: {
411
+ ...repo.variables?.repo,
412
+ ...variables.repo
413
+ } } : {},
414
+ ...repo.variables?.org || variables.org ? { org: {
415
+ ...repo.variables?.org,
416
+ ...variables.org
417
+ } } : {},
418
+ ...repo.variables?.sync || variables.sync ? { sync: mergeSync(repo.variables?.sync, variables.sync) } : {}
419
+ };
420
+ if (secrets) {
421
+ const environments = { ...repo.secrets?.environments };
422
+ for (const [env, list] of Object.entries(secrets.environments ?? {})) environments[env] = names.merge(environments[env] ?? [], list);
423
+ repo.secrets = {
424
+ ...repo.secrets?.repo || secrets.repo ? { repo: names.merge(repo.secrets?.repo ?? [], secrets.repo ?? []) } : {},
425
+ ...repo.secrets?.org || secrets.org ? { org: names.merge(repo.secrets?.org ?? [], secrets.org ?? []) } : {},
426
+ ...Object.keys(environments).length > 0 ? { environments } : {},
427
+ ...repo.secrets?.sync || secrets.sync ? { sync: mergeSync(repo.secrets?.sync, secrets.sync) } : {},
428
+ ...repo.secrets?.deploy || secrets.deploy ? { deploy: [...repo.secrets?.deploy ?? [], ...secrets.deploy ?? []] } : {}
429
+ };
430
+ }
431
+ if (topics) repo.topics = names.merge(repo.topics ?? [], topics);
432
+ if (teams) repo.teams = teamsByKey.merge(repo.teams ?? [], teams);
433
+ return repo;
434
+ }
435
+ // src/config/compose/task-name/task-name.ts
436
+ /**
437
+ * The key a task entry merges under. A name that stands for exactly one flat id (the id itself, or an old dotted
438
+ * alias such as `verification.unitTests`) keys by that id, so the alias overrides the preset's entry instead of
439
+ * sitting next to it; a name that stands for several ids or none (a suite, an unknown name) keys by itself.
440
+ */
441
+ function taskName(e) {
442
+ const name = typeof e === "string" ? e : e.name;
443
+ const resolved = resolveTaskName(name);
444
+ return resolved.length === 1 ? resolved[0].id : name;
445
+ }
446
+ // src/config/compose/merge-strategies/merge-strategies.ts
447
+ /**
448
+ * How `compose()` merges each key of the capabilities: tasks by name (an old dotted alias overrides the entry it names),
449
+ * providers shallowly, the non-task required checks as a union, `repo` by its own rules, the rest last writer wins.
450
+ */
451
+ const mergeStrategies = {
452
+ tasks: mergeByKey(taskName),
453
+ providers: shallowMerge(),
454
+ extraRequiredChecks: union(),
455
+ repo: {
456
+ empty: {},
457
+ merge: mergeRepo
458
+ },
459
+ org: lastWins(),
460
+ domain: lastWins(),
461
+ docs: lastWins()
462
+ };
463
+ // src/config/load-config/read-package-json-name/read-package-json-name.ts
464
+ /** The `name` of the `package.json` in `dir` without its scope, or `undefined`. */
465
+ async function readPackageJsonName(dir) {
466
+ const name = (await readPackageJson(dir))?.name;
467
+ return name === void 0 ? void 0 : name.replace(/^@[^/]+\//, "");
468
+ }
469
+ // src/config/load-config/derive-defaults/derive-defaults.ts
470
+ /**
471
+ * Fill in what a `holocron.config` leaves out: `name` from the package or directory, `repo.name` from the GitHub
472
+ * remote, and the task manifest (merged from `astromech.config.*`).
473
+ */
474
+ async function deriveDefaults(found) {
475
+ const configDir = dirname(found.filepath);
476
+ const result = { ...found.config };
477
+ if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
478
+ if (result.repo && !result.repo.name) {
479
+ const remote = await readGitRemote(configDir);
480
+ if (remote?.host === "github.com") result.repo = {
481
+ ...result.repo,
482
+ name: remote.slug
483
+ };
484
+ }
485
+ const manifest = await loadTasksConfig(configDir, { holocron: found });
486
+ if (manifest.tasks) result.tasks = manifest.tasks;
487
+ if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
488
+ if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
489
+ if (manifest.hooks !== void 0) result.hooks = manifest.hooks;
490
+ if (manifest.extraRequiredChecks) result.extraRequiredChecks = [...result.extraRequiredChecks ?? [], ...manifest.extraRequiredChecks];
491
+ return result;
492
+ }
493
+ // src/config/load-config/holocron-areas/holocron-areas.ts
494
+ /**
495
+ * The closed list of area files `loadConfig` reads from `.holocron/` (the directory is `.<config name>`, set by kyber):
496
+ * `.holocron/notifications.*` fills `providers.notifications`' `layout`, `.holocron/repo.*` fills keys of `repo`, and `.holocron/org.*` fills provider options (`teamId`, `accountId`) a config leaves out.
497
+ * A file not on this list is never read.
498
+ */
499
+ const HOLOCRON_AREAS = [
500
+ "notifications",
501
+ "repo",
502
+ "org"
503
+ ];
504
+ /**
505
+ * The areas a config in a subdirectory also reads from the repository root's `.holocron/` (SPEC-0069): only `org`,
506
+ * because its values are the organization's and every config needs them. `repo` and `notifications` describe the
507
+ * repository itself, so an app's config does not take them from the root.
508
+ */
509
+ const SHARED_AREAS = ["org"];
510
+ // src/config/load-config/place-notifications/place-notifications.ts
511
+ const isTuple$1 = (entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && typeof entry[1] === "object" && entry[1] !== null && !Array.isArray(entry[1]);
512
+ const providerName = (entry) => isTuple$1(entry) ? entry[0] : entry;
513
+ /** Index of the entry the layout belongs to in a multi-provider list: the first `discord`. */
514
+ function findDiscord(entries) {
515
+ return entries.findIndex((entry) => providerName(entry) === "discord");
516
+ }
517
+ function withLayout(entry, layout) {
518
+ return isTuple$1(entry) ? [entry[0], {
519
+ ...entry[1],
520
+ layout
521
+ }] : [entry, { layout }];
522
+ }
523
+ /**
524
+ * Set `layout` on the notifications provider from `.holocron/notifications.*`. The entry may be a name (`"discord"`),
525
+ * a `[name, options]` tuple, or a list (the first `discord` entry gets it). Throws `ConfigError` when the provider is
526
+ * not set or already has an inline `layout`.
527
+ */
528
+ function placeNotifications(raw, area) {
529
+ if (typeof area.value !== "object" || area.value === null || Array.isArray(area.value)) throw new ConfigError(`${area.path} must export the notifications layout as an object`);
530
+ const entry = raw.providers?.notifications;
531
+ const hint = `Set it in one place: remove the inline \`layout\` or delete ${area.path}`;
532
+ let placed;
533
+ if (entry === void 0) throw new ConfigError(`${area.path} holds the notifications layout, but providers.notifications is not set. Add \`notifications: ["discord", { guildId }]\` to providers`);
534
+ else if (Array.isArray(entry) && !isTuple$1(entry)) {
535
+ const index = findDiscord(entry);
536
+ if (index === -1) throw new ConfigError(`${area.path} holds the notifications layout, but providers.notifications has no discord entry`);
537
+ const target = entry[index];
538
+ if (isTuple$1(target) && target[1].layout !== void 0) throw new ConfigError(`the notifications layout is set in providers.notifications and in ${area.path}. ${hint}`);
539
+ placed = entry.map((item, i) => i === index ? withLayout(item, area.value) : item);
540
+ } else {
541
+ if (isTuple$1(entry) && entry[1].layout !== void 0) throw new ConfigError(`the notifications layout is set in providers.notifications and in ${area.path}. ${hint}`);
542
+ placed = withLayout(entry, area.value);
543
+ }
544
+ return {
545
+ ...raw,
546
+ providers: {
547
+ ...raw.providers,
548
+ notifications: placed
549
+ }
550
+ };
551
+ }
552
+ // src/config/load-config/place-org/place-org.ts
553
+ /** The options each provider key of `.holocron/org.*` may hold. Checked against `OrgConfig` by the type. */
554
+ const ORG_OPTIONS = {
555
+ cloudflare: ["accountId"],
556
+ vercel: ["teamId"],
557
+ checkly: ["accountId"],
558
+ sentry: ["org"]
559
+ };
560
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
561
+ const isTuple = (entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && isObject(entry[1]);
562
+ /**
563
+ * Check the shape of the area file: the top-level `domain` (a non-empty string), then a closed list of providers,
564
+ * each with a closed list of string options.
565
+ */
566
+ function validate(area) {
567
+ if (!isObject(area.value)) throw new ConfigError(`${area.path} must export the org settings as an object`);
568
+ const { domain, ...rest } = area.value;
569
+ if (domain !== void 0 && (typeof domain !== "string" || domain === "")) throw new ConfigError(`${area.path}: "domain" must be a non-empty string`);
570
+ for (const [provider, options] of Object.entries(rest)) {
571
+ const allowed = ORG_OPTIONS[provider];
572
+ if (allowed === void 0) throw new ConfigError(`${area.path} has an unknown provider "${provider}". Known: ${Object.keys(ORG_OPTIONS).join(", ")}`);
573
+ if (!isObject(options)) throw new ConfigError(`${area.path}: "${provider}" must be an object of options`);
574
+ for (const [option, value] of Object.entries(options)) {
575
+ if (!allowed.includes(option)) throw new ConfigError(`${area.path}: "${provider}.${option}" is not an org option. Known: ${allowed.join(", ")}`);
576
+ if (typeof value !== "string" || value === "") throw new ConfigError(`${area.path}: "${provider}.${option}" must be a non-empty string`);
577
+ }
578
+ }
579
+ return {
580
+ ...domain !== void 0 ? { domain } : {},
581
+ providers: rest
582
+ };
583
+ }
584
+ /**
585
+ * The org options of an area and, when the repository root has the same area, the root's under them: an option set in
586
+ * both takes the config's own value, option by option (the root's other options stay). Each file is checked on its own.
587
+ */
588
+ function merge(area) {
589
+ const providers = {};
590
+ let domain;
591
+ for (const layer of area.root ? [area.root, area] : [area]) {
592
+ const checked = validate(layer);
593
+ if (checked.domain !== void 0) domain = {
594
+ value: checked.domain,
595
+ path: layer.path
596
+ };
597
+ for (const [provider, options] of Object.entries(checked.providers)) {
598
+ const sourced = providers[provider] ??= {};
599
+ for (const [option, value] of Object.entries(options)) sourced[option] = {
600
+ value,
601
+ path: layer.path
602
+ };
603
+ }
604
+ }
605
+ return {
606
+ ...domain ? { domain } : {},
607
+ providers
608
+ };
609
+ }
610
+ /** Fill one entry when it names a provider the area holds; throws when the config already sets one of its options. */
611
+ function fill(entry, org, capability) {
612
+ const [provider, options] = isTuple(entry) ? entry : [entry, {}];
613
+ const values = org[provider];
614
+ if (values === void 0 || Object.keys(values).length === 0) return entry;
615
+ const filled = {};
616
+ for (const [option, { value, path }] of Object.entries(values)) {
617
+ if (options[option] !== void 0) throw new ConfigError(`${provider}.${option} is set in providers.${capability} and in ${path}. Set it in one place: remove the inline option or the key from ${path}`);
618
+ filled[option] = value;
619
+ }
620
+ return [provider, {
621
+ ...options,
622
+ ...filled
623
+ }];
624
+ }
625
+ /**
626
+ * Fill `.holocron/org.*` into the config. Its top-level `domain` (the org's zone) is set on a config that leaves
627
+ * `domain` out; set inline and in the file it is a `ConfigError` naming both. Its provider options go into the
628
+ * providers the config uses. A provider entry (a name, a
629
+ * `[name, options]` tuple, or either inside a list) that names a provider the file holds gets each option it leaves
630
+ * out. An option set inline and in the file is a `ConfigError` naming both (no merge, no precedence); a provider the
631
+ * config does not use is ignored; a provider or option the file lists but `OrgConfig` does not know is an error.
632
+ * When the area also came from the repository root (`area.root`, a config in a subdirectory), the two files combine
633
+ * option by option and the config's own file wins; that is not an error.
634
+ */
635
+ function placeOrg(raw, area) {
636
+ const { domain, providers: org } = merge(area);
637
+ if (domain !== void 0 && raw.domain !== void 0) throw new ConfigError(`domain is set in the config and in ${domain.path}. Set it in one place: remove the inline value or the key from ${domain.path}`);
638
+ const withDomain = domain === void 0 ? raw : {
639
+ ...raw,
640
+ domain: domain.value
641
+ };
642
+ if (withDomain.providers === void 0) return withDomain;
643
+ const providers = { ...withDomain.providers };
644
+ for (const [capability, entry] of Object.entries(withDomain.providers)) providers[capability] = Array.isArray(entry) && !isTuple(entry) ? entry.map((item) => fill(item, org, capability)) : fill(entry, org, capability);
645
+ return {
646
+ ...withDomain,
647
+ providers
648
+ };
649
+ }
650
+ // src/config/load-config/place-repo/place-repo.ts
651
+ /**
652
+ * Add the keys of `.holocron/repo.*` to `repo`. The keys of the two sources must differ (`repo.defaultBranch` stays
653
+ * inline so Sentinel can find the branch to read): a key set both inline and in the file is a `ConfigError` naming
654
+ * both.
655
+ */
656
+ function placeRepo(raw, area) {
657
+ if (typeof area.value !== "object" || area.value === null || Array.isArray(area.value)) throw new ConfigError(`${area.path} must export the repo settings as an object`);
658
+ const fromFile = area.value;
659
+ const inline = raw.repo ?? {};
660
+ for (const key of Object.keys(fromFile)) if (inline[key] !== void 0) throw new ConfigError(`repo.${key} is set in the config and in ${area.path}. Set it in one place: remove the inline value or the key from ${area.path}`);
661
+ return {
662
+ ...raw,
663
+ repo: {
664
+ ...inline,
665
+ ...fromFile
666
+ }
667
+ };
668
+ }
669
+ // src/config/load-config/place-areas/place-areas.ts
670
+ /**
671
+ * Put the area files of `.holocron/` into the config as loaded, before `deriveDefaults` runs: `notifications` becomes
672
+ * the `layout` of the notifications provider and `repo` supplies keys of `repo` and `org` fills the provider options a config leaves out. A value set both inline and in a file
673
+ * is a `ConfigError` naming both (no merge, no precedence). With no area files the config is returned as it was.
674
+ */
675
+ function placeAreas(areas, raw) {
676
+ let result = raw;
677
+ for (const area of areas) if (area.area === "notifications") result = placeNotifications(result, area);
678
+ else if (area.area === "repo") result = placeRepo(result, area);
679
+ else if (area.area === "org") result = placeOrg(result, area);
680
+ return result;
681
+ }
682
+ // src/config/resolve-layers/resolve-layers.ts
683
+ /**
684
+ * Turns every `layer` in a loaded config into the `environment` it names (spec `tech-environment-layers`, #2069), so
685
+ * the commands and doctors that read Environments see one literal name and none of them derives it again. The name is
686
+ * `layerEnvironment()` over the `origin` remote of `input.repoRoot`, read at most once and only when an entry names a
687
+ * layer. A remote that cannot be read is a `ConfigError` naming the `environment` option (`repoSlug()`); nothing is
688
+ * guessed. Covers `repo.secrets.sync`, `repo.secrets.deploy`, `repo.variables.sync`, `githubApps`, `dev` and the
689
+ * `vault` provider's `layer` option. Returns a new config; the one passed in is not changed.
690
+ *
691
+ * @param config - The resolved config, validated by `resolveConfig()`.
692
+ * @param input - Where to read the remote, and how.
693
+ * @returns The config with each `layer` replaced by its `environment`.
694
+ */
695
+ async function resolveLayers(config, input) {
696
+ let slug;
697
+ const named = async (entry) => {
698
+ if (entry.layer === void 0) return entry;
699
+ const { layer, ...rest } = entry;
700
+ slug ??= repoSlug(input.repoRoot, input.gitExec);
701
+ return {
702
+ ...rest,
703
+ environment: layerEnvironment(await slug, layer)
704
+ };
705
+ };
706
+ const all = (list) => Promise.all(list.map(named));
707
+ const out = { ...config };
708
+ const { repo } = config;
709
+ if (repo) {
710
+ const next = { ...repo };
711
+ if (repo.secrets) {
712
+ next.secrets = { ...repo.secrets };
713
+ if (repo.secrets.sync) next.secrets.sync = await all(repo.secrets.sync);
714
+ if (repo.secrets.deploy) next.secrets.deploy = await all(repo.secrets.deploy);
715
+ }
716
+ if (repo.variables?.sync) next.variables = {
717
+ ...repo.variables,
718
+ sync: await all(repo.variables.sync)
719
+ };
720
+ out.repo = next;
721
+ }
722
+ if (config.githubApps) out.githubApps = await all(config.githubApps);
723
+ if (config.dev) out.dev = await named(config.dev);
724
+ const vault = config.providers.vault;
725
+ if (vault?.cardinality === "single" && vault.tuple.options.layer !== void 0) {
726
+ const { layer, ...options } = vault.tuple.options;
727
+ const resolved = await named({ layer });
728
+ out.providers = {
729
+ ...config.providers,
730
+ vault: {
731
+ cardinality: "single",
732
+ tuple: {
733
+ ...vault.tuple,
734
+ options: {
735
+ ...options,
736
+ environment: resolved.environment
737
+ }
738
+ }
739
+ }
740
+ };
741
+ }
742
+ return out;
743
+ }
744
+ // src/config/config-system.ts
745
+ /**
746
+ * Holocron's config system: `defineConfig`, `loadConfig` and `compose`, all built from one
747
+ * `createConfigSystem` call.
748
+ *
749
+ * File discovery, the walk up to `.git`, module loading (typed configs via `tsx`) and the derive-then-resolve flow come
750
+ * from `@theholocron/kyber/config`. The holocron-specific parts are `deriveDefaults` (name, `repo.name`, the task
751
+ * manifest), `placeAreas` (the `.holocron/` area files, placed before `deriveDefaults`), `resolveConfig` and `mergeStrategies`.
752
+ *
753
+ * The three functions live together because each is only a method of the one system object; splitting them back into
754
+ * one file apiece would just be pass-through wrappers (an exception to the one-function-per-file rule).
755
+ *
756
+ * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
757
+ * see ADR-0010 / issue #75 / #81.
758
+ */
759
+ const system = createConfigSystem({
760
+ name: "holocron",
761
+ areas: HOLOCRON_AREAS,
762
+ shared: SHARED_AREAS,
763
+ place: placeAreas,
764
+ derive: deriveDefaults,
765
+ resolve: resolveConfig,
766
+ merge: mergeStrategies
767
+ });
768
+ /** Returns the config unchanged; it exists to type and autocomplete a `holocron.config.ts`. */
769
+ const defineConfig = system.defineConfig;
770
+ /**
771
+ * Read + parse + resolve `holocron.config.*` starting from the given
772
+ * directory, walking up through ancestors to the nearest `.git` boundary
773
+ * when `cwd` itself has no match — every command is usable from any
774
+ * subdirectory of a repo, not only its exact root (see
775
+ * `@theholocron/datapad`'s own doc comment for the stop conditions).
776
+ * Throws `ConfigFileError` when nothing is found or a file cannot
777
+ * be loaded, or `ConfigError` when the config fails schema checks.
778
+ *
779
+ * Every `layer` an entry names becomes the `environment` it stands for (`resolveLayers()`, spec
780
+ * `tech-environment-layers`, #2069), read from the `origin` remote at `cwd`; `input` lets a test pass a fake remote.
781
+ */
782
+ async function loadConfig(cwd, input = {}) {
783
+ const loaded = await system.loadConfig(cwd);
784
+ return {
785
+ ...loaded,
786
+ resolved: await resolveLayers(loaded.resolved, {
787
+ repoRoot: cwd,
788
+ ...input
789
+ })
790
+ };
791
+ }
792
+ /**
793
+ * Merge any number of capability fragments into a single preset object that
794
+ * spreads directly into `defineConfig()`.
795
+ *
796
+ * - Accepts individual capabilities or nested arrays (for bundle presets).
797
+ * - Deduplicates by `id` — when the same ID appears more than once, the last
798
+ * occurrence wins. This lets callers override bundle defaults by listing an
799
+ * explicit capability after the bundle.
800
+ * - Validates all `requires` at call time and throws `ConfigError` if any are
801
+ * unmet, listing every missing dependency in a single message.
802
+ *
803
+ * @example
804
+ * // docs-only site — no typecheck
805
+ * const preset = compose(node(), docs());
806
+ *
807
+ * // library with docs
808
+ * const preset = compose(node(), typecheck(), docs());
809
+ *
810
+ * // nextjs() is a bundle that returns Capability[]
811
+ * const preset = compose(node(), nextjs());
812
+ */
813
+ const compose = system.compose;
814
+ export { placeAreas as a, ConfigError$1 as c, resolveEntry as d, resolvePluginPackage$1 as f, layerEnvironment as g, isEnvironmentLayer as h, loadConfig as i, credentialsEnvironment as l, ENVIRONMENT_LAYERS as m, compose as n, HOLOCRON_AREAS as o, repoSlug as p, defineConfig as r, SHARED_AREAS as s, ConfigFileError as t, resolveConfig as u };