@theholocron/datapad 5.0.0-alpha.148 → 5.0.0-alpha.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,7 +69,8 @@ the exact same internals `loadConfigFile` uses for a file it discovered
69
69
  itself. `dir` matters: it's what upward `node_modules` resolution sees, so
70
70
  content that does `import { defineConfig } from "@theholocron/cli"` only
71
71
  resolves if `dir` sits under a tree where that package is a real
72
- 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
73
74
  `{ config, filepath }`; throws `ConfigFileError` the same way
74
75
  `loadConfigFile` does on a parse/load failure.
75
76
 
@@ -77,7 +78,26 @@ Built for `@theholocron/sentinel`'s `validateConfig()` — it fetches a
77
78
  repo's `holocron.config.*` from GitHub's API, not a local checkout, but
78
79
  still needs the fetched content to execute as a real module.
79
80
 
80
- ### `loadLayered<T>({ cwd, name, fallback?, extensions?, walkUp? })`
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
+ ### `withConfigSandbox({ nodeModules, root?, prefix? }, run)`
91
+
92
+ Runs `run(dir)` with a throwaway directory ready to be
93
+ `loadConfigFromContent`'s `dir`: `node_modules` symlinked to
94
+ `options.nodeModules` (so the config's package imports resolve) and a
95
+ `{"type":"module"}` `package.json` (so `tsx` doesn't default the files to
96
+ CommonJS and `require()` a pure-ESM dependency). Created under the OS temp dir
97
+ by default — read-only deployments can't write inside a package — and removed
98
+ afterwards, also when `run` throws.
99
+
100
+ ### `loadLayered<T>({ cwd, name, fallback?, extensions?, walkUp?, coerce? })`
81
101
 
82
102
  `<name>.config.*` layered over the `[fallback.key]` of
83
103
  `<fallback.file>.config.*`. Either, both, or neither may be present; the
@@ -85,6 +105,19 @@ dedicated file wins on conflict (`vitest`-over-`vite`). Returns
85
105
  `{ config, filepath, sources } | null` — `sources` lists the absolute
86
106
  paths actually merged, lowest priority first.
87
107
 
108
+ - `fallback.preloaded` — the `<fallback.file>.config.*` the caller has
109
+ already loaded (`null`: looked for, not there), used as is instead of loading
110
+ it again.
111
+ - `coerce(raw)` — turns each layer's raw value into the shape being merged
112
+ before the merge (a bare array standing for `{ tasks: [...] }`, say);
113
+ returning `undefined` treats the layer as absent.
114
+
115
+ ### `mergeLayers<T>(layers)`
116
+
117
+ The merge `loadLayered` uses, for layers loaded some other way: deep-merges
118
+ `layers` lowest priority first, skipping `undefined`, and returns a copy — or
119
+ `undefined` when there is nothing to merge.
120
+
88
121
  ### `mergeConfig<T>(base, override)`
89
122
 
90
123
  Deep-merge, `vite`-style: plain objects merge recursively, arrays
package/dist/index.d.mts CHANGED
@@ -1,4 +1,8 @@
1
1
  import { deepMerge as mergeConfig } from "@theholocron/object-utils";
2
+ //#region src/default-extensions.d.ts
3
+ /** Default extension probe order, highest priority first. */
4
+ declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
5
+ //#endregion
2
6
  //#region src/define.d.ts
3
7
  /**
4
8
  * Build a typed identity `defineConfig` for a specific config shape.
@@ -30,30 +34,7 @@ declare class ConfigFileError extends Error {
30
34
  filepath?: string | undefined);
31
35
  }
32
36
  //#endregion
33
- //#region src/load.d.ts
34
- /**
35
- * Discover and load `<name>.config.*` files, or load one from content that
36
- * didn't come from a file at all ({@link loadConfigFromContent}).
37
- * Holocron-agnostic — no schema, no validation, no defaults. Consumers
38
- * layer those on top.
39
- *
40
- * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
41
- * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
42
- * typed `defineConfig` file works with no build step.
43
- *
44
- * `walkUp` (off by default) adds the "nearest config" search
45
- * cosmiconfig/postcss/stylelint/ESLint's flat config all do: when `cwd`
46
- * itself has no match, check its parent, then its parent's parent, and so
47
- * on — stopping at the first directory containing a `.git` entry (checked
48
- * after that directory's own config probe, so the project root itself is
49
- * still searched) or the filesystem root. Never wanders past a repo
50
- * boundary into an unrelated enclosing directory. Built on
51
- * `@theholocron/fs-utils`'s `findUpward`/`hasGitEntry` — the same
52
- * upward-walk shape `@theholocron/sentinel`'s own `findPackageRoot` needs,
53
- * only with a different predicate.
54
- */
55
- /** Default extension probe order, highest priority first. */
56
- declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
37
+ //#region src/load-config-file.type.d.ts
57
38
  interface LoadConfigFileOptions {
58
39
  /** Directory to start looking in. */
59
40
  cwd: string;
@@ -75,6 +56,8 @@ interface Loaded<T> {
75
56
  /** Absolute path of the file the value came from. */
76
57
  filepath: string;
77
58
  }
59
+ //#endregion
60
+ //#region src/load-config-file.d.ts
78
61
  /**
79
62
  * Load the first `<name>.config.<ext>` found starting at `cwd` — just
80
63
  * `cwd` itself by default, or walking up through ancestor directories when
@@ -83,31 +66,8 @@ interface Loaded<T> {
83
66
  * {@link ConfigFileError} when a file exists but cannot be loaded.
84
67
  */
85
68
  declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
86
- interface LoadLayeredOptions extends LoadConfigFileOptions {
87
- /**
88
- * When no dedicated `<name>.config.*` exists — or in addition to it —
89
- * read `<file>.config.*` and take its `[key]`. The dedicated file (if
90
- * any) is merged on top.
91
- */
92
- fallback?: {
93
- file: string;
94
- key: string;
95
- };
96
- }
97
- interface LayeredResult<T> {
98
- config: T;
99
- /** The dedicated file path if present, else the fallback file path, else `null`. */
100
- filepath: string | null;
101
- /** Absolute paths actually merged, lowest priority first. */
102
- sources: string[];
103
- }
104
- /**
105
- * `<name>.config.*` layered over the `[fallback.key]` of
106
- * `<fallback.file>.config.*`. Either, both, or neither may be present;
107
- * the dedicated file wins on conflict (vitest-over-vite). Returns `null`
108
- * when neither source resolves.
109
- */
110
- declare function loadLayered<T>(opts: LoadLayeredOptions): Promise<LayeredResult<T> | null>;
69
+ //#endregion
70
+ //#region src/load-config-from-content.type.d.ts
111
71
  interface LoadConfigFromContentOptions {
112
72
  /**
113
73
  * Directory to write `<name>.config.<extension>` into before loading —
@@ -125,6 +85,8 @@ interface LoadConfigFromContentOptions {
125
85
  /** Which of `DEFAULT_EXTENSIONS` `content` is — determines how it's interpreted (ts/js/mjs/cjs parsed as a module, json as `JSON.parse`). */
126
86
  extension: string;
127
87
  }
88
+ //#endregion
89
+ //#region src/load-config-from-content.d.ts
128
90
  /**
129
91
  * Load config from content that didn't come from a file already on disk —
130
92
  * writes it to `<dir>/<name>.config.<extension>` first, then loads it
@@ -137,4 +99,131 @@ interface LoadConfigFromContentOptions {
137
99
  */
138
100
  declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
139
101
  //#endregion
140
- export { ConfigFileError, DEFAULT_EXTENSIONS, type LayeredResult, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
102
+ //#region src/load-layered.type.d.ts
103
+ interface LoadLayeredOptions<T = unknown> extends LoadConfigFileOptions {
104
+ /**
105
+ * When no dedicated `<name>.config.*` exists — or in addition to it —
106
+ * read `<file>.config.*` and take its `[key]`. The dedicated file (if
107
+ * any) is merged on top.
108
+ */
109
+ fallback?: {
110
+ file: string;
111
+ key: string;
112
+ /**
113
+ * The `<file>.config.*` already loaded by the caller (`null`: it was
114
+ * looked for and isn't there). Used as is instead of loading it again;
115
+ * leave it `undefined` to have `loadLayered` find and load it.
116
+ */
117
+ preloaded?: Loaded<object> | null;
118
+ };
119
+ /**
120
+ * Turns each layer's raw value — the dedicated file's default export, and
121
+ * the fallback's `[key]` — into the shape being merged, before the merge.
122
+ * Return `undefined` to treat the layer as absent. For configs that accept
123
+ * shorthand (a bare array standing for `{ tasks: [...] }`).
124
+ */
125
+ coerce?: (raw: unknown) => T | undefined;
126
+ }
127
+ interface LayeredResult<T> {
128
+ config: T;
129
+ /** The dedicated file path if present, else the fallback file path, else `null`. */
130
+ filepath: string | null;
131
+ /** Absolute paths actually merged, lowest priority first. */
132
+ sources: string[];
133
+ }
134
+ //#endregion
135
+ //#region src/load-layered.d.ts
136
+ /**
137
+ * `<name>.config.*` layered over the `[fallback.key]` of
138
+ * `<fallback.file>.config.*`. Either, both, or neither may be present;
139
+ * the dedicated file wins on conflict (vitest-over-vite). Returns `null`
140
+ * when neither source resolves.
141
+ */
142
+ declare function loadLayered<T>(opts: LoadLayeredOptions<T>): Promise<LayeredResult<T> | null>;
143
+ //#endregion
144
+ //#region src/merge-layers.d.ts
145
+ /**
146
+ * Deep-merges config layers, lowest priority first (a later layer wins on
147
+ * scalars; arrays concatenate; nested objects merge). `undefined` layers are
148
+ * skipped. Returns `undefined` when there is no layer to merge. The result is
149
+ * a copy for object layers — it never aliases a layer.
150
+ *
151
+ * The one merge `loadLayered` and every caller layering configs it loaded
152
+ * some other way (content from an API, say) use, so layering means the same
153
+ * thing everywhere.
154
+ */
155
+ declare function mergeLayers<T>(layers: readonly (T | undefined)[]): T | undefined;
156
+ //#endregion
157
+ //#region src/read-config-source.type.d.ts
158
+ /** A config file's content fetched from somewhere other than the local disk. */
159
+ interface ConfigSource {
160
+ /** The file name probed, e.g. `holocron.config.ts` — relative, as `fetch` was asked for it. */
161
+ path: string;
162
+ /** Which extension matched — what {@link loadConfigFromContent} needs as `extension`. */
163
+ extension: string;
164
+ /** The raw file content. */
165
+ content: string;
166
+ }
167
+ interface ReadConfigSourceOptions {
168
+ /** Base name — `"holocron"` probes `holocron.config.{ts,js,mjs,cjs,json}`. */
169
+ name: string;
170
+ /**
171
+ * Fetches one file by relative path (`holocron.config.ts`): its content, or
172
+ * `undefined` when it doesn't exist. Throw for anything else (a network
173
+ * failure, a permission error) — that propagates rather than reading as "absent".
174
+ */
175
+ fetch: (path: string) => Promise<string | undefined>;
176
+ /** Override the extension probe order. */
177
+ extensions?: readonly string[];
178
+ }
179
+ //#endregion
180
+ //#region src/read-config-source.d.ts
181
+ /**
182
+ * {@link probeExtensions} for a config that lives somewhere other than the
183
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
184
+ * extension-priority order through `options.fetch`, returning the first file
185
+ * that exists, or `undefined` when none does. Pass the result to
186
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
187
+ */
188
+ declare function readConfigSource(options: ReadConfigSourceOptions): Promise<ConfigSource | undefined>;
189
+ //#endregion
190
+ //#region src/with-config-sandbox.type.d.ts
191
+ interface ConfigSandboxOptions {
192
+ /**
193
+ * A real `node_modules` directory to make visible from the sandbox. A config
194
+ * that does `import { defineConfig } from "@theholocron/cli"` only resolves
195
+ * if the directory it sits in has that package reachable by Node's upward
196
+ * `node_modules` search, so the sandbox gets a symlink to this one (not a
197
+ * copy — nothing is duplicated).
198
+ */
199
+ nodeModules: string;
200
+ /** Where to create the sandbox. Defaults to the OS temp dir. */
201
+ root?: string;
202
+ /** Prefix for the sandbox directory's name. */
203
+ prefix?: string;
204
+ }
205
+ //#endregion
206
+ //#region src/with-config-sandbox.d.ts
207
+ /**
208
+ * Runs `run` with a throwaway directory prepared for
209
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
210
+ * `run` throws).
211
+ *
212
+ * The directory is made for a TS/JS config that imports packages:
213
+ *
214
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
215
+ * resolve as if the config sat next to that directory.
216
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
217
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
218
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
219
+ * correctly honouring that, would then `require()` a pure-ESM dependency
220
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
221
+ * ("require() of ES Module … not supported").
222
+ *
223
+ * The directory lives under the OS temp dir by default rather than inside any
224
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
225
+ * read-only under `/var/task`) can't create a directory there.
226
+ */
227
+ declare function withConfigSandbox<R>(options: ConfigSandboxOptions, run: (dir: string) => Promise<R>): Promise<R>;
228
+ //#endregion
229
+ export { ConfigFileError, type ConfigSandboxOptions, type ConfigSource, DEFAULT_EXTENSIONS, type LayeredResult, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, type ReadConfigSourceOptions, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig, mergeLayers, readConfigSource, withConfigSandbox };
package/dist/index.mjs CHANGED
@@ -1,9 +1,20 @@
1
- import { readFile, stat, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
1
  import { findUpward, hasGitEntry } from "@theholocron/fs-utils";
4
- import { deepMerge, deepMerge as mergeConfig } from "@theholocron/object-utils";
2
+ import { join } from "node:path";
3
+ import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
5
4
  import { pathToFileURL } from "node:url";
6
5
  import { errorMessage } from "@theholocron/misc-utils";
6
+ import { deepMerge, deepMerge as mergeConfig } from "@theholocron/object-utils";
7
+ import { tmpdir } from "node:os";
8
+ //#region src/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
+ //#endregion
7
18
  //#region src/define.ts
8
19
  /**
9
20
  * Build a typed identity `defineConfig` for a specific config shape.
@@ -37,7 +48,16 @@ var ConfigFileError = class extends Error {
37
48
  }
38
49
  };
39
50
  //#endregion
40
- //#region src/utils.ts
51
+ //#region src/is-file.ts
52
+ async function isFile(path) {
53
+ try {
54
+ return (await stat(path)).isFile();
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ //#endregion
60
+ //#region src/load-file.ts
41
61
  /**
42
62
  * The actual file-loading mechanics `load.ts`'s exported functions share:
43
63
  * JSON parsing, dynamic `import()` (TS via `tsx`'s persistent ESM loader,
@@ -49,7 +69,7 @@ var ConfigFileError = class extends Error {
49
69
  */
50
70
  async function loadFile(filepath, ext) {
51
71
  if (ext === "json") return loadJson(filepath);
52
- return extractDefault(filepath, ext === "ts" ? await importTs(filepath) : await importModule(filepath));
72
+ return extractDefault(filepath, await importModule(filepath, ext));
53
73
  }
54
74
  async function loadJson(filepath) {
55
75
  const text = await readFile(filepath, "utf8");
@@ -59,28 +79,23 @@ async function loadJson(filepath) {
59
79
  throw new ConfigFileError(`${filepath} is not valid JSON: ${errorMessage(err)}`, filepath);
60
80
  }
61
81
  }
62
- async function importModule(filepath) {
63
- try {
64
- return await import(pathToFileURL(filepath).href);
65
- } catch (err) {
66
- throw new ConfigFileError(`could not load ${filepath}: ${errorMessage(err)}`, filepath);
67
- }
68
- }
69
82
  let tsRegistered;
70
83
  async function registerTsx() {
71
84
  const { register } = await import("tsx/esm/api");
72
85
  register();
73
86
  }
74
87
  /**
75
- * Load a `.ts` file. `tsx`'s ESM loader is registered once per process
76
- * (lazily — only when a `.ts` file is actually loaded). `register()` is
77
- * used over `tsImport()` because a single run may load several TS files
78
- * (`loadLayered` reads a dedicated file *and* a parent file) and
79
- * `tsImport`'s one-off register/unregister cycle is not reentrant.
88
+ * Import `filepath`. For `.ts`, `tsx`'s ESM loader is registered first, once
89
+ * per process (lazily — only when a `.ts` file is actually loaded).
90
+ * `register()` is used over `tsImport()` because a single run may load
91
+ * several TS files (`loadLayered` reads a dedicated file *and* a parent
92
+ * file) and `tsImport`'s one-off register/unregister cycle is not reentrant.
80
93
  */
81
- async function importTs(filepath) {
82
- tsRegistered ??= registerTsx();
83
- await tsRegistered;
94
+ async function importModule(filepath, ext) {
95
+ if (ext === "ts") {
96
+ tsRegistered ??= registerTsx();
97
+ await tsRegistered;
98
+ }
84
99
  try {
85
100
  return await import(pathToFileURL(filepath).href);
86
101
  } catch (err) {
@@ -99,15 +114,27 @@ function extractDefault(filepath, mod) {
99
114
  if (raw === void 0 || raw === null) throw new ConfigFileError(`${filepath} must have a default export (use \`export default defineConfig({…})\`)`, filepath);
100
115
  return raw;
101
116
  }
102
- async function isFile(path) {
103
- try {
104
- return (await stat(path)).isFile();
105
- } catch {
106
- return false;
117
+ //#endregion
118
+ //#region src/probe-extensions.ts
119
+ /**
120
+ * Probe `dir` for `<name>.config.<ext>` in extension-priority order,
121
+ * loading and returning the first match. The one piece of per-directory
122
+ * orchestration `loadConfigFile` needs on both its non-walking and
123
+ * walking paths — pulled out so it can be unit-tested directly instead of
124
+ * only through `loadConfigFile`'s full probe/walk behavior.
125
+ */
126
+ async function probeExtensions(dir, name, extensions) {
127
+ for (const ext of extensions) {
128
+ const filepath = join(dir, `${name}.config.${ext}`);
129
+ if (!await isFile(filepath)) continue;
130
+ return {
131
+ config: await loadFile(filepath, ext),
132
+ filepath
133
+ };
107
134
  }
108
135
  }
109
136
  //#endregion
110
- //#region src/load.ts
137
+ //#region src/load-config-file.ts
111
138
  /**
112
139
  * Discover and load `<name>.config.*` files, or load one from content that
113
140
  * didn't come from a file at all ({@link loadConfigFromContent}).
@@ -129,31 +156,6 @@ async function isFile(path) {
129
156
  * upward-walk shape `@theholocron/sentinel`'s own `findPackageRoot` needs,
130
157
  * only with a different predicate.
131
158
  */
132
- /** Default extension probe order, highest priority first. */
133
- const DEFAULT_EXTENSIONS = [
134
- "ts",
135
- "js",
136
- "mjs",
137
- "cjs",
138
- "json"
139
- ];
140
- /**
141
- * Probe `dir` for `<name>.config.<ext>` in extension-priority order,
142
- * loading and returning the first match. The one piece of per-directory
143
- * orchestration `loadConfigFile` needs on both its non-walking and
144
- * walking paths — pulled out so it can be unit-tested directly instead of
145
- * only through `loadConfigFile`'s full probe/walk behavior.
146
- */
147
- async function probeExtensions(dir, name, extensions) {
148
- for (const ext of extensions) {
149
- const filepath = join(dir, `${name}.config.${ext}`);
150
- if (!await isFile(filepath)) continue;
151
- return {
152
- config: await loadFile(filepath, ext),
153
- filepath
154
- };
155
- }
156
- }
157
159
  /**
158
160
  * Load the first `<name>.config.<ext>` found starting at `cwd` — just
159
161
  * `cwd` itself by default, or walking up through ancestor directories when
@@ -167,6 +169,45 @@ async function loadConfigFile(opts) {
167
169
  if (!opts.walkUp) return await checkDir(opts.cwd) ?? null;
168
170
  return await findUpward(opts.cwd, checkDir, hasGitEntry) ?? null;
169
171
  }
172
+ //#endregion
173
+ //#region src/load-config-from-content.ts
174
+ /**
175
+ * Load config from content that didn't come from a file already on disk —
176
+ * writes it to `<dir>/<name>.config.<extension>` first, then loads it
177
+ * through the exact same path {@link loadConfigFile} uses for a file it
178
+ * discovered itself. Exists because sourcing config content from somewhere
179
+ * other than the local filesystem (a GitHub API fetch, for one — see
180
+ * `@theholocron/sentinel`) doesn't change what loading it correctly means:
181
+ * a `.ts` config still needs real module resolution, `defineConfig` import
182
+ * included, not a re-implemented parser.
183
+ */
184
+ async function loadConfigFromContent(opts) {
185
+ const filepath = join(opts.dir, `${opts.name}.config.${opts.extension}`);
186
+ await writeFile(filepath, opts.content, "utf8");
187
+ return {
188
+ config: await loadFile(filepath, opts.extension),
189
+ filepath
190
+ };
191
+ }
192
+ //#endregion
193
+ //#region src/merge-layers.ts
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
+ function mergeLayers(layers) {
205
+ const present = layers.filter((layer) => layer !== void 0);
206
+ if (present.length === 0) return void 0;
207
+ return present.reduce((acc, layer) => deepMerge(acc, layer), {});
208
+ }
209
+ //#endregion
210
+ //#region src/load-layered.ts
170
211
  /**
171
212
  * `<name>.config.*` layered over the `[fallback.key]` of
172
213
  * `<fallback.file>.config.*`. Either, both, or neither may be present;
@@ -174,47 +215,94 @@ async function loadConfigFile(opts) {
174
215
  * when neither source resolves.
175
216
  */
176
217
  async function loadLayered(opts) {
218
+ const coerce = opts.coerce ?? ((raw) => raw);
177
219
  const dedicated = await loadConfigFile(opts);
220
+ let top;
221
+ let topFile = null;
222
+ if (dedicated) {
223
+ top = coerce(dedicated.config);
224
+ if (top !== void 0) topFile = dedicated.filepath;
225
+ }
178
226
  let base;
179
227
  let baseFile = null;
180
228
  if (opts.fallback) {
181
- const parent = await loadConfigFile({
229
+ const parent = opts.fallback.preloaded !== void 0 ? opts.fallback.preloaded : await loadConfigFile({
182
230
  cwd: opts.cwd,
183
231
  name: opts.fallback.file,
184
232
  extensions: opts.extensions,
185
233
  walkUp: opts.walkUp
186
234
  });
187
- if (parent && parent.config[opts.fallback.key] !== void 0) {
188
- base = parent.config[opts.fallback.key];
189
- baseFile = parent.filepath;
235
+ const raw = (parent?.config)?.[opts.fallback.key];
236
+ if (parent && raw !== void 0) {
237
+ base = coerce(raw);
238
+ if (base !== void 0) baseFile = parent.filepath;
190
239
  }
191
240
  }
192
- if (!dedicated && base === void 0) return null;
193
- const config = deepMerge(base, dedicated?.config);
194
- const sources = [baseFile, dedicated?.filepath ?? null].filter((s) => s !== null);
241
+ const config = mergeLayers([base, top]);
242
+ if (config === void 0) return null;
243
+ const sources = [baseFile, topFile].filter((s) => s !== null);
195
244
  return {
196
245
  config,
197
- filepath: dedicated?.filepath ?? baseFile,
246
+ filepath: topFile ?? baseFile,
198
247
  sources
199
248
  };
200
249
  }
250
+ //#endregion
251
+ //#region src/read-config-source.ts
201
252
  /**
202
- * Load config from content that didn't come from a file already on disk —
203
- * writes it to `<dir>/<name>.config.<extension>` first, then loads it
204
- * through the exact same path {@link loadConfigFile} uses for a file it
205
- * discovered itself. Exists because sourcing config content from somewhere
206
- * other than the local filesystem (a GitHub API fetch, for one — see
207
- * `@theholocron/sentinel`) doesn't change what loading it correctly means:
208
- * a `.ts` config still needs real module resolution, `defineConfig` import
209
- * included, not a re-implemented parser.
253
+ * {@link probeExtensions} for a config that lives somewhere other than the
254
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
255
+ * extension-priority order through `options.fetch`, returning the first file
256
+ * that exists, or `undefined` when none does. Pass the result to
257
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
210
258
  */
211
- async function loadConfigFromContent(opts) {
212
- const filepath = join(opts.dir, `${opts.name}.config.${opts.extension}`);
213
- await writeFile(filepath, opts.content, "utf8");
214
- return {
215
- config: await loadFile(filepath, opts.extension),
216
- filepath
217
- };
259
+ async function readConfigSource(options) {
260
+ for (const extension of options.extensions ?? DEFAULT_EXTENSIONS) {
261
+ const path = `${options.name}.config.${extension}`;
262
+ const content = await options.fetch(path);
263
+ if (content !== void 0) return {
264
+ path,
265
+ extension,
266
+ content
267
+ };
268
+ }
269
+ }
270
+ //#endregion
271
+ //#region src/with-config-sandbox.ts
272
+ /**
273
+ * Runs `run` with a throwaway directory prepared for
274
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
275
+ * `run` throws).
276
+ *
277
+ * The directory is made for a TS/JS config that imports packages:
278
+ *
279
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
280
+ * resolve as if the config sat next to that directory.
281
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
282
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
283
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
284
+ * correctly honouring that, would then `require()` a pure-ESM dependency
285
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
286
+ * ("require() of ES Module … not supported").
287
+ *
288
+ * The directory lives under the OS temp dir by default rather than inside any
289
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
290
+ * read-only under `/var/task`) can't create a directory there.
291
+ */
292
+ async function withConfigSandbox(options, run) {
293
+ const root = options.root ?? tmpdir();
294
+ await mkdir(root, { recursive: true });
295
+ const dir = await mkdtemp(join(root, options.prefix ?? "datapad-"));
296
+ try {
297
+ await symlink(options.nodeModules, join(dir, "node_modules"), "dir");
298
+ await writeFile(join(dir, "package.json"), JSON.stringify({ type: "module" }), "utf8");
299
+ return await run(dir);
300
+ } finally {
301
+ await rm(dir, {
302
+ recursive: true,
303
+ force: true
304
+ });
305
+ }
218
306
  }
219
307
  //#endregion
220
- export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
308
+ export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig, mergeLayers, readConfigSource, withConfigSandbox };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/datapad",
3
- "version": "5.0.0-alpha.148",
3
+ "version": "5.0.0-alpha.149",
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",