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.
Files changed (122) hide show
  1. package/README.md +7 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +25 -5
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +211 -27
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +175 -34
  16. package/dist/compile.d.ts +15 -5
  17. package/dist/compile.js +198 -69
  18. package/dist/coverage.d.ts +38 -1
  19. package/dist/coverage.js +94 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +43 -1
  54. package/dist/projects.js +283 -11
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +5 -1
  58. package/dist/propertyWorker.js +7 -0
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +13 -5
  63. package/dist/runtimeEnv.js +48 -10
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/hooks/claude-hook.mjs +2 -0
  122. package/package.json +18 -6
package/dist/compile.js CHANGED
@@ -1,13 +1,16 @@
1
1
  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
- import { dirname, join, resolve } from 'node:path';
5
- import { fileURLToPath } from 'node:url';
4
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
6
  import { transformSync } from 'esbuild';
7
7
  import ts from 'typescript';
8
8
  import { lowerLawFile, usesLegacySyntax } from "./lower.js";
9
9
  import { readConfig } from "./coverage.js";
10
+ import { installLawRuntime, runtimeFile } from "./lawRuntime.js";
11
+ import { commonRoot, readResolution, resolutionCompilerOptions } from "./tsconfigResolve.js";
10
12
  import { importMetaEnvGlobal } from "./runtimeEnv.js";
13
+ import { sealLaws } from "./seal.js";
11
14
  /**
12
15
  * Runs the compiler, trying again when the system could not start it. On Windows a freshly built executable can be
13
16
  * briefly unavailable (a scanner holds it, the machine is out of handles), which surfaces as ENOENT or UNKNOWN.
@@ -101,9 +104,7 @@ function assertOneSyntax(files, cwd) {
101
104
  }
102
105
  export function readManifest(compiler, files, cwd) {
103
106
  if (usesBuiltin(compiler, files, cwd))
104
- return files
105
- .filter((f) => isLawFile(f, cwd))
106
- .flatMap((f) => (existsSync(join(cwd, f)) ? lowerFile(f, cwd).laws : []));
107
+ return sealLaws(cwd, files.filter((f) => isLawFile(f, cwd)).flatMap((f) => (existsSync(join(cwd, f)) ? lowerFile(f, cwd).laws : [])));
107
108
  assertOneSyntax(files, cwd);
108
109
  const run = launch(compiler, ['--laws-manifest', ...files], {
109
110
  cwd,
@@ -116,7 +117,7 @@ export function readManifest(compiler, files, cwd) {
116
117
  const text = (run.stdout ?? '').trim();
117
118
  if (text === '')
118
119
  throw new Error(`${compiler} --laws-manifest printed nothing: ${run.stderr ?? ''}`);
119
- return JSON.parse(text).laws;
120
+ return sealLaws(cwd, JSON.parse(text).laws);
120
121
  }
121
122
  const stringOptions = ['jsx', 'jsxFactory', 'jsxFragmentFactory', 'jsxImportSource'];
122
123
  const booleanOptions = [
@@ -164,28 +165,81 @@ export function compilerFlags(options) {
164
165
  }
165
166
  return flags;
166
167
  }
168
+ /** Turns emitted ES modules (with `import.meta` already rewritten) into CommonJS. */
169
+ function lowerModule(text, sourcefile) {
170
+ return transformSync(text, { format: 'cjs', target: 'es2022', sourcefile, logLevel: 'silent' }).code;
171
+ }
172
+ /** Where a compiled file came from: the source it mirrors under `root`, which is what `import.meta` should name. */
173
+ function sourceOfOutput(file, outDir, root) {
174
+ const mirrored = join(root, relative(outDir, file));
175
+ const endings = file.endsWith('.mjs')
176
+ ? ['.mts', '.mjs']
177
+ : file.endsWith('.cjs')
178
+ ? ['.cts', '.cjs']
179
+ : ['.ts', '.tsx', '.js', '.jsx'];
180
+ const stem = mirrored.replace(/\.[cm]?js$/, '');
181
+ return endings.map((ending) => `${stem}${ending}`).find((candidate) => existsSync(candidate)) ?? mirrored;
182
+ }
183
+ /** The first top-level `await` of a module (an `await` expression or `for await` outside every function), if any. */
184
+ function topLevelAwait(source) {
185
+ let found;
186
+ const visit = (node) => {
187
+ if (found !== undefined || ts.isFunctionLike(node) || ts.isClassLike(node))
188
+ return;
189
+ if (ts.isAwaitExpression(node) || (ts.isForOfStatement(node) && node.awaitModifier !== undefined))
190
+ found = node;
191
+ else
192
+ ts.forEachChild(node, visit);
193
+ };
194
+ visit(source);
195
+ return found;
196
+ }
167
197
  /**
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.
198
+ * Laws and the modules they load run as CommonJS (see `build`), where a module cannot wait at its top level. Said once,
199
+ * in terms of the way out, instead of as the loader's syntax error.
170
200
  */
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;
201
+ const awaitAdvice = 'top-level await is not supported in a law or in a module a law imports, because laws load as CommonJS; move the ' +
202
+ 'await into an async function (or into the law body, which may be async)';
203
+ const awaitProblem = (file) => `${file}: error: ${awaitAdvice}`;
204
+ /** What replaces such a module in the output, so the law that loads it fails with the reason and not a syntax error. */
205
+ const awaitStub = (file) => `throw new Error(${JSON.stringify(`${file}: ${awaitAdvice}`)});\n`;
206
+ /**
207
+ * `import.meta` for a module that is not run as written: `env` is the global the runner sets before any law loads (see
208
+ * runtimeEnv.ts), `url`, `filename` and `dirname` name the source file (not the copy in `.tslaws/out`), and any other
209
+ * use of `import.meta` is an object holding those four. Found as syntax so that a string or comment that says the same
210
+ * words is left alone. Returns the new text and whether the module waits at its top level.
211
+ */
212
+ function rewriteImportMeta(text, file, source) {
213
+ const parsed = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, false, ts.ScriptKind.JS);
214
+ const edits = [];
215
+ const env = `globalThis.${importMetaEnvGlobal}`;
216
+ const known = {
217
+ url: JSON.stringify(pathToFileURL(source).href),
218
+ filename: JSON.stringify(source),
219
+ dirname: JSON.stringify(dirname(source)),
220
+ env,
221
+ };
222
+ const isMeta = (node) => ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword && node.name.text === 'meta';
223
+ const visit = (node) => {
224
+ if (ts.isPropertyAccessExpression(node) && isMeta(node.expression) && node.name.text in known)
225
+ edits.push({ start: node.getStart(parsed), end: node.end, text: known[node.name.text] });
226
+ else if (isMeta(node)) {
227
+ const members = Object.entries(known).map(([key, value]) => `${key}: ${value}`);
228
+ edits.push({ start: node.getStart(parsed), end: node.end, text: `({ ${members.join(', ')} })` });
229
+ }
230
+ else
231
+ ts.forEachChild(node, visit);
232
+ };
233
+ visit(parsed);
234
+ const rewritten = edits.reduceRight((out, e) => out.slice(0, e.start) + e.text + out.slice(e.end), text);
235
+ return { text: rewritten, awaits: topLevelAwait(parsed) !== undefined };
179
236
  }
