@theholocron/datapad 5.0.0-alpha.43 → 5.0.0-alpha.430

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 (4) hide show
  1. package/README.md +108 -17
  2. package/dist/index.d.mts +253 -55
  3. package/dist/index.mjs +332 -124
  4. package/package.json +22 -19
package/README.md CHANGED
@@ -43,13 +43,23 @@ export const defineConfig = createDefineConfig<TasksConfig>();
43
43
 
44
44
  ## API
45
45
 
46
- ### `loadConfigFile<T>({ cwd, name, extensions? })`
47
-
48
- Loads the first `<name>.config.<ext>` found in `cwd`. Probe order is
49
- **TS-first** — `.ts` → `.js` → `.mjs` → `.cjs` → `.json` — overridable via
50
- `extensions`. Returns `{ config, filepath } | null`. `null` means "no such
51
- file"; a file that exists but cannot be parsed / loaded / has no default
52
- export throws `ConfigFileError`.
46
+ ### `loadConfigFile<T>({ cwd, name, extensions?, walkUp? })`
47
+
48
+ Loads the first `<name>.config.<ext>` found starting at `cwd`. Probe order
49
+ is **TS-first** — `.ts` → `.js` → `.mjs` → `.cjs` → `.json` — overridable
50
+ via `extensions`. Returns `{ config, filepath } | null`. `null` means "no
51
+ such file anywhere searched"; a file that exists but cannot be parsed /
52
+ loaded / has no default export throws `ConfigFileError`.
53
+
54
+ `walkUp: true` (off by default) adds the "nearest config" search
55
+ `cosmiconfig`/`postcss`/`stylelint`/ESLint's flat config all do: when `cwd`
56
+ has no match, check its parent, then its parent's parent, and so on —
57
+ stopping at the first directory containing a `.git` entry (that directory
58
+ is still searched before stopping) or the filesystem root. Never wanders
59
+ past a repo boundary into an unrelated enclosing directory. `loadLayered`
60
+ passes its own `walkUp` through to both the dedicated-file and
61
+ fallback-file lookups. Built on `@theholocron/fs-utils`'s generic
62
+ `findUpward`/`hasGitEntry` — not reimplemented here.
53
63
 
54
64
  ### `loadConfigFromContent<T>({ dir, content, name, extension })`
55
65
 
@@ -59,7 +69,8 @@ the exact same internals `loadConfigFile` uses for a file it discovered
59
69
  itself. `dir` matters: it's what upward `node_modules` resolution sees, so
60
70
  content that does `import { defineConfig } from "@theholocron/cli"` only
61
71
  resolves if `dir` sits under a tree where that package is a real
