kinde-testkit 0.3.0 → 0.4.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/cli.js CHANGED
@@ -271,6 +271,9 @@ var KindeTestkit = class _KindeTestkit {
271
271
  if (scenario.kind === "unauthenticated") return null;
272
272
  return scenarioPrincipal(scenario, this.issuer);
273
273
  }
274
+ async signPayload(payload, invalid2) {
275
+ return this.sign(payload, invalid2);
276
+ }
274
277
  async sign(payload, invalid2) {
275
278
  if (invalid2 === "unsigned") {
276
279
  const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
@@ -365,6 +368,19 @@ function resolveSeed(input) {
365
368
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
366
369
  const rawMemberships = listOf(input.memberships, "memberships", problems);
367
370
  const rawApplications = listOf(input.applications, "applications", problems);
371
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
372
+ const webhooks = [];
373
+ rawWebhooks.forEach((raw, index) => {
374
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
375
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
376
+ return;
377
+ }
378
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
379
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
380
+ return;
381
+ }
382
+ webhooks.push({ url: raw.url, events: raw.events });
383
+ });
368
384
  const users = [];
369
385
  rawUsers.forEach((raw, index) => {
370
386
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -456,7 +472,7 @@ function resolveSeed(input) {
456
472
  if (problems.length > 0) {
457
473
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
458
474
  }
459
- return { users, organizations, memberships, applications };
475
+ return { users, organizations, memberships, applications, webhooks };
460
476
  }
461
477
  function findUser(users, ref) {
462
478
  const needle = ref.toLowerCase();
@@ -593,12 +609,14 @@ var OAuthError = class extends Error {
593
609
  error;
594
610
  };
595
611
  var AuthorizationServer = class {
596
- constructor(testkit, seed) {
612
+ constructor(testkit, seed, emit = () => void 0) {
597
613
  this.testkit = testkit;
598
614
  this.seed = seed;
615
+ this.emit = emit;
599
616
  }
600
617
  testkit;
601
618
  seed;
619
+ emit;
602
620
  codes = /* @__PURE__ */ new Map();
603
621
  refreshTokens = /* @__PURE__ */ new Map();
604
622
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -716,6 +734,7 @@ var AuthorizationServer = class {
716
734
  codeChallengeMethod: request2.codeChallengeMethod,
717
735
  expiresAt: Date.now() + CODE_LIFETIME_MS
718
736
  });
737
+ this.emit("user.authenticated", user);
719
738
  const target = new URL(request2.redirectUri);
720
739
  target.searchParams.set("code", code);
721
740
  if (request2.state !== null) target.searchParams.set("state", request2.state);
@@ -881,8 +900,11 @@ var AuthorizationServer = class {
881
900
  if (seeded) return seeded;
882
901
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
883
902
  const user = createKindeUser({ email: ref.toLowerCase() });
884
- this.signedUpUsers.set(user.id, user);
885
- return user;
903
+ if (!this.signedUpUsers.has(user.id)) {
904
+ this.signedUpUsers.set(user.id, user);
905
+ this.emit("user.created", user);
906
+ }
907
+ return this.signedUpUsers.get(user.id);
886
908
  }
887
909
  organization(code) {
888
910
  return this.seed.organizations.find((org) => org.code === code) ?? null;
@@ -1071,6 +1093,271 @@ function validate(rule) {
1071
1093
  return problems;
1072
1094
  }
1073
1095
 
1096
+ // src/webhooks.ts
1097
+ import { randomBytes as randomBytes2 } from "crypto";
1098
+ var WEBHOOK_EVENT_TYPES = [
1099
+ "user.created",
1100
+ "user.updated",
1101
+ "user.deleted",
1102
+ "user.authenticated",
1103
+ "user.authentication_failed",
1104
+ "organization.created",
1105
+ "organization.updated",
1106
+ "organization.deleted",
1107
+ "role.created",
1108
+ "role.updated",
1109
+ "role.deleted",
1110
+ "permission.created",
1111
+ "permission.updated",
1112
+ "permission.deleted",
1113
+ "subscriber.created",
1114
+ "access_request.created"
1115
+ ];
1116
+ var BILLING_EVENT_TYPES = [
1117
+ "customer.agreement_cancelled",
1118
+ "customer.agreement_created",
1119
+ "customer.invoice_overdue",
1120
+ "customer.meter_usage_updated",
1121
+ "customer.payment_failed",
1122
+ "customer.payment_succeeded",
1123
+ "customer.plan_assigned",
1124
+ "customer.plan_changed"
1125
+ ];
1126
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
1127
+ var DEFAULT_TIMEOUT_MS = 5e3;
1128
+ var MAX_DUPLICATES = 10;
1129
+ var WebhookDispatcher = class {
1130
+ constructor(testkit, seed, endpoints = [], options = {}) {
1131
+ this.testkit = testkit;
1132
+ this.seed = seed;
1133
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
1134
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1135
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
1136
+ this.seededEndpoints = [...this.endpoints];
1137
+ }
1138
+ testkit;
1139
+ seed;
1140
+ endpoints = [];
1141
+ seededEndpoints = [];
1142
+ log = [];
1143
+ nextEndpoint = 1;
1144
+ retryDelaysMs;
1145
+ timeoutMs;
1146
+ addEndpoint(input) {
1147
+ if (!isHttpUrl2(input.url)) {
1148
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
1149
+ }
1150
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
1151
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
1152
+ }
1153
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
1154
+ this.endpoints.push(endpoint);
1155
+ return { ...endpoint };
1156
+ }
1157
+ removeEndpoint(id) {
1158
+ const before = this.endpoints.length;
1159
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
1160
+ return this.endpoints.length < before;
1161
+ }
1162
+ listEndpoints() {
1163
+ return this.endpoints.map((e) => ({ ...e }));
1164
+ }
1165
+ deliveries() {
1166
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
1167
+ }
1168
+ reset() {
1169
+ this.log = [];
1170
+ this.endpoints = [...this.seededEndpoints];
1171
+ }
1172
+ buildEvent(options) {
1173
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
1174
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
1175
+ }
1176
+ const now = /* @__PURE__ */ new Date();
1177
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
1178
+ const event = {
1179
+ data: options.data ?? this.buildData(options),
1180
+ event_id: `event_${randomBytes2(16).toString("hex")}`,
1181
+ event_timestamp: timestamp,
1182
+ source: options.source ?? "admin",
1183
+ timestamp,
1184
+ type: options.type
1185
+ };
1186
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
1187
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
1188
+ }
1189
+ return event;
1190
+ }
1191
+ async send(options) {
1192
+ const event = this.buildEvent(options);
1193
+ const copies = options.duplicate ?? 1;
1194
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
1195
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
1196
+ }
1197
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
1198
+ if (options.to && !isHttpUrl2(options.to)) {
1199
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
1200
+ }
1201
+ if (targets.length === 0) {
1202
+ throw new TestkitError(
1203
+ "INVALID_REQUEST",
1204
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
1205
+ );
1206
+ }
1207
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
1208
+ const signed = await this.testkit.signPayload(
1209
+ event,
1210
+ options.invalid === "stale" ? void 0 : options.invalid
1211
+ );
1212
+ const jobs = targets.flatMap((target) => {
1213
+ const webhookId = `wh_${randomBytes2(12).toString("hex")}`;
1214
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
1215
+ });
1216
+ return Promise.all(jobs);
1217
+ }
1218
+ async deliver(url, webhookId, body, event, copy) {
1219
+ const delivery = {
1220
+ webhookId,
1221
+ eventId: String(event.event_id),
1222
+ type: String(event.type),
1223
+ url,
1224
+ copy,
1225
+ delivered: false,
1226
+ attempts: [],
1227
+ payload: event
1228
+ };
1229
+ this.log.push(delivery);
1230
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
1231
+ if (delay > 0) await sleep(delay);
1232
+ const started = Date.now();
1233
+ try {
1234
+ const response = await fetch(url, {
1235
+ method: "POST",
1236
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
1237
+ body,
1238
+ signal: AbortSignal.timeout(this.timeoutMs)
1239
+ });
1240
+ await response.arrayBuffer().catch(() => void 0);
1241
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
1242
+ if (response.status === 200) {
1243
+ delivery.delivered = true;
1244
+ break;
1245
+ }
1246
+ } catch (error) {
1247
+ const name = error.name;
1248
+ delivery.attempts.push({
1249
+ attempt: index + 1,
1250
+ status: null,
1251
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
1252
+ durationMs: Date.now() - started
1253
+ });
1254
+ }
1255
+ }
1256
+ return { ...delivery, attempts: [...delivery.attempts] };
1257
+ }
1258
+ buildData(options) {
1259
+ const [subject] = options.type.split(".");
1260
+ switch (subject) {
1261
+ case "user":
1262
+ return { user: this.userData(options) };
1263
+ case "organization":
1264
+ return { organization: this.organizationData(options) };
1265
+ case "role":
1266
+ return { role: this.namedData(options, "role") };
1267
+ case "permission":
1268
+ return { permission: this.namedData(options, "permission") };
1269
+ case "subscriber": {
1270
+ const user = this.requireUser(options);
1271
+ return {
1272
+ subscriber: {
1273
+ email: user.email,
1274
+ first_name: user.givenName,
1275
+ id: stableId("sub", user.id),
1276
+ last_name: user.familyName,
1277
+ user_id: user.id
1278
+ }
1279
+ };
1280
+ }
1281
+ case "access_request": {
1282
+ const user = this.requireUser(options);
1283
+ return {
1284
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
1285
+ };
1286
+ }
1287
+ default:
1288
+ throw new TestkitError(
1289
+ "INVALID_REQUEST",
1290
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
1291
+ );
1292
+ }
1293
+ }
1294
+ emitForUser(type, user) {
1295
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
1296
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
1297
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
1298
+ }
1299
+ userData(options) {
1300
+ const user = this.requireUser(options);
1301
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
1302
+ return this.userPayload(user);
1303
+ }
1304
+ userPayload(user) {
1305
+ return {
1306
+ email: user.email,
1307
+ first_name: user.givenName,
1308
+ id: user.id,
1309
+ is_password_reset_requested: false,
1310
+ is_suspended: false,
1311
+ last_name: user.familyName,
1312
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
1313
+ code: m.organizationCode,
1314
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
1315
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
1316
+ })),
1317
+ phone: null,
1318
+ username: typeof user.claims.username === "string" ? user.claims.username : null
1319
+ };
1320
+ }
1321
+ organizationData(options) {
1322
+ if (!options.organization) {
1323
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
1324
+ }
1325
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
1326
+ if (options.type === "organization.deleted") return { code: options.organization };
1327
+ const name = org?.name ?? titleCase(options.organization);
1328
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
1329
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
1330
+ return data;
1331
+ }
1332
+ namedData(options, kind) {
1333
+ const key = kind === "role" ? options.role : options.permission;
1334
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
1335
+ const id = stableId(kind === "role" ? "role" : "perm", key);
1336
+ if (options.type.endsWith(".deleted")) return { id };
1337
+ const data = { description: "", id, key, name: titleCase(key) };
1338
+ if (kind === "role") data.is_default_role = false;
1339
+ return data;
1340
+ }
1341
+ requireUser(options) {
1342
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
1343
+ const user = findUser(this.seed.users, options.user);
1344
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
1345
+ return user;
1346
+ }
1347
+ };
1348
+ function isHttpUrl2(value) {
1349
+ if (typeof value !== "string") return false;
1350
+ try {
1351
+ const { protocol } = new URL(value);
1352
+ return protocol === "http:" || protocol === "https:";
1353
+ } catch {
1354
+ return false;
1355
+ }
1356
+ }
1357
+ function sleep(ms) {
1358
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1359
+ }
1360
+
1074
1361
  // src/server.ts