180
237
  /**
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.
238
+ * CommonJS for ES module text, with `import.meta` rewritten as above. TypeScript does the lowering, not esbuild, so the
239
+ * comments stay: the coverage analysis reads `@tslaws-exempt` from this output.
183
240
  */
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, {
241
+ function lowerToCommonJs(text, file) {
242
+ return ts.transpileModule(text, {
189
243
  fileName: file,
190
244
  compilerOptions: {
191
245
  module: ts.ModuleKind.CommonJS,
@@ -195,40 +249,80 @@ function lowerEmitted(text, file) {
195
249
  },
196
250
  }).outputText;
197
251
  }
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.
252
+ /**
253
+ * Lowers what the native compiler emitted into `dir` as ES modules, which is how `import.meta` is allowed: `.js` becomes
254
+ * CommonJS and the `import.meta` of a `.mjs` (from a `.mts`, kept as an ES module Node can load) is rewritten in place.
255
+ * `outDir` and `root` say where `dir` sits and what it mirrors, so `import.meta` can name the source. Returns one line
256
+ * per module that cannot be lowered.
257
+ */
258
+ export function lowerEmittedModules(dir, where = {}) {
259
+ const problems = [];
260
+ const outDir = where.outDir ?? dir;
261
+ const root = where.root ?? dir;
262
+ const lowerIn = (current) => {
263
+ if (!existsSync(current))
264
+ return;
265
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
266
+ const path = join(current, entry.name);
267
+ if (entry.isDirectory())
268
+ lowerIn(path);
269
+ else if (/\.m?js$/.test(entry.name)) {
270
+ try {
271
+ const { text, awaits } = rewriteImportMeta(readFileSync(path, 'utf8'), path, sourceOfOutput(path, outDir, root));
272
+ if (awaits) {
273
+ problems.push(awaitProblem(slash(relative(outDir, path))));
274
+ writeFileSync(path, awaitStub(slash(relative(outDir, path))));
275
+ }
276
+ else
277
+ writeFileSync(path, entry.name.endsWith('.mjs') ? text : lowerToCommonJs(text, path));
278
+ }
279
+ catch {
280
+ // Output that does not parse (JSX kept because the project sets no `jsx`): the compiler's diagnostics say why.
281
+ }
212
282
  }
213
283
  }
214
- }
284
+ };
285
+ lowerIn(dir);
286
+ return problems;
215
287
  }
