loadam 0.2.3 → 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/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: "API_PASSWORD"
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: "API_PASSWORD"
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 result = importCurl(input);
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
  `);
@@ -282,8 +369,8 @@ var SESSION_SCHEMA_VERSION = 1;
282
369
  var SESSIONS_DIR = "sessions";
283
370
  async function createSession(input) {
284
371
  const startedAt = /* @__PURE__ */ new Date();
285
- const slug = input.slug ? sanitizeSlug(input.slug) : input.command;
286
- const id = `${formatTimestamp(startedAt)}-${slug}`;
372
+ const slug2 = input.slug ? sanitizeSlug(input.slug) : input.command;
373
+ const id = `${formatTimestamp(startedAt)}-${slug2}`;
287
374
  const root = resolve(input.outRoot, SESSIONS_DIR);
288
375
  const dir = resolve(root, id);
289
376
  await mkdir(dir, { recursive: true });
@@ -319,6 +406,9 @@ async function createSession(input) {
319
406
  await writeFile(full, contents);
320
407
  if (!meta.artefacts.includes(relPath)) meta.artefacts.push(relPath);
321
408
  },
409
+ registerArtefact(relPath) {
410
+ if (!meta.artefacts.includes(relPath)) meta.artefacts.push(relPath);
411
+ },
322
412
  async finalize({ exitCode, thresholds, summary }) {
323
413
  const endedAt = /* @__PURE__ */ new Date();
324
414
  meta.endedAt = endedAt.toISOString();
@@ -594,8 +684,8 @@ function registerCompletionCommand(program) {
594
684
  }
595
685
 
596
686
  // src/commands/contract.ts
597
- import { mkdir as mkdir2, readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
598
- import { dirname, resolve as resolve4 } from "path";
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";
599
689
 
600
690
  // ../core/dist/index.js
601
691
  import { z } from "zod";
@@ -636,7 +726,7 @@ var ServerVariable = z.object({
636
726
  var Server = z.object({
637
727
  url: z.string(),
638
728
  description: z.string().optional(),
639
- variables: z.record(ServerVariable).optional()
729
+ variables: z.record(z.string(), ServerVariable).optional()
640
730
  });
641
731
  var AuthProfile = z.discriminatedUnion("kind", [
642
732
  z.object({ id: z.string(), kind: z.literal("none") }),
@@ -700,6 +790,7 @@ var Param = z.object({
700
790
  var RequestBody = z.object({
701
791
  required: z.boolean(),
702
792
  contentTypes: z.record(
793
+ z.string(),
703
794
  z.object({
704
795
  schema: SchemaRefOrInline,
705
796
  examples: z.array(z.unknown()).optional()
@@ -711,6 +802,7 @@ var ResponseDef = z.object({
711
802
  description: z.string().optional(),
712
803
  headers: z.array(Param).optional(),
713
804
  contentTypes: z.record(
805
+ z.string(),
714
806
  z.object({
715
807
  schema: SchemaRefOrInline,
716
808
  examples: z.array(z.unknown()).optional()
@@ -773,8 +865,8 @@ var ResourceGraph = z.object({
773
865
  var OperationExample = z.object({
774
866
  source: z.enum(["spec", "har", "user"]),
775
867
  request: z.object({
776
- params: z.record(z.unknown()).optional(),
777
- headers: z.record(z.string()).optional(),
868
+ params: z.record(z.string(), z.unknown()).optional(),
869
+ headers: z.record(z.string(), z.string()).optional(),
778
870
  body: z.unknown().optional()
779
871
  }),
780
872
  response: z.object({
@@ -783,8 +875,8 @@ var OperationExample = z.object({
783
875
  }).optional()
784
876
  });
785
877
  var ExampleSet = z.object({
786
- byOperation: z.record(z.array(OperationExample)).default({}),
787
- 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({})
788
880
  });
789
881
  var ParamBinding = z.object({
790
882
  paramName: z.string(),
@@ -837,7 +929,7 @@ var IR = z.object({
837
929
  meta: Meta,
838
930
  servers: z.array(Server).default([]),
839
931
  auth: z.array(AuthProfile).default([]),
840
- schemas: z.record(Schema).default({}),
932
+ schemas: z.record(z.string(), Schema).default({}),
841
933
  operations: z.array(Operation).default([]),
842
934
  resources: ResourceGraph.default({ kinds: [], edges: [] }),
843
935
  examples: ExampleSet.default({ byOperation: {}, byEntity: {} }),
@@ -1090,6 +1182,74 @@ function isRef(v) {
1090
1182
  }
1091
1183
 
1092
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
+ }
1093
1253
  var IRREGULAR = {
1094
1254
  people: "person",
1095
1255
  children: "child",
@@ -1132,16 +1292,18 @@ function preserveCase(source, replacement) {
1132
1292
  return replacement;
1133
1293
  }
1134
1294
  function toEntityName(segment) {
1135
- const singular = singularize(segment);
1136
- return singular.split(/[-_]/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
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("");
1137
1298
  }
1138
1299
  function inferResourceGraph(ir) {
1139
1300
  const opsByKind = /* @__PURE__ */ new Map();
1140
1301
  const kindIdField = /* @__PURE__ */ new Map();
1141
1302
  const kindSchemaId = /* @__PURE__ */ new Map();
1142
1303
  const edges = [];
1304
+ const allPaths = new Set(ir.operations.map((o) => o.path));
1143
1305
  for (const op of ir.operations) {
1144
- const classification = classifyOperation(op, ir.schemas);
1306
+ const classification = classifyOperation(op, ir.schemas, allPaths);
1145
1307
  if (!classification) continue;
1146
1308
  const { kind, action, idField, schemaId } = classification;
1147
1309
  op.resourceKind = kind;
@@ -1201,6 +1363,40 @@ function inferResourceGraph(ir) {
1201
1363
  deleteOps: ops.filter((o) => o.resourceAction === "delete").map((o) => o.id)
1202
1364
  });
1203
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);
1204
1400
  const seen = /* @__PURE__ */ new Set();
1205
1401
  const dedupedEdges = edges.filter((e) => {
1206
1402
  const key = `${e.from}|${e.to}|${e.via.operationId}|${e.via.param}`;
@@ -1211,9 +1407,16 @@ function inferResourceGraph(ir) {
1211
1407
  ir.resources = { kinds, edges: dedupedEdges };
1212
1408
  return ir;
1213
1409
  }
1214
- function classifyOperation(op, schemas) {
1410
+ function classifyOperation(op, schemas, allPaths) {
1215
1411
  const segments = op.path.split("/").filter(Boolean);
1216
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
+ }
1217
1420
  const last = segments[segments.length - 1];
1218
1421
  const lastIsParam = isParamSegment(last);
1219
1422
  let collectionSegment;
@@ -1248,6 +1451,37 @@ function classifyOperation(op, schemas) {
1248
1451
  const { schemaId, idField } = pickSuccessSchema(op, schemas);
1249
1452
  return { kind, action, idField, schemaId };
1250
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
+ }
1251
1485
  function isParamSegment(seg) {
1252
1486
  return seg.startsWith("{") && seg.endsWith("}");
1253
1487
  }
@@ -1263,11 +1497,23 @@ function pickSuccessSchema(op, schemas) {
1263
1497
  if (!sid) return {};
1264
1498
  return { schemaId: sid, idField: pickIdField(schemas[sid]) };
1265
1499
  }
1266
- function pickIdField(schema) {
1500
+ function schemaProps(schema) {
1267
1501
  const js = schema?.jsonSchema;
1268
- const props = js?.properties;
1269
- if (!props) return void 0;
1270
- const keys = Object.keys(props);
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;
1271
1517
  if (keys.includes("id")) return "id";
1272
1518
  if (keys.includes("uuid")) return "uuid";
1273
1519
  const idLike = keys.find((k) => /^id$|_id$/i.test(k));
@@ -1283,12 +1529,25 @@ function resolveTopRef(schema, schemas) {
1283
1529
  }
1284
1530
  const inner = unwrapArrayItem(schema.jsonSchema);
1285
1531
  if (inner && typeof inner === "string") return inner;
1532
+ const enveloped = unwrapEnvelope(schema.jsonSchema);
1533
+ if (enveloped) return enveloped;
1286
1534
  if (typeof schema.jsonSchema === "object" && schema.jsonSchema !== null) {
1287
1535
  const direct = schema.jsonSchema.$ref;
1288
1536
  if (direct) return direct;
1289
1537
  }
1290
1538
  return void 0;
1291
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
+ }
1292
1551
  function unwrapArrayItem(js) {
1293
1552
  if (!js || typeof js !== "object") return void 0;
1294
1553
  const obj = js;
@@ -1395,23 +1654,218 @@ function graphStats(graph) {
1395
1654
  orphanKinds
1396
1655
  };
1397
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
+ }
1398
1714
 
1399
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
+ }
1400
1842
  function compileContract(ir, specSource, opts = {}) {
1401
1843
  const specFileName = opts.specFileName ?? "openapi.yaml";
1402
1844
  const baseUrl = opts.baseUrl ?? ir.servers[0]?.url ?? "http://localhost:4010";
1403
1845
  const examples = opts.examples ?? 25;
1404
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
+ }
1405
1858
  const files = {
1406
- [specFileName]: specSource.endsWith("\n") ? specSource : `${specSource}
1407
- `,
1859
+ [specFileName]: specOut,
1408
1860
  "pyproject.toml": emitPyProject(ir),
1409
- "conftest.py": emitConftest(ir, specFileName, baseUrl, envVars),
1410
- "test_contract.py": emitContractTests(ir, examples),
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),
1411
1865
  "README.md": emitReadme(ir, specFileName),
1412
1866
  ".env.example": emitEnvExample(baseUrl, envVars)
1413
1867
  };
1414
- return { files, envVars };
1868
+ return { files, envVars, linksAdded };
1415
1869
  }
1416
1870
  function collectEnvVars(profiles) {
1417
1871
  const out = /* @__PURE__ */ new Set();
@@ -1421,7 +1875,7 @@ function collectEnvVars(profiles) {
1421
1875
  out.add(p.tokenEnv ?? "API_TOKEN");
1422
1876
  break;
1423
1877
  case "apiKey":
1424
- out.add(p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_"));
1878
+ out.add(apiKeyEnv(p));
1425
1879
  break;
1426
1880
  case "basic":
1427
1881
  out.add(p.userEnv ?? "API_USER");
@@ -1443,7 +1897,7 @@ version = "0.0.0"
1443
1897
  description = "Schemathesis contract suite for ${ir.meta.title} \u2014 generated by loadam"
1444
1898
  requires-python = ">=3.10"
1445
1899
  dependencies = [
1446
- "schemathesis>=3.36",
1900
+ "schemathesis>=4,<5",
1447
1901
  "pytest>=8.0",
1448
1902
  "pyyaml>=6.0",
1449
1903
  "python-dotenv>=1.0",
@@ -1454,115 +1908,243 @@ addopts = "-q"
1454
1908
  testpaths = ["."]
1455
1909
  `;
1456
1910
  }
