loadam 0.2.4 → 0.3.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/README.md +52 -19
- package/dist/bin.d.ts +1 -1
- package/dist/bin.js +1666 -331
- package/dist/bin.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1666 -331
- package/dist/index.js.map +1 -1
- package/package.json +8 -5
package/dist/index.js
CHANGED
|
@@ -113,7 +113,7 @@ function inferProfile(args) {
|
|
|
113
113
|
id: "basic",
|
|
114
114
|
kind: "basic",
|
|
115
115
|
userEnv: "API_USER",
|
|
116
|
-
passEnv: "
|
|
116
|
+
passEnv: "API_PASS"
|
|
117
117
|
};
|
|
118
118
|
}
|
|
119
119
|
}
|
|
@@ -134,7 +134,7 @@ function inferProfile(args) {
|
|
|
134
134
|
id: "basic",
|
|
135
135
|
kind: "basic",
|
|
136
136
|
userEnv: "API_USER",
|
|
137
|
-
passEnv: "
|
|
137
|
+
passEnv: "API_PASS"
|
|
138
138
|
};
|
|
139
139
|
}
|
|
140
140
|
if (url) {
|
|
@@ -172,6 +172,92 @@ function findApiKeyHeader(headers) {
|
|
|
172
172
|
}
|
|
173
173
|
return null;
|
|
174
174
|
}
|
|
175
|
+
var REDACTED = "<redacted>";
|
|
176
|
+
var SECRET_BODY_HINT = /pass(word)?|secret|token|api_?key|client_secret|credential/i;
|
|
177
|
+
var SECRET_HEADER_PATTERNS = [
|
|
178
|
+
/^authorization$/,
|
|
179
|
+
/^proxy-authorization$/,
|
|
180
|
+
/^cookie$/,
|
|
181
|
+
/^set-cookie$/,
|
|
182
|
+
/(^|-)api-?key$/,
|
|
183
|
+
/token/,
|
|
184
|
+
/secret/,
|
|
185
|
+
/password/,
|
|
186
|
+
/session/,
|
|
187
|
+
/(^|-)auth(-|$)/
|
|
188
|
+
];
|
|
189
|
+
var SECRET_QUERY_PARAMS = /* @__PURE__ */ new Set([
|
|
190
|
+
"api_key",
|
|
191
|
+
"apikey",
|
|
192
|
+
"key",
|
|
193
|
+
"access_token",
|
|
194
|
+
"token",
|
|
195
|
+
"secret",
|
|
196
|
+
"password",
|
|
197
|
+
"sig",
|
|
198
|
+
"signature"
|
|
199
|
+
]);
|
|
200
|
+
function isSecretHeader(name) {
|
|
201
|
+
const n = name.toLowerCase();
|
|
202
|
+
return SECRET_HEADER_PATTERNS.some((rx) => rx.test(n));
|
|
203
|
+
}
|
|
204
|
+
function redactUrl(raw) {
|
|
205
|
+
try {
|
|
206
|
+
const u = new URL(raw);
|
|
207
|
+
let changed = false;
|
|
208
|
+
if (u.password) {
|
|
209
|
+
u.password = REDACTED;
|
|
210
|
+
changed = true;
|
|
211
|
+
}
|
|
212
|
+
for (const k of [...u.searchParams.keys()]) {
|
|
213
|
+
if (SECRET_QUERY_PARAMS.has(k.toLowerCase())) {
|
|
214
|
+
u.searchParams.set(k, REDACTED);
|
|
215
|
+
changed = true;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return changed ? u.toString() : raw;
|
|
219
|
+
} catch {
|
|
220
|
+
return raw;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function redactHeaderLine(line) {
|
|
224
|
+
const idx = line.indexOf(":");
|
|
225
|
+
if (idx <= 0) return line;
|
|
226
|
+
const name = line.slice(0, idx).trim();
|
|
227
|
+
return isSecretHeader(name) ? `${name}: ${REDACTED}` : line;
|
|
228
|
+
}
|
|
229
|
+
function redactImportedCurl(result) {
|
|
230
|
+
const headers = {};
|
|
231
|
+
for (const [k, v] of Object.entries(result.headers)) {
|
|
232
|
+
headers[k] = isSecretHeader(k) ? REDACTED : v;
|
|
233
|
+
}
|
|
234
|
+
const tokens = [];
|
|
235
|
+
for (let i = 0; i < result.tokens.length; i++) {
|
|
236
|
+
const t = result.tokens[i];
|
|
237
|
+
const prev = i > 0 ? result.tokens[i - 1] : void 0;
|
|
238
|
+
if (prev === "-u" || prev === "--user" || prev === "-b" || prev === "--cookie") {
|
|
239
|
+
tokens.push(REDACTED);
|
|
240
|
+
} else if (prev === "-H" || prev === "--header") {
|
|
241
|
+
tokens.push(redactHeaderLine(t));
|
|
242
|
+
} else if (/^--(user|cookie)=/.test(t)) {
|
|
243
|
+
tokens.push(`${t.slice(0, t.indexOf("=") + 1)}${REDACTED}`);
|
|
244
|
+
} else if (/^--header=/.test(t)) {
|
|
245
|
+
tokens.push(`--header=${redactHeaderLine(t.slice("--header=".length))}`);
|
|
246
|
+
} else if (prev !== void 0 && /^(-d|--data|--data-raw|--data-binary|--data-urlencode|-F|--form)$/.test(prev) && SECRET_BODY_HINT.test(t)) {
|
|
247
|
+
tokens.push(REDACTED);
|
|
248
|
+
} else if (/^https?:\/\//i.test(t)) {
|
|
249
|
+
tokens.push(redactUrl(t));
|
|
250
|
+
} else {
|
|
251
|
+
tokens.push(t);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return {
|
|
255
|
+
...result,
|
|
256
|
+
headers,
|
|
257
|
+
tokens,
|
|
258
|
+
url: result.url ? redactUrl(result.url) : result.url
|
|
259
|
+
};
|
|
260
|
+
}
|
|
175
261
|
|
|
176
262
|
// src/commands/auth.ts
|
|
177
263
|
import { consola as consola2 } from "consola";
|
|
@@ -224,7 +310,7 @@ function registerAuthCommands(program) {
|
|
|
224
310
|
const auth = program.command("auth").description("Auth helpers");
|
|
225
311
|
auth.command("import").description(
|
|
226
312
|
"Parse a curl command and infer an auth profile. Reads from --file, then stdin, then args."
|
|
227
|
-
).option("-f, --file <path>", "read curl command from a file").option("--json", "emit JSON instead of pretty output", false).argument("[curl...]", "inline curl command").action(withFriendlyErrors(runAuthImport));
|
|
313
|
+
).option("-f, --file <path>", "read curl command from a file").option("--json", "emit JSON instead of pretty output", false).option("--show-secrets", "print header values and credentials unredacted", false).argument("[curl...]", "inline curl command").action(withFriendlyErrors(runAuthImport));
|
|
228
314
|
}
|
|
229
315
|
async function runAuthImport(curlArgs, opts) {
|
|
230
316
|
const input = await loadCurlInput(curlArgs, opts);
|
|
@@ -232,7 +318,8 @@ async function runAuthImport(curlArgs, opts) {
|
|
|
232
318
|
consola2.error("No curl command provided. Pass via --file, stdin, or as arguments.");
|
|
233
319
|
process.exit(2);
|
|
234
320
|
}
|
|
235
|
-
const
|
|
321
|
+
const raw = importCurl(input);
|
|
322
|
+
const result = opts.showSecrets ? raw : redactImportedCurl(raw);
|
|
236
323
|
if (opts.json) {
|
|
237
324
|
process.stdout.write(`${JSON.stringify(result, null, 2)}
|
|
238
325
|
`);
|
|
@@ -597,8 +684,8 @@ function registerCompletionCommand(program) {
|
|
|
597
684
|
}
|
|
598
685
|
|
|
599
686
|
// src/commands/contract.ts
|
|
600
|
-
import { mkdir as mkdir2, readFile as
|
|
601
|
-
import { dirname, resolve as
|
|
687
|
+
import { mkdir as mkdir2, readFile as readFile6, writeFile as writeFile2 } from "fs/promises";
|
|
688
|
+
import { dirname as dirname2, join as join3, resolve as resolve5 } from "path";
|
|
602
689
|
|
|
603
690
|
// ../core/dist/index.js
|
|
604
691
|
import { z } from "zod";
|
|
@@ -639,7 +726,7 @@ var ServerVariable = z.object({
|
|
|
639
726
|
var Server = z.object({
|
|
640
727
|
url: z.string(),
|
|
641
728
|
description: z.string().optional(),
|
|
642
|
-
variables: z.record(ServerVariable).optional()
|
|
729
|
+
variables: z.record(z.string(), ServerVariable).optional()
|
|
643
730
|
});
|
|
644
731
|
var AuthProfile = z.discriminatedUnion("kind", [
|
|
645
732
|
z.object({ id: z.string(), kind: z.literal("none") }),
|
|
@@ -703,6 +790,7 @@ var Param = z.object({
|
|
|
703
790
|
var RequestBody = z.object({
|
|
704
791
|
required: z.boolean(),
|
|
705
792
|
contentTypes: z.record(
|
|
793
|
+
z.string(),
|
|
706
794
|
z.object({
|
|
707
795
|
schema: SchemaRefOrInline,
|
|
708
796
|
examples: z.array(z.unknown()).optional()
|
|
@@ -714,6 +802,7 @@ var ResponseDef = z.object({
|
|
|
714
802
|
description: z.string().optional(),
|
|
715
803
|
headers: z.array(Param).optional(),
|
|
716
804
|
contentTypes: z.record(
|
|
805
|
+
z.string(),
|
|
717
806
|
z.object({
|
|
718
807
|
schema: SchemaRefOrInline,
|
|
719
808
|
examples: z.array(z.unknown()).optional()
|
|
@@ -776,8 +865,8 @@ var ResourceGraph = z.object({
|
|
|
776
865
|
var OperationExample = z.object({
|
|
777
866
|
source: z.enum(["spec", "har", "user"]),
|
|
778
867
|
request: z.object({
|
|
779
|
-
params: z.record(z.unknown()).optional(),
|
|
780
|
-
headers: z.record(z.string()).optional(),
|
|
868
|
+
params: z.record(z.string(), z.unknown()).optional(),
|
|
869
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
781
870
|
body: z.unknown().optional()
|
|
782
871
|
}),
|
|
783
872
|
response: z.object({
|
|
@@ -786,8 +875,8 @@ var OperationExample = z.object({
|
|
|
786
875
|
}).optional()
|
|
787
876
|
});
|
|
788
877
|
var ExampleSet = z.object({
|
|
789
|
-
byOperation: z.record(z.array(OperationExample)).default({}),
|
|
790
|
-
byEntity: z.record(z.array(z.unknown())).default({})
|
|
878
|
+
byOperation: z.record(z.string(), z.array(OperationExample)).default({}),
|
|
879
|
+
byEntity: z.record(z.string(), z.array(z.unknown())).default({})
|
|
791
880
|
});
|
|
792
881
|
var ParamBinding = z.object({
|
|
793
882
|
paramName: z.string(),
|
|
@@ -840,7 +929,7 @@ var IR = z.object({
|
|
|
840
929
|
meta: Meta,
|
|
841
930
|
servers: z.array(Server).default([]),
|
|
842
931
|
auth: z.array(AuthProfile).default([]),
|
|
843
|
-
schemas: z.record(Schema).default({}),
|
|
932
|
+
schemas: z.record(z.string(), Schema).default({}),
|
|
844
933
|
operations: z.array(Operation).default([]),
|
|
845
934
|
resources: ResourceGraph.default({ kinds: [], edges: [] }),
|
|
846
935
|
examples: ExampleSet.default({ byOperation: {}, byEntity: {} }),
|
|
@@ -1093,6 +1182,74 @@ function isRef(v) {
|
|
|
1093
1182
|
}
|
|
1094
1183
|
|
|
1095
1184
|
// ../graph/dist/index.js
|
|
1185
|
+
function bodyProperties(ir, schema) {
|
|
1186
|
+
const resolve15 = (s) => {
|
|
1187
|
+
if (typeof s === "string") return ir.schemas[s]?.jsonSchema;
|
|
1188
|
+
if (!s || typeof s !== "object") return void 0;
|
|
1189
|
+
const js = "jsonSchema" in s ? s.jsonSchema : s;
|
|
1190
|
+
if (js?.$ref) return ir.schemas[js.$ref]?.jsonSchema;
|
|
1191
|
+
return js;
|
|
1192
|
+
};
|
|
1193
|
+
return resolve15(schema)?.properties ?? {};
|
|
1194
|
+
}
|
|
1195
|
+
function isScalar(p) {
|
|
1196
|
+
if (p.$ref) return false;
|
|
1197
|
+
const types = Array.isArray(p.type) ? p.type : [p.type];
|
|
1198
|
+
return types.some((t) => t === "string" || t === "integer" || t === "number");
|
|
1199
|
+
}
|
|
1200
|
+
function detectBodyRef(field, prop, kinds, ownKind) {
|
|
1201
|
+
const byLower = new Map([...kinds.keys()].map((k) => [k.toLowerCase(), k]));
|
|
1202
|
+
const hint = prop["x-loadam-ref"];
|
|
1203
|
+
if (typeof hint === "string" && byLower.has(hint.toLowerCase())) {
|
|
1204
|
+
return { field, kind: byLower.get(hint.toLowerCase()), via: "x-loadam-ref" };
|
|
1205
|
+
}
|
|
1206
|
+
if (!isScalar(prop)) return void 0;
|
|
1207
|
+
const m = field.match(/^([a-zA-Z][a-zA-Z0-9]*?)(Id|_id|ID|Uuid|_uuid|Ref|_ref)$/) ?? field.match(/^([a-zA-Z][a-zA-Z0-9_]*)$/);
|
|
1208
|
+
if (m?.[1]) {
|
|
1209
|
+
const candidate = m[1].replace(/_/g, "").toLowerCase();
|
|
1210
|
+
const kind = byLower.get(candidate);
|
|
1211
|
+
if (kind && kind !== ownKind) return { field, kind, via: "name" };
|
|
1212
|
+
}
|
|
1213
|
+
const text = `${prop.description ?? ""} ${prop.title ?? ""}`.toLowerCase();
|
|
1214
|
+
if (text.trim()) {
|
|
1215
|
+
const mentioned = [...kinds.keys()].filter(
|
|
1216
|
+
(k) => k !== ownKind && new RegExp(`\\b${escapeRegExp(k.toLowerCase())}s?\\b`).test(text)
|
|
1217
|
+
);
|
|
1218
|
+
if (mentioned.length === 1) return { field, kind: mentioned[0], via: "description" };
|
|
1219
|
+
}
|
|
1220
|
+
return void 0;
|
|
1221
|
+
}
|
|
1222
|
+
function escapeRegExp(s) {
|
|
1223
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1224
|
+
}
|
|
1225
|
+
function inferBodyRefs(ir, kinds, edges) {
|
|
1226
|
+
const byName = new Map(kinds.map((k) => [k.name, k]));
|
|
1227
|
+
for (const op of ir.operations) {
|
|
1228
|
+
if (!op.body) continue;
|
|
1229
|
+
for (const media of Object.values(op.body.contentTypes)) {
|
|
1230
|
+
for (const [field, prop] of Object.entries(bodyProperties(ir, media.schema))) {
|
|
1231
|
+
const ref = detectBodyRef(field, prop, byName, op.resourceKind);
|
|
1232
|
+
if (ref) addBodyRef(op, ref, edges);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
function addBodyRef(op, ref, edges) {
|
|
1238
|
+
const consumes = op.consumes ?? [];
|
|
1239
|
+
if (!consumes.some((c) => c.kind === ref.kind && c.field === ref.field)) {
|
|
1240
|
+
consumes.push({ kind: ref.kind, field: ref.field });
|
|
1241
|
+
}
|
|
1242
|
+
op.consumes = consumes;
|
|
1243
|
+
if (op.resourceKind && op.resourceKind !== ref.kind) {
|
|
1244
|
+
edges.push({
|
|
1245
|
+
from: op.resourceKind,
|
|
1246
|
+
to: ref.kind,
|
|
1247
|
+
via: { operationId: op.id, param: ref.field },
|
|
1248
|
+
cardinality: "1:N",
|
|
1249
|
+
confidence: ref.via === "description" ? 0.6 : 0.8
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1096
1253
|
var IRREGULAR = {
|
|
1097
1254
|
people: "person",
|
|
1098
1255
|
children: "child",
|
|
@@ -1135,16 +1292,18 @@ function preserveCase(source, replacement) {
|
|
|
1135
1292
|
return replacement;
|
|
1136
1293
|
}
|
|
1137
1294
|
function toEntityName(segment) {
|
|
1138
|
-
const
|
|
1139
|
-
|
|
1295
|
+
const parts = segment.split(/[-_]/).filter(Boolean);
|
|
1296
|
+
if (parts.length > 0) parts[parts.length - 1] = singularize(parts[parts.length - 1]);
|
|
1297
|
+
return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
|
|
1140
1298
|
}
|
|
1141
1299
|
function inferResourceGraph(ir) {
|
|
1142
1300
|
const opsByKind = /* @__PURE__ */ new Map();
|
|
1143
1301
|
const kindIdField = /* @__PURE__ */ new Map();
|
|
1144
1302
|
const kindSchemaId = /* @__PURE__ */ new Map();
|
|
1145
1303
|
const edges = [];
|
|
1304
|
+
const allPaths = new Set(ir.operations.map((o) => o.path));
|
|
1146
1305
|
for (const op of ir.operations) {
|
|
1147
|
-
const classification = classifyOperation(op, ir.schemas);
|
|
1306
|
+
const classification = classifyOperation(op, ir.schemas, allPaths);
|
|
1148
1307
|
if (!classification) continue;
|
|
1149
1308
|
const { kind, action, idField, schemaId } = classification;
|
|
1150
1309
|
op.resourceKind = kind;
|
|
@@ -1204,6 +1363,40 @@ function inferResourceGraph(ir) {
|
|
|
1204
1363
|
deleteOps: ops.filter((o) => o.resourceAction === "delete").map((o) => o.id)
|
|
1205
1364
|
});
|
|
1206
1365
|
}
|
|
1366
|
+
for (const kind of kinds) {
|
|
1367
|
+
const props = schemaProps(kind.schemaId ? ir.schemas[kind.schemaId] : void 0);
|
|
1368
|
+
if (!props) continue;
|
|
1369
|
+
const itemOps = [...kind.readOps, ...kind.updateOps, ...kind.deleteOps];
|
|
1370
|
+
for (const opId of itemOps) {
|
|
1371
|
+
const op = ir.operations.find((o) => o.id === opId);
|
|
1372
|
+
const last = op?.path.split("/").filter(Boolean).pop();
|
|
1373
|
+
if (!last || !isParamSegment(last)) continue;
|
|
1374
|
+
const field = idFieldFromParam(last.slice(1, -1), kind.name, props);
|
|
1375
|
+
if (field) {
|
|
1376
|
+
kind.idField = field;
|
|
1377
|
+
break;
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
if (!props.includes(kind.idField)) {
|
|
1381
|
+
kind.idField = pickIdField(ir.schemas[kind.schemaId]) ?? kind.idField;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
const kindsByName = new Map(kinds.map((k) => [k.name, k]));
|
|
1385
|
+
for (const op of ir.operations) {
|
|
1386
|
+
const segments = op.path.split("/").filter(Boolean);
|
|
1387
|
+
for (let i = 1; i < segments.length; i++) {
|
|
1388
|
+
const seg = segments[i];
|
|
1389
|
+
const prev = segments[i - 1];
|
|
1390
|
+
if (!isParamSegment(seg) || isParamSegment(prev) || isVersionSegment(prev)) continue;
|
|
1391
|
+
const kind = kindsByName.get(toEntityName(prev));
|
|
1392
|
+
const param = op.pathParams.find((p) => p.name === seg.slice(1, -1));
|
|
1393
|
+
if (kind && param) {
|
|
1394
|
+
param.resourceKind = kind.name;
|
|
1395
|
+
param.resourceField = kind.idField;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
inferBodyRefs(ir, kinds, edges);
|
|
1207
1400
|
const seen = /* @__PURE__ */ new Set();
|
|
1208
1401
|
const dedupedEdges = edges.filter((e) => {
|
|
1209
1402
|
const key = `${e.from}|${e.to}|${e.via.operationId}|${e.via.param}`;
|
|
@@ -1214,9 +1407,16 @@ function inferResourceGraph(ir) {
|
|
|
1214
1407
|
ir.resources = { kinds, edges: dedupedEdges };
|
|
1215
1408
|
return ir;
|
|
1216
1409
|
}
|
|
1217
|
-
function classifyOperation(op, schemas) {
|
|
1410
|
+
function classifyOperation(op, schemas, allPaths) {
|
|
1218
1411
|
const segments = op.path.split("/").filter(Boolean);
|
|
1219
1412
|
if (segments.length === 0) return null;
|
|
1413
|
+
const actionOf = actionTarget(segments, allPaths);
|
|
1414
|
+
if (actionOf) {
|
|
1415
|
+
const { schemaId: schemaId2, idField: idField2 } = pickSuccessSchema(op, schemas);
|
|
1416
|
+
const kind2 = toEntityName(actionOf);
|
|
1417
|
+
const action2 = op.method === "GET" && returnsArray(op, schemas) && !isParamSegment(segments[segments.length - 2]) ? "list" : "action";
|
|
1418
|
+
return action2 === "list" ? { kind: kind2, action: action2, idField: idField2, schemaId: schemaId2 } : { kind: kind2, action: action2 };
|
|
1419
|
+
}
|
|
1220
1420
|
const last = segments[segments.length - 1];
|
|
1221
1421
|
const lastIsParam = isParamSegment(last);
|
|
1222
1422
|
let collectionSegment;
|
|
@@ -1251,6 +1451,37 @@ function classifyOperation(op, schemas) {
|
|
|
1251
1451
|
const { schemaId, idField } = pickSuccessSchema(op, schemas);
|
|
1252
1452
|
return { kind, action, idField, schemaId };
|
|
1253
1453
|
}
|
|
1454
|
+
var ACTION_VERB = /^(find|search|query|filter|get|list|count|create|update|delete|remove|upload|download|import|export|login|logout|signin|signout|signup|register|verify|validate|check|reset|send|cancel|approve|reject|activate|deactivate|enable|disable|archive|restore|publish|sync|batch|bulk|me$)/i;
|
|
1455
|
+
function actionTarget(segments, allPaths) {
|
|
1456
|
+
if (segments.length < 2) return void 0;
|
|
1457
|
+
const last = segments[segments.length - 1];
|
|
1458
|
+
if (isParamSegment(last) || isVersionSegment(last)) return void 0;
|
|
1459
|
+
const prefix = `/${segments.slice(0, -1).join("/")}`;
|
|
1460
|
+
const self = `/${segments.join("/")}`;
|
|
1461
|
+
const depth = segments.length;
|
|
1462
|
+
const prefixIsEndpoint = allPaths.has(prefix) || [...allPaths].some((p) => p.startsWith(`${prefix}/{`) && p.split("/").length === depth + 1);
|
|
1463
|
+
if (!prefixIsEndpoint) return void 0;
|
|
1464
|
+
if ([...allPaths].some((p) => p.startsWith(`${self}/`))) return void 0;
|
|
1465
|
+
const plural = singularize(last).toLowerCase() !== last.toLowerCase();
|
|
1466
|
+
if (plural && !ACTION_VERB.test(last)) return void 0;
|
|
1467
|
+
for (let i = segments.length - 2; i >= 0; i--) {
|
|
1468
|
+
const s = segments[i];
|
|
1469
|
+
if (!isParamSegment(s) && !isVersionSegment(s)) return s;
|
|
1470
|
+
}
|
|
1471
|
+
return void 0;
|
|
1472
|
+
}
|
|
1473
|
+
function returnsArray(op, schemas) {
|
|
1474
|
+
const success = op.responses.filter((r) => typeof r.status === "number" && r.status >= 200 && r.status < 300).sort((a, b) => a.status - b.status)[0];
|
|
1475
|
+
const media = success?.contentTypes ? Object.entries(success.contentTypes).find(([k]) => k.includes("json"))?.[1] : void 0;
|
|
1476
|
+
if (!media) return false;
|
|
1477
|
+
const js = typeof media.schema === "string" ? schemas[media.schema]?.jsonSchema : media.schema.jsonSchema;
|
|
1478
|
+
if (!js) return false;
|
|
1479
|
+
if (js.type === "array") return true;
|
|
1480
|
+
const props = js.properties ?? {};
|
|
1481
|
+
if ("id" in props || "uuid" in props) return false;
|
|
1482
|
+
const entityArrays = Object.values(props).filter((p) => !!unwrapArrayItem(p));
|
|
1483
|
+
return entityArrays.length === 1;
|
|
1484
|
+
}
|
|
1254
1485
|
function isParamSegment(seg) {
|
|
1255
1486
|
return seg.startsWith("{") && seg.endsWith("}");
|
|
1256
1487
|
}
|
|
@@ -1266,11 +1497,23 @@ function pickSuccessSchema(op, schemas) {
|
|
|
1266
1497
|
if (!sid) return {};
|
|
1267
1498
|
return { schemaId: sid, idField: pickIdField(schemas[sid]) };
|
|
1268
1499
|
}
|
|
1269
|
-
function
|
|
1500
|
+
function schemaProps(schema) {
|
|
1270
1501
|
const js = schema?.jsonSchema;
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1502
|
+
return js?.properties ? Object.keys(js.properties) : void 0;
|
|
1503
|
+
}
|
|
1504
|
+
function idFieldFromParam(param, kind, props) {
|
|
1505
|
+
if (props.includes(param)) return param;
|
|
1506
|
+
const prefix = kind.toLowerCase();
|
|
1507
|
+
const lower = param.toLowerCase();
|
|
1508
|
+
if (!lower.startsWith(prefix)) return void 0;
|
|
1509
|
+
const rest = param.slice(prefix.length).replace(/^[-_]/, "");
|
|
1510
|
+
if (!rest) return void 0;
|
|
1511
|
+
const field = rest.charAt(0).toLowerCase() + rest.slice(1);
|
|
1512
|
+
return props.includes(field) ? field : void 0;
|
|
1513
|
+
}
|
|
1514
|
+
function pickIdField(schema) {
|
|
1515
|
+
const keys = schemaProps(schema);
|
|
1516
|
+
if (!keys) return void 0;
|
|
1274
1517
|
if (keys.includes("id")) return "id";
|
|
1275
1518
|
if (keys.includes("uuid")) return "uuid";
|
|
1276
1519
|
const idLike = keys.find((k) => /^id$|_id$/i.test(k));
|
|
@@ -1286,12 +1529,25 @@ function resolveTopRef(schema, schemas) {
|
|
|
1286
1529
|
}
|
|
1287
1530
|
const inner = unwrapArrayItem(schema.jsonSchema);
|
|
1288
1531
|
if (inner && typeof inner === "string") return inner;
|
|
1532
|
+
const enveloped = unwrapEnvelope(schema.jsonSchema);
|
|
1533
|
+
if (enveloped) return enveloped;
|
|
1289
1534
|
if (typeof schema.jsonSchema === "object" && schema.jsonSchema !== null) {
|
|
1290
1535
|
const direct = schema.jsonSchema.$ref;
|
|
1291
1536
|
if (direct) return direct;
|
|
1292
1537
|
}
|
|
1293
1538
|
return void 0;
|
|
1294
1539
|
}
|
|
1540
|
+
function unwrapEnvelope(js) {
|
|
1541
|
+
if (!js || typeof js !== "object") return void 0;
|
|
1542
|
+
const props = js.properties;
|
|
1543
|
+
if (!props) return void 0;
|
|
1544
|
+
const refs = Object.values(props).map((v) => {
|
|
1545
|
+
if (!v || typeof v !== "object") return void 0;
|
|
1546
|
+
const direct = v.$ref;
|
|
1547
|
+
return direct ?? unwrapArrayItem(v);
|
|
1548
|
+
}).filter((r) => !!r);
|
|
1549
|
+
return refs.length === 1 ? refs[0] : void 0;
|
|
1550
|
+
}
|
|
1295
1551
|
function unwrapArrayItem(js) {
|
|
1296
1552
|
if (!js || typeof js !== "object") return void 0;
|
|
1297
1553
|
const obj = js;
|
|
@@ -1398,23 +1654,218 @@ function graphStats(graph) {
|
|
|
1398
1654
|
orphanKinds
|
|
1399
1655
|
};
|
|
1400
1656
|
}
|
|
1657
|
+
var ConfigError = class extends Error {
|
|
1658
|
+
};
|
|
1659
|
+
function applyConfig(ir, config) {
|
|
1660
|
+
const kinds = new Map(ir.resources.kinds.map((k) => [k.name, k]));
|
|
1661
|
+
const known = () => [...kinds.keys()].sort().join(", ");
|
|
1662
|
+
const kindNamed = (name, where) => {
|
|
1663
|
+
const kind = kinds.get(name) ?? [...kinds.values()].find((k) => k.name.toLowerCase() === name.toLowerCase());
|
|
1664
|
+
if (!kind) throw new ConfigError(`${where}: unknown resource "${name}". Known: ${known()}`);
|
|
1665
|
+
return kind;
|
|
1666
|
+
};
|
|
1667
|
+
for (const [name, override] of Object.entries(config.resources ?? {})) {
|
|
1668
|
+
const kind = kindNamed(name, `resources.${name}`);
|
|
1669
|
+
if (override.idField) {
|
|
1670
|
+
kind.idField = override.idField;
|
|
1671
|
+
for (const op of ir.operations) {
|
|
1672
|
+
for (const p of op.pathParams)
|
|
1673
|
+
if (p.resourceKind === kind.name) p.resourceField = override.idField;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
for (const [param, kindName] of Object.entries(config.pathParams ?? {})) {
|
|
1678
|
+
const kind = kindNamed(kindName, `pathParams.${param}`);
|
|
1679
|
+
let used = false;
|
|
1680
|
+
for (const op of ir.operations) {
|
|
1681
|
+
for (const p of op.pathParams) {
|
|
1682
|
+
if (p.name !== param) continue;
|
|
1683
|
+
p.resourceKind = kind.name;
|
|
1684
|
+
p.resourceField = kind.idField;
|
|
1685
|
+
used = true;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
if (!used)
|
|
1689
|
+
throw new ConfigError(`pathParams.${param}: no operation has a path param named "${param}"`);
|
|
1690
|
+
}
|
|
1691
|
+
for (const [key, kindName] of Object.entries(config.refs ?? {})) {
|
|
1692
|
+
const dot = key.lastIndexOf(".");
|
|
1693
|
+
if (dot <= 0)
|
|
1694
|
+
throw new ConfigError(`refs.${key}: expected "<Resource or operationId>.<field>"`);
|
|
1695
|
+
const owner = key.slice(0, dot);
|
|
1696
|
+
const field = key.slice(dot + 1);
|
|
1697
|
+
const kind = kindNamed(kindName, `refs.${key}`);
|
|
1698
|
+
const ops = ir.operations.filter(
|
|
1699
|
+
(o) => o.id === owner || o.resourceKind?.toLowerCase() === owner.toLowerCase()
|
|
1700
|
+
);
|
|
1701
|
+
const withField = ops.filter(
|
|
1702
|
+
(o) => o.body && Object.values(o.body.contentTypes).some((m) => field in bodyProperties(ir, m.schema))
|
|
1703
|
+
);
|
|
1704
|
+
if (withField.length === 0) {
|
|
1705
|
+
throw new ConfigError(`refs.${key}: no operation of "${owner}" has a body field "${field}"`);
|
|
1706
|
+
}
|
|
1707
|
+
for (const op of withField) {
|
|
1708
|
+
op.consumes = (op.consumes ?? []).filter((c) => c.field !== field);
|
|
1709
|
+
addBodyRef(op, { field, kind: kind.name, via: "config" }, ir.resources.edges);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
return ir;
|
|
1713
|
+
}
|
|
1401
1714
|
|
|
1402
1715
|
// ../test-contract/dist/index.js
|
|
1716
|
+
import { parse, stringify } from "yaml";
|
|
1717
|
+
function buildLinks(ir) {
|
|
1718
|
+
const out = {};
|
|
1719
|
+
const deref = (s) => {
|
|
1720
|
+
if (typeof s === "string") return ir.schemas[s]?.jsonSchema;
|
|
1721
|
+
if (!s || typeof s !== "object") return void 0;
|
|
1722
|
+
const js = "jsonSchema" in s ? s.jsonSchema : s;
|
|
1723
|
+
return js?.$ref ? ir.schemas[js.$ref]?.jsonSchema : js;
|
|
1724
|
+
};
|
|
1725
|
+
const entityPointer = (schema, idField) => {
|
|
1726
|
+
if (!schema) return void 0;
|
|
1727
|
+
if (schema.properties && idField in schema.properties) return `/${esc(idField)}`;
|
|
1728
|
+
const env = Object.entries(schema.properties ?? {}).filter(([, v]) => {
|
|
1729
|
+
const inner = deref(v);
|
|
1730
|
+
return !!inner?.properties && idField in inner.properties;
|
|
1731
|
+
});
|
|
1732
|
+
return env.length === 1 ? `/${esc(env[0][0])}/${esc(idField)}` : void 0;
|
|
1733
|
+
};
|
|
1734
|
+
const listPointer = (schema, idField) => {
|
|
1735
|
+
if (!schema) return void 0;
|
|
1736
|
+
if (schema.type === "array") {
|
|
1737
|
+
const p2 = entityPointer(deref(schema.items), idField);
|
|
1738
|
+
return p2 ? `/0${p2}` : void 0;
|
|
1739
|
+
}
|
|
1740
|
+
const arrays = Object.entries(schema.properties ?? {}).filter(
|
|
1741
|
+
([, v]) => deref(v)?.type === "array"
|
|
1742
|
+
);
|
|
1743
|
+
if (arrays.length !== 1) return void 0;
|
|
1744
|
+
const p = entityPointer(deref(deref(arrays[0][1])?.items), idField);
|
|
1745
|
+
return p ? `/${esc(arrays[0][0])}/0${p}` : void 0;
|
|
1746
|
+
};
|
|
1747
|
+
for (const kind of ir.resources.kinds) {
|
|
1748
|
+
const sources = [];
|
|
1749
|
+
for (const opId of [...kind.createOps, ...kind.listOps]) {
|
|
1750
|
+
const op = ir.operations.find((o) => o.id === opId);
|
|
1751
|
+
const res = op && successResponse(op);
|
|
1752
|
+
const media = res && jsonMedia(res);
|
|
1753
|
+
if (!op || !res || !media) continue;
|
|
1754
|
+
const schema = deref(media.schema);
|
|
1755
|
+
const pointer = op.resourceAction === "list" ? listPointer(schema, kind.idField) : entityPointer(schema, kind.idField);
|
|
1756
|
+
if (pointer) sources.push({ op, res, pointer });
|
|
1757
|
+
}
|
|
1758
|
+
const targets = ir.operations.filter(
|
|
1759
|
+
(o) => o.pathParams.some((p) => p.resourceKind === kind.name)
|
|
1760
|
+
);
|
|
1761
|
+
const addLink = (source, status, target, parameters, why) => {
|
|
1762
|
+
out[source.id] ??= {};
|
|
1763
|
+
const byStatus = out[source.id];
|
|
1764
|
+
byStatus[String(status)] ??= {};
|
|
1765
|
+
byStatus[String(status)][`loadam_${target.id}`] = {
|
|
1766
|
+
operationId: target.id,
|
|
1767
|
+
parameters,
|
|
1768
|
+
description: `${why} (inferred by loadam)`
|
|
1769
|
+
};
|
|
1770
|
+
};
|
|
1771
|
+
for (const { op: source, res, pointer } of sources) {
|
|
1772
|
+
for (const target of targets) {
|
|
1773
|
+
if (target.id === source.id) continue;
|
|
1774
|
+
const parameters = {};
|
|
1775
|
+
let complete = true;
|
|
1776
|
+
for (const p of target.pathParams) {
|
|
1777
|
+
if (p.resourceKind === kind.name) parameters[p.name] = `$response.body#${pointer}`;
|
|
1778
|
+
else if (source.pathParams.some((sp) => sp.name === p.name))
|
|
1779
|
+
parameters[p.name] = `$request.path.${p.name}`;
|
|
1780
|
+
else if (p.required) complete = false;
|
|
1781
|
+
}
|
|
1782
|
+
if (complete)
|
|
1783
|
+
addLink(source, res.status, target, parameters, `${kind.name} id from ${source.id}`);
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
const itemOps = targets.filter(
|
|
1787
|
+
(o) => o.resourceKind === kind.name && ["read", "update", "delete"].includes(o.resourceAction ?? "")
|
|
1788
|
+
);
|
|
1789
|
+
for (const source of itemOps) {
|
|
1790
|
+
const res = successResponse(source);
|
|
1791
|
+
if (!res) continue;
|
|
1792
|
+
for (const target of targets) {
|
|
1793
|
+
if (target.id === source.id) continue;
|
|
1794
|
+
if (!target.pathParams.every((p) => source.pathParams.some((sp) => sp.name === p.name)))
|
|
1795
|
+
continue;
|
|
1796
|
+
const parameters = Object.fromEntries(
|
|
1797
|
+
target.pathParams.map((p) => [p.name, `$request.path.${p.name}`])
|
|
1798
|
+
);
|
|
1799
|
+
addLink(source, res.status, target, parameters, `same ${kind.name} as ${source.id}`);
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
return out;
|
|
1804
|
+
}
|
|
1805
|
+
function successResponse(op) {
|
|
1806
|
+
return op.responses.filter((r) => typeof r.status === "number" && r.status >= 200 && r.status < 300).sort((a, b) => a.status - b.status)[0];
|
|
1807
|
+
}
|
|
1808
|
+
function jsonMedia(res) {
|
|
1809
|
+
const entry = Object.entries(res.contentTypes ?? {}).find(([k]) => k.includes("json"));
|
|
1810
|
+
return entry?.[1];
|
|
1811
|
+
}
|
|
1812
|
+
function esc(s) {
|
|
1813
|
+
return s.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
1814
|
+
}
|
|
1815
|
+
function injectLinks(doc, ir, links) {
|
|
1816
|
+
const paths = doc.paths ?? {};
|
|
1817
|
+
let added = 0;
|
|
1818
|
+
for (const [opId, byStatus] of Object.entries(links)) {
|
|
1819
|
+
const op = ir.operations.find((o) => o.id === opId);
|
|
1820
|
+
if (!op) continue;
|
|
1821
|
+
const node = paths[op.path]?.[op.method.toLowerCase()];
|
|
1822
|
+
if (!node) continue;
|
|
1823
|
+
const responses = node.responses ?? {};
|
|
1824
|
+
for (const [status, l] of Object.entries(byStatus)) {
|
|
1825
|
+
const r = responses[status];
|
|
1826
|
+
if (!r || "$ref" in r) continue;
|
|
1827
|
+
const existing = r.links ?? {};
|
|
1828
|
+
for (const [name, link] of Object.entries(l)) {
|
|
1829
|
+
if (name in existing) continue;
|
|
1830
|
+
existing[name] = link;
|
|
1831
|
+
added++;
|
|
1832
|
+
}
|
|
1833
|
+
r.links = existing;
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
for (const op of ir.operations) {
|
|
1837
|
+
const node = paths[op.path]?.[op.method.toLowerCase()];
|
|
1838
|
+
if (node && !node.operationId) node.operationId = op.id;
|
|
1839
|
+
}
|
|
1840
|
+
return added;
|
|
1841
|
+
}
|
|
1403
1842
|
function compileContract(ir, specSource, opts = {}) {
|
|
1404
1843
|
const specFileName = opts.specFileName ?? "openapi.yaml";
|
|
1405
1844
|
const baseUrl = opts.baseUrl ?? ir.servers[0]?.url ?? "http://localhost:4010";
|
|
1406
1845
|
const examples = opts.examples ?? 25;
|
|
1407
1846
|
const envVars = collectEnvVars(ir.auth);
|
|
1847
|
+
let specOut = specSource.endsWith("\n") ? specSource : `${specSource}
|
|
1848
|
+
`;
|
|
1849
|
+
let linksAdded = 0;
|
|
1850
|
+
if (opts.links !== false) {
|
|
1851
|
+
const doc = parse(specSource);
|
|
1852
|
+
linksAdded = injectLinks(doc, ir, buildLinks(ir));
|
|
1853
|
+
if (linksAdded > 0) {
|
|
1854
|
+
specOut = `# Copied by loadam; links marked "inferred by loadam" were added for stateful tests.
|
|
1855
|
+
${stringify(doc, { aliasDuplicateObjects: false })}`;
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1408
1858
|
const files = {
|
|
1409
|
-
[specFileName]:
|
|
1410
|
-
`,
|
|
1859
|
+
[specFileName]: specOut,
|
|
1411
1860
|
"pyproject.toml": emitPyProject(ir),
|
|
1412
|
-
"conftest.py": emitConftest(
|
|
1413
|
-
"
|
|
1861
|
+
"conftest.py": emitConftest(specFileName, envVars),
|
|
1862
|
+
"loadam_hooks.py": emitHooks(ir.auth, baseUrl),
|
|
1863
|
+
"schemathesis.toml": emitSchemathesisToml(ir),
|
|
1864
|
+
"test_contract.py": emitContractTests(examples, linksAdded > 0),
|
|
1414
1865
|
"README.md": emitReadme(ir, specFileName),
|
|
1415
1866
|
".env.example": emitEnvExample(baseUrl, envVars)
|
|
1416
1867
|
};
|
|
1417
|
-
return { files, envVars };
|
|
1868
|
+
return { files, envVars, linksAdded };
|
|
1418
1869
|
}
|
|
1419
1870
|
function collectEnvVars(profiles) {
|
|
1420
1871
|
const out = /* @__PURE__ */ new Set();
|
|
@@ -1424,7 +1875,7 @@ function collectEnvVars(profiles) {
|
|
|
1424
1875
|
out.add(p.tokenEnv ?? "API_TOKEN");
|
|
1425
1876
|
break;
|
|
1426
1877
|
case "apiKey":
|
|
1427
|
-
out.add(p
|
|
1878
|
+
out.add(apiKeyEnv(p));
|
|
1428
1879
|
break;
|
|
1429
1880
|
case "basic":
|
|
1430
1881
|
out.add(p.userEnv ?? "API_USER");
|
|
@@ -1446,7 +1897,7 @@ version = "0.0.0"
|
|
|
1446
1897
|
description = "Schemathesis contract suite for ${ir.meta.title} \u2014 generated by loadam"
|
|
1447
1898
|
requires-python = ">=3.10"
|
|
1448
1899
|
dependencies = [
|
|
1449
|
-
"schemathesis>=
|
|
1900
|
+
"schemathesis>=4,<5",
|
|
1450
1901
|
"pytest>=8.0",
|
|
1451
1902
|
"pyyaml>=6.0",
|
|
1452
1903
|
"python-dotenv>=1.0",
|
|
@@ -1457,115 +1908,243 @@ addopts = "-q"
|
|
|
1457
1908
|
testpaths = ["."]
|
|
1458
1909
|
`;
|
|
1459
1910
|
}
|
|
1460
|
-
function emitConftest(
|
|
1461
|
-
const authBuilder = emitAuthBuilder(ir.auth);
|
|
1911
|
+
function emitConftest(specFileName, envVars) {
|
|
1462
1912
|
return `# AUTO-GENERATED by @loadam/test-contract
|
|
1463
1913
|
"""
|
|
1464
|
-
Shared
|
|
1914
|
+
Shared setup for the Schemathesis contract suite.
|
|
1465
1915
|
|
|
1466
1916
|
The schema is loaded from a checked-in copy of the spec so the suite is
|
|
1467
|
-
self-contained and reproducible. Override BASE_URL / credentials via env vars
|
|
1917
|
+
self-contained and reproducible. Override BASE_URL / credentials via env vars
|
|
1918
|
+
or a .env file.
|
|
1468
1919
|
"""
|
|
1469
1920
|
|
|
1470
1921
|
import os
|
|
1471
1922
|
from pathlib import Path
|
|
1472
1923
|
|
|
1473
1924
|
import schemathesis
|
|
1474
|
-
from
|
|
1925
|
+
from schemathesis.config import SchemathesisConfig
|
|
1475
1926
|
|
|
1476
|
-
|
|
1927
|
+
import loadam_hooks # noqa: F401 \u2014 registers the auth provider
|
|
1928
|
+
from loadam_hooks import BASE_URL
|
|
1477
1929
|
|
|
1478
|
-
|
|
1479
|
-
|
|
1930
|
+
HERE = Path(__file__).parent
|
|
1931
|
+
SPEC_PATH = HERE / "${specFileName}"
|
|
1932
|
+
CONFIG_PATH = HERE / "schemathesis.toml"
|
|
1933
|
+
HOOKS_PATH = HERE / "loadam_hooks.py"
|
|
1480
1934
|
|
|
1481
|
-
#
|
|
1482
|
-
#
|
|
1935
|
+
# Credentials the spec's security schemes need. Missing ones are reported,
|
|
1936
|
+
# not required: unauthenticated runs still exercise public endpoints.
|
|
1483
1937
|
REQUIRED_ENV = ${JSON.stringify(envVars)}
|
|
1484
1938
|
|
|
1485
|
-
schema = schemathesis.from_path(
|
|
1939
|
+
schema = schemathesis.openapi.from_path(
|
|
1940
|
+
str(SPEC_PATH), config=SchemathesisConfig.from_path(str(CONFIG_PATH))
|
|
1941
|
+
)
|
|
1942
|
+
schema.config.update(base_url=BASE_URL)
|
|
1486
1943
|
|
|
1487
1944
|
|
|
1488
|
-
def
|
|
1489
|
-
|
|
1945
|
+
def pytest_report_header(config):
|
|
1946
|
+
missing = [name for name in REQUIRED_ENV if not os.getenv(name)]
|
|
1947
|
+
lines = [f"loadam: testing {BASE_URL}"]
|
|
1948
|
+
if missing:
|
|
1949
|
+
lines.append(f"loadam: auth env vars not set: {', '.join(missing)}")
|
|
1950
|
+
return lines
|
|
1490
1951
|
`;
|
|
1491
1952
|
}
|
|
1492
|
-
function
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
}
|
|
1496
|
-
const
|
|
1497
|
-
|
|
1953
|
+
function emitSchemathesisToml(ir) {
|
|
1954
|
+
const refOps = ir.operations.filter(
|
|
1955
|
+
(op) => (op.consumes ?? []).some((c) => c.field && !op.pathParams.some((p) => p.name === c.field))
|
|
1956
|
+
).map((op) => `${op.method.toUpperCase()} ${op.path}`).sort();
|
|
1957
|
+
const blocks = refOps.map(
|
|
1958
|
+
(label) => `
|
|
1959
|
+
[[operations]]
|
|
1960
|
+
include-name = ${JSON.stringify(label)}
|
|
1961
|
+
checks.positive_data_acceptance.enabled = false
|
|
1962
|
+
`
|
|
1963
|
+
);
|
|
1964
|
+
return `# AUTO-GENERATED by @loadam/test-contract
|
|
1965
|
+
# Read by conftest.py and by the stateful run (schemathesis CLI).
|
|
1966
|
+
# https://schemathesis.readthedocs.io/en/stable/reference/configuration/
|
|
1967
|
+
${blocks.length ? `
|
|
1968
|
+
# Request bodies here reference other resources. Fuzzed ids rarely exist, so
|
|
1969
|
+
# rejecting them is correct: skip the "schema-valid data rejected" check.
|
|
1970
|
+
${blocks.join("")}` : ""}`;
|
|
1971
|
+
}
|
|
1972
|
+
function emitHooks(profiles, baseUrl) {
|
|
1973
|
+
const head = `# AUTO-GENERATED by @loadam/test-contract
|
|
1974
|
+
"""
|
|
1975
|
+
Environment and auth for the contract suite. conftest.py imports this; the
|
|
1976
|
+
stateful test hands it to the Schemathesis CLI through SCHEMATHESIS_HOOKS.
|
|
1977
|
+
"""
|
|
1978
|
+
|
|
1979
|
+
import os
|
|
1980
|
+
from pathlib import Path
|
|
1981
|
+
|
|
1982
|
+
import schemathesis
|
|
1983
|
+
from dotenv import load_dotenv
|
|
1984
|
+
|
|
1985
|
+
load_dotenv(Path(__file__).parent / ".env")
|
|
1986
|
+
|
|
1987
|
+
BASE_URL = os.getenv("BASE_URL", ${JSON.stringify(baseUrl)})
|
|
1988
|
+
`;
|
|
1989
|
+
const relevant = profiles.filter((p) => p.kind !== "none" && p.kind !== "custom");
|
|
1990
|
+
if (relevant.length === 0) return `${head}
|
|
1991
|
+
# The spec declares no authentication.
|
|
1992
|
+
`;
|
|
1993
|
+
const usesOAuth = relevant.some((p) => p.kind === "oauth2_cc");
|
|
1994
|
+
const lines = [
|
|
1995
|
+
"def _credentials() -> dict:",
|
|
1996
|
+
` """Headers / query / cookies from env vars, per the spec's security schemes."""`,
|
|
1997
|
+
' out: dict = {"headers": {}, "query": {}, "cookies": {}}'
|
|
1998
|
+
];
|
|
1999
|
+
const env = (name) => `os.getenv(${JSON.stringify(name)})`;
|
|
2000
|
+
for (const p of relevant) {
|
|
1498
2001
|
switch (p.kind) {
|
|
1499
2002
|
case "bearer": {
|
|
1500
|
-
const
|
|
1501
|
-
lines.push(` if
|
|
1502
|
-
lines.push(
|
|
1503
|
-
` headers["Authorization"] = f"Bearer {os.environ[${JSON.stringify(env)}]}"`
|
|
1504
|
-
);
|
|
2003
|
+
const e = p.tokenEnv ?? "API_TOKEN";
|
|
2004
|
+
lines.push(` if ${env(e)}:`);
|
|
2005
|
+
lines.push(` out["headers"]["Authorization"] = "Bearer " + ${env(e)}`);
|
|
1505
2006
|
break;
|
|
1506
2007
|
}
|
|
1507
2008
|
case "apiKey": {
|
|
1508
|
-
const
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
` headers[${JSON.stringify(p.name)}] = os.environ[${JSON.stringify(env)}]`
|
|
1513
|
-
);
|
|
1514
|
-
} else if (p.in === "query") {
|
|
1515
|
-
lines.push(` if os.getenv(${JSON.stringify(env)}):`);
|
|
1516
|
-
lines.push(
|
|
1517
|
-
` params[${JSON.stringify(p.name)}] = os.environ[${JSON.stringify(env)}]`
|
|
1518
|
-
);
|
|
1519
|
-
}
|
|
2009
|
+
const e = apiKeyEnv(p);
|
|
2010
|
+
const bucket = p.in === "header" ? "headers" : p.in === "query" ? "query" : "cookies";
|
|
2011
|
+
lines.push(` if ${env(e)}:`);
|
|
2012
|
+
lines.push(` out[${JSON.stringify(bucket)}][${JSON.stringify(p.name)}] = ${env(e)}`);
|
|
1520
2013
|
break;
|
|
1521
2014
|
}
|
|
1522
2015
|
case "basic": {
|
|
1523
2016
|
const u = p.userEnv ?? "API_USER";
|
|
1524
2017
|
const pw = p.passEnv ?? "API_PASS";
|
|
1525
|
-
lines.push(` if
|
|
2018
|
+
lines.push(` if ${env(u)} and ${env(pw)}:`);
|
|
1526
2019
|
lines.push(
|
|
1527
|
-
`
|
|
2020
|
+
` raw = (${env(u)} + ":" + ${env(pw)}).encode()`,
|
|
2021
|
+
` out["headers"]["Authorization"] = "Basic " + base64.b64encode(raw).decode()`
|
|
2022
|
+
);
|
|
2023
|
+
break;
|
|
2024
|
+
}
|
|
2025
|
+
case "oauth2_cc": {
|
|
2026
|
+
lines.push(` if ${env(p.clientIdEnv)} and ${env(p.clientSecretEnv)}:`);
|
|
2027
|
+
lines.push(
|
|
2028
|
+
` token = _oauth_token(${JSON.stringify(p.tokenUrl)}, ${env(p.clientIdEnv)}, ${env(p.clientSecretEnv)}, ${JSON.stringify((p.scopes ?? []).join(" "))})`,
|
|
2029
|
+
" if token:",
|
|
2030
|
+
` out["headers"]["Authorization"] = "Bearer " + token`
|
|
1528
2031
|
);
|
|
1529
2032
|
break;
|
|
1530
2033
|
}
|
|
1531
2034
|
}
|
|
1532
2035
|
}
|
|
1533
|
-
lines.push(
|
|
1534
|
-
|
|
2036
|
+
lines.push(" return out");
|
|
2037
|
+
const oauth = usesOAuth ? `
|
|
2038
|
+
|
|
2039
|
+
def _oauth_token(token_url: str, client_id: str, client_secret: str, scope: str):
|
|
2040
|
+
"""OAuth2 client-credentials token. A relative tokenUrl resolves against BASE_URL."""
|
|
2041
|
+
url = urljoin(BASE_URL.rstrip("/") + "/", token_url)
|
|
2042
|
+
form = {"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret}
|
|
2043
|
+
if scope:
|
|
2044
|
+
form["scope"] = scope
|
|
2045
|
+
req = urllib.request.Request(
|
|
2046
|
+
url,
|
|
2047
|
+
data=urlencode(form).encode(),
|
|
2048
|
+
headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"},
|
|
2049
|
+
)
|
|
2050
|
+
try:
|
|
2051
|
+
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
2052
|
+
return json.loads(resp.read().decode()).get("access_token")
|
|
2053
|
+
except Exception as exc: # noqa: BLE001 \u2014 report, don't crash collection
|
|
2054
|
+
print(f"loadam: OAuth2 token request to {url} failed: {exc}")
|
|
2055
|
+
return None
|
|
2056
|
+
` : "";
|
|
2057
|
+
const imports = [
|
|
2058
|
+
relevant.some((p) => p.kind === "basic") ? "import base64" : "",
|
|
2059
|
+
usesOAuth ? "import json\nimport urllib.request\nfrom urllib.parse import urlencode, urljoin" : ""
|
|
2060
|
+
].filter(Boolean).join("\n");
|
|
2061
|
+
return `${head}${imports ? `${imports}
|
|
2062
|
+
` : ""}
|
|
2063
|
+
|
|
2064
|
+
${lines.join("\n")}
|
|
2065
|
+
${oauth}
|
|
2066
|
+
|
|
2067
|
+
@schemathesis.auth()
|
|
2068
|
+
class LoadamAuth:
|
|
2069
|
+
"""Applied to every generated request; the ignored_auth check strips it to verify enforcement."""
|
|
2070
|
+
|
|
2071
|
+
def get(self, case, context):
|
|
2072
|
+
return _credentials()
|
|
2073
|
+
|
|
2074
|
+
def set(self, case, data, context):
|
|
2075
|
+
for bucket in ("headers", "query", "cookies"):
|
|
2076
|
+
if data[bucket]:
|
|
2077
|
+
current = getattr(case, bucket) or {}
|
|
2078
|
+
current.update(data[bucket])
|
|
2079
|
+
setattr(case, bucket, current)
|
|
1535
2080
|
`;
|
|
1536
2081
|
}
|
|
1537
|
-
function emitContractTests(
|
|
2082
|
+
function emitContractTests(examples, stateful) {
|
|
2083
|
+
const statefulBlock = stateful ? `
|
|
2084
|
+
|
|
2085
|
+
def test_stateful():
|
|
2086
|
+
"""
|
|
2087
|
+
Chains calls along OpenAPI links (loadam adds them from its resource
|
|
2088
|
+
graph): create \u2192 read \u2192 update \u2192 delete with real ids. Catches
|
|
2089
|
+
use-after-delete and "created but not retrievable" bugs.
|
|
2090
|
+
|
|
2091
|
+
Runs through the Schemathesis CLI engine, which copes with a live
|
|
2092
|
+
server's state changing between sequences.
|
|
2093
|
+
"""
|
|
2094
|
+
cmd = [
|
|
2095
|
+
sys.executable,
|
|
2096
|
+
"-c",
|
|
2097
|
+
"import sys; from schemathesis.cli import schemathesis; sys.exit(schemathesis())",
|
|
2098
|
+
"--config-file", str(CONFIG_PATH),
|
|
2099
|
+
"--no-color",
|
|
2100
|
+
"run", str(SPEC_PATH),
|
|
2101
|
+
"--url", BASE_URL,
|
|
2102
|
+
"--phases", "stateful",
|
|
2103
|
+
"--max-examples", "${examples}",
|
|
2104
|
+
"--seed", "1",
|
|
2105
|
+
]
|
|
2106
|
+
env = {**os.environ, "SCHEMATHESIS_HOOKS": str(HOOKS_PATH)}
|
|
2107
|
+
result = subprocess.run(cmd, env=env, capture_output=True, text=True)
|
|
2108
|
+
if result.returncode != 0:
|
|
2109
|
+
# Fail with Schemathesis' own report only, not this test's source.
|
|
2110
|
+
pytest.fail((result.stdout + result.stderr)[-30000:], pytrace=False)
|
|
2111
|
+
` : "";
|
|
1538
2112
|
return `# AUTO-GENERATED by @loadam/test-contract
|
|
1539
2113
|
"""
|
|
1540
2114
|
Property-based contract tests for every declared operation.
|
|
1541
2115
|
|
|
1542
|
-
Each operation is fuzzed
|
|
1543
|
-
-
|
|
1544
|
-
-
|
|
1545
|
-
-
|
|
2116
|
+
Each operation is fuzzed up to ${examples} times with every Schemathesis check:
|
|
2117
|
+
- no 5xx on any input
|
|
2118
|
+
- status codes, content types, headers and bodies match the spec
|
|
2119
|
+
- invalid input is rejected, valid input is accepted
|
|
2120
|
+
- auth is enforced where the spec declares it
|
|
1546
2121
|
|
|
1547
|
-
|
|
1548
|
-
|
|
2122
|
+
Runs are derandomized: the same spec and server give the same cases, so a
|
|
2123
|
+
failure reproduces. Mutating endpoints are included \u2014 point the suite at a
|
|
2124
|
+
disposable environment, not production.
|
|
1549
2125
|
"""
|
|
2126
|
+
${stateful ? "\nimport os\nimport subprocess\nimport sys\n\nimport pytest\n" : ""}
|
|
2127
|
+
from hypothesis import HealthCheck, settings
|
|
1550
2128
|
|
|
1551
|
-
from
|
|
1552
|
-
|
|
1553
|
-
from conftest import auth_kwargs, schema
|
|
1554
|
-
|
|
1555
|
-
import schemathesis
|
|
2129
|
+
from conftest import ${stateful ? "BASE_URL, CONFIG_PATH, HOOKS_PATH, SPEC_PATH, " : ""}schema
|
|
1556
2130
|
|
|
1557
2131
|
|
|
1558
2132
|
@schema.parametrize()
|
|
1559
|
-
@settings(
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
2133
|
+
@settings(
|
|
2134
|
+
max_examples=${examples},
|
|
2135
|
+
deadline=None,
|
|
2136
|
+
derandomize=True,
|
|
2137
|
+
database=None,
|
|
2138
|
+
suppress_health_check=list(HealthCheck),
|
|
2139
|
+
)
|
|
2140
|
+
def test_contract(case):
|
|
2141
|
+
case.call_and_validate()
|
|
2142
|
+
${statefulBlock}`;
|
|
1564
2143
|
}
|
|
1565
2144
|
function emitReadme(ir, specFileName) {
|
|
1566
2145
|
return `# ${ir.meta.title} \u2014 contract test suite
|
|
1567
2146
|
|
|
1568
|
-
Generated by [loadam](https://github.com/loadam) from your API spec.
|
|
2147
|
+
Generated by [loadam](https://github.com/DesmondSanctity/loadam) from your API spec.
|
|
1569
2148
|
|
|
1570
2149
|
## Run
|
|
1571
2150
|
|
|
@@ -1581,11 +2160,20 @@ cp .env.example .env
|
|
|
1581
2160
|
pytest
|
|
1582
2161
|
\`\`\`
|
|
1583
2162
|
|
|
2163
|
+
Or let loadam run it and keep the results for \`loadam report\`:
|
|
2164
|
+
\`loadam contract <spec> --run\`.
|
|
2165
|
+
|
|
2166
|
+
The suite sends \`POST\`/\`PUT\`/\`PATCH\`/\`DELETE\` requests with generated data.
|
|
2167
|
+
Point it at a disposable environment, not production.
|
|
2168
|
+
|
|
1584
2169
|
## What's in here
|
|
1585
2170
|
|
|
1586
2171
|
- \`${specFileName}\` \u2014 checked-in copy of the spec under test.
|
|
1587
|
-
- \`conftest.py\` \u2014 schema loader
|
|
1588
|
-
- \`
|
|
2172
|
+
- \`conftest.py\` \u2014 schema loader.
|
|
2173
|
+
- \`loadam_hooks.py\` \u2014 env vars and the auth provider.
|
|
2174
|
+
- \`schemathesis.toml\` \u2014 check settings shared by pytest and the CLI.
|
|
2175
|
+
- \`test_contract.py\` \u2014 Schemathesis property-based suite, plus stateful
|
|
2176
|
+
tests chained along OpenAPI links loadam infers from your resources.
|
|
1589
2177
|
|
|
1590
2178
|
## Why contract tests?
|
|
1591
2179
|
|
|
@@ -1605,10 +2193,124 @@ function emitEnvExample(baseUrl, envVars) {
|
|
|
1605
2193
|
return `${lines.join("\n")}
|
|
1606
2194
|
`;
|
|
1607
2195
|
}
|
|
2196
|
+
function apiKeyEnv(p) {
|
|
2197
|
+
return p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
|
|
2198
|
+
}
|
|
1608
2199
|
function slugify(s) {
|
|
1609
2200
|
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
1610
2201
|
}
|
|
1611
2202
|
|
|
2203
|
+
// src/util/config.ts
|
|
2204
|
+
import { existsSync } from "fs";
|
|
2205
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
2206
|
+
import { dirname, join as join2, resolve as resolve4 } from "path";
|
|
2207
|
+
var CONFIG_FILE = "loadam.config.json";
|
|
2208
|
+
async function applyUserConfig(ir, specPath, explicit) {
|
|
2209
|
+
const candidates = explicit ? [resolve4(explicit)] : [resolve4(CONFIG_FILE), join2(dirname(resolve4(specPath)), CONFIG_FILE)];
|
|
2210
|
+
const path = candidates.find((p) => existsSync(p));
|
|
2211
|
+
if (!path) {
|
|
2212
|
+
if (explicit) throw new Error(`Config file not found: ${explicit}`);
|
|
2213
|
+
return null;
|
|
2214
|
+
}
|
|
2215
|
+
let config;
|
|
2216
|
+
try {
|
|
2217
|
+
config = JSON.parse(await readFile4(path, "utf8"));
|
|
2218
|
+
} catch (err) {
|
|
2219
|
+
throw new Error(`${path}: invalid JSON (${err instanceof Error ? err.message : String(err)})`);
|
|
2220
|
+
}
|
|
2221
|
+
try {
|
|
2222
|
+
applyConfig(ir, config);
|
|
2223
|
+
} catch (err) {
|
|
2224
|
+
if (err instanceof ConfigError) throw new Error(`${path}: ${err.message}`);
|
|
2225
|
+
throw err;
|
|
2226
|
+
}
|
|
2227
|
+
return path;
|
|
2228
|
+
}
|
|
2229
|
+
var CONFIG_OPTION_HELP = `corrections for inferred resources/refs (default: ./${CONFIG_FILE} or one next to the spec)`;
|
|
2230
|
+
|
|
2231
|
+
// src/util/pytest.ts
|
|
2232
|
+
import { spawn } from "child_process";
|
|
2233
|
+
import { readFile as readFile5 } from "fs/promises";
|
|
2234
|
+
var PROBE = "import schemathesis, pytest, dotenv; from importlib.metadata import version; print(version('schemathesis'))";
|
|
2235
|
+
async function checkPython(python) {
|
|
2236
|
+
const py = python ?? process.env.LOADAM_PYTHON ?? "python3";
|
|
2237
|
+
const r = await capture(py, ["-c", PROBE]);
|
|
2238
|
+
const version = r.stdout.trim().split("\n").pop() ?? "";
|
|
2239
|
+
if (r.code !== 0)
|
|
2240
|
+
return {
|
|
2241
|
+
python: py,
|
|
2242
|
+
ok: false,
|
|
2243
|
+
detail: r.code === -1 ? `${py} not found` : "schemathesis, pytest or python-dotenv is not importable"
|
|
2244
|
+
};
|
|
2245
|
+
if (!/^4\./.test(version))
|
|
2246
|
+
return { python: py, ok: false, detail: `schemathesis ${version} found, 4.x needed` };
|
|
2247
|
+
return { python: py, ok: true, detail: version };
|
|
2248
|
+
}
|
|
2249
|
+
function runPytest(opts) {
|
|
2250
|
+
return new Promise((done, reject) => {
|
|
2251
|
+
const child = spawn(
|
|
2252
|
+
opts.python,
|
|
2253
|
+
["-m", "pytest", "-q", "-p", "no:cacheprovider", `--junit-xml=${opts.junitPath}`],
|
|
2254
|
+
{
|
|
2255
|
+
cwd: opts.cwd,
|
|
2256
|
+
env: { ...process.env, ...opts.env },
|
|
2257
|
+
stdio: ["ignore", opts.stdout === "stderr" ? 2 : "inherit", "inherit"]
|
|
2258
|
+
}
|
|
2259
|
+
);
|
|
2260
|
+
child.on("error", reject);
|
|
2261
|
+
child.on("close", (code) => done(code ?? 1));
|
|
2262
|
+
});
|
|
2263
|
+
}
|
|
2264
|
+
var MAX_MESSAGE = 4e3;
|
|
2265
|
+
function parseJunit(xml) {
|
|
2266
|
+
const results = { tests: 0, passed: 0, failed: 0, skipped: 0, failures: [] };
|
|
2267
|
+
for (const m of xml.matchAll(/<testcase\b([^>]*?)(\/>|>([\s\S]*?)<\/testcase>)/g)) {
|
|
2268
|
+
const attrs = m[1] ?? "";
|
|
2269
|
+
const body = m[3] ?? "";
|
|
2270
|
+
results.tests++;
|
|
2271
|
+
const name = unescapeXml(attr(attrs, "name") ?? "?");
|
|
2272
|
+
const fail = body.match(/<(failure|error)\b([^>]*?)(?:\/>|>([\s\S]*?)<\/\1>)/);
|
|
2273
|
+
if (fail) {
|
|
2274
|
+
results.failed++;
|
|
2275
|
+
const text = unescapeXml((fail[3] ?? "").trim()) || unescapeXml(attr(fail[2] ?? "", "message") ?? "");
|
|
2276
|
+
results.failures.push({
|
|
2277
|
+
test: name,
|
|
2278
|
+
message: text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}
|
|
2279
|
+
\u2026` : text || void 0
|
|
2280
|
+
});
|
|
2281
|
+
} else if (/<skipped\b/.test(body)) {
|
|
2282
|
+
results.skipped++;
|
|
2283
|
+
} else {
|
|
2284
|
+
results.passed++;
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
return results;
|
|
2288
|
+
}
|
|
2289
|
+
async function readJunit(path) {
|
|
2290
|
+
try {
|
|
2291
|
+
return parseJunit(await readFile5(path, "utf8"));
|
|
2292
|
+
} catch {
|
|
2293
|
+
return null;
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
function attr(attrs, name) {
|
|
2297
|
+
return attrs.match(new RegExp(`\\b${name}="([^"]*)"`))?.[1];
|
|
2298
|
+
}
|
|
2299
|
+
function unescapeXml(s) {
|
|
2300
|
+
return s.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(Number.parseInt(n, 16))).replace(/&/g, "&");
|
|
2301
|
+
}
|
|
2302
|
+
function capture(cmd, args) {
|
|
2303
|
+
return new Promise((done) => {
|
|
2304
|
+
let stdout = "";
|
|
2305
|
+
const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "ignore"] });
|
|
2306
|
+
child.stdout.on("data", (d) => {
|
|
2307
|
+
stdout += d;
|
|
2308
|
+
});
|
|
2309
|
+
child.on("error", () => done({ code: -1, stdout }));
|
|
2310
|
+
child.on("close", (code) => done({ code: code ?? 1, stdout }));
|
|
2311
|
+
});
|
|
2312
|
+
}
|
|
2313
|
+
|
|
1612
2314
|
// src/util/target.ts
|
|
1613
2315
|
function resolveTarget(flag) {
|
|
1614
2316
|
if (typeof flag === "string" && flag.length > 0) return flag;
|
|
@@ -1623,27 +2325,28 @@ function registerContractCommand(program) {
|
|
|
1623
2325
|
"-o, --output <dir>",
|
|
1624
2326
|
"output directory for the generated suite",
|
|
1625
2327
|
"./loadam-out/contract"
|
|
1626
|
-
).option("--target <url>", "override base URL written to conftest.py").option("--examples <n>", "Hypothesis examples per operation", "25").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runContract));
|
|
2328
|
+
).option("--target <url>", "override base URL written to conftest.py").option("--examples <n>", "Hypothesis examples per operation", "25").option("--run", "run the suite with pytest after generating and save the results", false).option("--python <path>", "Python to run the suite with (default: $LOADAM_PYTHON or python3)").option("--config <path>", CONFIG_OPTION_HELP).option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runContract));
|
|
1627
2329
|
}
|
|
1628
2330
|
async function runContract(spec, opts) {
|
|
1629
2331
|
const out = makeOutput(!!opts.json);
|
|
1630
|
-
const specPath =
|
|
2332
|
+
const specPath = resolve5(spec);
|
|
1631
2333
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
1632
2334
|
const ir = await fromOpenApiFile(specPath);
|
|
1633
2335
|
inferResourceGraph(ir);
|
|
2336
|
+
await applyUserConfig(ir, specPath, opts.config);
|
|
1634
2337
|
parseIR(ir);
|
|
1635
|
-
const specSource = await
|
|
2338
|
+
const specSource = await readFile6(specPath, "utf8");
|
|
1636
2339
|
const examples = Number.parseInt(opts.examples ?? "25", 10);
|
|
1637
2340
|
const target = resolveTarget(opts.target);
|
|
1638
2341
|
const result = compileContract(ir, specSource, {
|
|
1639
2342
|
baseUrl: target,
|
|
1640
2343
|
examples: Number.isFinite(examples) ? examples : 25
|
|
1641
2344
|
});
|
|
1642
|
-
const outDir =
|
|
2345
|
+
const outDir = resolve5(opts.output);
|
|
1643
2346
|
await mkdir2(outDir, { recursive: true });
|
|
1644
2347
|
for (const [rel, contents] of Object.entries(result.files)) {
|
|
1645
|
-
const full =
|
|
1646
|
-
await mkdir2(
|
|
2348
|
+
const full = resolve5(outDir, rel);
|
|
2349
|
+
await mkdir2(dirname2(full), { recursive: true });
|
|
1647
2350
|
await writeFile2(full, contents, "utf8");
|
|
1648
2351
|
}
|
|
1649
2352
|
const fileCount = Object.keys(result.files).length;
|
|
@@ -1651,7 +2354,7 @@ async function runContract(spec, opts) {
|
|
|
1651
2354
|
out.info(` ${ir.operations.length} operations to fuzz`);
|
|
1652
2355
|
const session = await createSession({
|
|
1653
2356
|
command: "contract",
|
|
1654
|
-
outRoot:
|
|
2357
|
+
outRoot: resolve5(outDir, ".."),
|
|
1655
2358
|
specPath,
|
|
1656
2359
|
specSource,
|
|
1657
2360
|
ir,
|
|
@@ -1660,26 +2363,79 @@ async function runContract(spec, opts) {
|
|
|
1660
2363
|
envVars: result.envVars ?? [],
|
|
1661
2364
|
flags: {
|
|
1662
2365
|
target: target ?? null,
|
|
1663
|
-
examples
|
|
2366
|
+
examples,
|
|
2367
|
+
run: !!opts.run
|
|
1664
2368
|
},
|
|
1665
2369
|
slug: `contract-${ir.meta.title ?? "run"}`
|
|
1666
2370
|
});
|
|
2371
|
+
const summary = {
|
|
2372
|
+
files: fileCount,
|
|
2373
|
+
operations: ir.operations.length
|
|
2374
|
+
};
|
|
2375
|
+
let exitCode = 0;
|
|
2376
|
+
let ran;
|
|
2377
|
+
if (opts.run) {
|
|
2378
|
+
const py = await checkPython(opts.python);
|
|
2379
|
+
if (!py.ok) {
|
|
2380
|
+
out.info("");
|
|
2381
|
+
out.info(`Can't run the contract suite: ${py.detail}. Skipping run.`);
|
|
2382
|
+
out.info(`Install: ${py.python} -m pip install -e ${opts.output} (or pass --python)`);
|
|
2383
|
+
summary.skipped = py.detail;
|
|
2384
|
+
} else {
|
|
2385
|
+
if (!out.json) {
|
|
2386
|
+
out.step("");
|
|
2387
|
+
out.step(`Running contract suite (schemathesis ${py.detail})...`);
|
|
2388
|
+
}
|
|
2389
|
+
const junitPath = join3(session.dir, "contract-junit.xml");
|
|
2390
|
+
const code = await runPytest({
|
|
2391
|
+
python: py.python,
|
|
2392
|
+
cwd: outDir,
|
|
2393
|
+
junitPath,
|
|
2394
|
+
env: target ? { BASE_URL: target } : void 0,
|
|
2395
|
+
stdout: out.json ? "stderr" : "inherit"
|
|
2396
|
+
});
|
|
2397
|
+
const results = await readJunit(junitPath);
|
|
2398
|
+
if (results) {
|
|
2399
|
+
session.registerArtefact("contract-junit.xml");
|
|
2400
|
+
await session.addArtefact(
|
|
2401
|
+
"contract-failures.json",
|
|
2402
|
+
JSON.stringify(results.failures, null, 2)
|
|
2403
|
+
);
|
|
2404
|
+
ran = {
|
|
2405
|
+
tests: results.tests,
|
|
2406
|
+
passed: results.passed,
|
|
2407
|
+
failed: results.failed,
|
|
2408
|
+
skipped: results.skipped
|
|
2409
|
+
};
|
|
2410
|
+
Object.assign(summary, ran);
|
|
2411
|
+
}
|
|
2412
|
+
exitCode = code;
|
|
2413
|
+
if (code !== 0 && code !== 1)
|
|
2414
|
+
out.info(`pytest exited with code ${code}; the suite did not run cleanly.`);
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
1667
2417
|
await session.finalize({
|
|
1668
|
-
exitCode
|
|
2418
|
+
exitCode,
|
|
1669
2419
|
thresholds: { passed: [], failed: [] },
|
|
1670
|
-
summary
|
|
1671
|
-
files: fileCount,
|
|
1672
|
-
operations: ir.operations.length
|
|
1673
|
-
}
|
|
2420
|
+
summary
|
|
1674
2421
|
});
|
|
1675
2422
|
if (!out.json) {
|
|
1676
2423
|
out.info(` Session: ${session.id}`);
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
2424
|
+
if (ran) {
|
|
2425
|
+
out.step("");
|
|
2426
|
+
out.step(
|
|
2427
|
+
`Contract tests: ${ran.passed} passed \xB7 ${ran.failed} failed${ran.skipped ? ` \xB7 ${ran.skipped} skipped` : ""}`
|
|
2428
|
+
);
|
|
2429
|
+
out.step(" loadam report latest --open # failures with repro details");
|
|
2430
|
+
} else if (!opts.run) {
|
|
2431
|
+
out.step("");
|
|
2432
|
+
out.step("Next steps:");
|
|
2433
|
+
out.step(` cd ${opts.output}`);
|
|
2434
|
+
out.step(" python -m venv .venv && source .venv/bin/activate");
|
|
2435
|
+
out.step(" pip install -e .");
|
|
2436
|
+
out.step(" pytest");
|
|
2437
|
+
out.step("Or let loadam run it and archive the results: loadam contract <spec> --run");
|
|
2438
|
+
}
|
|
1683
2439
|
}
|
|
1684
2440
|
out.result({
|
|
1685
2441
|
command: "contract",
|
|
@@ -1687,13 +2443,15 @@ async function runContract(spec, opts) {
|
|
|
1687
2443
|
files: fileCount,
|
|
1688
2444
|
operations: ir.operations.length,
|
|
1689
2445
|
envVars: result.envVars,
|
|
1690
|
-
sessionId: session.id
|
|
2446
|
+
sessionId: session.id,
|
|
2447
|
+
...ran ? { results: ran } : {}
|
|
1691
2448
|
});
|
|
2449
|
+
if (exitCode !== 0) process.exitCode = 1;
|
|
1692
2450
|
}
|
|
1693
2451
|
|
|
1694
2452
|
// src/commands/diff.ts
|
|
1695
|
-
import { readFile as
|
|
1696
|
-
import { resolve as
|
|
2453
|
+
import { readFile as readFile7, writeFile as writeFile3 } from "fs/promises";
|
|
2454
|
+
import { resolve as resolve6 } from "path";
|
|
1697
2455
|
|
|
1698
2456
|
// ../test-drift/dist/index.js
|
|
1699
2457
|
import Ajv from "ajv";
|
|
@@ -1731,7 +2489,7 @@ function compareProbes(input) {
|
|
|
1731
2489
|
continue;
|
|
1732
2490
|
}
|
|
1733
2491
|
const ct = probe.contentType ?? Object.keys(declared.contentTypes)[0];
|
|
1734
|
-
const media = ct ? declared.contentTypes
|
|
2492
|
+
const media = ct ? matchMediaType(declared.contentTypes, ct) : void 0;
|
|
1735
2493
|
if (!media) {
|
|
1736
2494
|
findings.push({
|
|
1737
2495
|
operationId: op.id,
|
|
@@ -1758,6 +2516,13 @@ function compareProbes(input) {
|
|
|
1758
2516
|
}
|
|
1759
2517
|
return findings;
|
|
1760
2518
|
}
|
|
2519
|
+
function matchMediaType(declared, received) {
|
|
2520
|
+
if (declared[received]) return declared[received];
|
|
2521
|
+
const base = (t) => t.split(";")[0].trim().toLowerCase();
|
|
2522
|
+
const want = base(received);
|
|
2523
|
+
const key = Object.keys(declared).find((k) => base(k) === want);
|
|
2524
|
+
return key ? declared[key] : void 0;
|
|
2525
|
+
}
|
|
1761
2526
|
function pickResponseFor(op, status) {
|
|
1762
2527
|
const exact = op.responses.find((r) => r.status === status);
|
|
1763
2528
|
if (exact) return exact;
|
|
@@ -1816,58 +2581,189 @@ async function probeOperations(ir, opts) {
|
|
|
1816
2581
|
const skipped = [];
|
|
1817
2582
|
const safeOnly = opts.safeOnly ?? true;
|
|
1818
2583
|
const timeout = opts.timeoutMs ?? 5e3;
|
|
2584
|
+
const overrides = opts.pathParams ?? {};
|
|
2585
|
+
const ids = new IdPool();
|
|
2586
|
+
const idFields = new Map(ir.resources.kinds.map((k) => [k.name, k.idField]));
|
|
2587
|
+
let pending = [];
|
|
1819
2588
|
for (const op of ir.operations) {
|
|
1820
2589
|
if (safeOnly && !isSafeMethod(op.method)) {
|
|
1821
|
-
skipped.push({
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
});
|
|
1825
|
-
continue;
|
|
2590
|
+
skipped.push({ operationId: op.id, reason: `mutating ${op.method} skipped (safe-only)` });
|
|
2591
|
+
} else {
|
|
2592
|
+
pending.push(op);
|
|
1826
2593
|
}
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
2594
|
+
}
|
|
2595
|
+
pending.sort((a, b) => requiredPathParams(a).length - requiredPathParams(b).length);
|
|
2596
|
+
while (pending.length > 0) {
|
|
2597
|
+
const ready = [];
|
|
2598
|
+
const waiting = [];
|
|
2599
|
+
for (const op of pending) {
|
|
2600
|
+
const values = resolvePathParams(op, overrides, ids);
|
|
2601
|
+
if (values) ready.push({ op, values });
|
|
2602
|
+
else waiting.push(op);
|
|
1831
2603
|
}
|
|
1832
|
-
|
|
1833
|
-
const
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
2604
|
+
if (ready.length === 0) {
|
|
2605
|
+
for (const op of waiting) {
|
|
2606
|
+
const missing = requiredPathParams(op).filter(
|
|
2607
|
+
(p) => overrides[p.name] === void 0 && !(p.resourceKind && ids.has(p.resourceKind))
|
|
2608
|
+
).map((p) => p.name);
|
|
2609
|
+
skipped.push({
|
|
2610
|
+
operationId: op.id,
|
|
2611
|
+
reason: `no value for path param ${missing.join(", ")} (none discovered; pass --path-param)`
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
break;
|
|
2615
|
+
}
|
|
2616
|
+
for (const { op, values } of ready) {
|
|
2617
|
+
const url = buildUrl(opts.baseUrl, op, values, [
|
|
2618
|
+
...requiredQuery(ir, op),
|
|
2619
|
+
...Object.entries(opts.query ?? {})
|
|
2620
|
+
]);
|
|
2621
|
+
try {
|
|
2622
|
+
const ac = new AbortController();
|
|
2623
|
+
const timer = setTimeout(() => ac.abort(), timeout);
|
|
2624
|
+
const resp = await fetch(url, {
|
|
2625
|
+
method: op.method,
|
|
2626
|
+
headers: opts.headers ?? {},
|
|
2627
|
+
signal: ac.signal
|
|
2628
|
+
});
|
|
2629
|
+
clearTimeout(timer);
|
|
2630
|
+
const ct = resp.headers.get("content-type") ?? void 0;
|
|
2631
|
+
const body = await readBody(resp, ct);
|
|
2632
|
+
probes.push({
|
|
2633
|
+
operationId: op.id,
|
|
2634
|
+
status: resp.status,
|
|
2635
|
+
contentType: ct ? ct.split(";")[0].trim() : void 0,
|
|
2636
|
+
body
|
|
2637
|
+
});
|
|
2638
|
+
if (resp.ok && op.resourceKind) {
|
|
2639
|
+
ids.harvest(op.resourceKind, body, idFields.get(op.resourceKind));
|
|
2640
|
+
}
|
|
2641
|
+
} catch (err) {
|
|
2642
|
+
skipped.push({
|
|
2643
|
+
operationId: op.id,
|
|
2644
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
2645
|
+
});
|
|
2646
|
+
}
|
|
1854
2647
|
}
|
|
2648
|
+
pending = waiting;
|
|
1855
2649
|
}
|
|
1856
2650
|
return { probes, skipped };
|
|
1857
2651
|
}
|
|
1858
2652
|
function isSafeMethod(method) {
|
|
1859
2653
|
return method === "GET" || method === "HEAD" || method === "OPTIONS";
|
|
1860
2654
|
}
|
|
1861
|
-
function
|
|
1862
|
-
|
|
2655
|
+
function requiredPathParams(op) {
|
|
2656
|
+
return op.pathParams.filter((p) => p.required);
|
|
2657
|
+
}
|
|
2658
|
+
function resolvePathParams(op, overrides, ids) {
|
|
2659
|
+
const values = {};
|
|
1863
2660
|
for (const p of op.pathParams) {
|
|
1864
|
-
const v =
|
|
1865
|
-
if (v === void 0
|
|
1866
|
-
|
|
1867
|
-
|
|
2661
|
+
const v = overrides[p.name] ?? (p.resourceKind ? ids.first(p.resourceKind) : void 0);
|
|
2662
|
+
if (v === void 0) {
|
|
2663
|
+
if (p.required) return void 0;
|
|
2664
|
+
continue;
|
|
2665
|
+
}
|
|
2666
|
+
values[p.name] = v;
|
|
2667
|
+
}
|
|
2668
|
+
return values;
|
|
2669
|
+
}
|
|
2670
|
+
var IdPool = class {
|
|
2671
|
+
byKind = /* @__PURE__ */ new Map();
|
|
2672
|
+
has(kind) {
|
|
2673
|
+
return (this.byKind.get(kind)?.length ?? 0) > 0;
|
|
2674
|
+
}
|
|
2675
|
+
first(kind) {
|
|
2676
|
+
return this.byKind.get(kind)?.[0];
|
|
2677
|
+
}
|
|
2678
|
+
/** Pull ids out of a list or single-entity response, through `{ data }`-style envelopes. */
|
|
2679
|
+
harvest(kind, body, idField) {
|
|
2680
|
+
const fields = [idField, "id", "uuid"].filter((f) => !!f);
|
|
2681
|
+
const scalar = (v) => typeof v === "string" && v !== "" || typeof v === "number";
|
|
2682
|
+
const idOf = (obj) => {
|
|
2683
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) return void 0;
|
|
2684
|
+
const rec = obj;
|
|
2685
|
+
for (const f of fields) {
|
|
2686
|
+
if (scalar(rec[f])) return rec[f];
|
|
2687
|
+
}
|
|
2688
|
+
for (const f of ["url", "href", "self"]) {
|
|
2689
|
+
const v = rec[f];
|
|
2690
|
+
if (typeof v === "string") {
|
|
2691
|
+
const seg = lastSegment(v);
|
|
2692
|
+
if (seg !== void 0) return seg;
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
for (const f of ["name", "slug"]) {
|
|
2696
|
+
if (scalar(rec[f])) return rec[f];
|
|
2697
|
+
}
|
|
2698
|
+
return void 0;
|
|
2699
|
+
};
|
|
2700
|
+
let entities = [];
|
|
2701
|
+
if (Array.isArray(body)) entities = body;
|
|
2702
|
+
else if (idOf(body) !== void 0) entities = [body];
|
|
2703
|
+
else if (body && typeof body === "object") {
|
|
2704
|
+
const values = Object.values(body);
|
|
2705
|
+
const arr = values.find(Array.isArray);
|
|
2706
|
+
if (arr) entities = arr;
|
|
2707
|
+
else {
|
|
2708
|
+
const inner = values.find((v) => idOf(v) !== void 0);
|
|
2709
|
+
if (inner) entities = [inner];
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
const list = this.byKind.get(kind) ?? [];
|
|
2713
|
+
for (const e of entities) {
|
|
2714
|
+
const id = idOf(e);
|
|
2715
|
+
if (id !== void 0 && !list.includes(id)) list.push(id);
|
|
1868
2716
|
}
|
|
2717
|
+
if (list.length > 0) this.byKind.set(kind, list);
|
|
2718
|
+
}
|
|
2719
|
+
};
|
|
2720
|
+
function lastSegment(url) {
|
|
2721
|
+
const segs = url.split(/[?#]/)[0].split("/").filter(Boolean);
|
|
2722
|
+
return segs.length > 1 ? decodeURIComponent(segs[segs.length - 1]) : void 0;
|
|
2723
|
+
}
|
|
2724
|
+
function buildUrl(base, op, values, query) {
|
|
2725
|
+
let path = op.path;
|
|
2726
|
+
for (const [name, v] of Object.entries(values)) {
|
|
2727
|
+
path = path.split(`{${name}}`).join(encodeURIComponent(String(v)));
|
|
2728
|
+
}
|
|
2729
|
+
const qs = query.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
|
|
2730
|
+
return base.replace(/\/$/, "") + path + (qs ? `?${qs}` : "");
|
|
2731
|
+
}
|
|
2732
|
+
function requiredQuery(ir, op) {
|
|
2733
|
+
const out = [];
|
|
2734
|
+
for (const p of op.queryParams) {
|
|
2735
|
+
if (!p.required) continue;
|
|
2736
|
+
const v = sampleValue(ir, p);
|
|
2737
|
+
for (const one of Array.isArray(v) ? v : [v]) out.push([p.name, String(one)]);
|
|
2738
|
+
}
|
|
2739
|
+
return out;
|
|
2740
|
+
}
|
|
2741
|
+
function sampleValue(ir, p) {
|
|
2742
|
+
if (p.examples && p.examples.length > 0) return p.examples[0];
|
|
2743
|
+
const s = resolveSchema(ir, p.schema);
|
|
2744
|
+
return fromSchema(ir, s);
|
|
2745
|
+
}
|
|
2746
|
+
function resolveSchema(ir, schema) {
|
|
2747
|
+
if (typeof schema === "string") return ir.schemas[schema]?.jsonSchema ?? {};
|
|
2748
|
+
const js = schema && typeof schema === "object" && "jsonSchema" in schema ? schema.jsonSchema : schema;
|
|
2749
|
+
if (js?.$ref) return ir.schemas[js.$ref]?.jsonSchema ?? {};
|
|
2750
|
+
return js ?? {};
|
|
2751
|
+
}
|
|
2752
|
+
function fromSchema(ir, s) {
|
|
2753
|
+
if (s.example !== void 0) return s.example;
|
|
2754
|
+
if (s.default !== void 0) return s.default;
|
|
2755
|
+
if (s.enum && s.enum.length > 0) return s.enum[0];
|
|
2756
|
+
switch (s.type) {
|
|
2757
|
+
case "array":
|
|
2758
|
+
return [fromSchema(ir, resolveSchema(ir, s.items ?? {}))];
|
|
2759
|
+
case "integer":
|
|
2760
|
+
case "number":
|
|
2761
|
+
return 1;
|
|
2762
|
+
case "boolean":
|
|
2763
|
+
return true;
|
|
2764
|
+
default:
|
|
2765
|
+
return s.format === "date" ? "2024-01-01" : s.format === "date-time" ? "2024-01-01T00:00:00Z" : "test";
|
|
1869
2766
|
}
|
|
1870
|
-
return base.replace(/\/$/, "") + path;
|
|
1871
2767
|
}
|
|
1872
2768
|
async function readBody(resp, ct) {
|
|
1873
2769
|
const text = await resp.text();
|
|
@@ -1941,10 +2837,90 @@ function severityBadge(s) {
|
|
|
1941
2837
|
if (s === "warning") return "\u26A0\uFE0F warning";
|
|
1942
2838
|
return "\u2139\uFE0F info";
|
|
1943
2839
|
}
|
|
2840
|
+
function apiKeyEnv2(p) {
|
|
2841
|
+
return p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
|
|
2842
|
+
}
|
|
2843
|
+
function resolveTokenUrl(tokenUrl, baseUrl) {
|
|
2844
|
+
if (/^https?:\/\//i.test(tokenUrl)) return tokenUrl;
|
|
2845
|
+
const base = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
|
|
2846
|
+
return new URL(tokenUrl.startsWith("/") ? tokenUrl : tokenUrl, base).toString();
|
|
2847
|
+
}
|
|
2848
|
+
async function resolveAuth(ir, env, baseUrl, fetchImpl = fetch) {
|
|
2849
|
+
const out = { headers: {}, query: {}, missing: [], notes: [] };
|
|
2850
|
+
const need = (name) => {
|
|
2851
|
+
const v = env[name];
|
|
2852
|
+
if (!v) out.missing.push(name);
|
|
2853
|
+
return v;
|
|
2854
|
+
};
|
|
2855
|
+
for (const p of ir.auth) {
|
|
2856
|
+
switch (p.kind) {
|
|
2857
|
+
case "bearer": {
|
|
2858
|
+
const token = need(p.tokenEnv ?? "API_TOKEN");
|
|
2859
|
+
if (token) out.headers.Authorization = `Bearer ${token}`;
|
|
2860
|
+
break;
|
|
2861
|
+
}
|
|
2862
|
+
case "apiKey": {
|
|
2863
|
+
const value = need(apiKeyEnv2(p));
|
|
2864
|
+
if (!value) break;
|
|
2865
|
+
if (p.in === "header") out.headers[p.name] = value;
|
|
2866
|
+
else if (p.in === "query") out.query[p.name] = value;
|
|
2867
|
+
else {
|
|
2868
|
+
const prev = out.headers.Cookie ? `${out.headers.Cookie}; ` : "";
|
|
2869
|
+
out.headers.Cookie = `${prev}${p.name}=${encodeURIComponent(value)}`;
|
|
2870
|
+
}
|
|
2871
|
+
break;
|
|
2872
|
+
}
|
|
2873
|
+
case "basic": {
|
|
2874
|
+
const u = need(p.userEnv ?? "API_USER");
|
|
2875
|
+
const pw = need(p.passEnv ?? "API_PASS");
|
|
2876
|
+
if (u && pw)
|
|
2877
|
+
out.headers.Authorization = `Basic ${Buffer.from(`${u}:${pw}`).toString("base64")}`;
|
|
2878
|
+
break;
|
|
2879
|
+
}
|
|
2880
|
+
case "oauth2_cc": {
|
|
2881
|
+
const id = need(p.clientIdEnv);
|
|
2882
|
+
const secret = need(p.clientSecretEnv);
|
|
2883
|
+
if (!id || !secret) break;
|
|
2884
|
+
const url = resolveTokenUrl(p.tokenUrl, baseUrl);
|
|
2885
|
+
const body = new URLSearchParams({
|
|
2886
|
+
grant_type: "client_credentials",
|
|
2887
|
+
client_id: id,
|
|
2888
|
+
client_secret: secret
|
|
2889
|
+
});
|
|
2890
|
+
if (p.scopes?.length) body.set("scope", p.scopes.join(" "));
|
|
2891
|
+
try {
|
|
2892
|
+
const resp = await fetchImpl(url, {
|
|
2893
|
+
method: "POST",
|
|
2894
|
+
headers: {
|
|
2895
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
2896
|
+
accept: "application/json"
|
|
2897
|
+
},
|
|
2898
|
+
body
|
|
2899
|
+
});
|
|
2900
|
+
const json = await resp.json().catch(() => ({}));
|
|
2901
|
+
if (resp.ok && json.access_token)
|
|
2902
|
+
out.headers.Authorization = `Bearer ${json.access_token}`;
|
|
2903
|
+
else out.notes.push(`OAuth2 token request to ${url} failed (${resp.status}).`);
|
|
2904
|
+
} catch (err) {
|
|
2905
|
+
out.notes.push(
|
|
2906
|
+
`OAuth2 token request to ${url} failed: ${err instanceof Error ? err.message : String(err)}`
|
|
2907
|
+
);
|
|
2908
|
+
}
|
|
2909
|
+
break;
|
|
2910
|
+
}
|
|
2911
|
+
default:
|
|
2912
|
+
break;
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
return out;
|
|
2916
|
+
}
|
|
1944
2917
|
|
|
1945
2918
|
// src/commands/diff.ts
|
|
1946
2919
|
function registerDiffCommand(program) {
|
|
1947
|
-
program.command("diff").description("Probe a live API and report drift against the spec (Markdown).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("--target <url>", "base URL of the live API (or set LOADAM_TARGET)").option("-o, --output <path>", "write report to this file (otherwise stdout)").option("--timeout-ms <n>", "per-request timeout", "5000").option("--mutating", "also probe mutating ops (DANGEROUS \u2014 not for prod)", false).option("-H, --header <kv...>", 'additional headers, repeatable, "Name: value" form').option(
|
|
2920
|
+
program.command("diff").description("Probe a live API and report drift against the spec (Markdown).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("--target <url>", "base URL of the live API (or set LOADAM_TARGET)").option("-o, --output <path>", "write report to this file (otherwise stdout)").option("--timeout-ms <n>", "per-request timeout", "5000").option("--mutating", "also probe mutating ops (DANGEROUS \u2014 not for prod)", false).option("-H, --header <kv...>", 'additional headers, repeatable, "Name: value" form').option(
|
|
2921
|
+
"--path-param <kv...>",
|
|
2922
|
+
'path-param values (override ids discovered from list responses), repeatable, "name=value" form'
|
|
2923
|
+
).option("--fail-on <severity>", "exit non-zero when findings of this severity exist", "error").option("--config <path>", CONFIG_OPTION_HELP).option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runDiff));
|
|
1948
2924
|
}
|
|
1949
2925
|
async function runDiff(spec, opts) {
|
|
1950
2926
|
const out = makeOutput(!!opts.json);
|
|
@@ -1952,19 +2928,28 @@ async function runDiff(spec, opts) {
|
|
|
1952
2928
|
if (!target) {
|
|
1953
2929
|
throw new Error("--target is required (or set LOADAM_TARGET env var)");
|
|
1954
2930
|
}
|
|
1955
|
-
const specPath =
|
|
2931
|
+
const specPath = resolve6(spec);
|
|
1956
2932
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
1957
|
-
const specSource = await
|
|
2933
|
+
const specSource = await readFile7(specPath, "utf8");
|
|
1958
2934
|
const ir = await fromOpenApiFile(specPath);
|
|
1959
2935
|
inferResourceGraph(ir);
|
|
2936
|
+
await applyUserConfig(ir, specPath, opts.config);
|
|
1960
2937
|
parseIR(ir);
|
|
1961
2938
|
const headers = parseKvPairs(opts.header ?? [], ":");
|
|
1962
2939
|
const pathParams = parseKvPairs(opts.pathParam ?? [], "=");
|
|
1963
2940
|
const timeoutMs = Number.parseInt(opts.timeoutMs ?? "5000", 10);
|
|
2941
|
+
const auth = await resolveAuth(ir, process.env, target);
|
|
2942
|
+
for (const note of auth.notes) out.info(note);
|
|
2943
|
+
if (auth.missing.length > 0) {
|
|
2944
|
+
out.info(
|
|
2945
|
+
`Auth env vars not set: ${auth.missing.join(", ")} \u2014 protected endpoints may return 401.`
|
|
2946
|
+
);
|
|
2947
|
+
}
|
|
1964
2948
|
out.start(`Probing ${ir.operations.length} operations on ${target}\u2026`);
|
|
1965
2949
|
const { probes, skipped } = await probeOperations(ir, {
|
|
1966
2950
|
baseUrl: target,
|
|
1967
|
-
headers,
|
|
2951
|
+
headers: { ...auth.headers, ...headers },
|
|
2952
|
+
query: auth.query,
|
|
1968
2953
|
pathParams,
|
|
1969
2954
|
timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : 5e3,
|
|
1970
2955
|
safeOnly: !opts.mutating
|
|
@@ -1973,7 +2958,7 @@ async function runDiff(spec, opts) {
|
|
|
1973
2958
|
const counts = countBySeverity(findings);
|
|
1974
2959
|
const session = await createSession({
|
|
1975
2960
|
command: "diff",
|
|
1976
|
-
outRoot:
|
|
2961
|
+
outRoot: resolve6("./loadam-out"),
|
|
1977
2962
|
specPath,
|
|
1978
2963
|
specSource,
|
|
1979
2964
|
ir,
|
|
@@ -2003,7 +2988,7 @@ async function runDiff(spec, opts) {
|
|
|
2003
2988
|
);
|
|
2004
2989
|
if (!out.json) {
|
|
2005
2990
|
if (opts.output) {
|
|
2006
|
-
const outFile =
|
|
2991
|
+
const outFile = resolve6(opts.output);
|
|
2007
2992
|
await writeFile3(outFile, report, "utf8");
|
|
2008
2993
|
out.success(`Wrote drift report to ${outFile}`);
|
|
2009
2994
|
} else {
|
|
@@ -2014,7 +2999,7 @@ async function runDiff(spec, opts) {
|
|
|
2014
2999
|
);
|
|
2015
3000
|
out.info(` Session: ${session.id}`);
|
|
2016
3001
|
} else if (opts.output) {
|
|
2017
|
-
await writeFile3(
|
|
3002
|
+
await writeFile3(resolve6(opts.output), report, "utf8");
|
|
2018
3003
|
}
|
|
2019
3004
|
const failOn = opts.failOn ?? "error";
|
|
2020
3005
|
const failed = failOn === "error" && counts.error > 0 || failOn === "warning" && counts.error + counts.warning > 0;
|
|
@@ -2037,7 +3022,7 @@ async function runDiff(spec, opts) {
|
|
|
2037
3022
|
skipped: skipped.length,
|
|
2038
3023
|
findings: findings.length,
|
|
2039
3024
|
counts,
|
|
2040
|
-
reportPath: opts.output ?
|
|
3025
|
+
reportPath: opts.output ? resolve6(opts.output) : null,
|
|
2041
3026
|
failOn,
|
|
2042
3027
|
failed,
|
|
2043
3028
|
sessionId: session.id
|
|
@@ -2057,13 +3042,13 @@ function parseKvPairs(values, sep) {
|
|
|
2057
3042
|
}
|
|
2058
3043
|
|
|
2059
3044
|
// src/commands/history.ts
|
|
2060
|
-
import { resolve as
|
|
3045
|
+
import { resolve as resolve7 } from "path";
|
|
2061
3046
|
function registerHistoryCommand(program) {
|
|
2062
3047
|
program.command("history").description("List archived loadam sessions (newest first).").option("--root <dir>", "session archive root", "./loadam-out").option("--limit <n>", "show at most N sessions", "20").option("--command <cmd>", "filter by command (test|contract|diff)").option("--json", "emit a JSON array on stdout", false).action(withFriendlyErrors(runHistory));
|
|
2063
3048
|
}
|
|
2064
3049
|
async function runHistory(opts) {
|
|
2065
3050
|
const out = makeOutput(!!opts.json);
|
|
2066
|
-
const root =
|
|
3051
|
+
const root = resolve7(opts.root);
|
|
2067
3052
|
const limit = Number.parseInt(opts.limit ?? "20", 10);
|
|
2068
3053
|
const all = await listSessions(root);
|
|
2069
3054
|
const filtered = opts.command ? all.filter((s) => s.command === opts.command) : all;
|
|
@@ -2091,18 +3076,19 @@ async function runHistory(opts) {
|
|
|
2091
3076
|
|
|
2092
3077
|
// src/commands/init.ts
|
|
2093
3078
|
import { writeFile as writeFile4 } from "fs/promises";
|
|
2094
|
-
import { resolve as
|
|
3079
|
+
import { resolve as resolve8 } from "path";
|
|
2095
3080
|
function registerInitCommand(program) {
|
|
2096
|
-
program.command("init").description("Parse a spec and emit loadam.ir.json with inferred resource graph").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <path>", "output path for IR JSON", "./loadam.ir.json").option("--no-tree", "skip printing the resource-graph tree").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runInit));
|
|
3081
|
+
program.command("init").description("Parse a spec and emit loadam.ir.json with inferred resource graph").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <path>", "output path for IR JSON", "./loadam.ir.json").option("--no-tree", "skip printing the resource-graph tree").option("--config <path>", CONFIG_OPTION_HELP).option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runInit));
|
|
2097
3082
|
}
|
|
2098
3083
|
async function runInit(spec, opts) {
|
|
2099
3084
|
const out = makeOutput(!!opts.json);
|
|
2100
|
-
const specPath =
|
|
3085
|
+
const specPath = resolve8(spec);
|
|
2101
3086
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
2102
3087
|
const ir = await fromOpenApiFile(specPath);
|
|
2103
3088
|
inferResourceGraph(ir);
|
|
3089
|
+
await applyUserConfig(ir, specPath, opts.config);
|
|
2104
3090
|
parseIR(ir);
|
|
2105
|
-
const outPath =
|
|
3091
|
+
const outPath = resolve8(opts.output);
|
|
2106
3092
|
await writeFile4(outPath, `${JSON.stringify(ir, null, 2)}
|
|
2107
3093
|
`, "utf8");
|
|
2108
3094
|
const stats = graphStats(ir.resources);
|
|
@@ -2128,7 +3114,7 @@ async function runInit(spec, opts) {
|
|
|
2128
3114
|
|
|
2129
3115
|
// src/commands/mcp.ts
|
|
2130
3116
|
import { mkdir as mkdir3, writeFile as writeFile5 } from "fs/promises";
|
|
2131
|
-
import { dirname as
|
|
3117
|
+
import { dirname as dirname3, resolve as resolve9 } from "path";
|
|
2132
3118
|
|
|
2133
3119
|
// ../mcp/dist/index.js
|
|
2134
3120
|
function emitAuth(ir) {
|
|
@@ -2199,23 +3185,23 @@ function buildTool(ir, op) {
|
|
|
2199
3185
|
const properties = {};
|
|
2200
3186
|
const required = [];
|
|
2201
3187
|
for (const p of op.pathParams) {
|
|
2202
|
-
properties[p.name] = annotate(
|
|
3188
|
+
properties[p.name] = annotate(resolveSchema2(ir, p.schema), p);
|
|
2203
3189
|
required.push(p.name);
|
|
2204
3190
|
}
|
|
2205
3191
|
for (const p of op.queryParams) {
|
|
2206
|
-
properties[p.name] = annotate(
|
|
3192
|
+
properties[p.name] = annotate(resolveSchema2(ir, p.schema), p);
|
|
2207
3193
|
if (p.required) required.push(p.name);
|
|
2208
3194
|
}
|
|
2209
3195
|
for (const p of op.headerParams) {
|
|
2210
3196
|
if (isAuthHeader(p.name)) continue;
|
|
2211
|
-
properties[p.name] = annotate(
|
|
3197
|
+
properties[p.name] = annotate(resolveSchema2(ir, p.schema), p);
|
|
2212
3198
|
if (p.required) required.push(p.name);
|
|
2213
3199
|
}
|
|
2214
3200
|
let hasBody = false;
|
|
2215
3201
|
if (op.body) {
|
|
2216
3202
|
const json = op.body.contentTypes["application/json"];
|
|
2217
3203
|
if (json) {
|
|
2218
|
-
properties.body =
|
|
3204
|
+
properties.body = resolveSchema2(ir, json.schema);
|
|
2219
3205
|
if (op.body.required) required.push("body");
|
|
2220
3206
|
hasBody = true;
|
|
2221
3207
|
}
|
|
@@ -2241,7 +3227,7 @@ function buildTool(ir, op) {
|
|
|
2241
3227
|
}
|
|
2242
3228
|
};
|
|
2243
3229
|
}
|
|
2244
|
-
function
|
|
3230
|
+
function resolveSchema2(ir, ref) {
|
|
2245
3231
|
if (typeof ref === "string") {
|
|
2246
3232
|
const found = ir.schemas[ref];
|
|
2247
3233
|
if (found) return cloneJson(found.jsonSchema);
|
|
@@ -2300,6 +3286,7 @@ function emitPackageJson(ctx) {
|
|
|
2300
3286
|
function emitBinJs(_ctx) {
|
|
2301
3287
|
return `#!/usr/bin/env node
|
|
2302
3288
|
// AUTO-GENERATED by @loadam/mcp
|
|
3289
|
+
import './env.js'; // must stay first: server.js reads process.env at import time
|
|
2303
3290
|
import { buildServer } from './server.js';
|
|
2304
3291
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
2305
3292
|
|
|
@@ -2534,6 +3521,31 @@ export async function invokeTool(tool, args) {
|
|
|
2534
3521
|
}
|
|
2535
3522
|
`;
|
|
2536
3523
|
}
|
|
3524
|
+
function emitEnvJs(_ctx) {
|
|
3525
|
+
return `// AUTO-GENERATED by @loadam/mcp
|
|
3526
|
+
import { readFileSync } from 'node:fs';
|
|
3527
|
+
import { dirname, join } from 'node:path';
|
|
3528
|
+
import { fileURLToPath } from 'node:url';
|
|
3529
|
+
|
|
3530
|
+
const path = join(dirname(fileURLToPath(import.meta.url)), '.env');
|
|
3531
|
+
let text = '';
|
|
3532
|
+
try {
|
|
3533
|
+
text = readFileSync(path, 'utf8');
|
|
3534
|
+
} catch {
|
|
3535
|
+
// No .env \u2014 rely on the environment.
|
|
3536
|
+
}
|
|
3537
|
+
for (const raw of text.split(/\\r?\\n/)) {
|
|
3538
|
+
const line = raw.trim();
|
|
3539
|
+
if (!line || line.startsWith('#')) continue;
|
|
3540
|
+
const eq = line.indexOf('=');
|
|
3541
|
+
if (eq <= 0) continue;
|
|
3542
|
+
const key = line.slice(0, eq).trim();
|
|
3543
|
+
let value = line.slice(eq + 1).trim();
|
|
3544
|
+
if (/^(['"]).*\\1$/.test(value)) value = value.slice(1, -1);
|
|
3545
|
+
if (process.env[key] === undefined || process.env[key] === '') process.env[key] = value;
|
|
3546
|
+
}
|
|
3547
|
+
`;
|
|
3548
|
+
}
|
|
2537
3549
|
function emitEnvExample2(ctx) {
|
|
2538
3550
|
const lines = [
|
|
2539
3551
|
"# Generated by loadam \u2014 copy to .env or export in your shell.",
|
|
@@ -2554,7 +3566,7 @@ ${ctx.auth.notes.map((n) => `- ${n}`).join("\n")}
|
|
|
2554
3566
|
` : "";
|
|
2555
3567
|
return `# ${ctx.ir.meta.title} \u2014 MCP server
|
|
2556
3568
|
|
|
2557
|
-
Generated by [loadam](https://github.com/loadam) from your API spec.
|
|
3569
|
+
Generated by [loadam](https://github.com/DesmondSanctity/loadam) from your API spec.
|
|
2558
3570
|
|
|
2559
3571
|
${writesNote}
|
|
2560
3572
|
|
|
@@ -2617,6 +3629,7 @@ function compileMcp(ir, opts = {}) {
|
|
|
2617
3629
|
const files = {
|
|
2618
3630
|
"package.json": emitPackageJson(ctx),
|
|
2619
3631
|
"bin.js": emitBinJs(ctx),
|
|
3632
|
+
"env.js": emitEnvJs(ctx),
|
|
2620
3633
|
"server.js": emitServerJs(ctx),
|
|
2621
3634
|
"tools.js": emitToolsJs(ctx),
|
|
2622
3635
|
"client.js": emitClientJs(ctx),
|
|
@@ -2632,14 +3645,15 @@ function registerMcpCommand(program) {
|
|
|
2632
3645
|
program.command("mcp").description("Compile an OpenAPI spec into a runnable MCP server (stdio + HTTP).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("-o, --output <dir>", "output directory for the generated server", "./loadam-out/mcp").option(
|
|
2633
3646
|
"--target <url>",
|
|
2634
3647
|
"override base URL baked into client.js (env BASE_URL still wins at runtime)"
|
|
2635
|
-
).option("--writes", "include mutating ops (POST/PUT/PATCH/DELETE) \u2014 off by default", false).option("--exclude <opIds...>", "operation ids to exclude from the tool list, repeatable").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runMcp));
|
|
3648
|
+
).option("--writes", "include mutating ops (POST/PUT/PATCH/DELETE) \u2014 off by default", false).option("--exclude <opIds...>", "operation ids to exclude from the tool list, repeatable").option("--config <path>", CONFIG_OPTION_HELP).option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runMcp));
|
|
2636
3649
|
}
|
|
2637
3650
|
async function runMcp(spec, opts) {
|
|
2638
3651
|
const out = makeOutput(!!opts.json);
|
|
2639
|
-
const specPath =
|
|
3652
|
+
const specPath = resolve9(spec);
|
|
2640
3653
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
2641
3654
|
const ir = await fromOpenApiFile(specPath);
|
|
2642
3655
|
inferResourceGraph(ir);
|
|
3656
|
+
await applyUserConfig(ir, specPath, opts.config);
|
|
2643
3657
|
parseIR(ir);
|
|
2644
3658
|
const target = resolveTarget(opts.target);
|
|
2645
3659
|
const result = compileMcp(ir, {
|
|
@@ -2647,11 +3661,11 @@ async function runMcp(spec, opts) {
|
|
|
2647
3661
|
includeWrites: !!opts.writes,
|
|
2648
3662
|
exclude: opts.exclude
|
|
2649
3663
|
});
|
|
2650
|
-
const outDir =
|
|
3664
|
+
const outDir = resolve9(opts.output);
|
|
2651
3665
|
await mkdir3(outDir, { recursive: true });
|
|
2652
3666
|
for (const [rel, contents] of Object.entries(result.files)) {
|
|
2653
|
-
const full =
|
|
2654
|
-
await mkdir3(
|
|
3667
|
+
const full = resolve9(outDir, rel);
|
|
3668
|
+
await mkdir3(dirname3(full), { recursive: true });
|
|
2655
3669
|
await writeFile5(full, contents, "utf8");
|
|
2656
3670
|
}
|
|
2657
3671
|
const fileCount = Object.keys(result.files).length;
|
|
@@ -2679,9 +3693,9 @@ async function runMcp(spec, opts) {
|
|
|
2679
3693
|
}
|
|
2680
3694
|
|
|
2681
3695
|
// src/commands/report.ts
|
|
2682
|
-
import { spawn } from "child_process";
|
|
2683
|
-
import { readFile as
|
|
2684
|
-
import { join as
|
|
3696
|
+
import { spawn as spawn2 } from "child_process";
|
|
3697
|
+
import { readFile as readFile8, writeFile as writeFile6 } from "fs/promises";
|
|
3698
|
+
import { join as join4, resolve as resolve10 } from "path";
|
|
2685
3699
|
|
|
2686
3700
|
// ../report/dist/index.js
|
|
2687
3701
|
function renderReport(input) {
|
|
@@ -2709,8 +3723,8 @@ function renderReport(input) {
|
|
|
2709
3723
|
"<head>",
|
|
2710
3724
|
`<meta charset="utf-8" />`,
|
|
2711
3725
|
`<meta name="viewport" content="width=device-width,initial-scale=1" />`,
|
|
2712
|
-
`<meta name="generator" content="loadam ${
|
|
2713
|
-
`<title>${
|
|
3726
|
+
`<meta name="generator" content="loadam ${esc2(loadamVersion)}" />`,
|
|
3727
|
+
`<title>${esc2(reportTitle(meta))}</title>`,
|
|
2714
3728
|
`<style>${STYLES}${dynamicTabStyles(input.k6Summaries)}${dynamicEndpointStyles(input.operations)}</style>`,
|
|
2715
3729
|
"</head>",
|
|
2716
3730
|
"<body>",
|
|
@@ -2748,12 +3762,12 @@ function renderHeader(meta, overall, k6) {
|
|
|
2748
3762
|
</div>
|
|
2749
3763
|
<header class="hdr">
|
|
2750
3764
|
<div class="hdr-left">
|
|
2751
|
-
<div class="cmd">${
|
|
2752
|
-
<h1>${
|
|
2753
|
-
<div class="sub">${
|
|
3765
|
+
<div class="cmd">${esc2(meta.command)}${modeLabel ? ` \xB7 ${esc2(modeLabel)}` : ""} <span class="status-chip ${overall.cls}">${esc2(chipText)}</span></div>
|
|
3766
|
+
<h1>${esc2(meta.spec.title ?? "Untitled API")}</h1>
|
|
3767
|
+
<div class="sub">${esc2(meta.spec.version ?? "")} \xB7 target <code>${esc2(meta.target ?? "\u2014")}</code></div>
|
|
2754
3768
|
</div>
|
|
2755
3769
|
<div class="hdr-right">
|
|
2756
|
-
<div class="when">${
|
|
3770
|
+
<div class="when">${esc2(meta.startedAt)}</div>
|
|
2757
3771
|
${typeof meta.durationMs === "number" ? `<div class="dur">${(meta.durationMs / 1e3).toFixed(2)}s</div>` : ""}
|
|
2758
3772
|
<div class="actions">
|
|
2759
3773
|
<button type="button" class="act" data-loadam-download="html" title="Download this HTML report">\u2B07 Report</button>
|
|
@@ -2777,9 +3791,9 @@ function renderFailureReason(meta, overall, k6, contractFailures) {
|
|
|
2777
3791
|
const failedThresh = (meta.thresholds?.failed ?? []).filter((n) => !isSentinelThreshold(n));
|
|
2778
3792
|
if (failedThresh.length > 0) {
|
|
2779
3793
|
const PREVIEW = 3;
|
|
2780
|
-
const head = failedThresh.slice(0, PREVIEW).map((t) => `<code>${
|
|
3794
|
+
const head = failedThresh.slice(0, PREVIEW).map((t) => `<code>${esc2(t)}</code>`).join(", ");
|
|
2781
3795
|
const rest = failedThresh.slice(PREVIEW);
|
|
2782
|
-
const more = rest.length > 0 ? ` <details class="more"><summary>+${rest.length} more</summary>${rest.map((t) => `<code>${
|
|
3796
|
+
const more = rest.length > 0 ? ` <details class="more"><summary>+${rest.length} more</summary>${rest.map((t) => `<code>${esc2(t)}</code>`).join(", ")}</details>` : "";
|
|
2783
3797
|
reasons.push(
|
|
2784
3798
|
`<strong>${failedThresh.length}</strong> threshold${failedThresh.length === 1 ? "" : "s"} failed: ${head}${more}`
|
|
2785
3799
|
);
|
|
@@ -2847,7 +3861,7 @@ function renderSummary(meta, k6) {
|
|
|
2847
3861
|
return `
|
|
2848
3862
|
<section class="cards">
|
|
2849
3863
|
${cells.map(
|
|
2850
|
-
(c) => `<div class="card"><div class="card-v">${
|
|
3864
|
+
(c) => `<div class="card"><div class="card-v">${esc2(c.value)}</div><div class="card-l">${esc2(c.label)}</div></div>`
|
|
2851
3865
|
).join("\n ")}
|
|
2852
3866
|
</section>`;
|
|
2853
3867
|
}
|
|
@@ -2869,10 +3883,10 @@ function renderThresholds(meta) {
|
|
|
2869
3883
|
<section>
|
|
2870
3884
|
<h2>Thresholds <span class="muted">(${summary.join(" \xB7 ")})</span></h2>
|
|
2871
3885
|
<ul class="thr">
|
|
2872
|
-
${failedHead.map((x) => `<li class="bad">\u2717 ${
|
|
2873
|
-
${failedRest.length > 0 ? `<li class="thr-more"><details><summary>+${failedRest.length} more failed</summary><ul class="thr">${failedRest.map((x) => `<li class="bad">\u2717 ${
|
|
2874
|
-
${passedHead.map((x) => `<li class="ok">\u2713 ${
|
|
2875
|
-
${passedRest.length > 0 ? `<li class="thr-more"><details><summary>+${passedRest.length} more passed</summary><ul class="thr">${passedRest.map((x) => `<li class="ok">\u2713 ${
|
|
3886
|
+
${failedHead.map((x) => `<li class="bad">\u2717 ${esc2(x)}</li>`).join("\n ")}
|
|
3887
|
+
${failedRest.length > 0 ? `<li class="thr-more"><details><summary>+${failedRest.length} more failed</summary><ul class="thr">${failedRest.map((x) => `<li class="bad">\u2717 ${esc2(x)}</li>`).join("")}</ul></details></li>` : ""}
|
|
3888
|
+
${passedHead.map((x) => `<li class="ok">\u2713 ${esc2(x)}</li>`).join("\n ")}
|
|
3889
|
+
${passedRest.length > 0 ? `<li class="thr-more"><details><summary>+${passedRest.length} more passed</summary><ul class="thr">${passedRest.map((x) => `<li class="ok">\u2713 ${esc2(x)}</li>`).join("")}</ul></details></li>` : ""}
|
|
2876
3890
|
</ul>
|
|
2877
3891
|
</section>`;
|
|
2878
3892
|
}
|
|
@@ -2906,23 +3920,23 @@ function renderEndpoints(ops, k6) {
|
|
|
2906
3920
|
const rateLabel = status.rate === null ? "" : fmtRate(status.rate);
|
|
2907
3921
|
const p95 = opMetrics.get(op.id)?.p95;
|
|
2908
3922
|
const p95Label = typeof p95 === "number" ? `${Math.round(p95)}ms` : "";
|
|
2909
|
-
return `<label for="${
|
|
3923
|
+
return `<label for="${esc2(id)}" class="ep-item ${status.cls}" data-state="${status.cls}" title="${esc2(op.method.toUpperCase())} ${esc2(op.path)}">
|
|
2910
3924
|
<span class="ep-item-row">
|
|
2911
|
-
<span class="ep-method ${
|
|
2912
|
-
<span class="ep-item-path">${
|
|
2913
|
-
<span class="ep-item-dot ${status.cls}" aria-label="${
|
|
3925
|
+
<span class="ep-method ${esc2(op.method.toLowerCase())}">${esc2(op.method.toUpperCase())}</span>
|
|
3926
|
+
<span class="ep-item-path">${esc2(op.path)}</span>
|
|
3927
|
+
<span class="ep-item-dot ${status.cls}" aria-label="${esc2(status.label)}"></span>
|
|
2914
3928
|
</span>
|
|
2915
|
-
${rateLabel || p95Label ? `<span class="ep-item-meta">${rateLabel ? `<span class="ep-item-rate ${status.cls}">${
|
|
3929
|
+
${rateLabel || p95Label ? `<span class="ep-item-meta">${rateLabel ? `<span class="ep-item-rate ${status.cls}">${esc2(rateLabel)}</span> <span class="ep-item-state ${status.cls}">${esc2(status.label)}</span>` : ""}${p95Label ? ` <span class="ep-item-p95">p95 ${esc2(p95Label)}</span>` : ""}</span>` : ""}
|
|
2916
3930
|
</label>`;
|
|
2917
3931
|
}).join("\n ");
|
|
2918
3932
|
return `<div class="ep-group">
|
|
2919
|
-
<div class="ep-group-h">${
|
|
3933
|
+
<div class="ep-group-h">${esc2(tag)}</div>
|
|
2920
3934
|
${items}
|
|
2921
3935
|
</div>`;
|
|
2922
3936
|
}).join("\n ");
|
|
2923
3937
|
const radios = ops.map((op, i) => {
|
|
2924
3938
|
const id = opSlug(op);
|
|
2925
|
-
return `<input type="radio" name="loadam-endpoint" id="${
|
|
3939
|
+
return `<input type="radio" name="loadam-endpoint" id="${esc2(id)}" class="ep-radio"${i === 0 ? " checked" : ""}>`;
|
|
2926
3940
|
}).join("");
|
|
2927
3941
|
const totals = ops.map((op) => endpointStatus(checkLookup.get(op.id) ?? []));
|
|
2928
3942
|
const failedCount = totals.filter((t) => t.cls === "bad").length;
|
|
@@ -2953,32 +3967,32 @@ function renderEndpoints(ops, k6) {
|
|
|
2953
3967
|
const opChecks = checkLookup.get(op.id) ?? [];
|
|
2954
3968
|
const status = endpointStatus(opChecks);
|
|
2955
3969
|
const id = opSlug(op);
|
|
2956
|
-
const rateLabel = status.rate === null ? "" : ` <span class="ep-pill-rate">${
|
|
2957
|
-
const pill = `<span class="ep-pill ${status.cls}">${
|
|
3970
|
+
const rateLabel = status.rate === null ? "" : ` <span class="ep-pill-rate">${esc2(fmtRate(status.rate))}</span>`;
|
|
3971
|
+
const pill = `<span class="ep-pill ${status.cls}">${esc2(status.label)}${rateLabel}</span>`;
|
|
2958
3972
|
const runStrip = opChecks.map(({ run, check }) => {
|
|
2959
3973
|
const total = check.passes + check.fails;
|
|
2960
3974
|
const rate = total > 0 ? check.passes / total : 0;
|
|
2961
3975
|
const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
|
|
2962
3976
|
const pct = total > 0 ? fmtRate(rate) : "";
|
|
2963
|
-
return `<span class="ep-run ${cls}"><strong>${
|
|
3977
|
+
return `<span class="ep-run ${cls}"><strong>${esc2(run)}</strong> ${check.passes}/${total} passed${pct ? ` \xB7 ${pct}` : ""}</span>`;
|
|
2964
3978
|
}).join("");
|
|
2965
3979
|
const checkRows = opChecks.map(({ run, check }) => {
|
|
2966
3980
|
const total = check.passes + check.fails;
|
|
2967
3981
|
const rate = total > 0 ? check.passes / total : 0;
|
|
2968
3982
|
const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
|
|
2969
3983
|
const pct = total > 0 ? ` <span class="muted">(${fmtRate(rate)})</span>` : "";
|
|
2970
|
-
return `<tr class="${cls}"><th>${
|
|
3984
|
+
return `<tr class="${cls}"><th>${esc2(run)}</th><td>${esc2(check.name)}</td><td>${check.passes}/${total} passed${pct}</td></tr>`;
|
|
2971
3985
|
}).join("");
|
|
2972
3986
|
const detail = checkRows ? `<table class="kv ep-detail"><thead><tr><th>run</th><th>check</th><th>result</th></tr></thead><tbody>${checkRows}</tbody></table>` : `<p class="hint">No k6 checks recorded for this operation.</p>`;
|
|
2973
3987
|
const metricsBlock = renderOpMetricsBlock(opMetrics.get(op.id));
|
|
2974
|
-
const tags = (op.tags ?? []).map((t) => `<span class="ep-tag">${
|
|
2975
|
-
return `<div class="ep-pane" data-ep="${
|
|
3988
|
+
const tags = (op.tags ?? []).map((t) => `<span class="ep-tag">${esc2(t)}</span>`).join("");
|
|
3989
|
+
return `<div class="ep-pane" data-ep="${esc2(id)}">
|
|
2976
3990
|
<div class="ep-pane-h">
|
|
2977
|
-
<span class="ep-method ${
|
|
2978
|
-
<span class="ep-path"><code>${
|
|
3991
|
+
<span class="ep-method ${esc2(op.method.toLowerCase())}">${esc2(op.method.toUpperCase())}</span>
|
|
3992
|
+
<span class="ep-path"><code>${esc2(op.path)}</code></span>
|
|
2979
3993
|
${pill}
|
|
2980
3994
|
</div>
|
|
2981
|
-
${op.summary ? `<p class="ep-pane-sum">${
|
|
3995
|
+
${op.summary ? `<p class="ep-pane-sum">${esc2(op.summary)}</p>` : ""}
|
|
2982
3996
|
${tags ? `<div class="ep-tags">${tags}</div>` : ""}
|
|
2983
3997
|
${runStrip ? `<div class="ep-runs">${runStrip}</div>` : ""}
|
|
2984
3998
|
${metricsBlock}
|
|
@@ -2987,7 +4001,7 @@ function renderEndpoints(ops, k6) {
|
|
|
2987
4001
|
}).join("\n ");
|
|
2988
4002
|
return `
|
|
2989
4003
|
<section class="endpoints">
|
|
2990
|
-
<h2>Endpoints <span class="muted">(${
|
|
4004
|
+
<h2>Endpoints <span class="muted">(${esc2(headline)})</span></h2>
|
|
2991
4005
|
<p class="hint">Status uses pass-rate tiers: <span class="tier ok">passed \u2265 ${PASS_RATE_OK * 100}%</span> \xB7 <span class="tier warn">flaky ${PASS_RATE_WARN * 100}\u2013${PASS_RATE_OK * 100}%</span> \xB7 <span class="tier bad">failed < ${PASS_RATE_WARN * 100}%</span>.</p>
|
|
2992
4006
|
<div class="ep-layout">
|
|
2993
4007
|
${filterRadios}
|
|
@@ -3089,10 +4103,13 @@ function computeOverall(meta, k6, ops) {
|
|
|
3089
4103
|
return { cls: "bad", label: "failed", detail };
|
|
3090
4104
|
}
|
|
3091
4105
|
}
|
|
4106
|
+
const tests = meta.summary?.tests;
|
|
4107
|
+
const passedTests = meta.summary?.passed;
|
|
4108
|
+
const testDetail = meta.command === "contract" && typeof tests === "number" && typeof passedTests === "number" ? `${passedTests}/${tests} tests` : "";
|
|
3092
4109
|
if (thresholdsFailed || meta.exitCode !== void 0 && meta.exitCode !== 0) {
|
|
3093
|
-
return { cls: "bad", label: "failed", detail:
|
|
4110
|
+
return { cls: "bad", label: "failed", detail: testDetail };
|
|
3094
4111
|
}
|
|
3095
|
-
return { cls: "ok", label: "passed", detail:
|
|
4112
|
+
return { cls: "ok", label: "passed", detail: testDetail };
|
|
3096
4113
|
}
|
|
3097
4114
|
function collectOpMetrics(ops, k6) {
|
|
3098
4115
|
const out = /* @__PURE__ */ new Map();
|
|
@@ -3152,9 +4169,9 @@ function renderOpMetricsBlock(metrics) {
|
|
|
3152
4169
|
}).join("");
|
|
3153
4170
|
const p95 = m.p95 !== null ? `${Math.round(m.p95)}ms` : "\u2014";
|
|
3154
4171
|
rows.push(`<tr>
|
|
3155
|
-
<th>${
|
|
4172
|
+
<th>${esc2(run)}</th>
|
|
3156
4173
|
<td class="num">${m.total}</td>
|
|
3157
|
-
<td class="num">${
|
|
4174
|
+
<td class="num">${esc2(p95)}</td>
|
|
3158
4175
|
<td><div class="bkt-bar">${segments || `<span class="muted">no data</span>`}</div></td>
|
|
3159
4176
|
</tr>`);
|
|
3160
4177
|
}
|
|
@@ -3176,13 +4193,13 @@ function renderK6Section(k6, hasEndpoints) {
|
|
|
3176
4193
|
const tabs = blocks.map((b, i) => {
|
|
3177
4194
|
const id = `loadam-tab-${slug(b.name)}`;
|
|
3178
4195
|
return `
|
|
3179
|
-
<input type="radio" name="loadam-k6-tab" id="${
|
|
4196
|
+
<input type="radio" name="loadam-k6-tab" id="${esc2(id)}" class="tab-input"${i === 0 ? " checked" : ""}>`;
|
|
3180
4197
|
}).join("");
|
|
3181
4198
|
const labels = blocks.map((b) => {
|
|
3182
4199
|
const id = `loadam-tab-${slug(b.name)}`;
|
|
3183
|
-
return `<label for="${
|
|
4200
|
+
return `<label for="${esc2(id)}" class="tab-label">${esc2(b.name)}</label>`;
|
|
3184
4201
|
}).join("");
|
|
3185
|
-
const panes = blocks.map((b) => `<div class="tab-pane" data-tab="${
|
|
4202
|
+
const panes = blocks.map((b) => `<div class="tab-pane" data-tab="${esc2(slug(b.name))}">${b.html}</div>`).join("");
|
|
3186
4203
|
return `
|
|
3187
4204
|
<section class="tabs">
|
|
3188
4205
|
<h2>k6 results <span class="tab-hint">(${blocks.length} runs \u2014 click to switch)</span></h2>${tabs}
|
|
@@ -3205,7 +4222,7 @@ function renderK6Block(name, summary, hasEndpoints) {
|
|
|
3205
4222
|
if (failed && typeof failed.rate === "number")
|
|
3206
4223
|
headlineCells.push({ label: "errors", value: `${(failed.rate * 100).toFixed(2)}%` });
|
|
3207
4224
|
const headline = headlineCells.length > 0 ? `<div class="cards inner">${headlineCells.map(
|
|
3208
|
-
(c) => `<div class="card"><div class="card-v">${
|
|
4225
|
+
(c) => `<div class="card"><div class="card-v">${esc2(c.value)}</div><div class="card-l">${esc2(c.label)}</div></div>`
|
|
3209
4226
|
).join("")}</div>` : "";
|
|
3210
4227
|
const latency = dur ? `
|
|
3211
4228
|
<h3>http_req_duration</h3>
|
|
@@ -3219,7 +4236,7 @@ function renderK6Block(name, summary, hasEndpoints) {
|
|
|
3219
4236
|
["p(95)", fmtMs(dur["p(95)"])],
|
|
3220
4237
|
["p(99)", fmtMs(dur["p(99)"])],
|
|
3221
4238
|
["max", fmtMs(dur.max)]
|
|
3222
|
-
].map(([k, v]) => `<tr><th>${
|
|
4239
|
+
].map(([k, v]) => `<tr><th>${esc2(k)}</th><td>${esc2(v)}</td></tr>`).join("")}
|
|
3223
4240
|
</tbody>
|
|
3224
4241
|
</table>
|
|
3225
4242
|
${renderPercentileBars(dur)}` : "";
|
|
@@ -3256,7 +4273,7 @@ function renderChecksSummary(checks) {
|
|
|
3256
4273
|
if (warn > 0) parts.push(`<span class="warn-text">${warn} flaky</span>`);
|
|
3257
4274
|
if (bad > 0) parts.push(`<span class="bad-text">${bad} failed</span>`);
|
|
3258
4275
|
return `
|
|
3259
|
-
<div class="chk-line"><span class="chk-tag ${cls}">checks</span> ${parts.join(" \xB7 ")} <span class="muted">\xB7 ${
|
|
4276
|
+
<div class="chk-line"><span class="chk-tag ${cls}">checks</span> ${parts.join(" \xB7 ")} <span class="muted">\xB7 ${esc2(fmtRate(overallRate))} overall</span></div>`;
|
|
3260
4277
|
}
|
|
3261
4278
|
function renderChecks(checks) {
|
|
3262
4279
|
const entries = Object.values(checks);
|
|
@@ -3266,12 +4283,12 @@ function renderChecks(checks) {
|
|
|
3266
4283
|
const summaryLine = `${passed}/${entries.length} passed${failed.length > 0 ? ` \xB7 ${failed.length} failed` : ""}`;
|
|
3267
4284
|
const row = (c, kind) => {
|
|
3268
4285
|
const total = c.passes + c.fails;
|
|
3269
|
-
return `<tr class="${kind}"><th>${
|
|
4286
|
+
return `<tr class="${kind}"><th>${esc2(c.name)}</th><td><span class="chk-count">${c.passes}<span class="chk-sep">/</span>${total}</span> <span class="chk-word">passed</span></td></tr>`;
|
|
3270
4287
|
};
|
|
3271
4288
|
const failedRows = failed.map((c) => row(c, "bad")).join("");
|
|
3272
4289
|
const passedRows = entries.filter((c) => c.fails === 0).map((c) => row(c, "ok")).join("");
|
|
3273
4290
|
return `
|
|
3274
|
-
<h3>Per-operation checks <span class="muted">(${
|
|
4291
|
+
<h3>Per-operation checks <span class="muted">(${esc2(summaryLine)})</span></h3>
|
|
3275
4292
|
<p class="hint">Each row shows <em>passed / invoked</em>: how many times this assertion held vs. how many times it ran (one invocation per request).</p>
|
|
3276
4293
|
<table class="kv checks">
|
|
3277
4294
|
<tbody>${failedRows}${passedRows}</tbody>
|
|
@@ -3316,7 +4333,7 @@ function renderPercentileBars(dur) {
|
|
|
3316
4333
|
<div class="bars">
|
|
3317
4334
|
${bars.map(([k, v]) => {
|
|
3318
4335
|
const pct = Math.max(2, Math.round(v / max * 100));
|
|
3319
|
-
return `<div class="bar-row"><span class="bar-l">${
|
|
4336
|
+
return `<div class="bar-row"><span class="bar-l">${esc2(k)}</span><div class="bar"><div class="bar-fill" style="width:${pct}%"></div></div><span class="bar-v">${esc2(fmtMs(v))}</span></div>`;
|
|
3320
4337
|
}).join("\n ")}
|
|
3321
4338
|
</div>`;
|
|
3322
4339
|
}
|
|
@@ -3324,7 +4341,7 @@ function renderDrift(md) {
|
|
|
3324
4341
|
return `
|
|
3325
4342
|
<section>
|
|
3326
4343
|
<h2>Drift findings</h2>
|
|
3327
|
-
<pre class="drift">${
|
|
4344
|
+
<pre class="drift">${esc2(md)}</pre>
|
|
3328
4345
|
</section>`;
|
|
3329
4346
|
}
|
|
3330
4347
|
function renderContract(failures) {
|
|
@@ -3333,27 +4350,27 @@ function renderContract(failures) {
|
|
|
3333
4350
|
<h2>Contract failures (${failures.length})</h2>
|
|
3334
4351
|
<ul class="failures">
|
|
3335
4352
|
${failures.map(
|
|
3336
|
-
(f) => `<li><div class="ftest">${
|
|
4353
|
+
(f) => `<li><div class="ftest">${esc2(f.test)}</div>${f.message ? `<pre>${esc2(f.message)}</pre>` : ""}</li>`
|
|
3337
4354
|
).join("\n ")}
|
|
3338
4355
|
</ul>
|
|
3339
4356
|
</section>`;
|
|
3340
4357
|
}
|
|
3341
4358
|
function renderRunDetails(meta) {
|
|
3342
4359
|
const flagRows = Object.entries(meta.flags).map(
|
|
3343
|
-
([k, v]) => `<tr><th>${
|
|
4360
|
+
([k, v]) => `<tr><th>${esc2(k)}</th><td>${esc2(String(v))}</td></tr>`
|
|
3344
4361
|
);
|
|
3345
|
-
const envRow = meta.envVars.length > 0 ? `<tr><th>env vars</th><td>${meta.envVars.map((e) => `<code>${
|
|
4362
|
+
const envRow = meta.envVars.length > 0 ? `<tr><th>env vars</th><td>${meta.envVars.map((e) => `<code>${esc2(e)}</code>`).join(" ")}</td></tr>` : "";
|
|
3346
4363
|
return `
|
|
3347
4364
|
<section>
|
|
3348
4365
|
<h2>Run details</h2>
|
|
3349
4366
|
<table class="kv">
|
|
3350
4367
|
<tbody>
|
|
3351
|
-
<tr><th>session id</th><td><code>${
|
|
3352
|
-
<tr><th>spec</th><td><code>${
|
|
3353
|
-
<tr><th>spec sha256</th><td><code>${
|
|
3354
|
-
<tr><th>IR digest</th><td><code>${
|
|
3355
|
-
<tr><th>started</th><td>${
|
|
3356
|
-
${meta.endedAt ? `<tr><th>ended</th><td>${
|
|
4368
|
+
<tr><th>session id</th><td><code>${esc2(meta.id)}</code></td></tr>
|
|
4369
|
+
<tr><th>spec</th><td><code>${esc2(meta.spec.path)}</code></td></tr>
|
|
4370
|
+
<tr><th>spec sha256</th><td><code>${esc2(meta.spec.sha256.slice(0, 16))}\u2026</code></td></tr>
|
|
4371
|
+
<tr><th>IR digest</th><td><code>${esc2(meta.irDigest.slice(0, 16))}\u2026</code></td></tr>
|
|
4372
|
+
<tr><th>started</th><td>${esc2(meta.startedAt)}</td></tr>
|
|
4373
|
+
${meta.endedAt ? `<tr><th>ended</th><td>${esc2(meta.endedAt)}</td></tr>` : ""}
|
|
3357
4374
|
${typeof meta.exitCode === "number" ? `<tr><th>exit code</th><td>${meta.exitCode}</td></tr>` : ""}
|
|
3358
4375
|
${envRow}
|
|
3359
4376
|
${flagRows.join("\n ")}
|
|
@@ -3364,9 +4381,9 @@ function renderRunDetails(meta) {
|
|
|
3364
4381
|
function renderFooter(meta, version) {
|
|
3365
4382
|
return `
|
|
3366
4383
|
<footer>
|
|
3367
|
-
Generated by <a href="https://github.com/DesmondSanctity/loadam" target="_blank" rel="noopener">loadam ${
|
|
4384
|
+
Generated by <a href="https://github.com/DesmondSanctity/loadam" target="_blank" rel="noopener">loadam ${esc2(version)}</a> \xB7
|
|
3368
4385
|
schema v${meta.schemaVersion} \xB7
|
|
3369
|
-
IR <code>${
|
|
4386
|
+
IR <code>${esc2(meta.irDigest.slice(0, 12))}</code>
|
|
3370
4387
|
</footer>`;
|
|
3371
4388
|
}
|
|
3372
4389
|
function reportTitle(meta) {
|
|
@@ -3378,7 +4395,7 @@ function fmtMs(n) {
|
|
|
3378
4395
|
if (n >= 1e3) return `${(n / 1e3).toFixed(2)} s`;
|
|
3379
4396
|
return `${n.toFixed(0)} ms`;
|
|
3380
4397
|
}
|
|
3381
|
-
function
|
|
4398
|
+
function esc2(s) {
|
|
3382
4399
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
3383
4400
|
}
|
|
3384
4401
|
function escScript(s) {
|
|
@@ -3639,21 +4656,21 @@ if(bP)bP.addEventListener('click',function(){window.print()});
|
|
|
3639
4656
|
})();</script>`;
|
|
3640
4657
|
|
|
3641
4658
|
// src/commands/report.ts
|
|
3642
|
-
var VERSION = true ? "0.
|
|
4659
|
+
var VERSION = true ? "0.3.0" : "0.0.0";
|
|
3643
4660
|
function registerReportCommand(program) {
|
|
3644
4661
|
program.command("report").description("Render a self-contained HTML report for an archived session.").argument("[id]", 'session ID, prefix, or "latest" (default: latest)', "latest").option("--root <dir>", "session archive root", "./loadam-out").option("-o, --output <path>", "write to this path instead of <session>/report.html").option("--open", "open the report in your default browser after writing", false).option("--json", "emit a JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runReport));
|
|
3645
4662
|
}
|
|
3646
4663
|
async function runReport(id, opts) {
|
|
3647
4664
|
const out = makeOutput(!!opts.json);
|
|
3648
|
-
const root =
|
|
4665
|
+
const root = resolve10(opts.root);
|
|
3649
4666
|
const meta = await resolveSessionId(root, id);
|
|
3650
|
-
const dir =
|
|
4667
|
+
const dir = join4(root, "sessions", meta.id);
|
|
3651
4668
|
const k6Summaries = {};
|
|
3652
4669
|
for (const a of meta.artefacts) {
|
|
3653
4670
|
if (a.startsWith("k6-") && a.endsWith("-summary.json")) {
|
|
3654
4671
|
const label = a.replace(/^k6-/, "").replace(/-summary\.json$/, "");
|
|
3655
4672
|
try {
|
|
3656
|
-
k6Summaries[label] = JSON.parse(await
|
|
4673
|
+
k6Summaries[label] = JSON.parse(await readFile8(join4(dir, a), "utf8"));
|
|
3657
4674
|
} catch {
|
|
3658
4675
|
}
|
|
3659
4676
|
}
|
|
@@ -3661,13 +4678,20 @@ async function runReport(id, opts) {
|
|
|
3661
4678
|
let driftMarkdown;
|
|
3662
4679
|
if (meta.command === "diff") {
|
|
3663
4680
|
try {
|
|
3664
|
-
driftMarkdown = await
|
|
4681
|
+
driftMarkdown = await readFile8(join4(dir, "drift.md"), "utf8");
|
|
4682
|
+
} catch {
|
|
4683
|
+
}
|
|
4684
|
+
}
|
|
4685
|
+
let contractFailures;
|
|
4686
|
+
if (meta.command === "contract" && meta.artefacts.includes("contract-failures.json")) {
|
|
4687
|
+
try {
|
|
4688
|
+
contractFailures = JSON.parse(await readFile8(join4(dir, "contract-failures.json"), "utf8"));
|
|
3665
4689
|
} catch {
|
|
3666
4690
|
}
|
|
3667
4691
|
}
|
|
3668
4692
|
let operations;
|
|
3669
4693
|
try {
|
|
3670
|
-
const ir = JSON.parse(await
|
|
4694
|
+
const ir = JSON.parse(await readFile8(join4(dir, "ir.json"), "utf8"));
|
|
3671
4695
|
if (Array.isArray(ir.operations) && ir.operations.length > 0) {
|
|
3672
4696
|
operations = ir.operations.map((o) => ({
|
|
3673
4697
|
id: o.id,
|
|
@@ -3683,10 +4707,11 @@ async function runReport(id, opts) {
|
|
|
3683
4707
|
meta,
|
|
3684
4708
|
k6Summaries: Object.keys(k6Summaries).length > 0 ? k6Summaries : void 0,
|
|
3685
4709
|
driftMarkdown,
|
|
4710
|
+
contractFailures,
|
|
3686
4711
|
operations,
|
|
3687
4712
|
loadamVersion: VERSION
|
|
3688
4713
|
});
|
|
3689
|
-
const outPath = opts.output ?
|
|
4714
|
+
const outPath = opts.output ? resolve10(opts.output) : join4(dir, "report.html");
|
|
3690
4715
|
await writeFile6(outPath, html, "utf8");
|
|
3691
4716
|
const sizeKb = Math.round(Buffer.byteLength(html, "utf8") / 1024);
|
|
3692
4717
|
if (!out.json) {
|
|
@@ -3709,7 +4734,7 @@ async function openInBrowser(path) {
|
|
|
3709
4734
|
const cmd = platform === "darwin" ? "open" : platform === "win32" ? "start" : "xdg-open";
|
|
3710
4735
|
const args = platform === "win32" ? ["", path] : [path];
|
|
3711
4736
|
try {
|
|
3712
|
-
const child =
|
|
4737
|
+
const child = spawn2(cmd, args, {
|
|
3713
4738
|
detached: true,
|
|
3714
4739
|
stdio: "ignore",
|
|
3715
4740
|
shell: platform === "win32"
|
|
@@ -3720,20 +4745,20 @@ async function openInBrowser(path) {
|
|
|
3720
4745
|
}
|
|
3721
4746
|
|
|
3722
4747
|
// src/commands/show.ts
|
|
3723
|
-
import { readFile as
|
|
3724
|
-
import { join as
|
|
4748
|
+
import { readFile as readFile9, readdir as readdir2 } from "fs/promises";
|
|
4749
|
+
import { join as join6, resolve as resolve11 } from "path";
|
|
3725
4750
|
|
|
3726
4751
|
// src/util/k6.ts
|
|
3727
|
-
import { spawn as
|
|
4752
|
+
import { spawn as spawn3 } from "child_process";
|
|
3728
4753
|
import { constants, access } from "fs/promises";
|
|
3729
|
-
import { delimiter, join as
|
|
4754
|
+
import { delimiter, join as join5 } from "path";
|
|
3730
4755
|
async function findK6Binary() {
|
|
3731
4756
|
const path = process.env.PATH ?? "";
|
|
3732
4757
|
const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
|
|
3733
4758
|
for (const dir of path.split(delimiter)) {
|
|
3734
4759
|
if (!dir) continue;
|
|
3735
4760
|
for (const ext of exts) {
|
|
3736
|
-
const candidate =
|
|
4761
|
+
const candidate = join5(dir, `k6${ext}`);
|
|
3737
4762
|
try {
|
|
3738
4763
|
await access(candidate, constants.X_OK);
|
|
3739
4764
|
return candidate;
|
|
@@ -3743,6 +4768,13 @@ async function findK6Binary() {
|
|
|
3743
4768
|
}
|
|
3744
4769
|
return null;
|
|
3745
4770
|
}
|
|
4771
|
+
function envForRun(dotenv, shell = process.env) {
|
|
4772
|
+
const out = {};
|
|
4773
|
+
for (const [k, v] of Object.entries(dotenv)) {
|
|
4774
|
+
if (shell[k] === void 0 || shell[k] === "") out[k] = v;
|
|
4775
|
+
}
|
|
4776
|
+
return out;
|
|
4777
|
+
}
|
|
3746
4778
|
async function runK6(opts) {
|
|
3747
4779
|
const bin = await findK6Binary();
|
|
3748
4780
|
if (!bin) {
|
|
@@ -3754,10 +4786,11 @@ async function runK6(opts) {
|
|
|
3754
4786
|
if (opts.summaryPath) args.push(`--summary-export=${opts.summaryPath}`);
|
|
3755
4787
|
args.push(...opts.args ?? [], opts.script);
|
|
3756
4788
|
return await new Promise((resolveExit, reject) => {
|
|
3757
|
-
const child =
|
|
4789
|
+
const child = spawn3(bin, args, {
|
|
3758
4790
|
cwd: opts.cwd,
|
|
3759
4791
|
env: { ...process.env, ...opts.env },
|
|
3760
|
-
|
|
4792
|
+
// fd 2 = our stderr: k6 output stays visible without polluting stdout.
|
|
4793
|
+
stdio: ["inherit", opts.stdout === "stderr" ? 2 : "inherit", "inherit"]
|
|
3761
4794
|
});
|
|
3762
4795
|
child.on("error", reject);
|
|
3763
4796
|
child.on("close", (code) => resolveExit(code ?? 0));
|
|
@@ -3765,8 +4798,8 @@ async function runK6(opts) {
|
|
|
3765
4798
|
}
|
|
3766
4799
|
async function digestK6Summary(path) {
|
|
3767
4800
|
try {
|
|
3768
|
-
const { readFile:
|
|
3769
|
-
const text = await
|
|
4801
|
+
const { readFile: readFile12 } = await import("fs/promises");
|
|
4802
|
+
const text = await readFile12(path, "utf8");
|
|
3770
4803
|
const data = JSON.parse(text);
|
|
3771
4804
|
const passed = [];
|
|
3772
4805
|
const failed = [];
|
|
@@ -3799,9 +4832,9 @@ function registerShowCommand(program) {
|
|
|
3799
4832
|
}
|
|
3800
4833
|
async function runShow(id, opts) {
|
|
3801
4834
|
const out = makeOutput(!!opts.json);
|
|
3802
|
-
const root =
|
|
4835
|
+
const root = resolve11(opts.root);
|
|
3803
4836
|
const meta = await resolveSessionId(root, id);
|
|
3804
|
-
const dir =
|
|
4837
|
+
const dir = join6(root, "sessions", meta.id);
|
|
3805
4838
|
if (out.json) {
|
|
3806
4839
|
out.result({ ...meta });
|
|
3807
4840
|
return;
|
|
@@ -3839,19 +4872,30 @@ async function runShow(id, opts) {
|
|
|
3839
4872
|
}
|
|
3840
4873
|
if (meta.command === "diff") {
|
|
3841
4874
|
try {
|
|
3842
|
-
const drift = await
|
|
4875
|
+
const drift = await readFile9(join6(dir, "drift.md"), "utf8");
|
|
3843
4876
|
out.info("");
|
|
3844
4877
|
out.info("\u2500\u2500\u2500\u2500 drift.md \u2500\u2500\u2500\u2500");
|
|
3845
4878
|
process.stdout.write(drift);
|
|
3846
4879
|
} catch {
|
|
3847
4880
|
}
|
|
3848
4881
|
}
|
|
4882
|
+
if (meta.command === "contract" && meta.artefacts.includes("contract-failures.json")) {
|
|
4883
|
+
try {
|
|
4884
|
+
const failures = JSON.parse(
|
|
4885
|
+
await readFile9(join6(dir, "contract-failures.json"), "utf8")
|
|
4886
|
+
);
|
|
4887
|
+
out.info("");
|
|
4888
|
+
out.info(`\u2500\u2500\u2500\u2500 contract failures (${failures.length}) \u2500\u2500\u2500\u2500`);
|
|
4889
|
+
for (const f of failures) out.info(` \u2717 ${f.test}`);
|
|
4890
|
+
} catch {
|
|
4891
|
+
}
|
|
4892
|
+
}
|
|
3849
4893
|
if (meta.command === "test") {
|
|
3850
4894
|
try {
|
|
3851
4895
|
const entries = await readdir2(dir);
|
|
3852
4896
|
const summaryFile = entries.find((e) => /^k6-.*-summary\.json$/.test(e));
|
|
3853
4897
|
if (summaryFile) {
|
|
3854
|
-
const digest = await digestK6Summary(
|
|
4898
|
+
const digest = await digestK6Summary(join6(dir, summaryFile));
|
|
3855
4899
|
if (digest) {
|
|
3856
4900
|
out.info("");
|
|
3857
4901
|
out.info(`\u2500\u2500\u2500\u2500 ${summaryFile} \u2500\u2500\u2500\u2500`);
|
|
@@ -3881,8 +4925,8 @@ async function runShow(id, opts) {
|
|
|
3881
4925
|
}
|
|
3882
4926
|
|
|
3883
4927
|
// src/commands/test.ts
|
|
3884
|
-
import { mkdir as mkdir4, readFile as
|
|
3885
|
-
import { dirname as
|
|
4928
|
+
import { mkdir as mkdir4, readFile as readFile11, stat as stat2, writeFile as writeFile8 } from "fs/promises";
|
|
4929
|
+
import { dirname as dirname4, join as join7, resolve as resolve14 } from "path";
|
|
3886
4930
|
|
|
3887
4931
|
// ../data/dist/index.js
|
|
3888
4932
|
import { faker } from "@faker-js/faker";
|
|
@@ -3897,16 +4941,55 @@ function configureJsf() {
|
|
|
3897
4941
|
failOnInvalidFormat: false,
|
|
3898
4942
|
useExamplesValue: true,
|
|
3899
4943
|
useDefaultValue: true,
|
|
3900
|
-
fillProperties: false
|
|
4944
|
+
fillProperties: false,
|
|
4945
|
+
// An empty array is valid JSON Schema but most APIs reject it ("no items provided").
|
|
4946
|
+
minItems: 1
|
|
3901
4947
|
});
|
|
3902
4948
|
jsf.extend("faker", () => faker);
|
|
4949
|
+
const url = () => faker.internet.url({ appendSlash: false });
|
|
4950
|
+
jsf.format("uri", url);
|
|
4951
|
+
jsf.format("url", url);
|
|
4952
|
+
jsf.format("uri-reference", url);
|
|
4953
|
+
jsf.format("iri", url);
|
|
4954
|
+
jsf.format("hostname", () => faker.internet.domainName());
|
|
4955
|
+
}
|
|
4956
|
+
function seededRandom(seed) {
|
|
4957
|
+
let a = seed >>> 0;
|
|
4958
|
+
return () => {
|
|
4959
|
+
a = a + 1831565813 >>> 0;
|
|
4960
|
+
let t = a;
|
|
4961
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
4962
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
4963
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
4964
|
+
};
|
|
4965
|
+
}
|
|
4966
|
+
function stripReadOnly(node) {
|
|
4967
|
+
if (Array.isArray(node)) return node.map(stripReadOnly);
|
|
4968
|
+
if (!node || typeof node !== "object") return node;
|
|
4969
|
+
const obj = { ...node };
|
|
4970
|
+
const props = obj.properties;
|
|
4971
|
+
if (props && typeof props === "object") {
|
|
4972
|
+
const kept = {};
|
|
4973
|
+
for (const [k, v] of Object.entries(props)) if (!v?.readOnly) kept[k] = stripReadOnly(v);
|
|
4974
|
+
obj.properties = kept;
|
|
4975
|
+
if (Array.isArray(obj.required)) obj.required = obj.required.filter((r) => r in kept);
|
|
4976
|
+
}
|
|
4977
|
+
for (const key of ["items", "allOf", "anyOf", "oneOf", "additionalProperties"]) {
|
|
4978
|
+
if (obj[key] && typeof obj[key] === "object") obj[key] = stripReadOnly(obj[key]);
|
|
4979
|
+
}
|
|
4980
|
+
return obj;
|
|
3903
4981
|
}
|
|
3904
4982
|
function fakeFromSchema(schema, opts = {}) {
|
|
3905
4983
|
configureJsf();
|
|
3906
4984
|
if (opts.seed !== void 0) {
|
|
3907
4985
|
faker.seed(opts.seed);
|
|
3908
4986
|
}
|
|
3909
|
-
|
|
4987
|
+
jsf.option({
|
|
4988
|
+
alwaysFakeOptionals: !!opts.fillOptionals,
|
|
4989
|
+
random: opts.seed !== void 0 ? seededRandom(opts.seed) : Math.random
|
|
4990
|
+
});
|
|
4991
|
+
let expanded = expandRefs(schema, opts.resolveRef ?? (() => void 0), /* @__PURE__ */ new Set());
|
|
4992
|
+
if (opts.forRequest) expanded = stripReadOnly(expanded);
|
|
3910
4993
|
const generated = jsf.generate(expanded);
|
|
3911
4994
|
return overlayRegistry(generated, schema, opts);
|
|
3912
4995
|
}
|
|
@@ -3935,20 +5018,20 @@ function inferKindFromFieldName(field) {
|
|
|
3935
5018
|
const root = m[1];
|
|
3936
5019
|
return root.charAt(0).toUpperCase() + root.slice(1);
|
|
3937
5020
|
}
|
|
3938
|
-
function expandRefs(node,
|
|
3939
|
-
if (Array.isArray(node)) return node.map((n) => expandRefs(n,
|
|
5021
|
+
function expandRefs(node, resolve15, seen) {
|
|
5022
|
+
if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve15, seen));
|
|
3940
5023
|
if (!node || typeof node !== "object") return node;
|
|
3941
5024
|
const obj = node;
|
|
3942
5025
|
if (typeof obj.$ref === "string") {
|
|
3943
5026
|
if (seen.has(obj.$ref)) return {};
|
|
3944
|
-
const target =
|
|
5027
|
+
const target = resolve15(obj.$ref);
|
|
3945
5028
|
if (target === void 0) return obj;
|
|
3946
5029
|
const next = new Set(seen);
|
|
3947
5030
|
next.add(obj.$ref);
|
|
3948
|
-
return expandRefs(target,
|
|
5031
|
+
return expandRefs(target, resolve15, next);
|
|
3949
5032
|
}
|
|
3950
5033
|
const out = {};
|
|
3951
|
-
for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v,
|
|
5034
|
+
for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve15, seen);
|
|
3952
5035
|
return out;
|
|
3953
5036
|
}
|
|
3954
5037
|
|
|
@@ -3982,7 +5065,10 @@ function applyProfile(p, headers, query, envVars, notes) {
|
|
|
3982
5065
|
const env = p.valueEnv ?? `${p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
|
|
3983
5066
|
if (p.in === "header") headers[p.name] = `\${${env}}`;
|
|
3984
5067
|
else if (p.in === "query") query[p.name] = `\${${env}}`;
|
|
3985
|
-
else
|
|
5068
|
+
else {
|
|
5069
|
+
const prev = headers.Cookie ? `${headers.Cookie}; ` : "";
|
|
5070
|
+
headers.Cookie = `${prev}${p.name}=\${${env}}`;
|
|
5071
|
+
}
|
|
3986
5072
|
envVars.add(env);
|
|
3987
5073
|
return;
|
|
3988
5074
|
}
|
|
@@ -3997,10 +5083,11 @@ function applyProfile(p, headers, query, envVars, notes) {
|
|
|
3997
5083
|
}
|
|
3998
5084
|
case "oauth2_cc": {
|
|
3999
5085
|
notes.push(
|
|
4000
|
-
`OAuth2 client
|
|
5086
|
+
`OAuth2 client credentials ("${p.id}"): each VU fetches a token from ${p.tokenUrl} using \`${p.clientIdEnv}\`/\`${p.clientSecretEnv}\` and reuses it.`
|
|
4001
5087
|
);
|
|
4002
5088
|
envVars.add(p.clientIdEnv);
|
|
4003
5089
|
envVars.add(p.clientSecretEnv);
|
|
5090
|
+
headers.Authorization = `__OAUTH2__:${p.id}`;
|
|
4004
5091
|
return;
|
|
4005
5092
|
}
|
|
4006
5093
|
case "custom":
|
|
@@ -4013,22 +5100,24 @@ function sequenceForSmoke(ir) {
|
|
|
4013
5100
|
const out = [];
|
|
4014
5101
|
const seen = /* @__PURE__ */ new Set();
|
|
4015
5102
|
const orderedKinds = topoSortKinds(ir.resources.kinds, ir.resources.edges);
|
|
5103
|
+
const take = (opId) => {
|
|
5104
|
+
const op = opsById.get(opId);
|
|
5105
|
+
if (op && !seen.has(op.id)) {
|
|
5106
|
+
out.push(op);
|
|
5107
|
+
seen.add(op.id);
|
|
5108
|
+
}
|
|
5109
|
+
};
|
|
4016
5110
|
for (const kind of orderedKinds) {
|
|
4017
|
-
for (const bucket of ["listOps", "createOps", "readOps", "updateOps"
|
|
4018
|
-
for (const opId of kind[bucket])
|
|
4019
|
-
const op = opsById.get(opId);
|
|
4020
|
-
if (op && !seen.has(op.id)) {
|
|
4021
|
-
out.push(op);
|
|
4022
|
-
seen.add(op.id);
|
|
4023
|
-
}
|
|
4024
|
-
}
|
|
5111
|
+
for (const bucket of ["listOps", "createOps", "readOps", "updateOps"]) {
|
|
5112
|
+
for (const opId of kind[bucket]) take(opId);
|
|
4025
5113
|
}
|
|
4026
5114
|
}
|
|
5115
|
+
const deleteIds = new Set(orderedKinds.flatMap((k) => k.deleteOps));
|
|
4027
5116
|
for (const op of ir.operations) {
|
|
4028
|
-
if (!
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
5117
|
+
if (!deleteIds.has(op.id)) take(op.id);
|
|
5118
|
+
}
|
|
5119
|
+
for (const kind of [...orderedKinds].reverse()) {
|
|
5120
|
+
for (const opId of kind.deleteOps) take(opId);
|
|
4032
5121
|
}
|
|
4033
5122
|
return out;
|
|
4034
5123
|
}
|
|
@@ -4082,7 +5171,7 @@ function buildFixturePool(ir, opts = {}) {
|
|
|
4082
5171
|
const ct = pickContentType(op.body);
|
|
4083
5172
|
const media = ct ? op.body.contentTypes[ct] : void 0;
|
|
4084
5173
|
if (media) {
|
|
4085
|
-
fix.bodies = generateMany(media.schema, size, seed + i, resolveRef2);
|
|
5174
|
+
fix.bodies = generateMany(media.schema, size, seed + i, resolveRef2, true);
|
|
4086
5175
|
}
|
|
4087
5176
|
}
|
|
4088
5177
|
if (op.pathParams.length > 0) {
|
|
@@ -4091,7 +5180,11 @@ function buildFixturePool(ir, opts = {}) {
|
|
|
4091
5180
|
if (op.queryParams.length > 0) {
|
|
4092
5181
|
const required = op.queryParams.filter((p) => p.required);
|
|
4093
5182
|
if (required.length > 0) {
|
|
4094
|
-
|
|
5183
|
+
const columns = generateParamPool(required, size, seed + i, resolveRef2);
|
|
5184
|
+
fix.queryParams = Array.from(
|
|
5185
|
+
{ length: size },
|
|
5186
|
+
(_, row) => Object.fromEntries(Object.entries(columns).map(([name, values]) => [name, values[row]]))
|
|
5187
|
+
);
|
|
4095
5188
|
}
|
|
4096
5189
|
}
|
|
4097
5190
|
if (fix.bodies || fix.pathParams || fix.queryParams) {
|
|
@@ -4100,12 +5193,14 @@ function buildFixturePool(ir, opts = {}) {
|
|
|
4100
5193
|
}
|
|
4101
5194
|
return { byOperationId, size };
|
|
4102
5195
|
}
|
|
4103
|
-
function generateMany(schema, count, seed, resolveRef2) {
|
|
5196
|
+
function generateMany(schema, count, seed, resolveRef2, forRequest = false) {
|
|
4104
5197
|
const out = [];
|
|
4105
5198
|
const target = resolveSchemaRef(schema, resolveRef2);
|
|
4106
5199
|
for (let i = 0; i < count; i++) {
|
|
4107
5200
|
try {
|
|
4108
|
-
out.push(
|
|
5201
|
+
out.push(
|
|
5202
|
+
fakeFromSchema(target, { resolveRef: resolveRef2, seed: seed + i, fillOptionals: i === 0, forRequest })
|
|
5203
|
+
);
|
|
4109
5204
|
} catch {
|
|
4110
5205
|
out.push(null);
|
|
4111
5206
|
}
|
|
@@ -4140,13 +5235,54 @@ function makeRefResolver(ir) {
|
|
|
4140
5235
|
return void 0;
|
|
4141
5236
|
};
|
|
4142
5237
|
}
|
|
5238
|
+
function resolve12(ir, schema) {
|
|
5239
|
+
if (typeof schema === "string") return ir.schemas[schema]?.jsonSchema;
|
|
5240
|
+
if (!schema || typeof schema !== "object") return void 0;
|
|
5241
|
+
const js = "jsonSchema" in schema ? schema.jsonSchema : schema;
|
|
5242
|
+
if (js && typeof js.$ref === "string") return ir.schemas[js.$ref]?.jsonSchema;
|
|
5243
|
+
return js;
|
|
5244
|
+
}
|
|
5245
|
+
function buildIdFields(ir) {
|
|
5246
|
+
const out = {};
|
|
5247
|
+
for (const kind of ir.resources.kinds) {
|
|
5248
|
+
const schema = kind.schemaId ? resolve12(ir, kind.schemaId) : void 0;
|
|
5249
|
+
const prop = schema?.properties?.[kind.idField];
|
|
5250
|
+
out[kind.name] = { field: kind.idField, type: prop?.type };
|
|
5251
|
+
}
|
|
5252
|
+
return out;
|
|
5253
|
+
}
|
|
5254
|
+
function buildBodyRefs(ir) {
|
|
5255
|
+
const out = {};
|
|
5256
|
+
for (const op of ir.operations) {
|
|
5257
|
+
if (!op.body || !op.consumes?.length) continue;
|
|
5258
|
+
const ct = pickContentType(op.body);
|
|
5259
|
+
const media = ct ? op.body.contentTypes[ct] : void 0;
|
|
5260
|
+
const props = media ? resolve12(ir, media.schema)?.properties : void 0;
|
|
5261
|
+
if (!props) continue;
|
|
5262
|
+
const refs = {};
|
|
5263
|
+
for (const c of op.consumes) {
|
|
5264
|
+
if (c.field && c.field in props) refs[c.field] = c.kind;
|
|
5265
|
+
}
|
|
5266
|
+
if (Object.keys(refs).length > 0) out[op.id] = refs;
|
|
5267
|
+
}
|
|
5268
|
+
return out;
|
|
5269
|
+
}
|
|
5270
|
+
function binaryFields(ir, schema) {
|
|
5271
|
+
const props = schema ? resolve12(ir, schema)?.properties : void 0;
|
|
5272
|
+
if (!props) return [];
|
|
5273
|
+
return Object.entries(props).filter(([, v]) => {
|
|
5274
|
+
const f = v?.format;
|
|
5275
|
+
return f === "binary" || f === "base64";
|
|
5276
|
+
}).map(([k]) => k);
|
|
5277
|
+
}
|
|
4143
5278
|
function emitConfigJs(ctx) {
|
|
4144
5279
|
const { auth } = ctx;
|
|
4145
5280
|
const base = ctx.baseUrl;
|
|
4146
5281
|
const headerEntries = Object.entries(auth.headers);
|
|
4147
5282
|
const queryEntries = Object.entries(auth.query);
|
|
4148
5283
|
const needsB64 = headerEntries.some(([, v]) => v.startsWith("__BASIC__:"));
|
|
4149
|
-
const
|
|
5284
|
+
const oauth = ctx.ir.auth.filter((p) => p.kind === "oauth2_cc");
|
|
5285
|
+
const importLine = (needsB64 ? "import encoding from 'k6/encoding';\n" : "") + (oauth.length > 0 ? "import http from 'k6/http';\n" : "");
|
|
4150
5286
|
const headersBody = headerEntries.length ? headerEntries.map(([k, v]) => ` ${buildHeaderLine2(k, v)}`).join("\n") : " // no auth headers";
|
|
4151
5287
|
const queryBody = queryEntries.length ? queryEntries.map(([k, v]) => ` ${JSON.stringify(k)}: ${interpolate2(v)},`).join("\n") : "";
|
|
4152
5288
|
return `// AUTO-GENERATED by @loadam/test-k6
|
|
@@ -4156,7 +5292,7 @@ const BASE_URL = (typeof __ENV !== 'undefined' && __ENV.BASE_URL) || ${JSON.stri
|
|
|
4156
5292
|
export function baseUrl() {
|
|
4157
5293
|
return BASE_URL;
|
|
4158
5294
|
}
|
|
4159
|
-
|
|
5295
|
+
${oauth.map(emitOAuthFetcher).join("\n")}
|
|
4160
5296
|
export function authHeaders() {
|
|
4161
5297
|
const h = {};
|
|
4162
5298
|
${headersBody}
|
|
@@ -4179,15 +5315,60 @@ export function buildUrl(path, pathParams, queryParams) {
|
|
|
4179
5315
|
}
|
|
4180
5316
|
const aq = authQuery();
|
|
4181
5317
|
const merged = Object.assign({}, queryParams || {}, aq);
|
|
4182
|
-
const
|
|
4183
|
-
|
|
4184
|
-
|
|
4185
|
-
|
|
5318
|
+
const parts = [];
|
|
5319
|
+
for (const k of Object.keys(merged)) {
|
|
5320
|
+
const v = merged[k];
|
|
5321
|
+
if (v === undefined || v === null || v === '') continue;
|
|
5322
|
+
// Arrays repeat the key (OpenAPI's default form + explode style): ?tags=a&tags=b
|
|
5323
|
+
const values = Array.isArray(v) ? v : [v];
|
|
5324
|
+
for (const one of values) {
|
|
5325
|
+
const s = typeof one === 'object' ? JSON.stringify(one) : String(one);
|
|
5326
|
+
parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(s));
|
|
5327
|
+
}
|
|
5328
|
+
}
|
|
5329
|
+
const qs = parts.join('&');
|
|
4186
5330
|
return BASE_URL + p + (qs ? '?' + qs : '');
|
|
4187
5331
|
}
|
|
4188
5332
|
`;
|
|
4189
5333
|
}
|
|
5334
|
+
function emitOAuthFetcher(p) {
|
|
5335
|
+
if (p.kind !== "oauth2_cc") return "";
|
|
5336
|
+
const fn = `__oauth_${p.id.replace(/[^A-Za-z0-9_]/g, "_")}`;
|
|
5337
|
+
const scope = p.scopes?.length ? `&scope=' + encodeURIComponent(${JSON.stringify(p.scopes.join(" "))}) + '` : "";
|
|
5338
|
+
return `
|
|
5339
|
+
let ${fn}_token = null;
|
|
5340
|
+
function ${fn}() {
|
|
5341
|
+
if (${fn}_token) return ${fn}_token;
|
|
5342
|
+
const id = __ENV.${p.clientIdEnv};
|
|
5343
|
+
const secret = __ENV.${p.clientSecretEnv};
|
|
5344
|
+
if (!id || !secret) return null;
|
|
5345
|
+
const tokenUrl = ${JSON.stringify(p.tokenUrl)};
|
|
5346
|
+
const url = /^https?:/i.test(tokenUrl)
|
|
5347
|
+
? tokenUrl
|
|
5348
|
+
: tokenUrl.charAt(0) === '/'
|
|
5349
|
+
? BASE_URL.replace(/^(https?:\\/\\/[^/]+).*$/i, '$1') + tokenUrl
|
|
5350
|
+
: BASE_URL.replace(/\\/$/, '') + '/' + tokenUrl;
|
|
5351
|
+
const res = http.post(
|
|
5352
|
+
url,
|
|
5353
|
+
'grant_type=client_credentials&client_id=' + encodeURIComponent(id) + '&client_secret=' + encodeURIComponent(secret) + '${scope}',
|
|
5354
|
+
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, tags: { name: '__oauth_token' } },
|
|
5355
|
+
);
|
|
5356
|
+
let body = {};
|
|
5357
|
+
try { body = res.json(); } catch (_) { body = {}; }
|
|
5358
|
+
if (res.status >= 200 && res.status < 300 && body && body.access_token) {
|
|
5359
|
+
${fn}_token = body.access_token;
|
|
5360
|
+
} else {
|
|
5361
|
+
console.warn('loadam: OAuth2 token request to ' + url + ' failed with ' + res.status);
|
|
5362
|
+
}
|
|
5363
|
+
return ${fn}_token;
|
|
5364
|
+
}
|
|
5365
|
+
`;
|
|
5366
|
+
}
|
|
4190
5367
|
function buildHeaderLine2(name, value) {
|
|
5368
|
+
if (value.startsWith("__OAUTH2__:")) {
|
|
5369
|
+
const fn = `__oauth_${value.slice("__OAUTH2__:".length).replace(/[^A-Za-z0-9_]/g, "_")}`;
|
|
5370
|
+
return `{ const t = ${fn}(); if (t) { h[${JSON.stringify(name)}] = 'Bearer ' + t; } }`;
|
|
5371
|
+
}
|
|
4191
5372
|
if (value.startsWith("__BASIC__:")) {
|
|
4192
5373
|
const [, userEnv, passEnv] = value.split(":");
|
|
4193
5374
|
return `if (__ENV.${userEnv} && __ENV.${passEnv}) { h.Authorization = 'Basic ' + encoding.b64encode(__ENV.${userEnv} + ':' + __ENV.${passEnv}); }`;
|
|
@@ -4204,7 +5385,7 @@ function emitFlowJs(ctx) {
|
|
|
4204
5385
|
for (let i = 0; i < ops.length; i++) {
|
|
4205
5386
|
const op = ops[i];
|
|
4206
5387
|
if (!op) continue;
|
|
4207
|
-
lines.push(emitOpCall(
|
|
5388
|
+
lines.push(emitOpCall(ctx.ir, op));
|
|
4208
5389
|
}
|
|
4209
5390
|
return `// AUTO-GENERATED by @loadam/test-k6
|
|
4210
5391
|
import http from 'k6/http';
|
|
@@ -4236,10 +5417,143 @@ function pickFixture(opId, slot, idx) {
|
|
|
4236
5417
|
return undefined;
|
|
4237
5418
|
}
|
|
4238
5419
|
|
|
4239
|
-
|
|
4240
|
-
|
|
4241
|
-
|
|
5420
|
+
// Resource kind \u2192 { field, type } of its id. Inferred from the spec.
|
|
5421
|
+
const ID_FIELDS = ${JSON.stringify(buildIdFields(ctx.ir))};
|
|
5422
|
+
|
|
5423
|
+
// Operation id \u2192 { bodyField: kind } for body fields that reference another resource.
|
|
5424
|
+
const BODY_REFS = ${JSON.stringify(buildBodyRefs(ctx.ir))};
|
|
5425
|
+
|
|
5426
|
+
function __json(resp) {
|
|
5427
|
+
try { return resp.json(); } catch (_) { return undefined; }
|
|
5428
|
+
}
|
|
5429
|
+
|
|
5430
|
+
function __scalar(v) {
|
|
5431
|
+
return v !== undefined && v !== null && typeof v !== 'object' && v !== '';
|
|
5432
|
+
}
|
|
5433
|
+
|
|
5434
|
+
// Last path segment of a URL: 'https://x/api/ability/1/' \u2192 '1'.
|
|
5435
|
+
function __lastSegment(u) {
|
|
5436
|
+
const segs = String(u).split('?')[0].split('#')[0].split('/').filter(function (s) { return s; });
|
|
5437
|
+
return segs.length > 1 ? decodeURIComponent(segs[segs.length - 1]) : undefined;
|
|
5438
|
+
}
|
|
5439
|
+
|
|
5440
|
+
function __coerce(kind, id) {
|
|
5441
|
+
const t = ID_FIELDS[kind] && ID_FIELDS[kind].type;
|
|
5442
|
+
if ((t === 'integer' || t === 'number') && typeof id === 'string' && /^-?\\d+(\\.\\d+)?$/.test(id)) return Number(id);
|
|
5443
|
+
return id;
|
|
5444
|
+
}
|
|
5445
|
+
|
|
5446
|
+
function __idOf(kind, obj) {
|
|
5447
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return undefined;
|
|
5448
|
+
const fields = [ID_FIELDS[kind] && ID_FIELDS[kind].field, 'id', 'uuid'];
|
|
5449
|
+
for (const f of fields) {
|
|
5450
|
+
if (f && __scalar(obj[f])) return obj[f];
|
|
5451
|
+
}
|
|
5452
|
+
// Hypermedia: { name, url: '.../ability/1/' } \u2014 the self link carries the id.
|
|
5453
|
+
for (const f of ['url', 'href', 'self']) {
|
|
5454
|
+
if (typeof obj[f] === 'string') {
|
|
5455
|
+
const seg = __lastSegment(obj[f]);
|
|
5456
|
+
if (seg !== undefined) return __coerce(kind, seg);
|
|
5457
|
+
}
|
|
5458
|
+
}
|
|
5459
|
+
for (const f of ['name', 'slug']) {
|
|
5460
|
+
if (__scalar(obj[f])) return obj[f];
|
|
5461
|
+
}
|
|
5462
|
+
return undefined;
|
|
5463
|
+
}
|
|
5464
|
+
|
|
5465
|
+
// The entity id in a response body, looking through one envelope level ({ data: {...} }).
|
|
5466
|
+
function __entityId(kind, body) {
|
|
5467
|
+
const direct = __idOf(kind, body);
|
|
5468
|
+
if (direct !== undefined) return direct;
|
|
5469
|
+
if (body && typeof body === 'object' && !Array.isArray(body)) {
|
|
5470
|
+
for (const k in body) {
|
|
5471
|
+
const id = __idOf(kind, body[k]);
|
|
5472
|
+
if (id !== undefined) return id;
|
|
5473
|
+
}
|
|
5474
|
+
}
|
|
5475
|
+
return undefined;
|
|
5476
|
+
}
|
|
5477
|
+
|
|
5478
|
+
// The entity list in a response body: a bare array or the first array property.
|
|
5479
|
+
function __entityList(body) {
|
|
5480
|
+
if (Array.isArray(body)) return body;
|
|
5481
|
+
if (body && typeof body === 'object') {
|
|
5482
|
+
for (const k in body) if (Array.isArray(body[k])) return body[k];
|
|
5483
|
+
}
|
|
5484
|
+
return [];
|
|
5485
|
+
}
|
|
5486
|
+
|
|
5487
|
+
function __captureCreated(state, kind, resp) {
|
|
5488
|
+
if (resp.status < 200 || resp.status >= 300) return;
|
|
5489
|
+
let id = __entityId(kind, __json(resp));
|
|
5490
|
+
if (id === undefined) {
|
|
5491
|
+
// 201 + Location: /things/42 with no body.
|
|
5492
|
+
const loc = resp.headers.Location || resp.headers.location;
|
|
5493
|
+
const seg = loc ? String(loc).split('?')[0].replace(/\\/+$/, '').split('/').pop() : '';
|
|
5494
|
+
if (seg) id = __coerce(kind, decodeURIComponent(seg));
|
|
4242
5495
|
}
|
|
5496
|
+
if (id !== undefined) (state[kind] = state[kind] || []).push(id);
|
|
5497
|
+
}
|
|
5498
|
+
|
|
5499
|
+
// Ids seen in list responses: a fallback for kinds this flow cannot create.
|
|
5500
|
+
function __captureListed(state, kind, resp) {
|
|
5501
|
+
if (resp.status < 200 || resp.status >= 300) return;
|
|
5502
|
+
const items = __entityList(__json(resp));
|
|
5503
|
+
for (let i = 0; i < items.length && i < 20; i++) {
|
|
5504
|
+
const id = __idOf(kind, items[i]);
|
|
5505
|
+
if (id !== undefined) (state['~' + kind] = state['~' + kind] || []).push(id);
|
|
5506
|
+
}
|
|
5507
|
+
}
|
|
5508
|
+
|
|
5509
|
+
// Prefer the id this iteration created; fall back to one seen in a list.
|
|
5510
|
+
function __pickId(state, kind, idx) {
|
|
5511
|
+
if (state[kind] && state[kind].length > 0) return state[kind][state[kind].length - 1];
|
|
5512
|
+
const listed = state['~' + kind];
|
|
5513
|
+
if (listed && listed.length > 0) return listed[idx % listed.length];
|
|
5514
|
+
return undefined;
|
|
5515
|
+
}
|
|
5516
|
+
|
|
5517
|
+
function withRefs(opId, body, state, idx) {
|
|
5518
|
+
const refs = BODY_REFS[opId];
|
|
5519
|
+
if (!refs || !body || typeof body !== 'object' || Array.isArray(body)) return body;
|
|
5520
|
+
const out = Object.assign({}, body);
|
|
5521
|
+
for (const field in refs) {
|
|
5522
|
+
const id = __pickId(state, refs[field], idx);
|
|
5523
|
+
if (id !== undefined) out[field] = id;
|
|
5524
|
+
}
|
|
5525
|
+
return out;
|
|
5526
|
+
}
|
|
5527
|
+
|
|
5528
|
+
// Form bodies: flat key=value pairs (nested values as JSON).
|
|
5529
|
+
function __form(body) {
|
|
5530
|
+
const out = {};
|
|
5531
|
+
if (!body || typeof body !== 'object') return out;
|
|
5532
|
+
for (const k in body) {
|
|
5533
|
+
const v = body[k];
|
|
5534
|
+
if (v === undefined || v === null) continue;
|
|
5535
|
+
out[k] = typeof v === 'object' ? JSON.stringify(v) : String(v);
|
|
5536
|
+
}
|
|
5537
|
+
return out;
|
|
5538
|
+
}
|
|
5539
|
+
|
|
5540
|
+
// Multipart: file fields become http.file uploads, the rest plain parts.
|
|
5541
|
+
function __multipart(body, fileFields) {
|
|
5542
|
+
const out = __form(body);
|
|
5543
|
+
for (const f of fileFields) {
|
|
5544
|
+
out[f] = http.file('loadam test bytes', 'upload.bin', 'application/octet-stream');
|
|
5545
|
+
}
|
|
5546
|
+
return out;
|
|
5547
|
+
}
|
|
5548
|
+
|
|
5549
|
+
function __text(body) {
|
|
5550
|
+
if (typeof body === 'string' && body !== '') return body;
|
|
5551
|
+
return body === undefined || body === null ? 'loadam test' : JSON.stringify(body);
|
|
5552
|
+
}
|
|
5553
|
+
|
|
5554
|
+
function pickPathParam(opId, name, state, kind, idx) {
|
|
5555
|
+
const known = kind ? __pickId(state, kind, idx) : undefined;
|
|
5556
|
+
if (known !== undefined) return known;
|
|
4243
5557
|
const pool = fixtures[0][opId];
|
|
4244
5558
|
if (pool && pool.pathParams && pool.pathParams[name]) {
|
|
4245
5559
|
const arr = pool.pathParams[name];
|
|
@@ -4249,8 +5563,8 @@ function pickPathParam(opId, name, state, kind, idx) {
|
|
|
4249
5563
|
}
|
|
4250
5564
|
|
|
4251
5565
|
/**
|
|
4252
|
-
* Run one flow iteration. \`state\`
|
|
4253
|
-
*
|
|
5566
|
+
* Run one flow iteration. \`state\` collects ids by ResourceKind (created ones,
|
|
5567
|
+
* plus ids seen in list responses under '~Kind') so later ops use real ids.
|
|
4254
5568
|
*/
|
|
4255
5569
|
export function runFlow(iter) {
|
|
4256
5570
|
const state = {};
|
|
@@ -4259,7 +5573,7 @@ ${lines.join("\n")}
|
|
|
4259
5573
|
}
|
|
4260
5574
|
`;
|
|
4261
5575
|
}
|
|
4262
|
-
function emitOpCall(
|
|
5576
|
+
function emitOpCall(ir, op) {
|
|
4263
5577
|
const headersExpr = "Object.assign({}, authHeaders())";
|
|
4264
5578
|
const opIdLit = JSON.stringify(op.id);
|
|
4265
5579
|
const pathParamLines = [];
|
|
@@ -4268,30 +5582,25 @@ function emitOpCall(op, _index) {
|
|
|
4268
5582
|
const entries = [];
|
|
4269
5583
|
for (const p of op.pathParams) {
|
|
4270
5584
|
const ident = safeIdent(p.name);
|
|
4271
|
-
const
|
|
5585
|
+
const kindLit2 = p.resourceKind ? JSON.stringify(p.resourceKind) : "undefined";
|
|
4272
5586
|
pathParamLines.push(
|
|
4273
|
-
` const __pp_${ident} = pickPathParam(${opIdLit}, ${JSON.stringify(p.name)}, state, ${
|
|
5587
|
+
` const __pp_${ident} = pickPathParam(${opIdLit}, ${JSON.stringify(p.name)}, state, ${kindLit2}, __ITER);`
|
|
4274
5588
|
);
|
|
4275
5589
|
entries.push(`${JSON.stringify(p.name)}: __pp_${ident}`);
|
|
4276
5590
|
}
|
|
4277
5591
|
pathParamObj = `{ ${entries.join(", ")} }`;
|
|
4278
5592
|
}
|
|
4279
|
-
const
|
|
5593
|
+
const requiredQuery2 = op.queryParams.filter((p) => p.required);
|
|
4280
5594
|
let queryParamObj = "undefined";
|
|
4281
|
-
if (
|
|
4282
|
-
const entries =
|
|
5595
|
+
if (requiredQuery2.length > 0) {
|
|
5596
|
+
const entries = requiredQuery2.map(
|
|
4283
5597
|
(p) => `${JSON.stringify(p.name)}: (function () { const f = pickFixture(${opIdLit}, 'queryParams', __ITER); return f ? f[${JSON.stringify(p.name)}] : undefined; })()`
|
|
4284
5598
|
).join(", ");
|
|
4285
5599
|
queryParamObj = `{ ${entries} }`;
|
|
4286
5600
|
}
|
|
4287
|
-
const requestLine = emitRequestCall(op, headersExpr, pathParamObj, queryParamObj);
|
|
4288
|
-
const
|
|
4289
|
-
|
|
4290
|
-
try { body = resp.json(); } catch (_) { body = undefined; }
|
|
4291
|
-
if (body && body.id !== undefined) {
|
|
4292
|
-
(state[${JSON.stringify(op.resourceKind)}] = state[${JSON.stringify(op.resourceKind)}] || []).push(body.id);
|
|
4293
|
-
}
|
|
4294
|
-
}` : "";
|
|
5601
|
+
const requestLine = emitRequestCall(ir, op, headersExpr, pathParamObj, queryParamObj);
|
|
5602
|
+
const kindLit = op.resourceKind ? JSON.stringify(op.resourceKind) : void 0;
|
|
5603
|
+
const captureId = kindLit && op.resourceAction === "create" ? ` __captureCreated(state, ${kindLit}, resp);` : kindLit && op.resourceAction === "list" ? ` __captureListed(state, ${kindLit}, resp);` : "";
|
|
4295
5604
|
return ` // ${op.method} ${op.path} \u2014 ${op.id}
|
|
4296
5605
|
{
|
|
4297
5606
|
${pathParamLines.join("\n")}
|
|
@@ -4303,13 +5612,36 @@ ${captureId}
|
|
|
4303
5612
|
}
|
|
4304
5613
|
`;
|
|
4305
5614
|
}
|
|
4306
|
-
function
|
|
5615
|
+
function encodeBody(ir, op, headersExpr) {
|
|
5616
|
+
const opIdLit = JSON.stringify(op.id);
|
|
5617
|
+
const fixture = `withRefs(${opIdLit}, pickFixture(${opIdLit}, 'bodies', __ITER), state, __ITER)`;
|
|
5618
|
+
const ct = (op.body && pickContentType(op.body)) ?? "application/json";
|
|
5619
|
+
const base = ct.split(";")[0].trim().toLowerCase();
|
|
5620
|
+
const withCT = `Object.assign(${headersExpr}, { 'Content-Type': ${JSON.stringify(ct)} })`;
|
|
5621
|
+
if (base === "application/json" || base.endsWith("+json")) {
|
|
5622
|
+
return { bodyExpr: `JSON.stringify(${fixture})`, headersWithCT: withCT };
|
|
5623
|
+
}
|
|
5624
|
+
if (base === "application/x-www-form-urlencoded") {
|
|
5625
|
+
return { bodyExpr: `__form(${fixture})`, headersWithCT: withCT };
|
|
5626
|
+
}
|
|
5627
|
+
if (base === "multipart/form-data") {
|
|
5628
|
+
const files = binaryFields(ir, op.body?.contentTypes[ct]?.schema);
|
|
5629
|
+
return {
|
|
5630
|
+
bodyExpr: `__multipart(${fixture}, ${JSON.stringify(files)})`,
|
|
5631
|
+
headersWithCT: headersExpr
|
|
5632
|
+
};
|
|
5633
|
+
}
|
|
5634
|
+
if (base.startsWith("text/")) {
|
|
5635
|
+
return { bodyExpr: `__text(${fixture})`, headersWithCT: withCT };
|
|
5636
|
+
}
|
|
5637
|
+
return { bodyExpr: "'loadam test bytes'", headersWithCT: withCT };
|
|
5638
|
+
}
|
|
5639
|
+
function emitRequestCall(ir, op, headersExpr, pathParamObj, queryParamObj) {
|
|
4307
5640
|
const url = `buildUrl(${JSON.stringify(op.path)}, ${pathParamObj}, ${queryParamObj})`;
|
|
4308
5641
|
const method = op.method.toLowerCase();
|
|
4309
5642
|
const hasBody = !!op.body;
|
|
4310
5643
|
const opIdLit = JSON.stringify(op.id);
|
|
4311
|
-
const bodyExpr = hasBody ?
|
|
4312
|
-
const headersWithCT = hasBody ? `Object.assign(${headersExpr}, { 'Content-Type': 'application/json' })` : headersExpr;
|
|
5644
|
+
const { bodyExpr, headersWithCT } = hasBody ? encodeBody(ir, op, headersExpr) : { bodyExpr: "null", headersWithCT: headersExpr };
|
|
4313
5645
|
if (method === "get" || method === "head" || method === "options") {
|
|
4314
5646
|
return `http.${method}(${url}, { headers: ${headersExpr}, tags: { name: ${opIdLit} } })`;
|
|
4315
5647
|
}
|
|
@@ -4415,7 +5747,7 @@ ${ctx.auth.notes.map((n) => `- ${n}`).join("\n")}
|
|
|
4415
5747
|
` : "";
|
|
4416
5748
|
return `# ${ctx.ir.meta.title} \u2014 k6 test rig
|
|
4417
5749
|
|
|
4418
|
-
Generated by [loadam](https://github.com/loadam) from your API spec.
|
|
5750
|
+
Generated by [loadam](https://github.com/DesmondSanctity/loadam) from your API spec.
|
|
4419
5751
|
|
|
4420
5752
|
## Run
|
|
4421
5753
|
|
|
@@ -4440,8 +5772,8 @@ k6 run load.js
|
|
|
4440
5772
|
${notes}
|
|
4441
5773
|
## Regenerating
|
|
4442
5774
|
|
|
4443
|
-
Re-run \`loadam test\` to refresh.
|
|
4444
|
-
|
|
5775
|
+
Re-run \`loadam test\` to refresh. Regenerating overwrites these files, so commit
|
|
5776
|
+
your edits first and review the diff afterwards.
|
|
4445
5777
|
`;
|
|
4446
5778
|
}
|
|
4447
5779
|
function slugify3(s) {
|
|
@@ -4470,8 +5802,8 @@ function compileK6(ir, opts = {}) {
|
|
|
4470
5802
|
}
|
|
4471
5803
|
|
|
4472
5804
|
// src/util/interactive.ts
|
|
4473
|
-
import { chmod, readFile as
|
|
4474
|
-
import { resolve as
|
|
5805
|
+
import { chmod, readFile as readFile10, writeFile as writeFile7 } from "fs/promises";
|
|
5806
|
+
import { resolve as resolve13 } from "path";
|
|
4475
5807
|
import { confirm, password, select } from "@inquirer/prompts";
|
|
4476
5808
|
function isInteractive(noInteractiveFlag) {
|
|
4477
5809
|
if (noInteractiveFlag) return false;
|
|
@@ -4508,7 +5840,7 @@ async function confirmContinue(message) {
|
|
|
4508
5840
|
return await confirm({ message, default: true });
|
|
4509
5841
|
}
|
|
4510
5842
|
async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
|
|
4511
|
-
const path =
|
|
5843
|
+
const path = resolve13(dir, ".env");
|
|
4512
5844
|
const existing = await readEnvFile(path);
|
|
4513
5845
|
const written = [];
|
|
4514
5846
|
const preserved = [];
|
|
@@ -4535,7 +5867,7 @@ async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
|
|
|
4535
5867
|
}
|
|
4536
5868
|
async function readEnvFile(path) {
|
|
4537
5869
|
try {
|
|
4538
|
-
const text = await
|
|
5870
|
+
const text = await readFile10(path, "utf8");
|
|
4539
5871
|
const out = {};
|
|
4540
5872
|
for (const raw of text.split(/\r?\n/)) {
|
|
4541
5873
|
const line = raw.trim();
|
|
@@ -4561,15 +5893,16 @@ function registerTestCommand(program) {
|
|
|
4561
5893
|
).option("--fixture-size <n>", "number of fixtures per slot", "10").option("--seed <n>", "deterministic seed for fixture generation", "1").option(
|
|
4562
5894
|
"--mode <mode>",
|
|
4563
5895
|
"run after generating: smoke | load | both | skip (default: prompt if interactive, skip otherwise)"
|
|
4564
|
-
).option("--no-interactive", "disable all prompts (CI mode)", false).option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runTest));
|
|
5896
|
+
).option("--no-interactive", "disable all prompts (CI mode)", false).option("--config <path>", CONFIG_OPTION_HELP).option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runTest));
|
|
4565
5897
|
}
|
|
4566
5898
|
async function runTest(spec, opts) {
|
|
4567
5899
|
const out = makeOutput(!!opts.json);
|
|
4568
|
-
const specPath =
|
|
5900
|
+
const specPath = resolve14(spec);
|
|
4569
5901
|
out.start(`Parsing OpenAPI spec: ${specPath}`);
|
|
4570
|
-
const specSource = await
|
|
5902
|
+
const specSource = await readFile11(specPath, "utf8");
|
|
4571
5903
|
const ir = await fromOpenApiFile(specPath);
|
|
4572
5904
|
inferResourceGraph(ir);
|
|
5905
|
+
await applyUserConfig(ir, specPath, opts.config);
|
|
4573
5906
|
parseIR(ir);
|
|
4574
5907
|
out.success(`Parsed ${ir.operations.length} operation${ir.operations.length === 1 ? "" : "s"}`);
|
|
4575
5908
|
const fixtureSize = Number.parseInt(opts.fixtureSize ?? "10", 10);
|
|
@@ -4583,11 +5916,11 @@ async function runTest(spec, opts) {
|
|
|
4583
5916
|
fixtureSize: Number.isFinite(fixtureSize) ? fixtureSize : 10,
|
|
4584
5917
|
seed: Number.isFinite(seed) ? seed : 1
|
|
4585
5918
|
});
|
|
4586
|
-
const outDir =
|
|
5919
|
+
const outDir = resolve14(opts.output);
|
|
4587
5920
|
await mkdir4(outDir, { recursive: true });
|
|
4588
5921
|
for (const [rel, contents] of Object.entries(result.files)) {
|
|
4589
|
-
const full =
|
|
4590
|
-
await mkdir4(
|
|
5922
|
+
const full = resolve14(outDir, rel);
|
|
5923
|
+
await mkdir4(dirname4(full), { recursive: true });
|
|
4591
5924
|
await writeFile8(full, contents, "utf8");
|
|
4592
5925
|
}
|
|
4593
5926
|
const fileCount = Object.keys(result.files).length;
|
|
@@ -4696,7 +6029,7 @@ function parseModeFlag(raw) {
|
|
|
4696
6029
|
return raw;
|
|
4697
6030
|
}
|
|
4698
6031
|
function getSessionRoot(outDir) {
|
|
4699
|
-
return
|
|
6032
|
+
return resolve14(outDir, "..");
|
|
4700
6033
|
}
|
|
4701
6034
|
async function fileExists(p) {
|
|
4702
6035
|
try {
|
|
@@ -4725,13 +6058,15 @@ async function maybeRunWithSession(input) {
|
|
|
4725
6058
|
const allPassed = [];
|
|
4726
6059
|
const allFailed = [];
|
|
4727
6060
|
const summary = {};
|
|
6061
|
+
const env = envForRun(await readEnvFile(join7(cwd, ".env")));
|
|
6062
|
+
const stdout = out.json ? "stderr" : "inherit";
|
|
4728
6063
|
if (mode === "smoke" || mode === "both") {
|
|
4729
6064
|
if (!out.json) {
|
|
4730
6065
|
out.step("");
|
|
4731
6066
|
out.step("Running k6 smoke test...");
|
|
4732
6067
|
}
|
|
4733
|
-
const summaryPath =
|
|
4734
|
-
result.smokeExit = await runK6({ cwd, script: "smoke.js", summaryPath });
|
|
6068
|
+
const summaryPath = join7(session.dir, "k6-smoke-summary.json");
|
|
6069
|
+
result.smokeExit = await runK6({ cwd, script: "smoke.js", summaryPath, env, stdout });
|
|
4735
6070
|
if (await fileExists(summaryPath)) session.registerArtefact("k6-smoke-summary.json");
|
|
4736
6071
|
const digest = await digestK6Summary(summaryPath);
|
|
4737
6072
|
if (digest) {
|
|
@@ -4761,8 +6096,8 @@ async function maybeRunWithSession(input) {
|
|
|
4761
6096
|
out.step("");
|
|
4762
6097
|
out.step("Running k6 load test...");
|
|
4763
6098
|
}
|
|
4764
|
-
const summaryPath =
|
|
4765
|
-
result.loadExit = await runK6({ cwd, script: "load.js", summaryPath });
|
|
6099
|
+
const summaryPath = join7(session.dir, "k6-load-summary.json");
|
|
6100
|
+
result.loadExit = await runK6({ cwd, script: "load.js", summaryPath, env, stdout });
|
|
4766
6101
|
if (await fileExists(summaryPath)) session.registerArtefact("k6-load-summary.json");
|
|
4767
6102
|
const digest = await digestK6Summary(summaryPath);
|
|
4768
6103
|
if (digest) {
|
|
@@ -4805,8 +6140,8 @@ async function fetchLatestVersion(timeoutMs = 3e3) {
|
|
|
4805
6140
|
}
|
|
4806
6141
|
}
|
|
4807
6142
|
function compareVersions(a, b) {
|
|
4808
|
-
const
|
|
4809
|
-
const [aa, bb] = [
|
|
6143
|
+
const parse2 = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
6144
|
+
const [aa, bb] = [parse2(a), parse2(b)];
|
|
4810
6145
|
for (let i = 0; i < 3; i++) {
|
|
4811
6146
|
const d = (aa[i] ?? 0) - (bb[i] ?? 0);
|
|
4812
6147
|
if (d !== 0) return d > 0 ? 1 : -1;
|
|
@@ -4876,7 +6211,7 @@ ${dim}${TAGLINE}${reset}
|
|
|
4876
6211
|
}
|
|
4877
6212
|
|
|
4878
6213
|
// src/program.ts
|
|
4879
|
-
var VERSION2 = true ? "0.
|
|
6214
|
+
var VERSION2 = true ? "0.3.0" : "0.0.0";
|
|
4880
6215
|
function buildProgram() {
|
|
4881
6216
|
const program = new Command();
|
|
4882
6217
|
program.name("loadam").description(
|