@testsprite/testsprite-cli 0.1.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/LICENSE +201 -0
- package/README.md +190 -0
- package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
- package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
- package/dist/commands/agent.d.ts +51 -0
- package/dist/commands/agent.js +552 -0
- package/dist/commands/auth.d.ts +38 -0
- package/dist/commands/auth.js +247 -0
- package/dist/commands/init.d.ts +63 -0
- package/dist/commands/init.js +350 -0
- package/dist/commands/project.d.ts +72 -0
- package/dist/commands/project.js +400 -0
- package/dist/commands/test.d.ts +1245 -0
- package/dist/commands/test.js +6214 -0
- package/dist/commands/usage.d.ts +63 -0
- package/dist/commands/usage.js +156 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +146 -0
- package/dist/lib/agent-targets.d.ts +50 -0
- package/dist/lib/agent-targets.js +99 -0
- package/dist/lib/bundle.d.ts +178 -0
- package/dist/lib/bundle.js +600 -0
- package/dist/lib/client-factory.d.ts +72 -0
- package/dist/lib/client-factory.js +120 -0
- package/dist/lib/config.d.ts +24 -0
- package/dist/lib/config.js +30 -0
- package/dist/lib/credentials.d.ts +17 -0
- package/dist/lib/credentials.js +122 -0
- package/dist/lib/dry-run/fetch.d.ts +18 -0
- package/dist/lib/dry-run/fetch.js +52 -0
- package/dist/lib/dry-run/samples.d.ts +50 -0
- package/dist/lib/dry-run/samples.js +676 -0
- package/dist/lib/errors.d.ts +118 -0
- package/dist/lib/errors.js +388 -0
- package/dist/lib/facade.d.ts +48 -0
- package/dist/lib/facade.js +104 -0
- package/dist/lib/failing-fe-resolver.d.ts +60 -0
- package/dist/lib/failing-fe-resolver.js +103 -0
- package/dist/lib/http.d.ts +255 -0
- package/dist/lib/http.js +608 -0
- package/dist/lib/output.d.ts +55 -0
- package/dist/lib/output.js +70 -0
- package/dist/lib/pagination.d.ts +56 -0
- package/dist/lib/pagination.js +81 -0
- package/dist/lib/poll.d.ts +88 -0
- package/dist/lib/poll.js +221 -0
- package/dist/lib/prompt.d.ts +8 -0
- package/dist/lib/prompt.js +97 -0
- package/dist/lib/rate-throttle.d.ts +49 -0
- package/dist/lib/rate-throttle.js +75 -0
- package/dist/lib/render-error.d.ts +15 -0
- package/dist/lib/render-error.js +44 -0
- package/dist/lib/runs.types.d.ts +344 -0
- package/dist/lib/runs.types.js +25 -0
- package/dist/lib/target-url.d.ts +25 -0
- package/dist/lib/target-url.js +127 -0
- package/dist/lib/ticker.d.ts +37 -0
- package/dist/lib/ticker.js +63 -0
- package/dist/lib/validate.d.ts +82 -0
- package/dist/lib/validate.js +165 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +2 -0
- package/package.json +65 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared `HttpClient` factory used by every M2 command. Two reasons for
|
|
3
|
+
* the extraction:
|
|
4
|
+
*
|
|
5
|
+
* 1. Three command files (`auth`, `project`, `test`) had byte-equivalent
|
|
6
|
+
* `makeClient` helpers — drift between them would silently change
|
|
7
|
+
* behavior depending on which command you called.
|
|
8
|
+
* 2. P6's `--dry-run` branch needs to bypass `loadConfig` (so it works
|
|
9
|
+
* with no `~/.testsprite/credentials`) and substitute a canned-fetch
|
|
10
|
+
* impl. Doing that once here is safer than three near-copies.
|
|
11
|
+
*
|
|
12
|
+
* The factory is intentionally narrow: it only takes the HTTP-relevant
|
|
13
|
+
* deps. Per-command deps (auth's `prompt`, test's `rawStdout`) stay
|
|
14
|
+
* with the command.
|
|
15
|
+
*/
|
|
16
|
+
import { loadConfig } from './config.js';
|
|
17
|
+
import { defaultCredentialsPath } from './credentials.js';
|
|
18
|
+
import { ApiError } from './errors.js';
|
|
19
|
+
import { facadeBaseUrl } from './facade.js';
|
|
20
|
+
import { HttpClient, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, REQUEST_TIMEOUT_MIN_MS, } from './http.js';
|
|
21
|
+
import { createDryRunFetch } from './dry-run/fetch.js';
|
|
22
|
+
/**
|
|
23
|
+
* The fake API key used in dry-run. Never sent — the dry-run fetch
|
|
24
|
+
* impl ignores headers and returns a canned sample. Documented in the
|
|
25
|
+
* runbook so secret-scanners don't flag it as a leak.
|
|
26
|
+
*/
|
|
27
|
+
export const DRY_RUN_API_KEY = 'sk-user-DRY-RUN';
|
|
28
|
+
const DRY_RUN_DEFAULT_ENDPOINT = 'https://api.testsprite.com';
|
|
29
|
+
/** Stable banner text. Snapshot tests assert on this string. */
|
|
30
|
+
export const DRY_RUN_BANNER = '[dry-run] sample response — not from the server';
|
|
31
|
+
/**
|
|
32
|
+
* Emit the dry-run banner to stderr. Idempotent per process — the
|
|
33
|
+
* banner prints only on the first call so scripts that run several
|
|
34
|
+
* commands sequentially under one shell don't drown in repeats. The
|
|
35
|
+
* gate is reset by {@link resetDryRunBannerForTesting} for unit tests.
|
|
36
|
+
*/
|
|
37
|
+
let bannerEmitted = false;
|
|
38
|
+
export function emitDryRunBanner(stderr) {
|
|
39
|
+
if (bannerEmitted)
|
|
40
|
+
return;
|
|
41
|
+
bannerEmitted = true;
|
|
42
|
+
stderr(DRY_RUN_BANNER);
|
|
43
|
+
}
|
|
44
|
+
export function resetDryRunBannerForTesting() {
|
|
45
|
+
bannerEmitted = false;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Resolve per-request timeout in milliseconds.
|
|
49
|
+
*
|
|
50
|
+
* Precedence: `--request-timeout` flag (already converted to ms by the caller)
|
|
51
|
+
* > `TESTSPRITE_REQUEST_TIMEOUT_MS` env var > default (120s).
|
|
52
|
+
*
|
|
53
|
+
* The flag is supplied in seconds (consistent with `--timeout`); the caller
|
|
54
|
+
* multiplies by 1000 before storing in `opts.requestTimeoutMs`. The env var
|
|
55
|
+
* is in milliseconds to give scripts sub-second granularity and match the
|
|
56
|
+
* typical convention for `*_MS` env vars.
|
|
57
|
+
*
|
|
58
|
+
* Values are clamped to [REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS];
|
|
59
|
+
* values below the minimum are raised to 1s, values above the maximum are
|
|
60
|
+
* lowered to 10m — both silently (no exit 5), since this is a tuning knob,
|
|
61
|
+
* not a safety-critical gate.
|
|
62
|
+
*/
|
|
63
|
+
export function resolveRequestTimeoutMs(opts, env) {
|
|
64
|
+
// Flag (already in ms) takes precedence.
|
|
65
|
+
if (opts.requestTimeoutMs !== undefined) {
|
|
66
|
+
return clampRequestTimeout(opts.requestTimeoutMs);
|
|
67
|
+
}
|
|
68
|
+
// Env var (milliseconds).
|
|
69
|
+
const envRaw = env.TESTSPRITE_REQUEST_TIMEOUT_MS;
|
|
70
|
+
if (envRaw !== undefined) {
|
|
71
|
+
const parsed = Number(envRaw);
|
|
72
|
+
if (Number.isFinite(parsed) && parsed > 0) {
|
|
73
|
+
return clampRequestTimeout(parsed);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return REQUEST_TIMEOUT_DEFAULT_MS;
|
|
77
|
+
}
|
|
78
|
+
function clampRequestTimeout(ms) {
|
|
79
|
+
return Math.min(Math.max(Math.round(ms), REQUEST_TIMEOUT_MIN_MS), REQUEST_TIMEOUT_MAX_MS);
|
|
80
|
+
}
|
|
81
|
+
export function makeHttpClient(opts, deps = {}) {
|
|
82
|
+
const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
83
|
+
const env = deps.env ?? process.env;
|
|
84
|
+
const requestTimeoutMs = resolveRequestTimeoutMs(opts, env);
|
|
85
|
+
if (opts.dryRun) {
|
|
86
|
+
emitDryRunBanner(stderr);
|
|
87
|
+
return new HttpClient({
|
|
88
|
+
baseUrl: facadeBaseUrl(opts.endpointUrl ?? DRY_RUN_DEFAULT_ENDPOINT),
|
|
89
|
+
apiKey: DRY_RUN_API_KEY,
|
|
90
|
+
fetchImpl: deps.fetchImpl ?? createDryRunFetch(),
|
|
91
|
+
onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
|
|
92
|
+
onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
|
|
93
|
+
requestTimeoutMs,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
|
|
97
|
+
const config = loadConfig({
|
|
98
|
+
profile: opts.profile,
|
|
99
|
+
endpointUrl: opts.endpointUrl,
|
|
100
|
+
env,
|
|
101
|
+
credentialsPath,
|
|
102
|
+
});
|
|
103
|
+
if (!config.apiKey)
|
|
104
|
+
throw ApiError.authRequired();
|
|
105
|
+
return new HttpClient({
|
|
106
|
+
baseUrl: facadeBaseUrl(config.apiUrl),
|
|
107
|
+
apiKey: config.apiKey,
|
|
108
|
+
fetchImpl: deps.fetchImpl,
|
|
109
|
+
onDebug: opts.debug ? (event) => stderr(formatDebug(event)) : undefined,
|
|
110
|
+
onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
|
|
111
|
+
requestTimeoutMs,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function formatDebug(event) {
|
|
115
|
+
return `[debug ${new Date().toISOString()}] ${JSON.stringify(event)}`;
|
|
116
|
+
}
|
|
117
|
+
function formatDryRunDebug(event) {
|
|
118
|
+
return `[debug ${new Date().toISOString()}] ${JSON.stringify({ ...event, mode: 'dry-run' })}`;
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=client-factory.js.map
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface Config {
|
|
2
|
+
apiUrl: string;
|
|
3
|
+
apiKey?: string;
|
|
4
|
+
profile: string;
|
|
5
|
+
}
|
|
6
|
+
export interface LoadConfigOptions {
|
|
7
|
+
profile?: string;
|
|
8
|
+
endpointUrl?: string;
|
|
9
|
+
env?: NodeJS.ProcessEnv;
|
|
10
|
+
credentialsPath?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function defaultConfigPath(): string;
|
|
13
|
+
/**
|
|
14
|
+
* Resolves the active profile name and its (apiUrl, apiKey) pair.
|
|
15
|
+
*
|
|
16
|
+
* Resolution order, highest precedence first:
|
|
17
|
+
* profile name: options.profile > env.TESTSPRITE_PROFILE > "default"
|
|
18
|
+
* apiKey: env.TESTSPRITE_API_KEY > credentials file profile entry
|
|
19
|
+
* apiUrl: options.endpointUrl > env.TESTSPRITE_API_URL > credentials file > built-in default
|
|
20
|
+
*
|
|
21
|
+
* Env wins over the credentials file so CI / scripted callers can run without touching
|
|
22
|
+
* the user's ~/.testsprite/credentials.
|
|
23
|
+
*/
|
|
24
|
+
export declare function loadConfig(options?: LoadConfigOptions): Config;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { DEFAULT_PROFILE, defaultCredentialsPath, readProfile } from './credentials.js';
|
|
4
|
+
const DEFAULT_API_URL = 'https://api.testsprite.com';
|
|
5
|
+
export function defaultConfigPath() {
|
|
6
|
+
return join(homedir(), '.testsprite', 'config');
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Resolves the active profile name and its (apiUrl, apiKey) pair.
|
|
10
|
+
*
|
|
11
|
+
* Resolution order, highest precedence first:
|
|
12
|
+
* profile name: options.profile > env.TESTSPRITE_PROFILE > "default"
|
|
13
|
+
* apiKey: env.TESTSPRITE_API_KEY > credentials file profile entry
|
|
14
|
+
* apiUrl: options.endpointUrl > env.TESTSPRITE_API_URL > credentials file > built-in default
|
|
15
|
+
*
|
|
16
|
+
* Env wins over the credentials file so CI / scripted callers can run without touching
|
|
17
|
+
* the user's ~/.testsprite/credentials.
|
|
18
|
+
*/
|
|
19
|
+
export function loadConfig(options = {}) {
|
|
20
|
+
const env = options.env ?? process.env;
|
|
21
|
+
const profile = options.profile ?? env.TESTSPRITE_PROFILE ?? DEFAULT_PROFILE;
|
|
22
|
+
const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
|
|
23
|
+
const fileEntry = readProfile(profile, { path: credentialsPath });
|
|
24
|
+
return {
|
|
25
|
+
apiUrl: options.endpointUrl ?? env.TESTSPRITE_API_URL ?? fileEntry?.apiUrl ?? DEFAULT_API_URL,
|
|
26
|
+
apiKey: env.TESTSPRITE_API_KEY ?? fileEntry?.apiKey,
|
|
27
|
+
profile,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const DEFAULT_PROFILE = "default";
|
|
2
|
+
export declare function defaultCredentialsPath(): string;
|
|
3
|
+
export interface ProfileEntry {
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
apiUrl?: string;
|
|
6
|
+
}
|
|
7
|
+
export type CredentialsFile = Record<string, ProfileEntry>;
|
|
8
|
+
export interface CredentialsOptions {
|
|
9
|
+
path?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function parseCredentials(content: string): CredentialsFile;
|
|
12
|
+
export declare function serializeCredentials(file: CredentialsFile): string;
|
|
13
|
+
export declare function readCredentialsFile(options?: CredentialsOptions): CredentialsFile;
|
|
14
|
+
export declare function readProfile(profile: string, options?: CredentialsOptions): ProfileEntry | undefined;
|
|
15
|
+
export declare function writeProfile(profile: string, entry: ProfileEntry, options?: CredentialsOptions): void;
|
|
16
|
+
export declare function deleteProfile(profile: string, options?: CredentialsOptions): boolean;
|
|
17
|
+
export declare function ensureRestrictiveMode(path: string): void;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
export const DEFAULT_PROFILE = 'default';
|
|
5
|
+
export function defaultCredentialsPath() {
|
|
6
|
+
return join(homedir(), '.testsprite', 'credentials');
|
|
7
|
+
}
|
|
8
|
+
const FILE_KEY_TO_FIELD = {
|
|
9
|
+
api_key: 'apiKey',
|
|
10
|
+
api_url: 'apiUrl',
|
|
11
|
+
};
|
|
12
|
+
const FIELD_TO_FILE_KEY = {
|
|
13
|
+
apiKey: 'api_key',
|
|
14
|
+
apiUrl: 'api_url',
|
|
15
|
+
};
|
|
16
|
+
export function parseCredentials(content) {
|
|
17
|
+
const result = {};
|
|
18
|
+
let currentEntry = null;
|
|
19
|
+
for (const rawLine of content.split('\n')) {
|
|
20
|
+
const line = rawLine.trim();
|
|
21
|
+
if (line === '' || line.startsWith('#') || line.startsWith(';'))
|
|
22
|
+
continue;
|
|
23
|
+
const sectionMatch = /^\[([^\]]+)\]$/.exec(line);
|
|
24
|
+
if (sectionMatch) {
|
|
25
|
+
const sectionName = sectionMatch[1].trim();
|
|
26
|
+
const existing = result[sectionName];
|
|
27
|
+
if (existing) {
|
|
28
|
+
currentEntry = existing;
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
const newEntry = {};
|
|
32
|
+
result[sectionName] = newEntry;
|
|
33
|
+
currentEntry = newEntry;
|
|
34
|
+
}
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (currentEntry === null)
|
|
38
|
+
continue;
|
|
39
|
+
const eqIndex = line.indexOf('=');
|
|
40
|
+
if (eqIndex < 0)
|
|
41
|
+
continue;
|
|
42
|
+
const rawKey = line.slice(0, eqIndex).trim();
|
|
43
|
+
const rawValue = line.slice(eqIndex + 1).trim();
|
|
44
|
+
const field = FILE_KEY_TO_FIELD[rawKey];
|
|
45
|
+
if (field)
|
|
46
|
+
currentEntry[field] = rawValue;
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
export function serializeCredentials(file) {
|
|
51
|
+
const orderedSections = Object.keys(file).sort((a, b) => {
|
|
52
|
+
if (a === DEFAULT_PROFILE)
|
|
53
|
+
return -1;
|
|
54
|
+
if (b === DEFAULT_PROFILE)
|
|
55
|
+
return 1;
|
|
56
|
+
return a.localeCompare(b);
|
|
57
|
+
});
|
|
58
|
+
const lines = [];
|
|
59
|
+
for (const section of orderedSections) {
|
|
60
|
+
const entry = file[section];
|
|
61
|
+
if (!entry)
|
|
62
|
+
continue;
|
|
63
|
+
lines.push(`[${section}]`);
|
|
64
|
+
const fields = Object.keys(entry).sort();
|
|
65
|
+
for (const field of fields) {
|
|
66
|
+
const value = entry[field];
|
|
67
|
+
if (value === undefined || value === '')
|
|
68
|
+
continue;
|
|
69
|
+
lines.push(`${FIELD_TO_FILE_KEY[field]} = ${value}`);
|
|
70
|
+
}
|
|
71
|
+
lines.push('');
|
|
72
|
+
}
|
|
73
|
+
return lines.join('\n').trimEnd() + '\n';
|
|
74
|
+
}
|
|
75
|
+
export function readCredentialsFile(options = {}) {
|
|
76
|
+
const path = resolvePath(options);
|
|
77
|
+
if (!existsSync(path))
|
|
78
|
+
return {};
|
|
79
|
+
return parseCredentials(readFileSync(path, 'utf-8'));
|
|
80
|
+
}
|
|
81
|
+
export function readProfile(profile, options = {}) {
|
|
82
|
+
const file = readCredentialsFile(options);
|
|
83
|
+
return file[profile];
|
|
84
|
+
}
|
|
85
|
+
export function writeProfile(profile, entry, options = {}) {
|
|
86
|
+
const path = resolvePath(options);
|
|
87
|
+
const file = readCredentialsFile(options);
|
|
88
|
+
file[profile] = { ...file[profile], ...entry };
|
|
89
|
+
writeCredentialsAtomic(path, file);
|
|
90
|
+
}
|
|
91
|
+
export function deleteProfile(profile, options = {}) {
|
|
92
|
+
const path = resolvePath(options);
|
|
93
|
+
const file = readCredentialsFile(options);
|
|
94
|
+
if (!(profile in file))
|
|
95
|
+
return false;
|
|
96
|
+
delete file[profile];
|
|
97
|
+
if (Object.keys(file).length === 0) {
|
|
98
|
+
writeCredentialsAtomic(path, {});
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
writeCredentialsAtomic(path, file);
|
|
102
|
+
}
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
export function ensureRestrictiveMode(path) {
|
|
106
|
+
if (!existsSync(path))
|
|
107
|
+
return;
|
|
108
|
+
const overpermissive = (statSync(path).mode & 0o077) !== 0;
|
|
109
|
+
if (overpermissive)
|
|
110
|
+
chmodSync(path, 0o600);
|
|
111
|
+
}
|
|
112
|
+
function resolvePath(options) {
|
|
113
|
+
return options.path ?? defaultCredentialsPath();
|
|
114
|
+
}
|
|
115
|
+
function writeCredentialsAtomic(path, file) {
|
|
116
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
117
|
+
const tmp = `${path}.tmp.${process.pid}`;
|
|
118
|
+
writeFileSync(tmp, serializeCredentials(file), { mode: 0o600, encoding: 'utf8' });
|
|
119
|
+
renameSync(tmp, path);
|
|
120
|
+
ensureRestrictiveMode(path);
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=credentials.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dry-run fetch implementation. Drop-in `FetchImpl` that the
|
|
3
|
+
* `client-factory` swaps in when `--dry-run` is set; the existing
|
|
4
|
+
* `HttpClient` keeps its single retry / debug / error path and never
|
|
5
|
+
* has to know dry-run exists.
|
|
6
|
+
*
|
|
7
|
+
* Behavior:
|
|
8
|
+
* - Looks up a canned sample by (method, path). Path lookup ignores
|
|
9
|
+
* the host and query string (auto-pagination's `cursor` query is a
|
|
10
|
+
* no-op in M2 dry-run; see {@link findSample}).
|
|
11
|
+
* - Returns 200 with the sample body and a stable `x-request-id` so
|
|
12
|
+
* the caller's debug output is deterministic.
|
|
13
|
+
* - Missing sample → 500 INTERNAL envelope. Loud-and-broken beats a
|
|
14
|
+
* silent dry-run that returns empty data; the test suite asserts
|
|
15
|
+
* every M2 endpoint resolves.
|
|
16
|
+
*/
|
|
17
|
+
import type { FetchImpl } from '../http.js';
|
|
18
|
+
export declare function createDryRunFetch(): FetchImpl;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { findSample, SAMPLE_DRY_RUN_REQUEST_ID } from './samples.js';
|
|
2
|
+
const JSON_HEADERS = {
|
|
3
|
+
'content-type': 'application/json',
|
|
4
|
+
'x-request-id': SAMPLE_DRY_RUN_REQUEST_ID,
|
|
5
|
+
};
|
|
6
|
+
export function createDryRunFetch() {
|
|
7
|
+
return async (input, init) => {
|
|
8
|
+
const url = resolveUrl(input);
|
|
9
|
+
const method = (init?.method ?? 'GET').toUpperCase();
|
|
10
|
+
// Parse the request body so input-derived samples (updateTest,
|
|
11
|
+
// putPlanSteps, createTestBatch) can echo the user's actual fields.
|
|
12
|
+
let requestBody;
|
|
13
|
+
if (init?.body != null) {
|
|
14
|
+
try {
|
|
15
|
+
// Treat the body as a string if possible; fall back to String()
|
|
16
|
+
// for any other serialisable type (e.g. Uint8Array in Node 22
|
|
17
|
+
// whose toString() gives a comma-joined byte list, but in
|
|
18
|
+
// practice fetch bodies are always JSON strings here).
|
|
19
|
+
const raw = typeof init.body === 'string' ? init.body : String(init.body);
|
|
20
|
+
requestBody = JSON.parse(raw);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Unparseable body — leave requestBody undefined; samples fall
|
|
24
|
+
// back to their no-input defaults.
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const sample = findSample(method, url, requestBody);
|
|
28
|
+
if (sample === undefined) {
|
|
29
|
+
const body = JSON.stringify({
|
|
30
|
+
error: {
|
|
31
|
+
code: 'INTERNAL',
|
|
32
|
+
message: `No dry-run sample registered for ${method} ${url}`,
|
|
33
|
+
nextAction: 'Add a sample to `src/lib/dry-run/samples.ts` and re-run.',
|
|
34
|
+
requestId: SAMPLE_DRY_RUN_REQUEST_ID,
|
|
35
|
+
details: { method, url },
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
return new Response(body, { status: 500, headers: JSON_HEADERS });
|
|
39
|
+
}
|
|
40
|
+
return new Response(JSON.stringify(sample.body()), { status: 200, headers: JSON_HEADERS });
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function resolveUrl(input) {
|
|
44
|
+
if (typeof input === 'string')
|
|
45
|
+
return input;
|
|
46
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
47
|
+
const inp = input;
|
|
48
|
+
if (inp?.href !== undefined)
|
|
49
|
+
return inp.href; // URL instance
|
|
50
|
+
return inp.url; // Request instance
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=fetch.js.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export declare const SAMPLE_RUN_ID = "run_abc";
|
|
2
|
+
export declare const SAMPLE_DRY_RUN_REQUEST_ID = "req_dry-run";
|
|
3
|
+
/**
|
|
4
|
+
* Dry-run sample lookup keyed by OpenAPI operationId. Order matters in
|
|
5
|
+
* {@link findSample}: more specific patterns must precede their generic
|
|
6
|
+
* siblings (e.g. `/tests/{id}/code` before `/tests/{id}`).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* HTTP methods accepted by the dry-run registry. GET covered the M2
|
|
10
|
+
* read surface; POST landed with M3.2 piece-2 (`POST /api/cli/v1/tests`)
|
|
11
|
+
* and gained `/tests/batch` with M3.2 piece-5; PUT + DELETE landed with
|
|
12
|
+
* M3.2 piece-3 (`PUT/DELETE /api/cli/v1/tests/{id}`); piece-4 added
|
|
13
|
+
* `PUT /api/cli/v1/tests/{id}/code`; piece-6 added
|
|
14
|
+
* `PUT /api/cli/v1/tests/{id}/plan-steps`. The list grows as new
|
|
15
|
+
* mutation routes ship.
|
|
16
|
+
*/
|
|
17
|
+
export type DryRunMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
18
|
+
export interface DryRunSampleEntry {
|
|
19
|
+
operationId: string;
|
|
20
|
+
method: DryRunMethod;
|
|
21
|
+
/** Path under the `/api/cli/v1` prefix. Templated with `{name}` markers. */
|
|
22
|
+
pathTemplate: string;
|
|
23
|
+
/** Compiled regex matching the path (no leading prefix). */
|
|
24
|
+
pattern: RegExp;
|
|
25
|
+
/**
|
|
26
|
+
* Response body factory. When the entry is input-derived (e.g.
|
|
27
|
+
* `updateTest`, `putPlanSteps`, `createTestBatch`) the function
|
|
28
|
+
* receives the parsed request body so the sample can echo back the
|
|
29
|
+
* user's actual field values instead of a static canned placeholder.
|
|
30
|
+
* Simple read-only endpoints use a zero-arity factory that ignores the
|
|
31
|
+
* argument.
|
|
32
|
+
*/
|
|
33
|
+
body: (requestBody?: unknown) => unknown;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Resolve a fetch URL to its canned sample. Matches against the path
|
|
37
|
+
* portion only (query string is ignored — auto-pagination's `cursor`
|
|
38
|
+
* query is intentionally a no-op in M2 dry-run; see {@link pageOf}).
|
|
39
|
+
*
|
|
40
|
+
* Returns `undefined` when no pattern matches; the caller (the dry-run
|
|
41
|
+
* fetch impl) surfaces this as a 500 INTERNAL envelope so a missing
|
|
42
|
+
* sample is loud, not silent.
|
|
43
|
+
*
|
|
44
|
+
* `requestBody` is forwarded to input-derived entries (`updateTest`,
|
|
45
|
+
* `putPlanSteps`, `createTestBatch`) so their responses reflect the
|
|
46
|
+
* user's actual flags rather than static canned values.
|
|
47
|
+
*/
|
|
48
|
+
export declare function findSample(method: string, url: string, requestBody?: unknown): DryRunSampleEntry | undefined;
|
|
49
|
+
/** Test-only export so `samples.test.ts` can iterate the catalog. */
|
|
50
|
+
export declare const DRY_RUN_SAMPLE_ENTRIES: ReadonlyArray<DryRunSampleEntry>;
|