216
288
  /** The ambient `ImportMeta.env` declaration that ships with tslaws; also importable as `tslaws/env`. */
217
289
  const envTypes = fileURLToPath(new URL('../env.d.ts', import.meta.url));
218
290
  /** Whether `text` (compiler output) says `import.meta.env` has no declaration. */
219
291
  const lacksEnvTypes = (text) => /TS2339.*'ImportMeta'/.test(text);
292
+ /** Whether `text` (compiler output) says a module waits at its top level while the output is CommonJS (TS1378). */
293
+ const hasTopLevelAwaitError = (text) => /TS1378/.test(text);
220
294
  /** Whether `text` (compiler output) says the project uses `import.meta`, which CommonJS output does not allow. */
221
295
  const usesImportMeta = (text) => /TS1343/.test(text);
222
296
  /**
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.
297
+ * Compiles `files` to CommonJS plus declarations in `.tslaws/out` under `cwd`, so `node_modules` still resolves.
298
+ * Module resolution follows the project's tsconfig (see tsconfigResolve.ts), for the compiler and, through the runtime
299
+ * hooks, for Node when it loads the output. The built-in compiler always reads the project as ES modules and lowers the
300
+ * output. The native compiler does so only for a project that uses `import.meta` (it reports TS1343 as CommonJS), so
301
+ * every other project builds exactly as before.
226
302
  */
