@provino/policy 0.0.0-stage → 0.1.0-rc.0

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/policy
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
+ The policy runtime: the neutral defaults, layering a dialect's values over them, `defineDialect`, loading behaviour by reference, serializing a policy for a worker and diffing two policies. A policy is a set of typed values for the places where Jest and Vitest behave differently.
4
+
5
+ This package is a building block of [Provino](https://github.com/pixel-perfect-software/provino), a test runner that is pre-alpha and not on npm yet. 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,35 @@
1
+ import { EnvironmentConditions, FormatEachTitle, FormatValue, GlobalSetupFailure, SnapshotKey } from "@provino/types";
2
+ /**
3
+ * Formats a `.each` title. `%s %d %i %f %j %o %O %p` take the row's values in order, `%#` is the
4
+ * row index, `%$` the 1-based row number and `%%` a percent sign. `$name` (or `$a.b`) reads a
5
+ * key of an object row. Strings print bare; other values print on one line as `util.inspect`
6
+ * does. A value `%j` can't encode (a cycle) prints as `[Circular]`, so a title never throws.
7
+ * @public
8
+ */
9
+ export declare const formatEachTitle: FormatEachTitle;
10
+ /**
11
+ * Prints a value on one line, as `util.inspect` does to a depth of 3, for a message the runtime
12
+ * builds. A string prints in quotes.
13
+ * @public
14
+ */
15
+ export declare const formatValue: FormatValue;
16
+ /**
17
+ * Reports a global hook that threw (`orchestrator.globalSetup.failure`): an `Error` that names the
18
+ * hook and its path and says what the hook threw, with the thrown value as its `cause`. The
19
+ * header is that message, and the frames below it are the thrown error's own, so none of the
20
+ * runner's shows.
21
+ * @public
22
+ */
23
+ export declare const globalSetupFailure: GlobalSetupFailure;
24
+ /**
25
+ * Names the `count`-th snapshot of a test: `` `${fullName} ${count}` ``.
26
+ * @public
27
+ */
28
+ export declare const snapshotKey: SnapshotKey;
29
+ /**
30
+ * Export conditions for an environment: the project's `customExportConditions` option when it is
31
+ * a list of strings, else the environment's own list, `['browser']` for the DOM environments,
32
+ * otherwise `['node']`.
33
+ * @public
34
+ */
35
+ export declare const environmentConditions: EnvironmentConditions;
@@ -0,0 +1,102 @@
1
+ import { inspect } from "node:util";
2
+
3
+ // src/behaviours.ts
4
+ const PLACEHOLDER = /%[%#$sdifjoOp]|\$([A-Za-z_]\w*(?:\.\w+)*)/g;
5
+ const DOM_ENVIRONMENTS = /* @__PURE__ */ new Set(["jsdom", "happy-dom"]);
6
+ const INSPECT = {
7
+ depth: 2,
8
+ breakLength: Infinity,
9
+ compact: true
10
+ };
11
+ /**
12
+ * Formats a `.each` title. `%s %d %i %f %j %o %O %p` take the row's values in order, `%#` is the
13
+ * row index, `%$` the 1-based row number and `%%` a percent sign. `$name` (or `$a.b`) reads a
14
+ * key of an object row. Strings print bare; other values print on one line as `util.inspect`
15
+ * does. A value `%j` can't encode (a cycle) prints as `[Circular]`, so a title never throws.
16
+ * @public
17
+ */
18
+ const formatEachTitle = (template, row, index) => {
19
+ const values = Array.isArray(row) ? row : [row];
20
+ let next = 0;
21
+ return template.replace(PLACEHOLDER, (match, path) => {
22
+ if (path !== void 0) return Array.isArray(row) ? match : show(readPath(row, path), "s");
23
+ const kind = match.slice(1);
24
+ if (kind === "%") return "%";
25
+ if (kind === "#") return String(index);
26
+ if (kind === "$") return String(index + 1);
27
+ if (next >= values.length) return match;
28
+ return show(values[next++], kind);
29
+ });
30
+ };
31
+ /**
32
+ * Prints a value on one line, as `util.inspect` does to a depth of 3, for a message the runtime
33
+ * builds. A string prints in quotes.
34
+ * @public
35
+ */
36
+ const formatValue = (value) => inspect(value, {
37
+ depth: 3,
38
+ breakLength: Infinity,
39
+ compact: true
40
+ });
41
+ /**
42
+ * Reports a global hook that threw (`orchestrator.globalSetup.failure`): an `Error` that names the
43
+ * hook and its path and says what the hook threw, with the thrown value as its `cause`. The
44
+ * header is that message, and the frames below it are the thrown error's own, so none of the
45
+ * runner's shows.
46
+ * @public
47
+ */
48
+ const globalSetupFailure = (thrown, { hook, path }) => {
49
+ const message = `${hook} ${path} failed: ${thrown instanceof Error ? thrown.message : formatValue(thrown)}`;
50
+ const error = new Error(message, { cause: thrown });
51
+ const frames = (thrown instanceof Error ? thrown.stack ?? "" : "").split("\n").filter((line) => /^\s+at /.test(line));
52
+ error.stack = [`Error: ${message}`, ...frames].join("\n");
53
+ return error;
54
+ };
55
+ /**
56
+ * Names the `count`-th snapshot of a test: `` `${fullName} ${count}` ``.
57
+ * @public
58
+ */
59
+ const snapshotKey = (fullName, count) => `${fullName} ${count}`;
60
+ /**
61
+ * Export conditions for an environment: the project's `customExportConditions` option when it is
62
+ * a list of strings, else the environment's own list, `['browser']` for the DOM environments,
63
+ * otherwise `['node']`.
64
+ * @public
65
+ */
66
+ const environmentConditions = (env) => {
67
+ const custom = env.options?.customExportConditions;
68
+ if (Array.isArray(custom) && custom.every((item) => typeof item === "string")) return custom;
69
+ return env.conditions ?? (DOM_ENVIRONMENTS.has(env.name) ? ["browser"] : ["node"]);
70
+ };
71
+ function readPath(row, path) {
72
+ let value = row;
73
+ for (const key of path.split(".")) {
74
+ if (value === null || typeof value !== "object") return void 0;
75
+ value = value[key];
76
+ }
77
+ return value;
78
+ }
79
+ function show(value, kind) {
80
+ switch (kind) {
81
+ case "s": return typeof value === "string" ? value : inspect(value, INSPECT);
82
+ case "d":
83
+ case "i":
84
+ case "f": {
85
+ if (typeof value === "bigint") return `${value}n`;
86
+ const n = typeof value === "symbol" ? NaN : Number(value);
87
+ return String(kind === "i" ? Math.trunc(n) : n);
88
+ }
89
+ case "j": return toJson(value);
90
+ default: return inspect(value, INSPECT);
91
+ }
92
+ }
93
+ function toJson(value) {
94
+ try {
95
+ return JSON.stringify(value, (_key, item) => typeof item === "bigint" ? `${item}n` : item) ?? "undefined";
96
+ } catch (err) {
97
+ if (err instanceof TypeError && /circular/i.test(err.message)) return "[Circular]";
98
+ throw err;
99
+ }
100
+ }
101
+
102
+ export { environmentConditions, formatEachTitle, formatValue, globalSetupFailure, snapshotKey };
@@ -0,0 +1,159 @@
1
+ import { AnyFunction, Behaviour, DefineHoistPolicy, Dialect, ModuleRef, Policy, PolicyOverrides, SerializedPolicy } from "@provino/types";
2
+ /**
3
+ * Imports a module by specifier and returns its namespace.
4
+ * @public
5
+ */
6
+ type ModuleImporter = (specifier: string) => Promise<ModuleNamespace>;
7
+ /**
8
+ * A module's exports by name.
9
+ * @public
10
+ */
11
+ type ModuleNamespace = Readonly<Record<string, unknown>>;
12
+ /**
13
+ * Loads behaviour keys. A worker owns one loader (in its worker context), so each `ModuleRef`'s
14
+ * module is imported once per worker however often it is called.
15
+ * @public
16
+ */
17
+ interface BehaviourLoader {
18
+ /** Returns the function a behaviour key holds, importing its module the first time. */
19
+ load<Fn extends AnyFunction>(behaviour: Behaviour<Fn>): Promise<Fn>;
20
+ }
21
+ /**
22
+ * Options for `createBehaviourLoader`.
23
+ * @public
24
+ */
25
+ interface BehaviourLoaderOptions {
26
+ /**
27
+ * How modules are imported. Default: `import()`, with absolute paths turned into `file:` URLs.
28
+ * Bare specifiers then resolve from `@provino/policy`, so pass absolute refs for user modules.
29
+ */
30
+ readonly importModule?: ModuleImporter;
31
+ }
32
+ /**
33
+ * Creates a behaviour loader with its own module cache.
34
+ * @public
35
+ */
36
+ export declare function createBehaviourLoader(options?: BehaviourLoaderOptions): BehaviourLoader;
37
+ /**
38
+ * Calls a behaviour key with `args`: a closure directly, a `ModuleRef` after `loader` has
39
+ * imported it (once per loader).
40
+ * @public
41
+ */
42
+ export declare function callBehaviour<Args extends readonly unknown[], Result>(loader: BehaviourLoader, behaviour: Behaviour<(...args: Args) => Result>, ...args: Args): Promise<Awaited<Result>>;
43
+ /**
44
+ * Defines a dialect's mock-hoisting policy, keeping the literal names of its hoisted calls and
45
+ * values so a typo in adapter code is a compile error (Track 3 L563). The value is returned
46
+ * unchanged.
47
+ * @public
48
+ */
49
+ export declare const defineHoistPolicy: DefineHoistPolicy;
50
+ /**
51
+ * Defines a dialect, keeping its name as a literal type. Under `isolatedDeclarations`, annotate
52
+ * the export: `export const jest: Dialect<'jest', JestOptions> = defineDialect({...})`.
53
+ * @public
54
+ */
55
+ export declare function defineDialect<const Name extends string, Options = undefined>(dialect: Dialect<Name, Options>): Dialect<Name, Options>;
56
+ /**
57
+ * One policy key whose value differs between two policies.
58
+ * @public
59
+ */
60
+ interface PolicyDifference {
61
+ /** The key, e.g. `core.hookOrder.afterAll`. */
62
+ readonly path: string;
63
+ readonly a: unknown;
64
+ readonly b: unknown;
65
+ }
66
+ /**
67
+ * Lists every key whose value differs between two policies, in key order. Groups of keys are
68
+ * compared key by key; other values (arrays, refs, RegExps) are compared whole, and closures by
69
+ * identity.
70
+ * @public
71
+ */
72
+ export declare function diffPolicy(a: Policy, b: Policy): readonly PolicyDifference[];
73
+ /**
74
+ * Prints `diffPolicy` rows as an aligned key-by-key table, one line per key.
75
+ * @public
76
+ */
77
+ export declare function formatPolicyDiff(rows: readonly PolicyDifference[], labels?: readonly [string, string]): string;
78
+ /**
79
+ * Stable codes for policy errors, so callers and tests assert on the code, not the text.
80
+ * @public
81
+ */
82
+ type PolicyErrorCode = "POLICY_UNKNOWN_KEY" | "POLICY_INVALID_LAYER" | "POLICY_CLOSURE_NOT_SERIALIZABLE" | "POLICY_BEHAVIOUR_LOAD_FAILED" | "POLICY_BEHAVIOUR_NOT_FUNCTION";
83
+ /**
84
+ * An error from `@provino/policy`. `path` is the policy key it concerns (`core.hookOrder`), when
85
+ * there is one. `structuredClone` keeps only `name`, `message`, `stack` and `cause`, so a worker
86
+ * sends it to the coordinator as a serialized error record that carries `code` and `path` (the
87
+ * RPC layer's `SerializedError`, B09), not as this class.
88
+ * @public
89
+ */
90
+ export declare class PolicyError extends Error {
91
+ override readonly name = "PolicyError";
92
+ readonly code: PolicyErrorCode;
93
+ readonly path: string | undefined;
94
+ constructor(code: PolicyErrorCode, message: string, options?: {
95
+ readonly path?: string;
96
+ readonly cause?: unknown;
97
+ });
98
+ }
99
+ /**
100
+ * Whether a value is a `ModuleRef`: a plain object with string `module` and `export` and no other
101
+ * own keys. Re-exported publicly from `module-ref.ts`.
102
+ * @public
103
+ */
104
+ export declare function isModuleRef(value: unknown): value is ModuleRef;
105
+ /**
106
+ * Builds a `ModuleRef`. Pass an absolute path, a `file:` URL (`import.meta.resolve('./x.ts')`) or
107
+ * a package specifier `@provino/policy` can resolve.
108
+ * @public
109
+ */
110
+ export declare function moduleRef<Fn extends AnyFunction>(module: string, exportName: string): ModuleRef<Fn>;
111
+ /**
112
+ * Whether a worker can import `location` as it is (D21): an absolute path or a URL (`file:`,
113
+ * `data:`, `node:`). A bare package specifier or a relative path would resolve from the worker's
114
+ * own location, not the project's.
115
+ * @public
116
+ */
117
+ export declare function isImportableLocation(location: string): boolean;
118
+ /**
119
+ * Calls `visit` with each ref found in `value` and its key path, which starts at `path` and is
120
+ * dotted (`policy.core.formatEachTitle`), with an index for an array item (`list[0]`). A ref is
121
+ * what `isRef` says it is (a `ModuleRef`, by default) and is not searched further. `seen` stops a
122
+ * cyclic value, which structured clone can carry, from looping.
123
+ * @public
124
+ */
125
+ export declare function forEachModuleRef(value: unknown, path: string, visit: (ref: ModuleRef, path: string) => void): void;
126
+ export declare function forEachModuleRef<Ref>(value: unknown, path: string, visit: (ref: Ref, path: string) => void, isRef: (value: unknown) => value is Ref): void;
127
+ /**
128
+ * The neutral dialect's policy: what Provino does with no dialect, and the base every layer
129
+ * overrides. These are Provino's own choices, not Jest's or Vitest's ("better by default",
130
+ * DECISIONS D7): mistakes fail loudly, state doesn't leak between tests, setup and teardown are
131
+ * symmetric, and ESM semantics come first. `neutral.test.ts` pins the choices that matter most;
132
+ * a comment beside a value gives its reason where it isn't obvious.
133
+ * @public
134
+ */
135
+ export declare const neutralPolicy: Policy;
136
+ /**
137
+ * Resolves policy layers over `neutralPolicy`, lowest first: `resolvePolicy(dialect, project,
138
+ * facade)`. Groups of keys merge key by key. Every other value (an array, a record, a
139
+ * `ModuleRef`, a function, a primitive) replaces the lower layer's value whole. The result is a
140
+ * new, deeply frozen policy; layers are copied, never frozen or changed.
141
+ *
142
+ * Checks keys and shape, not leaf types: `POLICY_UNKNOWN_KEY` for a key the policy doesn't have,
143
+ * `POLICY_INVALID_LAYER` for a value where a group belongs or a group where a value belongs.
144
+ * A wrong leaf type (`maxConcurrency: 'lots'`) gets through, so config readers validate values
145
+ * before layering them (T1.4).
146
+ * @public
147
+ */
148
+ export declare function resolvePolicy(...layers: readonly (PolicyOverrides | undefined)[]): Policy;
149
+ /**
150
+ * Turns a policy into what crosses coordinator → worker: data keys as they are, behaviour keys as
151
+ * plain `{ module, export }` refs. The result survives `structuredClone`.
152
+ *
153
+ * A closure in a behaviour key can't cross a thread, and dropping it would leave the worker
154
+ * without that behaviour, so it throws `PolicyError` `POLICY_CLOSURE_NOT_SERIALIZABLE` naming the
155
+ * key. Give behaviour that runs in workers as a `ModuleRef`.
156
+ * @public
157
+ */
158
+ export declare function serializePolicy(policy: Policy): SerializedPolicy;
159
+ export type { BehaviourLoader, BehaviourLoaderOptions, ModuleImporter, ModuleNamespace, PolicyDifference, PolicyErrorCode };
package/dist/index.js ADDED
@@ -0,0 +1,634 @@
1
+ import { isAbsolute } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { inspect, isDeepStrictEqual } from "node:util";
4
+
5
+ // src/errors.ts
6
+ /**
7
+ * An error from `@provino/policy`. `path` is the policy key it concerns (`core.hookOrder`), when
8
+ * there is one. `structuredClone` keeps only `name`, `message`, `stack` and `cause`, so a worker
9
+ * sends it to the coordinator as a serialized error record that carries `code` and `path` (the
10
+ * RPC layer's `SerializedError`, B09), not as this class.
11
+ * @public
12
+ */
13
+ var PolicyError = class extends Error {
14
+ name = "PolicyError";
15
+ code;
16
+ path;
17
+ constructor(code, message, options) {
18
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
19
+ this.code = code;
20
+ this.path = options?.path;
21
+ }
22
+ };
23
+
24
+ // src/behaviour-loader.ts
25
+ const defaultImporter = (specifier) => isAbsolute(specifier) ? import(pathToFileURL(specifier).href) : import(specifier);
26
+ /**
27
+ * Creates a behaviour loader with its own module cache.
28
+ * @public
29
+ */
30
+ function createBehaviourLoader(options = {}) {
31
+ const importModule = options.importModule ?? defaultImporter;
32
+ const modules = /* @__PURE__ */ new Map();
33
+ function importOnce(specifier) {
34
+ let pending = modules.get(specifier);
35
+ if (pending === void 0) {
36
+ pending = importModule(specifier);
37
+ pending.catch(() => modules.delete(specifier));
38
+ modules.set(specifier, pending);
39
+ }
40
+ return pending;
41
+ }
42
+ async function loadRef(ref) {
43
+ if (ref.module.startsWith("./") || ref.module.startsWith("../")) throw new PolicyError("POLICY_BEHAVIOUR_LOAD_FAILED", `"${ref.module}" is relative; build refs with import.meta.resolve()`);
44
+ let namespace;
45
+ try {
46
+ namespace = await importOnce(ref.module);
47
+ } catch (cause) {
48
+ throw new PolicyError("POLICY_BEHAVIOUR_LOAD_FAILED", `can't import "${ref.module}"`, { cause });
49
+ }
50
+ const fn = namespace[ref.export];
51
+ if (typeof fn !== "function") throw new PolicyError("POLICY_BEHAVIOUR_NOT_FUNCTION", `"${ref.module}" has no function export "${ref.export}"`);
52
+ return fn;
53
+ }
54
+ return { async load(behaviour) {
55
+ if (typeof behaviour === "function") return behaviour;
56
+ if (behaviour === null || typeof behaviour !== "object") throw new PolicyError("POLICY_BEHAVIOUR_NOT_FUNCTION", `not a behaviour: ${String(behaviour)}`);
57
+ return loadRef(behaviour);
58
+ } };
59
+ }
60
+ /**
61
+ * Calls a behaviour key with `args`: a closure directly, a `ModuleRef` after `loader` has
62
+ * imported it (once per loader).
63
+ * @public
64
+ */
65
+ async function callBehaviour(loader, behaviour, ...args) {
66
+ return await (await loader.load(behaviour))(...args);
67
+ }
68
+
69
+ // src/dialect.ts
70
+ /**
71
+ * Defines a dialect's mock-hoisting policy, keeping the literal names of its hoisted calls and
72
+ * values so a typo in adapter code is a compile error (Track 3 L563). The value is returned
73
+ * unchanged.
74
+ * @public
75
+ */
76
+ const defineHoistPolicy = (policy) => policy;
77
+ /**
78
+ * Defines a dialect, keeping its name as a literal type. Under `isolatedDeclarations`, annotate
79
+ * the export: `export const jest: Dialect<'jest', JestOptions> = defineDialect({...})`.
80
+ * @public
81
+ */
82
+ function defineDialect(dialect) {
83
+ return dialect;
84
+ }
85
+
86
+ // src/internal/objects.ts
87
+ /** @internal */
88
+ function isPlainObject(value) {
89
+ if (value === null || typeof value !== "object") return false;
90
+ const proto = Object.getPrototypeOf(value);
91
+ return proto === Object.prototype || proto === null;
92
+ }
93
+ /**
94
+ * Whether a value is a `ModuleRef`: a plain object with string `module` and `export` and no other
95
+ * own keys. Re-exported publicly from `module-ref.ts`.
96
+ * @public
97
+ */
98
+ function isModuleRef(value) {
99
+ return isPlainObject(value) && Object.keys(value).length === 2 && typeof value.module === "string" && typeof value.export === "string";
100
+ }
101
+ /**
102
+ * Whether a value is a group of policy keys: a plain object that isn't a `ModuleRef`.
103
+ * @internal
104
+ */
105
+ function isGroup(value) {
106
+ return isPlainObject(value) && !isModuleRef(value);
107
+ }
108
+ /**
109
+ * Copies plain objects and arrays all the way down, so a result never aliases a caller's value.
110
+ * Other values (functions, RegExps, primitives) are shared as they are.
111
+ * @internal
112
+ */
113
+ function copyValue(value) {
114
+ if (Array.isArray(value)) return value.map(copyValue);
115
+ if (!isPlainObject(value)) return value;
116
+ const out = {};
117
+ for (const [key, item] of Object.entries(value)) Object.defineProperty(out, key, {
118
+ value: copyValue(item),
119
+ enumerable: true,
120
+ writable: true,
121
+ configurable: true
122
+ });
123
+ return out;
124
+ }
125
+ /**
126
+ * Freezes plain objects and arrays all the way down. Other objects (RegExp, Map, …) are left
127
+ * as they are.
128
+ * @internal
129
+ */
130
+ function deepFreeze(value) {
131
+ if (Array.isArray(value)) {
132
+ for (const item of value) deepFreeze(item);
133
+ Object.freeze(value);
134
+ } else if (isPlainObject(value)) {
135
+ for (const item of Object.values(value)) deepFreeze(item);
136
+ Object.freeze(value);
137
+ }
138
+ return value;
139
+ }
140
+ /** @internal */
141
+ function joinPath(parent, key) {
142
+ return parent === "" ? key : `${parent}.${key}`;
143
+ }
144
+
145
+ // src/diff.ts
146
+ /**
147
+ * Lists every key whose value differs between two policies, in key order. Groups of keys are
148
+ * compared key by key; other values (arrays, refs, RegExps) are compared whole, and closures by
149
+ * identity.
150
+ * @public
151
+ */
152
+ function diffPolicy(a, b) {
153
+ const out = [];
154
+ walk$1(a, b, "", out);
155
+ return out;
156
+ }
157
+ function walk$1(a, b, path, out) {
158
+ if (isGroup(a) && isGroup(b)) {
159
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
160
+ for (const key of [...keys].sort()) walk$1(a[key], b[key], joinPath(path, key), out);
161
+ return;
162
+ }
163
+ if (!isDeepStrictEqual(a, b)) out.push({
164
+ path,
165
+ a,
166
+ b
167
+ });
168
+ }
169
+ /**
170
+ * Prints `diffPolicy` rows as an aligned key-by-key table, one line per key.
171
+ * @public
172
+ */
173
+ function formatPolicyDiff(rows, labels = ["a", "b"]) {
174
+ const table = [["key", ...labels], ...rows.map((row) => [
175
+ row.path,
176
+ show(row.a),
177
+ show(row.b)
178
+ ])];
179
+ const keyWidth = Math.max(...table.map(([key]) => key.length));
180
+ const aWidth = Math.max(...table.map(([, a]) => a.length));
181
+ return table.map(([key, a, b]) => `${key.padEnd(keyWidth)} ${a.padEnd(aWidth)} ${b}`.trimEnd()).join("\n");
182
+ }
183
+ function show(value) {
184
+ if (typeof value === "function") return `[closure ${value.name || "anonymous"}]`;
185
+ return inspect(value, {
186
+ depth: 4,
187
+ breakLength: Infinity,
188
+ compact: true
189
+ });
190
+ }
191
+
192
+ // src/module-ref.ts
193
+ /**
194
+ * Builds a `ModuleRef`. Pass an absolute path, a `file:` URL (`import.meta.resolve('./x.ts')`) or
195
+ * a package specifier `@provino/policy` can resolve.
196
+ * @public
197
+ */
198
+ function moduleRef(module, exportName) {
199
+ return Object.freeze({
200
+ module,
201
+ export: exportName
202
+ });
203
+ }
204
+ /**
205
+ * Whether a worker can import `location` as it is (D21): an absolute path or a URL (`file:`,
206
+ * `data:`, `node:`). A bare package specifier or a relative path would resolve from the worker's
207
+ * own location, not the project's.
208
+ * @public
209
+ */
210
+ function isImportableLocation(location) {
211
+ return isAbsolute(location) || URL.canParse(location);
212
+ }
213
+ function forEachModuleRef(value, path, visit, isRef = isModuleRef) {
214
+ walk(value, path, visit, isRef, /* @__PURE__ */ new Set());
215
+ }
216
+ function walk(value, path, visit, isRef, seen) {
217
+ if (isRef(value)) {
218
+ visit(value, path);
219
+ return;
220
+ }
221
+ if (typeof value !== "object" || value === null || seen.has(value)) return;
222
+ seen.add(value);
223
+ if (Array.isArray(value)) {
224
+ value.forEach((item, index) => {
225
+ walk(item, `${path}[${index}]`, visit, isRef, seen);
226
+ });
227
+ return;
228
+ }
229
+ for (const [key, item] of Object.entries(value)) walk(item, `${path}.${key}`, visit, isRef, seen);
230
+ }
231
+
232
+ // src/neutral.ts
233
+ /**
234
+ * Where the neutral behaviours live, as an absolute `file:` URL (D21: a ref that crosses to a worker
235
+ * is absolute, so nothing depends on where the worker resolves from). The package names itself
236
+ * through its own `exports`, which works in source (`--conditions=provino-source`) and once built.
237
+ */
238
+ const BEHAVIOURS = import.meta.resolve("@provino/policy/behaviours");
239
+ /**
240
+ * The neutral dialect's policy: what Provino does with no dialect, and the base every layer
241
+ * overrides. These are Provino's own choices, not Jest's or Vitest's ("better by default",
242
+ * DECISIONS D7): mistakes fail loudly, state doesn't leak between tests, setup and teardown are
243
+ * symmetric, and ESM semantics come first. `neutral.test.ts` pins the choices that matter most;
244
+ * a comment beside a value gives its reason where it isn't obvious.
245
+ * @public
246
+ */
247
+ const neutralPolicy = deepFreeze({
248
+ core: {
249
+ hookOrder: {
250
+ beforeAll: "declaration",
251
+ beforeEach: "declaration",
252
+ afterEach: "reverse",
253
+ afterAll: "reverse"
254
+ },
255
+ eachHooksForConcurrent: true,
256
+ firstArg: "context",
257
+ allowGeneratorFns: false,
258
+ timeouts: {
259
+ test: 5e3,
260
+ hook: 1e4,
261
+ teardown: 1e4,
262
+ catchSyncOverrun: true,
263
+ zero: "none"
264
+ },
265
+ nameSeparator: " > ",
266
+ testNamePatternFlags: "",
267
+ missingTestFn: "todo",
268
+ asyncDescribe: "throw",
269
+ nonPromiseReturn: "fail",
270
+ formatEachTitle: moduleRef(BEHAVIOURS, "formatEachTitle"),
271
+ formatValue: moduleRef(BEHAVIOURS, "formatValue"),
272
+ eachTitleTruncate: null,
273
+ retry: {
274
+ timing: "immediate",
275
+ keepEarlierErrors: true,
276
+ functionCondition: "call",
277
+ functionConditionWarning: "every failure is retried instead. Pass a RegExp (tested against the error message) to limit the retries."
278
+ },
279
+ allowOnly: "not-in-ci",
280
+ maxConcurrency: 5,
281
+ unawaitedAsyncAssertion: "fail",
282
+ hookReturnsCleanup: true,
283
+ injectGlobals: false,
284
+ globalsBeforeSetupFiles: "all",
285
+ doneDeprecatedMessage: null,
286
+ collect: {
287
+ describeBody: "immediate",
288
+ describeReturnValue: "error",
289
+ lateRegistration: "fail-file",
290
+ emptyDescribe: "allow",
291
+ nestedInTest: "throw",
292
+ todoWithFn: "todo",
293
+ eachTableError: "failing-test"
294
+ },
295
+ hooks: {
296
+ afterError: "continue",
297
+ beforeAllError: "attach-to-tests",
298
+ nestedHooksAfterBeforeAllError: "skip",
299
+ afterAllError: "fail-suite",
300
+ timeoutCountsTestTimeout: false,
301
+ skippedBlock: "none"
302
+ },
303
+ concurrency: {
304
+ grouping: "consecutive",
305
+ limitHooks: true
306
+ },
307
+ errors: {
308
+ lateErrors: "fail-owner",
309
+ processListeners: "alongside",
310
+ waitForUnhandledRejections: false,
311
+ hasAssertionsWhenFailed: "skip"
312
+ },
313
+ focus: {
314
+ scope: "file",
315
+ insideSkip: "skipped"
316
+ },
317
+ status: {
318
+ todoUnderSkip: "todo",
319
+ expectFail: "body"
320
+ },
321
+ locationFrame: "test-file",
322
+ orderHooks: null,
323
+ shuffle: null,
324
+ shapeTestError: null,
325
+ boundaryTurns: {
326
+ hookStart: 0,
327
+ hookEnd: 0,
328
+ fnStart: 0,
329
+ fnEnd: 0,
330
+ testStart: 0,
331
+ testEnd: 0,
332
+ skippedTest: 0,
333
+ suiteStart: 0,
334
+ suiteEnd: 0,
335
+ runStart: 0,
336
+ retry: 0,
337
+ retryEnd: 0,
338
+ retryExit: 0
339
+ }
340
+ },
341
+ lazy: { readInBeforeAll: "error" },
342
+ mock: {
343
+ resetTo: "original-impl",
344
+ defaultName: "fn()",
345
+ between: {
346
+ order: [
347
+ "restore",
348
+ "reset",
349
+ "clear",
350
+ "unstubEnvs",
351
+ "unstubGlobals"
352
+ ],
353
+ clear: true,
354
+ reset: false,
355
+ restore: true,
356
+ unstubEnvs: true,
357
+ unstubGlobals: true
358
+ },
359
+ classMockPrototype: "chain-to-impl",
360
+ spyNameFromMethod: true,
361
+ functionName: "impl-or-Mock",
362
+ newCall: "construct",
363
+ valueShorthandsThrowOnNew: true,
364
+ fnOfMockReturnsSame: true,
365
+ copyStaticProps: true,
366
+ settledResults: true,
367
+ lastCallKey: "always",
368
+ clearReplacesStateObject: false,
369
+ mockPropertyWritable: false,
370
+ withImplementationReturnsMock: true,
371
+ getImplPrefersOnce: true,
372
+ spyReportsBridgeImpl: false,
373
+ isMockAcceptsObjects: false,
374
+ spyInstall: "define",
375
+ messages: {}
376
+ },
377
+ timers: {
378
+ toFakeDefault: "all-but-microtasks",
379
+ loopLimit: 1e4,
380
+ fakeTemporal: true,
381
+ legacyAvailable: false,
382
+ enableGlobally: false,
383
+ optionNames: "to-fake",
384
+ notFaked: "throw",
385
+ setSystemTimeWithoutFakes: "fake-date-only",
386
+ advanceToNextTimerHonorsSteps: true,
387
+ facadeReturns: "all",
388
+ messages: { notFaked: "A function to advance timers was called but the timers APIs are not replaced with fake timers. Call `useFakeTimers()` first." }
389
+ },
390
+ module: {
391
+ factoryShape: "namespace",
392
+ rootMocksAutoApply: false,
393
+ automock: false,
394
+ actual: "async-import",
395
+ resetModulesBetween: false,
396
+ injectCjsGlobals: true,
397
+ interopDefault: "babel",
398
+ resetModulesClearsMocks: false,
399
+ awaitFactory: true,
400
+ missingFactoryExport: "throw",
401
+ requireVirtualFlag: false,
402
+ virtualRelative: true,
403
+ mockValueOwner: "registration",
404
+ mockResolveKind: "import",
405
+ edgeResolveKind: "as-written",
406
+ moduleSyncCondition: "never",
407
+ mocksReachShared: true,
408
+ reevaluateHookingExternals: false,
409
+ reevaluatePatchingExternals: false,
410
+ stackFrameNames: "engine",
411
+ nativeLoadPatches: "apply",
412
+ automockShape: "deep",
413
+ unmockedPathPatterns: [],
414
+ messages: {},
415
+ mapperMiss: null
416
+ },
417
+ snapshot: {
418
+ header: "// Provino Snapshot v1",
419
+ key: moduleRef(BEHAVIOURS, "snapshotKey"),
420
+ keyJoin: " > ",
421
+ hintJoin: ": ",
422
+ dirName: "__snapshots__",
423
+ extension: ".snap",
424
+ format: {
425
+ escapeString: false,
426
+ printBasicPrototype: false,
427
+ maxOutputLength: null,
428
+ extra: {}
429
+ },
430
+ serializers: [],
431
+ obsolete: {
432
+ failLocal: false,
433
+ failCI: true
434
+ },
435
+ obsoleteFiles: "ignore",
436
+ ciUpdate: "none",
437
+ updateEnvVar: null,
438
+ throwErrorBody: "message",
439
+ inline: {
440
+ indent: "call",
441
+ formatter: "none",
442
+ writer: null,
443
+ prettierPath: null
444
+ },
445
+ printer: null,
446
+ resolvePath: null,
447
+ resolverFactory: null,
448
+ contextView: null
449
+ },
450
+ expect: {
451
+ matcherNamespace: "provino",
452
+ pollFailsOnTimeout: true,
453
+ diffContextLines: 5,
454
+ valueFormatter: "pretty-format",
455
+ matcherTable: null,
456
+ outsideTestCounts: "drop",
457
+ errorShape: "assertion-error",
458
+ equality: {
459
+ errors: "assert",
460
+ invalidDate: "equal"
461
+ },
462
+ soft: true,
463
+ poll: {
464
+ enabled: true,
465
+ intervalMs: 50,
466
+ timeoutMs: 1e3
467
+ },
468
+ requireAssertions: false,
469
+ expand: false
470
+ },
471
+ orchestrator: {
472
+ include: ["**/*.{test,spec}.?(c|m)[jt]s?(x)"],
473
+ exclude: ["**/node_modules/**", "**/dist/**"],
474
+ bail: { checkAfter: "test" },
475
+ watchDefault: "never",
476
+ watch: {
477
+ initialRun: "all",
478
+ interruptedFiles: "report"
479
+ },
480
+ changedFiles: null,
481
+ affected: {
482
+ extractor: null,
483
+ mockEdges: {
484
+ dir: "__mocks__",
485
+ adjacent: true,
486
+ byName: false
487
+ },
488
+ invalidateAll: "project-inputs",
489
+ graph: "recorded-then-static",
490
+ conditions: "environment"
491
+ },
492
+ globMatchesOn: "root-relative-path",
493
+ todoOnlyFile: "skip",
494
+ noTestsFile: "fail-unless-pass-with-no-tests",
495
+ consoleOrigin: "none",
496
+ processObject: "per-file",
497
+ passWithNoTests: false,
498
+ exitCodes: {
499
+ failure: 1,
500
+ noTests: 1,
501
+ unhandled: 1,
502
+ usage: 2
503
+ },
504
+ unhandledErrors: "fail-run",
505
+ coverageProvider: "v8",
506
+ coverageReporters: [
507
+ "text",
508
+ "html",
509
+ "json"
510
+ ],
511
+ slowTestThresholdMs: 300,
512
+ isolationDefault: {
513
+ default: "registry",
514
+ byEnvironment: {
515
+ jsdom: "realm",
516
+ "happy-dom": "realm"
517
+ }
518
+ },
519
+ envDefault: "node",
520
+ environmentPragmas: ["provino-environment"],
521
+ environmentConditions: moduleRef(BEHAVIOURS, "environmentConditions"),
522
+ pool: { default: "forks" },
523
+ inBand: {
524
+ single: false,
525
+ fastFileCount: 0,
526
+ slowMs: 0
527
+ },
528
+ shard: { fallback: "path-slice" },
529
+ sequence: { unknownFirst: true },
530
+ globalSetup: {
531
+ signature: "project-with-teardown",
532
+ teardownOrder: "reverse",
533
+ failure: moduleRef(BEHAVIOURS, "globalSetupFailure")
534
+ }
535
+ },
536
+ report: {
537
+ displaySeparator: " > ",
538
+ defaultReporters: ["default"],
539
+ failureTitleBullet: null,
540
+ listTestsForSingleFile: false,
541
+ resultStatusSkipped: "skipped"
542
+ },
543
+ coverage: {
544
+ thresholdGrouping: "all-files",
545
+ globThresholdScope: "aggregate",
546
+ includeUntestedByDefault: true,
547
+ reportsDirectory: "coverage",
548
+ v8Conversion: "ast",
549
+ v8HitCounts: false,
550
+ v8Hashbang: "kept",
551
+ istanbulVariable: "__coverage__",
552
+ thresholdMessages: {
553
+ belowMinimum: "Coverage for {metric} ({actual}%) does not meet \"{name}\" threshold ({threshold}%)",
554
+ aboveMaximumUncovered: "Uncovered count for {metric} ({actual}) exceeds {name} threshold ({threshold})",
555
+ notFound: "Coverage data for {path} was not found."
556
+ }
557
+ }
558
+ });
559
+
560
+ // src/resolve.ts
561
+ const RECORDS = /* @__PURE__ */ new Set([
562
+ "mock.messages",
563
+ "module.messages",
564
+ "orchestrator.isolationDefault.byEnvironment",
565
+ "snapshot.format.extra"
566
+ ]);
567
+ /**
568
+ * Resolves policy layers over `neutralPolicy`, lowest first: `resolvePolicy(dialect, project,
569
+ * facade)`. Groups of keys merge key by key. Every other value (an array, a record, a
570
+ * `ModuleRef`, a function, a primitive) replaces the lower layer's value whole. The result is a
571
+ * new, deeply frozen policy; layers are copied, never frozen or changed.
572
+ *
573
+ * Checks keys and shape, not leaf types: `POLICY_UNKNOWN_KEY` for a key the policy doesn't have,
574
+ * `POLICY_INVALID_LAYER` for a value where a group belongs or a group where a value belongs.
575
+ * A wrong leaf type (`maxConcurrency: 'lots'`) gets through, so config readers validate values
576
+ * before layering them (T1.4).
577
+ * @public
578
+ */
579
+ function resolvePolicy(...layers) {
580
+ let resolved = neutralPolicy;
581
+ for (const layer of layers) if (layer !== void 0) resolved = merge(resolved, layer, "");
582
+ return deepFreeze(resolved);
583
+ }
584
+ function merge(base, layer, path) {
585
+ if (RECORDS.has(path)) {
586
+ if (!isPlainObject(layer)) throw invalid(path, "a record; a layer must give it an object");
587
+ return copyValue(layer);
588
+ }
589
+ if (!isGroup(base)) {
590
+ if (isGroup(layer)) throw invalid(path, "a value; a layer must not give it a group of keys");
591
+ return copyValue(layer);
592
+ }
593
+ if (!isGroup(layer)) throw invalid(path, "a group of keys; a layer must give it an object");
594
+ const out = { ...base };
595
+ for (const [key, value] of Object.entries(layer)) {
596
+ const keyPath = joinPath(path, key);
597
+ if (!Object.hasOwn(base, key)) throw new PolicyError("POLICY_UNKNOWN_KEY", `unknown policy key "${keyPath}"`, { path: keyPath });
598
+ if (value !== void 0) out[key] = merge(base[key], value, keyPath);
599
+ }
600
+ return out;
601
+ }
602
+ function invalid(path, what) {
603
+ return new PolicyError("POLICY_INVALID_LAYER", `policy key "${path}" is ${what}`, { path });
604
+ }
605
+
606
+ // src/serialize.ts
607
+ /**
608
+ * Turns a policy into what crosses coordinator → worker: data keys as they are, behaviour keys as
609
+ * plain `{ module, export }` refs. The result survives `structuredClone`.
610
+ *
611
+ * A closure in a behaviour key can't cross a thread, and dropping it would leave the worker
612
+ * without that behaviour, so it throws `PolicyError` `POLICY_CLOSURE_NOT_SERIALIZABLE` naming the
613
+ * key. Give behaviour that runs in workers as a `ModuleRef`.
614
+ * @public
615
+ */
616
+ function serializePolicy(policy) {
617
+ return deepFreeze(serialize(policy, ""));
618
+ }
619
+ function serialize(value, path) {
620
+ if (typeof value === "function") throw new PolicyError("POLICY_CLOSURE_NOT_SERIALIZABLE", `policy key "${path}" is a closure, which can't cross to a worker; give it as a ModuleRef`, { path });
621
+ if (isModuleRef(value)) return {
622
+ module: value.module,
623
+ export: value.export
624
+ };
625
+ if (Array.isArray(value)) return value.map((item, i) => serialize(item, `${path}[${i}]`));
626
+ if (isPlainObject(value)) {
627
+ const out = {};
628
+ for (const [key, item] of Object.entries(value)) out[key] = serialize(item, joinPath(path, key));
629
+ return out;
630
+ }
631
+ return value;
632
+ }
633
+
634
+ export { PolicyError, callBehaviour, createBehaviourLoader, defineDialect, defineHoistPolicy, diffPolicy, forEachModuleRef, formatPolicyDiff, isImportableLocation, isModuleRef, moduleRef, neutralPolicy, resolvePolicy, serializePolicy };
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@provino/policy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-rc.0",
4
+ "description": "Provino's policy runtime: neutral defaults, layer resolution, dialect definitions, behaviour loading, serialization and policy diffs.",
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/policy"
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
+ "./behaviours": {
24
+ "provino-source": "./src/behaviours.ts",
25
+ "types": "./dist/behaviours.d.ts",
26
+ "import": "./dist/behaviours.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "engines": {
33
+ "node": "^22.15.0 || >=24"
34
+ },
35
+ "dependencies": {
36
+ "@provino/types": "0.1.0-rc.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsdown --config ../../tooling/packaging/tsdown.config.ts",
40
+ "test": "node --test --conditions=provino-source \"src/**/*.test.ts\""
41
+ }
6
42
  }