@blinkhost/cli 2.7.0 → 2.8.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 +4 -0
- package/README.md +514 -2
- package/dist/api.d.ts +2 -2
- package/dist/api.js +57 -8
- package/dist/assistant.js +6 -1
- package/dist/cli.js +157 -9
- package/dist/guidance.d.ts +1 -1
- package/dist/guidance.js +43 -11
- package/dist/javascript-runtime/resource-limits.js +3 -0
- package/dist/javascript-runtime/resource-profiles.js +2 -0
- package/dist/local-dev.d.ts +3 -0
- package/dist/local-dev.js +145 -0
- package/dist/local-development/README.md +410 -0
- package/dist/local-development/artifact-watch.mjs +36 -0
- package/dist/local-development/blinkhost.local.example.json +15 -0
- package/dist/local-development/frontend-proxy.mjs +189 -0
- package/dist/local-development/hello.rs +24 -0
- package/dist/local-development/local-stack.mjs +511 -0
- package/dist/local-development/native-database.mjs +37 -0
- package/dist/local-development/provider-fixtures.example.json +36 -0
- package/dist/local-development/provider-fixtures.mjs +203 -0
- package/dist/local-development/provider-grants.mjs +36 -0
- package/dist/local-development/test-provider-example.mjs +74 -0
- package/dist/local-source-build.d.ts +39 -0
- package/dist/local-source-build.js +225 -0
- package/dist/local-source-watch.d.ts +24 -0
- package/dist/local-source-watch.js +87 -0
- package/dist/local-test-command.d.ts +49 -0
- package/dist/local-test-command.js +128 -0
- package/dist/local-test-config.d.ts +37 -0
- package/dist/local-test-config.js +174 -0
- package/dist/local-test-gates.d.ts +71 -0
- package/dist/local-test-gates.js +247 -0
- package/dist/local-test-go-runner.d.ts +27 -0
- package/dist/local-test-go-runner.js +209 -0
- package/dist/local-test-node-arguments.d.ts +2 -0
- package/dist/local-test-node-arguments.js +14 -0
- package/dist/local-test-node-reporter.d.ts +7 -0
- package/dist/local-test-node-reporter.js +159 -0
- package/dist/local-test-results.d.ts +65 -0
- package/dist/local-test-results.js +163 -0
- package/dist/local-test-rust-runner.d.ts +18 -0
- package/dist/local-test-rust-runner.js +252 -0
- package/dist/local-test-starters.d.ts +3 -0
- package/dist/local-test-starters.js +157 -0
- package/dist/logs.d.ts +43 -0
- package/dist/logs.js +417 -0
- package/dist/module-build-diagnostics.d.ts +10 -0
- package/dist/module-build-diagnostics.js +208 -0
- package/dist/module-build.js +4 -0
- package/dist/release-preparation-diagnostics.d.ts +38 -0
- package/dist/release-preparation-diagnostics.js +204 -0
- package/dist/remote.js +14 -0
- package/dist/templates.d.ts +1 -0
- package/dist/templates.js +4 -1
- package/dist/test-credentials.d.ts +7 -0
- package/dist/test-credentials.js +236 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workflows.d.ts +39 -2
- package/dist/workflows.js +241 -14
- package/package.json +4 -3
- package/test-runners/python-unittest.py +266 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { access, lstat, open, realpath } from 'node:fs/promises';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { parseDocument } from 'yaml';
|
|
7
|
+
import { CliError, EXIT } from './errors.js';
|
|
8
|
+
import { LOCAL_TEST_CONFIG } from './local-test-config.js';
|
|
9
|
+
export const LOCAL_TEST_GATE_CONFIG = 'blinkhost.gates.json';
|
|
10
|
+
export const LOCAL_TEST_GATE_LIMITS = { files: 1024, bytes: 512 * 1024 * 1024, fileBytes: 256 * 1024 * 1024 };
|
|
11
|
+
const CATEGORIES = ['source', 'artifacts', 'dependencies', 'runtime', 'resources', 'fixtures'];
|
|
12
|
+
const CONFIGURATION = ['blinkhost.yaml', LOCAL_TEST_CONFIG, LOCAL_TEST_GATE_CONFIG];
|
|
13
|
+
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
14
|
+
function invalid() { throw new CliError('Invalid local test gate configuration or inputs.', EXIT.validation, 'invalid_local_test_gate'); }
|
|
15
|
+
function budget(deadline, signal) {
|
|
16
|
+
if (signal?.aborted)
|
|
17
|
+
throw new CliError('Local test gate was cancelled.', signal.reason === 'SIGTERM' ? 143 : 130, 'project_test_cancelled');
|
|
18
|
+
if (performance.now() >= deadline)
|
|
19
|
+
throw new CliError('Local test gate exhausted the shared test timeout.', EXIT.validation, 'project_test_timeout');
|
|
20
|
+
}
|
|
21
|
+
function object(value, fields) {
|
|
22
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !fields.includes(key)))
|
|
23
|
+
invalid();
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
async function read(filename, maximum, collect, deadline, signal) {
|
|
27
|
+
budget(deadline, signal);
|
|
28
|
+
const file = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
29
|
+
try {
|
|
30
|
+
const before = await file.stat({ bigint: true });
|
|
31
|
+
if (!before.isFile() || before.size > BigInt(maximum))
|
|
32
|
+
invalid();
|
|
33
|
+
const digest = createHash('sha256'), buffer = Buffer.alloc(65_536), chunks = [];
|
|
34
|
+
let bytes = 0;
|
|
35
|
+
while (true) {
|
|
36
|
+
budget(deadline, signal);
|
|
37
|
+
const result = await file.read(buffer, 0, Math.min(buffer.length, maximum - bytes + 1), bytes);
|
|
38
|
+
if (!result.bytesRead)
|
|
39
|
+
break;
|
|
40
|
+
bytes += result.bytesRead;
|
|
41
|
+
if (bytes > maximum)
|
|
42
|
+
invalid();
|
|
43
|
+
const chunk = buffer.subarray(0, result.bytesRead);
|
|
44
|
+
digest.update(chunk);
|
|
45
|
+
if (collect)
|
|
46
|
+
chunks.push(Buffer.from(chunk));
|
|
47
|
+
}
|
|
48
|
+
const after = await file.stat({ bigint: true }), current = await lstat(filename, { bigint: true });
|
|
49
|
+
if (!current.isFile() || current.isSymbolicLink() || ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].some(key => before[key] !== after[key]
|
|
50
|
+
|| before[key] !== current[key]) || bytes !== Number(before.size))
|
|
51
|
+
invalid();
|
|
52
|
+
return { sha256: digest.digest('hex'), bytes, content: Buffer.concat(chunks) };
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
await file.close();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function projectFile(root, path) {
|
|
59
|
+
if (!path || path.length > 1024 || !/^[a-zA-Z0-9_.@/-]+$/.test(path)
|
|
60
|
+
|| path.startsWith('/') || path.split('/').some(part => !part || part === '.' || part === '..'))
|
|
61
|
+
invalid();
|
|
62
|
+
let cursor = root;
|
|
63
|
+
for (const part of path.split('/').slice(0, -1)) {
|
|
64
|
+
cursor = join(cursor, part);
|
|
65
|
+
const stat = await lstat(cursor);
|
|
66
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
67
|
+
invalid();
|
|
68
|
+
}
|
|
69
|
+
return join(root, path);
|
|
70
|
+
}
|
|
71
|
+
async function executable(command, cwd) {
|
|
72
|
+
const candidates = command.includes('/') ? [isAbsolute(command) ? command : resolve(cwd, command)]
|
|
73
|
+
: (process.env.PATH ?? '').split(delimiter).map(path => resolve(cwd, path || '.', command));
|
|
74
|
+
for (const path of candidates) {
|
|
75
|
+
try {
|
|
76
|
+
await access(path, constants.X_OK);
|
|
77
|
+
const filename = await realpath(path);
|
|
78
|
+
if (!(await lstat(filename)).isFile())
|
|
79
|
+
continue;
|
|
80
|
+
return filename;
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (!['ENOENT', 'EACCES', 'ENOTDIR'].includes(error.code ?? ''))
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
invalid();
|
|
88
|
+
}
|
|
89
|
+
async function snapshot(prepared, deadline, signal) {
|
|
90
|
+
budget(deadline, signal);
|
|
91
|
+
if (await realpath(prepared.root) !== prepared.root)
|
|
92
|
+
invalid();
|
|
93
|
+
for (const tool of prepared.executables ?? []) {
|
|
94
|
+
budget(deadline, signal);
|
|
95
|
+
if (await executable(tool.command, tool.cwd) !== tool.filename)
|
|
96
|
+
invalid();
|
|
97
|
+
}
|
|
98
|
+
let remaining = LOCAL_TEST_GATE_LIMITS.bytes;
|
|
99
|
+
const inputs = [];
|
|
100
|
+
for (const input of prepared.paths) {
|
|
101
|
+
if (input.category !== 'cli' && await projectFile(prepared.root, input.path) !== input.filename)
|
|
102
|
+
invalid();
|
|
103
|
+
const value = await read(input.filename, Math.min(remaining, LOCAL_TEST_GATE_LIMITS.fileBytes), false, deadline, signal);
|
|
104
|
+
if (input.category !== 'cli')
|
|
105
|
+
await projectFile(prepared.root, input.path);
|
|
106
|
+
remaining -= value.bytes;
|
|
107
|
+
inputs.push({ category: input.category, path: input.path, sha256: value.sha256, bytes: value.bytes });
|
|
108
|
+
}
|
|
109
|
+
budget(deadline, signal);
|
|
110
|
+
return inputs;
|
|
111
|
+
}
|
|
112
|
+
/** Bind configuration observed before validation to configuration used for execution. */
|
|
113
|
+
export async function captureLocalTestGateConfiguration(root, deadline, signal) {
|
|
114
|
+
root = await realpath(root);
|
|
115
|
+
const inputs = [];
|
|
116
|
+
for (const path of CONFIGURATION) {
|
|
117
|
+
const value = await read(await projectFile(root, path), 65_536, false, deadline, signal);
|
|
118
|
+
inputs.push({ category: 'configuration', path, sha256: value.sha256, bytes: value.bytes });
|
|
119
|
+
}
|
|
120
|
+
return inputs;
|
|
121
|
+
}
|
|
122
|
+
/** A customer-local preflight, never a worker attestation or preview/promotion grant. */
|
|
123
|
+
export async function prepareLocalTestGate(root, stage, definitions, limits, deadline, signal, configuration) {
|
|
124
|
+
if (stage !== 'preview' && stage !== 'promotion')
|
|
125
|
+
invalid();
|
|
126
|
+
if (process.platform !== 'linux')
|
|
127
|
+
throw new CliError('Local test gates currently qualify Linux only.', EXIT.validation, 'local_test_gate_platform_unsupported');
|
|
128
|
+
root = await realpath(root);
|
|
129
|
+
const filename = await projectFile(root, LOCAL_TEST_GATE_CONFIG);
|
|
130
|
+
const source = await read(filename, 65_536, true, deadline, signal);
|
|
131
|
+
let parsed;
|
|
132
|
+
try {
|
|
133
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(source.content);
|
|
134
|
+
parsed = JSON.parse(text);
|
|
135
|
+
// JSON.parse accepts duplicate keys; a gate policy must be unambiguous.
|
|
136
|
+
if (parseDocument(text, { schema: 'json', strict: true, uniqueKeys: true }).errors.length)
|
|
137
|
+
invalid();
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
invalid();
|
|
141
|
+
}
|
|
142
|
+
const policy = object(parsed, ['schema', 'inputs', 'stages']);
|
|
143
|
+
if (policy.schema !== 'blinkhost.local-test-gates/v1')
|
|
144
|
+
invalid();
|
|
145
|
+
const declarations = object(policy.inputs, CATEGORIES), stages = object(policy.stages, ['preview', 'promotion']);
|
|
146
|
+
const required = stages[stage];
|
|
147
|
+
if (!Array.isArray(required) || !required.length || required.length > 32)
|
|
148
|
+
invalid();
|
|
149
|
+
for (const [name, checks] of Object.entries(stages)) {
|
|
150
|
+
if (!Array.isArray(checks) || !checks.length || checks.length > 32 || new Set(checks).size !== checks.length)
|
|
151
|
+
invalid();
|
|
152
|
+
for (const id of checks) {
|
|
153
|
+
const definition = definitions.find(row => row.id === id);
|
|
154
|
+
if (typeof id !== 'string' || !definition || definition.kind === 'build' || !definition.results)
|
|
155
|
+
invalid();
|
|
156
|
+
}
|
|
157
|
+
if (name !== 'preview' && name !== 'promotion')
|
|
158
|
+
invalid();
|
|
159
|
+
}
|
|
160
|
+
const paths = [];
|
|
161
|
+
const names = new Set();
|
|
162
|
+
for (const category of CATEGORIES) {
|
|
163
|
+
const values = declarations[category];
|
|
164
|
+
if (!Array.isArray(values) || values.length > LOCAL_TEST_GATE_LIMITS.files || (category === 'source' && !values.length))
|
|
165
|
+
invalid();
|
|
166
|
+
for (const path of values) {
|
|
167
|
+
if (typeof path !== 'string' || names.has(path))
|
|
168
|
+
invalid();
|
|
169
|
+
names.add(path);
|
|
170
|
+
paths.push({ category, path, filename: await projectFile(root, path) });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const path of CONFIGURATION) {
|
|
174
|
+
if (!names.has(path)) {
|
|
175
|
+
names.add(path);
|
|
176
|
+
paths.push({ category: 'configuration', path, filename: await projectFile(root, path) });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (paths.length > LOCAL_TEST_GATE_LIMITS.files)
|
|
180
|
+
invalid();
|
|
181
|
+
// Pin the current CLI, installed adapters and Node binary as additional local inputs.
|
|
182
|
+
const tools = new Set([await realpath(process.execPath),
|
|
183
|
+
fileURLToPath(new URL('./local-test-gates.js', import.meta.url)), fileURLToPath(new URL('./workflows.js', import.meta.url)),
|
|
184
|
+
fileURLToPath(new URL('./local-test-command.js', import.meta.url)), fileURLToPath(new URL('./local-test-config.js', import.meta.url)),
|
|
185
|
+
fileURLToPath(new URL('./local-test-results.js', import.meta.url))]);
|
|
186
|
+
const executables = [];
|
|
187
|
+
const addExecutable = async (command, cwd) => {
|
|
188
|
+
const filename = await executable(command, cwd);
|
|
189
|
+
tools.add(filename);
|
|
190
|
+
executables.push({ command, cwd, filename });
|
|
191
|
+
};
|
|
192
|
+
for (const definition of definitions) {
|
|
193
|
+
await addExecutable(definition.command, join(root, definition.cwd));
|
|
194
|
+
if (definition.runner === 'go' || definition.runner === 'rust')
|
|
195
|
+
await addExecutable(definition.runner === 'go' ? 'go' : 'cargo', join(root, definition.cwd));
|
|
196
|
+
if (definition.runner)
|
|
197
|
+
for (const arg of definition.args) {
|
|
198
|
+
const candidate = arg.startsWith('--test-reporter=') ? arg.slice('--test-reporter='.length) : arg;
|
|
199
|
+
if (candidate.startsWith(dirname(fileURLToPath(import.meta.url)) + '/') || candidate === fileURLToPath(new URL('../test-runners/python-unittest.py', import.meta.url)))
|
|
200
|
+
tools.add(await realpath(candidate));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
for (const [index, filename] of [...tools].sort().entries())
|
|
204
|
+
paths.push({ category: 'cli', path: `tool-${index}`, filename });
|
|
205
|
+
paths.sort((a, b) => `${a.category}/${a.path}`.localeCompare(`${b.category}/${b.path}`));
|
|
206
|
+
const inputs = await snapshot({ root, paths, executables }, deadline, signal);
|
|
207
|
+
if (inputs.find(row => row.path === LOCAL_TEST_GATE_CONFIG).sha256 !== source.sha256)
|
|
208
|
+
invalid();
|
|
209
|
+
if (configuration?.some(before => inputs.find(after => after.path === before.path)?.sha256 !== before.sha256))
|
|
210
|
+
invalid();
|
|
211
|
+
const context = hash(JSON.stringify({ definitions, limits }));
|
|
212
|
+
return { root, stage, required: required, paths, executables, inputs, context, digest: hash(JSON.stringify({ context, inputs })) };
|
|
213
|
+
}
|
|
214
|
+
export function blockedLocalTestGate(prepared, checks, reason) {
|
|
215
|
+
return { schema: 'blinkhost.local-test-gate/v1', stage: prepared.stage, status: 'blocked', authority: 'customer_runner_reported',
|
|
216
|
+
scope: 'declared_local_inputs', production_authority: false, input_sha256: prepared.digest, observed_input_sha256: null,
|
|
217
|
+
inputs_unchanged: null, inputs: prepared.inputs, reason, checks: prepared.required.map(id => {
|
|
218
|
+
const check = checks.find(row => row.id === id);
|
|
219
|
+
const passed = check?.kind !== 'build' && check?.status === 'succeeded' && !check.report_error
|
|
220
|
+
&& check.report?.status === 'passed' && check.report.counts.passed > 0 && !check.report.counts.failed
|
|
221
|
+
&& !check.report.counts.skipped && !check.report.counts.unsupported;
|
|
222
|
+
return { id, status: passed ? 'passed' : 'blocked', reason: passed ? null
|
|
223
|
+
: !check || check.status === 'not_run' ? 'required_check_not_run' : check.kind === 'build' ? 'build_is_not_test_evidence'
|
|
224
|
+
: check.status !== 'succeeded' ? 'required_execution_failed' : check.report_error ? 'required_result_invalid'
|
|
225
|
+
: !check.report ? 'required_result_missing' : 'required_tests_not_all_passed' };
|
|
226
|
+
}) };
|
|
227
|
+
}
|
|
228
|
+
export async function finishLocalTestGate(prepared, checks, deadline, signal) {
|
|
229
|
+
const result = blockedLocalTestGate(prepared, checks, 'required_checks_blocked');
|
|
230
|
+
try {
|
|
231
|
+
const inputs = await snapshot(prepared, deadline, signal);
|
|
232
|
+
result.observed_input_sha256 = hash(JSON.stringify({ context: prepared.context, inputs }));
|
|
233
|
+
result.inputs_unchanged = result.observed_input_sha256 === prepared.digest;
|
|
234
|
+
if (!result.inputs_unchanged)
|
|
235
|
+
result.reason = 'declared_inputs_changed';
|
|
236
|
+
else if (result.checks.every(row => row.status === 'passed')) {
|
|
237
|
+
result.status = 'passed';
|
|
238
|
+
result.reason = null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
result.reason = error instanceof CliError && ['project_test_cancelled', 'project_test_timeout'].includes(error.code)
|
|
243
|
+
? error.code : 'declared_inputs_unavailable';
|
|
244
|
+
}
|
|
245
|
+
return result;
|
|
246
|
+
}
|
|
247
|
+
//# sourceMappingURL=local-test-gates.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
interface TestRow {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
status: 'passed' | 'failed' | 'skipped';
|
|
5
|
+
duration_ms: number;
|
|
6
|
+
message?: string;
|
|
7
|
+
}
|
|
8
|
+
interface Context {
|
|
9
|
+
path: string;
|
|
10
|
+
runId: string;
|
|
11
|
+
checkId: string;
|
|
12
|
+
}
|
|
13
|
+
/** Consumes actual go test -json events. Package checks are never invented application tests. */
|
|
14
|
+
export declare class GoTestEvents {
|
|
15
|
+
private readonly ctx;
|
|
16
|
+
readonly tests: TestRow[];
|
|
17
|
+
private packages;
|
|
18
|
+
private startedTests;
|
|
19
|
+
private diagnosticBytes;
|
|
20
|
+
private buildFailed;
|
|
21
|
+
constructor(ctx: Context);
|
|
22
|
+
accept(value: unknown): string | undefined;
|
|
23
|
+
finish(exitCode: number): TestRow[];
|
|
24
|
+
}
|
|
25
|
+
/** Native test execution only. Parent CLI owns timeout, output budget and process-group cleanup. */
|
|
26
|
+
export declare function runGoTests(args: string[]): Promise<number>;
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { spawn, execFileSync } from 'node:child_process';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { open } from 'node:fs/promises';
|
|
4
|
+
import { resolve, dirname } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { LOCAL_TEST_RESULT_LIMITS } from './local-test-results.js';
|
|
7
|
+
import { sanitizeLocalTestOutput } from './local-test-command.js';
|
|
8
|
+
const EVENT_BYTES = 64 * 1024;
|
|
9
|
+
const STREAM_BYTES = 32 * 1024 * 1024;
|
|
10
|
+
const DIAGNOSTIC_BYTES = 4 * 1024 * 1024;
|
|
11
|
+
function fail() { throw new Error('The BlinkHost Go test runner could not qualify this result.'); }
|
|
12
|
+
function record(value) {
|
|
13
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
14
|
+
fail();
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
function string(value) {
|
|
18
|
+
if (typeof value !== 'string' || !value || Buffer.byteLength(value) > EVENT_BYTES)
|
|
19
|
+
fail();
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
function context() {
|
|
23
|
+
const env = process.env;
|
|
24
|
+
if (!env.BLINKHOST_TEST_RESULT_PATH || !env.BLINKHOST_TEST_RUN_ID || !env.BLINKHOST_TEST_CHECK_ID
|
|
25
|
+
|| env.BLINKHOST_TEST_PROFILE !== 'native') {
|
|
26
|
+
throw new Error('Run the Go adapter through a BlinkHost structured test check with profile native.');
|
|
27
|
+
}
|
|
28
|
+
return { path: env.BLINKHOST_TEST_RESULT_PATH, runId: env.BLINKHOST_TEST_RUN_ID, checkId: env.BLINKHOST_TEST_CHECK_ID };
|
|
29
|
+
}
|
|
30
|
+
function safeText(value, maximum, ctx) {
|
|
31
|
+
let screened = sanitizeLocalTestOutput(value);
|
|
32
|
+
for (const secret of [ctx.path, dirname(ctx.path), ctx.runId])
|
|
33
|
+
screened = screened.split(secret).join('[LOCAL TEST CONTEXT]');
|
|
34
|
+
let result = '', bytes = 0;
|
|
35
|
+
for (const character of screened) {
|
|
36
|
+
bytes += Buffer.byteLength(character);
|
|
37
|
+
if (bytes > maximum)
|
|
38
|
+
break;
|
|
39
|
+
result += character;
|
|
40
|
+
}
|
|
41
|
+
return result.trim() || '(unavailable)';
|
|
42
|
+
}
|
|
43
|
+
/** Consumes actual go test -json events. Package checks are never invented application tests. */
|
|
44
|
+
export class GoTestEvents {
|
|
45
|
+
ctx;
|
|
46
|
+
tests = [];
|
|
47
|
+
packages = new Map();
|
|
48
|
+
startedTests = 0;
|
|
49
|
+
diagnosticBytes = 0;
|
|
50
|
+
buildFailed = false;
|
|
51
|
+
constructor(ctx) {
|
|
52
|
+
this.ctx = ctx;
|
|
53
|
+
}
|
|
54
|
+
accept(value) {
|
|
55
|
+
const event = record(value);
|
|
56
|
+
const action = string(event.Action);
|
|
57
|
+
if (action === 'build-output' || action === 'build-fail') {
|
|
58
|
+
string(event.ImportPath);
|
|
59
|
+
if (action === 'build-fail') {
|
|
60
|
+
this.buildFailed = true;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
return string(event.Output);
|
|
64
|
+
}
|
|
65
|
+
const packageName = string(event.Package);
|
|
66
|
+
const testName = event.Test === undefined ? undefined : string(event.Test);
|
|
67
|
+
if (action === 'start') {
|
|
68
|
+
if (testName || this.packages.has(packageName) || this.packages.size >= LOCAL_TEST_RESULT_LIMITS.tests)
|
|
69
|
+
fail();
|
|
70
|
+
this.packages.set(packageName, { finished: false, failed: false, active: new Map() });
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const pkg = this.packages.get(packageName);
|
|
74
|
+
if (!pkg || pkg.finished)
|
|
75
|
+
fail();
|
|
76
|
+
if (action === 'run') {
|
|
77
|
+
if (!testName || pkg.active.has(testName) || ++this.startedTests > LOCAL_TEST_RESULT_LIMITS.tests)
|
|
78
|
+
fail();
|
|
79
|
+
pkg.active.set(testName, { name: packageName + '/' + testName, output: '' });
|
|
80
|
+
}
|
|
81
|
+
else if (action === 'output') {
|
|
82
|
+
const output = string(event.Output);
|
|
83
|
+
const test = testName ? pkg.active.get(testName) : undefined;
|
|
84
|
+
// Go emits framing output after terminal events; it is not another test.
|
|
85
|
+
if (test) {
|
|
86
|
+
this.diagnosticBytes += Buffer.byteLength(output);
|
|
87
|
+
if (this.diagnosticBytes > DIAGNOSTIC_BYTES || Buffer.byteLength(test.output) + Buffer.byteLength(output) > EVENT_BYTES)
|
|
88
|
+
fail();
|
|
89
|
+
test.output += output;
|
|
90
|
+
}
|
|
91
|
+
return output;
|
|
92
|
+
}
|
|
93
|
+
else if (action === 'pause' || action === 'cont') {
|
|
94
|
+
if (!testName || !pkg.active.has(testName))
|
|
95
|
+
fail();
|
|
96
|
+
}
|
|
97
|
+
else if (action === 'pass' || action === 'fail' || action === 'skip') {
|
|
98
|
+
if (!testName) {
|
|
99
|
+
if (pkg.active.size)
|
|
100
|
+
fail();
|
|
101
|
+
pkg.finished = true;
|
|
102
|
+
pkg.failed = action === 'fail';
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const test = pkg.active.get(testName);
|
|
106
|
+
if (!test)
|
|
107
|
+
fail();
|
|
108
|
+
const elapsed = event.Elapsed ?? 0;
|
|
109
|
+
if (typeof elapsed !== 'number' || !Number.isFinite(elapsed) || elapsed < 0 || elapsed > 1_000_000)
|
|
110
|
+
fail();
|
|
111
|
+
const status = action === 'pass' ? 'passed' : action === 'fail' ? 'failed' : 'skipped';
|
|
112
|
+
this.tests.push({ id: `go-${this.tests.length + 1}`, name: safeText(test.name, 1024, this.ctx), status,
|
|
113
|
+
duration_ms: Math.round(elapsed * 1000),
|
|
114
|
+
...(status !== 'passed' && test.output.trim() ? { message: safeText(test.output, 4096, this.ctx) } : {}) });
|
|
115
|
+
pkg.active.delete(testName);
|
|
116
|
+
}
|
|
117
|
+
else
|
|
118
|
+
fail();
|
|
119
|
+
}
|
|
120
|
+
finish(exitCode) {
|
|
121
|
+
if (!this.packages.size || this.startedTests !== this.tests.length
|
|
122
|
+
// A failed package that never reached a test has no test report. Keep
|
|
123
|
+
// successful empty suites distinct from compilation/setup failures.
|
|
124
|
+
|| exitCode !== 0 && this.tests.length === 0
|
|
125
|
+
|| [...this.packages.values()].some(pkg => !pkg.finished || pkg.active.size)
|
|
126
|
+
|| exitCode === 0 && (this.buildFailed || [...this.packages.values()].some(pkg => pkg.failed)
|
|
127
|
+
|| this.tests.some(test => test.status === 'failed')))
|
|
128
|
+
fail();
|
|
129
|
+
return this.tests;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Native test execution only. Parent CLI owns timeout, output budget and process-group cleanup. */
|
|
133
|
+
export async function runGoTests(args) {
|
|
134
|
+
const ctx = context();
|
|
135
|
+
const os = process.platform === 'win32' ? 'windows' : process.platform;
|
|
136
|
+
const arch = process.arch === 'x64' ? 'amd64' : process.arch;
|
|
137
|
+
if (process.env.GOOS && process.env.GOOS !== os || process.env.GOARCH && process.env.GOARCH !== arch)
|
|
138
|
+
fail();
|
|
139
|
+
// These modes cannot provide a complete ordinary test event stream. GOFLAGS
|
|
140
|
+
// is cleared so inherited flags cannot silently change the adapter's mode.
|
|
141
|
+
if (args.some(arg => /^-{1,2}(?:test\.)?(?:c|list|bench|benchtime|fuzz|fuzztime|fuzzminimizetime|json|exec|args)(?:=|$)/.test(arg)))
|
|
142
|
+
fail();
|
|
143
|
+
const env = { ...process.env, GOFLAGS: '' };
|
|
144
|
+
const version = execFileSync('go', ['version'], { env, encoding: 'utf8', timeout: 10_000, maxBuffer: 4096 }).trim();
|
|
145
|
+
if (!/^go version go[0-9]+\.[0-9]+(?:\.[0-9]+)?(?:[a-z]+[0-9]+)? \S+\/\S+$/.test(version))
|
|
146
|
+
fail();
|
|
147
|
+
const events = new GoTestEvents(ctx);
|
|
148
|
+
const child = spawn('go', ['test', '-json', ...args], { env, shell: false, stdio: ['ignore', 'pipe', 'inherit'] });
|
|
149
|
+
const closed = new Promise((resolveClose, reject) => {
|
|
150
|
+
child.once('error', reject);
|
|
151
|
+
child.once('close', (code, signal) => resolveClose({ code, signal }));
|
|
152
|
+
});
|
|
153
|
+
// Attach a rejection handler immediately, even while reading the stream.
|
|
154
|
+
void closed.catch(() => { });
|
|
155
|
+
let pending = Buffer.alloc(0), observed = 0;
|
|
156
|
+
try {
|
|
157
|
+
for await (const chunk of child.stdout) {
|
|
158
|
+
observed += chunk.length;
|
|
159
|
+
if (observed > STREAM_BYTES)
|
|
160
|
+
fail();
|
|
161
|
+
pending = Buffer.concat([pending, chunk]);
|
|
162
|
+
let end;
|
|
163
|
+
while ((end = pending.indexOf(10)) !== -1) {
|
|
164
|
+
if (end > EVENT_BYTES)
|
|
165
|
+
fail();
|
|
166
|
+
const line = new TextDecoder('utf8', { fatal: true }).decode(pending.subarray(0, end));
|
|
167
|
+
pending = pending.subarray(end + 1);
|
|
168
|
+
const output = events.accept(JSON.parse(line));
|
|
169
|
+
if (output && !process.stdout.write(output))
|
|
170
|
+
await once(process.stdout, 'drain');
|
|
171
|
+
}
|
|
172
|
+
if (pending.length > EVENT_BYTES)
|
|
173
|
+
fail();
|
|
174
|
+
}
|
|
175
|
+
if (pending.length)
|
|
176
|
+
fail();
|
|
177
|
+
const result = await closed;
|
|
178
|
+
if (result.signal || result.code === null)
|
|
179
|
+
fail();
|
|
180
|
+
const tests = events.finish(result.code);
|
|
181
|
+
const encoded = JSON.stringify({ schema: 'blinkhost.local-test-results/v1', run_id: ctx.runId,
|
|
182
|
+
check_id: ctx.checkId, profile: 'native', runner: `go:test/${version.split(' ')[2]}`, tests,
|
|
183
|
+
coverage: { status: 'not_collected' } });
|
|
184
|
+
if (Buffer.byteLength(encoded) > LOCAL_TEST_RESULT_LIMITS.bytes)
|
|
185
|
+
fail();
|
|
186
|
+
const file = await open(ctx.path, 'wx', 0o600);
|
|
187
|
+
try {
|
|
188
|
+
await file.writeFile(encoded);
|
|
189
|
+
await file.sync();
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
await file.close();
|
|
193
|
+
}
|
|
194
|
+
return result.code;
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
// The parent command's owned group supplies escalation and descendant cleanup.
|
|
198
|
+
child.kill('SIGTERM');
|
|
199
|
+
child.stdout.destroy();
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
204
|
+
runGoTests(process.argv.slice(2)).then(code => { process.exitCode = code; }, () => {
|
|
205
|
+
process.stderr.write('The BlinkHost Go test runner failed; no passing result was certified.\n');
|
|
206
|
+
process.exitCode = 2;
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
//# sourceMappingURL=local-test-go-runner.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CliError, EXIT } from './errors.js';
|
|
2
|
+
/** Used by both local configuration and the isolated Node adapter; no shell parsing. */
|
|
3
|
+
export function validateNodeTestArguments(args) {
|
|
4
|
+
if (!Array.isArray(args) || args.length > 64
|
|
5
|
+
|| args.some(arg => typeof arg !== 'string' || arg.length > 4096 || /[\u0000-\u001f\u007f]/.test(arg))
|
|
6
|
+
|| args.reduce((sum, arg) => sum + Buffer.byteLength(arg), 0) > 32_768) {
|
|
7
|
+
throw new CliError('Node runner args must be bounded literal strings.', EXIT.validation, 'invalid_local_test_config');
|
|
8
|
+
}
|
|
9
|
+
if (args.some(arg => /^--(?:test-reporter(?:-destination)?|test-isolation|test-watch|watch|watch-path|test-only|eval|print|input-type)(?:=|$)/.test(arg)
|
|
10
|
+
|| arg === '-e' || arg === '-p' || arg === '--print')) {
|
|
11
|
+
throw new CliError('Node runner args cannot change the result protocol or execution mode.', EXIT.validation, 'invalid_local_test_config');
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=local-test-node-arguments.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
interface Event {
|
|
2
|
+
type: string;
|
|
3
|
+
data: Record<string, unknown>;
|
|
4
|
+
}
|
|
5
|
+
/** node:test event adapter. Node execution is native; it never claims browser or WASM coverage. */
|
|
6
|
+
export default function blinkhostNodeReporter(source: AsyncIterable<Event>): AsyncGenerator<string>;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { writeFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { LOCAL_TEST_RESULT_LIMITS } from './local-test-results.js';
|
|
4
|
+
import { sanitizeLocalTestOutput } from './local-test-command.js';
|
|
5
|
+
function fail() { throw new Error('The BlinkHost Node test reporter could not qualify this runner result.'); }
|
|
6
|
+
function row(value) {
|
|
7
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
8
|
+
fail();
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
function count(value) {
|
|
12
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000)
|
|
13
|
+
fail();
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function safeText(value, maximum) {
|
|
17
|
+
if (typeof value !== 'string')
|
|
18
|
+
fail();
|
|
19
|
+
const screened = sanitizeLocalTestOutput(value);
|
|
20
|
+
// Screen whole strings before truncation, so a cut credential cannot bypass screening.
|
|
21
|
+
let result = '';
|
|
22
|
+
let bytes = 0;
|
|
23
|
+
for (const character of screened) {
|
|
24
|
+
bytes += Buffer.byteLength(character);
|
|
25
|
+
if (bytes > maximum)
|
|
26
|
+
break;
|
|
27
|
+
result += character;
|
|
28
|
+
}
|
|
29
|
+
return result || '(unavailable)';
|
|
30
|
+
}
|
|
31
|
+
/** node:test event adapter. Node execution is native; it never claims browser or WASM coverage. */
|
|
32
|
+
export default async function* blinkhostNodeReporter(source) {
|
|
33
|
+
const env = process.env;
|
|
34
|
+
if (!env.BLINKHOST_TEST_RESULT_PATH || !env.BLINKHOST_TEST_RUN_ID || !env.BLINKHOST_TEST_CHECK_ID
|
|
35
|
+
|| env.BLINKHOST_TEST_PROFILE !== 'native') {
|
|
36
|
+
throw new Error('Run this reporter through a BlinkHost structured test check with profile native.');
|
|
37
|
+
}
|
|
38
|
+
const terminal = [];
|
|
39
|
+
const fileWrappers = { passed: 0, failed: 0, skipped: 0 };
|
|
40
|
+
const fileSummaries = new Map();
|
|
41
|
+
let order = 0;
|
|
42
|
+
let summary;
|
|
43
|
+
let coverage = { status: 'not_collected' };
|
|
44
|
+
for await (const event of source) {
|
|
45
|
+
order++;
|
|
46
|
+
const data = event.data;
|
|
47
|
+
if (event.type === 'test:stdout' || event.type === 'test:stderr') {
|
|
48
|
+
if (typeof data.message !== 'string')
|
|
49
|
+
fail();
|
|
50
|
+
// Forward customer output intact to the parent CLI. Its shared byte
|
|
51
|
+
// budget must see every byte before it screens captured diagnostics;
|
|
52
|
+
// dropping or truncating these events would hide output-limit breaches.
|
|
53
|
+
yield data.message;
|
|
54
|
+
}
|
|
55
|
+
else if (event.type === 'test:pass' || event.type === 'test:fail') {
|
|
56
|
+
const details = row(data.details);
|
|
57
|
+
if (details.type === 'suite')
|
|
58
|
+
continue;
|
|
59
|
+
if (terminal.length >= LOCAL_TEST_RESULT_LIMITS.tests)
|
|
60
|
+
fail();
|
|
61
|
+
if (typeof details.duration_ms !== 'number' || !Number.isFinite(details.duration_ms)
|
|
62
|
+
|| details.duration_ms < 0 || details.duration_ms > 1_000_000_000)
|
|
63
|
+
fail();
|
|
64
|
+
const skipped = data.skip !== undefined && data.skip !== false || data.todo !== undefined && data.todo !== false;
|
|
65
|
+
const status = skipped ? 'skipped' : event.type === 'test:pass' ? 'passed' : 'failed';
|
|
66
|
+
const error = details.error && typeof details.error === 'object' ? details.error : undefined;
|
|
67
|
+
terminal.push({ order, file: typeof data.file === 'string' ? data.file : undefined,
|
|
68
|
+
// This identifies a candidate only: an application may itself use its
|
|
69
|
+
// filename as a test name, including at line/column 1.
|
|
70
|
+
fileCandidate: data.nesting === 0 && data.line === 1 && data.column === 1
|
|
71
|
+
&& typeof data.file === 'string' && typeof data.name === 'string' && resolve(data.name) === data.file,
|
|
72
|
+
test: { id: `node-${terminal.length + 1}`, name: safeText(data.name, 1024), status,
|
|
73
|
+
duration_ms: Math.round(details.duration_ms),
|
|
74
|
+
...(error && typeof error.message === 'string' ? { message: safeText(error.message, 4096) } : {}),
|
|
75
|
+
...(error && typeof error.stack === 'string' ? { stack: safeText(error.stack, 16_384) } : {}) } });
|
|
76
|
+
}
|
|
77
|
+
else if (event.type === 'test:summary') {
|
|
78
|
+
if (data.file === undefined) {
|
|
79
|
+
if (summary)
|
|
80
|
+
fail();
|
|
81
|
+
summary = row(data.counts);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
if (typeof data.file !== 'string' || fileSummaries.has(data.file)
|
|
85
|
+
|| fileSummaries.size >= LOCAL_TEST_RESULT_LIMITS.tests)
|
|
86
|
+
fail();
|
|
87
|
+
fileSummaries.set(data.file, { counts: row(data.counts), order });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
else if (event.type === 'test:coverage') {
|
|
91
|
+
const totals = row(row(data.summary).totals);
|
|
92
|
+
const metric = (covered, total) => {
|
|
93
|
+
const result = { covered: count(totals[covered]), total: count(totals[total]) };
|
|
94
|
+
if (result.covered > result.total)
|
|
95
|
+
fail();
|
|
96
|
+
return result;
|
|
97
|
+
};
|
|
98
|
+
coverage = { status: 'collected', metrics: {
|
|
99
|
+
lines: metric('coveredLineCount', 'totalLineCount'),
|
|
100
|
+
branches: metric('coveredBranchCount', 'totalBranchCount'),
|
|
101
|
+
functions: metric('coveredFunctionCount', 'totalFunctionCount'),
|
|
102
|
+
} };
|
|
103
|
+
}
|
|
104
|
+
else if (event.type === 'test:diagnostic' && typeof data.message === 'string') {
|
|
105
|
+
yield safeText(data.message, 4096) + '\n';
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!summary)
|
|
109
|
+
fail();
|
|
110
|
+
// Node's root count also includes synthetic file checks; child summaries
|
|
111
|
+
// count declared application tests. Exclude candidates only when both
|
|
112
|
+
// aggregates corroborate their number. Ambiguous/unsupported streams fail.
|
|
113
|
+
const childTotals = { tests: 0, passed: 0, failed: 0, skipped: 0 };
|
|
114
|
+
for (const { counts } of fileSummaries.values()) {
|
|
115
|
+
childTotals.tests += count(counts.tests);
|
|
116
|
+
childTotals.passed += count(counts.passed);
|
|
117
|
+
childTotals.failed += count(counts.failed) + count(counts.cancelled);
|
|
118
|
+
childTotals.skipped += count(counts.skipped) + count(counts.todo);
|
|
119
|
+
}
|
|
120
|
+
const wrapperCount = count(summary.tests) - childTotals.tests;
|
|
121
|
+
if (wrapperCount < 0)
|
|
122
|
+
fail();
|
|
123
|
+
const candidates = terminal.filter(item => item.fileCandidate
|
|
124
|
+
&& (!fileSummaries.has(item.file) || item.order > fileSummaries.get(item.file).order));
|
|
125
|
+
if (wrapperCount > 0 && candidates.length !== wrapperCount)
|
|
126
|
+
fail();
|
|
127
|
+
const excluded = new Set(wrapperCount > 0 ? candidates : []);
|
|
128
|
+
const tests = [];
|
|
129
|
+
for (const item of terminal) {
|
|
130
|
+
if (excluded.has(item)) {
|
|
131
|
+
fileWrappers[item.test.status]++;
|
|
132
|
+
yield `${item.test.status}: test-file execution (${item.test.status === 'passed' ? 'no declared tests' : 'no test result'})\n`;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
tests.push({ ...item.test, id: `node-${tests.length + 1}` });
|
|
136
|
+
yield `${item.test.status}: ${item.test.name}\n`;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (tests.length !== childTotals.tests
|
|
140
|
+
|| tests.filter(test => test.status === 'passed').length !== childTotals.passed
|
|
141
|
+
|| tests.filter(test => test.status === 'failed').length !== childTotals.failed
|
|
142
|
+
|| tests.filter(test => test.status === 'skipped').length !== childTotals.skipped)
|
|
143
|
+
fail();
|
|
144
|
+
// Reconcile actual terminal events against Node's final aggregate. Missing events fail closed.
|
|
145
|
+
if (count(summary.tests) !== tests.length + fileWrappers.passed + fileWrappers.failed + fileWrappers.skipped
|
|
146
|
+
|| count(summary.passed) !== tests.filter(test => test.status === 'passed').length + fileWrappers.passed
|
|
147
|
+
|| count(summary.failed) + count(summary.cancelled) !== tests.filter(test => test.status === 'failed').length + fileWrappers.failed
|
|
148
|
+
|| count(summary.skipped) + count(summary.todo) !== tests.filter(test => test.status === 'skipped').length + fileWrappers.skipped)
|
|
149
|
+
fail();
|
|
150
|
+
if (!tests.some(test => test.status === 'passed' || test.status === 'failed') && coverage.status === 'collected') {
|
|
151
|
+
coverage = { status: 'unavailable' };
|
|
152
|
+
}
|
|
153
|
+
const encoded = JSON.stringify({ schema: 'blinkhost.local-test-results/v1', run_id: env.BLINKHOST_TEST_RUN_ID,
|
|
154
|
+
check_id: env.BLINKHOST_TEST_CHECK_ID, profile: 'native', runner: `node:test/${process.version}`, tests, coverage });
|
|
155
|
+
if (Buffer.byteLength(encoded) > LOCAL_TEST_RESULT_LIMITS.bytes)
|
|
156
|
+
fail();
|
|
157
|
+
await writeFile(env.BLINKHOST_TEST_RESULT_PATH, encoded, { flag: 'wx', mode: 0o600 });
|
|
158
|
+
}
|
|
159
|
+
//# sourceMappingURL=local-test-node-reporter.js.map
|