@msm-platform/customer-sdk 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MSM
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
1
+ # MSM customer SDK (`@msm-platform/customer-sdk`)
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
+ A typed client for MSM's customer API: sign-in, public business reads, reservations and bookings. Generated from the engine's customer contract with `openapi-typescript`, on top of `openapi-fetch` 0.17.0. Versions are `0.x` until engine 1.0.0; a minor version can break.
4
+
5
+ ```sh
6
+ npm install @msm-platform/customer-sdk
7
+ ```
8
+
9
+ ## Two modes
10
+
11
+ **Server mode** is for your own server. Give it your application client's ID and secret: the SDK sends them as HTTP Basic (`Authorization: Basic base64(clientId:clientSecret)`) on every call, so there is no token to fetch, cache or renew. It refuses to run where `window` exists, so a secret bundled into browser code throws before any request.
12
+
13
+ ```ts
14
+ import { createCustomerClient } from "@msm-platform/customer-sdk";
15
+
16
+ const msm = createCustomerClient({
17
+ baseUrl: process.env.MSM_ENGINE_URL!, // https://… without a trailing /web
18
+ clientId: process.env.MSM_CLIENT_ID!,
19
+ clientSecret: process.env.MSM_CLIENT_SECRET!,
20
+ });
21
+ ```
22
+
23
+ **Proxy mode** is for a browser or any code that must not hold the secret. Give it only a base URL and, if needed, a custom `fetch`, and put a proxy on your server in front of the engine that adds the credentials. MSM's customer portal works this way through its BFF.
24
+
25
+ ```ts
26
+ const msm = createCustomerClient({ baseUrl: "/msm", fetch: myFetch });
27
+ ```
28
+
29
+ ## Sessions
30
+
31
+ A customer signs in with a code sent by SMS. The session token is yours to store, for example in an HttpOnly cookie, and you pass it on each call that acts as the customer:
32
+
33
+ ```ts
34
+ import { sessionHeaders } from "@msm-platform/customer-sdk";
35
+
36
+ const { data: started } = await msm.POST("/web/identity/initiateLogin", {
37
+ body: { phone: "+3545550004" },
38
+ });
39
+ const { data: session } = await msm.POST("/web/identity/customerLogin", {
40
+ body: { challenge: started!.challenge, code: "123456" },
41
+ });
42
+
43
+ const headers = sessionHeaders(session!.sessionToken);
44
+ const { data: reservation } = await msm.POST(
45
+ "/web/businesses/{businessId}/reservations",
46
+ { params: { path: { businessId } }, body: { eventId }, headers },
47
+ );
48
+ const { data: booking } = await msm.POST(
49
+ "/web/businesses/{businessId}/reservations/{reservationId}/confirm",
50
+ { params: { path: { businessId, reservationId: reservation!.id } }, headers },
51
+ );
52
+ ```
53
+
54
+ A new customer registers the same way with `POST /web/identity/initiateRegistration` (`{ phone, name }`) and `POST /web/identity/registerCustomer`. `POST /web/identity/logout` with `{ sessionToken }` ends a session of your client. Sign-in, registration and logout are on `/web` and need your client's credentials, so call them from server mode or through your proxy; `/api` is not for website clients. A reservation holds the seat or slot for a few minutes; confirming it makes the booking.
55
+
56
+ The same session reads the customer's own details, bookings and passes with every business of your partner, and ends all their sessions with your client:
57
+
58
+ ```ts
59
+ const { data: me } = await msm.GET("/web/me", { headers });
60
+ const { data: upcoming } = await msm.GET("/web/me/bookings", {
61
+ params: { query: { period: "upcoming" } },
62
+ headers,
63
+ });
64
+ const { data: passes } = await msm.GET("/web/me/memberships", { headers });
65
+ await msm.PATCH("/web/me", { body: { name: "Kata Jónsdóttir" }, headers });
66
+ await msm.DELETE("/web/me/sessions", { headers });
67
+ ```
68
+
69
+ Each booking carries its business's name, its event and `cancellableUntil` and `lateCancellationFrom`; each pass its `creditsRemaining`, null when unlimited. Phone and email are read-only.
70
+
71
+ ## Errors
72
+
73
+ Every non-2xx response throws `CustomerApiError` with `status`, the engine's stable `code`, `message`, `retryAfterSeconds` (from `Retry-After` on 429 and 503), `issues` (the failed input checks on `ValidationFailed`, each `{path, message}` with `path` a JSON Pointer into the request such as `/body/eventId`), the parsed `body` and the original `response`. `isCustomerApiError(error, method, path)` is true only for that operation's errors and narrows `code` to the codes the contract declares for it, so TypeScript checks the cases you handle:
74
+
75
+ ```ts
76
+ import { isCustomerApiError } from "@msm-platform/customer-sdk";
77
+
78
+ try {
79
+ await msm.POST("/web/businesses/{businessId}/reservations", request);
80
+ } catch (error) {
81
+ if (isCustomerApiError(error, "post", "/web/businesses/{businessId}/reservations")) {
82
+ switch (error.code) {
83
+ case "EventFull":
84
+ case "SlotTaken":
85
+ return "Pick another time";
86
+ }
87
+ }
88
+ throw error;
89
+ }
90
+ ```
91
+
92
+ Until the engine declares its codes per operation, `code` is a `string`; the cases then compile without the check.
93
+
94
+ The SDK never retries a request: a 401 throws, and the next call sends the same credentials. Writes are not idempotent yet: retry a reservation only when you know the first attempt did not reach the engine.
95
+
96
+ ## Next.js server example
97
+
98
+ [`examples/customer-nextjs`](../../examples/customer-nextjs) in the repository is a Next.js App Router server that does all of the above with server actions: phone and code sign-in with the session in an HttpOnly cookie, the business's availability, and booking (reserve, then confirm). The SDK and the secret live only in server code (`lib/msm.ts`):
99
+
100
+ ```ts
101
+ // lib/msm.ts, imported only by server components and server actions
102
+ export const msm = createCustomerClient({
103
+ baseUrl: process.env.MSM_ENGINE_URL!,
104
+ clientId: process.env.MSM_CLIENT_ID!,
105
+ clientSecret: process.env.MSM_CLIENT_SECRET!,
106
+ });
107
+
108
+ // app/actions.ts
109
+ ("use server");
110
+ export async function book(form: FormData) {
111
+ const sessionToken = (await cookies()).get("msm-session")?.value;
112
+ const headers = sessionHeaders(sessionToken!);
113
+ const { data: reservation } = await msm.POST(
114
+ "/web/businesses/{businessId}/reservations",
115
+ {
116
+ params: { path: { businessId } },
117
+ body: { eventId: String(form.get("eventId")) },
118
+ headers,
119
+ },
120
+ );
121
+ await msm.POST(
122
+ "/web/businesses/{businessId}/reservations/{reservationId}/confirm",
123
+ {
124
+ params: { path: { businessId, reservationId: reservation!.id } },
125
+ headers,
126
+ },
127
+ );
128
+ }
129
+ ```
130
+
131
+ To run it against a local engine, see the example's README.
132
+
133
+ ## Inside msm-platform
134
+
135
+ `pnpm generate` writes `src/generated/api.ts` from the customer contract, `contracts/openapi/customer.json`, and `pnpm generate:check` fails when it is stale. Never edit it by hand. Publishing is manual and only Daníel does it: [docs/runbooks/customer-sdk.md](../../docs/runbooks/customer-sdk.md). Every changelog entry says its `Web impact:` on this package's users.
@@ -0,0 +1,63 @@
1
+ import type { components, paths } from "./generated/api.js";
2
+ export type HttpMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";
3
+ /** The methods the contract declares on a path. */
4
+ export type MethodOf<Paths, Path extends keyof Paths> = {
5
+ [M in HttpMethod]: M extends keyof Paths[Path] ? [NonNullable<Paths[Path][M]>] extends [never] ? never : M : never;
6
+ }[HttpMethod];
7
+ type ErrorBody<Responses> = {
8
+ [Status in keyof Responses]: `${Status & (string | number)}` extends `2${string}` ? never : Responses[Status] extends {
9
+ content: {
10
+ "application/json": infer Body;
11
+ };
12
+ } ? Body : never;
13
+ }[keyof Responses];
14
+ /**
15
+ * The error codes the contract declares for an operation, over all its
16
+ * non-2xx responses: a union of literals where the contract lists them,
17
+ * `string` where it does not.
18
+ */
19
+ export type ErrorCode<Paths, Path extends keyof Paths, Method extends MethodOf<Paths, Path>> = NonNullable<Paths[Path][Method]> extends {
20
+ responses: infer Responses;
21
+ } ? ErrorBody<Responses> extends {
22
+ code: infer Code extends string;
23
+ } ? Code : never : never;
24
+ /**
25
+ * One failed check of a request's input, on `ValidationFailed`: `path` is a
26
+ * JSON Pointer into the request, such as `/body/eventId`. The contract's own
27
+ * type, so the two cannot drift (MVP-126).
28
+ */
29
+ export type ValidationIssue = NonNullable<components["schemas"]["ValidationErrorResponse"]["issues"]>[number];
30
+ /**
31
+ * A non-2xx response. `code` is the engine's stable error code (undefined when
32
+ * the body is not the engine's `{code, message}` envelope, such as a proxy's
33
+ * own error page); narrow it per operation with `isCustomerApiError`.
34
+ */
35
+ export declare class CustomerApiError<Code extends string = string> extends Error {
36
+ readonly response: Response;
37
+ readonly body: unknown;
38
+ /** The request's method, upper case, such as `POST`. */
39
+ readonly method: string;
40
+ /** The contract path, such as `/web/businesses/{businessId}/reservations`. */
41
+ readonly path: string;
42
+ readonly status: number;
43
+ readonly code: Code | undefined;
44
+ /** Seconds to wait before trying again, from `Retry-After` (429, 503). */
45
+ readonly retryAfterSeconds: number | undefined;
46
+ /** The failed input checks, when the engine lists them. */
47
+ readonly issues: ValidationIssue[] | undefined;
48
+ constructor(response: Response, body: unknown,
49
+ /** The request's method, upper case, such as `POST`. */
50
+ method: string,
51
+ /** The contract path, such as `/web/businesses/{businessId}/reservations`. */
52
+ path: string);
53
+ /** Reads the response body without consuming the original response. */
54
+ static from(response: Response, method: string, path: string): Promise<CustomerApiError<string>>;
55
+ }
56
+ /**
57
+ * True when `error` is a `CustomerApiError`. Given a method and a contract
58
+ * path, true only for that operation's errors, with `code` narrowed to the
59
+ * codes the contract declares for it.
60
+ */
61
+ export declare function isCustomerApiError(error: unknown): error is CustomerApiError<string>;
62
+ export declare function isCustomerApiError<Path extends keyof paths, Method extends MethodOf<paths, Path>>(error: unknown, method: Method, path: Path): error is CustomerApiError<ErrorCode<paths, Path, Method>>;
63
+ export {};
package/dist/errors.js ADDED
@@ -0,0 +1,69 @@
1
+ function retryAfter(response, body) {
2
+ const header = response.headers.get("retry-after")?.trim();
3
+ if (header) {
4
+ if (/^\d+$/.test(header))
5
+ return Number(header);
6
+ const at = Date.parse(header);
7
+ if (!Number.isNaN(at))
8
+ return Math.max(0, Math.ceil((at - Date.now()) / 1000));
9
+ }
10
+ return typeof body.retryAfterSeconds === "number"
11
+ ? body.retryAfterSeconds
12
+ : undefined;
13
+ }
14
+ /**
15
+ * A non-2xx response. `code` is the engine's stable error code (undefined when
16
+ * the body is not the engine's `{code, message}` envelope, such as a proxy's
17
+ * own error page); narrow it per operation with `isCustomerApiError`.
18
+ */
19
+ export class CustomerApiError extends Error {
20
+ response;
21
+ body;
22
+ method;
23
+ path;
24
+ status;
25
+ code;
26
+ /** Seconds to wait before trying again, from `Retry-After` (429, 503). */
27
+ retryAfterSeconds;
28
+ /** The failed input checks, when the engine lists them. */
29
+ issues;
30
+ constructor(response, body,
31
+ /** The request's method, upper case, such as `POST`. */
32
+ method,
33
+ /** The contract path, such as `/web/businesses/{businessId}/reservations`. */
34
+ path) {
35
+ const record = (typeof body === "object" && body !== null ? body : {});
36
+ super(typeof record.message === "string"
37
+ ? record.message
38
+ : `MSM API request failed: ${response.status} ${response.statusText}`.trim());
39
+ this.response = response;
40
+ this.body = body;
41
+ this.method = method;
42
+ this.path = path;
43
+ this.name = "CustomerApiError";
44
+ this.status = response.status;
45
+ this.code =
46
+ typeof record.code === "string" ? record.code : undefined;
47
+ this.retryAfterSeconds = retryAfter(response, record);
48
+ this.issues = Array.isArray(record.issues)
49
+ ? record.issues
50
+ : undefined;
51
+ }
52
+ /** Reads the response body without consuming the original response. */
53
+ static async from(response, method, path) {
54
+ const text = await response.clone().text();
55
+ let body = text || undefined;
56
+ try {
57
+ body = JSON.parse(text);
58
+ }
59
+ catch {
60
+ /* Keep non-JSON error bodies intact. */
61
+ }
62
+ return new CustomerApiError(response, body, method.toUpperCase(), path);
63
+ }
64
+ }
65
+ export function isCustomerApiError(error, method, path) {
66
+ return (error instanceof CustomerApiError &&
67
+ (method === undefined || error.method === method.toUpperCase()) &&
68
+ (path === undefined || error.path === path));
69
+ }