@provino/config 0.0.0-stage → 0.1.0-rc.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pixel Perfect Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @provino/config
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Loads a project's config file and resolves it, with a dialect's policy values, into the project the coordinator and its workers run: the dialect, the policy, the test file globs, the environment, the isolation tier and the config each worker is given. It names no dialect and no environment package: the caller supplies them.
4
+
5
+ This package is a building block of [Provino](https://github.com/pixel-perfect-software/provino), a test runner for Jest projects, on npm as [`provino`](https://www.npmjs.com/package/provino). The `provino` package ships every `@provino/*` package inlined in one bundle, so you install `provino`, not this package.
6
+
7
+ **Versioning:** this package is `@beta` as a whole. There is no semver promise for it before 1.0, and its API can change in any release.
8
+
9
+ [MIT](https://github.com/pixel-perfect-software/provino/blob/main/LICENSE)
@@ -0,0 +1,208 @@
1
+ import { hasProvinoTag } from "@provino/transform";
2
+ import { ConfigEnv, Dialect, IsolationTier, ModuleRef, NeutralDiscovery, NeutralProject, Policy, ProvinoConfigInput, SerializedProjectConfig } from "@provino/types";
3
+ /**
4
+ * Stable codes for config errors, so callers and tests assert on the code, not the text.
5
+ *
6
+ * - `CONFIG_LOAD_FAILED`: the file couldn't be imported, its function threw, or a dialect's
7
+ * `detect` or a policy behaviour couldn't run. `cause` is the underlying error.
8
+ * - `CONFIG_INVALID`: the file's default export, or a key in it, has the wrong shape or value.
9
+ * - `CONFIG_UNKNOWN_DIALECT`: `dialect` names a dialect that isn't known.
10
+ * - `CONFIG_DIALECT_TIE`: several dialects tie for the best `detect` score.
11
+ * - `CONFIG_UNKNOWN_ENVIRONMENT`: the environment has no entry in the table the caller gave.
12
+ * - `CONFIG_UNSUPPORTED`: a key that isn't wired yet (`projects`, `plugins`, `alsoServe`).
13
+ * - `CONFIG_BAD_DIALECT_OPTIONS`: the dialect's options failed its schema, or its policy factory threw.
14
+ * @public
15
+ */
16
+ type ConfigErrorCode = "CONFIG_LOAD_FAILED" | "CONFIG_INVALID" | "CONFIG_UNKNOWN_DIALECT" | "CONFIG_DIALECT_TIE" | "CONFIG_UNKNOWN_ENVIRONMENT" | "CONFIG_UNSUPPORTED" | "CONFIG_BAD_DIALECT_OPTIONS";
17
+ /**
18
+ * One problem a dialect's options schema reported: where it is (`a.b.0`, empty for the options
19
+ * as a whole) and what is wrong.
20
+ * @public
21
+ */
22
+ interface ConfigIssue {
23
+ readonly path: string;
24
+ readonly message: string;
25
+ }
26
+ /**
27
+ * One issue as the line a message lists it on: ` path: message`, with `(options)` for the
28
+ * options as a whole.
29
+ * @public
30
+ */
31
+ export declare function formatConfigIssue(issue: ConfigIssue): string;
32
+ /**
33
+ * A config error with a stable code. `issues` is set for `CONFIG_BAD_DIALECT_OPTIONS` when the
34
+ * dialect's schema rejected the options; `cause` holds the underlying error where there is one.
35
+ * @public
36
+ */
37
+ export declare class ConfigError extends Error {
38
+ override readonly name = "ConfigError";
39
+ readonly code: ConfigErrorCode;
40
+ readonly issues: readonly ConfigIssue[];
41
+ constructor(code: ConfigErrorCode, message: string, options?: {
42
+ readonly cause?: unknown;
43
+ readonly issues?: readonly ConfigIssue[];
44
+ });
45
+ }
46
+ /**
47
+ * What `resolveProject` needs besides the config itself. The dialects and environments come from
48
+ * the caller (`provino`), so this package names no dialect and no environment package.
49
+ * @public
50
+ */
51
+ interface ResolveProjectOptions {
52
+ /** The config file's absolute path: `root` and the default `rootDir` are relative to its directory. */
53
+ readonly configPath: string;
54
+ /** The dialects a project may name or have detected. A config's own `dialects` replaces them. */
55
+ readonly dialects: readonly Dialect[];
56
+ /** Each environment by name, as an absolute ref the worker can import. */
57
+ readonly environments: Readonly<Record<string, {
58
+ readonly module: string;
59
+ readonly export: string;
60
+ }>>;
61
+ /** Whether this is a CI run (`allowOnly: 'not-in-ci'`). */
62
+ readonly ci: boolean;
63
+ }
64
+ /**
65
+ * A project's worker config before the run gives it a seed: a Jest or Vitest config reader brings
66
+ * its own, a `provino.config.*` project none, and one run shares a single seed across its projects.
67
+ * @public
68
+ */
69
+ type UnseededProjectConfig = Omit<SerializedProjectConfig, "seed"> & {
70
+ readonly seed?: number;
71
+ };
72
+ /**
73
+ * A project's global setup and teardown (T9.15): modules the coordinator imports and calls, as the
74
+ * policy's `globalSetup.signature` says. Every path is absolute.
75
+ * @public
76
+ */
77
+ interface ResolvedGlobalSetup {
78
+ /** The setup modules, in the order they run. */
79
+ readonly setup: readonly string[];
80
+ /** The teardown modules. */
81
+ readonly teardown: readonly string[];
82
+ /**
83
+ * What the function is called with under the `global-and-project-config` signature (Jest's two
84
+ * configs, as the reader built them: they stay in the coordinator, so they are not JSON); absent
85
+ * for a project whose dialect passes none.
86
+ */
87
+ readonly args?: NeutralProject["globalSetupArgs"];
88
+ }
89
+ /**
90
+ * A project, resolved: the choices config and policy made, and the config its workers get.
91
+ * @public
92
+ */
93
+ interface ResolvedProject {
94
+ /** `''` when config gives none. */
95
+ readonly name: string;
96
+ /** The project root, an absolute path. */
97
+ readonly rootDir: string;
98
+ /** The selected dialect, or `null` for the neutral one. */
99
+ readonly dialect: Dialect | null;
100
+ /** The dialect's policy with the project's own keys layered on (`include`, `exclude`, `globals`). */
101
+ readonly policy: Policy;
102
+ /** The globs that find test files, relative to `rootDir`. */
103
+ readonly include: readonly string[];
104
+ readonly exclude: readonly string[];
105
+ /**
106
+ * A dialect reader's discovery rules (roots, patterns on absolute paths, extensions), or `null`
107
+ * for a `provino.config.*` project, which finds tests by `include` and `exclude`. Carried for
108
+ * discovery to read (B14c); today's discovery uses `include` and `exclude`.
109
+ */
110
+ readonly discovery: NeutralDiscovery | null;
111
+ /** The environment's name: `WorkerKey.environment`. */
112
+ readonly environment: string;
113
+ readonly isolation: IsolationTier;
114
+ /** What each worker is started with, but for the run's seed (`withSeed`). */
115
+ readonly config: UnseededProjectConfig;
116
+ /** The cache directory the project's config sets itself (D70), or absent for the default. */
117
+ readonly cacheDirectory?: string;
118
+ /** Global setup and teardown the coordinator runs for this project (T9.15); absent for none. */
119
+ readonly globalSetup?: ResolvedGlobalSetup;
120
+ /**
121
+ * What affected-test selection reads of the project itself (T9.12, T9.16): its own dependency
122
+ * extractor (Jest's `dependencyExtractor`); absent when it names none.
123
+ */
124
+ readonly affected?: {
125
+ readonly extractor: ModuleRef;
126
+ };
127
+ }
128
+ /**
129
+ * Resolves one project's config: its root, dialect, policy, globs, environment and isolation, and
130
+ * the `SerializedProjectConfig` its workers start with. Every failure is a `ConfigError`.
131
+ *
132
+ * - The dialect is the one `dialect` names, else the best `detect` score (a tie is an error),
133
+ * else none: the neutral policy, no globals.
134
+ * - The config's `include`, `exclude` and `globals` are layered over the dialect's policy, so the
135
+ * policy a worker gets agrees with them.
136
+ * - The environment is the config's, else the policy's `envDefault`; it must be in `environments`.
137
+ * - Isolation is the config's, else the policy's default for that environment.
138
+ * - The neutral `setupFiles` become the worker's `setupFilesAfterEnv`, as Vitest's `setupFiles`
139
+ * do, resolved against `rootDir`.
140
+ * @public
141
+ */
142
+ export declare function resolveProject(input: ProvinoConfigInput, options: ResolveProjectOptions): Promise<ResolvedProject>;
143
+ /**
144
+ * What `resolveNeutralProject` needs besides the project: the dialect its reader belongs to (the
145
+ * caller has it already), the environments, and whether this is a CI run.
146
+ * @public
147
+ */
148
+ interface ResolveNeutralProjectOptions {
149
+ /** The dialect whose config reader produced the project, or `null` for neutral. */
150
+ readonly dialect: Dialect | null;
151
+ /** Each environment by name, as an absolute ref the worker can import. */
152
+ readonly environments: ResolveProjectOptions["environments"];
153
+ readonly ci: boolean;
154
+ }
155
+ /**
156
+ * Resolves a project a dialect's config reader produced (`ConfigReader.toNeutral`): the dialect's
157
+ * policy with the project's own layered over it, its environment and isolation, and the
158
+ * `SerializedProjectConfig` its workers start with. The same steps as `resolveProject` after
159
+ * reading a `provino.config.*`. Its `setupFiles` stay the worker's `setupFiles` (run before the
160
+ * framework) and its `setupFilesAfterEnv` the worker's; each must be an absolute path to a file.
161
+ * Every failure is a `ConfigError`.
162
+ * @public
163
+ */
164
+ export declare function resolveNeutralProject(neutral: NeutralProject, options: ResolveNeutralProjectOptions): Promise<ResolvedProject>;
165
+ /**
166
+ * A CommonJS file compiled from `export default` (tsc, Babel) sets `exports.__esModule = true` and
167
+ * `exports.default = …`, which Node's ESM loader hands over as `default` = the whole `exports`
168
+ * object. Unwraps it as Jest's `interopRequireDefault` does. Also how the coordinator reads the
169
+ * default export of a global setup module (`@provino/orchestrator`).
170
+ * @internal
171
+ */
172
+ export declare function interopDefault(value: unknown): unknown;
173
+ /**
174
+ * Imports a config file and returns what its default export gives: the object itself, or what a
175
+ * function (sync or async) returns when called with `env`. The import is `importConfigModule`'s,
176
+ * so a file edited between two calls in one process gives the new contents (the modules it
177
+ * imports are still cached by Node).
178
+ *
179
+ * Throws `ConfigError`: `CONFIG_LOAD_FAILED` when the import or the function throws (the error is
180
+ * the `cause`), `CONFIG_INVALID` when there is no default export or it doesn't give an object. The
181
+ * object's keys are checked by `resolveProject`.
182
+ * @public
183
+ */
184
+ export declare function loadConfigFile(path: string, env: ConfigEnv): Promise<ProvinoConfigInput>;
185
+ /**
186
+ * Loads the config file at `configPath` (made absolute against the working directory) and
187
+ * resolves it: `loadConfigFile` then `resolveProject`. `env` defaults to
188
+ * `{ command: 'run', mode: 'test' }`.
189
+ * @public
190
+ */
191
+ export declare function loadProject(configPath: string, options: Omit<ResolveProjectOptions, "configPath"> & {
192
+ readonly env?: ConfigEnv;
193
+ }): Promise<ResolvedProject>;
194
+ /**
195
+ * `project` with its workers' transform cache directory set to `dir`, after `dir` is made ready:
196
+ * wiped when the project's lockfile is not the one it was filled under. When the wipe fails twice
197
+ * the project comes back without a `cacheDir` and a process warning says so. Never throws.
198
+ * `lockfiles`, shared by the projects of one run, holds each lockfile's hash by path.
199
+ * @public
200
+ */
201
+ export declare function withTransformCache(project: ResolvedProject, dir: string, lockfiles?: Map<string, string>): ResolvedProject;
202
+ /**
203
+ * Evicts the oldest entries of the transform cache in `dir` down to its size cap (512 MB), unless
204
+ * no entry was written since the last time this ran. Never throws.
205
+ * @public
206
+ */
207
+ export declare function pruneTransformCache(dir: string): void;
208
+ export { type ConfigErrorCode, type ConfigIssue, type ResolveNeutralProjectOptions, type ResolveProjectOptions, type ResolvedGlobalSetup, type ResolvedProject, type UnseededProjectConfig, hasProvinoTag };
package/dist/index.js ADDED
@@ -0,0 +1,867 @@
1
+ import { createRequire } from "node:module";
2
+ import { hasProvinoTag, lockfileHash, prepareCache, pruneCacheIfWritten, transformCodeIdentity } from "@provino/transform";
3
+ import { randomUUID } from "node:crypto";
4
+ import { dirname, isAbsolute, join, resolve } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { readFile, readdir, stat } from "node:fs/promises";
7
+ import { callBehaviour, createBehaviourLoader, forEachModuleRef, isImportableLocation, isModuleRef, resolvePolicy, serializePolicy } from "@provino/policy";
8
+
9
+ // src/errors.ts
10
+ /**
11
+ * One issue as the line a message lists it on: ` path: message`, with `(options)` for the
12
+ * options as a whole.
13
+ * @public
14
+ */
15
+ function formatConfigIssue(issue) {
16
+ return ` ${issue.path === "" ? "(options)" : issue.path}: ${issue.message}`;
17
+ }
18
+ /**
19
+ * A config error with a stable code. `issues` is set for `CONFIG_BAD_DIALECT_OPTIONS` when the
20
+ * dialect's schema rejected the options; `cause` holds the underlying error where there is one.
21
+ * @public
22
+ */
23
+ var ConfigError = class extends Error {
24
+ name = "ConfigError";
25
+ code;
26
+ issues;
27
+ constructor(code, message, options) {
28
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
29
+ this.code = code;
30
+ this.issues = options?.issues ?? [];
31
+ }
32
+ };
33
+
34
+ // src/internal/input.ts
35
+ /** The tiers config may name. */
36
+ const ISOLATION_TIERS = [
37
+ "none",
38
+ "registry",
39
+ "realm",
40
+ "process"
41
+ ];
42
+ /**
43
+ * Keys that parse but have no owner yet, with who builds them. A non-empty value for one is
44
+ * `CONFIG_UNSUPPORTED`: ignoring it silently would run something other than what the file says.
45
+ */
46
+ const UNSUPPORTED = {
47
+ projects: "T1.4 (multi-project config)",
48
+ plugins: "T1.4 (plugins)",
49
+ alsoServe: "T1.4 (a project serving several dialects)"
50
+ };
51
+ /** Whether a value is a non-null object that is not an array. */
52
+ function isRecord(value) {
53
+ return typeof value === "object" && value !== null && !Array.isArray(value);
54
+ }
55
+ /** A short description of a value for a message. */
56
+ function describe(value) {
57
+ if (value === null) return "null";
58
+ if (Array.isArray(value)) return "an array";
59
+ if (typeof value === "string") return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);
60
+ if (typeof value === "object" || typeof value === "function") return `a ${typeof value}`;
61
+ return `${typeof value} ${String(value)}`;
62
+ }
63
+ function invalid(key, expected, value) {
64
+ return new ConfigError("CONFIG_INVALID", `config key "${key}" must be ${expected} (got ${describe(value)})`);
65
+ }
66
+ /** Whether a value is a string. */
67
+ function isString(value) {
68
+ return typeof value === "string";
69
+ }
70
+ /** An error's message, or the text of whatever was thrown. */
71
+ function messageOf(error) {
72
+ return error instanceof Error ? error.message : String(error);
73
+ }
74
+ /** Whether a value is an array of strings. */
75
+ function isStringArray(value) {
76
+ return Array.isArray(value) && value.every(isString);
77
+ }
78
+ /** `input[key]` when it is absent (`undefined`) or passes `guard`, else `CONFIG_INVALID`. */
79
+ function optional(input, key, expected, guard) {
80
+ const value = Reflect.get(input, key);
81
+ if (value === void 0) return void 0;
82
+ if (!guard(value)) throw invalid(key, expected, value);
83
+ return value;
84
+ }
85
+ function isDialect(value) {
86
+ if (!isRecord(value) || typeof value.name !== "string" || value.name === "") return false;
87
+ return typeof value.policy === "function" || isRecord(value.policy);
88
+ }
89
+ function isDialectList(value) {
90
+ return Array.isArray(value) && value.every(isDialect);
91
+ }
92
+ function isTier(value) {
93
+ return ISOLATION_TIERS.some((candidate) => candidate === value);
94
+ }
95
+ function isBoolean(value) {
96
+ return typeof value === "boolean";
97
+ }
98
+ /**
99
+ * Checks the keys `resolveProject` reads, and refuses the ones nothing handles yet.
100
+ * @internal
101
+ */
102
+ function parseInput(input) {
103
+ if (!isRecord(input)) throw new ConfigError("CONFIG_INVALID", `the config must be an object (got ${describe(input)})`);
104
+ for (const [key, owner] of Object.entries(UNSUPPORTED)) {
105
+ const value = Reflect.get(input, key);
106
+ if (value === void 0) continue;
107
+ if (!Array.isArray(value)) throw invalid(key, "an array", value);
108
+ if (value.length > 0) throw new ConfigError("CONFIG_UNSUPPORTED", `config key "${key}" isn't supported yet; ${owner} builds it`);
109
+ }
110
+ return {
111
+ name: optional(input, "name", "a string", isString),
112
+ root: optional(input, "root", "a string", isString),
113
+ dialect: optional(input, "dialect", "a string", isString),
114
+ dialects: optional(input, "dialects", "an array of dialects (each with a name and a policy)", isDialectList),
115
+ include: optional(input, "include", "an array of strings", isStringArray),
116
+ exclude: optional(input, "exclude", "an array of strings", isStringArray),
117
+ environment: optional(input, "environment", "a string", isString),
118
+ isolation: optional(input, "isolation", `one of ${ISOLATION_TIERS.map((t) => `"${t}"`).join(", ")}`, isTier),
119
+ globals: optional(input, "globals", "a boolean", isBoolean),
120
+ setupFiles: optional(input, "setupFiles", "an array of strings", isStringArray)
121
+ };
122
+ }
123
+
124
+ // src/internal/dialect.ts
125
+ /** The names of `dialects`, for a message. */
126
+ function namesOf(dialects) {
127
+ return dialects.length === 0 ? "none" : dialects.map((d) => `"${d.name}"`).join(", ");
128
+ }
129
+ /**
130
+ * What `detect` sees: the names of the files directly in the project root, and its parsed
131
+ * `package.json` when it has one. A dialect looks for its own config file by name (`jest.config.js`).
132
+ */
133
+ async function detectContext(rootDir) {
134
+ let configFiles;
135
+ try {
136
+ const entries = await readdir(rootDir, { withFileTypes: true });
137
+ const files = await Promise.all(entries.map(async (entry) => {
138
+ if (entry.isFile()) return true;
139
+ if (!entry.isSymbolicLink()) return false;
140
+ try {
141
+ return (await stat(join(rootDir, entry.name))).isFile();
142
+ } catch {
143
+ return false;
144
+ }
145
+ }));
146
+ configFiles = entries.filter((_, index) => files[index]).map((entry) => entry.name).toSorted();
147
+ } catch (cause) {
148
+ throw new ConfigError("CONFIG_INVALID", `can't read the project root "${rootDir}"`, { cause });
149
+ }
150
+ let packageJson;
151
+ if (configFiles.includes("package.json")) {
152
+ const path = join(rootDir, "package.json");
153
+ try {
154
+ const parsed = JSON.parse(await readFile(path, "utf8"));
155
+ if (isRecord(parsed)) packageJson = parsed;
156
+ } catch (cause) {
157
+ throw new ConfigError("CONFIG_INVALID", `can't read "${path}" to detect the dialect`, { cause });
158
+ }
159
+ }
160
+ return {
161
+ root: rootDir,
162
+ packageJson,
163
+ configFiles
164
+ };
165
+ }
166
+ /**
167
+ * Picks the project's dialect. A name picks it from `known`; no name picks the one with the
168
+ * highest `detect` score above zero; a tie is an error rather than a guess, and no match is
169
+ * neutral (`null`).
170
+ * @internal
171
+ */
172
+ async function selectDialect(requested, known, rootDir) {
173
+ if (requested !== void 0) {
174
+ const found = known.find((dialect) => dialect.name === requested);
175
+ if (found === void 0) throw new ConfigError("CONFIG_UNKNOWN_DIALECT", `unknown dialect "${requested}"; the known dialects are ${namesOf(known)}`);
176
+ return found;
177
+ }
178
+ const detecting = known.filter((dialect) => dialect.detect !== void 0);
179
+ if (detecting.length === 0) return null;
180
+ const context = await detectContext(rootDir);
181
+ const scored = await Promise.all(detecting.map(async (dialect) => ({
182
+ dialect,
183
+ score: await score(dialect, context)
184
+ })));
185
+ const best = Math.max(0, ...scored.map((entry) => entry.score));
186
+ if (best === 0) return null;
187
+ const winners = scored.filter((entry) => entry.score === best).map((entry) => entry.dialect);
188
+ const [winner] = winners;
189
+ if (winners.length > 1 || winner === void 0) throw new ConfigError("CONFIG_DIALECT_TIE", `the dialects ${namesOf(winners)} fit this project equally well (score ${best}); name one with the "dialect" config key`);
190
+ return winner;
191
+ }
192
+ /** A dialect's `detect` score; anything that isn't a positive number is no fit. */
193
+ async function score(dialect, context) {
194
+ try {
195
+ const value = await dialect.detect?.(context);
196
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
197
+ } catch (cause) {
198
+ throw new ConfigError("CONFIG_LOAD_FAILED", `the "${dialect.name}" dialect's detect failed`, { cause });
199
+ }
200
+ }
201
+ function issueOf(issue) {
202
+ return {
203
+ path: (issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join("."),
204
+ message: issue.message
205
+ };
206
+ }
207
+ /**
208
+ * The dialect's policy layer. A plain layer is used as it is. A factory gets the options at
209
+ * `config[dialect.name]`, checked against `dialect.options` first when the dialect has a schema
210
+ * (the factory is typed to accept anything, so it can't check them itself).
211
+ * @internal
212
+ */
213
+ async function dialectPolicy(dialect, options) {
214
+ const { policy } = dialect;
215
+ if (typeof policy !== "function") return policy;
216
+ let checked = options;
217
+ const schema = dialect.options;
218
+ if (schema !== void 0) {
219
+ let result;
220
+ try {
221
+ result = await schema["~standard"].validate(options);
222
+ } catch (cause) {
223
+ throw new ConfigError("CONFIG_BAD_DIALECT_OPTIONS", `the "${dialect.name}" dialect's options schema threw`, { cause });
224
+ }
225
+ if (result.issues !== void 0) {
226
+ const issues = result.issues.map(issueOf);
227
+ const lines = issues.map(formatConfigIssue);
228
+ throw new ConfigError("CONFIG_BAD_DIALECT_OPTIONS", `invalid options for the "${dialect.name}" dialect:\n${lines.join("\n")}`, { issues });
229
+ }
230
+ checked = result.value;
231
+ }
232
+ try {
233
+ return policy(checked);
234
+ } catch (cause) {
235
+ throw new ConfigError("CONFIG_BAD_DIALECT_OPTIONS", `the "${dialect.name}" dialect couldn't build its policy from its options`, { cause });
236
+ }
237
+ }
238
+
239
+ // src/internal/refs.ts
240
+ /** Whether a value is a plain `{ module: string, export: string }` and nothing else. */
241
+ function isRefShape(value) {
242
+ if (!isRecord(value) || Object.getPrototypeOf(value) !== Object.prototype) return false;
243
+ if (Object.keys(value).length !== (Object.hasOwn(value, "options") ? 3 : 2)) return false;
244
+ return isModuleRef({
245
+ module: value.module,
246
+ export: value.export
247
+ });
248
+ }
249
+ /**
250
+ * The worker imports a ref's `module` as it is (D21), so it must be an absolute path or a URL:
251
+ * the same rule as the worker's (`isImportableLocation`). A bare or relative specifier would
252
+ * resolve from the worker's own location, not the project's.
253
+ */
254
+ function checkModule(module, path) {
255
+ if (isImportableLocation(module)) return;
256
+ throw new ConfigError("CONFIG_INVALID", `${path}.module must be an absolute path or a URL such as a file: URL (got ${describe(module)}); a worker can't resolve a package specifier or a relative path`);
257
+ }
258
+ /** Checks one ref at `path`. `ref` is a value from a dialect or the caller, so nothing is trusted. */
259
+ function checkRef(ref, path) {
260
+ if (!isRefShape(ref)) throw new ConfigError("CONFIG_INVALID", `${path} must be a { module, export } ref, since a function can't cross to a worker (got ${describe(ref)})`);
261
+ checkModule(ref.module, path);
262
+ }
263
+ /**
264
+ * What the policy walk stops at: a function (which can't cross, and which `serializePolicy` only
265
+ * catches in plain objects), or any object holding both `module` and `export`, which is meant as
266
+ * a ref and checked as one even when malformed.
267
+ */
268
+ function isRefOrFunction(value) {
269
+ return typeof value === "function" || typeof value === "object" && value !== null && "module" in value && "export" in value;
270
+ }
271
+ /**
272
+ * Checks that the finished worker config is something every worker can use, so a bad one is a
273
+ * config error (exit 2) and not a failure in each worker (exit 1): every `{ module, export }` ref
274
+ * in the policy, the globals and module-scope refs and the environment ref has a plain shape and an absolute
275
+ * `module`, and the whole config survives `structuredClone`. Throws `CONFIG_INVALID` naming the
276
+ * key path.
277
+ * @internal
278
+ */
279
+ function assertWorkerConfig(config) {
280
+ forEachModuleRef(config.policy, "policy", (ref, path) => {
281
+ if (typeof ref === "function") throw new ConfigError("CONFIG_INVALID", `${path} is a function, which can't cross to a worker; give it as a { module, export } ref`);
282
+ checkRef(ref, path);
283
+ }, isRefOrFunction);
284
+ if (config.globals !== null) checkRef(config.globals, "globals");
285
+ if (config.moduleScope !== null) checkRef(config.moduleScope, "moduleScope");
286
+ checkRef(config.environment, "environment");
287
+ config.loader.transform?.rules.forEach((rule, index) => {
288
+ checkRef(rule.transformer, `loader.transform.rules[${index}].transformer`);
289
+ });
290
+ try {
291
+ structuredClone(config);
292
+ } catch (cause) {
293
+ throw new ConfigError("CONFIG_INVALID", `the worker config can't be cloned to a worker: ${messageOf(cause)}`, { cause });
294
+ }
295
+ }
296
+
297
+ // src/internal/setup-files.ts
298
+ const RELATIVE = /^\.\.?(?:[/\\]|$)/;
299
+ /** One `setupFiles` entry as an absolute path, or `CONFIG_INVALID` for what can't be one. */
300
+ function setupPath(entry, rootDir, key) {
301
+ if (entry.startsWith("file:")) try {
302
+ return fileURLToPath(entry);
303
+ } catch (cause) {
304
+ throw new ConfigError("CONFIG_INVALID", `${key} is not a usable file: URL`, { cause });
305
+ }
306
+ if (isAbsolute(entry) || RELATIVE.test(entry)) return resolve(rootDir, entry);
307
+ throw new ConfigError("CONFIG_INVALID", `${key} must be a relative path (./ or ../), an absolute path or a file: URL; package specifiers and <rootDir> tokens in setupFiles aren't supported yet (T1.4)`);
308
+ }
309
+ /**
310
+ * The `setupFiles` entries as absolute paths, each checked to be a file, so a typo is a config
311
+ * error and not a failure in every worker that blames the test file.
312
+ * @internal
313
+ */
314
+ async function resolveSetupFiles(entries, rootDir, name = "setupFiles") {
315
+ return Promise.all(entries.map(async (entry, index) => {
316
+ const key = `config key "${name}[${index}]" (${JSON.stringify(entry)})`;
317
+ const path = setupPath(entry, rootDir, key);
318
+ let isFile = false;
319
+ try {
320
+ isFile = (await stat(path)).isFile();
321
+ } catch {}
322
+ if (!isFile) throw new ConfigError("CONFIG_INVALID", `${key} isn't a file: "${path}"`);
323
+ return path;
324
+ }));
325
+ }
326
+
327
+ // src/internal/transform.ts
328
+ /** A pattern that doesn't compile is a config error here, not a failure in every worker. */
329
+ function assertRegExp(source, path) {
330
+ try {
331
+ new RegExp(source);
332
+ } catch (cause) {
333
+ throw new ConfigError("CONFIG_INVALID", `${path} is not a regular expression: ${messageOf(cause)}`, { cause });
334
+ }
335
+ }
336
+ /**
337
+ * Checks `transformIgnorePatterns`: each pattern, then all of them joined with `|`, the one regular
338
+ * expression Jest builds (`ScriptTransformer.ts` `calcIgnorePatternRegExp`, L1072-L1081) and the
339
+ * loader and a transformer host build, whether or not a transform is configured. Two patterns that
340
+ * compile alone can fail joined (`\k<b>` and `(?<a>x)`: the second makes the first a reference to
341
+ * a group that isn't there). Jest fails every test file on it; here it is one config error.
342
+ */
343
+ function assertIgnorePatterns(neutral) {
344
+ const patterns = neutral.transformIgnorePatterns;
345
+ patterns.forEach((pattern, index) => {
346
+ assertRegExp(pattern, `transformIgnorePatterns[${index}]`);
347
+ });
348
+ if (patterns.length > 1) assertRegExp(patterns.join("|"), "transformIgnorePatterns (joined with \"|\", as Jest joins them)");
349
+ }
350
+ /**
351
+ * Ignore patterns that match every path with a `node_modules` directory in it (Jest's default is
352
+ * `/node_modules/`): with one, no `node_modules` file is any transform's, so there are no claims to
353
+ * ask a worker about.
354
+ */
355
+ const IGNORES_EVERY_PACKAGE = /* @__PURE__ */ new Set([
356
+ "/node_modules/",
357
+ "/node_modules",
358
+ "node_modules/",
359
+ "node_modules"
360
+ ]);
361
+ /**
362
+ * A transformer's module as the absolute path a worker can import (D21). A path stays as it is; a
363
+ * package name (a transformer a dialect left bare, such as Jest's own `babel-jest` with no Jest
364
+ * install to resolve it from) resolves from the project's root, as a transformer is the project's
365
+ * own dependency.
366
+ */
367
+ function resolveTransformer(module, rootDir, path) {
368
+ if (isAbsolute(module) || module.startsWith("file:")) return module;
369
+ try {
370
+ return createRequire(join(rootDir, "noop.js")).resolve(module);
371
+ } catch (cause) {
372
+ throw new ConfigError("CONFIG_INVALID", `${path}: cannot resolve the transformer ${describe(module)} from ${rootDir}: ${messageOf(cause)}`, { cause });
373
+ }
374
+ }
375
+ /**
376
+ * The project's `transform` entries as the worker's `SerializedTransformConfig` (T3.8), or
377
+ * `undefined` for a project with none, whose every file takes the Oxc pipeline. It checks
378
+ * `transformIgnorePatterns` first (`assertIgnorePatterns`), for `resolveTransformClaims` too, which
379
+ * a project resolves after it.
380
+ * @internal
381
+ */
382
+ function resolveTransforms(neutral) {
383
+ assertIgnorePatterns(neutral);
384
+ if (neutral.transforms.length === 0) return void 0;
385
+ return {
386
+ rules: neutral.transforms.map((rule, index) => {
387
+ const path = `transform[${index}]`;
388
+ assertRegExp(rule.pattern, `${path}.pattern`);
389
+ return {
390
+ pattern: rule.pattern,
391
+ transformer: {
392
+ module: resolveTransformer(rule.module, neutral.rootDir, path),
393
+ export: "default"
394
+ },
395
+ options: rule.options,
396
+ ...rule.checksMockFactories === true ? { checksMockFactories: true } : {}
397
+ };
398
+ }),
399
+ ignorePatterns: neutral.transformIgnorePatterns,
400
+ config: neutral.transformConfig ?? {},
401
+ hoistedMarkers: [...neutral.transformHoistedMarkers ?? []]
402
+ };
403
+ }
404
+ /**
405
+ * The files the project's transforms take (`SerializedLoaderConfig.transformClaims`): the rules'
406
+ * patterns and the ones Provino's pipeline stands in for (`standInTransformPatterns`), with
407
+ * `transformIgnorePatterns`. `undefined` for a project with no transform, whose `node_modules`
408
+ * files are all loaded by Node, and for one whose ignore patterns take every `node_modules` file
409
+ * out (Jest's default `/node_modules/`), where a worker has nothing to ask. The stand-in patterns
410
+ * are checked here; the ignore patterns by `resolveTransforms`, which runs first.
411
+ * @internal
412
+ */
413
+ function resolveTransformClaims(neutral) {
414
+ const standIns = neutral.standInTransformPatterns ?? [];
415
+ standIns.forEach((pattern, index) => {
416
+ assertRegExp(pattern, `standInTransformPatterns[${index}]`);
417
+ });
418
+ if (neutral.transforms.length === 0 && standIns.length === 0) return void 0;
419
+ if (neutral.transformIgnorePatterns.some((pattern) => IGNORES_EVERY_PACKAGE.has(pattern))) return;
420
+ return {
421
+ patterns: [...neutral.transforms.map((rule) => rule.pattern), ...standIns],
422
+ ignorePatterns: neutral.transformIgnorePatterns
423
+ };
424
+ }
425
+
426
+ // src/resolve.ts
427
+ /**
428
+ * The extensions a specifier without one is tried with, in order: Jest's `moduleFileExtensions`
429
+ * without `.node`. A neutral default of ours.
430
+ */
431
+ const LOADER_EXTENSIONS = [
432
+ ".js",
433
+ ".mjs",
434
+ ".cjs",
435
+ ".jsx",
436
+ ".ts",
437
+ ".mts",
438
+ ".cts",
439
+ ".tsx",
440
+ ".json"
441
+ ];
442
+ /** `rootDir` must be a directory that exists, whether or not a dialect detects. */
443
+ async function assertDirectory(rootDir) {
444
+ let isDirectory = false;
445
+ try {
446
+ isDirectory = (await stat(rootDir)).isDirectory();
447
+ } catch {}
448
+ if (!isDirectory) throw new ConfigError("CONFIG_INVALID", `config key "root" must be an existing directory ("${rootDir}" is not)`);
449
+ }
450
+ /**
451
+ * Awaits two independent promises together. If both fail, `first`'s error is thrown, as it would
452
+ * be had `first` been awaited alone before `second` started; `second`'s is never left unhandled.
453
+ */
454
+ async function inParallel(first, second) {
455
+ const [a, b] = await Promise.allSettled([first, second]);
456
+ if (a.status === "rejected") throw a.reason;
457
+ if (b.status === "rejected") throw b.reason;
458
+ return [a.value, b.value];
459
+ }
460
+ /** A record's own entry for a name from config (`constructor` is not an entry). */
461
+ function entry(record, key) {
462
+ return Object.hasOwn(record, key) ? record[key] : void 0;
463
+ }
464
+ /** The project's own keys, as the policy layer that goes over the dialect's. */
465
+ function projectLayer(include, exclude, globals) {
466
+ const orchestrator = {
467
+ ...include === void 0 ? {} : { include },
468
+ ...exclude === void 0 ? {} : { exclude }
469
+ };
470
+ return {
471
+ ...Object.keys(orchestrator).length === 0 ? {} : { orchestrator },
472
+ ...globals === void 0 ? {} : { core: { injectGlobals: globals } }
473
+ };
474
+ }
475
+ /**
476
+ * The resolver export conditions for the environment: the policy's `environmentConditions`
477
+ * behaviour, loaded and called here in the coordinator. It only knows the environment's name,
478
+ * not the `conditions` its `Environment` declares (that object lives in the worker).
479
+ */
480
+ async function loaderConditions(policy, environment, options) {
481
+ const behaviour = policy.orchestrator.environmentConditions;
482
+ let conditions;
483
+ try {
484
+ conditions = await callBehaviour(createBehaviourLoader(), behaviour, {
485
+ name: environment,
486
+ options
487
+ });
488
+ } catch (cause) {
489
+ throw new ConfigError("CONFIG_LOAD_FAILED", `can't get the resolver conditions for the "${environment}" environment from the policy's orchestrator.environmentConditions`, { cause });
490
+ }
491
+ if (!isStringArray(conditions)) throw new ConfigError("CONFIG_INVALID", `the policy's orchestrator.environmentConditions must return an array of strings (got ${describe(conditions)})`);
492
+ return conditions;
493
+ }
494
+ /**
495
+ * Resolves one project's config: its root, dialect, policy, globs, environment and isolation, and
496
+ * the `SerializedProjectConfig` its workers start with. Every failure is a `ConfigError`.
497
+ *
498
+ * - The dialect is the one `dialect` names, else the best `detect` score (a tie is an error),
499
+ * else none: the neutral policy, no globals.
500
+ * - The config's `include`, `exclude` and `globals` are layered over the dialect's policy, so the
501
+ * policy a worker gets agrees with them.
502
+ * - The environment is the config's, else the policy's `envDefault`; it must be in `environments`.
503
+ * - Isolation is the config's, else the policy's default for that environment.
504
+ * - The neutral `setupFiles` become the worker's `setupFilesAfterEnv`, as Vitest's `setupFiles`
505
+ * do, resolved against `rootDir`.
506
+ * @public
507
+ */
508
+ async function resolveProject(input, options) {
509
+ if (!isAbsolute(options.configPath)) throw new ConfigError("CONFIG_INVALID", `the config path must be absolute (got "${options.configPath}")`);
510
+ const parsed = parseInput(input);
511
+ const rootDir = resolve(dirname(options.configPath), parsed.root ?? ".");
512
+ const [, dialect] = await inParallel(assertDirectory(rootDir), selectDialect(parsed.dialect, parsed.dialects ?? options.dialects, rootDir));
513
+ const dialectLayer = dialect === null ? void 0 : await dialectPolicy(dialect, Object.hasOwn(input, dialect.name) ? Reflect.get(input, dialect.name) : void 0);
514
+ return finishProject({
515
+ name: parsed.name ?? "",
516
+ rootDir,
517
+ dialect,
518
+ layers: [dialectLayer, projectLayer(parsed.include, parsed.exclude, parsed.globals)],
519
+ environment: parsed.environment,
520
+ environmentOptions: {},
521
+ isolation: parsed.isolation,
522
+ setupFiles: [],
523
+ setupFilesAfterEnv: parsed.setupFiles ?? [],
524
+ setupFilesAfterEnvKey: "setupFiles",
525
+ discovery: null
526
+ }, options);
527
+ }
528
+ /**
529
+ * Resolves a project a dialect's config reader produced (`ConfigReader.toNeutral`): the dialect's
530
+ * policy with the project's own layered over it, its environment and isolation, and the
531
+ * `SerializedProjectConfig` its workers start with. The same steps as `resolveProject` after
532
+ * reading a `provino.config.*`. Its `setupFiles` stay the worker's `setupFiles` (run before the
533
+ * framework) and its `setupFilesAfterEnv` the worker's; each must be an absolute path to a file.
534
+ * Every failure is a `ConfigError`.
535
+ * @public
536
+ */
537
+ async function resolveNeutralProject(neutral, options) {
538
+ if (!isAbsolute(neutral.rootDir)) throw new ConfigError("CONFIG_INVALID", `the project's rootDir must be absolute (got "${neutral.rootDir}")`);
539
+ await assertDirectory(neutral.rootDir);
540
+ const dialectLayer = options.dialect === null ? void 0 : await dialectPolicy(options.dialect, void 0);
541
+ for (const [key, paths] of [
542
+ ["setupFiles", neutral.setupFiles],
543
+ ["setupFilesAfterEnv", neutral.setupFilesAfterEnv],
544
+ ["globalSetup", neutral.globalSetup],
545
+ ["globalTeardown", neutral.globalTeardown]
546
+ ]) {
547
+ const relative = paths.find((path) => !isAbsolute(path));
548
+ if (relative !== void 0) throw new ConfigError("CONFIG_INVALID", `the project's ${key} must hold absolute paths (got "${relative}")`);
549
+ }
550
+ return finishProject({
551
+ name: neutral.name,
552
+ rootDir: neutral.rootDir,
553
+ dialect: options.dialect,
554
+ layers: [dialectLayer, neutral.policy],
555
+ environment: neutral.environment.name,
556
+ environmentOptions: neutral.environment.options,
557
+ isolation: void 0,
558
+ setupFiles: neutral.setupFiles,
559
+ setupFilesAfterEnv: neutral.setupFilesAfterEnv,
560
+ setupFilesAfterEnvKey: "setupFilesAfterEnv",
561
+ discovery: neutral.discovery,
562
+ transform: resolveTransforms(neutral),
563
+ transformClaims: resolveTransformClaims(neutral),
564
+ cacheDirectory: neutral.cacheDirectory,
565
+ globalSetup: globalSetupOf(neutral),
566
+ affected: affectedOf(neutral),
567
+ aliases: neutral.aliases,
568
+ globalValues: neutral.globalValues,
569
+ fakeTimers: neutral.fakeTimers,
570
+ snapshotResolver: neutral.snapshotResolver,
571
+ seed: neutral.seed,
572
+ randomize: neutral.randomize,
573
+ resolution: neutral.resolution,
574
+ coverage: neutral.coverage
575
+ }, {
576
+ environments: options.environments,
577
+ ci: options.ci
578
+ });
579
+ }
580
+ /**
581
+ * The project's own affected-selection settings: its dependency extractor, or `undefined` when it
582
+ * names none. `watchPathIgnorePatterns` stays on the neutral project (`watch`) for the watch
583
+ * driver to carry (B23c Phase 8).
584
+ */
585
+ function affectedOf(neutral) {
586
+ const extractor = neutral.affected?.extractor;
587
+ return extractor === void 0 ? void 0 : { extractor };
588
+ }
589
+ /**
590
+ * The project's global hooks, or `undefined` when it has none and no args either: a project with
591
+ * no hook of its own keeps the args when the run has one (Jest's root `globalSetup`), since that
592
+ * hook is called with the config of the first project.
593
+ */
594
+ function globalSetupOf(neutral) {
595
+ if (neutral.globalSetup.length === 0 && neutral.globalTeardown.length === 0 && neutral.globalSetupArgs === void 0) return;
596
+ return {
597
+ setup: neutral.globalSetup,
598
+ teardown: neutral.globalTeardown,
599
+ ...neutral.globalSetupArgs === void 0 ? {} : { args: neutral.globalSetupArgs }
600
+ };
601
+ }
602
+ /** `record`, or `undefined` when it has no keys: an empty one is no setting. */
603
+ function nonEmpty(record) {
604
+ return record === void 0 || Object.keys(record).length === 0 ? void 0 : record;
605
+ }
606
+ /** The resolver keys of the loader config: only the ones the project gave (T3.3). */
607
+ function resolverKeys(input) {
608
+ const { aliases, resolution } = input;
609
+ return {
610
+ ...aliases === void 0 || aliases.length === 0 ? {} : { aliases },
611
+ ...resolution?.moduleDirectories === void 0 ? {} : { moduleDirectories: resolution.moduleDirectories },
612
+ ...resolution?.modulePaths === void 0 || resolution.modulePaths.length === 0 ? {} : { modulePaths: resolution.modulePaths },
613
+ ...resolution?.esmExtensions === void 0 || resolution.esmExtensions.length === 0 ? {} : { esmExtensions: resolution.esmExtensions },
614
+ ...resolution?.resolver === void 0 ? {} : { resolver: {
615
+ module: resolution.resolver,
616
+ export: "default"
617
+ } },
618
+ ...resolution?.skipNodeResolution === true ? { skipNodeResolution: true } : {}
619
+ };
620
+ }
621
+ /** The steps every project shares once its input is read: policy, environment, the worker config. */
622
+ async function finishProject(input, options) {
623
+ const { dialect, rootDir } = input;
624
+ let policy;
625
+ try {
626
+ policy = resolvePolicy(...input.layers);
627
+ } catch (cause) {
628
+ throw new ConfigError("CONFIG_INVALID", `the policy didn't resolve: ${messageOf(cause)}`, { cause });
629
+ }
630
+ const environment = input.environment ?? policy.orchestrator.envDefault;
631
+ const environmentRef = entry(options.environments, environment);
632
+ if (environmentRef === void 0) {
633
+ const known = Object.keys(options.environments);
634
+ throw new ConfigError("CONFIG_UNKNOWN_ENVIRONMENT", `unknown environment "${environment}"; the known environments are ${known.length === 0 ? "none" : known.map((n) => `"${n}"`).join(", ")}`);
635
+ }
636
+ const { isolationDefault } = policy.orchestrator;
637
+ const isolation = input.isolation ?? entry(isolationDefault.byEnvironment, environment) ?? isolationDefault.default;
638
+ const globalsFactory = policy.core.injectGlobals ? dialect?.globals?.factory ?? null : null;
639
+ let serialized;
640
+ try {
641
+ serialized = serializePolicy(policy);
642
+ } catch (cause) {
643
+ throw new ConfigError("CONFIG_INVALID", `the policy can't go to a worker: ${messageOf(cause)}`, { cause });
644
+ }
645
+ const [[setupFiles, setupFilesAfterEnv], conditions] = await inParallel(Promise.all([resolveSetupFiles(input.setupFiles, rootDir, "setupFiles"), resolveSetupFiles(input.setupFilesAfterEnv, rootDir, input.setupFilesAfterEnvKey)]), loaderConditions(policy, environment, input.environmentOptions));
646
+ const globalValues = nonEmpty(input.globalValues);
647
+ const fakeTimers = nonEmpty(input.fakeTimers);
648
+ const config = {
649
+ name: input.name,
650
+ rootDir,
651
+ ci: options.ci,
652
+ policy: serialized,
653
+ environment: {
654
+ module: environmentRef.module,
655
+ export: environmentRef.export,
656
+ options: input.environmentOptions
657
+ },
658
+ globals: globalsFactory,
659
+ moduleScope: dialect?.moduleScope?.factory ?? null,
660
+ ...dialect?.environmentResolver === void 0 ? {} : { environmentResolver: dialect.environmentResolver },
661
+ ...globalValues === void 0 ? {} : { globalValues },
662
+ ...fakeTimers === void 0 ? {} : { fakeTimers },
663
+ ...input.seed === void 0 ? {} : { seed: input.seed },
664
+ ...input.snapshotResolver === void 0 ? {} : { snapshotResolver: input.snapshotResolver },
665
+ ...input.coverage === void 0 ? {} : { coverage: input.coverage },
666
+ ...input.randomize === true ? { randomize: true } : {},
667
+ setupFiles,
668
+ setupFilesAfterEnv,
669
+ loader: {
670
+ hoist: dialect?.loader?.hoist ?? null,
671
+ moduleScope: policy.core.injectGlobals ? dialect?.moduleScope?.names ?? [] : [],
672
+ ...dialect?.moduleScope?.modules === void 0 ? {} : { scopeModules: dialect.moduleScope.modules },
673
+ ...dialect?.moduleScope?.mappable === void 0 ? {} : { scopeMappable: dialect.moduleScope.mappable },
674
+ extensions: Object.freeze([...LOADER_EXTENSIONS]),
675
+ conditions,
676
+ tsconfig: "auto",
677
+ mappers: [],
678
+ typescript: "oxc",
679
+ ...input.transform === void 0 ? {} : { transform: input.transform },
680
+ ...input.transformClaims === void 0 ? {} : { transformClaims: input.transformClaims },
681
+ ...resolverKeys(input)
682
+ }
683
+ };
684
+ assertWorkerConfig(config);
685
+ return {
686
+ name: input.name,
687
+ rootDir,
688
+ dialect,
689
+ policy,
690
+ include: policy.orchestrator.include,
691
+ exclude: policy.orchestrator.exclude,
692
+ discovery: input.discovery,
693
+ environment,
694
+ isolation,
695
+ config,
696
+ ...input.cacheDirectory === void 0 ? {} : { cacheDirectory: input.cacheDirectory },
697
+ ...input.globalSetup === void 0 ? {} : { globalSetup: input.globalSetup },
698
+ ...input.affected === void 0 ? {} : { affected: input.affected }
699
+ };
700
+ }
701
+
702
+ // src/load.ts
703
+ /** What `loadProject` does when the caller gives no `ConfigEnv`. */
704
+ const DEFAULT_ENV = Object.freeze({
705
+ command: "run",
706
+ mode: "test"
707
+ });
708
+ /** `require.cache` is Node's CommonJS module cache, which the ESM loader's CommonJS path shares. */
709
+ const nodeRequire = createRequire(import.meta.url);
710
+ /**
711
+ * Makes the next `import()` of `file` read it from disk, not from a module Node already holds.
712
+ * Node caches by URL, so a query string the file never sees gives an ESM file (`.mjs`, `.mts`,
713
+ * and `.js` or `.ts` under a package of type `module`) a URL of its own: it is read and run
714
+ * again. Node's CommonJS loader ignores the query and keys its cache by file name, so for a
715
+ * CommonJS file (`.cjs`, `.cts`, and `.js` or `.ts` under a package of type `commonjs`) the entry
716
+ * is dropped from that cache as well.
717
+ *
718
+ * Each load stays in the ESM module map for the life of the process, since Node can't unload a
719
+ * module. That is a small, accepted leak for config files. Only the config file itself is busted:
720
+ * a module it imports or requires is still served from Node's caches.
721
+ */
722
+ function freshUrl(file, cacheKey) {
723
+ delete nodeRequire.cache[cacheKey];
724
+ const url = pathToFileURL(file);
725
+ url.searchParams.set("provino-load", randomUUID());
726
+ return url.href;
727
+ }
728
+ /**
729
+ * The fresh load of each file that hasn't settled yet, by real path (the key of Node's CommonJS
730
+ * cache, so two spellings of one file share an entry). An `import()` of a CommonJS file puts the
731
+ * file's module in that cache when it reads the file, and checks, when it runs it, that the entry
732
+ * is still that module: Node 24's `loadCJSModuleWithModuleLoad` (`internal/modules/esm/translators`)
733
+ * asserts it, and the failure is `ERR_INTERNAL_ASSERTION`. A second fresh load of the same file in
734
+ * between deletes that entry (`freshUrl`), so the loads of one file run one after another: two
735
+ * `run()` calls that overlap on one config file reach it. It lives at module level because the
736
+ * cache it guards is the process's, and it holds a file only while a load of that file is running.
737
+ */
738
+ const loading = /* @__PURE__ */ new Map();
739
+ /**
740
+ * The key of `file` in Node's CommonJS cache, which is also the key of `loading`: what
741
+ * `require.resolve` gives, the file's real path. A file that doesn't resolve is cached under
742
+ * nothing, so it is its own key, and the import says why it can't be read.
743
+ */
744
+ function cacheKeyOf(file) {
745
+ try {
746
+ return nodeRequire.resolve(file);
747
+ } catch {
748
+ return file;
749
+ }
750
+ }
751
+ /** `import()` of `freshUrl(file)`, after any fresh load of the same file still running. */
752
+ function importFresh(file) {
753
+ const key = cacheKeyOf(file);
754
+ const load = (loading.get(key) ?? Promise.resolve()).then(() => import(freshUrl(file, key)));
755
+ const settled = load.then(() => void 0, () => void 0);
756
+ loading.set(key, settled);
757
+ settled.then(() => {
758
+ if (loading.get(key) === settled) loading.delete(key);
759
+ });
760
+ return load;
761
+ }
762
+ /**
763
+ * A CommonJS file compiled from `export default` (tsc, Babel) sets `exports.__esModule = true` and
764
+ * `exports.default = …`, which Node's ESM loader hands over as `default` = the whole `exports`
765
+ * object. Unwraps it as Jest's `interopRequireDefault` does. Also how the coordinator reads the
766
+ * default export of a global setup module (`@provino/orchestrator`).
767
+ * @internal
768
+ */
769
+ function interopDefault(value) {
770
+ return isRecord(value) && value.__esModule === true && Object.hasOwn(value, "default") ? value.default : value;
771
+ }
772
+ /**
773
+ * Imports a `provino.config.*` and returns its default export, unwrapped as
774
+ * `interopRequireDefault` does for a CommonJS file compiled from `export default`: how
775
+ * `loadConfigFile` reads it (build-plan §6). The Jest dialect reads Jest's files as jest-util's
776
+ * `requireOrImportModule` does instead (cached, as in Jest). Node's own loader reads the file, so
777
+ * `.mjs`, `.js` (per the nearest `package.json`'s `type`), `.mts` and `.ts` load as Node loads them
778
+ * (type stripping needs Node 22.18+, or `--experimental-strip-types`). Every call reads the file
779
+ * again (see `freshUrl`).
780
+ *
781
+ * Throws `ConfigError`: `CONFIG_LOAD_FAILED` when the import throws (the error is the `cause`),
782
+ * `CONFIG_INVALID` when the module has no default export.
783
+ */
784
+ async function importConfigModule(path) {
785
+ const file = resolve(path);
786
+ let namespace;
787
+ try {
788
+ namespace = await importFresh(file);
789
+ } catch (cause) {
790
+ throw new ConfigError("CONFIG_LOAD_FAILED", `can't load the config file "${file}"`, { cause });
791
+ }
792
+ if (!isRecord(namespace) || !("default" in namespace)) throw new ConfigError("CONFIG_INVALID", `the config file "${file}" has no default export; use "export default { … }"`);
793
+ return interopDefault(namespace.default);
794
+ }
795
+ /**
796
+ * Imports a config file and returns what its default export gives: the object itself, or what a
797
+ * function (sync or async) returns when called with `env`. The import is `importConfigModule`'s,
798
+ * so a file edited between two calls in one process gives the new contents (the modules it
799
+ * imports are still cached by Node).
800
+ *
801
+ * Throws `ConfigError`: `CONFIG_LOAD_FAILED` when the import or the function throws (the error is
802
+ * the `cause`), `CONFIG_INVALID` when there is no default export or it doesn't give an object. The
803
+ * object's keys are checked by `resolveProject`.
804
+ * @public
805
+ */
806
+ async function loadConfigFile(path, env) {
807
+ const file = resolve(path);
808
+ let value = await importConfigModule(file);
809
+ if (typeof value === "function") try {
810
+ value = await value(env);
811
+ } catch (cause) {
812
+ throw new ConfigError("CONFIG_LOAD_FAILED", `the config function in "${file}" threw`, { cause });
813
+ }
814
+ if (!isRecord(value)) throw new ConfigError("CONFIG_INVALID", `the config file "${file}" must export an object, or a function that returns one (got ${describe(value)})`);
815
+ return value;
816
+ }
817
+ /**
818
+ * Loads the config file at `configPath` (made absolute against the working directory) and
819
+ * resolves it: `loadConfigFile` then `resolveProject`. `env` defaults to
820
+ * `{ command: 'run', mode: 'test' }`.
821
+ * @public
822
+ */
823
+ async function loadProject(configPath, options) {
824
+ const absolute = resolve(configPath);
825
+ const { env, ...resolveOptions } = options;
826
+ const input = await loadConfigFile(absolute, env ?? DEFAULT_ENV);
827
+ return resolveProject(input, {
828
+ ...resolveOptions,
829
+ configPath: absolute
830
+ });
831
+ }
832
+
833
+ // src/transform-cache.ts
834
+ /**
835
+ * `project` with its workers' transform cache directory set to `dir`, after `dir` is made ready:
836
+ * wiped when the project's lockfile is not the one it was filled under. When the wipe fails twice
837
+ * the project comes back without a `cacheDir` and a process warning says so. Never throws.
838
+ * `lockfiles`, shared by the projects of one run, holds each lockfile's hash by path.
839
+ * @public
840
+ */
841
+ function withTransformCache(project, dir, lockfiles) {
842
+ if (!prepareCache(dir, lockfileHash(project.rootDir, lockfiles))) {
843
+ process.emitWarning(`Provino could not clear the transform cache at ${dir}; this run uses no transform cache.`, { code: "PROVINO_TRANSFORM_CACHE_STALE" });
844
+ return project;
845
+ }
846
+ return {
847
+ ...project,
848
+ config: {
849
+ ...project.config,
850
+ loader: {
851
+ ...project.config.loader,
852
+ cacheDir: dir,
853
+ codeIdentity: transformCodeIdentity()
854
+ }
855
+ }
856
+ };
857
+ }
858
+ /**
859
+ * Evicts the oldest entries of the transform cache in `dir` down to its size cap (512 MB), unless
860
+ * no entry was written since the last time this ran. Never throws.
861
+ * @public
862
+ */
863
+ function pruneTransformCache(dir) {
864
+ pruneCacheIfWritten(dir);
865
+ }
866
+
867
+ export { ConfigError, formatConfigIssue, hasProvinoTag, interopDefault, loadConfigFile, loadProject, pruneTransformCache, resolveNeutralProject, resolveProject, withTransformCache };
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@provino/config",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Provino's config: loading a config file, selecting the dialect, and resolving a project's policy, globs, environment and isolation into the config its workers get.",
5
+ "homepage": "https://github.com/pixel-perfect-software/provino#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/pixel-perfect-software/provino/issues"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/pixel-perfect-software/provino.git",
12
+ "directory": "packages/config"
13
+ },
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "provino-source": "./src/index.ts",
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "engines": {
28
+ "node": "^22.15.0 || >=24"
29
+ },
30
+ "dependencies": {
31
+ "@provino/policy": "0.1.0-rc.1",
32
+ "@provino/transform": "0.1.0-rc.1",
33
+ "@provino/types": "0.1.0-rc.1"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown --config ../../tooling/packaging/tsdown.config.ts",
37
+ "test": "node --test --conditions=provino-source \"src/**/*.test.ts\""
38
+ }
6
39
  }