1075
1362
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
1076
1363
  var MAX_BODY_BYTES = 64 * 1024;
@@ -1102,12 +1389,14 @@ async function startKindeTestkit(options = {}) {
1102
1389
  audience: options.audience ?? options.seed?.audience,
1103
1390
  clientId: options.clientId ?? options.seed?.clientId
1104
1391
  });
1105
- const auth = new AuthorizationServer(testkit, seed);
1392
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
1393
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
1106
1394
  const reset2 = () => {
1107
1395
  auth.reset();
1108
1396
  failures.clear();
1397
+ webhooks.reset();
1109
1398
  };
1110
- ready({ testkit, auth, seed, failures, reset: reset2 });
1399
+ ready({ testkit, auth, seed, failures, webhooks, reset: reset2 });
1111
1400
  return {
1112
1401
  url,
1113
1402
  issuer: testkit.issuer,
@@ -1116,6 +1405,7 @@ async function startKindeTestkit(options = {}) {
1116
1405
  testkit,
1117
1406
  seed,
1118
1407
  failures,
1408
+ webhooks,
1119
1409
  reset: reset2,
1120
1410
  close: () => new Promise((resolve2, reject) => {
1121
1411
  server.closeAllConnections();
@@ -1124,7 +1414,7 @@ async function startKindeTestkit(options = {}) {
1124
1414
  };
1125
1415
  }
1126
1416
  async function handle(req, res, context) {
1127
- const { testkit, auth, seed, failures } = context;
1417
+ const { testkit, auth, seed, failures, webhooks } = context;
1128
1418
  const url = new URL(req.url ?? "/", "http://localhost");
1129
1419
  const { pathname } = url;
1130
1420
  const method = req.method ?? "GET";
@@ -1169,6 +1459,21 @@ async function handle(req, res, context) {
1169
1459
  const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1170
1460
  return sendJson2(res, removed ? 200 : 404, { ok: removed });
1171
1461
  }
1462
+ if (method === "POST" && pathname === "/testkit/webhooks") {
1463
+ return sendJson2(res, 200, await webhooks.send(await readJson(req)));
1464
+ }
1465
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
1466
+ return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
1467
+ }
1468
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
1469
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
1470
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
1471
+ return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
1472
+ }
1473
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
1474
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
1475
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1476
+ }
1172
1477
  if (method === "POST" && pathname === "/testkit/reset") {
1173
1478
  context.reset();
1174
1479
  return sendJson2(res, 200, { ok: true });
@@ -1506,6 +1811,7 @@ Usage
1506
1811
  kinde-testkit doctor [options] Check your app's Kinde settings against the issuer
1507
1812
  kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
1508
1813
  kinde-testkit reset Clear sign-in sessions and failure rules
1814
+ kinde-testkit webhook <type> [options] Send a signed webhook event
1509
1815
 
1510
1816
  start
1511
1817
  --port <n> Port to listen on (default 4400)
@@ -1515,6 +1821,7 @@ start
1515
1821
  --client-id <id> Value for azp
1516
1822
  --seed <file> Seed file (default ./kinde-testkit.json when it exists)
1517
1823
  --allow-public Allow binding to a non-loopback interface
1824
+ --webhook <url> Send webhooks to this URL (repeatable)
1518
1825
 
1519
1826
  token
1520
1827
  --url <url> Running issuer (default ${DEFAULT_URL})
@@ -1550,6 +1857,18 @@ fail <path> An exact path such as /oauth2/token, or a prefix such as
1550
1857
  --method <verb> Only match this method
1551
1858
  --list Show active rules
1552
1859
  --clear Remove all rules
1860
+
1861
+ webhook <type> Any event type, such as user.created or customer.plan_assigned
1862
+ --user <id|email> Seeded user, for user.*, subscriber.* and access_request.*
1863
+ --org <code> Organization, for organization.*
1864
+ --role <key> Role, for role.*
1865
+ --permission <key> Permission, for permission.*
1866
+ --data <json> The event's data object. Needed for billing events
1867
+ --to <url> Send to this URL instead of the configured endpoints
1868
+ --duplicate <n> Send n copies with the same webhook-id
1869
+ --invalid <kind> bad-signature, unknown-key, unsigned or stale
1870
+ --types List the event types with built-in payloads
1871
+ --deliveries Show the delivery log
1553
1872
  `;
1554
1873
  async function main(argv) {
1555
1874
  const [command, ...rest] = argv;
@@ -1571,6 +1890,9 @@ async function main(argv) {
1571
1890
  return fail(rest);
1572
1891
  case "reset":
1573
1892
  return reset(rest);
1893
+ case "webhook":
1894
+ case "webhooks":
1895
+ return webhook(rest);
1574
1896
  case void 0:
1575
1897
  case "help":
1576
1898
  case "--help":
@@ -1592,11 +1914,13 @@ async function start(args) {
1592
1914
  "client-id": { type: "string" },
1593
1915
  seed: { type: "string" },
1594
1916
  "allow-public": { type: "boolean" },
1917
+ webhook: { type: "string", multiple: true },
1595
1918
  json: { type: "boolean" }
1596
1919
  }
1597
1920
  });
1598
1921
  const seedPath = values.seed ?? (existsSync(DEFAULT_SEED_FILE) ? DEFAULT_SEED_FILE : void 0);
1599
- const seed = seedPath ? readSeed(seedPath) : void 0;
1922
+ const seed = seedPath ? readSeed(seedPath) : values.webhook ? {} : void 0;
1923
+ if (seed && values.webhook) seed.webhooks = [...seed.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
1600
1924
  const running = await startKindeTestkit({
1601
1925
  port: values.port ? Number(values.port) : void 0,
1602
1926
  host: values.host,
@@ -1635,6 +1959,7 @@ async function start(args) {
1635
1959
  `Seed: ${seedPath ? resolve(seedPath) : "none"}`,
1636
1960
  `Users: ${running.seed.users.length}`,
1637
1961
  `Organizations: ${running.seed.organizations.length}`,
1962
+ `Webhooks: ${running.webhooks.listEndpoints().map((e) => e.url).join(", ") || "none"}`,
1638
1963
  "",
1639
1964
  "Test tokens only. Press Ctrl+C to stop.",
1640
1965
  ""
@@ -1831,6 +2156,90 @@ async function readStdin() {
1831
2156
  for await (const chunk of process.stdin) chunks.push(chunk);
1832
2157
  return Buffer.concat(chunks).toString("utf8");
1833
2158
  }
2159
+ async function webhook(args) {
2160
+ const { values, positionals } = parseArgs({
2161
+ args,
2162
+ allowPositionals: true,
2163
+ options: {
2164
+ url: { type: "string" },
2165
+ user: { type: "string" },
2166
+ org: { type: "string" },
2167
+ role: { type: "string" },
2168
+ permission: { type: "string" },
2169
+ data: { type: "string" },
2170
+ to: { type: "string" },
2171
+ duplicate: { type: "string" },
2172
+ invalid: { type: "string" },
2173
+ types: { type: "boolean" },
2174
+ deliveries: { type: "boolean" },
2175
+ json: { type: "boolean" }
2176
+ }
2177
+ });
2178
+ const base = values.url ?? DEFAULT_URL;
2179
+ if (values.types) {
2180
+ const types = await request(base, "/testkit/webhooks/types");
2181
+ process.stdout.write(
2182
+ values.json ? `${JSON.stringify(types)}
2183
+ ` : `Built-in payloads:
2184
+ ${types.built_in.map((t) => ` ${t}`).join("\n")}
2185
+
2186
+ Billing events (pass --data):
2187
+ ${types.billing.map((t) => ` ${t}`).join("\n")}
2188
+ `
2189
+ );
2190
+ return;
2191
+ }
2192
+ if (values.deliveries || positionals.length === 0) {
2193
+ const log = await request(base, "/testkit/webhooks/deliveries");
2194
+ if (values.json) {
2195
+ process.stdout.write(`${JSON.stringify(log)}
2196
+ `);
2197
+ } else if (log.length === 0) {
2198
+ process.stdout.write("No webhooks sent yet.\n");
2199
+ } else {
2200
+ for (const delivery of log) process.stdout.write(`${describeDelivery(delivery)}
2201
+ `);
2202
+ }
2203
+ return;
2204
+ }
2205
+ let data;
2206
+ if (values.data !== void 0) {
2207
+ try {
2208
+ data = JSON.parse(values.data);
2209
+ } catch {
2210
+ throw new TestkitError("INVALID_REQUEST", `--data must be a JSON object, for example '{"customer_id":"c_1"}'.`);
2211
+ }
2212
+ }
2213
+ const deliveries = await request(base, "/testkit/webhooks", {
2214
+ method: "POST",
2215
+ headers: { "content-type": "application/json" },
2216
+ body: JSON.stringify({
2217
+ type: positionals[0],
2218
+ user: values.user,
2219
+ organization: values.org,
2220
+ role: values.role,
2221
+ permission: values.permission,
2222
+ data,
2223
+ to: values.to,
2224
+ duplicate: values.duplicate !== void 0 ? Number(values.duplicate) : void 0,
2225
+ invalid: values.invalid
2226
+ })
2227
+ });
2228
+ if (values.json) {
2229
+ process.stdout.write(`${JSON.stringify(deliveries)}
2230
+ `);
2231
+ return;
2232
+ }
2233
+ for (const delivery of deliveries) process.stdout.write(`${describeDelivery(delivery)}
2234
+ `);
2235
+ if (deliveries.some((d) => !d.delivered)) process.exitCode = 1;
2236
+ }
2237
+ function describeDelivery(delivery) {
2238
+ const attempts = delivery.attempts ?? [];
2239
+ const outcome = attempts.map((a) => a.status === null ? "no answer" : String(a.status)).join(", ");
2240
+ const mark = delivery.delivered ? "\u2713" : "\u2717";
2241
+ return `${mark} ${String(delivery.type)} to ${String(delivery.url)} (${String(delivery.webhookId)}): ${outcome}`;
2242
+ }
1834
2243
  function describeRule(rule) {
1835
2244
  const parts = [`${String(rule.id)}: ${rule.method ? `${String(rule.method)} ` : ""}${String(rule.path)}`];
1836
2245
  if (rule.status !== null) parts.push(`answers ${String(rule.status)}`);