tslaws 0.8.0 → 0.10.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 CHANGED
@@ -167,6 +167,7 @@ See [docs/laws.md](../../docs/laws.md#the-dashboard).
167
167
  `tslaws mutate [files...] [--max N] [--seed N] [--json]` mutation-tests the laws: it mutates the covered code, re-runs the laws against each mutant, and lists the survivors no law caught. It handles `.tsx`/`.jsx` and projects with a lock, and takes the run flags of `check`. See [docs/laws.md](../../docs/laws.md#mutation-testing).
168
168
 
169
169
  - **Other source formats:** `tslaws.json` `bundlerPlugins` lists esbuild plugin modules (paths relative to the file) that teach the browser bundler formats like `.tsrx`. See [docs/laws.md](../../docs/laws.md#bundler-plugins).
170
+ - **Bundler-style source:** `import.meta.env` works in laws, in the code they reach and in browser pages (`tslaws.json` `env` adds or overrides entries), and a TypeScript dependency may import its own files without extensions. See [docs/laws.md](../../docs/laws.md#source-written-for-a-bundler).
170
171
  - **Settings:** `tslaws.json` `runs`, `bound`, `proofTimeoutMs` and `propertyTimeoutMs` set the run defaults; a command line flag beats them. `"solvers": ["z3", "cvc5"]` makes cvc5 confirm every Z3 proof (set `TSLAWS_CVC5` to its path, or put it on the PATH). See [docs/laws.md](../../docs/laws.md#settings).
171
172
 
172
173
  ## Agents cannot move the goalposts
package/dist/browser.js CHANGED
@@ -5,7 +5,8 @@ import { mkdirSync } from 'node:fs';
5
5
  import { delimiter, join, relative as pathRelative, resolve, sep } from 'node:path';
6
6
  import { build as bundleWith } from 'esbuild';
7
7
  import { explainBundleError, loadBundlerPlugins } from "./bundlerPlugins.js";
8
- import { readConfig } from "./coverage.js";
8
+ import { lawEnv, readConfig } from "./coverage.js";
9
+ import { importMetaEnvGlobal } from "./runtimeEnv.js";
9
10
  import { chromium, firefox, webkit } from 'playwright-core';
10
11
  import { toWire } from "./generators.js";
11
12
  import { runProperty, summarise } from "./property.js";
@@ -207,7 +208,12 @@ async function bundleOf(jsFile, cwd) {
207
208
  target: 'es2022',
208
209
  absWorkingDir: cwd,
209
210
  logLevel: 'silent',
210
- define: { 'process.env.NODE_ENV': '"development"', global: 'globalThis' },
211
+ // A dependency's `import.meta.env` reads the same global the compiled laws do; the page sets it before the bundle.
212
+ define: {
213
+ 'process.env.NODE_ENV': '"development"',
214
+ global: 'globalThis',
215
+ 'import.meta.env': `globalThis.${importMetaEnvGlobal}`,
216
+ },
211
217
  });
212
218
  const emitted = (extension) => result.outputFiles
213
219
  .filter((file) => file.path.endsWith(extension))
@@ -266,6 +272,9 @@ export async function runBrowserLaw(law, options) {
266
272
  // The stylesheet goes in before the script runs, as a linked one would.
267
273
  if (css !== '')
268
274
  await page.addStyleTag({ content: css });
275
+ await page.addScriptTag({
276
+ content: `globalThis.${importMetaEnvGlobal} = ${JSON.stringify(lawEnv(options.cwd, 'browser'))};`,
277
+ });
269
278
  await page.addScriptTag({ content: code });
270
279
  await page.addScriptTag({ content: harness });
271
280
  const call = async (...args) => {
package/dist/check.js CHANGED
@@ -3,11 +3,12 @@ import { resolve } from 'node:path';
3
3
  import ts from 'typescript';
4
4
  import { build, readManifest } from "./compile.js";
5
5
  import { compilerOptions, declarationFiles, isDiscard, jsPath, runLawGuarded, warmWorkers, typesOf, } from "./property.js";
6
- import { analyzeCoverage, coverFiles, readConfig } from "./coverage.js";
6
+ import { analyzeCoverage, coverFiles, lawEnv, readConfig } from "./coverage.js";
7
7
  import { derivedStore } from "./derived.js";
8
8
  import { jobs } from "./pool.js";
9
9
  import { compareLock, lawKey, readLock } from "./lock.js";
10
10
  import { crossCheck, disagreement } from "./propertyRun.js";
11
+ import { prepareRuntime } from "./runtimeEnv.js";
11
12
  import { proveLaw } from "./smt.js";
12
13
  import { decodeExample, loadExamples, regressionMessage, saveExample } from "./regressions.js";
13
14
  import { closeBrowser, runBrowserLaw } from "./browser.js";
@@ -184,6 +185,8 @@ export async function check(options, enforceLock) {
184
185
  const program = () => (programOf ??= built.program ?? ts.createProgram(declarationFiles(built.outDir), compilerOptions));
185
186
  const sourceCwd = built.program === undefined ? undefined : options.cwd;
186
187
  const require = createRequire(import.meta.url);
188
+ // Laws that run here (end to end) and the code they load read `import.meta.env` and extensionless imports as bundled.
189
+ prepareRuntime(lawEnv(options.cwd, 'node'));
187
190
  const runOne = async (law, index) => {
188
191
  const buffered = [];
189
192
  try {
package/dist/cli.d.ts CHANGED
@@ -7,6 +7,8 @@ export interface CommandContext {
7
7
  now?: Date;
8
8
  out?: (text: string) => void;
9
9
  err?: (text: string) => void;
10
+ /** Projects nested below `cwd`, project-relative: their laws are not this project's (set by a root run). */
11
+ skip?: string[];
10
12
  }
11
13
  export declare function acceptCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext): Promise<number>;
12
14
  /** `tslaws delegate <action> [--for D] [--root DIR]`; `argv` is everything after `delegate`. */
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import { isProposedLawFile } from "./lawNames.js";
11
11
  import { init, nextStep } from "./init.js";
12
12
  import { listLawFiles, renderList } from "./list.js";
13
13
  import { serveMcp } from "./mcp.js";
14
+ import { discoverProjects, isMonorepoRoot } from "./projects.js";
14
15
  import { promoteFiles, promoteProposal } from "./promote.js";
15
16
  import { addProposal, ProposalError } from "./proposals.js";
16
17
  import { clearCorpus, listCorpus } from "./regressions.js";
@@ -39,6 +40,10 @@ tslaws github report|command|merge|verify accept laws on GitHub: flag and run
39
40
  tslaws mcp [--compiler PATH] serve check, check_proposed, explain and propose as Model Context Protocol tools on stdio (cannot accept, promote or touch the lock)
40
41
  ${migrateUsage}
41
42
 
43
+ In a monorepo (a root tslaws.json with "projects", or package.json/pnpm workspaces whose packages have a tslaws.json), run from the root: check, accept, list, mutate and regressions run in every project, one after another, each with its own config and lock, and end with one summary line. --json and --reporter json print one object keyed by project path; --reporter ndjson tags each line with "project". init, ui, mcp, github, propose, promote, delegate, migrate and --watch run in one project: pick it with --project when the root has several.
44
+ --project run only in this project directory (repeat it, or comma-separate: --project packages/a,packages/b)
45
+ --filter run only in projects whose path matches this glob (repeatable; a leading ! excludes), for example --filter 'packages/*'
46
+
42
47
  Without files, every *.laws.ts under the current directory (and every file the "laws" globs of tslaws.json pick that declares a law) is checked; with --proposed, the in-tree *.proposed.laws.ts files are (and any proposals in .tslaws/proposals/), with no lock and no coverage gate.
43
48
  A laws file's level comes from its name by default: *.browser.laws.ts is a browser law, *.e2e.laws.ts an end-to-end law, anything else runs in Node. With "levels": "imports" in tslaws.json it comes from the import graph instead (tslaws/browser, tslaws/adapters/* or tslaws/e2e, directly or through the file's own modules), and the names are hints.
44
49
  Exit status is 0 only when every law is proved, bounded or tested and nothing is open, failed, uncovered or tampered with.
@@ -55,6 +60,8 @@ function discover(cwd, proposed) {
55
60
  function parse(args) {
56
61
  const flags = new Map();
57
62
  const files = [];
63
+ const projects = [];
64
+ const filters = [];
58
65
  let command = 'check';
59
66
  const valued = new Set([
60
67
  'runs',
@@ -78,12 +85,24 @@ function parse(args) {
78
85
  'head-sha',
79
86
  'rerun-workflow',
80
87
  'protect',
88
+ 'project-path',
81
89
  ]);
82
90
  for (let i = 0; i < args.length; i += 1) {
83
91
  const arg = args[i];
84
92
  if (arg.startsWith('--')) {
85
93
  const name = arg.slice(2);
86
- if (valued.has(name))
94
+ if (name === 'project') {
95
+ projects.push(...(args[(i += 1)] ?? '')
96
+ .split(',')
97
+ .map((p) => p.trim())
98
+ .filter(Boolean));
99
+ }
100
+ else if (name === 'filter') {
101
+ const glob = args[(i += 1)] ?? '';
102
+ if (glob !== '')
103
+ filters.push(glob);
104
+ }
105
+ else if (valued.has(name))
87
106
  flags.set(name, args[(i += 1)] ?? '');
88
107
  else
89
108
  flags.set(name, true);
@@ -106,7 +125,7 @@ function parse(args) {
106
125
  else
107
126
  files.push(arg);
108
127
  }
109
- return { command, flags, files };
128
+ return { command, flags, files, projects, filters };
110
129
  }
111
130
  function describe(result) {
112
131
  const where = `${result.file}:${result.line}`;
@@ -143,7 +162,7 @@ function totals(report) {
143
162
  const count = (status) => report.results.filter((r) => r.status === status).length;
144
163
  return `${report.results.length} laws: ${count('proved')} proved, ${count('bounded')} bounded, ${count('tested')} tested, ${count('open')} open, ${count('failed')} failed, ${count('tampered')} tampered, ${count('error')} errors`;
145
164
  }
146
- function render(report, flags) {
165
+ function render(report, flags, project) {
147
166
  const reporter = String(flags.get('reporter') ?? (flags.has('json') ? 'json' : 'text'));
148
167
  if (!reporterNames.includes(reporter)) {
149
168
  throw new Error(`unknown reporter '${reporter}' (expected ${reporterNames.join(', ')})`);
@@ -154,7 +173,7 @@ function render(report, flags) {
154
173
  return `${JSON.stringify({ ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) }, null, 2)}\n`;
155
174
  }
156
175
  if (reporter === 'ndjson') {
157
- return `${JSON.stringify({ type: 'report', ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) })}\n`;
176
+ return `${JSON.stringify({ ...(project === undefined ? {} : { project }), type: 'report', ...report, results: report.results.map((r) => ({ ...r, hint: hintFor(r) })) })}\n`;
158
177
  }
159
178
  let text = '';
160
179
  if (report.compileDiagnostics !== '')
@@ -196,14 +215,19 @@ function options(cwd, flags, chosen) {
196
215
  : undefined,
197
216
  };
198
217
  }
199
- function lawFiles(cwd, flags, files) {
218
+ /** Files outside the directories `skip` (project-relative paths of projects nested in this one). */
219
+ function outside(files, skip) {
220
+ return skip.length === 0 ? files : files.filter((f) => !skip.some((dir) => f === dir || f.startsWith(`${dir}/`)));
221
+ }
222
+ function lawFiles(cwd, flags, files, skip = []) {
200
223
  return files.length > 0
201
224
  ? files.map((f) => relative(cwd, resolve(cwd, f)).replace(/\\/g, '/'))
202
- : discover(cwd, flags.has('proposed'));
225
+ : outside(discover(cwd, flags.has('proposed')), skip);
203
226
  }
227
+ const direct = { out: (text) => void process.stdout.write(text), skip: [] };
204
228
  /** One check of the project. Resolves the exit status. */
205
- async function runCheck(cwd, flags, files) {
206
- const chosen = lawFiles(cwd, flags, files);
229
+ async function runCheck(cwd, flags, files, run = direct) {
230
+ const chosen = lawFiles(cwd, flags, files, run.skip);
207
231
  if (chosen.length === 0) {
208
232
  process.stderr.write('no laws files found (looking for *.laws.ts)\n');
209
233
  return 1;
@@ -213,11 +237,11 @@ async function runCheck(cwd, flags, files) {
213
237
  const onEvent = stream
214
238
  ? (event) => {
215
239
  if (event.type !== 'frame')
216
- process.stdout.write(`${JSON.stringify(event)}\n`);
240
+ run.out(`${JSON.stringify(run.tag === undefined ? event : { project: run.tag, ...event })}\n`);
217
241
  }
218
242
  : undefined;
219
243
  const report = await check({ ...options(cwd, flags, chosen), onEvent }, !flags.has('proposed'));
220
- process.stdout.write(render(report, flags));
244
+ run.out(render(report, flags, run.tag));
221
245
  return report.ok ? 0 : 1;
222
246
  }
223
247
  export function watched(filename) {
@@ -278,7 +302,7 @@ const stderrWrite = (text) => void process.stderr.write(text);
278
302
  export async function acceptCommand(cwd, flags, files, ctx) {
279
303
  const out = ctx.out ?? stdoutWrite;
280
304
  const err = ctx.err ?? stderrWrite;
281
- const chosen = lawFiles(cwd, flags, files);
305
+ const chosen = lawFiles(cwd, flags, files, ctx.skip);
282
306
  if (chosen.length === 0) {
283
307
  err('no laws files found (looking for *.laws.ts)\n');
284
308
  return 1;
@@ -465,19 +489,138 @@ export async function promoteCommand(cwd, flags, files, ctx) {
465
489
  }
466
490
  return 0;
467
491
  }
492
+ const list = (projects) => projects.map((p) => (p.path === '' ? '.' : p.path)).join(', ');
493
+ /** `undefined` for an ordinary single-project run: no project flags, and the directory is not a monorepo root. */
494
+ function selectProjects(cwd, only, filter) {
495
+ const asked = only.length > 0 || filter.length > 0;
496
+ const monorepo = isMonorepoRoot(cwd);
497
+ if (!asked && !monorepo)
498
+ return undefined;
499
+ const all = discoverProjects(cwd);
500
+ const chosen = asked ? discoverProjects(cwd, { only, filter }) : all;
501
+ if (chosen.length === 0) {
502
+ const named = [...only.map((p) => `--project ${p}`), ...filter.map((g) => `--filter ${g}`)].join(' ');
503
+ throw new Error(all.length === 0
504
+ ? 'no tslaws project found here (a project is a directory with a tslaws.json; see "projects" in tslaws.json)'
505
+ : `no project matches ${named}; projects: ${list(all)}`);
506
+ }
507
+ return { chosen, all, fanOut: monorepo || chosen.some((p) => p.path !== '') };
508
+ }
509
+ /** The projects nested below `project`, relative to it. */
510
+ function nestedIn(project, all) {
511
+ const prefix = project.path === '' ? '' : `${project.path}/`;
512
+ return all
513
+ .filter((other) => other.path !== project.path && other.path.startsWith(prefix))
514
+ .map((other) => other.path.slice(prefix.length));
515
+ }
516
+ /** Commands that run once for every project of a monorepo; the rest run in one project. */
517
+ const fansOut = new Set(['check', 'accept', 'list', 'mutate', 'regressions']);
518
+ /** How a root run lays out machine output: one JSON object keyed by project, or ndjson lines tagged with `project`. */
519
+ function machineOf(command, flags) {
520
+ if (command === 'check') {
521
+ const reporter = String(flags.get('reporter') ?? (flags.has('json') ? 'json' : 'text'));
522
+ if (reporter === 'junit')
523
+ throw new Error('--reporter junit writes one XML document per project: pick one project with --project <dir>');
524
+ return reporter === 'json' || reporter === 'ndjson' ? reporter : 'text';
525
+ }
526
+ return (command === 'list' || command === 'mutate') && flags.has('json') ? 'json' : 'text';
527
+ }
528
+ /** One project at a time, each under a `── path ──` header, then one summary line. Nonzero if any project failed. */
529
+ async function runProjects(selection, machine, run) {
530
+ const failed = [];
531
+ const keyed = {};
532
+ for (const [index, project] of selection.chosen.entries()) {
533
+ const label = project.path === '' ? '.' : project.path;
534
+ let buffer = '';
535
+ const io = {
536
+ out: machine === 'json' ? (text) => void (buffer += text) : stdoutWrite,
537
+ skip: nestedIn(project, selection.all),
538
+ tag: machine === 'ndjson' ? label : undefined,
539
+ };
540
+ if (machine === 'text')
541
+ stdoutWrite(`${index === 0 ? '' : '\n'}── ${label} ──\n`);
542
+ let status;
543
+ let problem;
544
+ try {
545
+ status = await run(project, io);
546
+ }
547
+ catch (error) {
548
+ problem = error instanceof Error ? error.message : String(error);
549
+ stderrWrite(`${label}: ${problem}\n`);
550
+ status = 1;
551
+ }
552
+ if (status !== 0)
553
+ failed.push(label);
554
+ if (machine === 'json') {
555
+ try {
556
+ keyed[label] = buffer === '' ? { error: problem ?? 'no output (see stderr)' } : JSON.parse(buffer);
557
+ }
558
+ catch {
559
+ keyed[label] = { error: problem ?? 'output was not JSON' };
560
+ }
561
+ }
562
+ }
563
+ if (machine === 'json')
564
+ stdoutWrite(`${JSON.stringify(keyed, null, 2)}\n`);
565
+ const count = selection.chosen.length;
566
+ const summary = `${count} project${count === 1 ? '' : 's'}, ${failed.length} failed${failed.length === 0 ? '' : ` (${failed.join(', ')})`}\n`;
567
+ if (machine === 'text')
568
+ stdoutWrite(`\n${summary}`);
569
+ else
570
+ stderrWrite(summary);
571
+ return failed.length === 0 ? 0 : 1;
572
+ }
468
573
  export async function main(args) {
469
574
  if (args.includes('--help') || args.includes('-h')) {
470
575
  process.stdout.write(`${usage}\n`);
471
576
  return 0;
472
577
  }
473
- const { command, flags, files } = parse(args);
578
+ const { command, flags, files, projects, filters } = parse(args);
474
579
  const cwd = process.cwd();
580
+ // `init --project .` scaffolds right here, in a root that has projects or not.
581
+ const here = command === 'init' && projects.some((p) => p === '.' || p === './');
582
+ let selection;
583
+ try {
584
+ selection = here ? undefined : selectProjects(cwd, projects, filters);
585
+ }
586
+ catch (error) {
587
+ stderrWrite(`${error instanceof Error ? error.message : String(error)}\n`);
588
+ return 1;
589
+ }
590
+ if (selection === undefined)
591
+ return runOne(command, flags, files, cwd, direct);
592
+ // One project and a reporter that writes one document (junit) runs plainly: there is nothing to join.
593
+ const oneDocument = command === 'check' && flags.get('reporter') === 'junit' && selection.chosen.length === 1 && !flags.has('watch');
594
+ if (selection.fanOut && fansOut.has(command) && !flags.has('watch') && !oneDocument) {
595
+ if (files.length > 0 && command !== 'regressions') {
596
+ stderrWrite(`name files only inside one project: run \`tslaws ${command} ${files[0]}\` there, or pick it with --project <dir>\n`);
597
+ return 1;
598
+ }
599
+ let machine;
600
+ try {
601
+ machine = machineOf(command, flags);
602
+ }
603
+ catch (error) {
604
+ stderrWrite(`${error instanceof Error ? error.message : String(error)}\n`);
605
+ return 1;
606
+ }
607
+ return runProjects(selection, machine, (project, io) => runOne(command, flags, files, project.dir, io));
608
+ }
609
+ if (selection.chosen.length > 1) {
610
+ stderrWrite(`tslaws ${flags.has('watch') ? 'check --watch' : command} runs in one project and this repository has ${selection.chosen.length}: pick one with --project <dir> (${list(selection.chosen)})${command === 'init' ? ', or --project . to scaffold here' : ''}\n`);
611
+ return 1;
612
+ }
613
+ const [only] = selection.chosen;
614
+ return runOne(command, flags, files, only.dir, { ...direct, skip: nestedIn(only, selection.all) });
615
+ }
616
+ /** One command in one project directory. */
617
+ async function runOne(command, flags, files, cwd, run) {
475
618
  if (command === 'init') {
476
619
  process.stdout.write(`${init({ cwd, force: flags.has('force') }).join('\n')}\n\n${nextStep}\n`);
477
620
  return 0;
478
621
  }
479
622
  if (command === 'github') {
480
- const { githubCommand } = await import("./githubCli.js");
623
+ const { githubCommand, projectPathOf } = await import("./githubCli.js");
481
624
  // The token stays with tslaws: laws run in worker threads and the compiler in a child process, and both get a copy of
482
625
  // process.env, so a law under test could otherwise read the token and act as the bot.
483
626
  const env = { ...process.env };
@@ -490,6 +633,7 @@ export async function main(args) {
490
633
  chosen.compiler = checkoutCompiler(resolve(cwd, trusted)) ?? 'tsc-laws';
491
634
  return githubCommand(files[0], {
492
635
  cwd,
636
+ projectPath: projectPathOf(cwd, flags.get('project-path')),
493
637
  options: chosen,
494
638
  env,
495
639
  flags,
@@ -498,7 +642,7 @@ export async function main(args) {
498
642
  });
499
643
  }
500
644
  if (command === 'accept')
501
- return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
645
+ return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env, skip: run.skip });
502
646
  if (command === 'delegate')
503
647
  return delegateCommand(cwd, files[0], flags, { isTTY: process.stdin.isTTY === true, env: process.env });
504
648
  if (command === 'migrate')
@@ -508,15 +652,15 @@ export async function main(args) {
508
652
  if (command === 'promote')
509
653
  return promoteCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
510
654
  if (command === 'list') {
511
- const listed = listLawFiles(cwd);
512
- process.stdout.write(flags.has('json') ? `${JSON.stringify({ files: listed }, null, 2)}\n` : renderList(listed));
655
+ const listed = listLawFiles(cwd).filter((f) => outside([f.file], run.skip).length > 0);
656
+ run.out(flags.has('json') ? `${JSON.stringify({ files: listed }, null, 2)}\n` : renderList(listed));
513
657
  return 0;
514
658
  }
515
659
  if (command === 'propose')
516
660
  return proposeCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env });
517
661
  if (command === 'mutate') {
518
662
  // *.laws.ts arguments choose the laws; other files restrict which covered sources are mutated.
519
- const chosen = lawFiles(cwd, flags, files.filter((f) => f.endsWith('.laws.ts')));
663
+ const chosen = lawFiles(cwd, flags, files.filter((f) => f.endsWith('.laws.ts')), run.skip);
520
664
  if (chosen.length === 0) {
521
665
  process.stderr.write('no laws files found (looking for *.laws.ts)\n');
522
666
  return 1;
@@ -537,13 +681,13 @@ export async function main(args) {
537
681
  seed: flags.has('seed') ? Number(flags.get('seed')) : undefined,
538
682
  onProgress: flags.has('json') ? undefined : (line) => process.stderr.write(`${line}\n`),
539
683
  });
540
- process.stdout.write(flags.has('json') ? `${JSON.stringify(report, null, 2)}\n` : renderMutation(report));
684
+ run.out(flags.has('json') ? `${JSON.stringify(report, null, 2)}\n` : renderMutation(report));
541
685
  return report.ok ? 0 : 1;
542
686
  }
543
687
  if (command === 'regressions') {
544
688
  const action = files[0] ?? 'list';
545
689
  if (action === 'clear') {
546
- process.stdout.write(clearCorpus(cwd) ? 'cleared .tslaws/regressions\n' : 'no regression corpus to clear\n');
690
+ run.out(clearCorpus(cwd) ? 'cleared .tslaws/regressions\n' : 'no regression corpus to clear\n');
547
691
  return 0;
548
692
  }
549
693
  if (action !== 'list') {
@@ -551,13 +695,13 @@ export async function main(args) {
551
695
  return 1;
552
696
  }
553
697
  const corpus = listCorpus(cwd);
554
- process.stdout.write(corpus.length === 0
698
+ run.out(corpus.length === 0
555
699
  ? 'no stored counterexamples\n'
556
700
  : `${corpus.map((e) => `${e.file} ${e.law}: ${e.count} example${e.count === 1 ? '' : 's'}`).join('\n')}\n`);
557
701
  return 0;
558
702
  }
559
703
  if (command === 'ui') {
560
- const chosen = lawFiles(cwd, flags, files);
704
+ const chosen = lawFiles(cwd, flags, files, run.skip);
561
705
  if (chosen.length === 0) {
562
706
  process.stderr.write('no laws files found (looking for *.laws.ts)\n');
563
707
  return 1;
@@ -572,5 +716,5 @@ export async function main(args) {
572
716
  log: (line) => process.stdout.write(`${line}\n`),
573
717
  });
574
718
  }
575
- return flags.has('watch') ? watchChecks(cwd, flags, files) : runCheck(cwd, flags, files);
719
+ return flags.has('watch') ? watchChecks(cwd, flags, files) : runCheck(cwd, flags, files, run);
576
720
  }
package/dist/compile.d.ts CHANGED
@@ -23,5 +23,11 @@ export declare function readManifest(compiler: string, files: string[], cwd: str
23
23
  * error rather than an arbitrary flag handed to the compiler. `strict` is the one default these can override.
24
24
  */
25
25
  export declare function compilerFlags(options: Record<string, unknown> | undefined): string[];
26
- /** Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. */
26
+ /** Lowers every `.js` file the native compiler emitted into `dir` as ES modules, which is how `import.meta` is allowed. */
27
+ export declare function lowerEmittedModules(dir: string): void;
28
+ /**
29
+ * Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. The
30
+ * built-in compiler always reads the project as ES modules and lowers the output. The native compiler does so only for a
31
+ * project that uses `import.meta` (it reports TS1343 as CommonJS), so every other project builds exactly as before.
32
+ */
27
33
  export declare function build(compiler: string, files: string[], cwd: string): BuildResult;
package/dist/compile.js CHANGED
@@ -2,10 +2,12 @@ import { spawnSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
4
  import { dirname, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
5
6
  import { transformSync } from 'esbuild';
6
7
  import ts from 'typescript';
7
8
  import { lowerLawFile, usesLegacySyntax } from "./lower.js";
8
9
  import { readConfig } from "./coverage.js";
10
+ import { importMetaEnvGlobal } from "./runtimeEnv.js";
9
11
  /**
10
12
  * Runs the compiler, trying again when the system could not start it. On Windows a freshly built executable can be
11
13
  * briefly unavailable (a scanner holds it, the machine is out of handles), which surfaces as ENOENT or UNKNOWN.
@@ -162,7 +164,66 @@ export function compilerFlags(options) {
162
164
  }
163
165
  return flags;
164
166
  }
165
- /** Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. */
167
+ /**
168
+ * Turns emitted ES modules into CommonJS, and `import.meta.env` into the global the runner sets before any law loads
169
+ * (see runtimeEnv.ts). Everything else in `import.meta` is left to esbuild, which makes it an empty object.
170
+ */
171
+ function lowerModule(text, sourcefile) {
172
+ return transformSync(text, {
173
+ format: 'cjs',
174
+ target: 'es2022',
175
+ sourcefile,
176
+ define: { 'import.meta.env': `globalThis.${importMetaEnvGlobal}` },
177
+ logLevel: 'silent',
178
+ }).code;
179
+ }
180
+ /**
181
+ * CommonJS for ES module text the native compiler emitted, with `import.meta.env` read from the runner's global. TypeScript
182
+ * does the lowering, not esbuild, so the comments stay: the coverage analysis reads `@tslaws-exempt` from this output.
183
+ */
184
+ function lowerEmitted(text, file) {
185
+ const source = text
186
+ .replace(/\bimport\.meta\.env\b/g, `globalThis.${importMetaEnvGlobal}`)
187
+ .replace(/\bimport\.meta\b/g, '({})');
188
+ return ts.transpileModule(source, {
189
+ fileName: file,
190
+ compilerOptions: {
191
+ module: ts.ModuleKind.CommonJS,
192
+ target: ts.ScriptTarget.ES2022,
193
+ esModuleInterop: true,
194
+ allowJs: true,
195
+ },
196
+ }).outputText;
197
+ }
198
+ /** Lowers every `.js` file the native compiler emitted into `dir` as ES modules, which is how `import.meta` is allowed. */
199
+ export function lowerEmittedModules(dir) {
200
+ if (!existsSync(dir))
201
+ return;
202
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
203
+ const path = join(dir, entry.name);
204
+ if (entry.isDirectory())
205
+ lowerEmittedModules(path);
206
+ else if (entry.name.endsWith('.js')) {
207
+ try {
208
+ writeFileSync(path, lowerEmitted(readFileSync(path, 'utf8'), path));
209
+ }
210
+ catch {
211
+ // Output that does not parse (JSX kept because the project sets no `jsx`): the compiler's diagnostics say why.
212
+ }
213
+ }
214
+ }
215
+ }
216
+ /** The ambient `ImportMeta.env` declaration that ships with tslaws; also importable as `tslaws/env`. */
217
+ const envTypes = fileURLToPath(new URL('../env.d.ts', import.meta.url));
218
+ /** Whether `text` (compiler output) says `import.meta.env` has no declaration. */
219
+ const lacksEnvTypes = (text) => /TS2339.*'ImportMeta'/.test(text);
220
+ /** Whether `text` (compiler output) says the project uses `import.meta`, which CommonJS output does not allow. */
221
+ const usesImportMeta = (text) => /TS1343/.test(text);
222
+ /**
223
+ * Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves. The
224
+ * built-in compiler always reads the project as ES modules and lowers the output. The native compiler does so only for a
225
+ * project that uses `import.meta` (it reports TS1343 as CommonJS), so every other project builds exactly as before.
226
+ */
166
227
  export function build(compiler, files, cwd) {
167
228
  const outDir = join(cwd, '.tslaws', 'out');
168
229
  const extra = compilerFlags(readConfig(cwd).compilerOptions);
@@ -204,6 +265,30 @@ export function build(compiler, files, cwd) {
204
265
  run = launch(compiler, args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
205
266
  if (run.error !== undefined)
206
267
  throw new Error(cannotRun(compiler, run.error));
268
+ const output = () => `${run.stdout ?? ''}${run.stderr ?? ''}`;
269
+ const again = (again) => {
270
+ const next = launch(compiler, again, {
271
+ cwd,
272
+ encoding: 'utf8',
273
+ maxBuffer: 64 << 20,
274
+ env: compilerEnv(cwd, compiler),
275
+ });
276
+ if (next.error === undefined)
277
+ run = next;
278
+ };
279
+ // CommonJS output does not allow `import.meta`: read the project as ES modules instead, and lower the output below.
280
+ let lowering = false;
281
+ let used = args;
282
+ if (usesImportMeta(output())) {
283
+ used = args.map((arg, i) => (args[i - 1] === '--module' ? 'preserve' : arg));
284
+ lowering = true;
285
+ again(used);
286
+ }
287
+ // A project without an `ImportMeta.env` declaration gets the one that ships with tslaws, and the build runs again.
288
+ if (lacksEnvTypes(output()))
289
+ again([...used, envTypes]);
290
+ if (lowering)
291
+ lowerEmittedModules(outDir);
207
292
  return { outDir, diagnostics: `${run.stdout ?? ''}${run.stderr ?? ''}`.trim(), ok: run.status === 0 };
208
293
  }
209
294
  /** Every `node_modules/@types` from `cwd` upwards: where the compiler looks for global declarations by default. */
@@ -248,6 +333,7 @@ function buildBuiltin(args, files, cwd, outDir) {
248
333
  : ts.createSourceFile(name, text, languageVersion, true);
249
334
  };
250
335
  const roots = parsed.fileNames.map((f) => resolve(cwd, f));
336
+ let used = options;
251
337
  let program = ts.createProgram(roots, options, host);
252
338
  let diagnostics = ts.getPreEmitDiagnostics(program);
253
339
  // An error may only be a global the narrow setup left out (`process`, `document`, a test runner's types): check again
@@ -257,14 +343,18 @@ function buildBuiltin(args, files, cwd, outDir) {
257
343
  // `@types` is looked up from the project, not from wherever the process happens to be (the compiler remembers the first directory it saw).
258
344
  const typeRoots = parsed.options.typeRoots ?? typeRootsOf(cwd);
259
345
  const full = { ...options, types: parsed.options.types, lib: parsed.options.lib, typeRoots };
346
+ used = full;
260
347
  program = ts.createProgram(roots, full, host);
261
348
  diagnostics = ts.getPreEmitDiagnostics(program);
262
349
  }
350
+ // A project without an `ImportMeta.env` declaration gets the one that ships with tslaws, checked the same way.
351
+ if (diagnostics.some((d) => d.code === 2339 && ts.flattenDiagnosticMessageText(d.messageText, ' ').includes("'ImportMeta'"))) {
352
+ program = ts.createProgram([...roots, envTypes], used, host);
353
+ diagnostics = ts.getPreEmitDiagnostics(program);
354
+ }
263
355
  program.emit(undefined, (name, text) => {
264
356
  mkdirSync(dirname(name), { recursive: true });
265
- const code = name.endsWith('.js')
266
- ? transformSync(text, { format: 'cjs', target: 'es2022', sourcefile: name }).code
267
- : text;
357
+ const code = name.endsWith('.js') ? lowerModule(text, name) : text;
268
358
  writeFileSync(name, code);
269
359
  });
270
360
  const text = ts.formatDiagnostics(diagnostics, {
@@ -287,7 +377,7 @@ function buildBuiltin(args, files, cwd, outDir) {
287
377
  const buildCachePath = (cwd) => join(cwd, '.tslaws', 'build-cache.json');
288
378
  function buildKey(args, files, cwd) {
289
379
  const hash = createHash('sha256');
290
- hash.update(JSON.stringify([args, ts.version, toolStamp]));
380
+ hash.update(JSON.stringify([args, ts.version, toolStamp, importMetaEnvGlobal, envTypes]));
291
381
  for (const file of files)
292
382
  if (isLawFile(file, cwd) && existsSync(join(cwd, file)))
293
383
  hash.update(`
@@ -1,5 +1,6 @@
1
1
  import ts from 'typescript';
2
2
  import { type E2eConfig } from './e2e.ts';
3
+ import { type ImportMetaEnv } from './runtimeEnv.ts';
3
4
  import { type SolverName } from './solvers.ts';
4
5
  export interface CoverageConfig {
5
6
  cover?: string[];
@@ -24,6 +25,11 @@ export interface CoverageConfig {
24
25
  solvers?: SolverName[];
25
26
  /** esbuild plugin modules (paths relative to tslaws.json) that teach the browser bundler new source formats. */
26
27
  bundlerPlugins?: string[];
28
+ /**
29
+ * `import.meta.env` for code laws reach, on top of `process.env` and the defaults (`MODE` `test`, `DEV`, `PROD`, `SSR`,
30
+ * `BASE_URL`); its entries override both. See runtimeEnv.ts.
31
+ */
32
+ env?: Record<string, string | boolean>;
27
33
  /** Run settings; a command line flag beats them and they beat the built-in default. */
28
34
  runs?: number;
29
35
  propertyTimeoutMs?: number;
@@ -43,9 +49,18 @@ export interface CoverageReport {
43
49
  /** The source files the check covers, for the compiler to emit. */
44
50
  files: string[];
45
51
  }
46
- /** Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. */
47
- export declare function parseConfig(raw: unknown): CoverageConfig;
52
+ /** Why `value` is not a usable `projects` list (directory globs relative to the file), or undefined. */
53
+ export declare function projectsProblem(value: unknown): string | undefined;
54
+ /**
55
+ * Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. `extends`
56
+ * and `projects` are accepted (a string, and a list of globs) but are not part of the result: `readConfig` has
57
+ * already acted on `extends`, and discovery reads `projects` from the file itself.
58
+ */
59
+ export declare function parseConfig(raw: unknown, source?: string): CoverageConfig;
60
+ /** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
48
61
  export declare function readConfig(cwd: string): CoverageConfig;
62
+ /** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */
63
+ export declare function lawEnv(cwd: string, surface: 'node' | 'browser'): ImportMetaEnv;
49
64
  /** Source files matching the `cover` globs (a leading `!` excludes), minus laws files and declarations. */
50
65
  export declare function coverFiles(cwd: string, globs: string[]): string[];
51
66
  export interface CoverageInput {