@work-shape/catalyst-api-client 0.8.0-rc.2 → 0.8.0-rc.21

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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { ApiErrorCode, Operation, OperationPathParamName, OperationRequestHeader, apiOperations, ApiOperationName } from '@work-shape/catalyst-api-contract';
2
+ import { ApiErrorCode, LocaleCode, Operation, OperationPathParamName, OperationRequestHeader, apiOperations, ApiOperationName } from '@work-shape/catalyst-api-contract';
3
3
  export * from '@work-shape/catalyst-api-contract';
4
4
 
5
5
  /**
@@ -22,14 +22,64 @@ declare const authSessionSchema: z.ZodNullable<z.ZodObject<{
22
22
  type AuthSession = NonNullable<z.infer<typeof authSessionSchema>>;
23
23
  interface AuthResult {
24
24
  ok: boolean;
25
+ /** The sign-in library's code for a refusal, such as `INVALID_EMAIL_OR_PASSWORD`. */
26
+ code?: string;
25
27
  message?: string;
28
+ /** The HTTP status of a refusal; 429 is the instance's limit on attempts. */
29
+ status?: number;
30
+ }
31
+ /** The second factor of a sign-in: a code from the authenticator app, or a backup code. */
32
+ type SecondFactorKind = "app" | "backup";
33
+ /** A sign-in: refused, signed in, or waiting for the second factor (TWO-FACTOR-1). */
34
+ interface SignInResult extends AuthResult {
35
+ /** The password was right and the account asks for a code before there is a session. */
36
+ secondFactor?: true;
37
+ }
38
+ /** What an authenticator app reads, and the ten backup codes, shown once. */
39
+ interface TwoFactorSetup {
40
+ totpUri: string;
41
+ backupCodes: string[];
26
42
  }
27
43
  declare function getAuthSession(apiBaseUrl: string): Promise<AuthSession | null>;
28
44
  declare function signInWithEmail(input: {
29
45
  apiBaseUrl: string;
30
46
  email: string;
31
47
  password: string;
48
+ }): Promise<SignInResult>;
49
+ /**
50
+ * The second sign-in step: a code from the authenticator app, or a backup code, which signs in
51
+ * once. `trustBrowser` skips the code in this browser for 30 days from now.
52
+ */
53
+ declare function verifySecondFactor(input: {
54
+ apiBaseUrl: string;
55
+ code: string;
56
+ kind: SecondFactorKind;
57
+ trustBrowser?: boolean;
58
+ }): Promise<AuthResult>;
59
+ /**
60
+ * Starts the setup of two-factor sign-in with the password. The factor is on only after the
61
+ * first code from the app is confirmed with `verifySecondFactor`.
62
+ */
63
+ declare function startTwoFactorSetup(input: {
64
+ apiBaseUrl: string;
65
+ password: string;
66
+ }): Promise<AuthResult & {
67
+ setup?: TwoFactorSetup;
68
+ }>;
69
+ /** Turns two-factor sign-in off with the password; every trusted browser is forgotten. */
70
+ declare function turnOffTwoFactor(input: {
71
+ apiBaseUrl: string;
72
+ password: string;
32
73
  }): Promise<AuthResult>;
74
+ /** Replaces all ten backup codes with the password. The new ones are shown once. */
75
+ declare function regenerateBackupCodes(input: {
76
+ apiBaseUrl: string;
77
+ password: string;
78
+ }): Promise<AuthResult & {
79
+ backupCodes?: string[];
80
+ }>;
81
+ /** Every browser of the person asks for the code again at its next sign-in. */
82
+ declare function forgetTrustedBrowsers(apiBaseUrl: string): Promise<AuthResult>;
33
83
  /**
34
84
  * For a tool outside a browser, which keeps no cookies: signs in and returns a fetch that
35
85
  * carries the session cookie and the origin the instance trusts on every request.
@@ -50,6 +100,12 @@ declare function signOut(apiBaseUrl: string): Promise<void>;
50
100
  */
