lawspec 0.21.0 → 0.22.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/CHANGELOG.md +65 -1
- package/README.md +3 -3
- package/beam-coverage.mjs +160 -0
- package/beam-doctor.mjs +306 -0
- package/bin/lawspec.mjs +71 -31
- package/build.json +232 -38
- package/compatibility.json +17 -0
- package/core.wasm +2 -2
- package/doctor.mjs +7 -1
- package/examples/native-payments/elixir/lawspec.json +149 -0
- package/examples/native-payments/elixir/lib/payments_domain.ex +54 -0
- package/examples/native-payments/elixir/test/support/payment_generators.ex +9 -0
- package/examples/native-payments/erlang/include/payments_domain.hrl +2 -0
- package/examples/native-payments/erlang/lawspec.json +148 -0
- package/examples/native-payments/erlang/src/payments_domain.erl +21 -0
- package/examples/native-payments/erlang/test/payment_generators.erl +10 -0
- package/examples/native-payments/gleam/lawspec.json +149 -0
- package/examples/native-payments/gleam/prepare.mjs +48 -0
- package/examples/native-payments/gleam/src/payments_domain.gleam +32 -0
- package/examples/native-payments/gleam/test/payment_generators.gleam +13 -0
- package/failure-database.mjs +46 -0
- package/index.d.ts +10 -1
- package/native-examples.mjs +7 -2
- package/package.json +1 -1
- package/templates.mjs +92 -3
- package/test-command.mjs +161 -15
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,69 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.22.0] - 2026-10-10
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Erlang, Elixir and Gleam targets share a BEAM runtime and generate native
|
|
14
|
+
data types, adapters and checked definitions. Tests use PropEr with EUnit,
|
|
15
|
+
StreamData with ExUnit, and qcheck with gleeunit, including each framework's
|
|
16
|
+
own generation and shrinking.
|
|
17
|
+
- BEAM ability handlers, typed failures, asynchronous tasks, workflow policies
|
|
18
|
+
and built-in abilities, with native type, function, handler and generator
|
|
19
|
+
bindings. Native payment examples demonstrate adopting and removing
|
|
20
|
+
generated tests in an existing application.
|
|
21
|
+
- BEAM stateful models, collection models, opaque handles, consistency
|
|
22
|
+
models, scenarios, typed sessions and mailboxes, and actors with OTP
|
|
23
|
+
supervision. Stateful checks have individual identities for CLI selection,
|
|
24
|
+
reports, caching and replay.
|
|
25
|
+
- Secure BEAM distribution uses the shared wire format and cryptographic
|
|
26
|
+
seed keys. Projects importing `lawspec.crypto` or `lawspec.network` build a
|
|
27
|
+
small C/OpenSSL NIF before compilation. The bridge requires OTP 29,
|
|
28
|
+
OpenSSL 3.5 or later matching OTP's OpenSSL major version, and a Unix C
|
|
29
|
+
toolchain on macOS, Linux or WSL. Projects without those imports have no
|
|
30
|
+
native crypto build step.
|
|
31
|
+
- BEAM setup guides, toolchain checks, offline dependencies, JUnit reporting,
|
|
32
|
+
coverage, and failure replay from the exact shrunk inputs.
|
|
33
|
+
- BEAM harness strategies, generated-case coverage and labels, targeted
|
|
34
|
+
search, repeats and flaky retries, skips and known failures, random law
|
|
35
|
+
order, parallel execution and benchmarks in the native test frameworks.
|
|
36
|
+
- BEAM matcher, table and description examples, with recorded values read
|
|
37
|
+
from the shared project folder and updated by `lawspec test --update-recorded`.
|
|
38
|
+
- BEAM per-case and shared resources use dedicated owner processes for
|
|
39
|
+
acquisition, reset and release. Harness timeouts cancel test workers and
|
|
40
|
+
join their asynchronous children; cleanup has a separate bounded allowance.
|
|
41
|
+
Cleanup failures fail the run, including under retries and known failures.
|
|
42
|
+
|
|
43
|
+
### Fixed
|
|
44
|
+
|
|
45
|
+
- Recorded values use one typed format across targets, including exact
|
|
46
|
+
numbers, floats, bytes, raw text, presence and nested data. Identity labels
|
|
47
|
+
are local to each recording. Existing extended scalar recordings may need
|
|
48
|
+
updating with `lawspec test --update-recorded`.
|
|
49
|
+
- Generated TypeScript, Python, Go and Kotlin product types retain their type
|
|
50
|
+
parameters when their sole constructor fixes a parameter's type.
|
|
51
|
+
- Generated Haskell constructors and codecs apply fixed type parameters to
|
|
52
|
+
their fields, including nested data.
|
|
53
|
+
- Erlang EUnit output retains deeper failure diagnostics, including native
|
|
54
|
+
generator identities used by acceptance checks.
|
|
55
|
+
- CI logs include exit statuses, and acceptance logs retain completed stages
|
|
56
|
+
when a runner exits unexpectedly.
|
|
57
|
+
- Failure databases and reports keep separate project roots apart, including
|
|
58
|
+
projects using the same target. Replaying or repairing one project's
|
|
59
|
+
failure cannot clear another project's counterexample.
|
|
60
|
+
- CLI JUnit output retains cases from flat Node reports and nested native
|
|
61
|
+
suites.
|
|
62
|
+
- BEAM JUnit output includes intentionally skipped laws and their reasons;
|
|
63
|
+
skips remain separate from evidence that a test executed. Scheduled cases
|
|
64
|
+
keep their declaring unit, so identical test names in different units
|
|
65
|
+
remain distinct.
|
|
66
|
+
- BEAM generators follow scalar and constructor-field refinements, including
|
|
67
|
+
named symbol identities, minimum lengths and bounds depending on earlier
|
|
68
|
+
fields. Native shrinking preserves these constraints.
|
|
69
|
+
- Generated BEAM sets and maps keep their portable order and distinct keys;
|
|
70
|
+
native values with unsorted or duplicate entries fail validation.
|
|
71
|
+
|
|
9
72
|
## [0.21.0] - 2026-10-07
|
|
10
73
|
|
|
11
74
|
### Added
|
|
@@ -1217,7 +1280,8 @@ A maintenance release. The language, generated code and API are unchanged from
|
|
|
1217
1280
|
machine-sized bindings reject an architecture mismatch. Rust adapters take
|
|
1218
1281
|
owned values.
|
|
1219
1282
|
|
|
1220
|
-
[Unreleased]: https://github.com/brain-fuel/lawspec/compare/v0.
|
|
1283
|
+
[Unreleased]: https://github.com/brain-fuel/lawspec/compare/v0.22.0...HEAD
|
|
1284
|
+
[0.22.0]: https://github.com/brain-fuel/lawspec/compare/v0.21.0...v0.22.0
|
|
1221
1285
|
[0.21.0]: https://github.com/brain-fuel/lawspec/compare/v0.20.1...v0.21.0
|
|
1222
1286
|
[0.20.1]: https://github.com/brain-fuel/lawspec/compare/v0.20.0...v0.20.1
|
|
1223
1287
|
[0.20.0]: https://github.com/brain-fuel/lawspec/compare/v0.19.1...v0.20.0
|
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ Node 22+ and the selected target's build tools are required. No Haskell
|
|
|
30
30
|
toolchain is needed. The reference platforms are macOS and Linux.
|
|
31
31
|
|
|
32
32
|
```sh
|
|
33
|
-
npm install --save-dev lawspec@0.
|
|
33
|
+
npm install --save-dev lawspec@0.22.0
|
|
34
34
|
npx lawspec --version
|
|
35
35
|
```
|
|
36
36
|
|
|
@@ -40,8 +40,8 @@ LawSpec can create `package.json` and its test script:
|
|
|
40
40
|
```sh
|
|
41
41
|
mkdir lawspec-example
|
|
42
42
|
cd lawspec-example
|
|
43
|
-
npm exec --package=lawspec@0.
|
|
44
|
-
npm install --save-dev lawspec@0.
|
|
43
|
+
npm exec --package=lawspec@0.22.0 -- lawspec init --target javascript
|
|
44
|
+
npm install --save-dev lawspec@0.22.0
|
|
45
45
|
npx lawspec check
|
|
46
46
|
npx lawspec explain 'example.atoi_codec::itoa and then atoi yields a'
|
|
47
47
|
npx lawspec doctor
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Generated from templates/npm/beam-coverage.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
import {execFile} from "node:child_process";
|
|
3
|
+
import {createHash} from "node:crypto";
|
|
4
|
+
import {mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile} from "node:fs/promises";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import {promisify} from "node:util";
|
|
8
|
+
|
|
9
|
+
const exec = promisify(execFile);
|
|
10
|
+
export function beamCoverageRequirement(target, report) {
|
|
11
|
+
if (target.language === "gleam" && Number(report?.versions?.gleam?.split(".")[1] ?? 0) < 19)
|
|
12
|
+
return {tool: "Gleam 1.19 for source coverage", install: "upgrade Gleam to 1.19 so native counters refer to the original source lines"};
|
|
13
|
+
if (target.language === "elixir" && report?.coverage?.tool !== "Mix.Tasks.Test.Coverage")
|
|
14
|
+
return {tool: "Mix.Tasks.Test.Coverage", install: "set test_coverage[:tool] to Mix.Tasks.Test.Coverage in mix.exs"};
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const collector = String.raw`#!/usr/bin/env escript
|
|
19
|
+
-mode(compile).
|
|
20
|
+
main([Input, Output]) ->
|
|
21
|
+
try
|
|
22
|
+
{ok, Bytes} = file:read_file(Input),
|
|
23
|
+
#{<<"runs">> := Runs, <<"directory">> := Directory} = json:decode(Bytes),
|
|
24
|
+
{ok, _} = cover:start(),
|
|
25
|
+
[ok = cover:import(text(maps:get(<<"file">>, Run))) || Run <- Runs],
|
|
26
|
+
Beams = lists:foldl(fun(Run, Acc) -> maps:merge(Acc, maps:get(<<"beams">>, Run, #{})) end, #{}, Runs),
|
|
27
|
+
Modules = [analyse(Module, text(Directory), Beams) || Module <- lists:sort(cover:imported_modules())],
|
|
28
|
+
true = Modules =/= [],
|
|
29
|
+
ok = file:write_file(Output, json:encode(Modules)),
|
|
30
|
+
cover:stop()
|
|
31
|
+
catch Class:Reason:Stack ->
|
|
32
|
+
io:format(standard_error, "Cannot collect BEAM coverage: ~tp:~tp~n~tp~n", [Class, Reason, Stack]), halt(1)
|
|
33
|
+
end.
|
|
34
|
+
|
|
35
|
+
analyse(Module, Directory, Beams) ->
|
|
36
|
+
{ok, Calls} = cover:analyse(Module, calls, line),
|
|
37
|
+
Lines = lists:foldl(fun
|
|
38
|
+
({{_, Line}, Hits}, Acc) when Line > 0 -> maps:update_with(Line, fun(N) -> N + Hits end, Hits, Acc);
|
|
39
|
+
(_, Acc) -> Acc
|
|
40
|
+
end, #{}, Calls),
|
|
41
|
+
Name = atom_to_binary(Module),
|
|
42
|
+
Rows = [#{line => Line, hits => Hits} || {Line, Hits} <- lists:sort(maps:to_list(Lines))],
|
|
43
|
+
case maps:find(Name, Beams) of
|
|
44
|
+
{ok, Beam} -> #{name => Name, lines => Rows, source => source(Module, text(Beam))};
|
|
45
|
+
error ->
|
|
46
|
+
File = binary_to_list(binary:encode_hex(crypto:hash(sha256, Name), lowercase)) ++ ".html",
|
|
47
|
+
{ok, _} = cover:analyse_to_file(Module, [html, {outfile, filename:join(Directory, File)}]),
|
|
48
|
+
#{name => Name, lines => Rows, report => unicode:characters_to_binary(File)}
|
|
49
|
+
end.
|
|
50
|
+
|
|
51
|
+
source(Module, Beam) ->
|
|
52
|
+
{ok, {Module, [{compile_info, Info}]}} = beam_lib:chunks(Beam, [compile_info]),
|
|
53
|
+
Source = case proplists:get_value(source, Info) of
|
|
54
|
+
undefined ->
|
|
55
|
+
{ok, {Module, [{abstract_code, {raw_abstract_v1, Forms}}]}} = beam_lib:chunks(Beam, [abstract_code]),
|
|
56
|
+
[File | _] = [F || {attribute, _, file, {F, _}} <- Forms], File;
|
|
57
|
+
File -> File
|
|
58
|
+
end,
|
|
59
|
+
unicode:characters_to_binary(Source).
|
|
60
|
+
text(Value) -> unicode:characters_to_list(Value).
|
|
61
|
+
`;
|
|
62
|
+
|
|
63
|
+
const escape = (value) => String(value).replace(/[&<>"']/g, (c) =>
|
|
64
|
+
({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c]));
|
|
65
|
+
const totals = (lines) => ({covered: lines.filter(({hits}) => hits > 0).length, total: lines.length});
|
|
66
|
+
const percentage = ({covered, total}) => total ? `${(100 * covered / total).toFixed(1)}%` : "no executable lines";
|
|
67
|
+
const page = (title, body) => `<!doctype html><html lang="en"><meta charset="utf-8"><title>${escape(title)}</title>
|
|
68
|
+
<style>body{font:16px system-ui;margin:2rem;color:#222}table{border-collapse:collapse;width:100%}td,th{padding:.3rem .7rem;text-align:left;border-bottom:1px solid #ddd}pre{margin:0;tab-size:4}.hit{background:#e4f5e9}.miss{background:#ffe6e6}.line,.count{width:4rem;text-align:right;color:#555}a{color:#174da8}</style>
|
|
69
|
+
<h1>${escape(title)}</h1>${body}</html>\n`;
|
|
70
|
+
|
|
71
|
+
// Only exports explicitly returned by this run's invocations are imported.
|
|
72
|
+
// A missing export is an error even if the native runner exited successfully.
|
|
73
|
+
export async function collectBeamCoverage({root, directory, runs}) {
|
|
74
|
+
if (!runs.length) return null;
|
|
75
|
+
root = path.resolve(root);
|
|
76
|
+
directory = path.resolve(directory);
|
|
77
|
+
const temporary = await mkdtemp(path.join(os.tmpdir(), "lawspec-beam-coverage-"));
|
|
78
|
+
try {
|
|
79
|
+
const inputs = [];
|
|
80
|
+
const seen = new Set();
|
|
81
|
+
let rebarDirectories;
|
|
82
|
+
for (const run of runs) {
|
|
83
|
+
if (!run.run || seen.has(run.run) || path.basename(run.file) !== `${run.run}.coverdata`)
|
|
84
|
+
throw new Error("Invalid or duplicate BEAM coverage invocation");
|
|
85
|
+
seen.add(run.run);
|
|
86
|
+
const info = await stat(run.file).catch(() => null);
|
|
87
|
+
if (!info?.isFile() || !info.size) throw new Error(`Native runner did not export coverage for ${run.run}: ${run.file}`);
|
|
88
|
+
let beams;
|
|
89
|
+
if (run.tool === "rebar3" && !rebarDirectories) {
|
|
90
|
+
// Before the first compile Rebar only knows dependency ebin paths.
|
|
91
|
+
// Ask after the test run so fresh and relocated applications are found.
|
|
92
|
+
const result = await exec("rebar3", ["as", "test", "path", "--ebin", "--separator", "\n"], {cwd: root});
|
|
93
|
+
rebarDirectories = result.stdout.trim().split("\n").filter(Boolean);
|
|
94
|
+
if (!rebarDirectories.length || !rebarDirectories.every((item) => path.isAbsolute(item)))
|
|
95
|
+
throw new Error("Cannot resolve Rebar's application beam directories after coverage");
|
|
96
|
+
}
|
|
97
|
+
const directories = run.tool === "rebar3" ? rebarDirectories
|
|
98
|
+
: run.beamDirectories ?? (run.beamDirectory ? [run.beamDirectory] : []);
|
|
99
|
+
for (const directory of directories) {
|
|
100
|
+
const entries = (await readdir(directory)).filter((name) => name.endsWith(".beam"));
|
|
101
|
+
beams = {...beams, ...Object.fromEntries(entries.map((name) => [name.slice(0, -5), path.resolve(directory, name)]))};
|
|
102
|
+
}
|
|
103
|
+
if (run.metadata) {
|
|
104
|
+
const metadata = JSON.parse(await readFile(run.metadata, "utf8"));
|
|
105
|
+
if (metadata.run !== run.run || metadata.file !== run.file || !metadata.modules?.length)
|
|
106
|
+
throw new Error(`Gleam coverage metadata does not match invocation ${run.run}`);
|
|
107
|
+
beams = Object.fromEntries(metadata.modules.map(({name, beam}) => [name, beam]));
|
|
108
|
+
}
|
|
109
|
+
inputs.push({file: path.resolve(run.file), ...(beams ? {beams} : {})});
|
|
110
|
+
}
|
|
111
|
+
// Assemble all pages off to the side. A failed import or source mapping
|
|
112
|
+
// cannot leave an apparently complete index behind.
|
|
113
|
+
const pages = path.join(temporary, "modules");
|
|
114
|
+
await mkdir(pages);
|
|
115
|
+
const input = path.join(temporary, "input.json"), output = path.join(temporary, "output.json");
|
|
116
|
+
const script = path.join(temporary, "collect.escript");
|
|
117
|
+
await writeFile(script, collector);
|
|
118
|
+
await writeFile(input, JSON.stringify({runs: inputs, directory: pages}));
|
|
119
|
+
await exec("escript", [script, input, output], {cwd: root, maxBuffer: 8 * 1024 * 1024});
|
|
120
|
+
const modules = JSON.parse(await readFile(output, "utf8"));
|
|
121
|
+
for (const module of modules) {
|
|
122
|
+
module.summary = totals(module.lines);
|
|
123
|
+
if (!module.source) continue;
|
|
124
|
+
let source = path.resolve(root, module.source);
|
|
125
|
+
const text = await readFile(source, "utf8");
|
|
126
|
+
// Gleam copies foreign Erlang sources into its build tree. Prefer the
|
|
127
|
+
// original when it is byte-for-byte the source that was compiled.
|
|
128
|
+
const marker = `${path.sep}_gleam_artefacts${path.sep}`;
|
|
129
|
+
if (source.includes(marker)) {
|
|
130
|
+
const original = path.join(root, "src", source.split(marker).at(-1));
|
|
131
|
+
if (await readFile(original, "utf8").catch(() => null) === text) source = original;
|
|
132
|
+
}
|
|
133
|
+
module.source = path.relative(root, source);
|
|
134
|
+
const sourceLines = text.split(/\r?\n/);
|
|
135
|
+
if (module.lines.some(({line}) => line > sourceLines.length))
|
|
136
|
+
throw new Error(`Coverage lines do not match source ${module.source}`);
|
|
137
|
+
const hits = new Map(module.lines.map(({line, hits}) => [line, hits]));
|
|
138
|
+
module.report = createHash("sha256").update(module.name).digest("hex") + ".html";
|
|
139
|
+
const rows = sourceLines.map((line, index) => {
|
|
140
|
+
const count = hits.get(index + 1);
|
|
141
|
+
return `<tr class="${count === undefined ? "" : count ? "hit" : "miss"}" id="L${index + 1}"><td class="line">${index + 1}</td><td class="count">${count ?? ""}</td><td><pre>${escape(line)}</pre></td></tr>`;
|
|
142
|
+
}).join("\n");
|
|
143
|
+
await writeFile(path.join(pages, module.report), page(module.name,
|
|
144
|
+
`<p>${escape(module.source)} — ${percentage(module.summary)}</p><table>${rows}</table>`));
|
|
145
|
+
}
|
|
146
|
+
const summary = modules.reduce((sum, module) => ({covered: sum.covered + module.summary.covered,
|
|
147
|
+
total: sum.total + module.summary.total}), {covered: 0, total: 0});
|
|
148
|
+
const result = {version: 1, root, runs: runs.map(({run}) => run), summary, modules};
|
|
149
|
+
const rows = modules.map((module) => `<tr><td><a href="modules/${module.report}">${escape(module.name)}</a></td><td>${module.summary.covered}/${module.summary.total}</td><td>${percentage(module.summary)}</td></tr>`).join("\n");
|
|
150
|
+
await mkdir(path.join(directory, "modules"), {recursive: true});
|
|
151
|
+
for (const module of modules)
|
|
152
|
+
await writeFile(path.join(directory, "modules", module.report), await readFile(path.join(pages, module.report)));
|
|
153
|
+
await writeFile(path.join(directory, "coverage.json"), JSON.stringify(result, null, 2) + "\n");
|
|
154
|
+
await writeFile(path.join(directory, "index.html"), page("BEAM line coverage",
|
|
155
|
+
`<p>${summary.covered}/${summary.total} executable lines covered (${percentage(summary)}); ${runs.length} native run(s).</p><table><thead><tr><th>Module</th><th>Lines</th><th>Coverage</th></tr></thead><tbody>${rows}</tbody></table>`));
|
|
156
|
+
return result;
|
|
157
|
+
} finally {
|
|
158
|
+
await rm(temporary, {recursive: true, force: true});
|
|
159
|
+
}
|
|
160
|
+
}
|
package/beam-doctor.mjs
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
// Generated from templates/npm/beam-doctor.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
// These are the same sources the compiler emits, including the NIF loader.
|
|
7
|
+
const runtime = {
|
|
8
|
+
"formatter": "# Observe ExUnit's real skip events; excluded tests are not reported as run.\n# ref:REQ-harness-units ref:DEC-native-property-frameworks\ndefmodule LawSpec.Beam.ExUnitFormatter do\n @moduledoc false\n use GenServer\n\n def init(_options), do: {:ok, :lawspec_beam_report.open()}\n\n def handle_cast({:test_finished, %{state: {:skipped, _}, tags: %{lawspec_skip: {law, reason}}}}, state) do\n :lawspec_beam_harness.skip(law, reason)\n {:noreply, state}\n end\n\n def handle_cast({:test_finished, %{state: {:excluded, _}}}, state), do: {:noreply, state}\n def handle_cast({:test_finished, %{state: {:skipped, _}}}, state), do: {:noreply, state}\n def handle_cast({:test_finished, test}, state) do\n :lawspec_beam_report.event(state, %{\n event: \"test\", name: Atom.to_string(test.name), classname: inspect(test.module),\n identity: Map.get(test.tags, :lawspec_identity, \"\"),\n status: if(test.state == nil, do: \"passed\", else: \"failed\"),\n time: (test.time || 0) / 1_000_000,\n failure: if(test.state == nil, do: \"\", else: inspect(test.state, limit: :infinity, printable_limit: :infinity))\n })\n {:noreply, state}\n end\n\n def handle_cast({:suite_finished, _}, state) do\n :lawspec_beam_report.finish(state)\n {:noreply, state}\n end\n\n def handle_cast(_event, state), do: {:noreply, state}\nend\n",
|
|
9
|
+
"native": "%% @doc The seed and vector bridge to the same OpenSSL ABI as OTP crypto.\n%% Build with escript lawspec_crypto_build.escript; ship the resulting priv/.\n%% ref:DEC-typed-core-boundary\n-module(lawspec_beam_crypto_native).\n-on_load(init/0).\n-export([expand/2, encapsulate_test/2, sign_context/5, verify_context/5]).\n\ninit() ->\n [{<<\"OpenSSL\">>, Version, _}] = crypto:info_lib(),\n BeamDir = filename:dirname(code:which(?MODULE)),\n %% Application layouts (Rebar, Mix, Gleam and releases) put ebin beside\n %% priv. The second path supports a standalone erlc output directory.\n Candidates = [filename:join([filename:dirname(BeamDir), \"priv\", \"lawspec_crypto_native\"]),\n filename:join([BeamDir, \"priv\", \"lawspec_crypto_native\"])],\n case [Path || Path <- Candidates, filelib:is_regular(Path ++ extension())] of\n [Library | _] -> erlang:load_nif(Library, Version bsr 28);\n [] -> {error, {load_failed,\n \"LawSpec crypto bridge is missing; run escript lawspec_crypto_build.escript before compiling and ship priv/ with the application\"}}\n end.\n\nextension() -> case os:type() of {win32, _} -> \".dll\"; _ -> \".so\" end.\n\nexpand(_, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\nencapsulate_test(_, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\nsign_context(_, _, _, _, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\nverify_context(_, _, _, _, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\n",
|
|
10
|
+
"c": "/* OpenSSL operations not exposed by OTP 29's crypto API: compact key seeds,\n * signature contexts and deterministic known-answer tests. Ordinary random\n * encapsulation, signing, verification and AEAD use OTP directly.\n * ref:DEC-typed-core-boundary\n */\n#include <erl_nif.h>\n#include <openssl/crypto.h>\n#include <openssl/evp.h>\n#include <openssl/err.h>\n#include <openssl/params.h>\n#include <openssl/core_names.h>\n#include <string.h>\n\n#if OPENSSL_VERSION_NUMBER < 0x30500000L\n#error \"LawSpec crypto requires OpenSSL 3.5 or newer\"\n#endif\n#if !defined(LAWSPEC_OPENSSL_MAJOR) || OPENSSL_VERSION_MAJOR != LAWSPEC_OPENSSL_MAJOR\n#error \"Build LawSpec crypto with the same OpenSSL major version as Erlang/OTP\"\n#endif\n\ntypedef struct {\n const char *tag, *name;\n size_t seed, public_key, private_key, signature;\n} Algorithm;\n\nstatic const Algorithm algorithms[] = {\n {\"mlkem768\", \"ML-KEM-768\", 64, 1184, 2400, 0},\n {\"mldsa65\", \"ML-DSA-65\", 32, 1952, 4032, 3309},\n {\"slh_dsa_shake_128f\", \"SLH-DSA-SHAKE-128f\", 48, 32, 64, 17088}\n};\n\nstatic const Algorithm *algorithm(ErlNifEnv *env, ERL_NIF_TERM term) {\n char tag[32];\n size_t i;\n if (!enif_get_atom(env, term, tag, sizeof(tag), ERL_NIF_LATIN1)) return NULL;\n for (i = 0; i < sizeof(algorithms) / sizeof(algorithms[0]); ++i)\n if (!strcmp(tag, algorithms[i].tag)) return &algorithms[i];\n return NULL;\n}\n\n/* No key material or provider error strings enter diagnostics. OpenSSL's\n * per-thread error queue must not leak between jobs on a dirty scheduler. */\nstatic ERL_NIF_TERM failure(ErlNifEnv *env, const char *operation) {\n ERR_clear_error();\n return enif_raise_exception(env, enif_make_tuple2(env,\n enif_make_atom(env, \"lawspec_crypto_failure\"), enif_make_atom(env, operation)));\n}\n\nstatic EVP_PKEY *import_key(const Algorithm *alg, const char *parameter,\n const ErlNifBinary *bytes, int selection) {\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_name(NULL, alg->name, NULL);\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(parameter, bytes->data, bytes->size),\n OSSL_PARAM_construct_end()\n };\n if (!ctx || EVP_PKEY_fromdata_init(ctx) <= 0\n || EVP_PKEY_fromdata(ctx, &key, selection, params) <= 0) {\n EVP_PKEY_free(key);\n key = NULL;\n }\n EVP_PKEY_CTX_free(ctx);\n return key;\n}\n\nstatic ERL_NIF_TERM expand(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n const Algorithm *alg;\n ErlNifBinary seed, pub = {0}, priv = {0};\n EVP_PKEY_CTX *ctx = NULL;\n EVP_PKEY *key = NULL;\n size_t written;\n int pub_allocated = 0, priv_allocated = 0, ok = 0;\n ERL_NIF_TERM result;\n if (argc != 2 || !(alg = algorithm(env, argv[0]))\n || !enif_inspect_binary(env, argv[1], &seed) || seed.size != alg->seed)\n return enif_make_badarg(env);\n ERR_clear_error();\n if (alg == &algorithms[2]) {\n /* SLH's seed parameter is used only for the NIST key-generation tests. */\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(\"seed\", seed.data, seed.size),\n OSSL_PARAM_construct_end()\n };\n ctx = EVP_PKEY_CTX_new_from_name(NULL, alg->name, NULL);\n if (!ctx || EVP_PKEY_keygen_init(ctx) <= 0\n || EVP_PKEY_CTX_set_params(ctx, params) <= 0\n || EVP_PKEY_generate(ctx, &key) <= 0) goto done;\n } else {\n key = import_key(alg, \"seed\", &seed, EVP_PKEY_KEYPAIR);\n if (!key) goto done;\n }\n if (!(pub_allocated = enif_alloc_binary(alg->public_key, &pub))\n || !(priv_allocated = enif_alloc_binary(alg->private_key, &priv))) goto done;\n if (!EVP_PKEY_get_octet_string_param(key, OSSL_PKEY_PARAM_PUB_KEY,\n pub.data, pub.size, &written) || written != pub.size\n || !EVP_PKEY_get_octet_string_param(key, OSSL_PKEY_PARAM_PRIV_KEY,\n priv.data, priv.size, &written) || written != priv.size) goto done;\n ok = 1;\ndone:\n EVP_PKEY_free(key);\n EVP_PKEY_CTX_free(ctx);\n if (ok) {\n result = enif_make_tuple2(env, enif_make_binary(env, &pub), enif_make_binary(env, &priv));\n ERR_clear_error();\n return result;\n }\n if (pub_allocated) enif_release_binary(&pub);\n if (priv_allocated) { OPENSSL_cleanse(priv.data, priv.size); enif_release_binary(&priv); }\n return failure(env, \"expand_seed\");\n}\n\n/* FIPS 203 deterministic encapsulation for known-answer tests only. */\nstatic ERL_NIF_TERM encapsulate_test(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n ErlNifBinary pub, randomness, ciphertext = {0}, secret = {0};\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n size_t ciphertext_size = 1088, secret_size = 32;\n int ciphertext_allocated = 0, secret_allocated = 0, ok = 0;\n ERL_NIF_TERM result;\n if (argc != 2 || !enif_inspect_binary(env, argv[0], &pub) || pub.size != 1184\n || !enif_inspect_binary(env, argv[1], &randomness) || randomness.size != 32)\n return enif_make_badarg(env);\n ERR_clear_error();\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(OSSL_KEM_PARAM_IKME, randomness.data, randomness.size),\n OSSL_PARAM_construct_end()\n };\n key = import_key(&algorithms[0], OSSL_PKEY_PARAM_PUB_KEY, &pub, EVP_PKEY_PUBLIC_KEY);\n if (!key || !(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL))\n || EVP_PKEY_encapsulate_init(ctx, params) <= 0) goto done;\n if (!(ciphertext_allocated = enif_alloc_binary(ciphertext_size, &ciphertext))\n || !(secret_allocated = enif_alloc_binary(secret_size, &secret))) goto done;\n if (EVP_PKEY_encapsulate(ctx, ciphertext.data, &ciphertext_size, secret.data, &secret_size) <= 0\n || ciphertext_size != ciphertext.size || secret_size != secret.size) goto done;\n ok = 1;\ndone:\n EVP_PKEY_CTX_free(ctx);\n EVP_PKEY_free(key);\n if (ok) {\n result = enif_make_tuple2(env, enif_make_binary(env, &ciphertext), enif_make_binary(env, &secret));\n ERR_clear_error();\n return result;\n }\n if (ciphertext_allocated) enif_release_binary(&ciphertext);\n if (secret_allocated) { OPENSSL_cleanse(secret.data, secret.size); enif_release_binary(&secret); }\n return failure(env, \"encapsulate_test\");\n}\n\nstatic ERL_NIF_TERM sign_context(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n const Algorithm *alg;\n ErlNifBinary secret, message, context, signature = {0};\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n EVP_SIGNATURE *scheme = NULL;\n int deterministic, allocated = 0, ok = 0;\n size_t length;\n ERL_NIF_TERM result;\n if (argc != 5 || !(alg = algorithm(env, argv[0])) || !alg->signature\n || !enif_inspect_binary(env, argv[1], &secret)\n || secret.size != (alg == &algorithms[1] ? alg->seed : alg->private_key)\n || !enif_inspect_binary(env, argv[2], &message)\n || !enif_inspect_binary(env, argv[3], &context) || context.size > 255)\n return enif_make_badarg(env);\n if (enif_is_identical(argv[4], enif_make_atom(env, \"true\"))) deterministic = 1;\n else if (enif_is_identical(argv[4], enif_make_atom(env, \"false\"))) deterministic = 0;\n else return enif_make_badarg(env);\n ERR_clear_error();\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, context.data, context.size),\n OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_DETERMINISTIC, &deterministic),\n OSSL_PARAM_construct_end()\n };\n key = import_key(alg, alg == &algorithms[1] ? \"seed\" : OSSL_PKEY_PARAM_PRIV_KEY,\n &secret, EVP_PKEY_KEYPAIR);\n if (!key || !(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL))\n || !(scheme = EVP_SIGNATURE_fetch(NULL, alg->name, NULL))\n || EVP_PKEY_sign_message_init(ctx, scheme, params) <= 0) goto done;\n length = alg->signature;\n if (!(allocated = enif_alloc_binary(length, &signature))) goto done;\n if (EVP_PKEY_sign(ctx, signature.data, &length, message.data, message.size) <= 0\n || length != signature.size) goto done;\n ok = 1;\ndone:\n EVP_SIGNATURE_free(scheme);\n EVP_PKEY_CTX_free(ctx);\n EVP_PKEY_free(key);\n if (ok) {\n result = enif_make_binary(env, &signature);\n ERR_clear_error();\n return result;\n }\n if (allocated) enif_release_binary(&signature);\n return failure(env, \"sign_context\");\n}\n\nstatic ERL_NIF_TERM verify_context(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n const Algorithm *alg;\n ErlNifBinary pub, message, signature, context;\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n EVP_SIGNATURE *scheme = NULL;\n int verified = -1;\n if (argc != 5 || !(alg = algorithm(env, argv[0])) || !alg->signature\n || !enif_inspect_binary(env, argv[1], &pub)\n || !enif_inspect_binary(env, argv[2], &message)\n || !enif_inspect_binary(env, argv[3], &signature)\n || !enif_inspect_binary(env, argv[4], &context)) return enif_make_badarg(env);\n if (pub.size != alg->public_key || signature.size != alg->signature || context.size > 255)\n return enif_make_atom(env, \"false\");\n ERR_clear_error();\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, context.data, context.size),\n OSSL_PARAM_construct_end()\n };\n key = import_key(alg, OSSL_PKEY_PARAM_PUB_KEY, &pub, EVP_PKEY_PUBLIC_KEY);\n if (!key || !(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL))\n || !(scheme = EVP_SIGNATURE_fetch(NULL, alg->name, NULL))\n || EVP_PKEY_verify_message_init(ctx, scheme, params) <= 0) goto done;\n verified = EVP_PKEY_verify(ctx, signature.data, signature.size, message.data, message.size);\ndone:\n EVP_SIGNATURE_free(scheme);\n EVP_PKEY_CTX_free(ctx);\n EVP_PKEY_free(key);\n if (verified < 0) return failure(env, \"verify_context\");\n ERR_clear_error();\n return enif_make_atom(env, verified == 1 ? \"true\" : \"false\");\n}\n\nstatic int load(ErlNifEnv *env, void **private_data, ERL_NIF_TERM info) {\n unsigned int expected;\n (void)private_data;\n return !enif_get_uint(env, info, &expected) || expected != OPENSSL_VERSION_MAJOR\n || OPENSSL_version_major() != expected || OpenSSL_version_num() < 0x30500000L;\n}\n\n/* Cover restores the original Erlang module after instrumentation. The\n * bridge holds no private state or resource types across calls, so each\n * module instance can use the same library after the ordinary ABI check. */\nstatic int upgrade(ErlNifEnv *env, void **private_data, void **old_private_data, ERL_NIF_TERM info) {\n (void)old_private_data;\n return load(env, private_data, info);\n}\n\nstatic ErlNifFunc functions[] = {\n {\"expand\", 2, expand, ERL_NIF_DIRTY_JOB_CPU_BOUND},\n {\"encapsulate_test\", 2, encapsulate_test, ERL_NIF_DIRTY_JOB_CPU_BOUND},\n {\"sign_context\", 5, sign_context, ERL_NIF_DIRTY_JOB_CPU_BOUND},\n {\"verify_context\", 5, verify_context, ERL_NIF_DIRTY_JOB_CPU_BOUND}\n};\nERL_NIF_INIT(lawspec_beam_crypto_native, functions, load, NULL, upgrade, NULL)\n",
|
|
11
|
+
"build": "#!/usr/bin/env escript\n%%! -noshell\n%% Build once before Rebar/Mix/Gleam compilation; no compiler runs at application\n%% startup. CC names one executable. LAWSPEC_OPENSSL_PREFIX selects a development\n%% installation matching OTP's OpenSSL major version (3.5+).\n%% ref:DEC-typed-core-boundary\n-mode(compile).\n\nmain(Arguments) ->\n try\n Project = case Arguments of\n [] -> filename:dirname(filename:absname(escript:script_name()));\n [Directory] -> filename:absname(Directory);\n _ -> fail(\"usage: escript lawspec_crypto_build.escript [project-directory]\")\n end,\n build(Project)\n catch\n throw:{build_error, Message} -> io:format(standard_error, \"LawSpec crypto: ~ts~n\", [Message]), halt(1);\n error:Reason -> io:format(standard_error, \"LawSpec crypto build failed: ~tp~n\", [Reason]), halt(1)\n end.\n\nbuild(Project) ->\n case list_to_integer(erlang:system_info(otp_release)) >= 29 of\n true -> ok;\n false -> fail(\"Erlang/OTP 29 or newer is required\")\n end,\n [{<<\"OpenSSL\">>, Version, Description}] = crypto:info_lib(),\n Major = Version bsr 28,\n MissingAlgorithms = lists:append([Expected -- crypto:supports(Kind) || {Kind, Expected} <-\n [{kems, [mlkem768]}, {public_keys, [mldsa65, slh_dsa_shake_128f]},\n {hashs, [sha3_256, shake256]}, {ciphers, [aes_256_gcm]}]]),\n case MissingAlgorithms of\n [] -> ok;\n Missing -> fail(io_lib:format(\"OTP crypto lacks ~tp; install OTP with OpenSSL 3.5+\", [Missing]))\n end,\n Compiler = executable(env(\"CC\", \"cc\")),\n {Include, Library, ProviderVersion} = openssl(Major),\n OtpInclude = filename:join([code:root_dir(), \"usr\", \"include\"]),\n Source = filename:join([Project, \"priv\", \"lawspec_crypto_native.c\"]),\n Output = filename:join([Project, \"priv\", \"lawspec_crypto_native.so\"]),\n Stamp = Output ++ \".build\",\n SourceBytes = read(Source),\n Args = [\"-std=c11\", \"-O2\", \"-Wall\", \"-Wextra\", \"-Werror\", \"-fPIC\", \"-shared\"] ++\n platform_flags() ++ [\"-DLAWSPEC_OPENSSL_MAJOR=\" ++ integer_to_list(Major),\n \"-I\" ++ OtpInclude, \"-I\" ++ Include, Source, \"-L\" ++ Library,\n \"-Xlinker\", \"-rpath\", \"-Xlinker\", Library, \"-lcrypto\"],\n Fingerprint = crypto:hash(sha3_256, term_to_binary({SourceBytes,\n read(escript:script_name()), read(filename:join(Include, \"openssl/opensslv.h\")),\n read(filename:join(OtpInclude, \"erl_nif.h\")),\n erlang:system_info(system_architecture), erlang:system_info(nif_version),\n Version, Description, ProviderVersion, Compiler, Args})),\n case current(Stamp, Output, Fingerprint) of\n true -> ok;\n false ->\n %% A failed or concurrent build cannot replace a working library.\n Temporary = Output ++ \".\" ++ os:getpid() ++ \".tmp\",\n try\n checked(Compiler, Args ++ [\"-o\", Temporary]),\n ok = file:rename(Temporary, Output),\n ok = file:write_file(Stamp, term_to_binary({Fingerprint, crypto:hash(sha3_256, read(Output))})),\n io:format(\"Built LawSpec crypto bridge (~ts).~n\", [Description])\n after\n file:delete(Temporary)\n end\n end.\n\nplatform_flags() ->\n case os:type() of\n {unix, darwin} -> [\"-undefined\", \"dynamic_lookup\"];\n {unix, _} -> [];\n _ -> fail(\"the crypto bridge build requires a Unix C toolchain; use WSL on Windows\")\n end.\n\nopenssl(Major) ->\n case os:getenv(\"LAWSPEC_OPENSSL_PREFIX\") of\n false -> discover_openssl(Major);\n Prefix -> prefix(Prefix, \"explicit prefix\")\n end.\n\ndiscover_openssl(Major) ->\n case os:find_executable(\"pkg-config\") of\n false -> homebrew_openssl(Major);\n Pkg ->\n case run(Pkg, [\"--modversion\", \"libcrypto\"]) of\n {0, Text} ->\n Version = string:trim(binary_to_list(Text)),\n case string:prefix(Version, integer_to_list(Major) ++ \".\") of\n nomatch -> homebrew_openssl(Major);\n _ -> {query(Pkg, [\"--variable=includedir\", \"libcrypto\"]),\n query(Pkg, [\"--variable=libdir\", \"libcrypto\"]), Version}\n end;\n _ -> homebrew_openssl(Major)\n end\n end.\n\nhomebrew_openssl(Major) ->\n case os:find_executable(\"brew\") of\n false -> missing_openssl(Major);\n Brew ->\n case run(Brew, [\"--prefix\", \"openssl@\" ++ integer_to_list(Major)]) of\n {0, Text} -> prefix(string:trim(binary_to_list(Text)), \"Homebrew\");\n _ -> missing_openssl(Major)\n end\n end.\n\nprefix(Prefix, Origin) ->\n Absolute = filename:absname(Prefix),\n Include = filename:join(Absolute, \"include\"),\n case filelib:is_regular(filename:join(Include, \"openssl/evp.h\")) of\n true ->\n Libraries = [filename:join(Absolute, Subdir) || Subdir <- [\"lib\", \"lib64\"],\n lists:any(fun(Name) -> filelib:is_regular(filename:join([Absolute, Subdir, Name])) end,\n [\"libcrypto.so\", \"libcrypto.dylib\"])],\n case Libraries of\n [Library | _] -> {Include, Library, Origin};\n [] -> fail(\"OpenSSL shared library missing under \" ++ Absolute)\n end;\n false -> fail(\"OpenSSL headers missing under \" ++ Absolute)\n end.\n\nmissing_openssl(Major) -> fail(io_lib:format(\n \"install pkg-config and OpenSSL ~B development headers/libraries (3.5+), or set LAWSPEC_OPENSSL_PREFIX to that installation\", [Major])).\n\ncurrent(Stamp, Output, Fingerprint) ->\n case {file:read_file(Stamp), file:read_file(Output)} of\n {{ok, StampBytes}, {ok, OutputBytes}} ->\n try binary_to_term(StampBytes, [safe]) =:= {Fingerprint, crypto:hash(sha3_256, OutputBytes)}\n catch error:badarg -> false end;\n _ -> false\n end.\n\nenv(Key, Default) -> case os:getenv(Key) of false -> Default; Value -> Value end.\nexecutable(Name) -> case os:find_executable(Name) of\n false -> fail(\"executable not found: \" ++ Name ++ \" (CC must name one compiler executable)\");\n Path -> Path\nend.\n\nread(Path) -> case file:read_file(Path) of\n {ok, Bytes} -> Bytes;\n {error, Reason} -> fail(io_lib:format(\"cannot read ~ts: ~tp\", [Path, Reason]))\nend.\n\nquery(Command, Args) -> string:trim(binary_to_list(checked(Command, Args))).\nchecked(Command, Args) -> case run(Command, Args) of\n {0, Output} -> Output;\n {Status, Output} -> fail(io_lib:format(\"~ts exited ~B:~n~ts\", [Command, Status, Output]))\nend.\n\n%% Argument arrays, never a shell: project and installation paths may contain\n%% spaces, quotes, dollar signs or other shell metacharacters.\nrun(Command, Args) ->\n Port = open_port({spawn_executable, Command}, [binary, exit_status, use_stdio, stderr_to_stdout, {args, Args}]),\n collect(Port, []).\n\ncollect(Port, Parts) ->\n receive\n {Port, {data, Bytes}} -> collect(Port, [Bytes | Parts]);\n {Port, {exit_status, Status}} -> {Status, iolist_to_binary(lists:reverse(Parts))}\n end.\n\nfail(Message) -> throw({build_error, lists:flatten(Message)}).\n"
|
|
12
|
+
};
|
|
13
|
+
const requireThat = (condition, message) => {
|
|
14
|
+
if (!condition) throw new Error(message);
|
|
15
|
+
};
|
|
16
|
+
async function exists(file) {
|
|
17
|
+
try { await access(file); return true; } catch { return false; }
|
|
18
|
+
}
|
|
19
|
+
const includesPath = (root, directories, directory) =>
|
|
20
|
+
directories.some((item) => path.resolve(root, item) === path.resolve(root, directory));
|
|
21
|
+
|
|
22
|
+
// Hex requirements used by Rebar and Gleam. Only stable numeric releases are
|
|
23
|
+
// admitted by the compatibility profiles. Reject unsupported syntax explicitly
|
|
24
|
+
// instead of accepting an old compiled dependency after a manifest edit.
|
|
25
|
+
export function satisfiesRequirement(version, requirement) {
|
|
26
|
+
const compare = (left, right) => {
|
|
27
|
+
const a = left.split(".").map(Number), b = right.split(".").map(Number);
|
|
28
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
29
|
+
const difference = (a[i] ?? 0) - (b[i] ?? 0);
|
|
30
|
+
if (difference) return Math.sign(difference);
|
|
31
|
+
}
|
|
32
|
+
return 0;
|
|
33
|
+
};
|
|
34
|
+
requireThat(/^\d+(?:\.\d+)*$/.test(version), `Cannot verify dependency version ${version}`);
|
|
35
|
+
const clauses = String(requirement).trim().split(/\s+or\s+/).map((clause) =>
|
|
36
|
+
clause.split(/\s+and\s+/).map((term) => {
|
|
37
|
+
const match = /^(~>|>=|<=|==|!=|>|<)?\s*(\d+(?:\.\d+)*)$/.exec(term.trim());
|
|
38
|
+
requireThat(match, `Cannot verify Hex requirement ${JSON.stringify(requirement)}; use an exact stable version`);
|
|
39
|
+
const [, operator = "==", wanted] = match;
|
|
40
|
+
const difference = compare(version, wanted);
|
|
41
|
+
if (operator === "~>") {
|
|
42
|
+
const parts = wanted.split(".").map(Number);
|
|
43
|
+
requireThat(parts.length === 2 || parts.length === 3, `Cannot verify Hex requirement ${JSON.stringify(requirement)}`);
|
|
44
|
+
const upper = parts.length === 2 ? `${parts[0] + 1}.0.0` : `${parts[0]}.${parts[1] + 1}.0`;
|
|
45
|
+
return difference >= 0 && compare(version, upper) < 0;
|
|
46
|
+
}
|
|
47
|
+
return {"==": difference === 0, "!=": difference !== 0, ">=": difference >= 0,
|
|
48
|
+
"<=": difference <= 0, ">": difference > 0, "<": difference < 0}[operator];
|
|
49
|
+
}));
|
|
50
|
+
return clauses.some((clause) => clause.every(Boolean));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Native readers evaluate the tools' effective configuration. Their reports go
|
|
54
|
+
// to a separate file so compiler warnings cannot be mistaken for JSON.
|
|
55
|
+
const erlangProbe = String.raw`#!/usr/bin/env escript
|
|
56
|
+
-mode(compile).
|
|
57
|
+
main([Input, Output]) ->
|
|
58
|
+
try
|
|
59
|
+
{ok, Bytes} = file:read_file(Input),
|
|
60
|
+
Data = inspect(json:decode(Bytes)),
|
|
61
|
+
ok = file:write_file(Output, json:encode(Data))
|
|
62
|
+
catch
|
|
63
|
+
throw:{doctor, Message} -> io:format(standard_error, "~ts~n", [Message]), halt(1);
|
|
64
|
+
Class:Reason -> io:format(standard_error, "BEAM doctor: ~tp:~tp~n", [Class, Reason]), halt(1)
|
|
65
|
+
end.
|
|
66
|
+
|
|
67
|
+
inspect(#{<<"mode">> := <<"otp">>}) ->
|
|
68
|
+
Major = erlang:system_info(otp_release),
|
|
69
|
+
{ok, Version} = file:read_file(filename:join([code:root_dir(), "releases", Major, "OTP_VERSION"])),
|
|
70
|
+
#{otp => string:trim(Version)};
|
|
71
|
+
inspect(#{<<"mode">> := <<"rebar">>, <<"archive">> := Archive, <<"proper">> := Proper}) ->
|
|
72
|
+
{ok, Parts} = escript:extract(os:find_executable("rebar3"), []),
|
|
73
|
+
{archive, Zip} = lists:keyfind(archive, 1, Parts),
|
|
74
|
+
ArchivePath = text(Archive),
|
|
75
|
+
ok = file:write_file(ArchivePath, Zip),
|
|
76
|
+
{ok, Files} = zip:extract(Zip, [memory]),
|
|
77
|
+
Directories = lists:usort([filename:dirname(Name) || {Name, _} <- Files, filename:extension(Name) =:= ".beam"]),
|
|
78
|
+
[true = code:add_patha(ArchivePath ++ "/" ++ Dir) || Dir <- Directories],
|
|
79
|
+
State = rebar_state:apply_profiles(rebar_state:new(rebar_config:consult_root()), [test]),
|
|
80
|
+
Get = fun(Key, Default) -> rebar_state:get(State, Key, Default) end,
|
|
81
|
+
ProperDependency = lists:any(fun
|
|
82
|
+
({proper, Version}) when is_list(Version) -> true;
|
|
83
|
+
({proper, Version, {pkg, proper}}) when is_list(Version) -> true;
|
|
84
|
+
(_) -> false
|
|
85
|
+
end, Get(deps, [])),
|
|
86
|
+
Report = proplists:get_value(report, Get(eunit_opts, [])),
|
|
87
|
+
Reporter = Report =:= {lawspec_beam_report, []} orelse Report =:= lawspec_beam_report,
|
|
88
|
+
#{src_dirs => directories(Get(src_dirs, ["src"])),
|
|
89
|
+
extra_src_dirs => directories(Get(extra_src_dirs, [])),
|
|
90
|
+
reporter => Reporter, proper_dependency => ProperDependency,
|
|
91
|
+
proper_requirement => case lists:keyfind(proper, 1, Get(deps, [])) of
|
|
92
|
+
{proper, Requirement} when is_list(Requirement) -> unicode:characters_to_binary(Requirement);
|
|
93
|
+
{proper, Requirement, {pkg, proper}} when is_list(Requirement) -> unicode:characters_to_binary(Requirement);
|
|
94
|
+
_ -> null
|
|
95
|
+
end,
|
|
96
|
+
filters => Get(eunit_tests, []) =/= [],
|
|
97
|
+
alias => proplists:is_defined(eunit, Get(alias, [])) orelse proplists:is_defined(eunit, Get(aliases, [])),
|
|
98
|
+
crypto_hook => lists:any(fun
|
|
99
|
+
({compile, Command}) -> string:trim(Command) =:= "escript lawspec_crypto_build.escript";
|
|
100
|
+
(_) -> false
|
|
101
|
+
end, Get(pre_hooks, [])),
|
|
102
|
+
proper => app(proper, text(Proper), proper)};
|
|
103
|
+
inspect(#{<<"mode">> := <<"gleam">>, <<"root">> := Root}) ->
|
|
104
|
+
Base = filename:join([text(Root), "build", "dev", "erlang"]),
|
|
105
|
+
maps:from_list([{Name, app(Name, filename:join([Base, atom_to_list(Name), "ebin"]), Module)} ||
|
|
106
|
+
{Name, Module} <- [{gleam_stdlib, gleam@list}, {gleeunit, gleeunit}, {qcheck, qcheck}]]);
|
|
107
|
+
inspect(#{<<"mode">> := <<"crypto">>, <<"ebin">> := Ebin}) ->
|
|
108
|
+
true = code:add_patha(text(Ebin)),
|
|
109
|
+
case code:ensure_loaded(lawspec_beam_crypto_native) of
|
|
110
|
+
{module, lawspec_beam_crypto_native} -> ok;
|
|
111
|
+
Other -> fail(io_lib:format("Cannot load the compiled OpenSSL bridge: ~tp", [Other]))
|
|
112
|
+
end,
|
|
113
|
+
[{<<"OpenSSL">>, _, Version}] = crypto:info_lib(),
|
|
114
|
+
#{openssl => Version}.
|
|
115
|
+
|
|
116
|
+
app(Name, Ebin, Module) ->
|
|
117
|
+
case file:consult(filename:join(Ebin, atom_to_list(Name) ++ ".app")) of
|
|
118
|
+
{ok, [{application, Name, Properties}]} ->
|
|
119
|
+
true = code:add_patha(Ebin),
|
|
120
|
+
case code:ensure_loaded(Module) of
|
|
121
|
+
{module, Module} ->
|
|
122
|
+
Expected = filename:absname(filename:join(Ebin, atom_to_list(Module) ++ ".beam")),
|
|
123
|
+
case filename:absname(code:which(Module)) =:= Expected of
|
|
124
|
+
true -> unicode:characters_to_binary(proplists:get_value(vsn, Properties));
|
|
125
|
+
false -> fail(io_lib:format("~p is shadowed by another installed module", [Name]))
|
|
126
|
+
end;
|
|
127
|
+
_ -> fail(io_lib:format("~p is not compiled; build the project's test dependencies first", [Name]))
|
|
128
|
+
end;
|
|
129
|
+
_ -> fail(io_lib:format("~p is not installed and compiled; build the project's test dependencies first", [Name]))
|
|
130
|
+
end.
|
|
131
|
+
directories(Items) -> [unicode:characters_to_binary(case Item of {Dir, _} -> Dir; Dir -> Dir end) || Item <- Items].
|
|
132
|
+
text(Value) -> unicode:characters_to_list(Value).
|
|
133
|
+
fail(Message) -> throw({doctor, lists:flatten(Message)}).
|
|
134
|
+
`;
|
|
135
|
+
|
|
136
|
+
const elixirProbe = String.raw`
|
|
137
|
+
[input, output] = System.argv()
|
|
138
|
+
request = input |> File.read!() |> :json.decode()
|
|
139
|
+
config = Mix.Project.config()
|
|
140
|
+
dependency = Enum.find(Mix.Dep.load_and_cache(), &(&1.app == :stream_data))
|
|
141
|
+
unless dependency && dependency.scm == Hex.SCM && dependency.top_level do
|
|
142
|
+
Mix.raise("StreamData must be a direct Hex test dependency, without a path or Git replacement")
|
|
143
|
+
end
|
|
144
|
+
unless match?({:ok, _}, dependency.status) && Code.ensure_loaded?(StreamData) do
|
|
145
|
+
Mix.raise("StreamData is not installed and compiled; run MIX_ENV=test mix deps.compile")
|
|
146
|
+
end
|
|
147
|
+
loaded = :code.which(StreamData) |> List.to_string() |> Path.expand()
|
|
148
|
+
expected = Path.join([dependency.opts[:build], "ebin", "Elixir.StreamData.beam"]) |> Path.expand()
|
|
149
|
+
unless loaded == expected, do: Mix.raise("StreamData is shadowed by another installed module")
|
|
150
|
+
version = Application.spec(:stream_data, :vsn) |> to_string()
|
|
151
|
+
unless dependency.status == {:ok, version}, do: Mix.raise("StreamData's compiled version differs from the resolved dependency")
|
|
152
|
+
|
|
153
|
+
# Inspect test_helper configuration without asking ExUnit to execute a suite.
|
|
154
|
+
# Stage the real formatter because generation may not have written it yet.
|
|
155
|
+
Code.compiler_options(ignore_module_conflict: true, no_warn_undefined: :all)
|
|
156
|
+
Code.compile_file(request["formatter"])
|
|
157
|
+
ExUnit.start(autorun: false)
|
|
158
|
+
helper = Path.join(request["test_dir"], "test_helper.exs")
|
|
159
|
+
unless File.regular?(helper), do: Mix.raise("Missing #{helper}; configure the LawSpec ExUnit formatter there")
|
|
160
|
+
Code.require_file(helper)
|
|
161
|
+
ExUnit.configure(autorun: false)
|
|
162
|
+
settings = ExUnit.configuration()
|
|
163
|
+
compilers = Keyword.get(config, :compilers, Mix.compilers())
|
|
164
|
+
coverage = Keyword.get(config, :test_coverage, [])
|
|
165
|
+
data = %{
|
|
166
|
+
elixir: System.version(), stream_data: version,
|
|
167
|
+
erlc_paths: Keyword.get(config, :erlc_paths, ["src"]),
|
|
168
|
+
elixirc_paths: Keyword.get(config, :elixirc_paths, ["lib"]),
|
|
169
|
+
test_paths: Keyword.get(config, :test_paths, ["test"]),
|
|
170
|
+
test_pattern: Keyword.get(config, :test_pattern, "*_test.exs"),
|
|
171
|
+
ignored: Keyword.get(config, :test_ignore_filters, []) != [],
|
|
172
|
+
alias: Enum.any?([:test, :"compile.erlang", :"compile.elixir"], &Keyword.has_key?(config[:aliases] || [], &1)),
|
|
173
|
+
compilers: Enum.map(compilers, &to_string/1),
|
|
174
|
+
reporter: LawSpec.Beam.ExUnitFormatter in settings[:formatters],
|
|
175
|
+
filtered: settings[:exclude] != [] or settings[:include] != [],
|
|
176
|
+
dry_run: settings[:dry_run], max_failures: to_string(settings[:max_failures]),
|
|
177
|
+
crypto_compiler: :lawspec_crypto in compilers and Code.ensure_loaded?(Mix.Tasks.Compile.LawspecCrypto),
|
|
178
|
+
coverage: %{output: Path.expand(Keyword.get(coverage, :output, "cover")),
|
|
179
|
+
tool: inspect(Keyword.get(coverage, :tool, Mix.Tasks.Test.Coverage)),
|
|
180
|
+
compilePath: Path.expand(Mix.Project.compile_path())}
|
|
181
|
+
}
|
|
182
|
+
File.write!(output, :json.encode(data))
|
|
183
|
+
`;
|
|
184
|
+
|
|
185
|
+
export async function beamDoctor(target, root, artifacts, run) {
|
|
186
|
+
root = path.resolve(root);
|
|
187
|
+
const temporary = await mkdtemp(path.join(os.tmpdir(), "lawspec-beam-doctor-"));
|
|
188
|
+
const sourceDir = target.sourceDir ?? (target.language === "elixir" ? "lib" : "src");
|
|
189
|
+
const testDir = target.testDir ?? "test";
|
|
190
|
+
const needsCrypto = artifacts.length
|
|
191
|
+
? artifacts.some((file) => file.path === "priv/lawspec_crypto_native.c")
|
|
192
|
+
: await exists(path.join(root, "priv/lawspec_crypto_native.c"));
|
|
193
|
+
try {
|
|
194
|
+
const probeFile = path.join(temporary, "probe.escript");
|
|
195
|
+
const input = path.join(temporary, "input.json");
|
|
196
|
+
const output = path.join(temporary, "output.json");
|
|
197
|
+
await writeFile(probeFile, erlangProbe);
|
|
198
|
+
const probe = async (mode, options = {}) => {
|
|
199
|
+
await writeFile(input, JSON.stringify({mode, ...options}));
|
|
200
|
+
await rm(output, {force: true});
|
|
201
|
+
await run("escript", [probeFile, input, output], root);
|
|
202
|
+
return JSON.parse(await readFile(output, "utf8"));
|
|
203
|
+
};
|
|
204
|
+
// Fail clearly before using OTP's JSON API on an older VM.
|
|
205
|
+
const otp = (await run("erl", ["-noshell", "-eval", 'io:put_chars(erlang:system_info(otp_release)), halt().'], root)).trim();
|
|
206
|
+
requireThat(otp === "29", `BEAM targets require the verified Erlang/OTP 29 profile; found ${otp}`);
|
|
207
|
+
const versions = await probe("otp");
|
|
208
|
+
let coverage;
|
|
209
|
+
|
|
210
|
+
if (target.language === "erlang") {
|
|
211
|
+
const version = await run("rebar3", ["version"], root);
|
|
212
|
+
versions.rebar3 = /\brebar (\S+)/.exec(version)?.[1];
|
|
213
|
+
const proper = (await run("rebar3", ["as", "test", "path", "--app", "proper", "--ebin"], root)).trim();
|
|
214
|
+
requireThat(proper && !proper.includes("\n"), "Cannot resolve PropEr; run rebar3 as test compile first");
|
|
215
|
+
requireThat(!await exists(path.join(root, "_checkouts/proper")), "PropEr must resolve from Hex without a checkout replacement");
|
|
216
|
+
const data = await probe("rebar", {archive: path.join(temporary, "rebar.ez"), proper});
|
|
217
|
+
requireThat(data.proper_dependency, "PropEr must be a direct Hex dependency in the Rebar test profile");
|
|
218
|
+
requireThat(satisfiesRequirement(data.proper, data.proper_requirement),
|
|
219
|
+
"PropEr's compiled version does not satisfy the test profile dependency; run rebar3 as test compile");
|
|
220
|
+
requireThat(includesPath(root, data.src_dirs, sourceDir), "Rebar src_dirs must include the configured sourceDir");
|
|
221
|
+
requireThat(path.resolve(root, testDir) === path.join(root, "test") || includesPath(root, data.extra_src_dirs, testDir),
|
|
222
|
+
"Rebar extra_src_dirs must include the configured testDir when it is not test");
|
|
223
|
+
requireThat(data.reporter, "Configure Rebar eunit_opts with {report, {lawspec_beam_report, []}} for native execution reports");
|
|
224
|
+
requireThat(!data.filters && !data.alias, "Rebar must use unfiltered EUnit discovery without eunit_tests or an eunit alias");
|
|
225
|
+
requireThat(!needsCrypto || data.crypto_hook, "Add the compile pre_hook: escript lawspec_crypto_build.escript");
|
|
226
|
+
versions.proper = data.proper;
|
|
227
|
+
} else if (target.language === "elixir") {
|
|
228
|
+
const formatter = path.join(temporary, "formatter.ex");
|
|
229
|
+
const mixProbe = path.join(temporary, "probe.exs");
|
|
230
|
+
await writeFile(formatter, runtime.formatter);
|
|
231
|
+
await writeFile(mixProbe, elixirProbe);
|
|
232
|
+
await writeFile(input, JSON.stringify({formatter, test_dir: testDir}));
|
|
233
|
+
await rm(output, {force: true});
|
|
234
|
+
await run("mix", ["run", "--no-compile", "--no-start", "--no-deps-check", mixProbe, input, output], root,
|
|
235
|
+
{env: {...process.env, MIX_ENV: "test", ...(process.env.LAWSPEC_OFFLINE === "1" ? {HEX_OFFLINE: "1"} : {})}});
|
|
236
|
+
const data = JSON.parse(await readFile(output, "utf8"));
|
|
237
|
+
for (const [key, directory] of [["erlc_paths", target.sourceDir ?? "src"], ["elixirc_paths", sourceDir],
|
|
238
|
+
["erlc_paths", `${testDir}/support`], ["elixirc_paths", `${testDir}/support`], ["test_paths", testDir]])
|
|
239
|
+
requireThat(includesPath(root, data[key], directory), `Mix ${key} must include ${directory} in MIX_ENV=test`);
|
|
240
|
+
requireThat(data.compilers.includes("erlang") && data.compilers.includes("elixir"), "Mix must enable both erlang and elixir compilers");
|
|
241
|
+
requireThat(!data.alias && !data.ignored && data.test_pattern === "*_test.exs",
|
|
242
|
+
"Mix must discover *_test.exs without test_ignore_filters or aliases for test/compile.erlang/compile.elixir");
|
|
243
|
+
requireThat(data.reporter, "Configure LawSpec.Beam.ExUnitFormatter in test_helper.exs for native execution reports");
|
|
244
|
+
requireThat(!data.filtered && !data.dry_run,
|
|
245
|
+
"ExUnit must run without include/exclude filters or dry_run");
|
|
246
|
+
requireThat(data.max_failures === "infinity" ||
|
|
247
|
+
typeof data.max_failures === "string" && /^[1-9][0-9]*$/.test(data.max_failures),
|
|
248
|
+
"ExUnit max_failures must be a positive integer or :infinity");
|
|
249
|
+
requireThat(!needsCrypto || data.crypto_compiler, "Add :lawspec_crypto to Mix compilers and define Mix.Tasks.Compile.LawspecCrypto to run the bridge builder");
|
|
250
|
+
Object.assign(versions, {elixir: data.elixir, stream_data: data.stream_data});
|
|
251
|
+
coverage = data.coverage;
|
|
252
|
+
} else {
|
|
253
|
+
requireThat(sourceDir === "src" && testDir === "test", "Gleam requires sourceDir=src and testDir=test; choose a separate project root for another layout");
|
|
254
|
+
versions.gleam = /\bgleam (\S+)/.exec(await run("gleam", ["--version"], root))?.[1];
|
|
255
|
+
const configFile = path.join(temporary, "gleam.json");
|
|
256
|
+
await run("gleam", ["export", "package-information", "--out", configFile], root);
|
|
257
|
+
const config = JSON.parse(await readFile(configFile, "utf8"))["gleam.toml"];
|
|
258
|
+
requireThat(config?.target === "erlang", "gleam.toml must select target=erlang");
|
|
259
|
+
requireThat(config.dependencies?.gleam_stdlib?.version &&
|
|
260
|
+
["gleeunit", "qcheck"].every((name) => config.dev_dependencies?.[name]?.version),
|
|
261
|
+
"Gleam requires Hex gleam_stdlib plus direct gleeunit and qcheck dev-dependencies, without local replacements");
|
|
262
|
+
requireThat(path.resolve(root, config.dev_dependencies?.lawspec_test_support?.path ?? "") === path.join(root, "test-support"),
|
|
263
|
+
"Add lawspec_test_support = { path = \"./test-support\" } to Gleam dev-dependencies");
|
|
264
|
+
await run("gleam", ["export", "package-information", "--out", configFile], path.join(root, "test-support"));
|
|
265
|
+
const support = JSON.parse(await readFile(configFile, "utf8"))["gleam.toml"];
|
|
266
|
+
requireThat(support?.name === "lawspec_test_support" && support.target === "erlang" && support.dependencies?.qcheck?.version,
|
|
267
|
+
"test-support/gleam.toml must define lawspec_test_support for Erlang with a Hex qcheck dependency");
|
|
268
|
+
const runnerPath = path.join(root, "test", `${config.name}_test.gleam`);
|
|
269
|
+
const runner = (await readFile(runnerPath, "utf8")).replace(/\/\/[^\n]*/g, "").trim();
|
|
270
|
+
requireThat(/^@external\(\s*erlang\s*,\s*"lawspec_beam_test_run"\s*,\s*"gleam_main"\s*\)\s*pub\s+fn\s+main\(\s*\)\s*->\s*Nil\s*$/.test(runner),
|
|
271
|
+
`Use @external(erlang, "lawspec_beam_test_run", "gleam_main") pub fn main() -> Nil in test/${config.name}_test.gleam; put tests in other *_test.gleam modules`);
|
|
272
|
+
const resolved = new Map((await run("gleam", ["deps", "list"], root)).trim().split("\n")
|
|
273
|
+
.map((line) => line.trim().split(/\s+/)));
|
|
274
|
+
const compiled = await probe("gleam", {root});
|
|
275
|
+
for (const name of ["gleam_stdlib", "gleeunit", "qcheck"]) {
|
|
276
|
+
requireThat(resolved.get(name) === compiled[name], `${name}'s compiled version differs from the resolved dependency; run gleam build`);
|
|
277
|
+
const requirement = (config.dependencies?.[name] ?? config.dev_dependencies?.[name]).version;
|
|
278
|
+
requireThat(satisfiesRequirement(compiled[name], requirement), `${name}'s compiled version does not satisfy gleam.toml; run gleam build`);
|
|
279
|
+
versions[name] = compiled[name];
|
|
280
|
+
}
|
|
281
|
+
requireThat(satisfiesRequirement(versions.qcheck, support.dependencies.qcheck.version),
|
|
282
|
+
"qcheck's compiled version does not satisfy test-support/gleam.toml; run gleam build");
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (needsCrypto) {
|
|
286
|
+
// An ebin directory under an application named "crypto" would shadow
|
|
287
|
+
// OTP's crypto priv directory in the code server, even without an .app.
|
|
288
|
+
const project = path.join(temporary, "lawspec_doctor_native");
|
|
289
|
+
const ebin = path.join(project, "ebin");
|
|
290
|
+
await mkdir(path.join(project, "priv"), {recursive: true});
|
|
291
|
+
await mkdir(ebin);
|
|
292
|
+
const builder = path.join(project, "lawspec_crypto_build.escript");
|
|
293
|
+
const native = path.join(project, "lawspec_beam_crypto_native.erl");
|
|
294
|
+
await writeFile(builder, runtime.build);
|
|
295
|
+
await writeFile(native, runtime.native);
|
|
296
|
+
await writeFile(path.join(project, "priv/lawspec_crypto_native.c"), runtime.c);
|
|
297
|
+
await run("escript", [builder, project], root);
|
|
298
|
+
await run("erlc", ["-o", ebin, native], root);
|
|
299
|
+
// Loading the real NIF checks the shared-library ABI as well as compilation.
|
|
300
|
+
Object.assign(versions, await probe("crypto", {ebin}));
|
|
301
|
+
}
|
|
302
|
+
return {versions, ...(coverage ? {coverage} : {})};
|
|
303
|
+
} finally {
|
|
304
|
+
await rm(temporary, {recursive: true, force: true});
|
|
305
|
+
}
|
|
306
|
+
}
|