1457
- function emitConftest(ir, specFileName, baseUrl, envVars) {
1458
- const authBuilder = emitAuthBuilder(ir.auth);
1911
+ function emitConftest(specFileName, envVars) {
1459
1912
  return `# AUTO-GENERATED by @loadam/test-contract
1460
1913
  """
1461
- Shared fixtures for the Schemathesis contract suite.
1914
+ Shared setup for the Schemathesis contract suite.
1462
1915
 
1463
1916
  The schema is loaded from a checked-in copy of the spec so the suite is
1464
- 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.
1465
1919
  """
1466
1920
 
1467
1921
  import os
1468
1922
  from pathlib import Path
1469
1923
 
1470
1924
  import schemathesis
1471
- from dotenv import load_dotenv
1925
+ from schemathesis.config import SchemathesisConfig
1472
1926
 
1473
- load_dotenv()
1927
+ import loadam_hooks # noqa: F401 \u2014 registers the auth provider
1928
+ from loadam_hooks import BASE_URL
1474
1929
 
1475
- SPEC_PATH = Path(__file__).parent / "${specFileName}"
1476
- BASE_URL = os.getenv("BASE_URL", ${JSON.stringify(baseUrl)})
1930
+ HERE = Path(__file__).parent
1931
+ SPEC_PATH = HERE / "${specFileName}"
1932
+ CONFIG_PATH = HERE / "schemathesis.toml"
1933
+ HOOKS_PATH = HERE / "loadam_hooks.py"
1477
1934
 
1478
- # Required env vars \u2014 listed for ergonomic discovery; not hard-required
1479
- # (Schemathesis can still run unauth flows).
1935
+ # Credentials the spec's security schemes need. Missing ones are reported,
1936
+ # not required: unauthenticated runs still exercise public endpoints.
1480
1937
  REQUIRED_ENV = ${JSON.stringify(envVars)}
1481
1938
 
1482
- schema = schemathesis.from_path(str(SPEC_PATH), base_url=BASE_URL)
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)
1483
1943
 
1484
1944
 
1485
- def auth_kwargs() -> dict:
1486
- ${authBuilder}
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
1487
1951
  `;
1488
1952
  }
1489
- function emitAuthBuilder(profiles) {
1490
- if (profiles.length === 0) {
1491
- return " return {}\n";
1492
- }
1493
- const lines = [" headers: dict = {}", " params: dict = {}"];
1494
- for (const p of profiles) {
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) {
1495
2001
  switch (p.kind) {
1496
2002
  case "bearer": {
1497
- const env = p.tokenEnv ?? "API_TOKEN";
1498
- lines.push(` if os.getenv(${JSON.stringify(env)}):`);
1499
- lines.push(
1500
- ` headers["Authorization"] = f"Bearer {os.environ[${JSON.stringify(env)}]}"`
1501
- );
2003
+ const e = p.tokenEnv ?? "API_TOKEN";
2004
+ lines.push(` if ${env(e)}:`);
2005
+ lines.push(` out["headers"]["Authorization"] = "Bearer " + ${env(e)}`);
1502
2006
  break;
1503
2007
  }
1504
2008
  case "apiKey": {
1505
- const env = p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
1506
- if (p.in === "header") {
1507
- lines.push(` if os.getenv(${JSON.stringify(env)}):`);
1508
- lines.push(
1509
- ` headers[${JSON.stringify(p.name)}] = os.environ[${JSON.stringify(env)}]`
1510
- );
1511
- } else if (p.in === "query") {
1512
- lines.push(` if os.getenv(${JSON.stringify(env)}):`);
1513
- lines.push(
1514
- ` params[${JSON.stringify(p.name)}] = os.environ[${JSON.stringify(env)}]`
1515
- );
1516
- }
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)}`);
1517
2013
  break;
1518
2014
  }
1519
2015
  case "basic": {
1520
2016
  const u = p.userEnv ?? "API_USER";
1521
2017
  const pw = p.passEnv ?? "API_PASS";
1522
- lines.push(` if os.getenv(${JSON.stringify(u)}) and os.getenv(${JSON.stringify(pw)}):`);
2018
+ lines.push(` if ${env(u)} and ${env(pw)}:`);
2019
+ lines.push(
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)}:`);
1523
2027
  lines.push(
1524
- ` import base64; headers["Authorization"] = "Basic " + base64.b64encode(f"{os.environ[${JSON.stringify(u)}]}:{os.environ[${JSON.stringify(pw)}]}".encode()).decode()`
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`
1525
2031
  );
1526
2032
  break;
1527
2033
  }
1528
2034
  }
1529
2035
  }
1530
- lines.push(` return {"headers": headers, "params": params}`);
1531
- return `${lines.join("\n")}
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)
1532
2080
  `;
1533
2081
  }
1534
- function emitContractTests(_ir, examples) {
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
+ ` : "";
1535
2112
  return `# AUTO-GENERATED by @loadam/test-contract
1536
2113
  """
1537
2114
  Property-based contract tests for every declared operation.
1538
2115
 
1539
- Each operation is fuzzed ~${examples} times. Schemathesis asserts:
1540
- - response status is one of the declared statuses
1541
- - response body validates against the declared response schema
1542
- - server returns no 500s on valid inputs
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
1543
2121
 
1544
- Mutating endpoints (POST/PUT/PATCH/DELETE) are included by default \u2014 point
1545
- the suite at a disposable / sandbox environment, not production.
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.
1546
2125
  """
2126
+ ${stateful ? "\nimport os\nimport subprocess\nimport sys\n\nimport pytest\n" : ""}
2127
+ from hypothesis import HealthCheck, settings
1547
2128
 
1548
- from hypothesis import settings
1549
-
1550
- from conftest import auth_kwargs, schema
1551
-
1552
- import schemathesis
2129
+ from conftest import ${stateful ? "BASE_URL, CONFIG_PATH, HOOKS_PATH, SPEC_PATH, " : ""}schema
1553
2130
 
1554
2131
 
1555
2132
  @schema.parametrize()
1556
- @settings(max_examples=${examples}, deadline=None)
1557
- def test_contract(case: "schemathesis.Case") -> None:
1558
- response = case.call(**auth_kwargs())
1559
- case.validate_response(response)
1560
- `;
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}`;
1561
2143
  }
1562
2144
  function emitReadme(ir, specFileName) {
1563
2145
  return `# ${ir.meta.title} \u2014 contract test suite
1564
2146
 
1565
- Generated by [loadam](https://github.com/loadam) from your API spec.
2147
+ Generated by [loadam](https://github.com/DesmondSanctity/loadam) from your API spec.
1566
2148
 
1567
2149
  ## Run
1568
2150
 
@@ -1578,11 +2160,20 @@ cp .env.example .env
1578
2160
  pytest
1579
2161
  \`\`\`
1580
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
+
1581
2169
  ## What's in here
1582
2170
 
1583
2171
  - \`${specFileName}\` \u2014 checked-in copy of the spec under test.
1584
- - \`conftest.py\` \u2014 schema loader + auth builder.
1585
- - \`test_contract.py\` \u2014 Schemathesis property-based suite.
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.
1586
2177
 
1587
2178
  ## Why contract tests?
1588
2179
 
@@ -1602,10 +2193,124 @@ function emitEnvExample(baseUrl, envVars) {
1602
2193
  return `${lines.join("\n")}
1603
2194
  `;
1604
2195
  }
2196
+ function apiKeyEnv(p) {
2197
+ return p.valueEnv ?? p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
2198
+ }
1605
2199
  function slugify(s) {
1606
2200
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1607
2201
  }
1608
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(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(Number.parseInt(n, 16))).replace(/&amp;/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
+
1609
2314
  // src/util/target.ts
1610
2315
  function resolveTarget(flag) {
1611
2316
  if (typeof flag === "string" && flag.length > 0) return flag;
@@ -1620,27 +2325,28 @@ function registerContractCommand(program) {
1620
2325
  "-o, --output <dir>",
1621
2326
  "output directory for the generated suite",
1622
2327
  "./loadam-out/contract"
1623
- ).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));
1624
2329
  }
1625
2330
  async function runContract(spec, opts) {
1626
2331
  const out = makeOutput(!!opts.json);
1627
- const specPath = resolve4(spec);
2332
+ const specPath = resolve5(spec);
1628
2333
  out.start(`Parsing OpenAPI spec: ${specPath}`);
1629
2334
  const ir = await fromOpenApiFile(specPath);
1630
2335
  inferResourceGraph(ir);
2336
+ await applyUserConfig(ir, specPath, opts.config);
1631
2337
  parseIR(ir);
1632
- const specSource = await readFile4(specPath, "utf8");
2338
+ const specSource = await readFile6(specPath, "utf8");
1633
2339
  const examples = Number.parseInt(opts.examples ?? "25", 10);
1634
2340
  const target = resolveTarget(opts.target);
1635
2341
  const result = compileContract(ir, specSource, {
1636
2342
  baseUrl: target,
1637
2343
  examples: Number.isFinite(examples) ? examples : 25
1638
2344
  });
1639
- const outDir = resolve4(opts.output);
2345
+ const outDir = resolve5(opts.output);
1640
2346
  await mkdir2(outDir, { recursive: true });
1641
2347
  for (const [rel, contents] of Object.entries(result.files)) {
1642
- const full = resolve4(outDir, rel);
1643
- await mkdir2(dirname(full), { recursive: true });
2348
+ const full = resolve5(outDir, rel);
2349
+ await mkdir2(dirname2(full), { recursive: true });
1644
2350
  await writeFile2(full, contents, "utf8");
1645
2351
  }
1646
2352
  const fileCount = Object.keys(result.files).length;
@@ -1648,7 +2354,7 @@ async function runContract(spec, opts) {
1648
2354
  out.info(` ${ir.operations.length} operations to fuzz`);
1649
2355
  const session = await createSession({
1650
2356
  command: "contract",
1651
- outRoot: resolve4(outDir, ".."),
2357
+ outRoot: resolve5(outDir, ".."),
1652
2358
  specPath,
1653
2359
  specSource,
1654
2360
  ir,
@@ -1657,26 +2363,79 @@ async function runContract(spec, opts) {
1657
2363
  envVars: result.envVars ?? [],
1658
2364
  flags: {
1659
2365
  target: target ?? null,
1660
- examples
2366
+ examples,
2367
+ run: !!opts.run
1661
2368
  },
1662
2369
  slug: `contract-${ir.meta.title ?? "run"}`
1663
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
+ }
1664
2417
  await session.finalize({
1665
- exitCode: 0,
2418
+ exitCode,
1666
2419
  thresholds: { passed: [], failed: [] },
1667
- summary: {
1668
- files: fileCount,
1669
- operations: ir.operations.length
1670
- }
2420
+ summary
1671
2421
  });
1672
2422
  if (!out.json) {
1673
2423
  out.info(` Session: ${session.id}`);
1674
- out.step("");
1675
- out.step("Next steps:");
1676
- out.step(` cd ${opts.output}`);
1677
- out.step(" python -m venv .venv && source .venv/bin/activate");
1678
- out.step(" pip install -e .");
1679
- out.step(" pytest");
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
+ }
1680
2439
  }
1681
2440
  out.result({
1682
2441
  command: "contract",
@@ -1684,13 +2443,15 @@ async function runContract(spec, opts) {
1684
2443
  files: fileCount,
1685
2444
  operations: ir.operations.length,
1686
2445
  envVars: result.envVars,
1687
- sessionId: session.id
2446
+ sessionId: session.id,
2447
+ ...ran ? { results: ran } : {}
1688
2448
  });
2449
+ if (exitCode !== 0) process.exitCode = 1;
1689
2450
  }
1690
2451
 
1691
2452
  // src/commands/diff.ts
1692
- import { readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
1693
- import { resolve as resolve5 } from "path";
2453
+ import { readFile as readFile7, writeFile as writeFile3 } from "fs/promises";
2454
+ import { resolve as resolve6 } from "path";
1694
2455
 
1695
2456
  // ../test-drift/dist/index.js
1696
2457
  import Ajv from "ajv";
@@ -1728,7 +2489,7 @@ function compareProbes(input) {
1728
2489
  continue;
1729
2490
  }
1730
2491
  const ct = probe.contentType ?? Object.keys(declared.contentTypes)[0];
1731
- const media = ct ? declared.contentTypes[ct] : void 0;
2492
+ const media = ct ? matchMediaType(declared.contentTypes, ct) : void 0;
1732
2493
  if (!media) {
1733
2494
  findings.push({
1734
2495
  operationId: op.id,
@@ -1755,6 +2516,13 @@ function compareProbes(input) {
1755
2516
  }
1756
2517
  return findings;
1757
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
+ }
1758
2526
  function pickResponseFor(op, status) {
1759
2527
  const exact = op.responses.find((r) => r.status === status);
1760
2528
  if (exact) return exact;
@@ -1813,58 +2581,189 @@ async function probeOperations(ir, opts) {
1813
2581
  const skipped = [];
1814
2582
  const safeOnly = opts.safeOnly ?? true;
1815
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 = [];
1816
2588
  for (const op of ir.operations) {
1817
2589
  if (safeOnly && !isSafeMethod(op.method)) {
1818
- skipped.push({
1819
- operationId: op.id,
1820
- reason: `mutating ${op.method} skipped (safe-only)`
1821
- });
1822
- continue;
2590
+ skipped.push({ operationId: op.id, reason: `mutating ${op.method} skipped (safe-only)` });
2591
+ } else {
2592
+ pending.push(op);
1823
2593
  }
1824
- const url = buildUrl(opts.baseUrl, op, opts.pathParams ?? {});
1825
- if (!url) {
1826
- skipped.push({ operationId: op.id, reason: "missing required path param" });
1827
- continue;
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);
1828
2603
  }
1829
- try {
1830
- const ac = new AbortController();
1831
- const timer = setTimeout(() => ac.abort(), timeout);
1832
- const resp = await fetch(url, {
1833
- method: op.method,
1834
- headers: opts.headers ?? {},
1835
- signal: ac.signal
1836
- });
1837
- clearTimeout(timer);
1838
- const ct = resp.headers.get("content-type") ?? void 0;
1839
- const body = await readBody(resp, ct);
1840
- probes.push({
1841
- operationId: op.id,
1842
- status: resp.status,
1843
- contentType: ct ? ct.split(";")[0].trim() : void 0,
1844
- body
1845
- });
1846
- } catch (err) {
1847
- skipped.push({
1848
- operationId: op.id,
1849
- reason: err instanceof Error ? err.message : String(err)
1850
- });
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
+ }
1851
2647
  }
2648
+ pending = waiting;
1852
2649
  }
1853
2650
  return { probes, skipped };
1854
2651
  }
1855
2652
  function isSafeMethod(method) {
1856
2653
  return method === "GET" || method === "HEAD" || method === "OPTIONS";
1857
2654
  }
1858
- function buildUrl(base, op, pathParams) {
1859
- let path = op.path;
2655
+ function requiredPathParams(op) {
2656
+ return op.pathParams.filter((p) => p.required);
2657
+ }
2658
+ function resolvePathParams(op, overrides, ids) {
2659
+ const values = {};
1860
2660
  for (const p of op.pathParams) {
1861
- const v = pathParams[p.name];
1862
- if (v === void 0 && p.required) return void 0;
1863
- if (v !== void 0) {
1864
- path = path.split(`{${p.name}}`).join(encodeURIComponent(String(v)));
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;
1865
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);
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";
1866
2766
  }
1867
- return base.replace(/\/$/, "") + path;
1868
2767
  }
1869
2768
  async function readBody(resp, ct) {
1870
2769
  const text = await resp.text();
@@ -1923,25 +2822,105 @@ function renderMarkdownReport(opts) {
1923
2822
  for (const s of opts.skipped) {
1924
2823
  sections.push(`- \`${s.operationId}\` \u2014 ${s.reason}`);
1925
2824
  }
1926
- sections.push("");
2825
+ sections.push("");
2826
+ }
2827
+ return `${sections.join("\n").trimEnd()}
2828
+ `;
2829
+ }
2830
+ function countBySeverity(findings) {
2831
+ const c = { error: 0, warning: 0, info: 0 };
2832
+ for (const f of findings) c[f.severity]++;
2833
+ return c;
2834
+ }
2835
+ function severityBadge(s) {
2836
+ if (s === "error") return "\u274C error";
2837
+ if (s === "warning") return "\u26A0\uFE0F warning";
2838
+ return "\u2139\uFE0F info";
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
+ }
1927
2914
  }
1928
- return `${sections.join("\n").trimEnd()}
1929
- `;
1930
- }
1931
- function countBySeverity(findings) {
1932
- const c = { error: 0, warning: 0, info: 0 };
1933
- for (const f of findings) c[f.severity]++;
1934
- return c;
1935
- }
1936
- function severityBadge(s) {
1937
- if (s === "error") return "\u274C error";
1938
- if (s === "warning") return "\u26A0\uFE0F warning";
1939
- return "\u2139\uFE0F info";
2915
+ return out;
1940
2916
  }
1941
2917
 
1942
2918
  // src/commands/diff.ts
1943
2919
  function registerDiffCommand(program) {
1944
- 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("--path-param <kv...>", 'fallback path-param values, repeatable, "name=value" form').option("--fail-on <severity>", "exit non-zero when findings of this severity exist", "error").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runDiff));
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));
1945
2924
  }