51
101
  declare class ApiError extends Error {
52
102
  readonly status: number;
103
+ /** Response location and category only; never response contents or URL credentials. */
104
+ responseInfo?: {
105
+ url: string;
106
+ contentType: string;
107
+ body: string;
108
+ };
53
109
  readonly code?: ApiErrorCode;
54
110
  readonly payload: unknown;
55
111
  readonly correlationId?: string;
@@ -73,6 +129,8 @@ declare class ApiResponseShapeError extends ApiError {
73
129
  readonly paths: readonly string[];
74
130
  constructor(status: number, cause: z.ZodError);
75
131
  }
132
+ /** Add diagnostics without retaining the response text, query parameters or credentials. */
133
+ declare function describeResponse(error: unknown, response: Response, url: string, text: string): unknown;
76
134
 
77
135
  interface ApiClientOptions {
78
136
  baseUrl: string;
@@ -82,6 +140,13 @@ interface ApiClientOptions {
82
140
  */
83
141
  getToken?: () => string | undefined | Promise<string | undefined>;
84
142
  fetchImpl?: typeof fetch;
143
+ /** Cancels this client's requests when its owning session ends. */
144
+ signal?: AbortSignal;
145
+ /**
146
+ * The language every request asks the server to answer in, read at each request. A browser's
147
+ * own Accept-Language names its settings, not the language a person chose in the interface.
148
+ */
149
+ locale?: LocaleCode;
85
150
  /** Only available without a token source; browser navigation cannot send a bearer token. */
86
151
  browserManagedDownloads?: boolean;
87
152
  /**
@@ -127,7 +192,12 @@ type ControlPart<Op extends Operation> = {
127
192
  } ? {
128
193
  /** Called when the server has nothing after the given position and sends no stream. */
129
194
  onCaughtUp?: () => void;
130
- } : unknown);
195
+ } & (Op["response"] extends {
196
+ skip: infer Skip extends z.ZodType;
197
+ } ? {
198
+ /** Called for an event this client does not know, which the stream passes over. */
199
+ onSkipped?: (value: z.output<Skip>) => void;
200
+ } : unknown) : unknown);
131
201
  /**
132
202
  * An operation that takes an `Idempotency-Key` gets a new one with every call. A caller that
133
203
  * sends the same call again after an answer that never arrived passes the key of the first.
@@ -139,7 +209,18 @@ type IdempotencyPart<Op> = Op extends {
139
209
  } ? "Idempotency-Key" extends Header ? {
140
210
  idempotencyKey?: string;
141
211
  } : unknown : unknown;
142
- type InputOf<Op extends Operation> = ParamsPart<Op["path"]> & QueryPart<Op> & BodyPart<Op> & IdempotencyPart<Op> & ControlPart<Op>;
212
+ /**
213
+ * An operation that takes `Catalyst-Unattended` is sent with it when `unattended` is set: nobody
214
+ * watches the caller's terminal, so a call that needs a confirmation waits in the Inbox.
215
+ */
216
+ type UnattendedPart<Op> = Op extends {
217
+ headers: {
218
+ request: readonly (infer Header extends OperationRequestHeader)[];
219
+ };
220
+ } ? "Catalyst-Unattended" extends Header ? {
221
+ unattended?: boolean;
222
+ } : unknown : unknown;
223
+ type InputOf<Op extends Operation> = ParamsPart<Op["path"]> & QueryPart<Op> & BodyPart<Op> & IdempotencyPart<Op> & UnattendedPart<Op> & ControlPart<Op>;
143
224
  /**
144
225
  * How a call of an operation that may wait for an approval came out. A refusal and a failure
145
226
  * are thrown as `ApiError`, as for every operation.
@@ -153,7 +234,10 @@ type OperationOutcome<Output, Run = unknown> = {
153
234
  status: "done";
154
235
  output: Output;
155
236
  }
156
- /** Nothing ran yet: somebody else decides. `location` is where the run is read again. */
237
+ /**
238
+ * Nothing ran yet: somebody decides it, an approver or, for a run `pending_confirmation`, the
239
+ * caller in their Inbox. `location` is where the run is read again.
240
+ */
157
241
  | {
158
242
  status: "pending_approval";
159
243
  run: Run;
@@ -169,6 +253,8 @@ type OutputOf<Op extends Operation> = Op["response"] extends {
169
253
  kind: "sse";
170
254
  schema: infer Schema extends z.ZodType;
171
255
  } ? AsyncIterable<z.output<Schema>> : Op["response"] extends {
256
+ kind: "redirect";
257
+ } ? Promise<undefined> : Op["response"] extends {
172
258
  schema: infer Schema extends z.ZodType;
173
259
  } ? Op extends {
174
260
  accepted: infer Accepted extends z.ZodType;
@@ -218,4 +304,4 @@ declare function listAll<Item>(readPage: (paging: {
218
304
  nextCursor?: string;
219
305
  }>): Promise<Item[]>;
220
306
 
221
- export { AUTH_MOUNT_PATH, type ApiClient, type ApiClientFor, type ApiClientOptions, ApiError, type ApiOperationMethods, ApiResponseShapeError, type AuthResult, type AuthSession, type OperationInput, type OperationOutcome, completedOutput, createApiClient, createApiClientFor, getAuthSession, listAll, refusalError, signInForSessionFetch, signInWithEmail, signOut, transportError, unreadableResponseError };
307
+ export { AUTH_MOUNT_PATH, type ApiClient, type ApiClientFor, type ApiClientOptions, ApiError, type ApiOperationMethods, ApiResponseShapeError, type AuthResult, type AuthSession, type OperationInput, type OperationOutcome, type SecondFactorKind, type SignInResult, type TwoFactorSetup, completedOutput, createApiClient, createApiClientFor, describeResponse, forgetTrustedBrowsers, getAuthSession, listAll, refusalError, regenerateBackupCodes, signInForSessionFetch, signInWithEmail, signOut, startTwoFactorSetup, transportError, turnOffTwoFactor, unreadableResponseError, verifySecondFactor };
package/dist/index.js CHANGED
@@ -6,9 +6,15 @@ var authSessionSchema = z.object({
6
6
  user: z.object({ id: z.string(), email: z.string(), name: z.string() })
7
7
  }).nullable();
8
8
  var authFailureSchema = z.object({
9
+ code: z.string().optional(),
9
10
  message: z.string().optional(),
10
11
  error: z.object({ message: z.string().optional() }).optional()
11
12
  });
13
+ var signInAnswerSchema = z.object({ twoFactorRedirect: z.boolean().optional() });
14
+ var twoFactorSetupSchema = z.object({
15
+ totpURI: z.string(),
16
+ backupCodes: z.array(z.string())
17
+ });
12
18
  async function getAuthSession(apiBaseUrl) {
13
19
  const response = await fetch(authUrl(apiBaseUrl, "/get-session"), {
14
20
  credentials: "include"
@@ -32,12 +38,64 @@ async function signInWithEmail(input) {
32
38
  })
33
39
  });
34
40
  if (response.ok) {
35
- return { ok: true };
41
+ const answer = signInAnswerSchema.safeParse(await response.json().catch(() => void 0));
42
+ return answer.data?.twoFactorRedirect === true ? { ok: true, secondFactor: true } : { ok: true };
43
+ }
44
+ return failureOf(response, "Sign in failed");
45
+ }
46
+ async function verifySecondFactor(input) {
47
+ const path = input.kind === "app" ? "/two-factor/verify-totp" : "/two-factor/verify-backup-code";
48
+ const response = await postAuth(input.apiBaseUrl, path, {
49
+ code: input.code.replaceAll(/\s/gu, ""),
50
+ trustDevice: input.trustBrowser === true
51
+ });
52
+ return response.ok ? { ok: true } : failureOf(response, "The code was not accepted");
53
+ }
54
+ async function startTwoFactorSetup(input) {
55
+ const response = await postAuth(input.apiBaseUrl, "/two-factor/enable", {
56
+ password: input.password
57
+ });
58
+ if (!response.ok) {
59
+ return failureOf(response, "Two-factor sign-in could not be set up");
60
+ }
61
+ const setup = twoFactorSetupSchema.parse(await response.json());
62
+ return { ok: true, setup: { totpUri: setup.totpURI, backupCodes: setup.backupCodes } };
63
+ }
64
+ async function turnOffTwoFactor(input) {
65
+ const response = await postAuth(input.apiBaseUrl, "/two-factor/disable", {
66
+ password: input.password
67
+ });
68
+ return response.ok ? { ok: true } : failureOf(response, "Two-factor sign-in stayed on");
69
+ }
70
+ async function regenerateBackupCodes(input) {
71
+ const response = await postAuth(input.apiBaseUrl, "/two-factor/generate-backup-codes", {
72
+ password: input.password
73
+ });
74
+ if (!response.ok) {
75
+ return failureOf(response, "No new backup codes were made");
36
76
  }
77
+ const { backupCodes } = twoFactorSetupSchema.pick({ backupCodes: true }).parse(await response.json());
78
+ return { ok: true, backupCodes };
79
+ }
80
+ async function forgetTrustedBrowsers(apiBaseUrl) {
81
+ const response = await postAuth(apiBaseUrl, "/two-factor/forget-trusted-browsers", {});
82
+ return response.ok ? { ok: true } : failureOf(response, "The browsers are still trusted");
83
+ }
84
+ function postAuth(apiBaseUrl, path, body) {
85
+ return fetch(authUrl(apiBaseUrl, path), {
86
+ method: "POST",
87
+ credentials: "include",
88
+ headers: { "content-type": "application/json" },
89
+ body: JSON.stringify(body)
90
+ });
91
+ }
92
+ async function failureOf(response, fallback) {
37
93
  const failure = authFailureSchema.safeParse(await response.json().catch(() => void 0));
38
94
  return {
39
95
  ok: false,
40
- message: failure.data?.message ?? failure.data?.error?.message ?? "Sign in failed"
96
+ status: response.status,
97
+ ...failure.data?.code === void 0 ? {} : { code: failure.data.code },
98
+ message: failure.data?.message ?? failure.data?.error?.message ?? fallback
41
99
  };
42
100
  }
43
101
  async function signInForSessionFetch(input) {
@@ -50,6 +108,12 @@ async function signInForSessionFetch(input) {
50
108
  if (!response.ok) {
51
109
  throw new Error(`Sign-in as '${input.email}' was refused with status ${response.status}`);
52
110
  }
111
+ const answer = signInAnswerSchema.safeParse(
112
+ await response.clone().json().catch(() => void 0)
113
+ );
114
+ if (answer.data?.twoFactorRedirect === true) {
115
+ throw new Error(`'${input.email}' signs in with a second factor; use an API key for this tool`);
116
+ }
53
117
  const cookie = response.headers.getSetCookie().map((value) => value.split(";", 1)[0]).join("; ");
54
118
  return (resource, init) => {
55
119
  const request = new Request(resource, init);
@@ -76,6 +140,8 @@ import {
76
140
  import { z as z2 } from "zod";
77
141
  var ApiError = class extends Error {
78
142
  status;
143
+ /** Response location and category only; never response contents or URL credentials. */
144
+ responseInfo;
79
145
  code;
80
146
  payload;
81
147
  correlationId;
@@ -143,6 +209,28 @@ function readRetryAfterSeconds(payload) {
143
209
  const parsed = z2.object({ error: z2.object({ details: rateLimitedDetailsSchema }) }).safeParse(payload);
144
210
  return parsed.success ? parsed.data.error.details.retryAfterSeconds : void 0;
145
211
  }
212
+ function describeResponse(error, response, url, text) {
213
+ if (!(error instanceof ApiError)) return error;
214
+ const address = new URL(response.url || url);
215
+ address.username = "";
216
+ address.password = "";
217
+ address.search = "";
218
+ address.hash = "";
219
+ const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim();
220
+ const contentType = mediaType && /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/iu.test(mediaType) ? mediaType : "unknown content type";
221
+ let body = "non-JSON text";
222
+ if (contentType === "text/html" || /^\s*(?:<!doctype html|<html)(?:\s|>)/iu.test(text)) {
223
+ body = "an HTML page instead of API JSON";
224
+ } else {
225
+ try {
226
+ JSON.parse(text);
227
+ body = "other JSON that does not match the API contract";
228
+ } catch {
229
+ }
230
+ }
231
+ error.responseInfo = { url: address.toString(), contentType, body };
232
+ return error;
233
+ }
146
234
 
147
235
  // src/client.ts
148
236
  import {
@@ -180,7 +268,9 @@ function readEventData(block) {
180
268
  }
181
269
 
182
270
  // src/transport.ts
183
- import { isUnknownOperationResponse } from "@work-shape/catalyst-api-contract";
271
+ import {
272
+ isUnknownOperationResponse
273
+ } from "@work-shape/catalyst-api-contract";
184
274
  function createApiTransport(options) {
185
275
  const baseUrl = options.baseUrl.replace(/\/$/u, "");
186
276
  const cookieMode = options.getToken === void 0;
@@ -209,10 +299,20 @@ function createApiTransport(options) {
209
299
  if (operation.headers?.request?.includes("Idempotency-Key")) {
210
300
  headers.set("idempotency-key", request.idempotencyKey ?? createIdempotencyKey());
211
301
  }
302
+ if (request.unattended && operation.headers?.request?.includes("Catalyst-Unattended")) {
303
+ headers.set("catalyst-unattended", "1");
304
+ }
212
305
  const token = await options.getToken?.();
306
+ const sessionSignal = options.signal;
307
+ const signal = sessionSignal && request.signal ? AbortSignal.any([sessionSignal, request.signal]) : sessionSignal ?? request.signal;
213
308
  if (token) {
214
309
  headers.set("authorization", `Bearer ${token}`);
215
310
  }
311
+ const locale = options.locale;
312
+ if (locale !== void 0) {
313
+ headers.set("accept-language", locale);
314
+ }
315
+ signal?.throwIfAborted();
216
316
  let response;
217
317
  try {
218
318
  response = await (options.fetchImpl ?? fetch)(url, {
@@ -220,10 +320,10 @@ function createApiTransport(options) {
220
320
  headers,
221
321
  body,
222
322
  credentials: cookieMode ? "include" : "omit",
223
- signal: request.signal
323
+ signal
224
324
  });
225
325
  } catch (error) {
226
- throw request.signal?.aborted ? error : transportError(error);
326
+ throw signal?.aborted ? error : transportError(error);
227
327
  }
228
328
  if (response.ok) {
229
329
  return response;
@@ -311,7 +411,13 @@ function hasEveryOperation(operations, tree) {
311
411
  function callOperation(transport, operation, request) {
312
412
  const { response } = operation;
313
413
  if (response.kind === "sse") {
314
- return streamEvents(transport, operation, response.schema, request);
414
+ return streamEvents(transport, operation, response, request);
415
+ }
416
+ if (response.kind === "redirect") {
417
+ return transport.send(operation, request).then(async (answer) => {
418
+ await answer.body?.cancel();
419
+ return void 0;
420
+ });
315
421
  }
316
422
  if (response.kind === "blob") {
317
423
  return transport.send(operation, request).then((answer) => readBody(() => answer.blob(), request));
@@ -322,26 +428,30 @@ function callOperation(transport, operation, request) {
322
428
  return void 0;
323
429
  }
324
430
  const text = await readBody(() => answer.text(), request);
325
- if (!accepted) {
326
- return parseJson(transport, text, response.schema, answer.status);
431
+ try {
432
+ if (!accepted) {
433
+ return parseJson(transport, text, response.schema, answer.status);
434
+ }
435
+ const outcome = {
436
+ operationRunId: answer.headers.get("operation-run-id") ?? void 0,
437
+ replayed: answer.headers.get("idempotent-replayed") === "true"
438
+ };
439
+ return answer.status === 202 ? {
440
+ ...outcome,
441
+ status: "pending_approval",
442
+ run: parseJson(transport, text, accepted, answer.status),
443
+ location: answer.headers.get("location") ?? void 0
444
+ } : {
445
+ ...outcome,
446
+ status: "done",
447
+ output: parseJson(transport, text, response.schema, answer.status)
448
+ };
449
+ } catch (error) {
450
+ throw describeResponse(error, answer, transport.urlFor(operation, request), text);
327
451
  }
328
- const outcome = {
329
- operationRunId: answer.headers.get("operation-run-id") ?? void 0,
330
- replayed: answer.headers.get("idempotent-replayed") === "true"
331
- };
332
- return answer.status === 202 ? {
333
- ...outcome,
334
- status: "pending_approval",
335
- run: parseJson(transport, text, accepted, answer.status),
336
- location: answer.headers.get("location") ?? void 0
337
- } : {
338
- ...outcome,
339
- status: "done",
340
- output: parseJson(transport, text, response.schema, answer.status)
341
- };
342
452
  });
343
453
  }
344
- async function* streamEvents(transport, operation, schema, request) {
454
+ async function* streamEvents(transport, operation, response, request) {
345
455
  const answer = await transport.send(operation, request);
346
456
  if (answer.status === 204) {
347
457
  request.onCaughtUp?.();
@@ -352,7 +462,12 @@ async function* streamEvents(transport, operation, schema, request) {
352
462
  }
353
463
  try {
354
464
  for await (const data of readServerSentEvents(answer.body)) {
355
- yield parseJson(transport, data, schema, answer.status);
465
+ const event = readEvent(transport, data, response, answer.status);
466
+ if (event.skipped) {
467
+ request.onSkipped?.(event.value);
468
+ continue;
469
+ }
470
+ yield event.value;
356
471
  }
357
472
  } catch (error) {
358
473
  throw asCallFailure(error, request);
@@ -368,6 +483,22 @@ async function readBody(read, request) {
368
483
  function asCallFailure(error, request) {
369
484
  return error instanceof ApiError || request.signal?.aborted ? error : transportError(error);
370
485
  }
486
+ function readEvent(transport, text, response, status) {
487
+ const { skip } = response;
488
+ if (skip) {
489
+ let value;
490
+ try {
491
+ value = JSON.parse(text);
492
+ } catch (error) {
493
+ throw unreadableResponseError(status, error);
494
+ }
495
+ const parsed = response.schema.safeParse(value);
496
+ if (parsed.success) return { skipped: false, value: parsed.data };
497
+ const skipped = skip.safeParse(value);
498
+ if (skipped.success) return { skipped: true, value: skipped.data };
499
+ }
500
+ return { skipped: false, value: parseJson(transport, text, response.schema, status) };
501
+ }
371
502
  function parseJson(transport, text, schema, status) {
372
503
  let value;
373
504
  try {
@@ -392,12 +523,18 @@ export {
392
523
  completedOutput,
393
524
  createApiClient,
394
525
  createApiClientFor,
526
+ describeResponse,
527
+ forgetTrustedBrowsers,
395
528
  getAuthSession,
396
529
  listAll,
397
530
  refusalError,
531
+ regenerateBackupCodes,
398
532
  signInForSessionFetch,
399
533
  signInWithEmail,
400
534
  signOut,
535
+ startTwoFactorSetup,
401
536
  transportError,
402
- unreadableResponseError
537
+ turnOffTwoFactor,
538
+ unreadableResponseError,
539
+ verifySecondFactor
403
540
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@work-shape/catalyst-api-client",
3
- "version": "0.8.0-rc.2",
3
+ "version": "0.8.0-rc.21",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "zod": "4.4.3",
32
- "@work-shape/catalyst-api-contract": "0.8.0-rc.2"
32
+ "@work-shape/catalyst-api-contract": "0.8.0-rc.21"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^24.13.1",