@sous-io/sous 0.2.37 → 1.0.2

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.
Files changed (244) hide show
  1. package/README.md +14 -256
  2. package/dist/bin.js +11 -0
  3. package/dist/sous.js +1094 -0
  4. package/docs/markdown/README.md +5 -4
  5. package/docs/markdown/_sidebar.md +21 -1
  6. package/docs/markdown/commands.md +294 -431
  7. package/docs/markdown/config-discovery.md +25 -14
  8. package/docs/markdown/config-inspection.md +53 -31
  9. package/docs/markdown/config-layers.md +168 -66
  10. package/docs/markdown/config-variables.md +44 -11
  11. package/docs/markdown/configuration.md +104 -17
  12. package/docs/markdown/design-principles.md +4 -1
  13. package/docs/markdown/repositories-authoring.md +30 -0
  14. package/docs/markdown/repositories-consuming.md +72 -14
  15. package/docs/markdown/repositories-file-formats.md +31 -13
  16. package/docs/markdown/repositories-providers.md +48 -57
  17. package/docs/markdown/repositories-quickstart.md +3 -2
  18. package/docs/markdown/repositories-troubleshooting.md +27 -1
  19. package/docs/markdown/repositories-variables.md +6 -1
  20. package/docs/markdown/repositories.md +18 -8
  21. package/package.json +48 -107
  22. package/recipes/core/sous-skills/skills/about-liquid-templates/SKILL.tpl.md +4 -6
  23. package/recipes/core/sous-skills/skills/about-liquid-templates/references/liquid-filters.tpl.md +2 -0
  24. package/recipes/core/sous-skills/skills/about-sous/SKILL.tpl.md +10 -9
  25. package/recipes/core/sous-skills/skills/about-sous-configuration/SKILL.tpl.md +35 -14
  26. package/recipes/core/sous-skills/skills/about-sous-recipes/SKILL.tpl.md +51 -20
  27. package/recipes/core/sous-skills/sous.recipe.yaml +1 -1
  28. package/sous.config.schema.json +351 -132
  29. package/bin/run.js +0 -51
  30. package/src/base-command.ts +0 -457
  31. package/src/commands/build.ts +0 -181
  32. package/src/commands/clear.ts +0 -79
  33. package/src/commands/compile.ts +0 -155
  34. package/src/commands/config/get.ts +0 -110
  35. package/src/commands/config/show.ts +0 -32
  36. package/src/commands/config/validate.ts +0 -53
  37. package/src/commands/help.ts +0 -46
  38. package/src/commands/init.ts +0 -289
  39. package/src/commands/launch.ts +0 -139
  40. package/src/commands/lock/rebuild.ts +0 -239
  41. package/src/commands/lock/show.ts +0 -115
  42. package/src/commands/namespace/list.ts +0 -138
  43. package/src/commands/namespace/show.ts +0 -130
  44. package/src/commands/prune.ts +0 -43
  45. package/src/commands/recipe/list.ts +0 -112
  46. package/src/commands/recipe/show.ts +0 -439
  47. package/src/commands/repo/add.ts +0 -145
  48. package/src/commands/repo/contribute.ts +0 -604
  49. package/src/commands/repo/gc.ts +0 -173
  50. package/src/commands/repo/init.ts +0 -136
  51. package/src/commands/repo/link.ts +0 -899
  52. package/src/commands/repo/list.ts +0 -236
  53. package/src/commands/repo/release.ts +0 -685
  54. package/src/commands/repo/remove.ts +0 -194
  55. package/src/commands/repo/search.ts +0 -243
  56. package/src/commands/repo/submit.ts +0 -341
  57. package/src/commands/repo/unlink.ts +0 -461
  58. package/src/commands/subscription/add.ts +0 -286
  59. package/src/commands/subscription/list.ts +0 -208
  60. package/src/commands/subscription/remove.ts +0 -182
  61. package/src/commands/subscription/update.ts +0 -216
  62. package/src/commands/update.ts +0 -178
  63. package/src/commands/vars/ask.ts +0 -417
  64. package/src/commands/vars/index.ts +0 -79
  65. package/src/commands/vars/list.ts +0 -67
  66. package/src/commands/vars/show.ts +0 -77
  67. package/src/config-command.ts +0 -30
  68. package/src/lib/build-preparation.ts +0 -128
  69. package/src/lib/build-service.ts +0 -580
  70. package/src/lib/config-discovery.ts +0 -378
  71. package/src/lib/config-inspect.ts +0 -145
  72. package/src/lib/config-kernel.mjs +0 -379
  73. package/src/lib/config-schema.ts +0 -401
  74. package/src/lib/env-file.ts +0 -328
  75. package/src/lib/env-local.ts +0 -212
  76. package/src/lib/errors.ts +0 -32
  77. package/src/lib/glob-pattern.ts +0 -24
  78. package/src/lib/include-resolver.ts +0 -523
  79. package/src/lib/interactive.ts +0 -165
  80. package/src/lib/markdown-compiler.ts +0 -947
  81. package/src/lib/package-info.ts +0 -25
  82. package/src/lib/pid-service.ts +0 -99
  83. package/src/lib/project-install.d.mts +0 -44
  84. package/src/lib/project-install.mjs +0 -234
  85. package/src/lib/project-scaffold/index.ts +0 -332
  86. package/src/lib/project-scaffold/templates.ts +0 -240
  87. package/src/lib/repos/catalog-display.ts +0 -215
  88. package/src/lib/repos/catalog-inputs.ts +0 -288
  89. package/src/lib/repos/catalog.ts +0 -842
  90. package/src/lib/repos/contribute.ts +0 -452
  91. package/src/lib/repos/core-recipe.ts +0 -105
  92. package/src/lib/repos/declarations.ts +0 -187
  93. package/src/lib/repos/defaults.ts +0 -175
  94. package/src/lib/repos/formats/common.ts +0 -440
  95. package/src/lib/repos/formats/index-file.ts +0 -253
  96. package/src/lib/repos/formats/links-map.ts +0 -98
  97. package/src/lib/repos/formats/lockfile.ts +0 -169
  98. package/src/lib/repos/formats/patterns.ts +0 -57
  99. package/src/lib/repos/formats/recipe-manifest.ts +0 -205
  100. package/src/lib/repos/formats/repo-manifest.ts +0 -97
  101. package/src/lib/repos/formats/store-entry.ts +0 -84
  102. package/src/lib/repos/formats/variable-definition.ts +0 -268
  103. package/src/lib/repos/freshness.ts +0 -264
  104. package/src/lib/repos/git-clone.ts +0 -850
  105. package/src/lib/repos/identity.ts +0 -89
  106. package/src/lib/repos/index.ts +0 -57
  107. package/src/lib/repos/links.ts +0 -356
  108. package/src/lib/repos/load-manifest.ts +0 -237
  109. package/src/lib/repos/lock-service.ts +0 -454
  110. package/src/lib/repos/locked-namespace-resolver.ts +0 -232
  111. package/src/lib/repos/locked-recipe-lookup.ts +0 -123
  112. package/src/lib/repos/locked-recipes.ts +0 -254
  113. package/src/lib/repos/managed-layer.ts +0 -422
  114. package/src/lib/repos/memories-hash-name.ts +0 -33
  115. package/src/lib/repos/namespace-resolver.ts +0 -527
  116. package/src/lib/repos/providers/base.ts +0 -268
  117. package/src/lib/repos/providers/git.ts +0 -245
  118. package/src/lib/repos/providers/github.ts +0 -589
  119. package/src/lib/repos/providers/gitlab.ts +0 -332
  120. package/src/lib/repos/providers/http.ts +0 -128
  121. package/src/lib/repos/providers/index-cache.ts +0 -421
  122. package/src/lib/repos/providers/index.ts +0 -106
  123. package/src/lib/repos/providers/local.ts +0 -410
  124. package/src/lib/repos/providers/provider.ts +0 -615
  125. package/src/lib/repos/recipe-config-layers.ts +0 -316
  126. package/src/lib/repos/recipe-key-matcher.ts +0 -62
  127. package/src/lib/repos/recipe-memories.ts +0 -178
  128. package/src/lib/repos/recipe-targets.ts +0 -236
  129. package/src/lib/repos/ref-search.ts +0 -46
  130. package/src/lib/repos/release/bump.ts +0 -161
  131. package/src/lib/repos/release/changelog.ts +0 -461
  132. package/src/lib/repos/release/git-state.ts +0 -460
  133. package/src/lib/repos/release/index-builder.ts +0 -1108
  134. package/src/lib/repos/release/index.ts +0 -19
  135. package/src/lib/repos/release/plan.ts +0 -521
  136. package/src/lib/repos/release/settle.ts +0 -154
  137. package/src/lib/repos/release/submissions.ts +0 -214
  138. package/src/lib/repos/release/submit-checkout.ts +0 -290
  139. package/src/lib/repos/release/submit-questions.ts +0 -153
  140. package/src/lib/repos/release/submit-service.ts +0 -898
  141. package/src/lib/repos/release/tags.ts +0 -239
  142. package/src/lib/repos/release/validate.ts +0 -463
  143. package/src/lib/repos/resolver.ts +0 -1028
  144. package/src/lib/repos/scaffold/index.ts +0 -245
  145. package/src/lib/repos/scaffold/templates.ts +0 -517
  146. package/src/lib/repos/seed.ts +0 -473
  147. package/src/lib/repos/store/contract.ts +0 -64
  148. package/src/lib/repos/store/hash.ts +0 -191
  149. package/src/lib/repos/store/recipe-store.ts +0 -599
  150. package/src/lib/repos/store/settings.ts +0 -58
  151. package/src/lib/repos/subscription-service.ts +0 -3859
  152. package/src/lib/repos/trust.ts +0 -447
  153. package/src/lib/repos/update-plan.ts +0 -235
  154. package/src/lib/self-update/index.ts +0 -14
  155. package/src/lib/self-update/installs.ts +0 -413
  156. package/src/lib/self-update/managers.ts +0 -126
  157. package/src/lib/self-update/plan.ts +0 -315
  158. package/src/lib/self-update/registry.ts +0 -99
  159. package/src/lib/self-update/run.ts +0 -506
  160. package/src/lib/self-update/versions.ts +0 -243
  161. package/src/lib/settings.ts +0 -1107
  162. package/src/lib/sous-home.ts +0 -104
  163. package/src/lib/state.ts +0 -167
  164. package/src/lib/vars/answers.ts +0 -192
  165. package/src/lib/vars/ask.ts +0 -1152
  166. package/src/lib/vars/definition-source.ts +0 -261
  167. package/src/lib/vars/display.ts +0 -231
  168. package/src/lib/vars/index.ts +0 -20
  169. package/src/lib/vars/ladder.ts +0 -282
  170. package/src/lib/vars/mappings.ts +0 -260
  171. package/src/lib/vars/names.ts +0 -94
  172. package/src/lib/vars/preanswers.ts +0 -395
  173. package/src/lib/vars/question-plan.ts +0 -241
  174. package/src/lib/vars/report.ts +0 -228
  175. package/src/lib/vars/safe-regex.ts +0 -235
  176. package/src/lib/vars/secrets.ts +0 -131
  177. package/src/lib/vars/validate.ts +0 -312
  178. package/src/lib/version-report.ts +0 -90
  179. package/src/lib/watch-loop.ts +0 -148
  180. package/src/lib/watch-service.ts +0 -116
  181. package/src/services/ref-resolver/container.ts +0 -107
  182. package/src/services/ref-resolver/dependency.ts +0 -60
  183. package/src/services/ref-resolver/format.ts +0 -197
  184. package/src/services/ref-resolver/glob.ts +0 -115
  185. package/src/services/ref-resolver/hash-names.ts +0 -155
  186. package/src/services/ref-resolver/index.ts +0 -55
  187. package/src/services/ref-resolver/injectable.ts +0 -36
  188. package/src/services/ref-resolver/location.ts +0 -62
  189. package/src/services/ref-resolver/lookups/cached-index-lookup.ts +0 -53
  190. package/src/services/ref-resolver/lookups/catalog-lookup.ts +0 -23
  191. package/src/services/ref-resolver/lookups/catalog-matcher.ts +0 -261
  192. package/src/services/ref-resolver/lookups/chained-lookup.ts +0 -27
  193. package/src/services/ref-resolver/lookups/env-var-lookup.ts +0 -65
  194. package/src/services/ref-resolver/lookups/fetched-index-lookup.ts +0 -150
  195. package/src/services/ref-resolver/lookups/recorded-dependency-lookup.ts +0 -62
  196. package/src/services/ref-resolver/lookups/ref-lookup.ts +0 -54
  197. package/src/services/ref-resolver/lookups/variable-lookup.ts +0 -123
  198. package/src/services/ref-resolver/named-refs.ts +0 -144
  199. package/src/services/ref-resolver/parser/env-var-splitter.ts +0 -27
  200. package/src/services/ref-resolver/parser/location-splitter.ts +0 -239
  201. package/src/services/ref-resolver/parser/name-path-splitter.ts +0 -200
  202. package/src/services/ref-resolver/parser/partial-ref.ts +0 -84
  203. package/src/services/ref-resolver/parser/query-splitter.ts +0 -61
  204. package/src/services/ref-resolver/parser/range-splitter.ts +0 -52
  205. package/src/services/ref-resolver/parser/ref-parser.ts +0 -115
  206. package/src/services/ref-resolver/parser/repo-qualifier-splitter.ts +0 -51
  207. package/src/services/ref-resolver/parts.ts +0 -115
  208. package/src/services/ref-resolver/pruners/command-line-pruner.ts +0 -47
  209. package/src/services/ref-resolver/pruners/include-pruner.ts +0 -66
  210. package/src/services/ref-resolver/pruners/manifest-pruner.ts +0 -130
  211. package/src/services/ref-resolver/pruners/ref-pruner.ts +0 -135
  212. package/src/services/ref-resolver/pruners/rule-helpers.ts +0 -44
  213. package/src/services/ref-resolver/pruners/stored-key-pruner.ts +0 -136
  214. package/src/services/ref-resolver/ref-helpers.ts +0 -62
  215. package/src/services/ref-resolver/ref-picker-service.ts +0 -204
  216. package/src/services/ref-resolver/ref-report.ts +0 -84
  217. package/src/services/ref-resolver/ref-resolve-arguments.ts +0 -47
  218. package/src/services/ref-resolver/ref-resolve-result.ts +0 -36
  219. package/src/services/ref-resolver/ref-resolver-service.ts +0 -323
  220. package/src/services/ref-resolver/source.ts +0 -48
  221. package/src/services/ref-resolver/tokens.ts +0 -25
  222. package/src/services/ref-resolver/types.ts +0 -155
  223. package/src/templating/filters/bullet-list.ts +0 -9
  224. package/src/templating/filters/index.ts +0 -8
  225. package/src/templating/init-liquid-engine.ts +0 -139
  226. package/src/templating/lib/glob-files.ts +0 -74
  227. package/src/templating/lib/import-export.ts +0 -32
  228. package/src/templating/lib/secret-scope.ts +0 -41
  229. package/src/templating/lib/tag-args.ts +0 -19
  230. package/src/templating/tags/exportScalarVarsJs.ts +0 -46
  231. package/src/templating/tags/getFiles.ts +0 -89
  232. package/src/templating/tags/index.ts +0 -14
  233. package/src/templating/tags/listFiles.ts +0 -54
  234. package/src/templating/tags/showVars.ts +0 -28
  235. package/src/utils/choice-prompt.ts +0 -143
  236. package/src/utils/command-errors.ts +0 -186
  237. package/src/utils/command-help.ts +0 -45
  238. package/src/utils/confirm-prompt.ts +0 -110
  239. package/src/utils/flags.ts +0 -177
  240. package/src/utils/formatting.ts +0 -849
  241. package/src/utils/prompts.ts +0 -53
  242. package/src/utils/sous-directory.ts +0 -245
  243. package/src/utils/table.ts +0 -603
  244. package/src/utils/value-prompt.ts +0 -119