62
- dependency. Callers own creating and cleaning up `dir`. Returns
72
+ dependency — [`withConfigSandbox`](#withconfigsandbox-nodemodules-root-prefix--run) prepares
73
+ one. Callers own creating and cleaning up `dir`. Returns
63
74
  `{ config, filepath }`; throws `ConfigFileError` the same way
64
75
  `loadConfigFile` does on a parse/load failure.
65
76
 
@@ -67,7 +78,71 @@ Built for `@theholocron/sentinel`'s `validateConfig()` — it fetches a
67
78
  repo's `holocron.config.*` from GitHub's API, not a local checkout, but
68
79
  still needs the fetched content to execute as a real module.
69
80
 
70
- ### `loadLayered<T>({ cwd, name, fallback?, extensions? })`
81
+ ### `readConfigSource({ name, fetch, extensions? })`
82
+
83
+ `loadConfigFile`'s extension probe for a config that lives somewhere other
84
+ than the local disk. Asks `fetch(path)` for `<name>.config.<ext>` in
85
+ extension-priority order (`fetch` returns the content, or `undefined` when
86
+ the file isn't there, and throws for any other failure) and returns the first
87
+ hit as `{ path, extension, content }`, or `undefined`. Hand the result to
88
+ `loadConfigFromContent`.
89
+
90
+ ### `loadConfigPath<T>(filepath)`
91
+
92
+ Loads the one file at `filepath`, whatever its name (`linear-trial.json`), for a file the caller names rather than one
93
+ found by convention: `.json` is parsed, `.ts` goes through `tsx`, `.js`, `.mjs` and `.cjs` are imported, and the default
94
+ export is the value. Throws `ConfigFileError` for a missing file, an extension that is not one of those, or a file that
95
+ cannot be loaded.
96
+
97
+ ### `loadConfigDir<T>({ cwd, dir, areas, extensions? })`
98
+
99
+ Loads the area files of a config directory (`.holocron/notifications.ts`,
100
+ `.holocron/repo.json`, ...) the way `loadConfigFile` loads a config. For each
101
+ name in the closed list `areas`, the first of `<cwd>/<dir>/<area>.{ts,js,mjs,cjs,json}`
102
+ that exists is loaded (`.ts` wins over `.json` when both are there). Returns
103
+ `{ area, path, extension, filepath, value }[]`, one entry per area that has a
104
+ file; a missing directory returns `[]`. A file that cannot be loaded throws
105
+ `ConfigFileError`. Files not named in `areas` are never read. The directory name
106
+ and the area names are parameters: datapad does not know what an area means, and
107
+ an area file may `import` a sibling in the directory.
108
+
109
+ ### `readConfigDirSource({ dir, areas, fetch, extensions? })`
110
+
111
+ `loadConfigDir`'s probe for a directory that lives somewhere other than the local
112
+ disk. Asks `fetch("<dir>/<area>.<ext>")` in extension-priority order for each
113
+ area and returns `{ area, path, extension, content }[]` for the areas found.
114
+ It reads only the named areas; a caller that lists the whole directory and
115
+ fetches every file passes that tree to `writeConfigDir` instead.
116
+
117
+ ### `writeConfigDir({ dir, files })`
118
+
119
+ The sandbox writer: writes a tree of fetched files (`{ path, content }`, `path`
120
+ relative to `dir`, e.g. `.holocron/notifications.ts` or `.holocron/lib/x.ts`)
121
+ into the sandbox beside the config, creating sub-directories and keeping the
122
+ relative paths, so `loadConfigDir({ cwd: dir, ... })` finds them and an area that
123
+ imports a sibling resolves it. Returns the absolute paths written. A path that is
124
+ absolute or leaves `dir` throws `ConfigFileError` before anything is written.
125
+
126
+ ```ts
127
+ await withConfigSandbox({ nodeModules }, async (dir) => {
128
+ const { extension, content } = (await readConfigSource({ name: "holocron", fetch }))!;
129
+ await loadConfigFromContent({ dir, name: "holocron", extension, content });
130
+ await writeConfigDir({ dir, files: [{ path: ".holocron/notifications.ts", content: "export default {}" }] });
131
+ const areas = await loadConfigDir({ cwd: dir, dir: ".holocron", areas: ["notifications", "repo"] });
132
+ });
133
+ ```
134
+
135
+ ### `withConfigSandbox({ nodeModules, root?, prefix? }, run)`
136
+
137
+ Runs `run(dir)` with a throwaway directory ready to be
138
+ `loadConfigFromContent`'s `dir`: `node_modules` symlinked to
139
+ `options.nodeModules` (so the config's package imports resolve) and a
140
+ `{"type":"module"}` `package.json` (so `tsx` doesn't default the files to
141
+ CommonJS and `require()` a pure-ESM dependency). Created under the OS temp dir
142
+ by default — read-only deployments can't write inside a package — and removed
143
+ afterwards, also when `run` throws.
144
+
145
+ ### `loadLayered<T>({ cwd, name, fallback?, extensions?, walkUp?, coerce? })`
71
146
 
72
147
  `<name>.config.*` layered over the `[fallback.key]` of
73
148
  `<fallback.file>.config.*`. Either, both, or neither may be present; the
@@ -75,11 +150,27 @@ dedicated file wins on conflict (`vitest`-over-`vite`). Returns
75
150
  `{ config, filepath, sources } | null` — `sources` lists the absolute
76
151
  paths actually merged, lowest priority first.
77
152
 
153
+ - `fallback.preloaded` — the `<fallback.file>.config.*` the caller has
154
+ already loaded (`null`: looked for, not there), used as is instead of loading
155
+ it again.
156
+ - `coerce(raw)` — turns each layer's raw value into the shape being merged
157
+ before the merge (a bare array standing for `{ tasks: [...] }`, say);
158
+ returning `undefined` treats the layer as absent.
159
+
160
+ ### `mergeLayers<T>(layers)`
161
+
162
+ The merge `loadLayered` uses, for layers loaded some other way: deep-merges
163
+ `layers` lowest priority first, skipping `undefined`, and returns a copy — or
164
+ `undefined` when there is nothing to merge.
165
+
78
166
  ### `mergeConfig<T>(base, override)`
79
167
 
80
168
  Deep-merge, `vite`-style: plain objects merge recursively, arrays
81
169
  concatenate (`base` first), `undefined` in `override` is skipped, every
82
- other `override` value replaces `base`. Neither input is mutated.
170
+ other `override` value replaces `base`. Neither input is mutated. A
171
+ re-export of `@theholocron/object-utils`'s `deepMerge` under this
172
+ package's established name — the merge logic itself has no awareness of
173
+ configs at all, so it lives there instead of being duplicated here.
83
174
 
84
175
  ### `createDefineConfig<T>()`
85
176
 
@@ -100,12 +191,12 @@ reads a dedicated file _and_ a parent file), so the persistent
100
191
 
101
192
  ## Development
102
193
 
103
- | Script | Description |
104
- | --------------------------------------- | ------------------------------------------- |
105
- | `pnpm run delivery.build` | Bundle with tsdown |
106
- | `pnpm run verification.unitTests` | Run the vitest suite (always with coverage) |
107
- | `pnpm run verification.typeSafety` | `tsc --noEmit` |
108
- | `pnpm run sourceQuality.staticAnalysis` | ESLint |
194
+ | Script | Description |
195
+ | -------------------- | ------------------------------------------- |
196
+ | `pnpm run build` | Bundle with tsdown |
197
+ | `pnpm run test:unit` | Run the vitest suite (always with coverage) |
198
+ | `pnpm run typecheck` | `tsc --noEmit` |
199
+ | `pnpm run lint:code` | ESLint |
109
200
 
110
201
  ## Releases
111
202
 
@@ -113,4 +204,4 @@ Automated via semantic-release. See [CHANGELOG.md](../../CHANGELOG.md).
113
204
 
114
205
  ## Documentation
115
206
 
116
- <https://theholocron.github.io/holocron/>
207
+ <https://docs.theholocron.dev/holocron/>
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
- //#region src/define.d.ts
1
+ import { deepMerge as mergeConfig } from "@theholocron/object-utils";
2
+ /** Default extension probe order, highest priority first. */
3
+ export declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
2
4
  /**
3
5
  * Build a typed identity `defineConfig` for a specific config shape.
4
6
  *
@@ -11,68 +13,171 @@
11
13
  * export const defineConfig = createDefineConfig<TasksConfig>();
12
14
  * ```
13
15
  */
14
- declare function createDefineConfig<T>(): <C extends T>(config: C) => C;
15
- //#endregion
16
- //#region src/errors.d.ts
16
+ export declare function createDefineConfig<T>(): <C extends T>(config: C) => C;
17
17
  /**
18
18
  * Thrown when a config file is found but cannot be loaded — malformed
19
19
  * JSON, a syntax error in a `.ts` / `.js` module, or no usable default
20
20
  * export. "Not found" is never an error: {@link loadConfigFile} returns
21
21
  * `null` for that.
22
22
  */
23
- declare class ConfigFileError extends Error {
23
+ export declare class ConfigFileError extends Error {
24
24
  /** Absolute path of the offending file, when known. */
25
25
  readonly filepath?: string | undefined;
26
+ /** The error's name, `"ConfigFileError"`. */
26
27
  name: string;
27
28
  constructor(message: string,
28
29
  /** Absolute path of the offending file, when known. */
29
30
  filepath?: string | undefined);
30
31
  }
31
- //#endregion
32
- //#region src/load.d.ts
32
+ /** One area file loaded from a config directory. */
33
+ interface ConfigDirArea<T = unknown> {
34
+ /** The area's name, as passed in `areas`. */
35
+ area: string;
36
+ /** The file path relative to `cwd`, with `/` separators: `.holocron/notifications.ts`. */
37
+ path: string;
38
+ /** Which extension matched. */
39
+ extension: string;
40
+ /** Absolute path of the file. */
41
+ filepath: string;
42
+ /** The file's default export (`.ts`, `.js`, `.mjs`, `.cjs`) or its parsed content (`.json`). */
43
+ value: T;
44
+ /**
45
+ * The same area read from the repository root's directory, when this one is the config's own and the root has a
46
+ * file for it too. Only areas named in `shared` are looked up there. Absent when the root has no such file.
47
+ */
48
+ root?: ConfigDirArea<T>;
49
+ }
50
+ /** Options for loading the area files of a config directory from disk. */
51
+ interface LoadConfigDirOptions {
52
+ /** The directory holding `dir` — normally the one the config file was found in. */
53
+ cwd: string;
54
+ /** The directory the areas live in, relative to `cwd`: `".holocron"`. */
55
+ dir: string;
56
+ /** The closed list of area names to look for. Files not named here are never read. */
57
+ areas: readonly string[];
58
+ /**
59
+ * Area names that are also read from the repository root's `dir` (the nearest ancestor of `cwd` with a `.git`
60
+ * entry, `cwd` itself first). A shared area with a file in both places comes back as the one in `cwd` with the
61
+ * root's as `root`; one that only the root has comes back as the root's file, its `path` relative to `cwd`. The
62
+ * caller decides how the two combine. When `cwd` is the root there is nothing to inherit.
63
+ */
64
+ shared?: readonly string[];
65
+ /** Override the extension probe order. */
66
+ extensions?: readonly string[];
67
+ }
33
68
  /**
34
- * Discover and load `<name>.config.*` files, or load one from content that
35
- * didn't come from a file at all ({@link loadConfigFromContent}).
36
- * Holocron-agnostic — no schema, no validation, no defaults. Consumers
37
- * layer those on top.
69
+ * Load the area files of a config directory: for each name in `options.areas`, the first of
70
+ * `<cwd>/<dir>/<area>.{ts,js,mjs,cjs,json}` that exists, loaded the way {@link loadConfigFile} loads a config. Areas
71
+ * with no file are left out, so a missing directory returns `[]`. When one area has files in two formats, the
72
+ * extension priority picks one (`.ts` over `.json`). Throws {@link ConfigFileError} when a file exists but cannot be
73
+ * loaded. Holocron-agnostic: the directory and the area names are parameters, and what an area means is the caller's.
38
74
  *
39
- * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
40
- * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
41
- * typed `defineConfig` file works with no build step.
75
+ * Areas named in `options.shared` are also looked up in the repository root's directory (see
76
+ * {@link LoadConfigDirOptions.shared}), so a config in a subdirectory can inherit what the repo declares once.
42
77
  */
43
- /** Default extension probe order, highest priority first. */
44
- declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
78
+ export declare function loadConfigDir<T = unknown>(options: LoadConfigDirOptions): Promise<ConfigDirArea<T>[]>;
79
+ /** Options for finding and loading a config file from disk. */
45
80
  interface LoadConfigFileOptions {
46
- /** Directory to look in. */
81
+ /** Directory to start looking in. */
47
82
  cwd: string;
48
83
  /** Base name — `"holocron"` resolves `holocron.config.{ts,js,mjs,cjs,json}`. */
49
84
  name: string;
50
85
  /** Override the extension probe order. */
51
86
  extensions?: readonly string[];
87
+ /**
88
+ * Walk upward through ancestor directories when `cwd` itself has no
89
+ * match, stopping at the first directory containing a `.git` entry (that
90
+ * directory is still searched before stopping) or the filesystem root.
91
+ * Off by default — exact-`cwd`-only, unchanged behavior for any existing
92
+ * caller that doesn't pass this.
93
+ */
94
+ walkUp?: boolean;
52
95
  }
96
+ /** A config value together with the file it was loaded from. */
53
97
  interface Loaded<T> {
98
+ /** The loaded config value. */
54
99
  config: T;
55
100
  /** Absolute path of the file the value came from. */
56
101
  filepath: string;
57
102
  }
58
103
  /**
59
- * Load the first `<name>.config.<ext>` that exists in `cwd`. Returns
60
- * `null` when none is present; throws {@link ConfigFileError} when a file
61
- * exists but cannot be loaded.
104
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
105
+ * `cwd` itself by default, or walking up through ancestor directories when
106
+ * `walkUp` is set (see the module doc comment for the stop conditions).
107
+ * Returns `null` when none is present anywhere searched; throws
108
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
62
109
  */
63
- declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
64
- interface LoadLayeredOptions extends LoadConfigFileOptions {
110
+ export declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
111
+ /** Options for loading a config from raw content rather than a file already on disk. */
112
+ interface LoadConfigFromContentOptions {
113
+ /**
114
+ * Directory to write `<name>.config.<extension>` into before loading —
115
+ * this is what upward `node_modules` resolution sees, so a config that
116
+ * does `import { defineConfig } from "@theholocron/cli"` only resolves
117
+ * if `dir` sits under a tree where that package is a real dependency.
118
+ * Callers own creating and cleaning up `dir` — this function only
119
+ * writes the one file into it.
120
+ */
121
+ dir: string;
122
+ /** Raw file content — not necessarily sourced from a local file at all (a network fetch, a git blob, …). */
123
+ content: string;
124
+ /** Base name — `"holocron"` writes `holocron.config.<extension>`. */
125
+ name: string;
126
+ /** Which of `DEFAULT_EXTENSIONS` `content` is — determines how it's interpreted (ts/js/mjs/cjs parsed as a module, json as `JSON.parse`). */
127
+ extension: string;
128
+ }
129
+ /**
130
+ * Load config from content that didn't come from a file already on disk —
131
+ * writes it to `<dir>/<name>.config.<extension>` first, then loads it
132
+ * through the exact same path {@link loadConfigFile} uses for a file it
133
+ * discovered itself. Exists because sourcing config content from somewhere
134
+ * other than the local filesystem (a GitHub API fetch, for one — see
135
+ * `@theholocron/sentinel`) doesn't change what loading it correctly means:
136
+ * a `.ts` config still needs real module resolution, `defineConfig` import
137
+ * included, not a re-implemented parser.
138
+ */
139
+ export declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
140
+ /**
141
+ * Load the one file at `filepath`, whatever its name: `.json` is parsed, `.ts` goes through `tsx`, and `.js`, `.mjs`
142
+ * and `.cjs` are imported; the default export is the value. For a file the caller names (a flag's argument) rather
143
+ * than one found by convention.
144
+ *
145
+ * Throws {@link ConfigFileError} when the file is missing, has an extension that is not one of
146
+ * {@link DEFAULT_EXTENSIONS}, or cannot be loaded.
147
+ *
148
+ * @param filepath - Absolute path of the file.
149
+ */
150
+ export declare function loadConfigPath<T = unknown>(filepath: string): Promise<T>;
151
+ /** Options for loading a dedicated config file layered over a fallback file's key. */
152
+ interface LoadLayeredOptions<T = unknown> extends LoadConfigFileOptions {
65
153
  /**
66
154
  * When no dedicated `<name>.config.*` exists — or in addition to it —
67
155
  * read `<file>.config.*` and take its `[key]`. The dedicated file (if
68
156
  * any) is merged on top.
69
157
  */
70
158
  fallback?: {
159
+ /** Base name of the fallback file, read as `<file>.config.*`. */
71
160
  file: string;
161
+ /** The key in the fallback file whose value is taken. */
72
162
  key: string;
163
+ /**
164
+ * The `<file>.config.*` already loaded by the caller (`null`: it was
165
+ * looked for and isn't there). Used as is instead of loading it again;
166
+ * leave it `undefined` to have `loadLayered` find and load it.
167
+ */
168
+ preloaded?: Loaded<object> | null;
73
169
  };
170
+ /**
171
+ * Turns each layer's raw value — the dedicated file's default export, and
172
+ * the fallback's `[key]` — into the shape being merged, before the merge.
173
+ * Return `undefined` to treat the layer as absent. For configs that accept
174
+ * shorthand (a bare array standing for `{ tasks: [...] }`).
175
+ */
176
+ coerce?: (raw: unknown) => T | undefined;
74
177
  }
178
+ /** The merged config from `loadLayered`, with where it came from. */
75
179
  interface LayeredResult<T> {
180
+ /** The merged config value. */
76
181
  config: T;
77
182
  /** The dedicated file path if present, else the fallback file path, else `null`. */
78
183
  filepath: string | null;
@@ -85,47 +190,140 @@ interface LayeredResult<T> {
85
190
  * the dedicated file wins on conflict (vitest-over-vite). Returns `null`
86
191
  * when neither source resolves.
87
192
  */
88
- declare function loadLayered<T>(opts: LoadLayeredOptions): Promise<LayeredResult<T> | null>;
89
- interface LoadConfigFromContentOptions {
193
+ export declare function loadLayered<T>(opts: LoadLayeredOptions<T>): Promise<LayeredResult<T> | null>;
194
+ /**
195
+ * Deep-merges config layers, lowest priority first (a later layer wins on
196
+ * scalars; arrays concatenate; nested objects merge). `undefined` layers are
197
+ * skipped. Returns `undefined` when there is no layer to merge. The result is
198
+ * a copy for object layers — it never aliases a layer.
199
+ *
200
+ * The one merge `loadLayered` and every caller layering configs it loaded
201
+ * some other way (content from an API, say) use, so layering means the same
202
+ * thing everywhere.
203
+ */
204
+ export declare function mergeLayers<T>(layers: readonly (T | undefined)[]): T | undefined;
205
+ /** One area file's content fetched from somewhere other than the local disk. */
206
+ interface ConfigDirSource {
207
+ /** The area's name, as passed in `areas` — `"notifications"` for `.holocron/notifications.ts`. */
208
+ area: string;
209
+ /** The file path probed, relative as `fetch` was asked for it, e.g. `.holocron/notifications.ts`. */
210
+ path: string;
211
+ /** Which extension matched. */
212
+ extension: string;
213
+ /** The raw file content. */
214
+ content: string;
215
+ }
216
+ /** Options for fetching the area files of a config directory from a remote source. */
217
+ interface ReadConfigDirSourceOptions {
218
+ /** The directory the areas live in, relative to the config: `".holocron"`. */
219
+ dir: string;
220
+ /** The closed list of area names to look for: `["notifications", "repo"]` probes `<dir>/notifications.*` and `<dir>/repo.*`. */
221
+ areas: readonly string[];
90
222
  /**
91
- * Directory to write `<name>.config.<extension>` into before loading —
92
- * this is what upward `node_modules` resolution sees, so a config that
93
- * does `import { defineConfig } from "@theholocron/cli"` only resolves
94
- * if `dir` sits under a tree where that package is a real dependency.
95
- * Callers own creating and cleaning up `dir` — this function only
96
- * writes the one file into it.
223
+ * Fetches one file by relative path (`.holocron/notifications.ts`): its content, or `undefined` when it doesn't
224
+ * exist. Throw for anything else (a network failure, a permission error) — that propagates rather than reading
225
+ * as "absent".
97
226
  */
98
- dir: string;
99
- /** Raw file content — not necessarily sourced from a local file at all (a network fetch, a git blob, …). */
227
+ fetch: (path: string) => Promise<string | undefined>;
228
+ /** Override the extension probe order. */
229
+ extensions?: readonly string[];
230
+ }
231
+ /**
232
+ * {@link readConfigSource} for the area files of a config directory (`.holocron/<area>.<ext>`) that live somewhere
233
+ * other than the local disk: for each name in `options.areas`, probes the extensions in priority order through
234
+ * `options.fetch` and keeps the first file that exists. Areas with no file are left out, so a repo with no
235
+ * directory returns `[]`. Write the result with {@link writeConfigDir} and read it back with {@link loadConfigDir}.
236
+ *
237
+ * This reads only the named areas. A caller that lists the whole directory (and so also gets the files an area
238
+ * imports) passes that tree to {@link writeConfigDir} directly.
239
+ */
240
+ export declare function readConfigDirSource(options: ReadConfigDirSourceOptions): Promise<ConfigDirSource[]>;
241
+ /** A config file's content fetched from somewhere other than the local disk. */
242
+ interface ConfigSource {
243
+ /** The file name probed, e.g. `holocron.config.ts` — relative, as `fetch` was asked for it. */
244
+ path: string;
245
+ /** Which extension matched — what {@link loadConfigFromContent} needs as `extension`. */
246
+ extension: string;
247
+ /** The raw file content. */
100
248
  content: string;
101
- /** Base name — `"holocron"` writes `holocron.config.<extension>`. */
249
+ }
250
+ /** Options for fetching a config file's content from a remote source. */
251
+ interface ReadConfigSourceOptions {
252
+ /** Base name — `"holocron"` probes `holocron.config.{ts,js,mjs,cjs,json}`. */
102
253
  name: string;
103
- /** Which of `DEFAULT_EXTENSIONS` `content` is — determines how it's interpreted (ts/js/mjs/cjs parsed as a module, json as `JSON.parse`). */
104
- extension: string;
254
+ /**
255
+ * Fetches one file by relative path (`holocron.config.ts`): its content, or
256
+ * `undefined` when it doesn't exist. Throw for anything else (a network
257
+ * failure, a permission error) — that propagates rather than reading as "absent".
258
+ */
259
+ fetch: (path: string) => Promise<string | undefined>;
260
+ /** Override the extension probe order. */
261
+ extensions?: readonly string[];
105
262
  }
106
263
  /**
107
- * Load config from content that didn't come from a file already on disk —
108
- * writes it to `<dir>/<name>.config.<extension>` first, then loads it
109
- * through the exact same path {@link loadConfigFile} uses for a file it
110
- * discovered itself. Exists because sourcing config content from somewhere
111
- * other than the local filesystem (a GitHub API fetch, for one — see
112
- * `@theholocron/sentinel`) doesn't change what loading it correctly means:
113
- * a `.ts` config still needs real module resolution, `defineConfig` import
114
- * included, not a re-implemented parser.
264
+ * {@link probeExtensions} for a config that lives somewhere other than the
265
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
266
+ * extension-priority order through `options.fetch`, returning the first file
267
+ * that exists, or `undefined` when none does. Pass the result to
268
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
115
269
  */
116
- declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
117
- //#endregion
118
- //#region src/merge.d.ts
270
+ export declare function readConfigSource(options: ReadConfigSourceOptions): Promise<ConfigSource | undefined>;
271
+ /** Options for the temporary directory a config is loaded in. */
272
+ interface ConfigSandboxOptions {
273
+ /**
274
+ * A real `node_modules` directory to make visible from the sandbox. A config
275
+ * that does `import { defineConfig } from "@theholocron/cli"` only resolves
276
+ * if the directory it sits in has that package reachable by Node's upward
277
+ * `node_modules` search, so the sandbox gets a symlink to this one (not a
278
+ * copy — nothing is duplicated).
279
+ */
280
+ nodeModules: string;
281
+ /** Where to create the sandbox. Defaults to the OS temp dir. */
282
+ root?: string;
283
+ /** Prefix for the sandbox directory's name. */
284
+ prefix?: string;
285
+ }
119
286
  /**
120
- * Deep-merge two config objects, `vite`-style:
287
+ * Runs `run` with a throwaway directory prepared for
288
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
289
+ * `run` throws).
290
+ *
291
+ * The directory is made for a TS/JS config that imports packages:
121
292
  *
122
- * - plain objects merge recursively
123
- * - arrays concatenate (`base` first, then `override`)
124
- * - an `undefined` value in `override` is skipped (keeps `base`)
125
- * - every other `override` value replaces `base`
293
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
294
+ * resolve as if the config sat next to that directory.
295
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
296
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
297
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
298
+ * correctly honouring that, would then `require()` a pure-ESM dependency
299
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
300
+ * ("require() of ES Module … not supported").
126
301
  *
127
- * Neither input is mutated.
302
+ * The directory lives under the OS temp dir by default rather than inside any
303
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
304
+ * read-only under `/var/task`) can't create a directory there.
305
+ */
306
+ export declare function withConfigSandbox<R>(options: ConfigSandboxOptions, run: (dir: string) => Promise<R>): Promise<R>;
307
+ /** One file of a config directory's tree, as fetched from a remote source. */
308
+ interface ConfigDirFile {
309
+ /** Path relative to the sandbox directory, e.g. `.holocron/notifications.ts` or `.holocron/lib/channels.ts`. */
310
+ path: string;
311
+ /** The raw file content. */
312
+ content: string;
313
+ }
314
+ /** Options for writing a fetched config directory beside a config. */
315
+ interface WriteConfigDirOptions {
316
+ /** The sandbox directory (the `dir` given to {@link loadConfigFromContent}); `files` are written under it. */
317
+ dir: string;
318
+ /** The files to write; their relative paths (and so the sub-directories) are kept. */
319
+ files: readonly ConfigDirFile[];
320
+ }
321
+ /**
322
+ * Write the files fetched from a config directory (`.holocron/…`) into the sandbox beside the config, keeping each
323
+ * relative path, so {@link loadConfigDir} finds them and an area file that imports a sibling resolves it. Creates the
324
+ * sub-directories as needed and returns the absolute paths written. Throws {@link ConfigFileError} for a path that is
325
+ * absolute or leaves `dir`, because the paths come from a remote tree and must never write outside the sandbox; it
326
+ * checks every path before it writes any.
128
327
  */
129
- declare function mergeConfig<T>(base: T, override: unknown): T;
130
- //#endregion
131
- export { ConfigFileError, DEFAULT_EXTENSIONS, type LayeredResult, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
328
+ export declare function writeConfigDir(options: WriteConfigDirOptions): Promise<string[]>;
329
+ export { type ConfigDirArea, type ConfigDirFile, type ConfigDirSource, type ConfigSandboxOptions, type ConfigSource, type LayeredResult, type LoadConfigDirOptions, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, type ReadConfigDirSourceOptions, type ReadConfigSourceOptions, type WriteConfigDirOptions, mergeConfig };
package/dist/index.mjs CHANGED
@@ -1,7 +1,20 @@
1
- import { readFile, stat, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
1
+ import { findRoot, findUpward, hasGitEntry } from "@theholocron/fs-utils";
2
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
3
4
  import { pathToFileURL } from "node:url";
4
- //#region src/define.ts
5
+ import { errorMessage } from "@theholocron/misc-utils";
6
+ import { deepMerge, deepMerge as mergeConfig } from "@theholocron/object-utils";
7
+ import { tmpdir } from "node:os";
8
+ // src/default-extensions/default-extensions.ts
9
+ /** Default extension probe order, highest priority first. */
10
+ const DEFAULT_EXTENSIONS = [
11
+ "ts",
12
+ "js",
13
+ "mjs",
14
+ "cjs",
15
+ "json"
16
+ ];
17
+ // src/define/define.ts
5
18
  /**
6
19
  * Build a typed identity `defineConfig` for a specific config shape.
7
20
  *
@@ -17,8 +30,7 @@ import { pathToFileURL } from "node:url";
17
30
  function createDefineConfig() {
18
31
  return (config) => config;
19
32
  }
20
- //#endregion
21
- //#region src/errors.ts
33
+ // src/errors/errors.ts
22
34
  /**
23
35
  * Thrown when a config file is found but cannot be loaded — malformed
24
36
  * JSON, a syntax error in a `.ts` / `.js` module, or no usable default
@@ -27,43 +39,150 @@ function createDefineConfig() {
27
39
  */
28
40
  var ConfigFileError = class extends Error {
29
41
  filepath;
42
+ /** The error's name, `"ConfigFileError"`. */
30
43
  name = "ConfigFileError";
31
44
  constructor(message, filepath) {
32
45
  super(message);
33
46
  this.filepath = filepath;
34
47
  }
35
48
  };
36
- //#endregion
37
- //#region src/merge.ts
49
+ // src/is-file/is-file.ts
50
+ async function isFile(path) {
51
+ try {
52
+ return (await stat(path)).isFile();
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+ // src/load-file/load-file.ts
58
+ /**
59
+ * The actual file-loading mechanics `load.ts`'s exported functions share:
60
+ * JSON parsing, dynamic `import()` (TS via `tsx`'s persistent ESM loader,
61
+ * JS/MJS/CJS natively), and unwrapping the CJS/ESM default-export
62
+ * double-wrap `tsx`'s transform produces. Kept separate from `load.ts`'s
63
+ * own orchestration (which directory, which extension order, upward
64
+ * search) — this file only knows "given one exact filepath and
65
+ * extension, load it," always throwing {@link ConfigFileError} on failure.
66
+ */
67
+ async function loadFile(filepath, ext) {
68
+ if (ext === "json") return loadJson(filepath);
69
+ return extractDefault(filepath, await importModule(filepath, ext));
70
+ }
71
+ async function loadJson(filepath) {
72
+ const text = await readFile(filepath, "utf8");
73
+ try {
74
+ return JSON.parse(text);
75
+ } catch (err) {
76
+ throw new ConfigFileError(`${filepath} is not valid JSON: ${errorMessage(err)}`, filepath);
77
+ }
78
+ }
79
+ let tsRegistered;
80
+ async function registerTsx() {
81
+ const { register } = await import("tsx/esm/api");
82
+ register();
83
+ }
84
+ /**
85
+ * Import `filepath`. For `.ts`, `tsx`'s ESM loader is registered first, once
86
+ * per process (lazily — only when a `.ts` file is actually loaded).
87
+ * `register()` is used over `tsImport()` because a single run may load
88
+ * several TS files (`loadLayered` reads a dedicated file *and* a parent
89
+ * file) and `tsImport`'s one-off register/unregister cycle is not reentrant.
90
+ */
91
+ async function importModule(filepath, ext) {
92
+ if (ext === "ts") {
93
+ tsRegistered ??= registerTsx();
94
+ await tsRegistered;
95
+ }
96
+ try {
97
+ return await import(pathToFileURL(filepath).href);
98
+ } catch (err) {
99
+ throw new ConfigFileError(`could not load ${filepath}: ${errorMessage(err)}`, filepath);
100
+ }
101
+ }
38
102
  /**
39
- * Deep-merge two config objects, `vite`-style:
103
+ * Unwrap `export default`. `tsx` CJS-transforms `export default x` into
104
+ * `exports.default = x`, which dynamic import wraps as
105
+ * `{ default: { __esModule: true, default: x } }` — strip the extra layer
106
+ * when present so ESM and CJS outputs both resolve.
107
+ */
108
+ function extractDefault(filepath, mod) {
109
+ const outer = mod.default;
110
+ const raw = outer?.__esModule === true ? outer.default : outer;
111
+ if (raw === void 0 || raw === null) throw new ConfigFileError(`${filepath} must have a default export (use \`export default defineConfig({…})\`)`, filepath);
112
+ return raw;
113
+ }
114
+ // src/load-config-dir-area/load-config-dir-area.ts
115
+ /**
116
+ * Load one area of a config directory: the first of `<root>/<dir>/<area>.{ts,js,mjs,cjs,json}` that exists, or
117
+ * `undefined` when there is none. `path` on the result is relative to `base` (the directory the caller treats as
118
+ * its own), with `/` separators, so an area read from an ancestor directory comes back as `../../.holocron/org.ts`.
119
+ * Throws {@link ConfigFileError} when the file exists but cannot be loaded.
40
120
  *
41
- * - plain objects merge recursively
42
- * - arrays concatenate (`base` first, then `override`)
43
- * - an `undefined` value in `override` is skipped (keeps `base`)
44
- * - every other `override` value replaces `base`
121
+ * @param root - The directory holding `dir`.
122
+ * @param base - The directory `path` is relative to; the same as `root` for the caller's own directory.
123
+ * @param dir - The directory the area lives in, relative to `root`: `".holocron"`.
124
+ * @param area - The area's name.
125
+ * @param extensions - The extension probe order. Default {@link DEFAULT_EXTENSIONS}.
126
+ */
127
+ async function loadConfigDirArea(root, base, dir, area, extensions = DEFAULT_EXTENSIONS) {
128
+ for (const extension of extensions) {
129
+ const filepath = join(root, dir, `${area}.${extension}`);
130
+ if (!await isFile(filepath)) continue;
131
+ return {
132
+ area,
133
+ path: relative(base, filepath).split(sep).join("/"),
134
+ extension,
135
+ filepath,
136
+ value: await loadFile(filepath, extension)
137
+ };
138
+ }
139
+ }
140
+ // src/load-config-dir/load-config-dir.ts
141
+ /**
142
+ * Load the area files of a config directory: for each name in `options.areas`, the first of
143
+ * `<cwd>/<dir>/<area>.{ts,js,mjs,cjs,json}` that exists, loaded the way {@link loadConfigFile} loads a config. Areas
144
+ * with no file are left out, so a missing directory returns `[]`. When one area has files in two formats, the
145
+ * extension priority picks one (`.ts` over `.json`). Throws {@link ConfigFileError} when a file exists but cannot be
146
+ * loaded. Holocron-agnostic: the directory and the area names are parameters, and what an area means is the caller's.
45
147
  *
46
- * Neither input is mutated.
47
- */
48
- function mergeConfig(base, override) {
49
- if (!isPlainObject(base) || !isPlainObject(override)) return override === void 0 ? base : override;
50
- const out = { ...base };
51
- for (const [key, value] of Object.entries(override)) {
52
- if (value === void 0) continue;
53
- const prev = out[key];
54
- if (Array.isArray(prev) && Array.isArray(value)) out[key] = [...prev, ...value];
55
- else if (isPlainObject(prev) && isPlainObject(value)) out[key] = mergeConfig(prev, value);
56
- else out[key] = value;
148
+ * Areas named in `options.shared` are also looked up in the repository root's directory (see
149
+ * {@link LoadConfigDirOptions.shared}), so a config in a subdirectory can inherit what the repo declares once.
150
+ */
151
+ async function loadConfigDir(options) {
152
+ const shared = options.shared ?? [];
153
+ const root = shared.length > 0 ? await findRoot(options.cwd, ".git") : void 0;
154
+ const inheritFrom = root !== void 0 && root !== options.cwd ? root : void 0;
155
+ const areas = [];
156
+ for (const area of options.areas) {
157
+ const own = await loadConfigDirArea(options.cwd, options.cwd, options.dir, area, options.extensions);
158
+ const inherited = inheritFrom !== void 0 && shared.includes(area) ? await loadConfigDirArea(inheritFrom, options.cwd, options.dir, area, options.extensions) : void 0;
159
+ const found = own && inherited ? {
160
+ ...own,
161
+ root: inherited
162
+ } : own ?? inherited;
163
+ if (found) areas.push(found);
57
164
  }
58
- return out;
165
+ return areas;
59
166
  }
60
- function isPlainObject(value) {
61
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
62
- const proto = Object.getPrototypeOf(value);
63
- return proto === Object.prototype || proto === null;
167
+ // src/probe-extensions/probe-extensions.ts
168
+ /**
169
+ * Probe `dir` for `<name>.config.<ext>` in extension-priority order,
170
+ * loading and returning the first match. The one piece of per-directory
171
+ * orchestration `loadConfigFile` needs on both its non-walking and
172
+ * walking paths — pulled out so it can be unit-tested directly instead of
173
+ * only through `loadConfigFile`'s full probe/walk behavior.
174
+ */
175
+ async function probeExtensions(dir, name, extensions) {
176
+ for (const ext of extensions) {
177
+ const filepath = join(dir, `${name}.config.${ext}`);
178
+ if (!await isFile(filepath)) continue;
179
+ return {
180
+ config: await loadFile(filepath, ext),
181
+ filepath
182
+ };
183
+ }
64
184
  }
65
- //#endregion
66
- //#region src/load.ts
185
+ // src/load-config-file/load-config-file.ts
67
186
  /**
68
187
  * Discover and load `<name>.config.*` files, or load one from content that
69
188
  * didn't come from a file at all ({@link loadConfigFromContent}).
@@ -73,32 +192,85 @@ function isPlainObject(value) {
73
192
  * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
74
193
  * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
75
194
  * typed `defineConfig` file works with no build step.
195
+ *
196
+ * `walkUp` (off by default) adds the "nearest config" search
197
+ * cosmiconfig/postcss/stylelint/ESLint's flat config all do: when `cwd`
198
+ * itself has no match, check its parent, then its parent's parent, and so
199
+ * on — stopping at the first directory containing a `.git` entry (checked
200
+ * after that directory's own config probe, so the project root itself is
201
+ * still searched) or the filesystem root. Never wanders past a repo
202
+ * boundary into an unrelated enclosing directory. Built on
203
+ * `@theholocron/fs-utils`'s `findUpward`/`hasGitEntry` — the same
204
+ * upward-walk shape `@theholocron/sentinel`'s own `findPackageRoot` needs,
205
+ * only with a different predicate.
76
206
  */
77
- /** Default extension probe order, highest priority first. */
78
- const DEFAULT_EXTENSIONS = [
79
- "ts",
80
- "js",
81
- "mjs",
82
- "cjs",
83
- "json"
84
- ];
85
207
  /**
86
- * Load the first `<name>.config.<ext>` that exists in `cwd`. Returns
87
- * `null` when none is present; throws {@link ConfigFileError} when a file
88
- * exists but cannot be loaded.
208
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
209
+ * `cwd` itself by default, or walking up through ancestor directories when
210
+ * `walkUp` is set (see the module doc comment for the stop conditions).
211
+ * Returns `null` when none is present anywhere searched; throws
212
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
89
213
  */
90
214
  async function loadConfigFile(opts) {
91
215
  const extensions = opts.extensions ?? DEFAULT_EXTENSIONS;
92
- for (const ext of extensions) {
93
- const filepath = join(opts.cwd, `${opts.name}.config.${ext}`);
94
- if (!await isFile(filepath)) continue;
95
- return {
96
- config: await loadFile(filepath, ext),
97
- filepath
98
- };
99
- }
100
- return null;
216
+ const checkDir = (dir) => probeExtensions(dir, opts.name, extensions);
217
+ if (!opts.walkUp) return await checkDir(opts.cwd) ?? null;
218
+ return await findUpward(opts.cwd, checkDir, hasGitEntry) ?? null;
101
219
  }
220
+ // src/load-config-from-content/load-config-from-content.ts
221
+ /**
222
+ * Load config from content that didn't come from a file already on disk —
223
+ * writes it to `<dir>/<name>.config.<extension>` first, then loads it
224
+ * through the exact same path {@link loadConfigFile} uses for a file it
225
+ * discovered itself. Exists because sourcing config content from somewhere
226
+ * other than the local filesystem (a GitHub API fetch, for one — see
227
+ * `@theholocron/sentinel`) doesn't change what loading it correctly means:
228
+ * a `.ts` config still needs real module resolution, `defineConfig` import
229
+ * included, not a re-implemented parser.
230
+ */
231
+ async function loadConfigFromContent(opts) {
232
+ const filepath = join(opts.dir, `${opts.name}.config.${opts.extension}`);
233
+ await writeFile(filepath, opts.content, "utf8");
234
+ return {
235
+ config: await loadFile(filepath, opts.extension),
236
+ filepath
237
+ };
238
+ }
239
+ // src/load-config-path/load-config-path.ts
240
+ const SUPPORTED = DEFAULT_EXTENSIONS;
241
+ /**
242
+ * Load the one file at `filepath`, whatever its name: `.json` is parsed, `.ts` goes through `tsx`, and `.js`, `.mjs`
243
+ * and `.cjs` are imported; the default export is the value. For a file the caller names (a flag's argument) rather
244
+ * than one found by convention.
245
+ *
246
+ * Throws {@link ConfigFileError} when the file is missing, has an extension that is not one of
247
+ * {@link DEFAULT_EXTENSIONS}, or cannot be loaded.
248
+ *
249
+ * @param filepath - Absolute path of the file.
250
+ */
251
+ async function loadConfigPath(filepath) {
252
+ if (!await isFile(filepath)) throw new ConfigFileError(`${filepath} is not a file`, filepath);
253
+ const extension = extname(filepath).slice(1);
254
+ if (!SUPPORTED.includes(extension)) throw new ConfigFileError(`${filepath} must be a .${SUPPORTED.join(", .")} file`, filepath);
255
+ return loadFile(filepath, extension);
256
+ }
257
+ // src/merge-layers/merge-layers.ts
258
+ /**
259
+ * Deep-merges config layers, lowest priority first (a later layer wins on
260
+ * scalars; arrays concatenate; nested objects merge). `undefined` layers are
261
+ * skipped. Returns `undefined` when there is no layer to merge. The result is
262
+ * a copy for object layers — it never aliases a layer.
263
+ *
264
+ * The one merge `loadLayered` and every caller layering configs it loaded
265
+ * some other way (content from an API, say) use, so layering means the same
266
+ * thing everywhere.
267
+ */
268
+ function mergeLayers(layers) {
269
+ const present = layers.filter((layer) => layer !== void 0);
270
+ if (present.length === 0) return void 0;
271
+ return present.reduce((acc, layer) => deepMerge(acc, layer), {});
272
+ }
273
+ // src/load-layered/load-layered.ts
102
274
  /**
103
275
  * `<name>.config.*` layered over the `[fallback.key]` of
104
276
  * `<fallback.file>.config.*`. Either, both, or neither may be present;
@@ -106,106 +278,142 @@ async function loadConfigFile(opts) {
106
278
  * when neither source resolves.
107
279
  */
108
280
  async function loadLayered(opts) {
281
+ const coerce = opts.coerce ?? ((raw) => raw);
109
282
  const dedicated = await loadConfigFile(opts);
283
+ let top;
284
+ let topFile = null;
285
+ if (dedicated) {
286
+ top = coerce(dedicated.config);
287
+ if (top !== void 0) topFile = dedicated.filepath;
288
+ }
110
289
  let base;
111
290
  let baseFile = null;
112
291
  if (opts.fallback) {
113
- const parent = await loadConfigFile({
292
+ const parent = opts.fallback.preloaded !== void 0 ? opts.fallback.preloaded : await loadConfigFile({
114
293
  cwd: opts.cwd,
115
294
  name: opts.fallback.file,
116
- extensions: opts.extensions
295
+ extensions: opts.extensions,
296
+ walkUp: opts.walkUp
117
297
  });
118
- if (parent && parent.config[opts.fallback.key] !== void 0) {
119
- base = parent.config[opts.fallback.key];
120
- baseFile = parent.filepath;
298
+ const raw = (parent?.config)?.[opts.fallback.key];
299
+ if (parent && raw !== void 0) {
300
+ base = coerce(raw);
301
+ if (base !== void 0) baseFile = parent.filepath;
121
302
  }
122
303
  }
123
- if (!dedicated && base === void 0) return null;
124
- const config = mergeConfig(base, dedicated?.config);
125
- const sources = [baseFile, dedicated?.filepath ?? null].filter((s) => s !== null);
304
+ const config = mergeLayers([base, top]);
305
+ if (config === void 0) return null;
306
+ const sources = [baseFile, topFile].filter((s) => s !== null);
126
307
  return {
127
308
  config,
128
- filepath: dedicated?.filepath ?? baseFile,
309
+ filepath: topFile ?? baseFile,
129
310
  sources
130
311
  };
131
312
  }
313
+ // src/read-config-dir-source/read-config-dir-source.ts
132
314
  /**
133
- * Load config from content that didn't come from a file already on disk —
134
- * writes it to `<dir>/<name>.config.<extension>` first, then loads it
135
- * through the exact same path {@link loadConfigFile} uses for a file it
136
- * discovered itself. Exists because sourcing config content from somewhere
137
- * other than the local filesystem (a GitHub API fetch, for one — see
138
- * `@theholocron/sentinel`) doesn't change what loading it correctly means:
139
- * a `.ts` config still needs real module resolution, `defineConfig` import
140
- * included, not a re-implemented parser.
315
+ * {@link readConfigSource} for the area files of a config directory (`.holocron/<area>.<ext>`) that live somewhere
316
+ * other than the local disk: for each name in `options.areas`, probes the extensions in priority order through
317
+ * `options.fetch` and keeps the first file that exists. Areas with no file are left out, so a repo with no
318
+ * directory returns `[]`. Write the result with {@link writeConfigDir} and read it back with {@link loadConfigDir}.
319
+ *
320
+ * This reads only the named areas. A caller that lists the whole directory (and so also gets the files an area
321
+ * imports) passes that tree to {@link writeConfigDir} directly.
141
322
  */
142
- async function loadConfigFromContent(opts) {
143
- const filepath = join(opts.dir, `${opts.name}.config.${opts.extension}`);
144
- await writeFile(filepath, opts.content, "utf8");
145
- return {
146
- config: await loadFile(filepath, opts.extension),
147
- filepath
148
- };
149
- }
150
- async function loadFile(filepath, ext) {
151
- if (ext === "json") return loadJson(filepath);
152
- return extractDefault(filepath, ext === "ts" ? await importTs(filepath) : await importModule(filepath));
153
- }
154
- async function loadJson(filepath) {
155
- const text = await readFile(filepath, "utf8");
156
- try {
157
- return JSON.parse(text);
158
- } catch (err) {
159
- throw new ConfigFileError(`${filepath} is not valid JSON: ${message(err)}`, filepath);
323
+ async function readConfigDirSource(options) {
324
+ const sources = [];
325
+ for (const area of options.areas) for (const extension of options.extensions ?? DEFAULT_EXTENSIONS) {
326
+ const path = `${options.dir}/${area}.${extension}`;
327
+ const content = await options.fetch(path);
328
+ if (content === void 0) continue;
329
+ sources.push({
330
+ area,
331
+ path,
332
+ extension,
333
+ content
334
+ });
335
+ break;
160
336
  }
337
+ return sources;
161
338
  }
162
- async function importModule(filepath) {
163
- try {
164
- return await import(pathToFileURL(filepath).href);
165
- } catch (err) {
166
- throw new ConfigFileError(`could not load ${filepath}: ${message(err)}`, filepath);
339
+ // src/read-config-source/read-config-source.ts
340
+ /**
341
+ * {@link probeExtensions} for a config that lives somewhere other than the
342
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
343
+ * extension-priority order through `options.fetch`, returning the first file
344
+ * that exists, or `undefined` when none does. Pass the result to
345
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
346
+ */
347
+ async function readConfigSource(options) {
348
+ for (const extension of options.extensions ?? DEFAULT_EXTENSIONS) {
349
+ const path = `${options.name}.config.${extension}`;
350
+ const content = await options.fetch(path);
351
+ if (content !== void 0) return {
352
+ path,
353
+ extension,
354
+ content
355
+ };
167
356
  }
168
357
  }
169
- let tsRegistered;
170
- async function registerTsx() {
171
- const { register } = await import("tsx/esm/api");
172
- register();
173
- }
358
+ // src/with-config-sandbox/with-config-sandbox.ts
174
359
  /**
175
- * Load a `.ts` config. `tsx`'s ESM loader is registered once per process
176
- * (lazily — only when a `.ts` config is actually loaded). `register()` is
177
- * used over `tsImport()` because a single run may load several TS configs
178
- * (`loadLayered` reads a dedicated file *and* a parent file) and
179
- * `tsImport`'s one-off register/unregister cycle is not reentrant.
360
+ * Runs `run` with a throwaway directory prepared for
361
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
362
+ * `run` throws).
363
+ *
364
+ * The directory is made for a TS/JS config that imports packages:
365
+ *
366
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
367
+ * resolve as if the config sat next to that directory.
368
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
369
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
370
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
371
+ * correctly honouring that, would then `require()` a pure-ESM dependency
372
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
373
+ * ("require() of ES Module … not supported").
374
+ *
375
+ * The directory lives under the OS temp dir by default rather than inside any
376
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
377
+ * read-only under `/var/task`) can't create a directory there.
180
378
  */
181
- async function importTs(filepath) {
182
- tsRegistered ??= registerTsx();
183
- await tsRegistered;
379
+ async function withConfigSandbox(options, run) {
380
+ const root = options.root ?? tmpdir();
381
+ await mkdir(root, { recursive: true });
382
+ const dir = await mkdtemp(join(root, options.prefix ?? "datapad-"));
184
383
  try {
185
- return await import(pathToFileURL(filepath).href);
186
- } catch (err) {
187
- throw new ConfigFileError(`could not load ${filepath}: ${message(err)}`, filepath);
384
+ await symlink(options.nodeModules, join(dir, "node_modules"), "dir");
385
+ await writeFile(join(dir, "package.json"), JSON.stringify({ type: "module" }), "utf8");
386
+ return await run(dir);
387
+ } finally {
388
+ await rm(dir, {
389
+ recursive: true,
390
+ force: true
391
+ });
188
392
  }
189
393
  }
394
+ // src/write-config-dir/write-config-dir.ts
190
395
  /**
191
- * Unwrap `export default`. `tsx` CJS-transforms `export default x` into
192
- * `exports.default = x`, which dynamic import wraps as
193
- * `{ default: { __esModule: true, default: x } }` — strip the extra layer
194
- * when present so ESM and CJS outputs both resolve.
396
+ * Write the files fetched from a config directory (`.holocron/…`) into the sandbox beside the config, keeping each
397
+ * relative path, so {@link loadConfigDir} finds them and an area file that imports a sibling resolves it. Creates the
398
+ * sub-directories as needed and returns the absolute paths written. Throws {@link ConfigFileError} for a path that is
399
+ * absolute or leaves `dir`, because the paths come from a remote tree and must never write outside the sandbox; it
400
+ * checks every path before it writes any.
195
401
  */
196
- function extractDefault(filepath, mod) {
197
- const outer = mod.default;
198
- const raw = outer?.__esModule === true ? outer.default : outer;
199
- if (raw === void 0 || raw === null) throw new ConfigFileError(`${filepath} must have a default export (use \`export default defineConfig({…})\`)`, filepath);
200
- return raw;
201
- }
202
- async function isFile(path) {
203
- try {
204
- return (await stat(path)).isFile();
205
- } catch {
206
- return false;
402
+ async function writeConfigDir(options) {
403
+ const root = resolve(options.dir);
404
+ const targets = options.files.map((file) => {
405
+ const target = resolve(root, file.path);
406
+ const rel = relative(root, target);
407
+ if (isAbsolute(file.path) || rel === "" || rel.startsWith("..") || isAbsolute(rel)) throw new ConfigFileError(`refusing to write ${file.path}: it is not inside ${options.dir}`, target);
408
+ return {
409
+ target,
410
+ content: file.content
411
+ };
412
+ });
413
+ for (const { target, content } of targets) {
414
+ await mkdir(dirname(target), { recursive: true });
415
+ await writeFile(target, content, "utf8");
207
416
  }
417
+ return targets.map(({ target }) => target);
208
418
  }
209
- const message = (err) => err instanceof Error ? err.message : String(err);
210
- //#endregion
211
- export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
419
+ export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigDir, loadConfigFile, loadConfigFromContent, loadConfigPath, loadLayered, mergeConfig, mergeLayers, readConfigDirSource, readConfigSource, withConfigSandbox, writeConfigDir };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/datapad",
3
- "version": "5.0.0-alpha.43",
3
+ "version": "5.0.0-alpha.430",
4
4
  "description": "Generic config-file loading for Holocron — discover, load (JSON/JS/TS/ESM/CJS), and merge <name>.config.* files with a typed defineConfig.",
5
5
  "keywords": [
6
6
  "config",
@@ -10,12 +10,12 @@
10
10
  "theholocron",
11
11
  "typescript"
12
12
  ],
13
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/datapad#readme",
13
+ "homepage": "https://docs.theholocron.dev/holocron/datapad/",
14
14
  "bugs": "https://github.com/theholocron/holocron/issues",
15
15
  "repository": {
16
16
  "type": "git",
17
17
  "url": "git+https://github.com/theholocron/holocron.git",
18
- "directory": "packages/datapad"
18
+ "directory": "cli/datapad"
19
19
  },
20
20
  "license": "MIT",
21
21
  "author": "Newton Koumantzelis",
@@ -32,22 +32,25 @@
32
32
  "dist"
33
33
  ],
34
34
  "dependencies": {
35
- "tsx": "4.23.12"
35
+ "tsx": "4.23.15",
36
+ "@theholocron/fs-utils": "^1.17.0-alpha.4",
37
+ "@theholocron/misc-utils": "^1.17.0-alpha.4",
38
+ "@theholocron/object-utils": "^1.17.0-alpha.4"
36
39
  },
37
40
  "devDependencies": {
38
- "@theholocron/eslint-config": "^8.4.5",
39
- "@theholocron/tsconfig": "^8.4.5",
40
- "@theholocron/tsdown-config": "^8.4.5",
41
- "@theholocron/vitest-config": "^8.4.5",
42
41
  "@types/node": "^26",
43
- "@vitest/coverage-v8": "^4.1.11",
44
- "@vitest/eslint-plugin": "^1.6.27",
45
- "eslint": "^10.8.1",
46
- "eslint-plugin-n": "^18.3.0",
47
- "globals": "^17.11.0",
48
- "tsdown": "^0.22.14",
42
+ "@vitest/coverage-v8": "^5.1.0",
43
+ "@vitest/eslint-plugin": "^1.6.28",
44
+ "eslint": "^10.14.0",
45
+ "eslint-plugin-n": "^18.5.0",
46
+ "globals": "^17.14.0",
47
+ "tsdown": "^0.23.5",
49
48
  "typescript": "^5.9.3",
50
- "vitest": "^4.1.11"
49
+ "vitest": "^5.1.0",
50
+ "@theholocron/eslint-config": "^8.9.0-alpha.17",
51
+ "@theholocron/tsdown-config": "^8.9.0-alpha.17",
52
+ "@theholocron/vitest-config": "^8.9.0-alpha.17",
53
+ "@theholocron/tsconfig": "^8.9.0-alpha.17"
51
54
  },
52
55
  "engines": {
53
56
  "node": ">=22"
@@ -56,10 +59,10 @@
56
59
  "access": "public"
57
60
  },
58
61
  "scripts": {
59
- "delivery.build": "tsdown",
60
- "sourceQuality.staticAnalysis": "eslint .",
62
+ "build": "tsdown",
63
+ "lint:code": "eslint .",
64
+ "test:unit": "vitest run --coverage",
61
65
  "test:watch": "vitest",
62
- "verification.typeSafety": "tsc --noEmit",
63
- "verification.unitTests": "vitest run"
66
+ "typecheck": "tsc --noEmit"
64
67
  }
65
68
  }