1946
2925
  async function runDiff(spec, opts) {
1947
2926
  const out = makeOutput(!!opts.json);
@@ -1949,19 +2928,28 @@ async function runDiff(spec, opts) {
1949
2928
  if (!target) {
1950
2929
  throw new Error("--target is required (or set LOADAM_TARGET env var)");
1951
2930
  }
1952
- const specPath = resolve5(spec);
2931
+ const specPath = resolve6(spec);
1953
2932
  out.start(`Parsing OpenAPI spec: ${specPath}`);
1954
- const specSource = await readFile5(specPath, "utf8");
2933
+ const specSource = await readFile7(specPath, "utf8");
1955
2934
  const ir = await fromOpenApiFile(specPath);
1956
2935
  inferResourceGraph(ir);
2936
+ await applyUserConfig(ir, specPath, opts.config);
1957
2937
  parseIR(ir);
1958
2938
  const headers = parseKvPairs(opts.header ?? [], ":");
1959
2939
  const pathParams = parseKvPairs(opts.pathParam ?? [], "=");
1960
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
+ }
1961
2948
  out.start(`Probing ${ir.operations.length} operations on ${target}\u2026`);
1962
2949
  const { probes, skipped } = await probeOperations(ir, {
1963
2950
  baseUrl: target,
1964
- headers,
2951
+ headers: { ...auth.headers, ...headers },
2952
+ query: auth.query,
1965
2953
  pathParams,
1966
2954
  timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : 5e3,
1967
2955
  safeOnly: !opts.mutating
@@ -1970,7 +2958,7 @@ async function runDiff(spec, opts) {
1970
2958
  const counts = countBySeverity(findings);
1971
2959
  const session = await createSession({
1972
2960
  command: "diff",
1973
- outRoot: resolve5("./loadam-out"),
2961
+ outRoot: resolve6("./loadam-out"),
1974
2962
  specPath,
1975
2963
  specSource,
1976
2964
  ir,
@@ -2000,7 +2988,7 @@ async function runDiff(spec, opts) {
2000
2988
  );
2001
2989
  if (!out.json) {
2002
2990
  if (opts.output) {
2003
- const outFile = resolve5(opts.output);
2991
+ const outFile = resolve6(opts.output);
2004
2992
  await writeFile3(outFile, report, "utf8");
2005
2993
  out.success(`Wrote drift report to ${outFile}`);
2006
2994
  } else {
@@ -2011,7 +2999,7 @@ async function runDiff(spec, opts) {
2011
2999
  );
2012
3000
  out.info(` Session: ${session.id}`);
2013
3001
  } else if (opts.output) {
2014
- await writeFile3(resolve5(opts.output), report, "utf8");
3002
+ await writeFile3(resolve6(opts.output), report, "utf8");
2015
3003
  }
2016
3004
  const failOn = opts.failOn ?? "error";
2017
3005
  const failed = failOn === "error" && counts.error > 0 || failOn === "warning" && counts.error + counts.warning > 0;
@@ -2034,7 +3022,7 @@ async function runDiff(spec, opts) {
2034
3022
  skipped: skipped.length,
2035
3023
  findings: findings.length,
2036
3024
  counts,
2037
- reportPath: opts.output ? resolve5(opts.output) : null,
3025
+ reportPath: opts.output ? resolve6(opts.output) : null,
2038
3026
  failOn,
2039
3027
  failed,
2040
3028
  sessionId: session.id
@@ -2054,13 +3042,13 @@ function parseKvPairs(values, sep) {
2054
3042
  }
2055
3043
 
2056
3044
  // src/commands/history.ts
2057
- import { resolve as resolve6 } from "path";
3045
+ import { resolve as resolve7 } from "path";
2058
3046
  function registerHistoryCommand(program) {
2059
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));
2060
3048
  }
2061
3049
  async function runHistory(opts) {
2062
3050
  const out = makeOutput(!!opts.json);
2063
- const root = resolve6(opts.root);
3051
+ const root = resolve7(opts.root);
2064
3052
  const limit = Number.parseInt(opts.limit ?? "20", 10);
2065
3053
  const all = await listSessions(root);
2066
3054
  const filtered = opts.command ? all.filter((s) => s.command === opts.command) : all;
@@ -2088,18 +3076,19 @@ async function runHistory(opts) {
2088
3076
 
2089
3077
  // src/commands/init.ts
2090
3078
  import { writeFile as writeFile4 } from "fs/promises";
2091
- import { resolve as resolve7 } from "path";
3079
+ import { resolve as resolve8 } from "path";
2092
3080
  function registerInitCommand(program) {
2093
- 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));
2094
3082
  }
2095
3083
  async function runInit(spec, opts) {
2096
3084
  const out = makeOutput(!!opts.json);
2097
- const specPath = resolve7(spec);
3085
+ const specPath = resolve8(spec);
2098
3086
  out.start(`Parsing OpenAPI spec: ${specPath}`);
2099
3087
  const ir = await fromOpenApiFile(specPath);
2100
3088
  inferResourceGraph(ir);
3089
+ await applyUserConfig(ir, specPath, opts.config);
2101
3090
  parseIR(ir);
2102
- const outPath = resolve7(opts.output);
3091
+ const outPath = resolve8(opts.output);
2103
3092
  await writeFile4(outPath, `${JSON.stringify(ir, null, 2)}
2104
3093
  `, "utf8");
2105
3094
  const stats = graphStats(ir.resources);
@@ -2125,7 +3114,7 @@ async function runInit(spec, opts) {
2125
3114
 
2126
3115
  // src/commands/mcp.ts
2127
3116
  import { mkdir as mkdir3, writeFile as writeFile5 } from "fs/promises";
2128
- import { dirname as dirname2, resolve as resolve8 } from "path";
3117
+ import { dirname as dirname3, resolve as resolve9 } from "path";
2129
3118
 
2130
3119
  // ../mcp/dist/index.js
2131
3120
  function emitAuth(ir) {
@@ -2196,23 +3185,23 @@ function buildTool(ir, op) {
2196
3185
  const properties = {};
2197
3186
  const required = [];
2198
3187
  for (const p of op.pathParams) {
2199
- properties[p.name] = annotate(resolveSchema(ir, p.schema), p);
3188
+ properties[p.name] = annotate(resolveSchema2(ir, p.schema), p);
2200
3189
  required.push(p.name);
2201
3190
  }
2202
3191
  for (const p of op.queryParams) {
2203
- properties[p.name] = annotate(resolveSchema(ir, p.schema), p);
3192
+ properties[p.name] = annotate(resolveSchema2(ir, p.schema), p);
2204
3193
  if (p.required) required.push(p.name);
2205
3194
  }
2206
3195
  for (const p of op.headerParams) {
2207
3196
  if (isAuthHeader(p.name)) continue;
2208
- properties[p.name] = annotate(resolveSchema(ir, p.schema), p);
3197
+ properties[p.name] = annotate(resolveSchema2(ir, p.schema), p);
2209
3198
  if (p.required) required.push(p.name);
2210
3199
  }
2211
3200
  let hasBody = false;
2212
3201
  if (op.body) {
2213
3202
  const json = op.body.contentTypes["application/json"];
2214
3203
  if (json) {
2215
- properties.body = resolveSchema(ir, json.schema);
3204
+ properties.body = resolveSchema2(ir, json.schema);
2216
3205
  if (op.body.required) required.push("body");
2217
3206
  hasBody = true;
2218
3207
  }
@@ -2238,7 +3227,7 @@ function buildTool(ir, op) {
2238
3227
  }
2239
3228
  };
2240
3229
  }
2241
- function resolveSchema(ir, ref) {
3230
+ function resolveSchema2(ir, ref) {
2242
3231
  if (typeof ref === "string") {
2243
3232
  const found = ir.schemas[ref];
2244
3233
  if (found) return cloneJson(found.jsonSchema);
@@ -2297,6 +3286,7 @@ function emitPackageJson(ctx) {
2297
3286
  function emitBinJs(_ctx) {
2298
3287
  return `#!/usr/bin/env node
2299
3288
  // AUTO-GENERATED by @loadam/mcp
3289
+ import './env.js'; // must stay first: server.js reads process.env at import time
2300
3290
  import { buildServer } from './server.js';
2301
3291
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
2302
3292
 
@@ -2531,6 +3521,31 @@ export async function invokeTool(tool, args) {
2531
3521
  }
2532
3522
  `;
2533
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
+ }
2534
3549
  function emitEnvExample2(ctx) {
2535
3550
  const lines = [
2536
3551
  "# Generated by loadam \u2014 copy to .env or export in your shell.",
@@ -2551,7 +3566,7 @@ ${ctx.auth.notes.map((n) => `- ${n}`).join("\n")}
2551
3566
  ` : "";
2552
3567
  return `# ${ctx.ir.meta.title} \u2014 MCP server
2553
3568
 
2554
- Generated by [loadam](https://github.com/loadam) from your API spec.
3569
+ Generated by [loadam](https://github.com/DesmondSanctity/loadam) from your API spec.
2555
3570
 
2556
3571
  ${writesNote}
2557
3572
 
@@ -2614,6 +3629,7 @@ function compileMcp(ir, opts = {}) {
2614
3629
  const files = {
2615
3630
  "package.json": emitPackageJson(ctx),
2616
3631
  "bin.js": emitBinJs(ctx),
3632
+ "env.js": emitEnvJs(ctx),
2617
3633
  "server.js": emitServerJs(ctx),
2618
3634
  "tools.js": emitToolsJs(ctx),
2619
3635
  "client.js": emitClientJs(ctx),
@@ -2629,14 +3645,15 @@ function registerMcpCommand(program) {
2629
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(
2630
3646
  "--target <url>",
2631
3647
  "override base URL baked into client.js (env BASE_URL still wins at runtime)"
2632
- ).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));
2633
3649
  }
2634
3650
  async function runMcp(spec, opts) {
2635
3651
  const out = makeOutput(!!opts.json);
2636
- const specPath = resolve8(spec);
3652
+ const specPath = resolve9(spec);
2637
3653
  out.start(`Parsing OpenAPI spec: ${specPath}`);
2638
3654
  const ir = await fromOpenApiFile(specPath);
2639
3655
  inferResourceGraph(ir);
3656
+ await applyUserConfig(ir, specPath, opts.config);
2640
3657
  parseIR(ir);
2641
3658
  const target = resolveTarget(opts.target);
2642
3659
  const result = compileMcp(ir, {
@@ -2644,11 +3661,11 @@ async function runMcp(spec, opts) {
2644
3661
  includeWrites: !!opts.writes,
2645
3662
  exclude: opts.exclude
2646
3663
  });
2647
- const outDir = resolve8(opts.output);
3664
+ const outDir = resolve9(opts.output);
2648
3665
  await mkdir3(outDir, { recursive: true });
2649
3666
  for (const [rel, contents] of Object.entries(result.files)) {
2650
- const full = resolve8(outDir, rel);
2651
- await mkdir3(dirname2(full), { recursive: true });
3667
+ const full = resolve9(outDir, rel);
3668
+ await mkdir3(dirname3(full), { recursive: true });
2652
3669
  await writeFile5(full, contents, "utf8");
2653
3670
  }
2654
3671
  const fileCount = Object.keys(result.files).length;
@@ -2676,62 +3693,141 @@ async function runMcp(spec, opts) {
2676
3693
  }
2677
3694
 
2678
3695
  // src/commands/report.ts
2679
- import { spawn } from "child_process";
2680
- import { readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
2681
- import { join as join2, resolve as resolve9 } from "path";
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";
2682
3699
 
2683
3700
  // ../report/dist/index.js
2684
3701
  function renderReport(input) {
2685
3702
  const { meta, loadamVersion } = input;
2686
- const passed = meta.exitCode === 0 && (meta.thresholds?.failed.length ?? 0) === 0;
3703
+ const overall = computeOverall(meta, input.k6Summaries, input.operations);
2687
3704
  const dataPayload = {
2688
3705
  meta,
2689
3706
  k6Summaries: input.k6Summaries ?? null,
2690
3707
  contractFailures: input.contractFailures ?? null,
3708
+ operations: input.operations ?? null,
2691
3709
  loadamVersion
2692
3710
  };
3711
+ const hasEndpoints = (input.operations?.length ?? 0) > 0;
3712
+ const sideSections = [
3713
+ renderThresholds(meta),
3714
+ renderK6Section(input.k6Summaries, hasEndpoints),
3715
+ input.driftMarkdown ? renderDrift(input.driftMarkdown) : "",
3716
+ input.contractFailures && input.contractFailures.length > 0 ? renderContract(input.contractFailures) : "",
3717
+ renderRunDetails(meta)
3718
+ ].filter((s) => s !== "").join("\n");
3719
+ const mainBlock = renderEndpoints(input.operations, input.k6Summaries);
2693
3720
  return [
2694
3721
  "<!doctype html>",
2695
3722
  `<html lang="en">`,
2696
3723
  "<head>",
2697
3724
  `<meta charset="utf-8" />`,
2698
3725
  `<meta name="viewport" content="width=device-width,initial-scale=1" />`,
2699
- `<meta name="generator" content="loadam ${esc(loadamVersion)}" />`,
2700
- `<title>${esc(reportTitle(meta))}</title>`,
2701
- `<style>${STYLES}</style>`,
3726
+ `<meta name="generator" content="loadam ${esc2(loadamVersion)}" />`,
3727
+ `<title>${esc2(reportTitle(meta))}</title>`,
3728
+ `<style>${STYLES}${dynamicTabStyles(input.k6Summaries)}${dynamicEndpointStyles(input.operations)}</style>`,
2702
3729
  "</head>",
2703
3730
  "<body>",
2704
- renderHeader(meta, passed),
3731
+ renderHeader(meta, overall, input.k6Summaries),
3732
+ renderFailureReason(meta, overall, input.k6Summaries, input.contractFailures),
2705
3733
  renderSummary(meta, input.k6Summaries),
2706
- renderThresholds(meta),
2707
- renderK6Metrics(input.k6Summaries),
2708
- input.driftMarkdown ? renderDrift(input.driftMarkdown) : "",
2709
- input.contractFailures && input.contractFailures.length > 0 ? renderContract(input.contractFailures) : "",
2710
- renderRunDetails(meta),
3734
+ // Two-column layout: endpoints fill the main column on the left, while
3735
+ // run-level data (thresholds, k6 results, drift, contract findings, run
3736
+ // details) lives in a sticky sidebar on the right so a reader never has
3737
+ // to scroll past a long endpoint list to see the overall numbers.
3738
+ mainBlock ? `<div class="page-grid"><div class="page-main">${mainBlock}</div><aside class="page-side">${sideSections}</aside></div>` : sideSections,
2711
3739
  renderFooter(meta, loadamVersion),
2712
3740
  `<script type="application/json" id="loadam-data">${escScript(JSON.stringify(dataPayload))}</script>`,
3741
+ DOWNLOAD_SCRIPT,
2713
3742
  "</body>",
2714
3743
  "</html>",
2715
3744
  ""
2716
3745
  ].join("\n");
2717
3746
  }
2718
- function renderHeader(meta, passed) {
2719
- const status = passed ? "PASSED" : "FAILED";
2720
- const cls = passed ? "ok" : "bad";
3747
+ function renderHeader(meta, overall, k6) {
3748
+ const modeLabel = describeModes(meta, k6);
3749
+ const chipText = overall.detail ? `${overall.detail} \xB7 ${overall.label}` : overall.label;
2721
3750
  return `
3751
+ <div class="brand-row">
3752
+ <a class="brand" href="https://github.com/DesmondSanctity/loadam" target="_blank" rel="noopener" title="loadam on GitHub">
3753
+ <svg class="brand-mark" viewBox="0 0 24 24" fill="none" aria-hidden="true">
3754
+ <defs><linearGradient id="loadam-g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f59e0b"/><stop offset="1" stop-color="#ef4444"/></linearGradient></defs>
3755
+ <path d="M3 18 A 9 9 0 0 1 21 18" stroke="url(#loadam-g)" stroke-width="2.5" stroke-linecap="round"/>
3756
+ <path d="M12 18 L17 10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>
3757
+ <circle cx="12" cy="18" r="1.6" fill="currentColor"/>
3758
+ </svg>
3759
+ <span class="brand-name">load<span class="brand-name-am">am</span></span>
3760
+ </a>
3761
+ <span class="brand-tag">load tests &amp; contract checks from OpenAPI</span>
3762
+ </div>
2722
3763
  <header class="hdr">
2723
3764
  <div class="hdr-left">
2724
- <div class="cmd">${esc(meta.command)}</div>
2725
- <h1>${esc(meta.spec.title ?? "Untitled API")}</h1>
2726
- <div class="sub">${esc(meta.spec.version ?? "")} \xB7 target <code>${esc(meta.target ?? "\u2014")}</code></div>
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>
2727
3768
  </div>
2728
3769
  <div class="hdr-right">
2729
- <span class="badge ${cls}">${status}</span>
2730
- <div class="when">${esc(meta.startedAt)}</div>
3770
+ <div class="when">${esc2(meta.startedAt)}</div>
2731
3771
  ${typeof meta.durationMs === "number" ? `<div class="dur">${(meta.durationMs / 1e3).toFixed(2)}s</div>` : ""}
3772
+ <div class="actions">
3773
+ <button type="button" class="act" data-loadam-download="html" title="Download this HTML report">\u2B07 Report</button>
3774
+ <button type="button" class="act" data-loadam-download="json" title="Download raw run data as JSON">\u2B07 Data</button>
3775
+ <button type="button" class="act" data-loadam-print title="Print or save as PDF">\u2399 Print</button>
3776
+ </div>
2732
3777
  </div>
2733
3778
  </header>`;
2734
3779
  }
3780
+ function describeModes(meta, k6) {
3781
+ if (meta.command !== "test") return void 0;
3782
+ const labels = k6 ? Object.keys(k6) : [];
3783
+ if (labels.length > 0) return labels.join(" + ");
3784
+ const flagMode = meta.flags.mode;
3785
+ if (typeof flagMode === "string" && flagMode !== "skip") return flagMode;
3786
+ return "generated only";
3787
+ }
3788
+ function renderFailureReason(meta, overall, k6, contractFailures) {
3789
+ if (overall.cls === "ok" || overall.cls === "muted") return "";
3790
+ const reasons = [];
3791
+ const failedThresh = (meta.thresholds?.failed ?? []).filter((n) => !isSentinelThreshold(n));
3792
+ if (failedThresh.length > 0) {
3793
+ const PREVIEW = 3;
3794
+ const head = failedThresh.slice(0, PREVIEW).map((t) => `<code>${esc2(t)}</code>`).join(", ");
3795
+ const rest = failedThresh.slice(PREVIEW);
3796
+ const more = rest.length > 0 ? ` <details class="more"><summary>+${rest.length} more</summary>${rest.map((t) => `<code>${esc2(t)}</code>`).join(", ")}</details>` : "";
3797
+ reasons.push(
3798
+ `<strong>${failedThresh.length}</strong> threshold${failedThresh.length === 1 ? "" : "s"} failed: ${head}${more}`
3799
+ );
3800
+ }
3801
+ if (k6) {
3802
+ for (const [name, s] of Object.entries(k6)) {
3803
+ const checks = s.root_group?.checks;
3804
+ if (!checks) continue;
3805
+ const entries = Object.values(checks);
3806
+ const failed = entries.filter((c) => c.fails > 0);
3807
+ const totalChecks = entries.length;
3808
+ if (failed.length > 0) {
3809
+ reasons.push(
3810
+ `<strong>${name}</strong>: ${failed.length}/${totalChecks} operation check${failed.length === 1 ? "" : "s"} failed`
3811
+ );
3812
+ }
3813
+ }
3814
+ }
3815
+ if (contractFailures && contractFailures.length > 0) {
3816
+ reasons.push(
3817
+ `<strong>${contractFailures.length}</strong> contract test${contractFailures.length === 1 ? "" : "s"} failed`
3818
+ );
3819
+ }
3820
+ if (reasons.length === 0 && typeof meta.exitCode === "number" && meta.exitCode !== 0) {
3821
+ reasons.push(`Process exited with code <code>${meta.exitCode}</code>`);
3822
+ }
3823
+ if (reasons.length === 0) return "";
3824
+ const heading = overall.cls === "bad" ? "Why this failed" : "Issues to investigate";
3825
+ return `
3826
+ <section class="reason ${overall.cls}">
3827
+ <h2>${heading}</h2>
3828
+ <ul>${reasons.map((r) => `<li>${r}</li>`).join("")}</ul>
3829
+ </section>`;
3830
+ }
2735
3831
  function renderSummary(meta, k6) {
2736
3832
  const cells = [];
2737
3833
  if (meta.summary) {
@@ -2765,51 +3861,463 @@ function renderSummary(meta, k6) {
2765
3861
  return `
2766
3862
  <section class="cards">
2767
3863
  ${cells.map(
2768
- (c) => `<div class="card"><div class="card-v">${esc(c.value)}</div><div class="card-l">${esc(c.label)}</div></div>`
3864
+ (c) => `<div class="card"><div class="card-v">${esc2(c.value)}</div><div class="card-l">${esc2(c.label)}</div></div>`
2769
3865
  ).join("\n ")}
2770
3866
  </section>`;
2771
3867
  }
2772
3868
  function renderThresholds(meta) {
2773
3869
  const t = meta.thresholds;
2774
- if (!t || t.passed.length === 0 && t.failed.length === 0) return "";
3870
+ if (!t) return "";
3871
+ const failed = t.failed.filter((n) => !isSentinelThreshold(n));
3872
+ const passed = t.passed.filter((n) => !isSentinelThreshold(n));
3873
+ if (failed.length === 0 && passed.length === 0) return "";
3874
+ const PREVIEW = 4;
3875
+ const failedHead = failed.slice(0, PREVIEW);
3876
+ const failedRest = failed.slice(PREVIEW);
3877
+ const passedHead = passed.slice(0, PREVIEW);
3878
+ const passedRest = passed.slice(PREVIEW);
3879
+ const summary = [];
3880
+ if (failed.length > 0) summary.push(`<span class="bad">${failed.length} failed</span>`);
3881
+ if (passed.length > 0) summary.push(`<span class="ok">${passed.length} passed</span>`);
2775
3882
  return `
2776
3883
  <section>
2777
- <h2>Thresholds</h2>
3884
+ <h2>Thresholds <span class="muted">(${summary.join(" \xB7 ")})</span></h2>
2778
3885
  <ul class="thr">
2779
- ${t.failed.map((x) => `<li class="bad">\u2717 ${esc(x)}</li>`).join("\n ")}
2780
- ${t.passed.map((x) => `<li class="ok">\u2713 ${esc(x)}</li>`).join("\n ")}
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>` : ""}
2781
3890
  </ul>
2782
3891
  </section>`;
2783
3892
  }
2784
- function renderK6Metrics(k6) {
2785
- if (!k6 || Object.keys(k6).length === 0) return "";
2786
- const blocks = [];
2787
- for (const [name, s] of Object.entries(k6)) {
2788
- const metrics = s.metrics ?? {};
2789
- const dur = metrics.http_req_duration?.values;
2790
- if (!dur) continue;
2791
- const rows = [
2792
- ["min", fmtMs(dur.min)],
2793
- ["med", fmtMs(dur.med)],
2794
- ["avg", fmtMs(dur.avg)],
2795
- ["p(90)", fmtMs(dur["p(90)"])],
2796
- ["p(95)", fmtMs(dur["p(95)"])],
2797
- ["p(99)", fmtMs(dur["p(99)"])],
2798
- ["max", fmtMs(dur.max)]
2799
- ];
2800
- blocks.push(`
2801
- <div class="metric-block">
2802
- <h3>${esc(name)} \xB7 http_req_duration</h3>
3893
+ function renderEndpoints(ops, k6) {
3894
+ if (!ops || ops.length === 0) return "";
3895
+ const runs = k6 ? Object.entries(k6) : [];
3896
+ const checkLookup = /* @__PURE__ */ new Map();
3897
+ for (const op of ops) checkLookup.set(op.id, []);
3898
+ for (const [run, summary] of runs) {
3899
+ const checks = summary.root_group?.checks;
3900
+ if (!checks) continue;
3901
+ for (const c of Object.values(checks)) {
3902
+ const opId = c.name.split(/\s+/)[0];
3903
+ if (opId && checkLookup.has(opId)) {
3904
+ checkLookup.get(opId)?.push({ run, check: c });
3905
+ }
3906
+ }
3907
+ }
3908
+ const opMetrics = collectOpMetrics(ops, k6);
3909
+ const groups = /* @__PURE__ */ new Map();
3910
+ for (const op of ops) {
3911
+ const tag = op.tags?.[0] ?? "default";
3912
+ if (!groups.has(tag)) groups.set(tag, []);
3913
+ groups.get(tag)?.push(op);
3914
+ }
3915
+ const opSlug = (op) => slug(`ep-${op.id}`);
3916
+ const sidebar = Array.from(groups.entries()).map(([tag, list]) => {
3917
+ const items = list.map((op, _i) => {
3918
+ const status = endpointStatus(checkLookup.get(op.id) ?? []);
3919
+ const id = opSlug(op);
3920
+ const rateLabel = status.rate === null ? "" : fmtRate(status.rate);
3921
+ const p95 = opMetrics.get(op.id)?.p95;
3922
+ const p95Label = typeof p95 === "number" ? `${Math.round(p95)}ms` : "";
3923
+ return `<label for="${esc2(id)}" class="ep-item ${status.cls}" data-state="${status.cls}" title="${esc2(op.method.toUpperCase())} ${esc2(op.path)}">
3924
+ <span class="ep-item-row">
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>
3928
+ </span>
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>` : ""}
3930
+ </label>`;
3931
+ }).join("\n ");
3932
+ return `<div class="ep-group">
3933
+ <div class="ep-group-h">${esc2(tag)}</div>
3934
+ ${items}
3935
+ </div>`;
3936
+ }).join("\n ");
3937
+ const radios = ops.map((op, i) => {
3938
+ const id = opSlug(op);
3939
+ return `<input type="radio" name="loadam-endpoint" id="${esc2(id)}" class="ep-radio"${i === 0 ? " checked" : ""}>`;
3940
+ }).join("");
3941
+ const totals = ops.map((op) => endpointStatus(checkLookup.get(op.id) ?? []));
3942
+ const failedCount = totals.filter((t) => t.cls === "bad").length;
3943
+ const flakyCount = totals.filter((t) => t.cls === "warn").length;
3944
+ const passedCount = totals.filter((t) => t.cls === "ok").length;
3945
+ const noDataCount = totals.length - failedCount - flakyCount - passedCount;
3946
+ const parts = [`${ops.length} endpoint${ops.length === 1 ? "" : "s"}`];
3947
+ if (runs.length > 0) {
3948
+ parts.push(`${passedCount} passed`);
3949
+ if (flakyCount > 0) parts.push(`${flakyCount} flaky`);
3950
+ if (failedCount > 0) parts.push(`${failedCount} failed`);
3951
+ if (noDataCount > 0) parts.push(`${noDataCount} no data`);
3952
+ }
3953
+ const headline = parts.join(" \xB7 ");
3954
+ const filterRadios = [
3955
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-all" class="ep-filter-radio" checked>`,
3956
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-bad" class="ep-filter-radio">`,
3957
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-warn" class="ep-filter-radio">`,
3958
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-ok" class="ep-filter-radio">`
3959
+ ].join("");
3960
+ const filterChips = `<div class="ep-filter">
3961
+ <label for="ep-filter-all" title="Show all endpoints">All ${ops.length}</label>
3962
+ <label for="ep-filter-bad" class="bad" title="Show failed endpoints only">Failed ${failedCount}</label>
3963
+ <label for="ep-filter-warn" class="warn" title="Show flaky endpoints only">Flaky ${flakyCount}</label>
3964
+ <label for="ep-filter-ok" class="ok" title="Show passed endpoints only">Passed ${passedCount}</label>
3965
+ </div>`;
3966
+ const panes = ops.map((op) => {
3967
+ const opChecks = checkLookup.get(op.id) ?? [];
3968
+ const status = endpointStatus(opChecks);
3969
+ const id = opSlug(op);
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>`;
3972
+ const runStrip = opChecks.map(({ run, check }) => {
3973
+ const total = check.passes + check.fails;
3974
+ const rate = total > 0 ? check.passes / total : 0;
3975
+ const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
3976
+ const pct = total > 0 ? fmtRate(rate) : "";
3977
+ return `<span class="ep-run ${cls}"><strong>${esc2(run)}</strong> ${check.passes}/${total} passed${pct ? ` \xB7 ${pct}` : ""}</span>`;
3978
+ }).join("");
3979
+ const checkRows = opChecks.map(({ run, check }) => {
3980
+ const total = check.passes + check.fails;
3981
+ const rate = total > 0 ? check.passes / total : 0;
3982
+ const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
3983
+ const pct = total > 0 ? ` <span class="muted">(${fmtRate(rate)})</span>` : "";
3984
+ return `<tr class="${cls}"><th>${esc2(run)}</th><td>${esc2(check.name)}</td><td>${check.passes}/${total} passed${pct}</td></tr>`;
3985
+ }).join("");
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>`;
3987
+ const metricsBlock = renderOpMetricsBlock(opMetrics.get(op.id));
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)}">
3990
+ <div class="ep-pane-h">
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>
3993
+ ${pill}
3994
+ </div>
3995
+ ${op.summary ? `<p class="ep-pane-sum">${esc2(op.summary)}</p>` : ""}
3996
+ ${tags ? `<div class="ep-tags">${tags}</div>` : ""}
3997
+ ${runStrip ? `<div class="ep-runs">${runStrip}</div>` : ""}
3998
+ ${metricsBlock}
3999
+ ${detail}
4000
+ </div>`;
4001
+ }).join("\n ");
4002
+ return `
4003
+ <section class="endpoints">
4004
+ <h2>Endpoints <span class="muted">(${esc2(headline)})</span></h2>
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 &lt; ${PASS_RATE_WARN * 100}%</span>.</p>
4006
+ <div class="ep-layout">
4007
+ ${filterRadios}
4008
+ ${radios}
4009
+ <aside class="ep-sidebar">
4010
+ ${filterChips}
4011
+ ${sidebar}
4012
+ </aside>
4013
+ <div class="ep-main">
4014
+ ${panes}
4015
+ </div>
4016
+ </div>
4017
+ </section>`;
4018
+ }
4019
+ var PASS_RATE_OK = 0.99;
4020
+ var PASS_RATE_WARN = 0.95;
4021
+ function endpointStatus(opChecks) {
4022
+ if (opChecks.length === 0) return { cls: "muted", label: "no data", rate: null };
4023
+ let passes = 0;
4024
+ let total = 0;
4025
+ for (const { check } of opChecks) {
4026
+ passes += check.passes;
4027
+ total += check.passes + check.fails;
4028
+ }
4029
+ if (total === 0) return { cls: "muted", label: "no data", rate: null };
4030
+ const rate = passes / total;
4031
+ if (rate >= PASS_RATE_OK) return { cls: "ok", label: "passed", rate };
4032
+ if (rate >= PASS_RATE_WARN) return { cls: "warn", label: "flaky", rate };
4033
+ return { cls: "bad", label: "failed", rate };
4034
+ }
4035
+ function fmtRate(rate) {
4036
+ if (rate === null) return "";
4037
+ const pct = rate * 100;
4038
+ return Number.isInteger(pct) ? `${pct}%` : `${pct.toFixed(1)}%`;
4039
+ }
4040
+ function computeOverall(meta, k6, ops) {
4041
+ const thresholdsFailed = (meta.thresholds?.failed ?? []).some((n) => !isSentinelThreshold(n));
4042
+ if (ops && ops.length > 0 && k6) {
4043
+ const lookup = /* @__PURE__ */ new Map();
4044
+ for (const op of ops) lookup.set(op.id, []);
4045
+ for (const summary of Object.values(k6)) {
4046
+ const checks = summary.root_group?.checks;
4047
+ if (!checks) continue;
4048
+ for (const c of Object.values(checks)) {
4049
+ const opId = c.name.split(/\s+/)[0];
4050
+ if (opId && lookup.has(opId)) lookup.get(opId)?.push(c);
4051
+ }
4052
+ }
4053
+ let okN = 0;
4054
+ let warnN = 0;
4055
+ let badN = 0;
4056
+ let withData = 0;
4057
+ for (const op of ops) {
4058
+ const opChecks = lookup.get(op.id) ?? [];
4059
+ const status = endpointStatus(opChecks.map((check) => ({ run: "", check })));
4060
+ if (status.cls === "ok") {
4061
+ okN++;
4062
+ withData++;
4063
+ } else if (status.cls === "warn") {
4064
+ warnN++;
4065
+ withData++;
4066
+ } else if (status.cls === "bad") {
4067
+ badN++;
4068
+ withData++;
4069
+ }
4070
+ }
4071
+ if (withData > 0) {
4072
+ const detail = `${okN}/${ops.length} endpoints`;
4073
+ if (badN === 0 && warnN === 0) {
4074
+ return { cls: "ok", label: "passed", detail };
4075
+ }
4076
+ const passingRate = (okN + warnN * 0.5) / ops.length;
4077
+ if (badN === 0) return { cls: "warn", label: "flaky", detail };
4078
+ if (passingRate >= PASS_RATE_WARN) return { cls: "warn", label: "partial", detail };
4079
+ if (passingRate >= 0.5) return { cls: "warn", label: "partial", detail };
4080
+ return { cls: "bad", label: "failed", detail };
4081
+ }
4082
+ }
4083
+ if (k6) {
4084
+ let passes = 0;
4085
+ let total = 0;
4086
+ for (const summary of Object.values(k6)) {
4087
+ const checks = summary.root_group?.checks;
4088
+ if (!checks) continue;
4089
+ for (const c of Object.values(checks)) {
4090
+ passes += c.passes;
4091
+ total += c.passes + c.fails;
4092
+ }
4093
+ }
4094
+ if (total > 0) {
4095
+ const rate = passes / total;
4096
+ const detail = fmtRate(rate);
4097
+ if (rate >= PASS_RATE_OK && !thresholdsFailed) {
4098
+ return { cls: "ok", label: "passed", detail };
4099
+ }
4100
+ if (rate >= PASS_RATE_WARN && !thresholdsFailed) {
4101
+ return { cls: "warn", label: "flaky", detail };
4102
+ }
4103
+ return { cls: "bad", label: "failed", detail };
4104
+ }
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` : "";
4109
+ if (thresholdsFailed || meta.exitCode !== void 0 && meta.exitCode !== 0) {
4110
+ return { cls: "bad", label: "failed", detail: testDetail };
4111
+ }
4112
+ return { cls: "ok", label: "passed", detail: testDetail };
4113
+ }
4114
+ function collectOpMetrics(ops, k6) {
4115
+ const out = /* @__PURE__ */ new Map();
4116
+ for (const op of ops) out.set(op.id, { perRun: /* @__PURE__ */ new Map(), p95: null });
4117
+ if (!k6) return out;
4118
+ for (const [runName, summary] of Object.entries(k6)) {
4119
+ const metrics = summary.metrics;
4120
+ if (!metrics) continue;
4121
+ for (const op of ops) {
4122
+ const latencyKey = Object.keys(metrics).find(
4123
+ (k) => k.startsWith("loadam_op_latency{") && k.includes(`name:${op.id}`)
4124
+ );
4125
+ const p95 = latencyKey && typeof metrics[latencyKey]?.values?.["p(95)"] === "number" ? metrics[latencyKey].values["p(95)"] : null;
4126
+ const buckets = {};
4127
+ let total = 0;
4128
+ for (const [k, m] of Object.entries(metrics)) {
4129
+ if (!k.startsWith("loadam_op_status{") || !k.includes(`name:${op.id}`)) continue;
4130
+ const bucket = (k.match(/bucket:([0-9]xx)/) ?? [])[1];
4131
+ if (!bucket) continue;
4132
+ const count = typeof m.values?.count === "number" ? m.values.count : 0;
4133
+ if (count > 0) {
4134
+ buckets[bucket] = count;
4135
+ total += count;
4136
+ }
4137
+ }
4138
+ const entry = out.get(op.id);
4139
+ if (entry) {
4140
+ entry.perRun.set(runName, { p95, buckets, total });
4141
+ if (runName === "load" && p95 !== null) entry.p95 = p95;
4142
+ else if (entry.p95 === null && p95 !== null) entry.p95 = p95;
4143
+ }
4144
+ }
4145
+ }
4146
+ return out;
4147
+ }
4148
+ function isSentinelThreshold(name) {
4149
+ const stripped = name.replace(/^[a-zA-Z0-9_-]+:\s+/, "");
4150
+ return stripped.startsWith("loadam_op_latency") || stripped.startsWith("loadam_op_status");
4151
+ }
4152
+ var BUCKET_ORDER = ["1xx", "2xx", "3xx", "4xx", "5xx"];
4153
+ var BUCKET_CLASS = {
4154
+ "1xx": "muted",
4155
+ "2xx": "ok",
4156
+ "3xx": "ok",
4157
+ "4xx": "bad",
4158
+ "5xx": "bad"
4159
+ };
4160
+ function renderOpMetricsBlock(metrics) {
4161
+ if (!metrics || metrics.perRun.size === 0) return "";
4162
+ const rows = [];
4163
+ for (const [run, m] of metrics.perRun) {
4164
+ if (m.total === 0 && m.p95 === null) continue;
4165
+ const segments = BUCKET_ORDER.filter((b) => (m.buckets[b] ?? 0) > 0).map((b) => {
4166
+ const count = m.buckets[b] ?? 0;
4167
+ const pct = m.total > 0 ? count / m.total * 100 : 0;
4168
+ return `<span class="bkt ${BUCKET_CLASS[b]}" style="width:${pct.toFixed(2)}%" title="${b} \xB7 ${count} req \xB7 ${pct.toFixed(1)}%">${b} ${count}</span>`;
4169
+ }).join("");
4170
+ const p95 = m.p95 !== null ? `${Math.round(m.p95)}ms` : "\u2014";
4171
+ rows.push(`<tr>
4172
+ <th>${esc2(run)}</th>
4173
+ <td class="num">${m.total}</td>
4174
+ <td class="num">${esc2(p95)}</td>
4175
+ <td><div class="bkt-bar">${segments || `<span class="muted">no data</span>`}</div></td>
4176
+ </tr>`);
4177
+ }
4178
+ if (rows.length === 0) return "";
4179
+ return `<table class="kv ep-metrics">
4180
+ <thead><tr><th>run</th><th>requests</th><th>p95</th><th>status codes</th></tr></thead>
4181
+ <tbody>${rows.join("")}</tbody>
4182
+ </table>`;
4183
+ }
4184
+ function renderK6Section(k6, hasEndpoints) {
4185
+ if (!k6) return "";
4186
+ const entries = Object.entries(k6);
4187
+ if (entries.length === 0) return "";
4188
+ const blocks = entries.map(([name, summary]) => ({ name, html: renderK6Block(name, summary, hasEndpoints) })).filter((b) => b.html !== "");
4189
+ if (blocks.length === 0) return "";
4190
+ if (blocks.length === 1) {
4191
+ return `<section><h2>k6 results</h2>${blocks[0]?.html ?? ""}</section>`;
4192
+ }
4193
+ const tabs = blocks.map((b, i) => {
4194
+ const id = `loadam-tab-${slug(b.name)}`;
4195
+ return `
4196
+ <input type="radio" name="loadam-k6-tab" id="${esc2(id)}" class="tab-input"${i === 0 ? " checked" : ""}>`;
4197
+ }).join("");
4198
+ const labels = blocks.map((b) => {
4199
+ const id = `loadam-tab-${slug(b.name)}`;
4200
+ return `<label for="${esc2(id)}" class="tab-label">${esc2(b.name)}</label>`;
4201
+ }).join("");
4202
+ const panes = blocks.map((b) => `<div class="tab-pane" data-tab="${esc2(slug(b.name))}">${b.html}</div>`).join("");
4203
+ return `
4204
+ <section class="tabs">
4205
+ <h2>k6 results <span class="tab-hint">(${blocks.length} runs \u2014 click to switch)</span></h2>${tabs}
4206
+ <div class="tab-bar">${labels}</div>
4207
+ ${panes}
4208
+ </section>`;
4209
+ }
4210
+ function renderK6Block(name, summary, hasEndpoints) {
4211
+ const metrics = summary.metrics ?? {};
4212
+ const dur = metrics.http_req_duration?.values;
4213
+ const reqs = metrics.http_reqs?.values;
4214
+ const failed = metrics.http_req_failed?.values;
4215
+ const headlineCells = [];
4216
+ if (dur && typeof dur["p(95)"] === "number")
4217
+ headlineCells.push({ label: "p95", value: fmtMs(dur["p(95)"]) });
4218
+ if (reqs && typeof reqs.count === "number")
4219
+ headlineCells.push({ label: "requests", value: String(reqs.count) });
4220
+ if (reqs && typeof reqs.rate === "number")
4221
+ headlineCells.push({ label: "rps", value: `${reqs.rate.toFixed(1)}/s` });
4222
+ if (failed && typeof failed.rate === "number")
4223
+ headlineCells.push({ label: "errors", value: `${(failed.rate * 100).toFixed(2)}%` });
4224
+ const headline = headlineCells.length > 0 ? `<div class="cards inner">${headlineCells.map(
4225
+ (c) => `<div class="card"><div class="card-v">${esc2(c.value)}</div><div class="card-l">${esc2(c.label)}</div></div>`
4226
+ ).join("")}</div>` : "";
4227
+ const latency = dur ? `
4228
+ <h3>http_req_duration</h3>
2803
4229
  <table class="kv">
2804
4230
  <tbody>
2805
- ${rows.map(([k, v]) => `<tr><th>${esc(k)}</th><td>${esc(v)}</td></tr>`).join("\n ")}
4231
+ ${[
4232
+ ["min", fmtMs(dur.min)],
4233
+ ["med", fmtMs(dur.med)],
4234
+ ["avg", fmtMs(dur.avg)],
4235
+ ["p(90)", fmtMs(dur["p(90)"])],
4236
+ ["p(95)", fmtMs(dur["p(95)"])],
4237
+ ["p(99)", fmtMs(dur["p(99)"])],
4238
+ ["max", fmtMs(dur.max)]
4239
+ ].map(([k, v]) => `<tr><th>${esc2(k)}</th><td>${esc2(v)}</td></tr>`).join("")}
2806
4240
  </tbody>
2807
4241
  </table>
2808
- ${renderPercentileBars(dur)}
2809
- </div>`);
2810
- }
2811
- if (blocks.length === 0) return "";
2812
- return `<section><h2>Latency</h2>${blocks.join("\n")}</section>`;
4242
+ ${renderPercentileBars(dur)}` : "";
4243
+ const checks = summary.root_group?.checks;
4244
+ const checkBlock = checks ? hasEndpoints ? renderChecksSummary(checks) : renderChecks(checks) : "";
4245
+ if (!headline && !latency && !checkBlock) return "";
4246
+ return `
4247
+ <div class="metric-block">
4248
+ ${headline}
4249
+ ${latency}
4250
+ ${checkBlock}
4251
+ </div>`;
4252
+ }
4253
+ function renderChecksSummary(checks) {
4254
+ const entries = Object.values(checks);
4255
+ if (entries.length === 0) return "";
4256
+ let ok = 0;
4257
+ let warn = 0;
4258
+ let bad = 0;
4259
+ let totalPasses = 0;
4260
+ let totalInvocations = 0;
4261
+ for (const c of entries) {
4262
+ const t = c.passes + c.fails;
4263
+ totalPasses += c.passes;
4264
+ totalInvocations += t;
4265
+ const r = t > 0 ? c.passes / t : 0;
4266
+ if (r >= PASS_RATE_OK) ok++;
4267
+ else if (r >= PASS_RATE_WARN) warn++;
4268
+ else bad++;
4269
+ }
4270
+ const cls = bad > 0 ? "bad" : warn > 0 ? "warn" : "ok";
4271
+ const overallRate = totalInvocations > 0 ? totalPasses / totalInvocations : 0;
4272
+ const parts = [`<strong>${ok}</strong>/${entries.length} passed`];
4273
+ if (warn > 0) parts.push(`<span class="warn-text">${warn} flaky</span>`);
4274
+ if (bad > 0) parts.push(`<span class="bad-text">${bad} failed</span>`);
4275
+ return `
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>`;
4277
+ }
4278
+ function renderChecks(checks) {
4279
+ const entries = Object.values(checks);
4280
+ if (entries.length === 0) return "";
4281
+ const failed = entries.filter((c) => c.fails > 0);
4282
+ const passed = entries.length - failed.length;
4283
+ const summaryLine = `${passed}/${entries.length} passed${failed.length > 0 ? ` \xB7 ${failed.length} failed` : ""}`;
4284
+ const row = (c, kind) => {
4285
+ const total = c.passes + c.fails;
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>`;
4287
+ };
4288
+ const failedRows = failed.map((c) => row(c, "bad")).join("");
4289
+ const passedRows = entries.filter((c) => c.fails === 0).map((c) => row(c, "ok")).join("");
4290
+ return `
4291
+ <h3>Per-operation checks <span class="muted">(${esc2(summaryLine)})</span></h3>
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>
4293
+ <table class="kv checks">
4294
+ <tbody>${failedRows}${passedRows}</tbody>
4295
+ </table>`;
4296
+ }
4297
+ function slug(s) {
4298
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "tab";
4299
+ }
4300
+ function dynamicEndpointStyles(ops) {
4301
+ if (!ops || ops.length === 0) return "";
4302
+ return ops.map((op) => {
4303
+ const id = slug(`ep-${op.id}`);
4304
+ return `
4305
+ .ep-layout > input#${id}:checked ~ .ep-main .ep-pane[data-ep="${id}"]{display:block}
4306
+ .ep-layout > input#${id}:checked ~ .ep-sidebar label[for="${id}"]{background:var(--card);color:var(--fg);box-shadow:inset 2px 0 0 var(--acc)}`;
4307
+ }).join("");
4308
+ }
4309
+ function dynamicTabStyles(k6) {
4310
+ if (!k6) return "";
4311
+ const names = Object.keys(k6);
4312
+ if (names.length < 2) return "";
4313
+ const rules = names.map((n) => {
4314
+ const s = slug(n);
4315
+ const id = `loadam-tab-${s}`;
4316
+ return `
4317
+ section.tabs > input#${id}:checked ~ .tab-bar label[for="${id}"]{background:var(--card);color:var(--fg);border-color:var(--brd);border-bottom-color:var(--card)}
4318
+ section.tabs > input#${id}:checked ~ .tab-pane[data-tab="${s}"]{display:block}`;
4319
+ }).join("\n");
4320
+ return rules;
2813
4321
  }
2814
4322
  function renderPercentileBars(dur) {
2815
4323
  const max = dur.max ?? Math.max(...Object.values(dur));
@@ -2825,7 +4333,7 @@ function renderPercentileBars(dur) {
2825
4333
  <div class="bars">
2826
4334
  ${bars.map(([k, v]) => {
2827
4335
  const pct = Math.max(2, Math.round(v / max * 100));
2828
- return `<div class="bar-row"><span class="bar-l">${esc(k)}</span><div class="bar"><div class="bar-fill" style="width:${pct}%"></div></div><span class="bar-v">${esc(fmtMs(v))}</span></div>`;
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>`;
2829
4337
  }).join("\n ")}
2830
4338
  </div>`;
2831
4339
  }
@@ -2833,7 +4341,7 @@ function renderDrift(md) {
2833
4341
  return `
2834
4342
  <section>
2835
4343
  <h2>Drift findings</h2>
2836
- <pre class="drift">${esc(md)}</pre>
4344
+ <pre class="drift">${esc2(md)}</pre>
2837
4345
  </section>`;
2838
4346
  }
2839
4347
  function renderContract(failures) {
@@ -2842,27 +4350,27 @@ function renderContract(failures) {
2842
4350
  <h2>Contract failures (${failures.length})</h2>
2843
4351
  <ul class="failures">
2844
4352
  ${failures.map(
2845
- (f) => `<li><div class="ftest">${esc(f.test)}</div>${f.message ? `<pre>${esc(f.message)}</pre>` : ""}</li>`
4353
+ (f) => `<li><div class="ftest">${esc2(f.test)}</div>${f.message ? `<pre>${esc2(f.message)}</pre>` : ""}</li>`
2846
4354
  ).join("\n ")}
2847
4355
  </ul>
2848
4356
  </section>`;
2849
4357
  }
2850
4358
  function renderRunDetails(meta) {
2851
4359
  const flagRows = Object.entries(meta.flags).map(
2852
- ([k, v]) => `<tr><th>${esc(k)}</th><td>${esc(String(v))}</td></tr>`
4360
+ ([k, v]) => `<tr><th>${esc2(k)}</th><td>${esc2(String(v))}</td></tr>`
2853
4361
  );
2854
- const envRow = meta.envVars.length > 0 ? `<tr><th>env vars</th><td>${meta.envVars.map((e) => `<code>${esc(e)}</code>`).join(" ")}</td></tr>` : "";
4362
+ const envRow = meta.envVars.length > 0 ? `<tr><th>env vars</th><td>${meta.envVars.map((e) => `<code>${esc2(e)}</code>`).join(" ")}</td></tr>` : "";
2855
4363
  return `
2856
4364
  <section>
2857
4365
  <h2>Run details</h2>
2858
4366
  <table class="kv">
2859
4367
  <tbody>
2860
- <tr><th>session id</th><td><code>${esc(meta.id)}</code></td></tr>
2861
- <tr><th>spec</th><td><code>${esc(meta.spec.path)}</code></td></tr>
2862
- <tr><th>spec sha256</th><td><code>${esc(meta.spec.sha256.slice(0, 16))}\u2026</code></td></tr>
2863
- <tr><th>IR digest</th><td><code>${esc(meta.irDigest.slice(0, 16))}\u2026</code></td></tr>
2864
- <tr><th>started</th><td>${esc(meta.startedAt)}</td></tr>
2865
- ${meta.endedAt ? `<tr><th>ended</th><td>${esc(meta.endedAt)}</td></tr>` : ""}
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>` : ""}
2866
4374
  ${typeof meta.exitCode === "number" ? `<tr><th>exit code</th><td>${meta.exitCode}</td></tr>` : ""}
2867
4375
  ${envRow}
2868
4376
  ${flagRows.join("\n ")}
@@ -2873,9 +4381,9 @@ function renderRunDetails(meta) {
2873
4381
  function renderFooter(meta, version) {
2874
4382
  return `
2875
4383
  <footer>
2876
- Generated by <a href="https://github.com/anonxhash/loadam">loadam ${esc(version)}</a> \xB7
4384
+ Generated by <a href="https://github.com/DesmondSanctity/loadam" target="_blank" rel="noopener">loadam ${esc2(version)}</a> \xB7
2877
4385
  schema v${meta.schemaVersion} \xB7
2878
- IR <code>${esc(meta.irDigest.slice(0, 12))}</code>
4386
+ IR <code>${esc2(meta.irDigest.slice(0, 12))}</code>
2879
4387
  </footer>`;
2880
4388
  }
2881
4389
  function reportTitle(meta) {
@@ -2887,7 +4395,7 @@ function fmtMs(n) {
2887
4395
  if (n >= 1e3) return `${(n / 1e3).toFixed(2)} s`;
2888
4396
  return `${n.toFixed(0)} ms`;
2889
4397
  }
2890
- function esc(s) {
4398
+ function esc2(s) {
2891
4399
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2892
4400
  }
2893
4401
  function escScript(s) {
@@ -2897,18 +4405,20 @@ var STYLES = `
2897
4405
  :root{
2898
4406
  --bg:#fafafa;--fg:#111;--mut:#666;--brd:#e5e5e5;--card:#fff;
2899
4407
  --ok:#15803d;--ok-bg:#dcfce7;--bad:#b91c1c;--bad-bg:#fee2e2;
4408
+ --warn:#a16207;--warn-bg:#fef3c7;
2900
4409
  --acc:#2563eb;--bar:#3b82f6;--code:#f4f4f5;
2901
4410
  }
2902
4411
  @media (prefers-color-scheme:dark){
2903
4412
  :root{
2904
4413
  --bg:#0a0a0a;--fg:#f5f5f5;--mut:#a1a1aa;--brd:#27272a;--card:#18181b;
2905
4414
  --ok:#86efac;--ok-bg:#14532d;--bad:#fca5a5;--bad-bg:#7f1d1d;
4415
+ --warn:#fcd34d;--warn-bg:#78350f;
2906
4416
  --acc:#60a5fa;--bar:#3b82f6;--code:#27272a;
2907
4417
  }
2908
4418
  }
2909
4419
  *{box-sizing:border-box}
2910
4420
  html,body{margin:0;padding:0;background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
2911
- body{max-width:960px;margin:0 auto;padding:24px 20px 60px}
4421
+ body{max-width:1200px;margin:0 auto;padding:24px 20px 60px}
2912
4422
  h1{font-size:20px;margin:0 0 4px}
2913
4423
  h2{font-size:15px;margin:24px 0 12px;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}
2914
4424
  h3{font-size:14px;margin:16px 0 8px;font-weight:600}
@@ -2916,11 +4426,23 @@ code{font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--
2916
4426
  a{color:var(--acc);text-decoration:none}
2917
4427
  a:hover{text-decoration:underline}
2918
4428
  section{margin-top:8px}
4429
+ .brand-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding-bottom:14px;margin-bottom:16px;border-bottom:1px solid var(--brd)}
4430
+ .brand{display:inline-flex;align-items:center;gap:8px;color:var(--fg);text-decoration:none;font-weight:700;font-size:16px;letter-spacing:-0.01em;line-height:1}
4431
+ .brand:hover{text-decoration:none;opacity:.8}
4432
+ .brand svg.brand-mark{width:22px;height:22px;display:block;color:var(--fg)}
4433
+ .brand-name{font-family:ui-sans-serif,system-ui,-apple-system,sans-serif}
4434
+ .brand-name-am{background:linear-gradient(135deg,#f59e0b,#ef4444);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;color:transparent}
4435
+ .brand-tag{font-size:11px;color:var(--mut);text-transform:uppercase;letter-spacing:.08em;font-weight:500}
4436
+ @media (max-width:600px){.brand-tag{display:none}}
2919
4437
  .hdr{display:flex;justify-content:space-between;align-items:flex-start;gap:24px;padding-bottom:16px;border-bottom:1px solid var(--brd)}
2920
- .hdr-left .cmd{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--mut);font-weight:600}
4438
+ .hdr-left .cmd{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--mut);font-weight:600;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
2921
4439
  .hdr-left .sub{color:var(--mut);font-size:13px;margin-top:4px}
2922
4440
  .hdr-right{text-align:right}
2923
- .hdr-right .when,.hdr-right .dur{font-size:12px;color:var(--mut);margin-top:4px;font-variant-numeric:tabular-nums}
4441
+ .hdr-right .when,.hdr-right .dur{font-size:12px;color:var(--mut);margin-top:2px;font-variant-numeric:tabular-nums}
4442
+ .status-chip{display:inline-block;padding:2px 8px;border-radius:3px;font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase}
4443
+ .status-chip.ok{background:var(--ok-bg);color:var(--ok)}
4444
+ .status-chip.warn{background:var(--warn-bg);color:var(--warn)}
4445
+ .status-chip.bad{background:var(--bad-bg);color:var(--bad)}
2924
4446
  .badge{display:inline-block;padding:4px 10px;border-radius:4px;font-size:11px;font-weight:700;letter-spacing:.06em}
2925
4447
  .badge.ok{background:var(--ok-bg);color:var(--ok)}
2926
4448
  .badge.bad{background:var(--bad-bg);color:var(--bad)}
@@ -2947,25 +4469,208 @@ table.kv th{font-weight:500;color:var(--mut);width:160px;white-space:nowrap}
2947
4469
  .failures li{background:var(--bad-bg);border:1px solid var(--bad);border-radius:4px;padding:8px 12px;margin-bottom:6px}
2948
4470
  .failures .ftest{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;font-weight:600}
2949
4471
  .failures pre{margin:6px 0 0;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap}
4472
+ .reason{background:var(--bad-bg);border:1px solid var(--bad);border-radius:6px;padding:12px 16px;margin-top:20px}
4473
+ .reason.warn{background:var(--warn-bg);border-color:var(--warn)}
4474
+ .reason h2{margin:0 0 8px;color:var(--bad);text-transform:uppercase;letter-spacing:.04em;font-size:12px}
4475
+ .reason.warn h2{color:var(--warn)}
4476
+ .reason ul{margin:0;padding:0 0 0 18px}
4477
+ .reason li{margin:4px 0;font-size:13px}
4478
+ .reason details.more{display:inline;margin-left:6px}
4479
+ .reason details.more summary{display:inline;cursor:pointer;color:var(--mut);font-size:12px;list-style:none}
4480
+ .reason details.more summary::-webkit-details-marker{display:none}
4481
+ .reason details.more summary:hover{color:var(--fg)}
4482
+ .reason details.more[open] summary{display:block;margin-bottom:4px}
4483
+ .thr li.thr-more{list-style:none;margin-left:-18px}
4484
+ .thr li.thr-more details summary{cursor:pointer;font-size:11px;color:var(--mut);padding:2px 0}
4485
+ .thr li.thr-more details summary:hover{color:var(--fg)}
4486
+ .thr li.thr-more details ul.thr{margin-top:4px;padding-left:14px}
4487
+ .reason code{background:rgba(0,0,0,.12)}
4488
+ .muted{color:var(--mut);font-weight:400;font-size:11px}
4489
+ table.checks tr.bad th,table.checks tr.bad td{color:var(--bad);background:var(--bad-bg)}
4490
+ table.checks tr.warn th,table.checks tr.warn td{color:var(--warn);background:var(--warn-bg)}
4491
+ table.checks tr.ok th{color:var(--mut)}
4492
+ table.checks tr.ok td{color:var(--ok)}
4493
+ .ep-detail tr.bad th,.ep-detail tr.bad td{color:var(--bad);background:var(--bad-bg)}
4494
+ .ep-detail tr.warn th,.ep-detail tr.warn td{color:var(--warn);background:var(--warn-bg)}
4495
+ .ep-detail tr.ok th{color:var(--mut)}
4496
+ .ep-detail tr.ok td{color:var(--ok)}
4497
+ .tier{display:inline-block;padding:1px 7px;border-radius:9px;font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}
4498
+ .tier.ok{background:var(--ok-bg);color:var(--ok)}
4499
+ .tier.warn{background:var(--warn-bg);color:var(--warn)}
4500
+ .tier.bad{background:var(--bad-bg);color:var(--bad)}
4501
+ .cards.inner{margin-top:0;margin-bottom:12px;grid-template-columns:repeat(auto-fit,minmax(110px,1fr))}
4502
+ section.tabs > input.tab-input{position:absolute;opacity:0;pointer-events:none}
4503
+ section.tabs > .tab-bar{display:flex;gap:0;border-bottom:1px solid var(--brd);margin-top:4px}
4504
+ section.tabs > .tab-bar .tab-label{padding:8px 16px;cursor:pointer;font-size:13px;font-weight:500;color:var(--mut);border:1px solid transparent;border-bottom:none;border-radius:4px 4px 0 0;margin-bottom:-1px;user-select:none}
4505
+ section.tabs > .tab-bar .tab-label:hover{color:var(--fg)}
4506
+ section.tabs > .tab-pane{display:none;padding-top:14px}
4507
+ section.tabs > h2 .tab-hint{font-size:11px;font-weight:400;color:var(--mut);text-transform:none;letter-spacing:0;margin-left:6px}
4508
+ .actions{display:flex;gap:6px;margin-top:8px;justify-content:flex-end;flex-wrap:wrap}
4509
+ .act{font:inherit;font-size:11px;padding:4px 9px;border:1px solid var(--brd);background:var(--card);color:var(--fg);border-radius:4px;cursor:pointer;letter-spacing:.02em}
4510
+ .act:hover{background:var(--code);border-color:var(--mut)}
4511
+ .hint{color:var(--mut);font-size:12px;margin:4px 0 8px}
4512
+ .page-grid{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:24px;align-items:start;margin-top:20px}
4513
+ .page-main{min-width:0}
4514
+ .page-side{position:sticky;top:16px;max-height:calc(100vh - 32px);overflow-y:auto;font-size:13px;padding-right:4px}
4515
+ .page-side h2{margin-top:8px;font-size:11px}
4516
+ .page-side section{margin-top:16px}
4517
+ .page-side section:first-child{margin-top:0}
4518
+ .page-side .cards{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
4519
+ .page-side .card{padding:8px 10px}
4520
+ .page-side .card-v{font-size:15px}
4521
+ .page-side .metric-block{padding:10px 12px}
4522
+ .page-side table.kv th{width:90px;font-size:12px}
4523
+ .page-side table.kv td{font-size:12px}
4524
+ .page-side section.tabs > .tab-bar .tab-label{padding:6px 10px;font-size:12px}
4525
+ .page-side .bar-row{grid-template-columns:48px 1fr 64px}
4526
+ .page-side .bars{margin-top:6px}
4527
+ @media (max-width:900px){
4528
+ .page-grid{grid-template-columns:1fr;gap:0}
4529
+ .page-side{position:static;max-height:none;padding-right:0}
4530
+ }
4531
+ .chk-count{font-variant-numeric:tabular-nums;font-weight:600}
4532
+ .chk-sep{opacity:.5;margin:0 1px}
4533
+ .chk-word{color:var(--mut);font-size:12px;margin-left:2px}
4534
+ .chk-line{font-size:12px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:8px;padding:6px 8px;background:var(--code);border-radius:4px}
4535
+ .chk-tag{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.04em;color:var(--mut);padding:2px 6px;border-radius:3px;background:var(--card)}
4536
+ .chk-tag.ok{color:var(--ok)}
4537
+ .chk-tag.warn{color:var(--warn);background:var(--warn-bg)}
4538
+ .chk-tag.bad{color:var(--bad);background:var(--bad-bg)}
4539
+ .bad-text{color:var(--bad);font-weight:600}
4540
+ .warn-text{color:var(--warn);font-weight:600}
4541
+ section.endpoints{margin-top:24px}
4542
+ .ep-layout{display:grid;grid-template-columns:220px minmax(0,1fr);gap:0;border:1px solid var(--brd);border-radius:6px;background:var(--card);overflow:hidden;min-height:520px}
4543
+ .ep-layout > .ep-radio{position:absolute;opacity:0;pointer-events:none}
4544
+ .ep-sidebar{border-right:1px solid var(--brd);background:var(--bg);max-height:820px;overflow-y:auto;padding:6px 0}
4545
+ .ep-group{padding:6px 0}
4546
+ .ep-group + .ep-group{border-top:1px solid var(--brd)}
4547
+ .ep-group-h{font-size:10px;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);padding:4px 12px;font-weight:600}
4548
+ .ep-item{display:flex;flex-direction:column;gap:2px;padding:7px 12px;cursor:pointer;font-size:12px;border-left:2px solid transparent;color:var(--mut);user-select:none}
4549
+ .ep-item:hover{background:var(--code);color:var(--fg)}
4550
+ .ep-item-row{display:flex;align-items:center;gap:8px;min-width:0}
4551
+ .ep-item-path{font:12px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
4552
+ .ep-item-meta{display:flex;align-items:center;gap:6px;padding-left:62px;font-size:10px}
4553
+ .ep-item-state{text-transform:uppercase;letter-spacing:.04em;font-weight:600;font-size:9px;opacity:.85}
4554
+ .ep-item-state.ok{color:var(--ok)}
4555
+ .ep-item-state.warn{color:var(--warn)}
4556
+ .ep-item-state.bad{color:var(--bad)}
4557
+ .ep-item-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0;background:var(--brd)}
4558
+ .ep-item-dot.ok{background:var(--ok)}
4559
+ .ep-item-dot.warn{background:var(--warn)}
4560
+ .ep-item-dot.bad{background:var(--bad)}
4561
+ .ep-item-dot.muted{background:var(--mut);opacity:.5}
4562
+ .ep-item-rate{font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--mut);font-variant-numeric:tabular-nums;flex-shrink:0}
4563
+ .ep-item-rate.ok{color:var(--ok)}
4564
+ .ep-item-rate.warn{color:var(--warn)}
4565
+ .ep-item-rate.bad{color:var(--bad)}
4566
+ .ep-item-p95{font:10px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--mut);font-variant-numeric:tabular-nums;margin-left:auto;flex-shrink:0;opacity:.85}
4567
+ .ep-main{padding:18px 20px;overflow-x:auto}
4568
+ .ep-pane{display:none}
4569
+ .ep-pane-h{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:6px}
4570
+ .ep-pane-sum{margin:4px 0 12px;color:var(--mut);font-size:13px}
4571
+ .ep-method{display:inline-block;min-width:54px;text-align:center;padding:3px 8px;border-radius:3px;font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;font-weight:700;letter-spacing:.04em;color:#fff;background:#6b7280}
4572
+ .ep-method.get{background:#2563eb}
4573
+ .ep-method.post{background:#15803d}
4574
+ .ep-method.put{background:#d97706}
4575
+ .ep-method.patch{background:#7c3aed}
4576
+ .ep-method.delete{background:#b91c1c}
4577
+ .ep-path{font:13px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;font-weight:600}
4578
+ .ep-path code{background:transparent;padding:0;font-size:13px}
4579
+ .ep-pill{font-size:10px;padding:2px 8px;border-radius:10px;font-weight:600;text-transform:uppercase;letter-spacing:.05em}
4580
+ .ep-pill.ok{background:var(--ok-bg);color:var(--ok)}
4581
+ .ep-pill.warn{background:var(--warn-bg);color:var(--warn)}
4582
+ .ep-pill.bad{background:var(--bad-bg);color:var(--bad)}
4583
+ .ep-pill.muted{background:var(--code);color:var(--mut)}
4584
+ .ep-pill-rate{font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:none;letter-spacing:0;font-weight:500;margin-left:4px;opacity:.85}
4585
+ .ep-runs{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0}
4586
+ .ep-run{font-size:12px;padding:3px 8px;border-radius:3px;background:var(--code);font-variant-numeric:tabular-nums}
4587
+ .ep-run.bad{background:var(--bad-bg);color:var(--bad)}
4588
+ .ep-run.warn{background:var(--warn-bg);color:var(--warn)}
4589
+ .ep-run.ok{background:var(--ok-bg);color:var(--ok)}
4590
+ .ep-run strong{font-weight:600;margin-right:4px;text-transform:uppercase;letter-spacing:.04em;font-size:11px}
4591
+ .ep-tags{display:flex;gap:4px;flex-wrap:wrap;margin-top:4px}
4592
+ .ep-tag{font-size:10px;padding:2px 6px;background:var(--code);color:var(--mut);border-radius:3px;text-transform:uppercase;letter-spacing:.04em}
4593
+ .ep-detail{margin-top:10px}
4594
+ .ep-detail th:first-child{width:60px;text-transform:uppercase;font-size:10px;letter-spacing:.04em}
4595
+ .ep-metrics{margin:10px 0 4px;font-size:12px}
4596
+ .ep-metrics th{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}
4597
+ .ep-metrics td.num{font-variant-numeric:tabular-nums;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
4598
+ .bkt-bar{display:flex;height:14px;border-radius:3px;overflow:hidden;background:var(--code);font-size:10px;line-height:14px;font-variant-numeric:tabular-nums;min-width:160px}
4599
+ .bkt{display:inline-block;text-align:center;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:clip;padding:0 4px;letter-spacing:.02em;font-weight:600}
4600
+ .bkt.ok{background:var(--ok)}
4601
+ .bkt.warn{background:var(--warn)}
4602
+ .bkt.bad{background:var(--bad)}
4603
+ .bkt.muted{background:var(--mut);opacity:.6}
4604
+ .ep-filter{display:flex;gap:4px;padding:8px 10px;border-bottom:1px solid var(--brd);background:var(--card)}
4605
+ .ep-layout > .ep-filter-radio{position:absolute;opacity:0;pointer-events:none}
4606
+ .ep-filter label{font-size:10px;text-transform:uppercase;letter-spacing:.05em;font-weight:600;padding:4px 8px;border-radius:3px;cursor:pointer;color:var(--mut);background:var(--code);user-select:none}
4607
+ .ep-filter label:hover{color:var(--fg)}
4608
+ .ep-filter label.ok{color:var(--ok)}
4609
+ .ep-filter label.warn{color:var(--warn)}
4610
+ .ep-filter label.bad{color:var(--bad)}
4611
+ /* Active chip + matching item visibility \u2014 pure CSS via :checked ~ siblings. */
4612
+ .ep-layout > input#ep-filter-all:checked ~ .ep-sidebar label[for="ep-filter-all"]{background:var(--acc);color:#fff}
4613
+ .ep-layout > input#ep-filter-bad:checked ~ .ep-sidebar label[for="ep-filter-bad"]{background:var(--bad);color:#fff}
4614
+ .ep-layout > input#ep-filter-warn:checked ~ .ep-sidebar label[for="ep-filter-warn"]{background:var(--warn);color:#fff}
4615
+ .ep-layout > input#ep-filter-ok:checked ~ .ep-sidebar label[for="ep-filter-ok"]{background:var(--ok);color:#fff}
4616
+ .ep-layout > input#ep-filter-bad:checked ~ .ep-sidebar .ep-item:not([data-state="bad"]){display:none}
4617
+ .ep-layout > input#ep-filter-warn:checked ~ .ep-sidebar .ep-item:not([data-state="warn"]){display:none}
4618
+ .ep-layout > input#ep-filter-ok:checked ~ .ep-sidebar .ep-item:not([data-state="ok"]){display:none}
4619
+ /* Hide group headers whose children are all filtered out. Cheap heuristic:
4620
+ when a non-"All" filter is active and a group has no children matching
4621
+ its tier, we leave the header visible \u2014 minor visual noise but no JS. */
4622
+ @media (max-width:720px){
4623
+ .ep-layout{grid-template-columns:1fr;min-height:0}
4624
+ .ep-sidebar{max-height:240px;border-right:none;border-bottom:1px solid var(--brd)}
4625
+ }
4626
+ @media print{
4627
+ .actions{display:none}
4628
+ .ep-layout{grid-template-columns:1fr;border:none}
4629
+ .ep-sidebar{display:none}
4630
+ .ep-pane{display:block!important;break-inside:avoid;border-bottom:1px solid var(--brd);padding-bottom:12px;margin-bottom:12px}
4631
+ }
2950
4632
  footer{margin-top:40px;padding-top:16px;border-top:1px solid var(--brd);color:var(--mut);font-size:12px;text-align:center}
2951
4633
  `;
4634
+ var DOWNLOAD_SCRIPT = `<script>(function(){
4635
+ var d=document,el=d.getElementById('loadam-data');
4636
+ if(!el)return;
4637
+ var data;try{data=JSON.parse(el.textContent||'{}')}catch(e){return}
4638
+ var name=(data&&data.meta&&data.meta.id)||'loadam-report';
4639
+ function dl(blob,filename){
4640
+ var url=URL.createObjectURL(blob);
4641
+ var a=d.createElement('a');a.href=url;a.download=filename;
4642
+ d.body.appendChild(a);a.click();d.body.removeChild(a);
4643
+ setTimeout(function(){URL.revokeObjectURL(url)},1000);
4644
+ }
4645
+ var bH=d.querySelector('[data-loadam-download="html"]');
4646
+ if(bH)bH.addEventListener('click',function(){
4647
+ var html='<!doctype html>\\n'+d.documentElement.outerHTML;
4648
+ dl(new Blob([html],{type:'text/html'}),name+'.html');
4649
+ });
4650
+ var bJ=d.querySelector('[data-loadam-download="json"]');
4651
+ if(bJ)bJ.addEventListener('click',function(){
4652
+ dl(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}),name+'.json');
4653
+ });
4654
+ var bP=d.querySelector('[data-loadam-print]');
4655
+ if(bP)bP.addEventListener('click',function(){window.print()});
4656
+ })();</script>`;
2952
4657
 
2953
4658
  // src/commands/report.ts
2954
- var VERSION = true ? "0.2.3" : "0.0.0";
4659
+ var VERSION = true ? "0.3.0" : "0.0.0";
2955
4660
  function registerReportCommand(program) {
2956
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));
2957
4662
  }
2958
4663
  async function runReport(id, opts) {
2959
4664
  const out = makeOutput(!!opts.json);
2960
- const root = resolve9(opts.root);
4665
+ const root = resolve10(opts.root);
2961
4666
  const meta = await resolveSessionId(root, id);
2962
- const dir = join2(root, "sessions", meta.id);
4667
+ const dir = join4(root, "sessions", meta.id);
2963
4668
  const k6Summaries = {};
2964
4669
  for (const a of meta.artefacts) {
2965
4670
  if (a.startsWith("k6-") && a.endsWith("-summary.json")) {
2966
4671
  const label = a.replace(/^k6-/, "").replace(/-summary\.json$/, "");
2967
4672
  try {
2968
- k6Summaries[label] = JSON.parse(await readFile6(join2(dir, a), "utf8"));
4673
+ k6Summaries[label] = JSON.parse(await readFile8(join4(dir, a), "utf8"));
2969
4674
  } catch {
2970
4675
  }
2971
4676
  }
@@ -2973,17 +4678,40 @@ async function runReport(id, opts) {
2973
4678
  let driftMarkdown;
2974
4679
  if (meta.command === "diff") {
2975
4680
  try {
2976
- driftMarkdown = await readFile6(join2(dir, "drift.md"), "utf8");
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"));
2977
4689
  } catch {
2978
4690
  }
2979
4691
  }
4692
+ let operations;
4693
+ try {
4694
+ const ir = JSON.parse(await readFile8(join4(dir, "ir.json"), "utf8"));
4695
+ if (Array.isArray(ir.operations) && ir.operations.length > 0) {
4696
+ operations = ir.operations.map((o) => ({
4697
+ id: o.id,
4698
+ method: o.method,
4699
+ path: o.path,
4700
+ summary: o.summary,
4701
+ tags: o.tags
4702
+ }));
4703
+ }
4704
+ } catch {
4705
+ }
2980
4706
  const html = renderReport({
2981
4707
  meta,
2982
4708
  k6Summaries: Object.keys(k6Summaries).length > 0 ? k6Summaries : void 0,
2983
4709
  driftMarkdown,
4710
+ contractFailures,
4711
+ operations,
2984
4712
  loadamVersion: VERSION
2985
4713
  });
2986
- const outPath = opts.output ? resolve9(opts.output) : join2(dir, "report.html");
4714
+ const outPath = opts.output ? resolve10(opts.output) : join4(dir, "report.html");
2987
4715
  await writeFile6(outPath, html, "utf8");
2988
4716
  const sizeKb = Math.round(Buffer.byteLength(html, "utf8") / 1024);
2989
4717
  if (!out.json) {
@@ -3006,7 +4734,7 @@ async function openInBrowser(path) {
3006
4734
  const cmd = platform === "darwin" ? "open" : platform === "win32" ? "start" : "xdg-open";
3007
4735
  const args = platform === "win32" ? ["", path] : [path];
3008
4736
  try {
3009
- const child = spawn(cmd, args, {
4737
+ const child = spawn2(cmd, args, {
3010
4738
  detached: true,
3011
4739
  stdio: "ignore",
3012
4740
  shell: platform === "win32"
@@ -3017,20 +4745,20 @@ async function openInBrowser(path) {
3017
4745
  }
3018
4746
 
3019
4747
  // src/commands/show.ts
3020
- import { readFile as readFile7, readdir as readdir2 } from "fs/promises";
3021
- import { join as join4, resolve as resolve10 } from "path";
4748
+ import { readFile as readFile9, readdir as readdir2 } from "fs/promises";
4749
+ import { join as join6, resolve as resolve11 } from "path";
3022
4750
 
3023
4751
  // src/util/k6.ts
3024
- import { spawn as spawn2 } from "child_process";
4752
+ import { spawn as spawn3 } from "child_process";
3025
4753
  import { constants, access } from "fs/promises";
3026
- import { delimiter, join as join3 } from "path";
4754
+ import { delimiter, join as join5 } from "path";
3027
4755
  async function findK6Binary() {
3028
4756
  const path = process.env.PATH ?? "";
3029
4757
  const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
3030
4758
  for (const dir of path.split(delimiter)) {
3031
4759
  if (!dir) continue;
3032
4760
  for (const ext of exts) {
3033
- const candidate = join3(dir, `k6${ext}`);
4761
+ const candidate = join5(dir, `k6${ext}`);
3034
4762
  try {
3035
4763
  await access(candidate, constants.X_OK);
3036
4764
  return candidate;
@@ -3040,6 +4768,13 @@ async function findK6Binary() {
3040
4768
  }
3041
4769
  return null;
3042
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
+ }
3043
4778
  async function runK6(opts) {
3044
4779
  const bin = await findK6Binary();
3045
4780
  if (!bin) {
@@ -3051,10 +4786,11 @@ async function runK6(opts) {
3051
4786
  if (opts.summaryPath) args.push(`--summary-export=${opts.summaryPath}`);
3052
4787
  args.push(...opts.args ?? [], opts.script);
3053
4788
  return await new Promise((resolveExit, reject) => {
3054
- const child = spawn2(bin, args, {
4789
+ const child = spawn3(bin, args, {
3055
4790
  cwd: opts.cwd,
3056
4791
  env: { ...process.env, ...opts.env },
3057
- stdio: "inherit"
4792
+ // fd 2 = our stderr: k6 output stays visible without polluting stdout.
4793
+ stdio: ["inherit", opts.stdout === "stderr" ? 2 : "inherit", "inherit"]
3058
4794
  });
3059
4795
  child.on("error", reject);
3060
4796
  child.on("close", (code) => resolveExit(code ?? 0));
@@ -3062,13 +4798,16 @@ async function runK6(opts) {
3062
4798
  }
3063
4799
  async function digestK6Summary(path) {
3064
4800
  try {
3065
- const { readFile: readFile10 } = await import("fs/promises");
3066
- const text = await readFile10(path, "utf8");
4801
+ const { readFile: readFile12 } = await import("fs/promises");
4802
+ const text = await readFile12(path, "utf8");
3067
4803
  const data = JSON.parse(text);
3068
4804
  const passed = [];
3069
4805
  const failed = [];
3070
4806
  const metrics = {};
3071
4807
  for (const [name, m] of Object.entries(data.metrics ?? {})) {
4808
+ if (name.startsWith("loadam_op_latency") || name.startsWith("loadam_op_status")) {
4809
+ continue;
4810
+ }
3072
4811
  if (m.thresholds) {
3073
4812
  for (const [expr, info] of Object.entries(m.thresholds)) {
3074
4813
  (info.ok ? passed : failed).push(`${name}: ${expr}`);
@@ -3093,9 +4832,9 @@ function registerShowCommand(program) {
3093
4832
  }
3094
4833
  async function runShow(id, opts) {
3095
4834
  const out = makeOutput(!!opts.json);
3096
- const root = resolve10(opts.root);
4835
+ const root = resolve11(opts.root);
3097
4836
  const meta = await resolveSessionId(root, id);
3098
- const dir = join4(root, "sessions", meta.id);
4837
+ const dir = join6(root, "sessions", meta.id);
3099
4838
  if (out.json) {
3100
4839
  out.result({ ...meta });
3101
4840
  return;
@@ -3133,19 +4872,30 @@ async function runShow(id, opts) {
3133
4872
  }
3134
4873
  if (meta.command === "diff") {
3135
4874
  try {
3136
- const drift = await readFile7(join4(dir, "drift.md"), "utf8");
4875
+ const drift = await readFile9(join6(dir, "drift.md"), "utf8");
3137
4876
  out.info("");
3138
4877
  out.info("\u2500\u2500\u2500\u2500 drift.md \u2500\u2500\u2500\u2500");
3139
4878
  process.stdout.write(drift);
3140
4879
  } catch {
3141
4880
  }
3142
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
+ }
3143
4893
  if (meta.command === "test") {
3144
4894
  try {
3145
4895
  const entries = await readdir2(dir);
3146
4896
  const summaryFile = entries.find((e) => /^k6-.*-summary\.json$/.test(e));
3147
4897
  if (summaryFile) {
3148
- const digest = await digestK6Summary(join4(dir, summaryFile));
4898
+ const digest = await digestK6Summary(join6(dir, summaryFile));
3149
4899
  if (digest) {
3150
4900
  out.info("");
3151
4901
  out.info(`\u2500\u2500\u2500\u2500 ${summaryFile} \u2500\u2500\u2500\u2500`);
@@ -3175,8 +4925,8 @@ async function runShow(id, opts) {
3175
4925
  }
3176
4926
 
3177
4927
  // src/commands/test.ts
3178
- import { mkdir as mkdir4, readFile as readFile9, writeFile as writeFile8 } from "fs/promises";
3179
- import { dirname as dirname3, join as join5, resolve as resolve12 } from "path";
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";
3180
4930
 
3181
4931
  // ../data/dist/index.js
3182
4932
  import { faker } from "@faker-js/faker";
@@ -3191,16 +4941,55 @@ function configureJsf() {
3191
4941
  failOnInvalidFormat: false,
3192
4942
  useExamplesValue: true,
3193
4943
  useDefaultValue: true,
3194
- fillProperties: false
4944
+ fillProperties: false,
4945
+ // An empty array is valid JSON Schema but most APIs reject it ("no items provided").
4946
+ minItems: 1
3195
4947
  });
3196
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;
3197
4981
  }
3198
4982
  function fakeFromSchema(schema, opts = {}) {
3199
4983
  configureJsf();
3200
4984
  if (opts.seed !== void 0) {
3201
4985
  faker.seed(opts.seed);
3202
4986
  }
3203
- const expanded = expandRefs(schema, opts.resolveRef ?? (() => void 0), /* @__PURE__ */ new Set());
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);
3204
4993
  const generated = jsf.generate(expanded);
3205
4994
  return overlayRegistry(generated, schema, opts);
3206
4995
  }
@@ -3229,20 +5018,20 @@ function inferKindFromFieldName(field) {
3229
5018
  const root = m[1];
3230
5019
  return root.charAt(0).toUpperCase() + root.slice(1);
3231
5020
  }
3232
- function expandRefs(node, resolve13, seen) {
3233
- if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve13, seen));
5021
+ function expandRefs(node, resolve15, seen) {
5022
+ if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve15, seen));
3234
5023
  if (!node || typeof node !== "object") return node;
3235
5024
  const obj = node;
3236
5025
  if (typeof obj.$ref === "string") {
3237
5026
  if (seen.has(obj.$ref)) return {};
3238
- const target = resolve13(obj.$ref);
5027
+ const target = resolve15(obj.$ref);
3239
5028
  if (target === void 0) return obj;
3240
5029
  const next = new Set(seen);
3241
5030
  next.add(obj.$ref);
3242
- return expandRefs(target, resolve13, next);
5031
+ return expandRefs(target, resolve15, next);
3243
5032
  }
3244
5033
  const out = {};
3245
- for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve13, seen);
5034
+ for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve15, seen);
3246
5035
  return out;
3247
5036
  }
3248
5037
 
@@ -3276,7 +5065,10 @@ function applyProfile(p, headers, query, envVars, notes) {
3276
5065
  const env = p.valueEnv ?? `${p.name.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
3277
5066
  if (p.in === "header") headers[p.name] = `\${${env}}`;
3278
5067
  else if (p.in === "query") query[p.name] = `\${${env}}`;
3279
- else notes.push(`Cookie-based apiKey "${p.name}" requires manual handling.`);
5068
+ else {
5069
+ const prev = headers.Cookie ? `${headers.Cookie}; ` : "";
5070
+ headers.Cookie = `${prev}${p.name}=\${${env}}`;
5071
+ }
3280
5072
  envVars.add(env);
3281
5073
  return;
3282
5074
  }
@@ -3291,10 +5083,11 @@ function applyProfile(p, headers, query, envVars, notes) {
3291
5083
  }
3292
5084
  case "oauth2_cc": {
3293
5085
  notes.push(
3294
- `OAuth2 client-credentials profile "${p.id}" detected \u2014 V1 emits stubs only; populate \`${p.clientIdEnv}\`/\`${p.clientSecretEnv}\` and supply your own token endpoint call.`
5086
+ `OAuth2 client credentials ("${p.id}"): each VU fetches a token from ${p.tokenUrl} using \`${p.clientIdEnv}\`/\`${p.clientSecretEnv}\` and reuses it.`
3295
5087
  );
3296
5088
  envVars.add(p.clientIdEnv);
3297
5089
  envVars.add(p.clientSecretEnv);
5090
+ headers.Authorization = `__OAUTH2__:${p.id}`;
3298
5091
  return;
3299
5092
  }
3300
5093
  case "custom":
@@ -3307,22 +5100,24 @@ function sequenceForSmoke(ir) {
3307
5100
  const out = [];
3308
5101
  const seen = /* @__PURE__ */ new Set();
3309
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
+ };
3310
5110
  for (const kind of orderedKinds) {
3311
- for (const bucket of ["listOps", "createOps", "readOps", "updateOps", "deleteOps"]) {
3312
- for (const opId of kind[bucket]) {
3313
- const op = opsById.get(opId);
3314
- if (op && !seen.has(op.id)) {
3315
- out.push(op);
3316
- seen.add(op.id);
3317
- }
3318
- }
5111
+ for (const bucket of ["listOps", "createOps", "readOps", "updateOps"]) {
5112
+ for (const opId of kind[bucket]) take(opId);
3319
5113
  }
3320
5114
  }
5115
+ const deleteIds = new Set(orderedKinds.flatMap((k) => k.deleteOps));
3321
5116
  for (const op of ir.operations) {
3322
- if (!seen.has(op.id)) {
3323
- out.push(op);
3324
- seen.add(op.id);
3325
- }
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);
3326
5121
  }
3327
5122
  return out;
3328
5123
  }
@@ -3376,7 +5171,7 @@ function buildFixturePool(ir, opts = {}) {
3376
5171
  const ct = pickContentType(op.body);
3377
5172
  const media = ct ? op.body.contentTypes[ct] : void 0;
3378
5173
  if (media) {
3379
- fix.bodies = generateMany(media.schema, size, seed + i, resolveRef2);
5174
+ fix.bodies = generateMany(media.schema, size, seed + i, resolveRef2, true);
3380
5175
  }
3381
5176
  }
3382
5177
  if (op.pathParams.length > 0) {
@@ -3385,7 +5180,11 @@ function buildFixturePool(ir, opts = {}) {
3385
5180
  if (op.queryParams.length > 0) {
3386
5181
  const required = op.queryParams.filter((p) => p.required);
3387
5182
  if (required.length > 0) {
3388
- fix.queryParams = generateParamPool(required, size, seed + i, resolveRef2);
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
+ );
3389
5188
  }
3390
5189
  }
3391
5190
  if (fix.bodies || fix.pathParams || fix.queryParams) {
@@ -3394,12 +5193,14 @@ function buildFixturePool(ir, opts = {}) {
3394
5193
  }
3395
5194
  return { byOperationId, size };
3396
5195
  }
3397
- function generateMany(schema, count, seed, resolveRef2) {
5196
+ function generateMany(schema, count, seed, resolveRef2, forRequest = false) {
3398
5197
  const out = [];
3399
5198
  const target = resolveSchemaRef(schema, resolveRef2);
3400
5199
  for (let i = 0; i < count; i++) {
3401
5200
  try {
3402
- out.push(fakeFromSchema(target, { resolveRef: resolveRef2, seed: seed + i }));
5201
+ out.push(
5202
+ fakeFromSchema(target, { resolveRef: resolveRef2, seed: seed + i, fillOptionals: i === 0, forRequest })
5203
+ );
3403
5204
  } catch {
3404
5205
  out.push(null);
3405
5206
  }
@@ -3434,13 +5235,54 @@ function makeRefResolver(ir) {
3434
5235
  return void 0;
3435
5236
  };
3436
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
+ }
3437
5278
  function emitConfigJs(ctx) {
3438
5279
  const { auth } = ctx;
3439
5280
  const base = ctx.baseUrl;
3440
5281
  const headerEntries = Object.entries(auth.headers);
3441
5282
  const queryEntries = Object.entries(auth.query);
3442
5283
  const needsB64 = headerEntries.some(([, v]) => v.startsWith("__BASIC__:"));
3443
- const importLine = needsB64 ? "import encoding from 'k6/encoding';\n" : "";
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" : "");
3444
5286
  const headersBody = headerEntries.length ? headerEntries.map(([k, v]) => ` ${buildHeaderLine2(k, v)}`).join("\n") : " // no auth headers";
3445
5287
  const queryBody = queryEntries.length ? queryEntries.map(([k, v]) => ` ${JSON.stringify(k)}: ${interpolate2(v)},`).join("\n") : "";
3446
5288
  return `// AUTO-GENERATED by @loadam/test-k6
@@ -3450,7 +5292,7 @@ const BASE_URL = (typeof __ENV !== 'undefined' && __ENV.BASE_URL) || ${JSON.stri
3450
5292
  export function baseUrl() {
3451
5293
  return BASE_URL;
3452
5294
  }
3453
-
5295
+ ${oauth.map(emitOAuthFetcher).join("\n")}
3454
5296
  export function authHeaders() {
3455
5297
  const h = {};
3456
5298
  ${headersBody}
@@ -3473,15 +5315,60 @@ export function buildUrl(path, pathParams, queryParams) {
3473
5315
  }
3474
5316
  const aq = authQuery();
3475
5317
  const merged = Object.assign({}, queryParams || {}, aq);
3476
- const qs = Object.keys(merged)
3477
- .filter((k) => merged[k] !== undefined && merged[k] !== null && merged[k] !== '')
3478
- .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(String(merged[k])))
3479
- .join('&');
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('&');
3480
5330
  return BASE_URL + p + (qs ? '?' + qs : '');
3481
5331
  }
3482
5332
  `;
3483
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
+ }
3484
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
+ }
3485
5372
  if (value.startsWith("__BASIC__:")) {
3486
5373
  const [, userEnv, passEnv] = value.split(":");
3487
5374
  return `if (__ENV.${userEnv} && __ENV.${passEnv}) { h.Authorization = 'Basic ' + encoding.b64encode(__ENV.${userEnv} + ':' + __ENV.${passEnv}); }`;
@@ -3498,14 +5385,26 @@ function emitFlowJs(ctx) {
3498
5385
  for (let i = 0; i < ops.length; i++) {
3499
5386
  const op = ops[i];
3500
5387
  if (!op) continue;
3501
- lines.push(emitOpCall(op, i));
5388
+ lines.push(emitOpCall(ctx.ir, op));
3502
5389
  }
3503
5390
  return `// AUTO-GENERATED by @loadam/test-k6
3504
5391
  import http from 'k6/http';
3505
5392
  import { check } from 'k6';
5393
+ import { Counter, Trend } from 'k6/metrics';
3506
5394
  import { SharedArray } from 'k6/data';
3507
5395
  import { authHeaders, buildUrl } from './config.js';
3508
5396
 
5397
+ const opLatency = new Trend('loadam_op_latency', true);
5398
+ const opStatus = new Counter('loadam_op_status');
5399
+
5400
+ function __statusBucket(s) {
5401
+ if (s < 200) return '1xx';
5402
+ if (s < 300) return '2xx';
5403
+ if (s < 400) return '3xx';
5404
+ if (s < 500) return '4xx';
5405
+ return '5xx';
5406
+ }
5407
+
3509
5408
  const fixtures = new SharedArray('loadam-fixtures', function () {
3510
5409
  return [JSON.parse(open('./fixtures.json'))];
3511
5410
  });
@@ -3518,10 +5417,143 @@ function pickFixture(opId, slot, idx) {
3518
5417
  return undefined;
3519
5418
  }
3520
5419
 
3521
- function pickPathParam(opId, name, state, kind, idx) {
3522
- if (kind && state[kind] && state[kind].length > 0) {
3523
- return state[kind][state[kind].length - 1];
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));
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');
3524
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;
3525
5557
  const pool = fixtures[0][opId];
3526
5558
  if (pool && pool.pathParams && pool.pathParams[name]) {
3527
5559
  const arr = pool.pathParams[name];
@@ -3531,8 +5563,8 @@ function pickPathParam(opId, name, state, kind, idx) {
3531
5563
  }
3532
5564
 
3533
5565
  /**
3534
- * Run one flow iteration. \`state\` accumulates created IDs by ResourceKind
3535
- * so subsequent ops in the same iteration reuse them.
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.
3536
5568
  */
3537
5569
  export function runFlow(iter) {
3538
5570
  const state = {};
@@ -3541,7 +5573,7 @@ ${lines.join("\n")}
3541
5573
  }
3542
5574
  `;
3543
5575
  }
3544
- function emitOpCall(op, _index) {
5576
+ function emitOpCall(ir, op) {
3545
5577
  const headersExpr = "Object.assign({}, authHeaders())";
3546
5578
  const opIdLit = JSON.stringify(op.id);
3547
5579
  const pathParamLines = [];
@@ -3550,46 +5582,66 @@ function emitOpCall(op, _index) {
3550
5582
  const entries = [];
3551
5583
  for (const p of op.pathParams) {
3552
5584
  const ident = safeIdent(p.name);
3553
- const kindLit = p.resourceKind ? JSON.stringify(p.resourceKind) : "undefined";
5585
+ const kindLit2 = p.resourceKind ? JSON.stringify(p.resourceKind) : "undefined";
3554
5586
  pathParamLines.push(
3555
- ` const __pp_${ident} = pickPathParam(${opIdLit}, ${JSON.stringify(p.name)}, state, ${kindLit}, __ITER);`
5587
+ ` const __pp_${ident} = pickPathParam(${opIdLit}, ${JSON.stringify(p.name)}, state, ${kindLit2}, __ITER);`
3556
5588
  );
3557
5589
  entries.push(`${JSON.stringify(p.name)}: __pp_${ident}`);
3558
5590
  }
3559
5591
  pathParamObj = `{ ${entries.join(", ")} }`;
3560
5592
  }
3561
- const requiredQuery = op.queryParams.filter((p) => p.required);
5593
+ const requiredQuery2 = op.queryParams.filter((p) => p.required);
3562
5594
  let queryParamObj = "undefined";
3563
- if (requiredQuery.length > 0) {
3564
- const entries = requiredQuery.map(
5595
+ if (requiredQuery2.length > 0) {
5596
+ const entries = requiredQuery2.map(
3565
5597
  (p) => `${JSON.stringify(p.name)}: (function () { const f = pickFixture(${opIdLit}, 'queryParams', __ITER); return f ? f[${JSON.stringify(p.name)}] : undefined; })()`
3566
5598
  ).join(", ");
3567
5599
  queryParamObj = `{ ${entries} }`;
3568
5600
  }
3569
- const requestLine = emitRequestCall(op, headersExpr, pathParamObj, queryParamObj);
3570
- const captureId = op.resourceAction === "create" && op.resourceKind ? ` if (resp.status >= 200 && resp.status < 300) {
3571
- let body;
3572
- try { body = resp.json(); } catch (_) { body = undefined; }
3573
- if (body && body.id !== undefined) {
3574
- (state[${JSON.stringify(op.resourceKind)}] = state[${JSON.stringify(op.resourceKind)}] || []).push(body.id);
3575
- }
3576
- }` : "";
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);` : "";
3577
5604
  return ` // ${op.method} ${op.path} \u2014 ${op.id}
3578
5605
  {
3579
5606
  ${pathParamLines.join("\n")}
3580
5607
  const resp = ${requestLine};
3581
5608
  check(resp, { ${JSON.stringify(`${op.id} 2xx-3xx`)}: (r) => r.status >= 200 && r.status < 400 });
5609
+ opLatency.add(resp.timings.duration, { name: ${opIdLit} });
5610
+ opStatus.add(1, { name: ${opIdLit}, bucket: __statusBucket(resp.status) });
3582
5611
  ${captureId}
3583
5612
  }
3584
5613
  `;
3585
5614
  }
3586
- function emitRequestCall(op, headersExpr, pathParamObj, queryParamObj) {
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) {
3587
5640
  const url = `buildUrl(${JSON.stringify(op.path)}, ${pathParamObj}, ${queryParamObj})`;
3588
5641
  const method = op.method.toLowerCase();
3589
5642
  const hasBody = !!op.body;
3590
5643
  const opIdLit = JSON.stringify(op.id);
3591
- const bodyExpr = hasBody ? `JSON.stringify(pickFixture(${opIdLit}, 'bodies', __ITER))` : "null";
3592
- const headersWithCT = hasBody ? `Object.assign(${headersExpr}, { 'Content-Type': 'application/json' })` : headersExpr;
5644
+ const { bodyExpr, headersWithCT } = hasBody ? encodeBody(ir, op, headersExpr) : { bodyExpr: "null", headersWithCT: headersExpr };
3593
5645
  if (method === "get" || method === "head" || method === "options") {
3594
5646
  return `http.${method}(${url}, { headers: ${headersExpr}, tags: { name: ${opIdLit} } })`;
3595
5647
  }
@@ -3601,7 +5653,7 @@ function emitRequestCall(op, headersExpr, pathParamObj, queryParamObj) {
3601
5653
  function safeIdent(s) {
3602
5654
  return s.replace(/[^A-Za-z0-9_]/g, "_");
3603
5655
  }
3604
- function emitSmokeJs() {
5656
+ function emitSmokeJs(ctx) {
3605
5657
  return `// AUTO-GENERATED by @loadam/test-k6 \u2014 smoke test
3606
5658
  import { runFlow } from './flow.js';
3607
5659
 
@@ -3612,7 +5664,7 @@ export const options = {
3612
5664
  checks: ['rate>=0.95'],
3613
5665
  http_req_failed: ['rate<0.05'],
3614
5666
  http_req_duration: ['p(95)<2000'],
3615
- },
5667
+ ${emitOpThresholds(ctx)} },
3616
5668
  };
3617
5669
 
3618
5670
  export default function () {
@@ -3620,7 +5672,7 @@ export default function () {
3620
5672
  }
3621
5673
  `;
3622
5674
  }
3623
- function emitLoadJs() {
5675
+ function emitLoadJs(ctx) {
3624
5676
  return `// AUTO-GENERATED by @loadam/test-k6 \u2014 load test
3625
5677
  import { runFlow } from './flow.js';
3626
5678
 
@@ -3634,7 +5686,7 @@ export const options = {
3634
5686
  checks: ['rate>=0.95'],
3635
5687
  http_req_failed: ['rate<0.05'],
3636
5688
  http_req_duration: ['p(95)<1000'],
3637
- },
5689
+ ${emitOpThresholds(ctx)} },
3638
5690
  };
3639
5691
 
3640
5692
  export default function () {
@@ -3642,6 +5694,18 @@ export default function () {
3642
5694
  }
3643
5695
  `;
3644
5696
  }
5697
+ function emitOpThresholds(ctx) {
5698
+ const buckets = ["1xx", "2xx", "3xx", "4xx", "5xx"];
5699
+ const lines = [];
5700
+ for (const op of ctx.sequencedOps) {
5701
+ lines.push(` 'loadam_op_latency{name:${op.id}}': ['p(95)<999999'],`);
5702
+ for (const b of buckets) {
5703
+ lines.push(` 'loadam_op_status{name:${op.id},bucket:${b}}': ['count>=0'],`);
5704
+ }
5705
+ }
5706
+ return lines.length === 0 ? "" : `${lines.join("\n")}
5707
+ `;
5708
+ }
3645
5709
  function emitFixturesJson(pool) {
3646
5710
  return `${JSON.stringify(pool, null, 2)}
3647
5711
  `;
@@ -3683,7 +5747,7 @@ ${ctx.auth.notes.map((n) => `- ${n}`).join("\n")}
3683
5747
  ` : "";
3684
5748
  return `# ${ctx.ir.meta.title} \u2014 k6 test rig
3685
5749
 
3686
- Generated by [loadam](https://github.com/loadam) from your API spec.
5750
+ Generated by [loadam](https://github.com/DesmondSanctity/loadam) from your API spec.
3687
5751
 
3688
5752
  ## Run
3689
5753
 
@@ -3708,8 +5772,8 @@ k6 run load.js
3708
5772
  ${notes}
3709
5773
  ## Regenerating
3710
5774
 
3711
- Re-run \`loadam test\` to refresh. Edits to generated files will be overwritten \u2014
3712
- preserve-user-block markers land in V1.1.
5775
+ Re-run \`loadam test\` to refresh. Regenerating overwrites these files, so commit
5776
+ your edits first and review the diff afterwards.
3713
5777
  `;
3714
5778
  }
3715
5779
  function slugify3(s) {
@@ -3727,8 +5791,8 @@ function compileK6(ir, opts = {}) {
3727
5791
  const files = {
3728
5792
  "config.js": emitConfigJs(ctx),
3729
5793
  "flow.js": emitFlowJs(ctx),
3730
- "smoke.js": emitSmokeJs(),
3731
- "load.js": emitLoadJs(),
5794
+ "smoke.js": emitSmokeJs(ctx),
5795
+ "load.js": emitLoadJs(ctx),
3732
5796
  "fixtures.json": emitFixturesJson(fixtures.byOperationId),
3733
5797
  "package.json": emitPackageJson2(ctx),
3734
5798
  ".env.example": emitEnvExample3(ctx),
@@ -3738,8 +5802,8 @@ function compileK6(ir, opts = {}) {
3738
5802
  }
3739
5803
 
3740
5804
  // src/util/interactive.ts
3741
- import { chmod, readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
3742
- import { resolve as resolve11 } from "path";
5805
+ import { chmod, readFile as readFile10, writeFile as writeFile7 } from "fs/promises";
5806
+ import { resolve as resolve13 } from "path";
3743
5807
  import { confirm, password, select } from "@inquirer/prompts";
3744
5808
  function isInteractive(noInteractiveFlag) {
3745
5809
  if (noInteractiveFlag) return false;
@@ -3776,7 +5840,7 @@ async function confirmContinue(message) {
3776
5840
  return await confirm({ message, default: true });
3777
5841
  }
3778
5842
  async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
3779
- const path = resolve11(dir, ".env");
5843
+ const path = resolve13(dir, ".env");
3780
5844
  const existing = await readEnvFile(path);
3781
5845
  const written = [];
3782
5846
  const preserved = [];
@@ -3803,7 +5867,7 @@ async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
3803
5867
  }
3804
5868
  async function readEnvFile(path) {
3805
5869
  try {
3806
- const text = await readFile8(path, "utf8");
5870
+ const text = await readFile10(path, "utf8");
3807
5871
  const out = {};
3808
5872
  for (const raw of text.split(/\r?\n/)) {
3809
5873
  const line = raw.trim();
@@ -3829,29 +5893,34 @@ function registerTestCommand(program) {
3829
5893
  ).option("--fixture-size <n>", "number of fixtures per slot", "10").option("--seed <n>", "deterministic seed for fixture generation", "1").option(
3830
5894
  "--mode <mode>",
3831
5895
  "run after generating: smoke | load | both | skip (default: prompt if interactive, skip otherwise)"
3832
- ).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));
3833
5897
  }
3834
5898
  async function runTest(spec, opts) {
3835
5899
  const out = makeOutput(!!opts.json);
3836
- const specPath = resolve12(spec);
5900
+ const specPath = resolve14(spec);
3837
5901
  out.start(`Parsing OpenAPI spec: ${specPath}`);
3838
- const specSource = await readFile9(specPath, "utf8");
5902
+ const specSource = await readFile11(specPath, "utf8");
3839
5903
  const ir = await fromOpenApiFile(specPath);
3840
5904
  inferResourceGraph(ir);
5905
+ await applyUserConfig(ir, specPath, opts.config);
3841
5906
  parseIR(ir);
5907
+ out.success(`Parsed ${ir.operations.length} operation${ir.operations.length === 1 ? "" : "s"}`);
3842
5908
  const fixtureSize = Number.parseInt(opts.fixtureSize ?? "10", 10);
3843
5909
  const seed = Number.parseInt(opts.seed ?? "1", 10);
3844
5910
  const target = resolveTarget(opts.target);
5911
+ out.start(
5912
+ `Generating k6 scripts for ${ir.operations.length} operation${ir.operations.length === 1 ? "" : "s"}\u2026`
5913
+ );
3845
5914
  const result = compileK6(ir, {
3846
5915
  baseUrl: target,
3847
5916
  fixtureSize: Number.isFinite(fixtureSize) ? fixtureSize : 10,
3848
5917
  seed: Number.isFinite(seed) ? seed : 1
3849
5918
  });
3850
- const outDir = resolve12(opts.output);
5919
+ const outDir = resolve14(opts.output);
3851
5920
  await mkdir4(outDir, { recursive: true });
3852
5921
  for (const [rel, contents] of Object.entries(result.files)) {
3853
- const full = resolve12(outDir, rel);
3854
- await mkdir4(dirname3(full), { recursive: true });
5922
+ const full = resolve14(outDir, rel);
5923
+ await mkdir4(dirname4(full), { recursive: true });
3855
5924
  await writeFile8(full, contents, "utf8");
3856
5925
  }
3857
5926
  const fileCount = Object.keys(result.files).length;
@@ -3860,7 +5929,8 @@ async function runTest(spec, opts) {
3860
5929
  out.info(
3861
5930
  ` ${ir.operations.length} operations \xB7 ${fixtureCount} ops with fixtures \xB7 ${result.fixtures.size} samples each`
3862
5931
  );
3863
- const interactive = !opts.json && isInteractive(!!opts.noInteractive);
5932
+ const noInteractiveFlag = opts.interactive === false;
5933
+ const interactive = !opts.json && isInteractive(noInteractiveFlag);
3864
5934
  const requestedMode = parseModeFlag(opts.mode);
3865
5935
  let envAction = "not-needed";
3866
5936
  let runResult = null;
@@ -3906,14 +5976,14 @@ async function runTest(spec, opts) {
3906
5976
  target: target ?? null,
3907
5977
  fixtureSize,
3908
5978
  seed,
3909
- noInteractive: !!opts.noInteractive,
5979
+ noInteractive: noInteractiveFlag,
3910
5980
  json: !!opts.json
3911
5981
  },
3912
5982
  slug: `${mode}-${ir.meta.title ?? "run"}`
3913
5983
  });
3914
5984
  if (!out.json) out.info(` Session: ${session.id}`);
3915
5985
  if (mode !== "skip") {
3916
- runResult = await maybeRunWithSession({ mode, cwd: outDir, out, session });
5986
+ runResult = await maybeRunWithSession({ mode, cwd: outDir, out, session, interactive });
3917
5987
  } else if (!interactive && !out.json) {
3918
5988
  out.step("");
3919
5989
  out.step("Next steps:");
@@ -3959,10 +6029,18 @@ function parseModeFlag(raw) {
3959
6029
  return raw;
3960
6030
  }
3961
6031
  function getSessionRoot(outDir) {
3962
- return resolve12(outDir, "..");
6032
+ return resolve14(outDir, "..");
6033
+ }
6034
+ async function fileExists(p) {
6035
+ try {
6036
+ await stat2(p);
6037
+ return true;
6038
+ } catch {
6039
+ return false;
6040
+ }
3963
6041
  }
3964
6042
  async function maybeRunWithSession(input) {
3965
- const { mode, cwd, out, session } = input;
6043
+ const { mode, cwd, out, session, interactive } = input;
3966
6044
  if (mode === "skip") return { mode };
3967
6045
  const bin = await findK6Binary();
3968
6046
  if (!bin) {
@@ -3980,13 +6058,16 @@ async function maybeRunWithSession(input) {
3980
6058
  const allPassed = [];
3981
6059
  const allFailed = [];
3982
6060
  const summary = {};
6061
+ const env = envForRun(await readEnvFile(join7(cwd, ".env")));
6062
+ const stdout = out.json ? "stderr" : "inherit";
3983
6063
  if (mode === "smoke" || mode === "both") {
3984
6064
  if (!out.json) {
3985
6065
  out.step("");
3986
6066
  out.step("Running k6 smoke test...");
3987
6067
  }
3988
- const summaryPath = join5(session.dir, "k6-smoke-summary.json");
3989
- 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 });
6070
+ if (await fileExists(summaryPath)) session.registerArtefact("k6-smoke-summary.json");
3990
6071
  const digest = await digestK6Summary(summaryPath);
3991
6072
  if (digest) {
3992
6073
  allPassed.push(...digest.passed.map((t) => `smoke: ${t}`));
@@ -4000,7 +6081,7 @@ async function maybeRunWithSession(input) {
4000
6081
  }
4001
6082
  }
4002
6083
  if (mode === "load" || mode === "both") {
4003
- if (mode === "both") {
6084
+ if (mode === "both" && interactive) {
4004
6085
  const cont = await confirmContinue("Smoke complete. Continue with load test?");
4005
6086
  if (!cont) {
4006
6087
  await session.finalize({
@@ -4015,8 +6096,9 @@ async function maybeRunWithSession(input) {
4015
6096
  out.step("");
4016
6097
  out.step("Running k6 load test...");
4017
6098
  }
4018
- const summaryPath = join5(session.dir, "k6-load-summary.json");
4019
- 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 });
6101
+ if (await fileExists(summaryPath)) session.registerArtefact("k6-load-summary.json");
4020
6102
  const digest = await digestK6Summary(summaryPath);
4021
6103
  if (digest) {
4022
6104
  allPassed.push(...digest.passed.map((t) => `load: ${t}`));
@@ -4058,8 +6140,8 @@ async function fetchLatestVersion(timeoutMs = 3e3) {
4058
6140
  }
4059
6141
  }
4060
6142
  function compareVersions(a, b) {
4061
- const parse = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10) || 0);
4062
- const [aa, bb] = [parse(a), parse(b)];
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)];
4063
6145
  for (let i = 0; i < 3; i++) {
4064
6146
  const d = (aa[i] ?? 0) - (bb[i] ?? 0);
4065
6147
  if (d !== 0) return d > 0 ? 1 : -1;
@@ -4120,16 +6202,16 @@ function banner() {
4120
6202
  ${TAGLINE}
4121
6203
  `;
4122
6204
  }
4123
- const cyan = "\x1B[36m";
6205
+ const amber = "\x1B[38;5;208m";
4124
6206
  const dim = "\x1B[2m";
4125
6207
  const reset = "\x1B[0m";
4126
- return `${cyan}${ART}${reset}
6208
+ return `${amber}${ART}${reset}
4127
6209
  ${dim}${TAGLINE}${reset}
4128
6210
  `;
4129
6211
  }
4130
6212
 
4131
6213
  // src/program.ts
4132
- var VERSION2 = true ? "0.2.3" : "0.0.0";
6214
+ var VERSION2 = true ? "0.3.0" : "0.0.0";
4133
6215
  function buildProgram() {
4134
6216
  const program = new Command();
4135
6217
  program.name("loadam").description(