227
303
  export function build(compiler, files, cwd) {
304
+ const resolution = readResolution(cwd);
305
+ const result = compile(compiler, files, cwd, resolution);
306
+ const bundlerPlugins = (readConfig(cwd).bundlerPlugins ?? []).map((path) => resolve(cwd, path));
307
+ const runtime = { cwd, options: resolution?.options, outDir: result.outDir, bundlerPlugins };
308
+ installLawRuntime(runtime);
309
+ try {
310
+ writeFileSync(join(result.outDir, runtimeFile), JSON.stringify(runtime));
311
+ }
312
+ catch {
313
+ // A worker then loads the output without the aliases; the error it reports names the import.
314
+ }
315
+ return result;
316
+ }
317
+ function compile(compiler, files, cwd, resolution) {
228
318
  const outDir = join(cwd, '.tslaws', 'out');
319
+ const builtin = usesBuiltin(compiler, files, cwd);
320
+ // The compiler wants every source file under one root, and `paths` can lead out of the project (a sibling package),
321
+ // so the root is the common ancestor and the output mirrors the tree from there. The built-in path writes only what
322
+ // is inside the project, so it keeps the project as the root.
323
+ const root = builtin ? cwd : commonRoot(cwd, resolution?.options);
229
324
  const extra = compilerFlags(readConfig(cwd).compilerOptions);
230
- const args = [
231
- '--ignoreConfig',
325
+ const flags = [
232
326
  '--target',
233
327
  'es2022',
234
328
  '--module',
@@ -240,14 +334,15 @@ export function build(compiler, files, cwd) {
240
334
  '--esModuleInterop',
241
335
  '--declaration',
242
336
  '--rootDir',
243
- cwd,
337
+ root,
244
338
  '--outDir',
245
339
  outDir,
246
340
  ...extra,
247
- ...files,
248
341
  ];
249
- const builtin = usesBuiltin(compiler, files, cwd);
250
- const reused = builtin ? cachedBuild(args, files, cwd, outDir) : undefined;
342
+ const args = ['--ignoreConfig', ...flags, ...files];
343
+ // What the options say is part of what was built.
344
+ const keyArgs = [...args, JSON.stringify(resolution?.options ?? null)];
345
+ const reused = builtin ? cachedBuild(keyArgs, files, cwd, outDir) : undefined;
251
346
  if (reused !== undefined)
252
347
  return reused;
253
348
  rmSync(outDir, { recursive: true, force: true });
@@ -255,41 +350,59 @@ export function build(compiler, files, cwd) {
255
350
  // The output is CommonJS whatever the project's own package.json says.
256
351
  writeFileSync(join(outDir, 'package.json'), JSON.stringify({ type: 'commonjs' }));
257
352
  if (builtin)
258
- return buildBuiltin(args, files, cwd, outDir);
259
- let run = launch(compiler, args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
353
+ return buildBuiltin(args, keyArgs, files, cwd, outDir, resolution);
354
+ // `paths` is not a command line option, so the compiler gets the resolution options in a generated tsconfig that names
355
+ // the files; everything else stays a flag, and flags win over the file. Without any, the flags alone do as before.
356
+ const project = join(cwd, '.tslaws', 'resolution.tsconfig.json');
357
+ const argsFor = (flagList, more = []) => {
358
+ if (resolution === undefined)
359
+ return ['--ignoreConfig', ...flagList, ...files, ...more];
360
+ writeFileSync(project, JSON.stringify({
361
+ compilerOptions: { ...resolution.options, rootDir: root },
362
+ files: [...files, ...more].map((f) => resolve(cwd, f)),
363
+ }));
364
+ return ['-p', project, ...flagList];
365
+ };
366
+ const given = argsFor(flags);
367
+ let run = launch(compiler, given, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
260
368
  // A compiler that dies without a word (out of memory on a busy machine) is run again; a type error always says so.
261
369
  for (let attempt = 0; attempt < 2 &&
262
370
  run.error === undefined &&
263
371
  run.status !== 0 &&
264
372
  `${run.stdout ?? ''}${run.stderr ?? ''}`.trim() === ''; attempt += 1)
265
- run = launch(compiler, args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
373
+ run = launch(compiler, given, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
266
374
  if (run.error !== undefined)
267
375
  throw new Error(cannotRun(compiler, run.error));
268
376
  const output = () => `${run.stdout ?? ''}${run.stderr ?? ''}`;
269
- const again = (again) => {
270
- const next = launch(compiler, again, {
377
+ const again = (next) => {
378
+ const rerun = launch(compiler, next, {
271
379
  cwd,
272
380
  encoding: 'utf8',
273
381
  maxBuffer: 64 << 20,
274
382
  env: compilerEnv(cwd, compiler),
275
383
  });
276
- if (next.error === undefined)
277
- run = next;
384
+ if (rerun.error === undefined)
385
+ run = rerun;
278
386
  };
279
- // CommonJS output does not allow `import.meta`: read the project as ES modules instead, and lower the output below.
387
+ // CommonJS output does not allow `import.meta` or a top-level await: read the project as ES modules instead, and lower
388
+ // the output below, where a module that waits at its top level is replaced by a stub that says so.
280
389
  let lowering = false;
281
- let used = args;
282
- if (usesImportMeta(output())) {
283
- used = args.map((arg, i) => (args[i - 1] === '--module' ? 'preserve' : arg));
390
+ let used = flags;
391
+ if (usesImportMeta(output()) || hasTopLevelAwaitError(output())) {
392
+ used = flags.map((flag, i) => (flags[i - 1] === '--module' ? 'preserve' : flag));
284
393
  lowering = true;
285
- again(used);
394
+ again(argsFor(used));
286
395
  }
287
396
  // A project without an `ImportMeta.env` declaration gets the one that ships with tslaws, and the build runs again.
288
397
  if (lacksEnvTypes(output()))
289
- again([...used, envTypes]);
290
- if (lowering)
291
- lowerEmittedModules(outDir);
292
- return { outDir, diagnostics: `${run.stdout ?? ''}${run.stderr ?? ''}`.trim(), ok: run.status === 0 };
398
+ again(argsFor(used, [envTypes]));
399
+ const problems = lowering ? lowerEmittedModules(outDir, { outDir, root }) : [];
400
+ // The project's own files sit where they do under the root, so its output is that deep in `outDir`.
401
+ return {
402
+ outDir: join(outDir, relative(root, cwd)),
403
+ diagnostics: [output().trim(), ...problems].filter((part) => part !== '').join('\n'),
404
+ ok: run.status === 0 && problems.length === 0,
405
+ };
293
406
  }
294
407
  /** Every `node_modules/@types` from `cwd` upwards: where the compiler looks for global declarations by default. */
295
408
  function typeRootsOf(cwd) {
@@ -303,11 +416,13 @@ function typeRootsOf(cwd) {
303
416
  }
304
417
  }
305
418
  /** Compiles in-process with stock TypeScript: law files are lowered in memory, nothing is written next to them. */
306
- function buildBuiltin(args, files, cwd, outDir) {
419
+ function buildBuiltin(args, keyArgs, files, cwd, outDir, resolution) {
307
420
  const at = args.indexOf('--moduleResolution');
308
421
  const parsed = ts.parseCommandLine(at < 0 ? args : [...args.slice(0, at), ...args.slice(at + 2)]);
309
422
  // Types resolve the bundler way, so package `exports` (tslaws/browser) work; the ES output is made CommonJS below.
310
423
  const options = {
424
+ // The tsconfig's resolution first, so the project's own compilerOptions win over it.
425
+ ...resolutionCompilerOptions(resolution?.options),
311
426
  ...parsed.options,
312
427
  module: ts.ModuleKind.ESNext,
313
428
  moduleResolution: ts.ModuleResolutionKind.Bundler,
@@ -352,11 +467,25 @@ function buildBuiltin(args, files, cwd, outDir) {
352
467
  program = ts.createProgram([...roots, envTypes], used, host);
353
468
  diagnostics = ts.getPreEmitDiagnostics(program);
354
469
  }
470
+ const problems = [];
355
471
  program.emit(undefined, (name, text) => {
472
+ // A source file outside the project (reached through `paths`) is checked and loaded in place, never written here.
473
+ const under = relative(outDir, name);
474
+ if (under.startsWith('..') || isAbsolute(under))
475
+ return;
356
476
  mkdirSync(dirname(name), { recursive: true });
357
- const code = name.endsWith('.js') ? lowerModule(text, name) : text;
358
- writeFileSync(name, code);
477
+ if (!/\.m?js$/.test(name))
478
+ return void writeFileSync(name, text);
479
+ const rewritten = rewriteImportMeta(text, name, sourceOfOutput(name, outDir, cwd));
480
+ if (rewritten.awaits) {
481
+ problems.push(awaitProblem(slash(under)));
482
+ writeFileSync(name, awaitStub(slash(under)));
483
+ }
484
+ else
485
+ writeFileSync(name, name.endsWith('.mjs') ? rewritten.text : lowerModule(rewritten.text, name));
359
486
  });
487
+ // Such a file is outside the root directory by design (TS6059).
488
+ diagnostics = diagnostics.filter((d) => d.code !== 6059);
360
489
  const text = ts.formatDiagnostics(diagnostics, {
361
490
  getCanonicalFileName: (f) => f,
362
491
  getCurrentDirectory: () => cwd,
@@ -364,11 +493,11 @@ function buildBuiltin(args, files, cwd, outDir) {
364
493
  });
365
494
  const result = {
366
495
  outDir,
367
- diagnostics: text.trim(),
368
- ok: diagnostics.every((d) => d.category !== ts.DiagnosticCategory.Error),
496
+ diagnostics: [text.trim(), ...problems].filter((part) => part !== '').join('\n'),
497
+ ok: problems.length === 0 && diagnostics.every((d) => d.category !== ts.DiagnosticCategory.Error),
369
498
  };
370
499
  Object.defineProperty(result, 'program', { value: program, enumerable: false });
371
- saveBuildCache(args, files, cwd, result, program
500
+ saveBuildCache(keyArgs, files, cwd, result, program
372
501
  .getSourceFiles()
373
502
  .map((f) => f.fileName)
374
503
  .filter((f) => !overrides.has(slash(resolve(f)))));
@@ -1,11 +1,17 @@
1
1
  import ts from 'typescript';
2
2
  import { type E2eConfig } from './e2e.ts';
3
+ import { type CertifyMode } from './certificates.ts';
3
4
  import { type ImportMetaEnv } from './runtimeEnv.ts';
4
5
  import { type SolverName } from './solvers.ts';
5
6
  export interface CoverageConfig {
6
7
  cover?: string[];
7
8
  /** Compiler options the runner passes to tsc; see `compilerFlags` in compile.ts for the supported keys. */
8
9
  compilerOptions?: Record<string, unknown>;
10
+ /**
11
+ * Where laws take their module resolution (`paths`, `baseUrl`, project references) from: a tsconfig path relative to
12
+ * tslaws.json, or `false` for none. Default: the nearest tsconfig.json above the project. See tsconfigResolve.ts.
13
+ */
14
+ tsconfig?: string | false;
9
15
  /** End-to-end laws: the app to drive; see `parseE2eConfig`. */
10
16
  e2e?: E2eConfig;
11
17
  /**
@@ -23,8 +29,19 @@ export interface CoverageConfig {
23
29
  * must also answer `unsat` or the law is `bounded`. Z3 is required. See solvers.ts.
24
30
  */
25
31
  solvers?: SolverName[];
32
+ /**
33
+ * Check every proof Z3 finds with cvc5 (an Alethe proof) and Carcara, and record the law as `certified` or
34
+ * `uncertified`. `"require"` makes anything short of `certified` an error. Default off. See certificates.ts.
35
+ */
36
+ certify?: CertifyMode;
26
37
  /** esbuild plugin modules (paths relative to tslaws.json) that teach the browser bundler new source formats. */
27
38
  bundlerPlugins?: string[];
39
+ /**
40
+ * Directories outside the project (paths relative to tslaws.json) whose reviewed files the law sandbox may read, besides
41
+ * the workspace packages and the `paths` and `references` targets of the tsconfig. Dotfiles and the home directory are
42
+ * refused whatever is named. See sandbox.ts.
43
+ */
44
+ sandboxReads?: string[];
28
45
  /**
29
46
  * `import.meta.env` for code laws reach, on top of `process.env` and the defaults (`MODE` `test`, `DEV`, `PROD`, `SSR`,
30
47
  * `BASE_URL`); its entries override both. See runtimeEnv.ts.
@@ -35,8 +52,12 @@ export interface CoverageConfig {
35
52
  propertyTimeoutMs?: number;
36
53
  proofTimeoutMs?: number;
37
54
  bound?: number;
38
- /** Accepting laws on GitHub: see github.ts. When present, `tslaws accept` refuses to run outside that workflow. */
55
+ /** The most laws, proofs and solvers that run at once (the CPU budget); `--jobs` and `TSLAWS_JOBS` beat it. Not sealed: it is the machine's, not the project's. */
56
+ jobs?: number;
57
+ /** Accepting laws on GitHub: see github.ts. When present, `tslaws accept` refuses to run unless `github.local` is true (the default). */
39
58
  github?: unknown;
59
+ /** `tslaws security deps`: the severity that fails the check, offline mode, the cache; see security/deps/config.ts. */
60
+ security?: unknown;
40
61
  }
41
62
  export interface Uncovered {
42
63
  file: string;
@@ -57,6 +78,22 @@ export declare function projectsProblem(value: unknown): string | undefined;
57
78
  * already acted on `extends`, and discovery reads `projects` from the file itself.
58
79
  */
59
80
  export declare function parseConfig(raw: unknown, source?: string): CoverageConfig;
81
+ /**
82
+ * The text of an `extends` value if it is one this tool will follow: a non-empty relative path with forward slashes only.
83
+ * An absolute path, a drive or UNC path, a backslash, or a NUL is refused, so the on-disk loader and the GitHub checks
84
+ * that read the same files through the API resolve one target and never two.
85
+ */
86
+ export declare function checkExtendsValue(value: unknown): string;
87
+ /**
88
+ * Where `extends` points, as a repository path: `fromFile` is the repository path of the file that names it. Refuses
89
+ * what `checkExtendsValue` does, and a target that leaves the repository.
90
+ */
91
+ export declare function extendsTarget(fromFile: string, value: unknown): string;
92
+ /**
93
+ * The directory no `extends` may leave: the nearest enclosing directory with a `.git`, else the highest enclosing one
94
+ * that carries a workspace file (`tslaws.json`, `package.json` or `pnpm-workspace.yaml`), else `cwd` itself.
95
+ */
96
+ export declare function extendsRoot(cwd: string): string;
60
97
  /** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
61
98
  export declare function readConfig(cwd: string): CoverageConfig;
62
99
  /** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */