docattest 0.0.0-stage → 0.1.1

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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  3. package/dist/agents/claude.json +30 -0
  4. package/dist/agents/cursor.json +19 -0
  5. package/dist/agents/gemini.json +27 -0
  6. package/dist/agents/index.json +3 -0
  7. package/dist/api/adapter.d.ts +231 -0
  8. package/dist/api/adapter.js +2 -0
  9. package/dist/api/attestation.d.ts +76 -0
  10. package/dist/api/attestation.js +2 -0
  11. package/dist/api/audit.d.ts +56 -0
  12. package/dist/api/audit.js +2 -0
  13. package/dist/api/config.d.ts +44 -0
  14. package/dist/api/config.js +2 -0
  15. package/dist/api/constants.d.ts +35 -0
  16. package/dist/api/constants.js +56 -0
  17. package/dist/api/errors.d.ts +15 -0
  18. package/dist/api/errors.js +22 -0
  19. package/dist/api/impact.d.ts +49 -0
  20. package/dist/api/impact.js +2 -0
  21. package/dist/api/project.d.ts +64 -0
  22. package/dist/api/project.js +2 -0
  23. package/dist/api/report.d.ts +107 -0
  24. package/dist/api/report.js +2 -0
  25. package/dist/client/answers.d.ts +17 -0
  26. package/dist/client/answers.js +23 -0
  27. package/dist/client/core.d.ts +18 -0
  28. package/dist/client/core.js +58 -0
  29. package/dist/client/place.d.ts +14 -0
  30. package/dist/client/place.js +37 -0
  31. package/dist/client/project.d.ts +3 -0
  32. package/dist/client/project.js +98 -0
  33. package/dist/client/workspace.d.ts +12 -0
  34. package/dist/client/workspace.js +72 -0
  35. package/dist/compare-strings.d.ts +2 -0
  36. package/dist/compare-strings.js +5 -0
  37. package/dist/core-binary/locate.js +113 -0
  38. package/dist/core-binary/package.js +70 -0
  39. package/dist/core.json +4 -0
  40. package/dist/files/disk.d.ts +4 -0
  41. package/dist/files/disk.js +67 -0
  42. package/dist/files/glob.d.ts +10 -0
  43. package/dist/files/glob.js +21 -0
  44. package/dist/files/ignored.d.ts +14 -0
  45. package/dist/files/ignored.js +14 -0
  46. package/dist/files/memory.d.ts +5 -0
  47. package/dist/files/memory.js +26 -0
  48. package/dist/files/source.d.ts +22 -0
  49. package/dist/files/source.js +17 -0
  50. package/dist/index.d.ts +10 -0
  51. package/dist/index.js +6 -0
  52. package/dist/json.d.ts +16 -0
  53. package/dist/json.js +43 -0
  54. package/dist/language/cache.js +18 -0
  55. package/dist/language/citations/listing.js +64 -0
  56. package/dist/language/citations/match.js +14 -0
  57. package/dist/language/citations/tests-in-file.js +101 -0
  58. package/dist/language/compiler.js +73 -0
  59. package/dist/language/description.js +24 -0
  60. package/dist/language/impact/affected.js +50 -0
  61. package/dist/language/impact/fingerprint.js +123 -0
  62. package/dist/language/impact/graph.js +72 -0
  63. package/dist/language/impact/lookup.js +100 -0
  64. package/dist/language/impact/program.js +87 -0
  65. package/dist/language/impact/renames.js +57 -0
  66. package/dist/language/impact/revision.js +62 -0
  67. package/dist/language/impact/units.js +80 -0
  68. package/dist/language/index.js +10 -0
  69. package/dist/language/inventory/observables.js +56 -0
  70. package/dist/language/inventory/plan.js +72 -0
  71. package/dist/language/inventory/probe.js +150 -0
  72. package/dist/language/languages.js +43 -0
  73. package/dist/language/node/dependency.js +34 -0
  74. package/dist/language/node/exports-map.js +92 -0
  75. package/dist/language/program/exports.js +29 -0
  76. package/dist/language/program/file-names.js +13 -0
  77. package/dist/language/program/globals.js +38 -0
  78. package/dist/language/program/host.js +91 -0
  79. package/dist/language/program/options.js +48 -0
  80. package/dist/language/program/program.js +41 -0
  81. package/dist/language/run/attempt.js +100 -0
  82. package/dist/language/run/facts.js +109 -0
  83. package/dist/language/run/host.js +73 -0
  84. package/dist/language/run/jobs.js +37 -0
  85. package/dist/language/run/pool.js +75 -0
  86. package/dist/language/run/protocol.js +37 -0
  87. package/dist/language/run/result.js +18 -0
  88. package/dist/language/run/runner.js +115 -0
  89. package/dist/language/run/sourcemap.js +43 -0
  90. package/dist/language/run/spawn.js +40 -0
  91. package/dist/language/run/transpile.js +50 -0
  92. package/dist/language/session.js +42 -0
  93. package/dist/language/surfaces/packages.js +71 -0
  94. package/dist/language/surfaces/resolve.js +48 -0
  95. package/dist/language/surfaces/specs.js +32 -0
  96. package/dist/language/surfaces/stale.js +23 -0
  97. package/dist/language/symbols.js +95 -0
  98. package/dist/language/syntax/doc-comments.js +90 -0
  99. package/dist/language/syntax/doc-prose.js +23 -0
  100. package/dist/language/syntax/expression.js +52 -0
  101. package/dist/language/syntax/imports.js +83 -0
  102. package/dist/language/syntax/lexical.js +41 -0
  103. package/dist/language/syntax/parse.js +11 -0
  104. package/dist/language/syntax/prose.js +11 -0
  105. package/dist/language/syntax/setup-module.js +88 -0
  106. package/dist/language/ts.cjs +9 -0
  107. package/dist/language/worker/cases.js +73 -0
  108. package/dist/language/worker/compile.js +15 -0
  109. package/dist/language/worker/console.js +10 -0
  110. package/dist/language/worker/context.js +16 -0
  111. package/dist/language/worker/describe.js +107 -0
  112. package/dist/language/worker/example.js +27 -0
  113. package/dist/language/worker/facts.js +69 -0
  114. package/dist/language/worker/host-client.js +55 -0
  115. package/dist/language/worker/main.js +71 -0
  116. package/dist/language/worker/network.js +35 -0
  117. package/dist/language/worker/observe.js +39 -0
  118. package/dist/language/worker/registry.js +78 -0
  119. package/dist/language/worker/setup-facts.js +50 -0
  120. package/dist/language/worker/strays.js +37 -0
  121. package/dist/launcher/main.js +38 -0
  122. package/dist/platforms.json +40 -0
  123. package/dist/protocol/context.js +48 -0
  124. package/dist/protocol/main.js +22 -0
  125. package/dist/protocol/methods.js +178 -0
  126. package/dist/protocol/output.js +40 -0
  127. package/dist/protocol/overlay.js +31 -0
  128. package/dist/protocol/serve.js +24 -0
  129. package/dist/protocol/server.js +108 -0
  130. package/dist/protocol/wire.js +117 -0
  131. package/dist/schema/agent.json +162 -0
  132. package/dist/schema/attestations.json +307 -0
  133. package/dist/schema/kit.json +190 -0
  134. package/dist/schema/language.json +162 -0
  135. package/dist/schema/messages.json +68 -0
  136. package/dist/schema/methods.json +412 -0
  137. package/dist/schema/project.json +113 -0
  138. package/dist/schema/results.json +249 -0
  139. package/package.json +73 -4
