@theholocron/cli 5.0.0-alpha.34 → 5.0.0-alpha.341

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,319 @@
1
+ import { CARDINALITY, REQUIRED_CAPABILITIES } from "./plugin/capabilities.mjs";
2
+ import { ConfigError, createConfigSystem, lastWins, mergeByKey, shallowMerge, union } from "@theholocron/kyber/config";
3
+ import { basename, dirname } from "node:path";
4
+ import { readPackageJson } from "@theholocron/pkg-utils";
5
+ import { resolveTaskName } from "@theholocron/astromech";
6
+ import { loadTasksConfig } from "@theholocron/astromech/config";
7
+ import { readGitRemote } from "@theholocron/git-utils";
8
+ // src/config/config/config.ts
9
+ const PLUGIN_PREFIX = "@theholocron/holocron-plugin-";
10
+ const COMMUNITY_PREFIX = "holocron-plugin-";
11
+ /**
12
+ * Resolve `"github"` → `"@theholocron/holocron-plugin-github"`.
13
+ * Fully-qualified names (scoped or not) are honored verbatim, which
14
+ * is how third-party plugins published outside the org work.
15
+ */
16
+ function resolvePluginPackage(provider) {
17
+ if (!provider) throw new ConfigError("provider name is empty");
18
+ if (provider.startsWith("@")) return provider;
19
+ if (provider.startsWith(COMMUNITY_PREFIX)) return provider;
20
+ if (provider.includes("/")) return provider;
21
+ return PLUGIN_PREFIX + provider;
22
+ }
23
+ /** A bare `[provider, options]` tuple, with both elements present? */
24
+ function isOptionsTuple(value) {
25
+ if (!Array.isArray(value)) return false;
26
+ if (value.length !== 2) return false;
27
+ if (typeof value[0] !== "string") return false;
28
+ const opt = value[1];
29
+ return typeof opt === "object" && opt !== null && !Array.isArray(opt);
30
+ }
31
+ function normalizeEntry(entry) {
32
+ if (typeof entry === "string") return {
33
+ provider: entry,
34
+ packageName: resolvePluginPackage(entry),
35
+ options: {}
36
+ };
37
+ const [provider, options] = entry;
38
+ return {
39
+ provider,
40
+ packageName: resolvePluginPackage(provider),
41
+ options
42
+ };
43
+ }
44
+ /** Resolves one capability's raw provider entry into single or multiple resolved tuples, checking it against the capability's cardinality. */
45
+ function resolveEntry(key, raw) {
46
+ const cardinality = CARDINALITY[key];
47
+ if (typeof raw === "string") {
48
+ if (cardinality === "many") throw new ConfigError(`\`${key}\` accepts multiple providers; wrap a single one in an array: ["${raw}"]`);
49
+ return {
50
+ cardinality: "single",
51
+ tuple: normalizeEntry(raw)
52
+ };
53
+ }
54
+ if (!Array.isArray(raw)) throw new ConfigError(`\`${key}\` entry must be a string or array, got ${typeof raw}`);
55
+ if (isOptionsTuple(raw)) {
56
+ if (cardinality === "many") return {
57
+ cardinality: "many",
58
+ tuples: [normalizeEntry(raw)]
59
+ };
60
+ return {
61
+ cardinality: "single",
62
+ tuple: normalizeEntry(raw)
63
+ };
64
+ }
65
+ if (cardinality === "single") throw new ConfigError(`\`${key}\` accepts exactly one provider; got a multi-provider list with ${raw.length} entries`);
66
+ return {
67
+ cardinality: "many",
68
+ tuples: raw.map((entry, idx) => {
69
+ if (typeof entry === "string") return normalizeEntry(entry);
70
+ if (isOptionsTuple(entry)) return normalizeEntry(entry);
71
+ throw new ConfigError(`\`${key}[${idx}]\` must be a provider string or [provider, options] tuple`);
72
+ })
73
+ };
74
+ }
75
+ /** A DNS hostname of at least two labels: no scheme, port, path or space. */
76
+ 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])?)+$/;
77
+ /** Throws a {@link ConfigError} naming the first thing wrong with the `dev` block. */
78
+ function validateDev(dev) {
79
+ const nonEmpty = (value) => typeof value === "string" && value.trim() !== "";
80
+ if (dev.environment !== void 0 && !nonEmpty(dev.environment)) throw new ConfigError("`dev.environment` must be the name of a vault environment, got an empty value");
81
+ if (dev.tunnel !== void 0) {
82
+ if (!nonEmpty(dev.tunnel.name)) throw new ConfigError("`dev.tunnel.name` must be a name, got an empty value");
83
+ if (typeof dev.tunnel.hostname !== "string" || !HOSTNAME.test(dev.tunnel.hostname)) throw new ConfigError(`\`dev.tunnel.hostname\` must be a hostname such as sentinel-dev.example.dev (no scheme or path), got ${JSON.stringify(dev.tunnel.hostname)}`);
84
+ }
85
+ if (dev.port !== void 0 && !(Number.isInteger(dev.port) && dev.port >= 1 && dev.port <= 65535)) throw new ConfigError(`\`dev.port\` must be a port from 1 to 65535, got ${JSON.stringify(dev.port)}`);
86
+ if (dev.command !== void 0 && !(Array.isArray(dev.command) && dev.command.length > 0 && dev.command.every(nonEmpty))) throw new ConfigError("`dev.command` must be the program and its arguments, e.g. [\"pnpm\", \"run\", \"serve\"]");
87
+ if (dev.serve !== void 0) {
88
+ const { serve } = dev;
89
+ if (!nonEmpty(serve.handler)) throw new ConfigError("`dev.serve.handler` must be the path of the module that exports the handler");
90
+ if (serve.export !== void 0 && !nonEmpty(serve.export)) throw new ConfigError("`dev.serve.export` must be the name of the handler's export, got an empty value");
91
+ if (serve.required !== void 0 && !(Array.isArray(serve.required) && serve.required.every(nonEmpty))) throw new ConfigError("`dev.serve.required` must be a list of variable names");
92
+ if (serve.logging !== void 0 && !(nonEmpty(serve.logging.tokenVar) && nonEmpty(serve.logging.datasetVar))) throw new ConfigError("`dev.serve.logging` needs a `tokenVar` and a `datasetVar`, both variable names");
93
+ }
94
+ }
95
+ /** The values `repoValidation.docsCoverage` accepts. */
96
+ const DOCS_COVERAGE_MODES = [
97
+ "off",
98
+ "warn",
99
+ "required"
100
+ ];
101
+ /**
102
+ * The environment a `credentials` provider reads: its own `environment` option when it has one, else the shared
103
+ * `credentials.environment`, else `undefined`. The option lets each of several providers name its own (a 1Password
104
+ * Environment and an AWS secret are not called the same thing) without the plugin storing the name.
105
+ */
106
+ function credentialsEnvironment(tuple, config) {
107
+ const own = tuple.options.environment;
108
+ return typeof own === "string" && own.trim() !== "" ? own : config.credentials?.environment;
109
+ }
110
+ /** Validates a raw `holocron.config` and resolves its provider entries; throws `ConfigError` when `name` or `providers` is missing or an entry is malformed. */
111
+ function resolveConfig(raw) {
112
+ if (!raw.name) throw new ConfigError("`name` is required");
113
+ if (!raw.providers || typeof raw.providers !== "object") throw new ConfigError("`providers` block is required");
114
+ const providers = {};
115
+ for (const [key, entry] of Object.entries(raw.providers)) {
116
+ if (entry === void 0) continue;
117
+ providers[key] = resolveEntry(key, entry);
118
+ }
119
+ for (const required of REQUIRED_CAPABILITIES) if (!providers[required]) throw new ConfigError(`required capability \`${required}\` is missing from providers`);
120
+ let docs;
121
+ if (raw.docs !== void 0) {
122
+ if (!raw.docs.build) throw new ConfigError("`docs.build` is required when `docs` is set");
123
+ docs = raw.docs;
124
+ }
125
+ const docsCoverage = raw.repoValidation?.docsCoverage;
126
+ if (docsCoverage !== void 0 && !DOCS_COVERAGE_MODES.includes(docsCoverage)) throw new ConfigError(`\`repoValidation.docsCoverage\` must be one of ${DOCS_COVERAGE_MODES.map((m) => `"${m}"`).join(", ")}, got ${JSON.stringify(docsCoverage)}`);
127
+ if (raw.credentials !== void 0) {
128
+ const environment = raw.credentials.environment;
129
+ if (typeof environment !== "string" || environment.trim() === "") throw new ConfigError("`credentials.environment` must be the name of an environment, got an empty value");
130
+ }
131
+ if (raw.dev !== void 0) validateDev(raw.dev);
132
+ const credentialsEntry = providers.credentials;
133
+ if (credentialsEntry?.cardinality === "many") for (const tuple of credentialsEntry.tuples) {
134
+ const own = tuple.options.environment;
135
+ if (own !== void 0 && (typeof own !== "string" || own.trim() === "")) throw new ConfigError(`the \`environment\` option of the \`${tuple.provider}\` credentials provider must be the name of an environment, got an empty value`);
136
+ if (credentialsEnvironment(tuple, raw) === void 0) throw new ConfigError(`the \`${tuple.provider}\` credentials provider has no environment to read: give it an \`environment\` option or set \`credentials.environment\``);
137
+ }
138
+ const homepage = raw.homepage ?? (docs?.domain ? `https://${docs.domain}/` : void 0);
139
+ return {
140
+ name: raw.name,
141
+ description: raw.description,
142
+ homepage,
143
+ org: raw.org,
144
+ domain: raw.domain,
145
+ repo: raw.repo,
146
+ repoValidation: raw.repoValidation,
147
+ tasks: raw.tasks,
148
+ syncScripts: raw.syncScripts,
149
+ holocronScript: raw.holocronScript,
150
+ extraRequiredChecks: raw.extraRequiredChecks,
151
+ hooks: raw.hooks,
152
+ providers,
153
+ apps: raw.apps ?? [],
154
+ doctor: raw.doctor ?? {},
155
+ agent: raw.agent,
156
+ skills: raw.skills,
157
+ docs,
158
+ env: raw.env,
159
+ credentials: raw.credentials,
160
+ dev: raw.dev,
161
+ log: raw.log,
162
+ telemetry: raw.telemetry,
163
+ eslint: raw.eslint
164
+ };
165
+ }
166
+ // src/config/compose/merge-sync/merge-sync.ts
167
+ /**
168
+ * Merge two lists of `repo.secrets.sync` entries. An entry is the same sync when its environment and scope match;
169
+ * the keys then add up, and an entry that names no keys (every key the vault holds) stays that way.
170
+ */
171
+ function mergeSync(a, b) {
172
+ const merged = /* @__PURE__ */ new Map();
173
+ for (const entry of [...a ?? [], ...b ?? []]) {
174
+ const id = `${entry.environment}\0${entry.scope ?? "repo"}`;
175
+ const have = merged.get(id);
176
+ merged.set(id, have ? {
177
+ ...have,
178
+ ...have.keys && entry.keys ? { keys: [.../* @__PURE__ */ new Set([...have.keys, ...entry.keys])] } : { keys: void 0 }
179
+ } : { ...entry });
180
+ }
181
+ return [...merged.values()].map(({ keys, ...rest }) => keys ? {
182
+ ...rest,
183
+ keys
184
+ } : rest);
185
+ }
186
+ // src/config/compose/merge-repo/merge-repo.ts
187
+ const names = union();
188
+ const properties = shallowMerge();
189
+ const teamsByKey = mergeByKey((t) => typeof t === "string" ? t : t.slug);
190
+ /**
191
+ * Merge one capability's `repo` fragment onto what earlier ones gave. Scalars: last writer wins. `properties`: shallow
192
+ * merge. `variables`: merged per scope (`repo`, `org`). `secrets`: each name list is a union, and `sync` entries merge by
193
+ * environment and scope. `topics`: union. `teams`: merged by slug.
194
+ */
195
+ function mergeRepo(prev, next) {
196
+ const { properties: nextProperties, topics, teams, variables, secrets, ...scalars } = next;
197
+ const repo = {
198
+ ...prev,
199
+ ...scalars
200
+ };
201
+ if (nextProperties) repo.properties = properties.merge(repo.properties ?? {}, nextProperties);
202
+ if (variables) repo.variables = {
203
+ ...repo.variables,
204
+ ...variables,
205
+ ...repo.variables?.repo || variables.repo ? { repo: {
206
+ ...repo.variables?.repo,
207
+ ...variables.repo
208
+ } } : {},
209
+ ...repo.variables?.org || variables.org ? { org: {
210
+ ...repo.variables?.org,
211
+ ...variables.org
212
+ } } : {}
213
+ };
214
+ if (secrets) {
215
+ const environments = { ...repo.secrets?.environments };
216
+ for (const [env, list] of Object.entries(secrets.environments ?? {})) environments[env] = names.merge(environments[env] ?? [], list);
217
+ repo.secrets = {
218
+ ...repo.secrets?.repo || secrets.repo ? { repo: names.merge(repo.secrets?.repo ?? [], secrets.repo ?? []) } : {},
219
+ ...repo.secrets?.org || secrets.org ? { org: names.merge(repo.secrets?.org ?? [], secrets.org ?? []) } : {},
220
+ ...Object.keys(environments).length > 0 ? { environments } : {},
221
+ ...repo.secrets?.sync || secrets.sync ? { sync: mergeSync(repo.secrets?.sync, secrets.sync) } : {}
222
+ };
223
+ }
224
+ if (topics) repo.topics = names.merge(repo.topics ?? [], topics);
225
+ if (teams) repo.teams = teamsByKey.merge(repo.teams ?? [], teams);
226
+ return repo;
227
+ }
228
+ // src/config/compose/task-name/task-name.ts
229
+ /**
230
+ * The key a task entry merges under. A name that stands for exactly one flat id (the id itself, or an old dotted
231
+ * alias such as `verification.unitTests`) keys by that id, so the alias overrides the preset's entry instead of
232
+ * sitting next to it; a name that stands for several ids or none (a suite, an unknown name) keys by itself.
233
+ */
234
+ function taskName(e) {
235
+ const name = typeof e === "string" ? e : e.name;
236
+ const resolved = resolveTaskName(name);
237
+ return resolved.length === 1 ? resolved[0].id : name;
238
+ }
239
+ // src/config/compose/merge-strategies/merge-strategies.ts
240
+ /**
241
+ * How `compose()` merges each key of the capabilities: tasks by name (an old dotted alias overrides the entry it names),
242
+ * providers shallowly, the non-task required checks as a union, `repo` by its own rules, the rest last writer wins.
243
+ */
244
+ const mergeStrategies = {
245
+ tasks: mergeByKey(taskName),
246
+ providers: shallowMerge(),
247
+ extraRequiredChecks: union(),
248
+ repo: {
249
+ empty: {},
250
+ merge: mergeRepo
251
+ },
252
+ org: lastWins(),
253
+ domain: lastWins(),
254
+ docs: lastWins()
255
+ };
256
+ // src/config/load-config/read-package-json-name/read-package-json-name.ts
257
+ /** The `name` of the `package.json` in `dir` without its scope, or `undefined`. */
258
+ async function readPackageJsonName(dir) {
259
+ const name = (await readPackageJson(dir))?.name;
260
+ return name === void 0 ? void 0 : name.replace(/^@[^/]+\//, "");
261
+ }
262
+ // src/config/load-config/derive-defaults/derive-defaults.ts
263
+ /**
264
+ * Fill in what a `holocron.config` leaves out: `name` from the package or directory, `repo.name` from the GitHub
265
+ * remote, and the task manifest (merged from `astromech.config.*`).
266
+ */
267
+ async function deriveDefaults(found) {
268
+ const configDir = dirname(found.filepath);
269
+ const result = { ...found.config };
270
+ if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
271
+ if (result.repo && !result.repo.name) {
272
+ const remote = await readGitRemote(configDir);
273
+ if (remote?.host === "github.com") result.repo = {
274
+ ...result.repo,
275
+ name: remote.slug
276
+ };
277
+ }
278
+ const manifest = await loadTasksConfig(configDir, { holocron: found });
279
+ if (manifest.tasks) result.tasks = manifest.tasks;
280
+ if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
281
+ if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
282
+ if (manifest.hooks !== void 0) result.hooks = manifest.hooks;
283
+ if (manifest.extraRequiredChecks) result.extraRequiredChecks = [...result.extraRequiredChecks ?? [], ...manifest.extraRequiredChecks];
284
+ return result;
285
+ }
286
+ // src/config/system/system.ts
287
+ /** Holocron's config system, built from kyber's factory; `loadConfig`, `compose` and `defineConfig` wrap its parts. */
288
+ const system = createConfigSystem({
289
+ name: "holocron",
290
+ derive: deriveDefaults,
291
+ resolve: resolveConfig,
292
+ merge: mergeStrategies
293
+ });
294
+ // src/config/compose/compose.ts
295
+ /**
296
+ * Merge any number of capability fragments into a single preset object that
297
+ * spreads directly into `defineConfig()`.
298
+ *
299
+ * - Accepts individual capabilities or nested arrays (for bundle presets).
300
+ * - Deduplicates by `id` — when the same ID appears more than once, the last
301
+ * occurrence wins. This lets callers override bundle defaults by listing an
302
+ * explicit capability after the bundle.
303
+ * - Validates all `requires` at call time and throws `ConfigError` if any are
304
+ * unmet, listing every missing dependency in a single message.
305
+ *
306
+ * @example
307
+ * // docs-only site — no typecheck
308
+ * const preset = compose(node(), docs());
309
+ *
310
+ * // library with docs
311
+ * const preset = compose(node(), typecheck(), docs());
312
+ *
313
+ * // nextjs() is a bundle that returns Capability[]
314
+ * const preset = compose(node(), nextjs());
315
+ */
316
+ function compose(...args) {
317
+ return system.compose(...args);
318
+ }
319
+ export { resolveConfig as a, credentialsEnvironment as i, system as n, resolveEntry as o, ConfigError as r, resolvePluginPackage as s, compose as t };