@@ -1,379 +0,0 @@
1
- /**
2
- * The sous "config kernel": a single loader subprocess that turns an ordered
3
- * list of config layer files into ONE merged, plain-JSON config.
4
- *
5
- * Spawned by loadSettings (src/lib/settings.ts). Plain JavaScript ESM, no
6
- * TypeScript syntax — it must run under bare Node AND under the tsx loader
7
- * (the tsx attempt exists so user configs may use TypeScript syntax). It ships
8
- * to npm via the package.json "files": "src" allowlist.
9
- *
10
- * Protocol
11
- * --------
12
- * stdin (one JSON document):
13
- * {
14
- * sources: (string | { path, config })[], // ordered layers, primary first.
15
- * // A string is an absolute layer path the
16
- * // kernel reads itself. An object is a layer
17
- * // the parent already read and filtered (a
18
- * // subscribed recipe's config layer); the
19
- * // kernel merges `config` as-is and never
20
- * // opens `path`.
21
- * context: { sousDir, confDir, sousRootPath, sousVersion, configPath },
22
- * trace: boolean
23
- * }
24
- *
25
- * stdout (one JSON document):
26
- * { config, layers }
27
- * `layers` is [] unless trace; when tracing it holds one { path, config }
28
- * snapshot of the CUMULATIVE config after each top-level source. Builder
29
- * sub-loads (loadConfig/loadConfigs) fold into the enclosing layer's snapshot.
30
- *
31
- * Any layer failure (parse error, import error, configure() throw, cycle,
32
- * old multi-project schema) writes a message NAMING THE LAYER FILE to stderr
33
- * and exits 1; the parent wraps stderr in a ConfigError.
34
- *
35
- * Layer contract
36
- * --------------
37
- * - .json → JSON.parse of the file text.
38
- * - .jsonc → JSON with comments: line comments, block comments and trailing
39
- * commas are allowed. The layers sous manages are written this way.
40
- * - .yaml → parsed with the 'yaml' package.
41
- * - .js/.mjs → dynamic import. The module may export:
42
- * * an object: `config`, else `default` when it is a non-function object;
43
- * * a function: `configure`, else `default` when it is a function;
44
- * * both: the object merges FIRST, then the function runs.
45
- * The function is awaited: `await fn(currentConfig, builder)`. It may mutate
46
- * `currentConfig` by reference freely; a returned object (if any) is merged
47
- * after it resolves — UNLESS it is `currentConfig` itself (mutate-and-return
48
- * for chaining), which is skipped so self-merge does not duplicate arrays.
49
- *
50
- * Every layer object is forced through a JSON round-trip BEFORE merging, so
51
- * functions, RegExp, Date and undefined values drop at the layer boundary.
52
- * The final cumulative config is JSON round-tripped again on the way out.
53
- *
54
- * Merge semantics (deepMerge): plain object + plain object → recurse;
55
- * array + array → concatenate (target then source); anything else → the
56
- * source value replaces. No dedupe.
57
- */
58
-
59
- import fs from "node:fs";
60
- import path from "node:path";
61
- import { pathToFileURL } from "node:url";
62
- import { parse as parseYaml } from "yaml";
63
- import { globSync } from "glob";
64
- import { parse as parseJsonc, printParseErrorCode } from "jsonc-parser";
65
-
66
- // --- small utilities -----------------------------------------------------------------------------
67
-
68
- /** True for a plain object (not null, not an array). */
69
- function isPlainObject(value) {
70
- return value !== null && typeof value === "object" && !Array.isArray(value);
71
- }
72
-
73
- /**
74
- * Parses a `.jsonc` layer: JSON plus line comments, block comments and trailing
75
- * commas. The error names the layer file and the line the parser stopped on.
76
- */
77
- function parseJsoncLayer(text, filePath) {
78
- const errors = [];
79
- const value = parseJsonc(text, errors, { allowTrailingComma: true, disallowComments: false });
80
-
81
- if (errors.length > 0) {
82
- const first = errors[0];
83
- const before = text.slice(0, first.offset);
84
- const line = before.split("\n").length;
85
- const column = first.offset - before.lastIndexOf("\n");
86
- throw new Error(
87
- `Config layer ${filePath} is not valid JSON with comments: ` +
88
- `${printParseErrorCode(first.error)} at line ${line}, column ${column}.\n` +
89
- ` Comments and trailing commas are allowed; anything else must be valid JSON.`
90
- );
91
- }
92
-
93
- return value;
94
- }
95
-
96
- /** Forces a value through a JSON round-trip. */
97
- function jsonRoundTrip(value) {
98
- return JSON.parse(JSON.stringify(value));
99
- }
100
-
101
- /**
102
- * Bytewise string comparison (plain `<` on the string), locale-independent so
103
- * layer order is identical on every machine. NOT numeric: '10-' sorts before '2-'.
104
- */
105
- function bytewiseCompare(a, b) {
106
- return a < b ? -1 : a > b ? 1 : 0;
107
- }
108
-
109
- /**
110
- * Deep-merges `source` INTO `target` (the live cumulative config).
111
- * plain object + plain object → recurse; array + array → concatenate
112
- * (target then source, no dedupe); anything else → source replaces.
113
- */
114
- function deepMerge(target, source) {
115
- for (const [key, sourceValue] of Object.entries(source)) {
116
- // Guard against prototype pollution: a JSON layer can carry an OWN
117
- // enumerable "__proto__" (or "constructor"/"prototype") key through the
118
- // round-trip; merging it would mutate Object.prototype and corrupt every
119
- // later object (including tripping the old-schema guard on innocent layers).
120
- if (key === "__proto__" || key === "constructor" || key === "prototype") {
121
- continue;
122
- }
123
- const targetValue = target[key];
124
- if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {
125
- deepMerge(targetValue, sourceValue);
126
- } else if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
127
- target[key] = [...targetValue, ...sourceValue];
128
- } else {
129
- target[key] = sourceValue;
130
- }
131
- }
132
- return target;
133
- }
134
-
135
- // --- kernel --------------------------------------------------------------------------------------
136
-
137
- async function readStdin() {
138
- const chunks = [];
139
- for await (const chunk of process.stdin) chunks.push(chunk);
140
- return Buffer.concat(chunks).toString("utf8");
141
- }
142
-
143
- async function main() {
144
- const { sources, context, trace } = JSON.parse(await readStdin());
145
-
146
- /** The live cumulative config every layer merges into. */
147
- const currentConfig = {};
148
-
149
- /** Trace-mode snapshots: one per TOP-LEVEL source, taken after it finishes. */
150
- const layers = [];
151
-
152
- /** Absolute paths currently mid-load, for cycle detection. */
153
- const loadingSet = new Set();
154
-
155
- /** The layer file whose code is currently executing (for builder.currentFile). */
156
- let currentFile = null;
157
-
158
- /**
159
- * The only variables usable in builder loadConfig/loadConfigs paths. Builder
160
- * paths resolve BEFORE variable resolution, so user _vars do not exist yet.
161
- */
162
- const autoVars = {
163
- sousDir: context.sousDir,
164
- sousConfDir: context.confDir,
165
- sousRootPath: context.sousRootPath,
166
- sousVersion: context.sousVersion,
167
- };
168
-
169
- /** Substitutes ${autoVar} references in a builder path; any other var is fatal. */
170
- function substituteAutoVars(rawPath, where) {
171
- return rawPath.replace(/\$\{([^}]+)\}/g, (_match, name) => {
172
- if (name in autoVars) return autoVars[name];
173
- throw new Error(
174
- `${where}: \${${name}} cannot be used in a builder path.\n` +
175
- ` Builder paths (loadConfig/loadConfigs) resolve BEFORE variable resolution, so user\n` +
176
- ` _vars are not available yet. Only these auto-vars are allowed:\n` +
177
- ` ${Object.keys(autoVars)
178
- .map((n) => "${" + n + "}")
179
- .join(", ")}`
180
- );
181
- });
182
- }
183
-
184
- /** Resolves a builder path: auto-vars, then relative-to-the-current-layer-file. */
185
- function resolveBuilderPath(rawPath, where) {
186
- const substituted = substituteAutoVars(String(rawPath), where);
187
- if (path.isAbsolute(substituted)) return path.normalize(substituted);
188
- return path.resolve(path.dirname(currentFile), substituted);
189
- }
190
-
191
- /**
192
- * Guards against the removed multi-project schema, per layer, so the error
193
- * names the exact file that still uses it.
194
- */
195
- function assertNotOldSchema(layerObject, filePath) {
196
- if (isPlainObject(layerObject) && ("projects" in layerObject || "defaultProject" in layerObject)) {
197
- throw new Error(
198
- `Config layer ${filePath} uses the removed multi-project schema ` +
199
- `('projects' / 'defaultProject').\n` +
200
- ` A sous config now describes exactly one project. To migrate:\n` +
201
- ` 1. Move your single project's fields (name, _vars, _aliases, compilation,\n` +
202
- ` runtimeContext, tools) to the top level of the config.\n` +
203
- ` 2. Delete the 'projects' and 'defaultProject' keys.\n` +
204
- ` A config with several projects must be split into one config per project.`
205
- );
206
- }
207
- }
208
-
209
- /**
210
- * JSON-forces a layer's object and deep-merges it into the live config.
211
- * Runs the old-schema guard on the layer's OWN object, pre-merge.
212
- */
213
- function mergeLayerObject(layerObject, filePath) {
214
- if (!isPlainObject(layerObject)) {
215
- throw new Error(
216
- `Config layer ${filePath} did not produce a plain object (got ${
217
- Array.isArray(layerObject) ? "an array" : typeof layerObject
218
- }).`
219
- );
220
- }
221
- assertNotOldSchema(layerObject, filePath);
222
- deepMerge(currentConfig, jsonRoundTrip(layerObject));
223
- }
224
-
225
- /**
226
- * The builder singleton passed to every configure(currentConfig, builder).
227
- * One instance per kernel run; `currentFile` tracks whichever layer is executing.
228
- */
229
- const builder = {
230
- get config() {
231
- return currentConfig;
232
- },
233
- sousDir: context.sousDir,
234
- confDir: context.confDir,
235
- get currentFile() {
236
- return currentFile;
237
- },
238
- env(name, fallback) {
239
- return process.env[name] ?? fallback;
240
- },
241
- merge(obj) {
242
- mergeLayerObject(obj, currentFile ?? "<builder.merge>");
243
- },
244
- async loadConfig(p) {
245
- await loadLayer(resolveBuilderPath(p, `loadConfig(${JSON.stringify(p)}) in ${currentFile}`));
246
- },
247
- async loadConfigs(globPattern) {
248
- const where = `loadConfigs(${JSON.stringify(globPattern)}) in ${currentFile}`;
249
- const pattern = resolveBuilderPath(globPattern, where);
250
- // glob reads `\` as an escape, so a Windows path is handed over with `/`
251
- // separators (see src/lib/glob-pattern.ts; this file stays plain JS).
252
- const matches = globSync(pattern.split(path.sep).join("/"), { absolute: true })
253
- .filter((p) => fs.statSync(p).isFile())
254
- .sort(bytewiseCompare);
255
- for (const match of matches) {
256
- await loadLayer(match);
257
- }
258
- },
259
- };
260
-
261
- /**
262
- * Loads ONE layer file (any extension) and merges it into the cumulative
263
- * config. Builder sub-loads recurse here too, under the full layer contract
264
- * (including nested configure), guarded by the loading-set cycle check.
265
- */
266
- async function loadLayer(filePath) {
267
- const resolved = path.resolve(filePath);
268
-
269
- if (loadingSet.has(resolved)) {
270
- throw new Error(
271
- `Config layer cycle detected: ${resolved} is already being loaded.\n` +
272
- ` Load chain: ${[...loadingSet].join(" -> ")} -> ${resolved}`
273
- );
274
- }
275
- if (!fs.existsSync(resolved)) {
276
- throw new Error(`Config layer not found: ${resolved}`);
277
- }
278
-
279
- loadingSet.add(resolved);
280
- const previousFile = currentFile;
281
- currentFile = resolved;
282
-
283
- try {
284
- const ext = path.extname(resolved).toLowerCase();
285
-
286
- if (ext === ".json") {
287
- mergeLayerObject(JSON.parse(fs.readFileSync(resolved, "utf8")), resolved);
288
- } else if (ext === ".jsonc") {
289
- mergeLayerObject(parseJsoncLayer(fs.readFileSync(resolved, "utf8"), resolved), resolved);
290
- } else if (ext === ".yaml") {
291
- mergeLayerObject(parseYaml(fs.readFileSync(resolved, "utf8")), resolved);
292
- } else if (ext === ".js" || ext === ".mjs") {
293
- const mod = await import(pathToFileURL(resolved).href);
294
-
295
- let configObject;
296
- if (mod.config !== undefined) {
297
- configObject = mod.config;
298
- } else if (mod.default !== undefined && typeof mod.default !== "function") {
299
- configObject = mod.default;
300
- }
301
-
302
- let configureFn;
303
- if (typeof mod.configure === "function") {
304
- configureFn = mod.configure;
305
- } else if (typeof mod.default === "function") {
306
- configureFn = mod.default;
307
- }
308
-
309
- if (configObject === undefined && configureFn === undefined) {
310
- throw new Error(
311
- `Config layer ${resolved} exports neither a config object ` +
312
- `(\`config\` or a default object) nor a configure function ` +
313
- `(\`configure\` or a default function).`
314
- );
315
- }
316
-
317
- // When both exist, the object merges FIRST, then the function runs.
318
- if (configObject !== undefined) {
319
- mergeLayerObject(configObject, resolved);
320
- }
321
- if (configureFn !== undefined) {
322
- const returned = await configureFn(currentConfig, builder);
323
- // A configure() may mutate currentConfig by reference AND return it for
324
- // chaining (`cfg.x = ...; return cfg;`, or `return builder.config`).
325
- // Merging currentConfig back onto itself would deepMerge it with itself,
326
- // concatenating (and so duplicating) every array. Only merge a returned
327
- // value when it is a DISTINCT object.
328
- if (returned !== undefined && returned !== null && returned !== currentConfig) {
329
- mergeLayerObject(returned, resolved);
330
- }
331
- }
332
- } else {
333
- throw new Error(
334
- `Config layer ${resolved} has an unsupported extension '${ext}'. ` +
335
- `Supported: .js, .mjs, .json, .jsonc, .yaml`
336
- );
337
- }
338
- } catch (error) {
339
- // Make sure every failure names a layer file.
340
- const message = error instanceof Error ? error.message : String(error);
341
- if (message.includes(resolved)) throw error;
342
- throw new Error(`Config layer ${resolved} failed to load: ${message}`);
343
- } finally {
344
- loadingSet.delete(resolved);
345
- currentFile = previousFile;
346
- }
347
- }
348
-
349
- for (const source of sources) {
350
- // An inline source is a layer the PARENT already read and already filtered
351
- // (a subscribed recipe's config layer; see repos/recipe-config-layers.ts).
352
- // The kernel merges the content it was handed and never opens the file, so
353
- // the filtering cannot be sidestepped by re-reading it here.
354
- if (isPlainObject(source)) {
355
- const previousFile = currentFile;
356
- currentFile = source.path;
357
- try {
358
- mergeLayerObject(source.config, source.path);
359
- } finally {
360
- currentFile = previousFile;
361
- }
362
- } else {
363
- await loadLayer(source);
364
- }
365
- if (trace) {
366
- layers.push({
367
- path: isPlainObject(source) ? source.path : source,
368
- config: jsonRoundTrip(currentConfig),
369
- });
370
- }
371
- }
372
-
373
- process.stdout.write(JSON.stringify({ config: jsonRoundTrip(currentConfig), layers }));
374
- }
375
-
376
- main().catch((error) => {
377
- process.stderr.write(error instanceof Error ? error.message : String(error));
378
- process.exit(1);
379
- });