@@ -0,0 +1,73 @@
1
+ import { builtinModules } from 'node:module';
2
+ import * as path from 'node:path';
3
+ import { InternalError } from '../../api/errors.js';
4
+ import { displayPath } from '../../files/source.js';
5
+ import { transpile } from './transpile.js';
6
+ import { isHostRequest } from './protocol.js';
7
+ const SCRIPT_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json'];
8
+ /**
9
+ * Answers workers' module questions. The session owns the files (in-memory projects exist
10
+ * only here) and the compiler, so workers never load TypeScript: they ask for a module and
11
+ * get CommonJS back.
12
+ */
13
+ export class ModuleHost {
14
+ files;
15
+ surfaces;
16
+ constructor(files,
17
+ /** Import specifier → runtime entry of a surface, absolute. */
18
+ surfaces) {
19
+ this.files = files;
20
+ this.surfaces = surfaces;
21
+ }
22
+ /** Answer one request from a worker. */
23
+ handle(request) {
24
+ if (!isHostRequest(request)) {
25
+ throw new InternalError('a worker sent a malformed module request');
26
+ }
27
+ if (request.op === 'resolve') {
28
+ return { op: 'resolve', resolution: this.resolve(request.specifier, request.from) };
29
+ }
30
+ return { op: 'source', source: this.source(request.file) };
31
+ }
32
+ /** Surfaces and relative imports are project modules; anything else is a dependency. */
33
+ resolve(specifier, from) {
34
+ const surface = this.surfaces.get(specifier);
35
+ if (surface !== undefined)
36
+ return { kind: 'project', file: surface };
37
+ if (specifier.startsWith('.') || specifier.startsWith('/')) {
38
+ const file = this.resolveFile(path.resolve(path.dirname(from), specifier));
39
+ if (file)
40
+ return { kind: 'project', file };
41
+ return {
42
+ kind: 'missing',
43
+ message: `Cannot find module '${specifier}' from ${displayPath(this.files.root, from)}`,
44
+ };
45
+ }
46
+ // In-memory files are not on disk, so their dependencies resolve from where docattest runs.
47
+ const builtin = specifier.startsWith('node:') || builtinModules.includes(specifier);
48
+ const base = builtin || this.files.memory ? path.join(process.cwd(), 'noop.js') : from;
49
+ return { kind: 'external', base };
50
+ }
51
+ /** A project module's code, transpiled to CommonJS. */
52
+ source(file) {
53
+ const text = this.files.readAbsolute(file);
54
+ if (text === undefined)
55
+ return undefined;
56
+ if (file.endsWith('.json'))
57
+ return { format: 'json', text };
58
+ return { format: 'script', code: transpile(file, text).code };
59
+ }
60
+ // Sources import each other by their compiled names (./x.js for ./x.ts), so try those too.
61
+ resolveFile(file) {
62
+ const candidates = [file];
63
+ const ext = path.extname(file);
64
+ if (['.js', '.mjs', '.cjs', '.jsx'].includes(ext)) {
65
+ const stem = file.slice(0, -ext.length);
66
+ candidates.push(stem + ext.replace('j', 't'), `${stem}.ts`, `${stem}.tsx`);
67
+ }
68
+ candidates.push(...SCRIPT_EXTENSIONS.map((e) => file + e));
69
+ candidates.push(...['.ts', '.tsx', '.js'].map((e) => path.join(file, `index${e}`)));
70
+ return candidates.find((c) => this.files.existsAbsolute(c));
71
+ }
72
+ }
73
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1,37 @@
1
+ import { attempt } from './attempt.js';
2
+ /**
3
+ * Run a job of `count` items to the end. When an item times out or kills its worker, it is
4
+ * recorded and the job resumes from the next item on a fresh worker.
5
+ */
6
+ export async function runJob(pool, job, count, timeoutMs) {
7
+ const result = { items: [], strays: [] };
8
+ const { items } = result;
9
+ for (;;) {
10
+ const { outcomes, strays, end } = await attempt(pool, job, items.length, timeoutMs);
11
+ result.strays.push(...strays);
12
+ items.push(...outcomes.map((outcome) => ({ kind: 'outcome', outcome })));
13
+ if (end.kind === 'done')
14
+ return result;
15
+ if (end.kind === 'failed' || !end.prepared)
16
+ return abandoned(result, end, count, timeoutMs);
17
+ if (items.length >= count)
18
+ return result;
19
+ items.push(end.kind === 'timeout' ? { kind: 'timeout' } : { kind: 'lost', message: end.message });
20
+ if (items.length >= count)
21
+ return result;
22
+ }
23
+ }
24
+ /**
25
+ * The job, once an attempt failed or could not prepare: when nothing ran, the job failed;
26
+ * when a resumed attempt could not prepare again, the remaining items never ran.
27
+ */
28
+ function abandoned(result, end, count, timeoutMs) {
29
+ const message = end.kind === 'timeout' ? `timed out after ${timeoutMs} ms` : end.message;
30
+ if (result.items.length === 0) {
31
+ return { failure: { message, timedOut: end.kind === 'timeout' }, ...result };
32
+ }
33
+ while (result.items.length < count)
34
+ result.items.push({ kind: 'lost', message });
35
+ return result;
36
+ }
37
+ //# sourceMappingURL=jobs.js.map
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A pool of reusable workers, spawned lazily up to `size`. A worker that timed out is
3
+ * discarded (terminated) and a fresh one takes its place when work is waiting.
4
+ *
5
+ * Closing is final: work still in flight loses its worker, and nothing it does afterwards
6
+ * (resuming, waiting its turn, starting) gets another, so no worker outlives `close`.
7
+ */
8
+ export class WorkerPool {
9
+ size;
10
+ spawn;
11
+ idle = [];
12
+ busy = new Set();
13
+ waiting = [];
14
+ stopping = new Set();
15
+ closed = false;
16
+ constructor(size, spawn) {
17
+ this.size = size;
18
+ this.spawn = spawn;
19
+ }
20
+ /** An idle worker, a new one, or the next one released; none once the pool is closed. */
21
+ async acquire() {
22
+ if (this.closed)
23
+ return undefined;
24
+ const idle = this.idle.pop();
25
+ if (idle)
26
+ return { worker: this.claim(idle), fresh: false };
27
+ if (this.busy.size < this.size)
28
+ return { worker: this.claim(this.spawn()), fresh: true };
29
+ return new Promise((resolve) => this.waiting.push(resolve));
30
+ }
31
+ /** Return a healthy worker for reuse. */
32
+ release(worker) {
33
+ // Closing already terminated it; its last message was still on its way.
34
+ if (this.closed)
35
+ return;
36
+ const next = this.waiting.shift();
37
+ if (next) {
38
+ next({ worker, fresh: false });
39
+ return;
40
+ }
41
+ this.busy.delete(worker);
42
+ this.idle.push(worker);
43
+ }
44
+ /** Terminate a worker that cannot be trusted any more, and replace it if work waits. */
45
+ discard(worker) {
46
+ this.busy.delete(worker);
47
+ this.stop(worker);
48
+ if (this.closed)
49
+ return;
50
+ const next = this.waiting.shift();
51
+ if (next)
52
+ next({ worker: this.claim(this.spawn()), fresh: true });
53
+ }
54
+ /** Terminate every worker, for good: whoever waits for one, or asks later, gets none. */
55
+ async close() {
56
+ this.closed = true;
57
+ for (const worker of [...this.idle, ...this.busy])
58
+ this.stop(worker);
59
+ this.idle.length = 0;
60
+ this.busy.clear();
61
+ for (const next of this.waiting.splice(0))
62
+ next(undefined);
63
+ await Promise.all(this.stopping);
64
+ }
65
+ claim(worker) {
66
+ this.busy.add(worker);
67
+ return worker;
68
+ }
69
+ stop(worker) {
70
+ const stopped = worker.terminate();
71
+ this.stopping.add(stopped);
72
+ void stopped.finally(() => this.stopping.delete(stopped));
73
+ }
74
+ }
75
+ //# sourceMappingURL=pool.js.map
@@ -0,0 +1,37 @@
1
+ import { isObject } from '../../json.js';
2
+ /** The free variable `import.meta` becomes in transpiled modules; the registry passes it. */
3
+ export const IMPORT_META = '__docattest_import_meta';
4
+ /** Whether a message is a {@link WorkerMessage}. */
5
+ export function isWorkerMessage(value) {
6
+ return isObject(value) && typeof value.type === 'string' && typeof value.id === 'string';
7
+ }
8
+ /** Whether a message is a {@link WorkerListening}. */
9
+ export function isWorkerListening(value) {
10
+ return isObject(value) && value.type === 'listening';
11
+ }
12
+ /** Whether a message is a {@link JobRequest}. */
13
+ export function isJobRequest(value) {
14
+ return isObject(value) && typeof value.id === 'string' && isObject(value.job);
15
+ }
16
+ /** Whether a message is a {@link HostRequest}. */
17
+ export function isHostRequest(value) {
18
+ return isObject(value) && (value.op === 'resolve' || value.op === 'source');
19
+ }
20
+ /** Whether a message is a {@link HostReply}. */
21
+ export function isHostReply(value) {
22
+ return (isObject(value) && (value.op === 'resolve' || value.op === 'source' || value.op === 'error'));
23
+ }
24
+ /** Whether worker data has the shape the session sends. */
25
+ export function isWorkerData(value) {
26
+ return (isObject(value) &&
27
+ typeof value.root === 'string' &&
28
+ value.signal instanceof Int32Array &&
29
+ isObject(value.snapshots) &&
30
+ isObject(value.manifests));
31
+ }
32
+ /** Why a fact cannot use a name that is both a surface export and a setup fact. */
33
+ export function ambiguous(name, surface) {
34
+ const what = `"${name}" is both an export of surface "${surface}" and a setup fact`;
35
+ return `${what}; rename the setup fact`;
36
+ }
37
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1,18 @@
1
+ /** A result located at an attestation (or at one of its rows, via `detail.line`). */
2
+ export function resultFor(attestation, status, message, detail = {}) {
3
+ const { page, kind } = attestation;
4
+ const result = {
5
+ page,
6
+ line: detail.line ?? attestation.line,
7
+ kind,
8
+ status,
9
+ symbols: [],
10
+ message,
11
+ };
12
+ if (detail.expected !== undefined)
13
+ result.expected = detail.expected;
14
+ if (detail.actual !== undefined)
15
+ result.actual = detail.actual;
16
+ return result;
17
+ }
18
+ //# sourceMappingURL=result.js.map
@@ -0,0 +1,115 @@
1
+ import * as path from 'node:path';
2
+ import { resultFor } from './result.js';
3
+ import { blockFile } from '../languages.js';
4
+ import { transpile } from './transpile.js';
5
+ import { ModuleHost } from './host.js';
6
+ import { runJob } from './jobs.js';
7
+ import { WorkerPool } from './pool.js';
8
+ import { spawnWorker } from './spawn.js';
9
+ const NETWORK_OFF = 'network example skipped: the network is off (set DOCATTEST_NETWORK=1 to run it)';
10
+ /** Runs examples and cases tables on the session's worker pool, created on first use. */
11
+ export class Runner {
12
+ ctx;
13
+ pool;
14
+ host;
15
+ constructor(ctx, surfaces) {
16
+ this.ctx = ctx;
17
+ const entries = surfaces.flatMap((s) => s.entry === undefined ? [] : [[s.spec.import, s.entry]]);
18
+ this.host = new ModuleHost(ctx.files, new Map(entries));
19
+ }
20
+ /** Run a job to the end on the pool. */
21
+ async execute(job, count) {
22
+ return runJob(this.getPool(), job, count, this.ctx.timeoutMs);
23
+ }
24
+ /** Run one example block. */
25
+ async example(e) {
26
+ if (e.network && !this.ctx.network)
27
+ return resultFor(e, 'skipped', NETWORK_OFF);
28
+ const file = blockFile(this.ctx.files.root, e);
29
+ const { code, lines } = transpile(file, e.code);
30
+ const job = {
31
+ type: 'example',
32
+ file,
33
+ code,
34
+ lines,
35
+ source: e.code,
36
+ offline: !e.network,
37
+ weak: e.weak,
38
+ };
39
+ const { items, strays } = await this.execute(job, 1);
40
+ const [item] = items;
41
+ const verdict = item
42
+ ? this.verdict(item)
43
+ : { status: 'fail', message: 'the block produced no result' };
44
+ return resultFor(e, ...withStrays(verdict, strays));
45
+ }
46
+ /** Run every row of a cases table; an unusable table is one `error` at its line. */
47
+ async cases(c) {
48
+ const at = `cases "${c.runner}" at L${c.line}`;
49
+ const setup = this.ctx.setup;
50
+ if (setup === undefined) {
51
+ return [
52
+ resultFor(c, 'error', `${at}: no setup module is configured ("setup" in docattest.config.json)`),
53
+ ];
54
+ }
55
+ if (!this.ctx.files.exists(setup)) {
56
+ return [resultFor(c, 'error', `${at}: setup module ${setup} not found`)];
57
+ }
58
+ const { runner, page, line, header, rows } = c;
59
+ const label = { file: path.join(this.ctx.files.root, setup), label: setup };
60
+ const job = { type: 'cases', setup: label, runner, page, line, header, rows };
61
+ const { failure, items, strays } = await this.execute(job, rows.length);
62
+ if (failure) {
63
+ const message = failure.timedOut
64
+ ? `${at}: setup module ${setup} failed to load: ${failure.message}`
65
+ : failure.message;
66
+ return [resultFor(c, 'error', message)];
67
+ }
68
+ return rows.map((row, k) => {
69
+ const item = items[k];
70
+ const name = `${page}:${row.line} ${row.name}`;
71
+ const verdict = item
72
+ ? this.verdict(item, name)
73
+ : { status: 'fail', message: `${name}: did not run` };
74
+ const [status, message, detail] = k === rows.length - 1 ? withStrays(verdict, strays) : withStrays(verdict, []);
75
+ return resultFor(c, status, message, { ...detail, line: row.line });
76
+ });
77
+ }
78
+ /** Terminate the pool's workers. */
79
+ async close() {
80
+ await this.pool?.close();
81
+ }
82
+ verdict(item, name) {
83
+ const prefix = name === undefined ? '' : `${name}: `;
84
+ if (item.kind === 'timeout') {
85
+ return { status: 'fail', message: `${prefix}timed out after ${this.ctx.timeoutMs} ms` };
86
+ }
87
+ if (item.kind === 'lost')
88
+ return { status: 'fail', message: `${prefix}${item.message}` };
89
+ if (item.outcome.kind === 'verdict')
90
+ return item.outcome.verdict;
91
+ return { status: 'fail', message: `${prefix}the worker returned an evaluation for a row` };
92
+ }
93
+ getPool() {
94
+ const snapshots = {
95
+ dir: this.ctx.snapshots.dir,
96
+ data: Object.fromEntries(this.ctx.snapshots.data),
97
+ };
98
+ const manifests = Object.fromEntries(this.ctx.manifests);
99
+ this.pool ??= new WorkerPool(this.ctx.workers, () => spawnWorker(this.host, this.ctx.files.root, { snapshots, manifests }));
100
+ return this.pool;
101
+ }
102
+ }
103
+ // Errors that escaped the attested code after its block or row finished still fail it.
104
+ function withStrays(verdict, strays) {
105
+ const { status, message, expected, actual } = verdict;
106
+ const detail = {
107
+ ...(expected === undefined ? {} : { expected }),
108
+ ...(actual === undefined ? {} : { actual }),
109
+ };
110
+ if (!strays.length)
111
+ return [status, message, detail];
112
+ const escaped = `unhandled error from attested code: ${strays.join('; ')}`;
113
+ return ['fail', status === 'pass' ? escaped : `${message}; ${escaped}`, detail];
114
+ }
115
+ //# sourceMappingURL=runner.js.map
@@ -0,0 +1,43 @@
1
+ const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2
+ /**
3
+ * For each generated line, the first original line it maps to (0-based), from a source
4
+ * map's `mappings`. Only lines are needed: failures are reported as `block line N`.
5
+ */
6
+ export function decodeLines(mappings) {
7
+ const out = [];
8
+ let source = 0;
9
+ for (const line of mappings.split(';')) {
10
+ let first;
11
+ for (const segment of line.split(',')) {
12
+ if (!segment)
13
+ continue;
14
+ const fields = decodeVlq(segment);
15
+ const delta = fields[2];
16
+ if (fields.length < 4 || delta === undefined)
17
+ continue;
18
+ source += delta;
19
+ first ??= source;
20
+ }
21
+ out.push(first);
22
+ }
23
+ return out;
24
+ }
25
+ /** Decode one base64 VLQ segment into its signed fields. */
26
+ export function decodeVlq(segment) {
27
+ const out = [];
28
+ let value = 0;
29
+ let shift = 0;
30
+ for (const char of segment) {
31
+ const digit = BASE64.indexOf(char);
32
+ value += (digit & 31) << shift;
33
+ if (digit & 32) {
34
+ shift += 5;
35
+ continue;
36
+ }
37
+ out.push(value & 1 ? -(value >>> 1) : value >>> 1);
38
+ value = 0;
39
+ shift = 0;
40
+ }
41
+ return out;
42
+ }
43
+ //# sourceMappingURL=sourcemap.js.map
@@ -0,0 +1,40 @@
1
+ import { MessageChannel, Worker } from 'node:worker_threads';
2
+ import { messageOf } from '../../api/errors.js';
3
+ const WORKER = new URL('../worker/main.js', import.meta.url);
4
+ /**
5
+ * Start a worker wired to a module host. The worker blocks on `signal` after each request;
6
+ * the host posts its reply and then flips the signal, so the reply is always waiting.
7
+ */
8
+ export function spawnWorker(host, root, { snapshots, manifests }) {
9
+ const { port1, port2 } = new MessageChannel();
10
+ const signal = new Int32Array(new SharedArrayBuffer(4));
11
+ port1.on('message', (request) => {
12
+ port1.postMessage(answer(host, request));
13
+ Atomics.store(signal, 0, 1);
14
+ Atomics.notify(signal, 0);
15
+ });
16
+ const workerData = { root, port: port2, signal, snapshots, manifests };
17
+ // Attested code may print; its output must not mix with the report or its JSON.
18
+ const worker = new Worker(WORKER, {
19
+ workerData,
20
+ transferList: [port2],
21
+ stdout: true,
22
+ stderr: true,
23
+ });
24
+ worker.stdout.resume();
25
+ worker.stderr.resume();
26
+ worker.once('exit', () => {
27
+ port1.close();
28
+ });
29
+ return worker;
30
+ }
31
+ // A worker is blocked until it gets a reply, so a failure must still produce one.
32
+ function answer(host, request) {
33
+ try {
34
+ return host.handle(request);
35
+ }
36
+ catch (err) {
37
+ return { op: 'error', message: messageOf(err) };
38
+ }
39
+ }
40
+ //# sourceMappingURL=spawn.js.map
@@ -0,0 +1,50 @@
1
+ import ts from '../ts.cjs';
2
+ import { isObject } from '../../json.js';
3
+ import { threadCache } from '../cache.js';
4
+ import { IMPORT_META } from './protocol.js';
5
+ import { decodeLines } from './sourcemap.js';
6
+ // Transpiling is a pure function of path and text, so every copy of docattest shares it.
7
+ const CACHE = threadCache('transpiled');
8
+ /**
9
+ * Transpile TypeScript or JavaScript to CommonJS. Blocks and project modules run in a fresh
10
+ * registry per block, which needs a module format whose cache docattest owns.
11
+ */
12
+ export function transpile(file, text) {
13
+ const key = `${file}\0${text}`;
14
+ const cached = CACHE.get(key);
15
+ if (cached)
16
+ return cached;
17
+ const out = ts.transpileModule(text, {
18
+ fileName: file,
19
+ compilerOptions: {
20
+ module: ts.ModuleKind.CommonJS,
21
+ target: ts.ScriptTarget.ES2022,
22
+ esModuleInterop: true,
23
+ sourceMap: true,
24
+ allowJs: true,
25
+ jsx: ts.JsxEmit.React,
26
+ verbatimModuleSyntax: false,
27
+ },
28
+ transformers: { before: [importMetaTransformer] },
29
+ });
30
+ const code = out.outputText.replace(/\n\/\/# sourceMappingURL=.*\s*$/, '\n');
31
+ const transpiled = { code, lines: decodeLines(mappingsOf(out.sourceMapText)) };
32
+ CACHE.set(key, transpiled);
33
+ return transpiled;
34
+ }
35
+ function mappingsOf(sourceMap) {
36
+ const parsed = JSON.parse(sourceMap ?? '{}');
37
+ return isObject(parsed) && typeof parsed.mappings === 'string' ? parsed.mappings : '';
38
+ }
39
+ // CommonJS has no `import.meta`; ESM code (including docattest's own build) uses it for
40
+ // paths relative to the module, so it becomes a variable the registry provides.
41
+ function importMetaTransformer(context) {
42
+ const visit = (node) => {
43
+ if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) {
44
+ return context.factory.createIdentifier(IMPORT_META);
45
+ }
46
+ return ts.visitEachChild(node, visit, context);
47
+ };
48
+ return (source) => ts.visitEachChild(source, visit, context);
49
+ }
50
+ //# sourceMappingURL=transpile.js.map
@@ -0,0 +1,42 @@
1
+ import { listTests } from './citations/listing.js';
2
+ import { Compiler } from './compiler.js';
3
+ import { surfaceObservables } from './inventory/observables.js';
4
+ import { affectedExports } from './impact/affected.js';
5
+ import { FactEvaluator } from './run/facts.js';
6
+ import { Runner } from './run/runner.js';
7
+ import { resolveSurfaces } from './surfaces/resolve.js';
8
+ import { surfaceSpecs } from './surfaces/specs.js';
9
+ import { namesInCode } from './syntax/lexical.js';
10
+ import { SymbolResolver } from './symbols.js';
11
+ /**
12
+ * The TypeScript adapter for one check: a compiler program for `compile`, `symbols` and
13
+ * `exports`, and a worker pool for `evaluate` and `run`. Nothing is built until used.
14
+ */
15
+ export function createSession(ctx) {
16
+ const specs = surfaceSpecs(ctx.surfaces, ctx.files);
17
+ const surfaces = resolveSurfaces(ctx.files, specs);
18
+ const compiler = new Compiler(ctx.files, surfaces, ctx.examples);
19
+ const symbols = new SymbolResolver(ctx.files, surfaces, compiler, ctx.setup);
20
+ const runner = new Runner(ctx, surfaces);
21
+ const facts = new FactEvaluator(ctx, surfaces, runner, (name) => compiler.exports(name));
22
+ return {
23
+ compile: (examples) => Promise.resolve(compiler.compile(examples)),
24
+ evaluate: async (list) => facts.evaluate(list),
25
+ run: async (examples, cases) => {
26
+ const ran = await Promise.all([
27
+ ...examples.map(async (e) => [await runner.example(e)]),
28
+ ...cases.map(async (c) => runner.cases(c)),
29
+ ]);
30
+ return ran.flat();
31
+ },
32
+ symbols: (attestation) => Promise.resolve(symbols.of(attestation)),
33
+ exports: (name) => Promise.resolve(compiler.exports(name)),
34
+ tests: (file) => Promise.resolve(listTests(ctx.files, file)),
35
+ observables: async (name) => surfaceObservables(facts, compiler.exports(name) ?? [], name),
36
+ describeSurfaces: () => Promise.resolve(new Map(surfaces.map((s) => [s.spec.name, s.description]))),
37
+ affected: (change) => Promise.resolve(affectedExports(ctx.files, specs, change)),
38
+ inCode: (names, files) => Promise.resolve(namesInCode(ctx.files, specs, names, files)),
39
+ close: async () => runner.close(),
40
+ };
41
+ }
42
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1,71 @@
1
+ import * as fs from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import * as path from 'node:path';
4
+ import { globMatcher } from '../../files/glob.js';
5
+ import { relativeTo } from '../../files/source.js';
6
+ import { isObject, isStringArray, projectObject } from '../../json.js';
7
+ // Only a pnpm workspace needs YAML, so its parser is loaded then, not by every adapter.
8
+ const load = createRequire(import.meta.url);
9
+ const parseYaml = (text) => load('yaml').parse(text);
10
+ /**
11
+ * The package a file belongs to: the nearest `package.json` with a name. Nameless ones
12
+ * (such as `{ "type": "module" }` markers inside a build) are skipped.
13
+ */
14
+ export function nearestPackage(files, file) {
15
+ for (let dir = path.dirname(file);; dir = path.dirname(dir)) {
16
+ const info = readPackage(files, dir);
17
+ if (info)
18
+ return info;
19
+ if (path.dirname(dir) === dir)
20
+ return undefined;
21
+ }
22
+ }
23
+ /** Packages of the project's workspace: npm, Yarn and Bun `workspaces`, and pnpm's file. */
24
+ export function workspacePackages(files) {
25
+ const patterns = workspacePatterns(files);
26
+ const include = globMatcher(patterns.filter((p) => !p.startsWith('!')).map((p) => `${p}/package.json`));
27
+ const exclude = globMatcher(patterns.filter((p) => p.startsWith('!')).map((p) => `${p.slice(1)}/package.json`));
28
+ return files
29
+ .list()
30
+ .filter((f) => include(f) && !exclude(f))
31
+ .flatMap((f) => readPackage(files, path.join(files.root, path.posix.dirname(f))) ?? []);
32
+ }
33
+ /**
34
+ * A path for the report: project-relative when inside the project, also when the runtime
35
+ * resolved it through a symlinked root (macOS's /var is /private/var), else absolute.
36
+ */
37
+ export function projectPath(files, file) {
38
+ const real = files.memory ? undefined : realpath(files.root);
39
+ return (relativeTo(files.root, file) ??
40
+ (real === undefined ? undefined : relativeTo(real, file)) ??
41
+ file);
42
+ }
43
+ function realpath(file) {
44
+ try {
45
+ return fs.realpathSync(file);
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ /** Whether two package directories are the same directory once symlinks are followed. */
52
+ export function sameDirectory(files, a, b) {
53
+ if (files.memory)
54
+ return a === b;
55
+ return (realpath(a) ?? a) === (realpath(b) ?? b);
56
+ }
57
+ function readPackage(files, dir) {
58
+ const file = path.join(dir, 'package.json');
59
+ const manifest = projectObject(files.readAbsolute(file), projectPath(files, file));
60
+ if (typeof manifest?.name !== 'string' || !manifest.name)
61
+ return undefined;
62
+ const version = typeof manifest.version === 'string' ? manifest.version : undefined;
63
+ return { name: manifest.name, version, dir };
64
+ }
65
+ function workspacePatterns(files) {
66
+ const workspaces = projectObject(files.read('package.json'), 'package.json')?.workspaces;
67
+ const declared = isObject(workspaces) ? workspaces.packages : workspaces;
68
+ const pnpm = projectObject(files.read('pnpm-workspace.yaml'), 'pnpm-workspace.yaml', parseYaml)?.packages;
69
+ return [...(isStringArray(declared) ? declared : []), ...(isStringArray(pnpm) ? pnpm : [])];
70
+ }
71
+ //# sourceMappingURL=packages.js.map
@@ -0,0 +1,48 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { resolveDependency } from '../node/dependency.js';
4
+ import { nearestPackage, projectPath } from './packages.js';
5
+ import { staleCopyWarning } from './stale.js';
6
+ /** Resolve every configured surface once per session. */
7
+ export function resolveSurfaces(files, specs) {
8
+ return specs.map((spec) => {
9
+ const entry = runtimeEntry(files, spec);
10
+ const types = spec.path !== undefined && entry ? typesEntry(files, entry) : undefined;
11
+ return { spec, entry, types, description: describe(files, spec, entry) };
12
+ });
13
+ }
14
+ function runtimeEntry(files, spec) {
15
+ if (spec.path !== undefined) {
16
+ return files.exists(spec.path) ? path.join(files.root, spec.path) : undefined;
17
+ }
18
+ if (files.memory)
19
+ return undefined;
20
+ const found = resolveDependency(spec.import, path.join(files.root, 'package.json'));
21
+ return found && fs.existsSync(found) ? fs.realpathSync(found) : found;
22
+ }
23
+ // A built entry such as dist/index.js is checked against its declarations when they exist,
24
+ // which is what a user of the package sees.
25
+ function typesEntry(files, entry) {
26
+ const declaration = entry.replace(/\.(m|c)?jsx?$/, (_, kind) => `.d.${kind ?? ''}ts`);
27
+ return declaration !== entry && files.existsAbsolute(declaration) ? declaration : entry;
28
+ }
29
+ function describe(files, spec, entry) {
30
+ if (!entry) {
31
+ const where = spec.path === undefined ? '' : ` (${spec.path} does not exist)`;
32
+ return {
33
+ warnings: [`"${spec.import}" did not resolve${where}; examples and facts that use it fail`],
34
+ };
35
+ }
36
+ const resolution = { import: spec.import, entry: projectPath(files, entry) };
37
+ const pkg = nearestPackage(files, entry);
38
+ if (pkg) {
39
+ // How npm writes a package and its version.
40
+ resolution.package =
41
+ pkg.version === undefined
42
+ ? { name: pkg.name, display: pkg.name }
43
+ : { name: pkg.name, version: pkg.version, display: `${pkg.name}@${pkg.version}` };
44
+ }
45
+ const stale = spec.path === undefined ? staleCopyWarning(files, spec, entry) : undefined;
46
+ return { resolution, warnings: stale ? [stale] : [] };
47
+ }
48
+ //# sourceMappingURL=resolve.js.map