@brightoutcome/guidistry-client 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @brightoutcome/guidistry-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed client and sign-in helpers for the [Guidistry](https://github.com/BrightOutcome-Inc/guidistry) API. Every path, parameter and response type is generated from the API's OpenAPI contract, so an API change shows up as a type error.
4
+
5
+ ```
6
+ npm install @brightoutcome/guidistry-client aws-amplify
7
+ ```
8
+
9
+ ## Set up once
10
+
11
+ ```ts
12
+ import { createGuidistryClient } from "@brightoutcome/guidistry-client";
13
+ import { configureAuth, getAccessToken } from "@brightoutcome/guidistry-client/auth";
14
+
15
+ configureAuth(); // Guidistry QA user pool
16
+
17
+ let activeContext: string | null = null; // a membership ID from GET /v1/me
18
+
19
+ export const api = createGuidistryClient({
20
+ baseUrl: import.meta.env.VITE_GUIDISTRY_API_URL ?? "/guidistry/api",
21
+ getAccessToken,
22
+ getContext: () => activeContext,
23
+ });
24
+ export const setContext = (membershipId: string | null) => {
25
+ activeContext = membershipId;
26
+ };
27
+ ```
28
+
29
+ ## Sign in (identifier first)
30
+
31
+ ```ts
32
+ import { confirmSignIn, startSignIn } from "@brightoutcome/guidistry-client/auth";
33
+
34
+ const start = await startSignIn(api, "gloria@example.org");
35
+ if (start.kind === "sso") {
36
+ // later: redirect to the organization's sign-in (not used in January)
37
+ } else {
38
+ const { nextStep } = start.output;
39
+ // "CONTINUE_SIGN_IN_WITH_FIRST_FACTOR_SELECTION": show nextStep.availableChallenges
40
+ // (EMAIL_OTP, WEB_AUTHN, PASSWORD, …) and send the choice:
41
+ // await confirmSignIn({ challengeResponse: "EMAIL_OTP" })
42
+ // "CONFIRM_SIGN_IN_WITH_EMAIL_CODE": await confirmSignIn({ challengeResponse: code })
43
+ // "CONFIRM_SIGN_IN_WITH_PASSWORD": await confirmSignIn({ challengeResponse: password })
44
+ // "DONE": signed in
45
+ }
46
+ ```
47
+
48
+ After a first sign-in, offer a passkey: `registerPasskey()`. Sign out with `signOut()`.
49
+
50
+ ## Calling the API
51
+
52
+ ```ts
53
+ const { data: me } = await api.GET("/v1/me");
54
+ // me.memberships: the contexts this person can act in; pick one with setContext(m.id)
55
+
56
+ const { data: people } = await api.GET("/v1/people", { params: { query: { q: "lind" } } });
57
+
58
+ await api.POST("/v1/invitations", {
59
+ body: { email: "new@clinic.org", role: "provider", names: { given: "Mara", family: "Whitfield" } },
60
+ });
61
+ ```
62
+
63
+ Failed calls throw `GuidistryError` with `status` and `problem` (title, detail, request_id). A `409` from most endpoints means "choose a context" (the person has more than one membership).
64
+
65
+ ## Versioning
66
+
67
+ Semantic versioning: a new major version means a breaking API change and comes with a handoff note. Releases are published only by the Guidistry pipeline (npm trusted publishing).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { confirmSignIn, signOut, type SignInOutput } from "aws-amplify/auth";
2
+ import type { GuidistryClient } from "./client.js";
3
+ export { confirmSignIn, signOut };
4
+ export type { SignInOutput };
5
+ export interface AuthConfig {
6
+ userPoolId: string;
7
+ userPoolClientId: string;
8
+ }
9
+ /**
10
+ * Guidistry QA. Production values come with the production environment. These are public
11
+ * identifiers (every browser that signs in sees them), not secrets; the app client has none.
12
+ */
13
+ export declare const QA_AUTH: AuthConfig;
14
+ /** Call once at app start-up. */
15
+ export declare function configureAuth(config?: AuthConfig): void;
16
+ export type StartResult = {
17
+ kind: "sso";
18
+ provider: string;
19
+ message: string;
20
+ } | {
21
+ kind: "cognito";
22
+ output: SignInOutput;
23
+ message: string;
24
+ };
25
+ /**
26
+ * Begin signing in. With no preferred method, Cognito offers the methods this account can
27
+ * use (nextStep "CONTINUE_SIGN_IN_WITH_FIRST_FACTOR_SELECTION", with availableChallenges such
28
+ * as EMAIL_OTP, WEB_AUTHN, PASSWORD); answer with confirmSignIn({ challengeResponse }).
29
+ */
30
+ export declare function startSignIn(api: GuidistryClient, identifier: string, preferred?: "EMAIL_OTP" | "SMS_OTP" | "WEB_AUTHN" | "PASSWORD_SRP"): Promise<StartResult>;
31
+ /** The current access token, refreshed if needed; null when signed out. */
32
+ export declare function getAccessToken(): Promise<string | null>;
33
+ /** Offer this after a first sign-in: Face ID, Touch ID, Windows Hello or a security key. */
34
+ export declare function registerPasskey(): Promise<void>;
package/dist/auth.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Sign-in for Guidistry, on Amazon Cognito through AWS Amplify (peer dependency).
3
+ *
4
+ * The flow is identifier first (design: identity-and-tenancy §7):
5
+ * 1. startSignIn(identifier) asks the Guidistry API where to send the person. If their
6
+ * organization uses SSO, it returns { kind: "sso" }; otherwise it starts Cognito's
7
+ * choice-based sign-in and returns Amplify's next step.
8
+ * 2. Continue with Amplify's confirmSignIn (re-exported here): a one-time code, a
9
+ * password, or the method the person picks. Passkeys need no extra step.
10
+ * 3. getAccessToken() gives the client a fresh token; Amplify refreshes it automatically.
11
+ */
12
+ import { Amplify } from "aws-amplify";
13
+ import { associateWebAuthnCredential, confirmSignIn, fetchAuthSession, signIn, signOut, } from "aws-amplify/auth";
14
+ export { confirmSignIn, signOut };
15
+ /**
16
+ * Guidistry QA. Production values come with the production environment. These are public
17
+ * identifiers (every browser that signs in sees them), not secrets; the app client has none.
18
+ */
19
+ export const QA_AUTH = {
20
+ userPoolId: "us-east-2_GhNjwaNHA",
21
+ userPoolClientId: "7vtsis599vn7g38sl1843ncui8", // gitleaks:allow (public app client ID)
22
+ };
23
+ /** Call once at app start-up. */
24
+ export function configureAuth(config = QA_AUTH) {
25
+ Amplify.configure({
26
+ Auth: {
27
+ Cognito: {
28
+ userPoolId: config.userPoolId,
29
+ userPoolClientId: config.userPoolClientId,
30
+ loginWith: { email: true, phone: true, username: true },
31
+ },
32
+ },
33
+ });
34
+ }
35
+ /**
36
+ * Begin signing in. With no preferred method, Cognito offers the methods this account can
37
+ * use (nextStep "CONTINUE_SIGN_IN_WITH_FIRST_FACTOR_SELECTION", with availableChallenges such
38
+ * as EMAIL_OTP, WEB_AUTHN, PASSWORD); answer with confirmSignIn({ challengeResponse }).
39
+ */
40
+ export async function startSignIn(api, identifier, preferred) {
41
+ const { data } = await api.POST("/v1/auth/start", { body: { identifier } });
42
+ if (!data)
43
+ throw new Error("No response from /v1/auth/start");
44
+ if (data.sso)
45
+ return { kind: "sso", provider: data.sso, message: data.message };
46
+ const output = await signIn({
47
+ username: identifier.trim(),
48
+ options: preferred
49
+ ? { authFlowType: "USER_AUTH", preferredChallenge: preferred }
50
+ : { authFlowType: "USER_AUTH" },
51
+ });
52
+ return { kind: "cognito", output, message: data.message };
53
+ }
54
+ /** The current access token, refreshed if needed; null when signed out. */
55
+ export async function getAccessToken() {
56
+ try {
57
+ const session = await fetchAuthSession();
58
+ return session.tokens?.accessToken.toString() ?? null;
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ /** Offer this after a first sign-in: Face ID, Touch ID, Windows Hello or a security key. */
65
+ export async function registerPasskey() {
66
+ await associateWebAuthnCredential();
67
+ }
@@ -0,0 +1,39 @@
1
+ import type { components, paths } from "./schema.js";
2
+ export type Schemas = components["schemas"];
3
+ export type Me = Schemas["MeOut"];
4
+ export type Person = Schemas["PersonOut"];
5
+ export type Membership = Schemas["MembershipOut"];
6
+ export type Setting = Schemas["SettingOut"];
7
+ /** Header that selects which membership (context) a request acts through. */
8
+ export declare const CONTEXT_HEADER = "X-Guidistry-Context";
9
+ /** The API's error body (RFC 9457 problem details). */
10
+ export interface Problem {
11
+ title: string;
12
+ status: number;
13
+ detail?: unknown;
14
+ request_id?: string | null;
15
+ }
16
+ export declare class GuidistryError extends Error {
17
+ readonly status: number;
18
+ readonly problem: Problem;
19
+ constructor(problem: Problem);
20
+ }
21
+ export interface ClientOptions {
22
+ /** e.g. "https://qa.brightoutcome.com/guidistry/api". Defaults to "/guidistry/api". */
23
+ baseUrl?: string;
24
+ /** Returns the current Cognito access token, or null when signed out. */
25
+ getAccessToken?: () => Promise<string | null>;
26
+ /** Returns the active membership ID (from GET /v1/me), or null to let the API choose. */
27
+ getContext?: () => string | null;
28
+ fetch?: typeof globalThis.fetch;
29
+ }
30
+ /**
31
+ * Create a client. Calls look like:
32
+ *
33
+ * const { data } = await api.GET("/v1/people", { params: { query: { q: "lind" } } });
34
+ *
35
+ * Errors are thrown as GuidistryError (status and problem details), so `data` is always set
36
+ * when a call returns.
37
+ */
38
+ export declare function createGuidistryClient(options?: ClientOptions): import("openapi-fetch").Client<paths, `${string}/${string}`>;
39
+ export type GuidistryClient = ReturnType<typeof createGuidistryClient>;
package/dist/client.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Typed Guidistry API client. Every path, parameter and response type comes from the API's
3
+ * OpenAPI contract (src/schema.d.ts, generated), so a breaking API change is a type error.
4
+ */
5
+ import createClient, {} from "openapi-fetch";
6
+ /** Header that selects which membership (context) a request acts through. */
7
+ export const CONTEXT_HEADER = "X-Guidistry-Context";
8
+ export class GuidistryError extends Error {
9
+ status;
10
+ problem;
11
+ constructor(problem) {
12
+ super(problem.title);
13
+ this.name = "GuidistryError";
14
+ this.status = problem.status;
15
+ this.problem = problem;
16
+ }
17
+ }
18
+ /**
19
+ * Create a client. Calls look like:
20
+ *
21
+ * const { data } = await api.GET("/v1/people", { params: { query: { q: "lind" } } });
22
+ *
23
+ * Errors are thrown as GuidistryError (status and problem details), so `data` is always set
24
+ * when a call returns.
25
+ */
26
+ export function createGuidistryClient(options = {}) {
27
+ const client = createClient({
28
+ baseUrl: (options.baseUrl ?? "/guidistry/api").replace(/\/$/, ""),
29
+ fetch: options.fetch,
30
+ });
31
+ const auth = {
32
+ async onRequest({ request }) {
33
+ const token = options.getAccessToken ? await options.getAccessToken() : null;
34
+ if (token)
35
+ request.headers.set("Authorization", `Bearer ${token}`);
36
+ const context = options.getContext?.();
37
+ if (context)
38
+ request.headers.set(CONTEXT_HEADER, context);
39
+ return request;
40
+ },
41
+ async onResponse({ response }) {
42
+ if (response.ok)
43
+ return response;
44
+ let problem = { title: response.statusText || "Request failed", status: response.status };
45
+ try {
46
+ problem = { ...problem, ...(await response.clone().json()) };
47
+ }
48
+ catch {
49
+ // not JSON: keep the status text
50
+ }
51
+ throw new GuidistryError(problem);
52
+ },
53
+ };
54
+ client.use(auth);
55
+ return client;
56
+ }
@@ -0,0 +1,2 @@
1
+ export { CONTEXT_HEADER, createGuidistryClient, GuidistryError, type ClientOptions, type GuidistryClient, type Me, type Membership, type Person, type Problem, type Schemas, type Setting, } from "./client.js";
2
+ export type { components, paths } from "./schema.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { CONTEXT_HEADER, createGuidistryClient, GuidistryError, } from "./client.js";