tslaws 0.10.0 → 1.0.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/README.md +7 -2
- package/bin/tslaws.js +8 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +25 -5
- package/dist/bundled.js +2 -2
- package/dist/bundlerPlugins.d.ts +2 -0
- package/dist/bundlerPlugins.js +7 -0
- package/dist/certificates.d.ts +139 -0
- package/dist/certificates.js +433 -0
- package/dist/chc.d.ts +85 -0
- package/dist/chc.js +298 -0
- package/dist/check.d.ts +13 -1
- package/dist/check.js +211 -27
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +175 -34
- package/dist/compile.d.ts +15 -5
- package/dist/compile.js +198 -69
- package/dist/coverage.d.ts +38 -1
- package/dist/coverage.js +94 -12
- package/dist/e2eApi.js +3 -1
- package/dist/generators.js +12 -2
- package/dist/github.d.ts +49 -5
- package/dist/github.js +107 -24
- package/dist/githubCli.d.ts +28 -0
- package/dist/githubCli.js +1039 -211
- package/dist/hints.js +2 -1
- package/dist/init.js +42 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +262 -0
- package/dist/isolatedCheck.d.ts +1 -0
- package/dist/isolatedCheck.js +16 -0
- package/dist/lawHost.d.ts +50 -0
- package/dist/lawHost.js +199 -0
- package/dist/lawRuntime.d.ts +39 -0
- package/dist/lawRuntime.js +242 -0
- package/dist/lock.d.ts +49 -9
- package/dist/lock.js +132 -21
- package/dist/mcp.js +28 -7
- package/dist/mutate.d.ts +4 -0
- package/dist/mutate.js +7 -1
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +4 -0
- package/dist/pluginHooks.d.ts +16 -0
- package/dist/pluginHooks.js +48 -0
- package/dist/pluginHost.d.ts +5 -0
- package/dist/pluginHost.js +43 -0
- package/dist/pluginWorker.d.ts +1 -0
- package/dist/pluginWorker.js +40 -0
- package/dist/plural.d.ts +2 -0
- package/dist/plural.js +4 -0
- package/dist/pool.d.ts +80 -7
- package/dist/pool.js +222 -11
- package/dist/projects.d.ts +43 -1
- package/dist/projects.js +283 -11
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +5 -1
- package/dist/propertyWorker.js +7 -0
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +13 -5
- package/dist/runtimeEnv.js +48 -10
- package/dist/sandbox.d.ts +98 -0
- package/dist/sandbox.js +673 -0
- package/dist/sandboxGuard.d.ts +56 -0
- package/dist/sandboxGuard.js +249 -0
- package/dist/seal.d.ts +9 -0
- package/dist/seal.js +426 -0
- package/dist/security/cli.d.ts +6 -0
- package/dist/security/cli.js +39 -0
- package/dist/security/cwe.d.ts +14 -0
- package/dist/security/cwe.js +40 -0
- package/dist/security/deps/cache.d.ts +28 -0
- package/dist/security/deps/cache.js +107 -0
- package/dist/security/deps/config.d.ts +16 -0
- package/dist/security/deps/config.js +43 -0
- package/dist/security/deps/imports.d.ts +4 -0
- package/dist/security/deps/imports.js +33 -0
- package/dist/security/deps/lockfiles.d.ts +23 -0
- package/dist/security/deps/lockfiles.js +153 -0
- package/dist/security/deps/osv.d.ts +66 -0
- package/dist/security/deps/osv.js +137 -0
- package/dist/security/deps/run.d.ts +54 -0
- package/dist/security/deps/run.js +135 -0
- package/dist/security/deps/severity.d.ts +26 -0
- package/dist/security/deps/severity.js +78 -0
- package/dist/security/generators.d.ts +9 -0
- package/dist/security/generators.js +36 -0
- package/dist/security/index.d.ts +27 -0
- package/dist/security/index.js +18 -0
- package/dist/security/integers.d.ts +31 -0
- package/dist/security/integers.js +105 -0
- package/dist/security/law.d.ts +54 -0
- package/dist/security/law.js +54 -0
- package/dist/security/pathTraversal.d.ts +29 -0
- package/dist/security/pathTraversal.js +146 -0
- package/dist/security/prototypePollution.d.ts +30 -0
- package/dist/security/prototypePollution.js +142 -0
- package/dist/security/redirect.d.ts +21 -0
- package/dist/security/redirect.js +154 -0
- package/dist/security/redos.d.ts +21 -0
- package/dist/security/redos.js +93 -0
- package/dist/security/validation.d.ts +25 -0
- package/dist/security/validation.js +89 -0
- package/dist/security/xss.d.ts +21 -0
- package/dist/security/xss.js +90 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +32 -0
- package/dist/smt.d.ts +29 -1
- package/dist/smt.js +239 -107
- package/dist/smtWorker.d.ts +1 -0
- package/dist/smtWorker.js +26 -0
- package/dist/solvers.d.ts +9 -0
- package/dist/solvers.js +11 -5
- package/dist/symbolic.d.ts +54 -1
- package/dist/symbolic.js +239 -13
- package/dist/tsconfigResolve.d.ts +28 -0
- package/dist/tsconfigResolve.js +141 -0
- package/dist/types.d.ts +28 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +18 -6
package/dist/mcp.js
CHANGED
|
@@ -14,8 +14,9 @@ import { hintFor } from "./hints.js";
|
|
|
14
14
|
import { discoverLaws, discoverProposals, ignoredDirs } from "./lawFiles.js";
|
|
15
15
|
import { listLawFiles } from "./list.js";
|
|
16
16
|
import { parseLawFile } from "./promote.js";
|
|
17
|
-
import { addProposal, mergeProposal, ProposalError } from "./proposals.js";
|
|
17
|
+
import { addProposal, mergeProposal, previewProposal, ProposalError } from "./proposals.js";
|
|
18
18
|
import { resolveSettings } from "./settings.js";
|
|
19
|
+
import { plural } from "./plural.js";
|
|
19
20
|
const passing = new Set(['proved', 'bounded', 'tested']);
|
|
20
21
|
const supportedVersions = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
21
22
|
const defaultProposalFile = 'agent.ts';
|
|
@@ -52,14 +53,22 @@ export const tools = [
|
|
|
52
53
|
},
|
|
53
54
|
{
|
|
54
55
|
name: 'tslaws_propose',
|
|
55
|
-
description: 'Write a law into a proposal file in .tslaws/proposals/ (appended; a law of the same name is replaced) and check it. Only that directory can be written. Write imports of project files relative to the project root with a leading ./ (for example ./src/cart); the level (Node, browser, end to end) comes from what the file imports. A person promotes proposals with `tslaws promote`.',
|
|
56
|
+
description: 'Write a law into a proposal file in .tslaws/proposals/ (appended; a law of the same name is replaced) and check it. The source may also hold the top-level const, function, type and interface declarations the law needs (a helper of the same name is replaced); any other top-level statement is refused, and so is a const whose initialiser can run code (a call, new, await, tagged template, assignment and so on). Helpers and package imports become part of the trusted tree when a person promotes them, so a source with either is not written until you call again with confirmCode: true, after the person has seen the text this tool returns. An import of a file must name reviewed code: inside the project, outside .tslaws/, node_modules and .git, and not git-ignored; any other is refused. Only that directory can be written. Write imports of project files relative to the project root with a leading ./ (for example ./src/cart); the level (Node, browser, end to end) comes from what the file imports. A person promotes proposals with `tslaws promote`.',
|
|
56
57
|
inputSchema: {
|
|
57
58
|
type: 'object',
|
|
58
59
|
properties: {
|
|
59
60
|
name: { type: 'string', description: 'the law name' },
|
|
60
61
|
source: {
|
|
61
62
|
type: 'string',
|
|
62
|
-
description: "the full law, as `law('name', ...)` or `export law name ...` (the project's syntax), with any imports it needs",
|
|
63
|
+
description: "the full law, as `law('name', ...)` or `export law name ...` (the project's syntax), with any imports and helper declarations it needs",
|
|
64
|
+
},
|
|
65
|
+
confirmCode: {
|
|
66
|
+
type: 'boolean',
|
|
67
|
+
description: 'required (true) when source declares helpers or imports a package: the first call returns that code and writes nothing; set this once the person has seen it',
|
|
68
|
+
},
|
|
69
|
+
confirmHelpers: {
|
|
70
|
+
type: 'boolean',
|
|
71
|
+
description: 'deprecated alias of confirmCode; use confirmCode',
|
|
63
72
|
},
|
|
64
73
|
file: {
|
|
65
74
|
type: 'string',
|
|
@@ -116,7 +125,7 @@ function withHints(report) {
|
|
|
116
125
|
}
|
|
117
126
|
function totals(report) {
|
|
118
127
|
const count = (status) => report.results.filter((r) => r.status === status).length;
|
|
119
|
-
return `${report.results.length}
|
|
128
|
+
return `${plural(report.results.length, 'law')}: ${count('proved')} proved, ${count('bounded')} bounded, ${count('tested')} tested, ${count('open')} open, ${count('failed')} failed, ${count('tampered')} tampered, ${plural(count('error'), 'error')}`;
|
|
120
129
|
}
|
|
121
130
|
function summarised(report) {
|
|
122
131
|
const full = withHints(report);
|
|
@@ -132,12 +141,12 @@ export class Session {
|
|
|
132
141
|
for (const r of report.results)
|
|
133
142
|
this.last.set(r.name, r);
|
|
134
143
|
}
|
|
135
|
-
async run(files, enforceLock) {
|
|
144
|
+
async run(files, enforceLock, partial = false) {
|
|
136
145
|
if (files.length === 0)
|
|
137
146
|
throw new ToolError(enforceLock
|
|
138
147
|
? 'no laws files found (looking for *.laws.ts)'
|
|
139
148
|
: 'no proposals found (looking in .tslaws/proposals/, and for in-tree *.proposed.laws.ts files)');
|
|
140
|
-
const report = await check(options(this.opts, files), enforceLock);
|
|
149
|
+
const report = await check({ ...options(this.opts, files), partial }, enforceLock);
|
|
141
150
|
this.remember(report);
|
|
142
151
|
return report;
|
|
143
152
|
}
|
|
@@ -151,7 +160,7 @@ export class Session {
|
|
|
151
160
|
const files = given === undefined || given.length === 0
|
|
152
161
|
? discover(cwd, false)
|
|
153
162
|
: given.map((f) => slash(relative(cwd, insideRoot(cwd, f))));
|
|
154
|
-
const report = await this.run(files, true);
|
|
163
|
+
const report = await this.run(files, true, given !== undefined && given.length > 0);
|
|
155
164
|
return args.summary === true ? summarised(report) : withHints(report);
|
|
156
165
|
}
|
|
157
166
|
case 'tslaws_list':
|
|
@@ -187,6 +196,18 @@ export class Session {
|
|
|
187
196
|
throw new ToolError('source must be a string');
|
|
188
197
|
let written;
|
|
189
198
|
try {
|
|
199
|
+
const preview = previewProposal(args.source, cwd);
|
|
200
|
+
if ((preview.helpers.length > 0 || preview.packages.length > 0) &&
|
|
201
|
+
args.confirmCode !== true &&
|
|
202
|
+
args.confirmHelpers !== true)
|
|
203
|
+
return {
|
|
204
|
+
written: false,
|
|
205
|
+
needsConfirmation: true,
|
|
206
|
+
message: 'Nothing was written. This source declares helpers or imports packages; that code becomes part of the trusted tree when a person promotes the proposal. Show the import and helper text below to the person, then call tslaws_propose again with confirmCode: true.',
|
|
207
|
+
imports: preview.imports,
|
|
208
|
+
packages: preview.packages,
|
|
209
|
+
helpers: preview.helpers,
|
|
210
|
+
};
|
|
190
211
|
written = addProposal(cwd, typeof args.file === 'string' ? args.file : defaultProposalFile, args.source, args.name);
|
|
191
212
|
}
|
|
192
213
|
catch (error) {
|
package/dist/mutate.d.ts
CHANGED
|
@@ -25,6 +25,10 @@ export interface MutateOptions {
|
|
|
25
25
|
/** True when the person named law files: only the sources those laws reach are mutated. */
|
|
26
26
|
lawsNamed?: boolean;
|
|
27
27
|
seed?: number;
|
|
28
|
+
/** False runs laws without the sandbox (`--no-sandbox`). */
|
|
29
|
+
sandbox?: boolean;
|
|
30
|
+
/** Let end-to-end laws run outside the sandbox (`--allow-e2e`). */
|
|
31
|
+
allowE2e?: boolean;
|
|
28
32
|
/** Run settings as `check` takes them; unset ones come from tslaws.json, then the mutate defaults (30 runs). */
|
|
29
33
|
runs?: number;
|
|
30
34
|
bound?: number;
|
package/dist/mutate.js
CHANGED
|
@@ -5,8 +5,10 @@ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statS
|
|
|
5
5
|
import { dirname, join, relative } from 'node:path';
|
|
6
6
|
import ts from 'typescript';
|
|
7
7
|
import { check } from "./check.js";
|
|
8
|
+
import { releaseSandbox } from "./sandbox.js";
|
|
8
9
|
import { coverFiles, readConfig } from "./coverage.js";
|
|
9
10
|
import { mutateDefaults } from "./settings.js";
|
|
11
|
+
import { plural } from "./plural.js";
|
|
10
12
|
const ignoredDirs = new Set(['node_modules', '.tslaws', '.git']);
|
|
11
13
|
const sourceExt = /\.(ts|tsx|mts|cts)$/;
|
|
12
14
|
const copiedExt = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs|json)$/;
|
|
@@ -197,6 +199,8 @@ export async function mutate(options) {
|
|
|
197
199
|
proofTimeoutMs: options.proofTimeoutMs ?? config.proofTimeoutMs ?? mutateDefaults.proofTimeoutMs,
|
|
198
200
|
propertyTimeoutMs: options.propertyTimeoutMs ?? config.propertyTimeoutMs ?? mutateDefaults.propertyTimeoutMs,
|
|
199
201
|
browser: options.browser,
|
|
202
|
+
sandbox: options.sandbox,
|
|
203
|
+
allowE2e: options.allowE2e,
|
|
200
204
|
// The lock is not enforced on mutants; it is copied so the scratch project is complete.
|
|
201
205
|
explicit: options.runs === undefined ? [] : ['runs'],
|
|
202
206
|
});
|
|
@@ -229,7 +233,7 @@ export async function mutate(options) {
|
|
|
229
233
|
const originals = new Map(files.map((f) => [f, readFileSync(join(cwd, f), 'utf8')]));
|
|
230
234
|
const all = files.flatMap((f) => mutantsOf(f, originals.get(f)));
|
|
231
235
|
const chosen = sample(all, options.max, options.seed ?? 1);
|
|
232
|
-
say(`${chosen.length} of ${all.length}
|
|
236
|
+
say(`${chosen.length} of ${plural(all.length, 'mutant')} in ${plural(files.length, 'file')}`);
|
|
233
237
|
const results = [];
|
|
234
238
|
for (const [n, mutant] of chosen.entries()) {
|
|
235
239
|
const dir = join(scratchRoot, String(n + 1));
|
|
@@ -260,6 +264,7 @@ export async function mutate(options) {
|
|
|
260
264
|
};
|
|
261
265
|
}
|
|
262
266
|
finally {
|
|
267
|
+
releaseSandbox(dir);
|
|
263
268
|
rmSync(dir, { recursive: true, force: true });
|
|
264
269
|
}
|
|
265
270
|
results.push(result);
|
|
@@ -278,6 +283,7 @@ export async function mutate(options) {
|
|
|
278
283
|
};
|
|
279
284
|
}
|
|
280
285
|
finally {
|
|
286
|
+
releaseSandbox(scratchRoot);
|
|
281
287
|
rmSync(scratchRoot, { recursive: true, force: true });
|
|
282
288
|
}
|
|
283
289
|
}
|
package/dist/plan.d.ts
CHANGED
package/dist/plan.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import { sequence } from "./sequence.js";
|
|
5
5
|
import * as fc from 'fast-check';
|
|
6
6
|
import { arbitraryRegistry } from "./api.js";
|
|
7
|
+
import { registerSecurityGenerators } from "./security/generators.js";
|
|
7
8
|
export class UnsupportedType extends Error {
|
|
8
9
|
}
|
|
9
10
|
const numbers = fc.oneof({ weight: 4, arbitrary: fc.integer({ min: -8, max: 8 }) }, { weight: 3, arbitrary: fc.integer({ min: -1000, max: 1000 }) }, { weight: 1, arbitrary: fc.integer() }, { weight: 2, arbitrary: fc.double({ noNaN: true, noDefaultInfinity: true }) });
|
|
@@ -86,6 +87,9 @@ export function arbitraryOf(plan) {
|
|
|
86
87
|
return fc.tuple(...parts).map((p) => p.join(''));
|
|
87
88
|
}
|
|
88
89
|
case 'named': {
|
|
90
|
+
// A payload type of tslaws/security: a worker has not loaded the law yet, so it registers these itself.
|
|
91
|
+
if (plan.security === true && !arbitraryRegistry().has(plan.name))
|
|
92
|
+
registerSecurityGenerators();
|
|
89
93
|
const registered = arbitraryRegistry().get(plan.name);
|
|
90
94
|
if (registered !== undefined)
|
|
91
95
|
return registered;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** What the hooks ask of the runtime: the project owning a file, and a relative import found beside the source. */
|
|
2
|
+
export interface PluginHookHost {
|
|
3
|
+
ownerOf(file: string): {
|
|
4
|
+
cwd: string;
|
|
5
|
+
bundlerPlugins?: string[];
|
|
6
|
+
} | undefined;
|
|
7
|
+
beside(request: string, parent: {
|
|
8
|
+
filename: string;
|
|
9
|
+
}): string | undefined;
|
|
10
|
+
/** The source Node can run for a file in a project format (see `transformPluginFile` in pluginHost.ts). */
|
|
11
|
+
transform(file: string, cwd: string, plugins: readonly string[], format: 'cjs' | 'esm'): string;
|
|
12
|
+
}
|
|
13
|
+
/** Whether Node cannot load a file with this extension itself, so a plugin must. */
|
|
14
|
+
export declare const pluginExtensionNeeded: (extension: string) => boolean;
|
|
15
|
+
/** Registers the hooks once per thread; returns whether they are in place. */
|
|
16
|
+
export declare function installPluginHooks(host: PluginHookHost): boolean;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// The module hooks for `bundlerPlugins` in node laws (the plugins themselves run in pluginHost.ts). `require` and
|
|
2
|
+
// `import()` reach a project format (`.tsrx`) by different roads, and the extension handler in lawRuntime.ts only
|
|
3
|
+
// serves `require`. `module.registerHooks` sits in front of both: it finds a template or stylesheet beside its source,
|
|
4
|
+
// and loads it through the plugins as a CommonJS module for `require` and an ES module for `import()`. Needs Node 22.15,
|
|
5
|
+
// 23.5 or later; on an older Node the extension handler still serves `require`.
|
|
6
|
+
import { extname } from 'node:path';
|
|
7
|
+
import nodeModule from 'node:module';
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
9
|
+
const nodeExtensions = new Set(['', '.js', '.cjs', '.mjs', '.json', '.node', '.ts', '.tsx', '.mts', '.cts']);
|
|
10
|
+
/** Whether Node cannot load a file with this extension itself, so a plugin must. */
|
|
11
|
+
export const pluginExtensionNeeded = (extension) => !nodeExtensions.has(extension.toLowerCase());
|
|
12
|
+
let installed;
|
|
13
|
+
/** Registers the hooks once per thread; returns whether they are in place. */
|
|
14
|
+
export function installPluginHooks(host) {
|
|
15
|
+
if (installed !== undefined)
|
|
16
|
+
return installed;
|
|
17
|
+
installed = false;
|
|
18
|
+
const { registerHooks } = nodeModule;
|
|
19
|
+
if (typeof registerHooks !== 'function')
|
|
20
|
+
return installed;
|
|
21
|
+
registerHooks({
|
|
22
|
+
resolve(specifier, context, nextResolve) {
|
|
23
|
+
try {
|
|
24
|
+
return nextResolve(specifier, context);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
const parent = context.parentURL?.startsWith('file:') ? fileURLToPath(context.parentURL) : undefined;
|
|
28
|
+
const file = parent === undefined ? undefined : host.beside(specifier, { filename: parent });
|
|
29
|
+
if (file === undefined)
|
|
30
|
+
throw error;
|
|
31
|
+
return { url: pathToFileURL(file).href, shortCircuit: true };
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
load(url, context, nextLoad) {
|
|
35
|
+
if (!url.startsWith('file:'))
|
|
36
|
+
return nextLoad(url, context);
|
|
37
|
+
const file = fileURLToPath(url);
|
|
38
|
+
if (!pluginExtensionNeeded(extname(file)))
|
|
39
|
+
return nextLoad(url, context);
|
|
40
|
+
const owner = host.ownerOf(file);
|
|
41
|
+
const commonjs = context.conditions.includes('require');
|
|
42
|
+
const source = host.transform(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], commonjs ? 'cjs' : 'esm');
|
|
43
|
+
return { format: commonjs ? 'commonjs' : 'module', source, shortCircuit: true };
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
installed = true;
|
|
47
|
+
return installed;
|
|
48
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The source Node can run for `file`, a file in a format only the project's bundler plugins know: CommonJS for `require`,
|
|
3
|
+
* an ES module for `import()`.
|
|
4
|
+
*/
|
|
5
|
+
export declare function transformPluginFile(file: string, cwd: string, plugins: readonly string[], format?: 'cjs' | 'esm'): string;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Source formats for laws that run in Node. Compiled laws are CommonJS and load through `require`, which cannot read a
|
|
2
|
+
// project format (`.tsrx`, `.svelte`). The project's `bundlerPlugins` (esbuild plugins) can, but they are asynchronous
|
|
3
|
+
// and `require` is not. A helper thread loads the plugins and runs esbuild on one file at a time; the requiring thread
|
|
4
|
+
// blocks on a shared flag (`Atomics.wait`) until the answer arrives, so the loader stays synchronous and each file is
|
|
5
|
+
// transformed by exactly the plugin that handles it in the browser. One helper per project, started on first need.
|
|
6
|
+
import { MessageChannel, Worker, receiveMessageOnPort } from 'node:worker_threads';
|
|
7
|
+
import { explainNodeLoadError } from "./bundlerPlugins.js";
|
|
8
|
+
const hosts = new Map();
|
|
9
|
+
const waitLimitMs = 120_000;
|
|
10
|
+
function startHost(cwd, plugins) {
|
|
11
|
+
const { port1, port2 } = new MessageChannel();
|
|
12
|
+
const signal = new Int32Array(new SharedArrayBuffer(4));
|
|
13
|
+
const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
14
|
+
const worker = new Worker(new URL(`./pluginWorker${extension}`, import.meta.url), {
|
|
15
|
+
workerData: { cwd, plugins, port: port2, signal },
|
|
16
|
+
transferList: [port2],
|
|
17
|
+
});
|
|
18
|
+
// Neither the helper nor its port may keep the process alive once the laws are done.
|
|
19
|
+
worker.unref();
|
|
20
|
+
port1.unref();
|
|
21
|
+
return { worker, port: port1, signal };
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The source Node can run for `file`, a file in a format only the project's bundler plugins know: CommonJS for `require`,
|
|
25
|
+
* an ES module for `import()`.
|
|
26
|
+
*/
|
|
27
|
+
export function transformPluginFile(file, cwd, plugins, format = 'cjs') {
|
|
28
|
+
const key = `${cwd}\0${plugins.join('\0')}`;
|
|
29
|
+
let host = hosts.get(key);
|
|
30
|
+
if (host === undefined) {
|
|
31
|
+
host = startHost(cwd, plugins);
|
|
32
|
+
hosts.set(key, host);
|
|
33
|
+
}
|
|
34
|
+
Atomics.store(host.signal, 0, 0);
|
|
35
|
+
host.worker.postMessage({ file, format });
|
|
36
|
+
const waited = Atomics.wait(host.signal, 0, 0, waitLimitMs);
|
|
37
|
+
const message = receiveMessageOnPort(host.port)?.message;
|
|
38
|
+
if (waited === 'timed-out' || message === undefined)
|
|
39
|
+
throw new Error(`cannot load "${file}": the bundlerPlugins helper did not answer within ${waitLimitMs / 1000}s`);
|
|
40
|
+
if ('error' in message)
|
|
41
|
+
throw message.missingLoader === true ? explainNodeLoadError(file, message.error) : new Error(message.error);
|
|
42
|
+
return message.code;
|
|
43
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
3
|
+
import { build } from 'esbuild';
|
|
4
|
+
import { loadBundlerPlugins } from "./bundlerPlugins.js";
|
|
5
|
+
import { importMetaEnvGlobal } from "./runtimeEnv.js";
|
|
6
|
+
// The helper thread of pluginHost.ts: loads the project's bundler plugins once, then turns one file at a time into
|
|
7
|
+
// CommonJS or an ES module with esbuild and the plugins. It answers on a port and then raises the shared flag the caller waits on.
|
|
8
|
+
const { cwd, plugins, port, signal } = workerData;
|
|
9
|
+
let loaded;
|
|
10
|
+
async function transform(file, format) {
|
|
11
|
+
loaded ??= loadBundlerPlugins(cwd, plugins);
|
|
12
|
+
const result = await build({
|
|
13
|
+
entryPoints: [file],
|
|
14
|
+
// Not bundled: an import in the output stays a `require`, so a module shared with the laws is the same instance.
|
|
15
|
+
bundle: false,
|
|
16
|
+
write: false,
|
|
17
|
+
format,
|
|
18
|
+
platform: 'node',
|
|
19
|
+
target: 'es2022',
|
|
20
|
+
sourcemap: 'inline',
|
|
21
|
+
outdir: dirname(file),
|
|
22
|
+
plugins: await loaded,
|
|
23
|
+
define: { 'import.meta.env': `globalThis.${importMetaEnvGlobal}` },
|
|
24
|
+
logLevel: 'silent',
|
|
25
|
+
});
|
|
26
|
+
// A stylesheet has no meaning in Node: a plugin that answers with CSS leaves the module empty.
|
|
27
|
+
const script = result.outputFiles.find((output) => /\.[cm]?js$/.test(output.path));
|
|
28
|
+
return { code: script?.text ?? (format === 'cjs' ? 'module.exports = {};' : 'export default {};') };
|
|
29
|
+
}
|
|
30
|
+
parentPort.on('message', async ({ file, format }) => {
|
|
31
|
+
try {
|
|
32
|
+
port.postMessage(await transform(file, format));
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const message = error.message;
|
|
36
|
+
port.postMessage({ error: message, missingLoader: /No loader is configured for "/.test(message) });
|
|
37
|
+
}
|
|
38
|
+
Atomics.store(signal, 0, 1);
|
|
39
|
+
Atomics.notify(signal, 0);
|
|
40
|
+
});
|
package/dist/plural.d.ts
ADDED
package/dist/plural.js
ADDED
package/dist/pool.d.ts
CHANGED
|
@@ -1,21 +1,94 @@
|
|
|
1
1
|
import type { Worker } from 'node:worker_threads';
|
|
2
|
-
/**
|
|
2
|
+
/** Where the number of slots may come from, in the order that wins: the flag, the environment, tslaws.json. */
|
|
3
|
+
export interface JobSources {
|
|
4
|
+
flag?: number;
|
|
5
|
+
config?: number;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* How many things run at once. A given number (flag, then `TSLAWS_JOBS`, then `jobs` in tslaws.json) is used as it is.
|
|
9
|
+
* Without one: the cores less one, so the machine stays usable, up to 8, and no more than one slot per GiB of free memory
|
|
10
|
+
* (a Z3 instance holds a large WebAssembly heap).
|
|
11
|
+
*/
|
|
12
|
+
export declare function resolveJobs(input: JobSources & {
|
|
13
|
+
env?: string;
|
|
14
|
+
cores: number;
|
|
15
|
+
freeBytes: number;
|
|
16
|
+
}): number;
|
|
17
|
+
/**
|
|
18
|
+
* Sets where the number of slots comes from (the command line flag, `jobs` of tslaws.json). An absent `flag` leaves the
|
|
19
|
+
* flag as it was; a `config` key replaces the config source even when it is undefined, so one project's `jobs` never
|
|
20
|
+
* carries over to the next project checked in the same process.
|
|
21
|
+
*/
|
|
22
|
+
export declare function configureJobs(next?: JobSources): void;
|
|
23
|
+
/** Forgets every configured source and the number worked out from them; for tests. */
|
|
24
|
+
export declare function resetJobs(): void;
|
|
25
|
+
/** The size of the CPU budget. Worked out once per configuration, so free memory does not move it mid-run. */
|
|
3
26
|
export declare function jobs(): number;
|
|
27
|
+
/** Runs below normal priority, so a solver does not starve the machine's other work. Failures are ignored. */
|
|
28
|
+
export declare function lowerPriority(pid: number | undefined): void;
|
|
29
|
+
/**
|
|
30
|
+
* Slots of CPU for everything heavy: a law run, a solve, a spawned solver, a property worker task, a sandboxed law
|
|
31
|
+
* process. One budget serves the whole process, so the pools below no longer each take every core.
|
|
32
|
+
*
|
|
33
|
+
* Nesting reuses the slot: work started inside a function that `run` is holding a slot for (a proof under the law that
|
|
34
|
+
* asked for it) takes no second slot, so a waiting law can never be starved by the work it is waiting on, and a budget
|
|
35
|
+
* of 1 cannot deadlock. A race or portfolio asks for one extra slot per additional member with `portfolio`, never
|
|
36
|
+
* waiting for it: with none free the members run one after another on the slot already held.
|
|
37
|
+
*/
|
|
38
|
+
export declare class Budget {
|
|
39
|
+
private used;
|
|
40
|
+
private readonly waiting;
|
|
41
|
+
private readonly held;
|
|
42
|
+
private readonly limit;
|
|
43
|
+
constructor(limit?: () => number);
|
|
44
|
+
/** The slots in use now. */
|
|
45
|
+
get inUse(): number;
|
|
46
|
+
/** The most slots there may be. */
|
|
47
|
+
get size(): number;
|
|
48
|
+
/** Whether this async context already holds a slot. */
|
|
49
|
+
get holding(): boolean;
|
|
50
|
+
/** Runs `work` holding one slot, waiting for one when none is free; reuses the slot this context already holds. */
|
|
51
|
+
run<T>(work: () => Promise<T> | T): Promise<T>;
|
|
52
|
+
/** Takes a slot if one is free right now; the returned function gives it back. */
|
|
53
|
+
tryHold(): (() => void) | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* Runs the tasks together, each past the first on an extra slot, and the rest one after another on the slot already
|
|
56
|
+
* held. Results come back in the order of the tasks.
|
|
57
|
+
*/
|
|
58
|
+
portfolio<T>(tasks: (() => Promise<T>)[]): Promise<T[]>;
|
|
59
|
+
private take;
|
|
60
|
+
private give;
|
|
61
|
+
}
|
|
62
|
+
/** The one budget of this process. */
|
|
63
|
+
export declare const budget: Budget;
|
|
4
64
|
/**
|
|
5
65
|
* A pool of workers where each request holds one exclusively, so a timeout can terminate its worker without
|
|
6
|
-
* disturbing a neighbour. Workers start on demand and are reused.
|
|
66
|
+
* disturbing a neighbour. Workers start on demand and are reused. `size` is read each time, so it may follow the budget.
|
|
67
|
+
* With `idleMs`, a worker that sits unused that long is terminated.
|
|
7
68
|
*/
|
|
8
|
-
export declare class WorkerPool {
|
|
69
|
+
export declare class WorkerPool<T extends {
|
|
70
|
+
terminate(): unknown;
|
|
71
|
+
} = Worker> {
|
|
9
72
|
private readonly idle;
|
|
73
|
+
private readonly timers;
|
|
10
74
|
private readonly waiting;
|
|
11
75
|
private count;
|
|
12
76
|
private readonly start;
|
|
13
77
|
private readonly size;
|
|
14
|
-
|
|
15
|
-
|
|
78
|
+
private readonly idleMs;
|
|
79
|
+
constructor(start: () => T, size?: number | (() => number), idleMs?: number);
|
|
80
|
+
/** The workers this pool has started and not yet ended, busy or idle. */
|
|
81
|
+
get live(): number;
|
|
82
|
+
acquire(): Promise<T>;
|
|
16
83
|
/** Starts up to `n` workers now, so they finish loading while the caller does other work. */
|
|
17
84
|
warm(n: number): void;
|
|
18
|
-
release(worker:
|
|
85
|
+
release(worker: T): void;
|
|
86
|
+
/** Terminates one idle worker, to make room elsewhere; false when none is idle. */
|
|
87
|
+
evictOne(): boolean;
|
|
88
|
+
/** Terminates the idle workers, for a project that is done (a scratch copy that is about to be deleted). */
|
|
89
|
+
close(): void;
|
|
19
90
|
/** Terminates a worker that timed out or crashed; a waiting request gets a fresh one. */
|
|
20
|
-
discard(worker:
|
|
91
|
+
discard(worker: T): void;
|
|
92
|
+
private park;
|
|
93
|
+
private untimed;
|
|
21
94
|
}
|