@tamr/api 0.0.0-stage → 1.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/CHANGELOG.md ADDED
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0
4
+
5
+ - Post-meal reviews from an app (#453): `reviewsMatch`, the dishes of an order your backend sent that the
6
+ diner can rate, and `reviewsSubmit`, their stars, one review per dish per order (sending again changes
7
+ a rating). A new error code, `review_refused`, with `reviewRefusal` (an open list).
8
+ - The diner's nutrition goal (#450): a `dishes` card can carry `goal` (`mode`, the dishes that `fits` it by the restaurant's own figures, and the `unknown` ones it has no figures for), and each `surprise_basket` basket can carry `nutrition` (the meal's figures, each null unless every dish has it) and `goalFit`. All optional; `goal.mode` and `goalFit` are open lists.
9
+ - `GET` and `PUT /api/v1/goal` (#450): the goal Tamr keeps for the session's diner across visits, per meal (`mode`, and optional `kcal` and `proteinGrams`); `PUT` with `goal: null` clears it. `canSet` is false for a guest's session or a test key's, and `PUT` then answers the new error code `identity_required`. `ChatRequest.goal` sends the app's own goal with a message: never stored, it wins over the diner's while it's sent.
10
+ - The usual and reorder (#451): `usual()` (`GET /api/v1/usual`) answers the signed-in diner's usual, or their last completed order when there is no usual yet (`kind`, an open list), each item by the order's own title with today's `dish` (null once it's off the menu), `onMenu` and `available`. `usual` is null for a guest's session or a diner with no order. A `cart_proposal` card can carry `reorder` (`which`, `placedAt`, and the order's lines it left out in `dropped`, with a `reason`; both open lists). All additive.
11
+ - A dish's choices (#452): each `ChoiceOption` gains `extra` (what choosing it adds; null when nothing) and the
12
+ option's own `calories`, `proteinGrams`, `carbsGrams` and `fatGrams` (null where the restaurant gives none).
13
+ `price` is what the dish costs with the option in a pick-one choice, not an add-on. A dish whose options carry
14
+ figures has no figures of its own in `DishSummary`. All additive.
15
+ - The `build` card (#452): the waiter builds a dish with choices with the diner, one choice at a time. `DishBuild`
16
+ carries the dish, each choice with its `picked` option ids and `remaining`, `complete`, `total`, the build's
17
+ `nutrition` and `goalFit`. `CardKind` gains `build` (an open list). All additive.
18
+ - Allergens per choice option (#706): each `ChoiceOption` gains `allergens`, what the option brings beyond the
19
+ dish's own (empty when nothing). A chosen option's allergens are checked as the dish's, the app's
20
+ `restrictions` included. Additive.
21
+ - `nutritionPut` on the Server API client (`PUT /api/v1/catalog/nutrition`, #685): your own per-dish nutrition figures (`calories`, `proteinGrams`, `carbsGrams`, `fatGrams`), by Tamr's `dishId` or your `externalId`, up to 500 rows, all or nothing. A refused call's `data.rows` gives each row's `reason`, an open list. Your figures only fill the gaps the restaurant left in Tamr. On a dish whose options carry
22
+ figures (#452), they fill only the dish's part without choices.
23
+ - Treats on the house (#455): a `CartLine` can carry `treat` (`treatId`, `expiresAt`); price that line at
24
+ zero in your checkout. `sdkTreatRedeem` on the Server API client (`POST /api/v1/sdk/treats/{treatId}/redeem`)
25
+ redeems it once the order is placed, idempotent on the treat id. A new error code, `treat_refused`, with
26
+ `treatRefusal` (an open list). All additive.
27
+ - What an app hides (#726): `ChatRequest.hide` (`retailSuggestions`, `loyalty`) sent with each message turns
28
+ take-home suggestions and treats off for that turn, and `AppShown` gains `hideReviews`, `hideRetailSuggestions`
29
+ and `hideLoyalty`, the restaurant's own switches, which apply whatever is sent. Additive.
30
+ - `order.cancelled` (#743): a webhook for an order your app heard placed that ended unserved (`status`:
31
+ `declined`, `cancelled` or `expired`; `by`: `restaurant`, `diner` or `time`, an open list), once per order.
32
+ `WebhookEventType` gains it. Additive.
33
+ - Test orders (#742): a test key's pickup is checked and priced as a real one and written nowhere; the answer
34
+ and `order.placed` carry `test: true` (an `orderId` that starts `test_`), heard only by test webhook endpoints.
35
+ `OrderPlaced.test` is optional. Additive.
36
+
37
+ ## 1.0.0 (not published: 1.1.0 is the first version on npm, and includes it)
38
+
39
+ The first release (#448), for `/api/v1` 1.0.
40
+
41
+ - `createClient` for the Client API: `startSession` (a token, a launch code, or a guest's device), the session and device sent with every call, and `onSessionExpired` asked once with the call sent again once. One typed function for every route, and the chat as an async iterator of typed server-sent events.
42
+ - `createServerClient` (`@tamr/api/server`) for the Server API, with a secret key. It throws in a browser.
43
+ - Generated from the spec, with no runtime dependencies. A value Tamr adds to an open list reads as its fallback, and a new event or card kind reads as `$unknown`.
44
+ - `TamrApiError` with the stable `code`, `requestId` and `retryAfter`.
45
+ - Node 20+ and every current browser.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abiroot
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,57 @@
1
- # Temporary Holding Version
1
+ # @tamr/api
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 Tamr's API: the **Client API**, for an app that draws its own waiter UI, and the **Server API**, for its backend. It's generated from Tamr's OpenAPI spec, has no runtime dependencies, and runs in Node 20+ and every current browser.
4
+
5
+ The guide to authentication, sessions, the chat stream, errors, rate limits and versioning is [`docs/sdk/api.md`](https://github.com/abiroot/tamr/blob/main/docs/sdk/api.md). Every route is in the reference at [tamr.link/api/v1/docs](https://tamr.link/api/v1/docs).
6
+
7
+ ```sh
8
+ npm install @tamr/api
9
+ ```
10
+
11
+ ## The Client API
12
+
13
+ ```ts
14
+ import { createClient } from "@tamr/api";
15
+
16
+ const tamr = createClient({
17
+ appKey: "tamr_pk_live_…", // your publishable key
18
+ // A session ended: return a new launch for the diner (one call, one retry).
19
+ onSessionExpired: async () => ({ token: await yourBackend.signDinerToken() }),
20
+ });
21
+
22
+ await tamr.startSession({ token: await yourBackend.signDinerToken() });
23
+ const { menu, categories } = await tamr.menu({ branch: "achrafieh" });
24
+
25
+ for await (const event of tamr.chat({ message: "Something light, no nuts?" })) {
26
+ if (event.event === "message" && event.data.type === "text") show(event.data.delta);
27
+ if (event.event === "message" && event.data.type === "card") draw(event.data.card);
28
+ // A kind this version doesn't know reads as `$unknown`: skip it.
29
+ }
30
+ ```
31
+
32
+ Every route has a typed function (`menu`, `chat`, `conversationsList`, `cartMatch`, `tableSeat`, `pickupOrdersPlace`, `payStart`, …). Each answer is decoded, so a value Tamr adds to an open list later reads as that list's fallback instead of breaking your app.
33
+
34
+ ## The Server API
35
+
36
+ ```ts
37
+ import { createServerClient } from "@tamr/api/server";
38
+
39
+ const tamr = createServerClient({ secretKey: process.env.TAMR_SECRET_KEY });
40
+ const { code } = await tamr.sdkLaunchCodes({ externalUserId: "user-88213" });
41
+ ```
42
+
43
+ `createServerClient` throws in a browser: a secret key must never ship to one. That check (`typeof window`) is a guard against an honest mistake, not a wall: code in a web worker isn't stopped by it. Keep secret keys on your server.
44
+
45
+ Every call takes a last, optional `{ signal }`; aborting it stops the call, and breaking out of a `chat` loop stops the stream and the turn. A stopped call rejects with the platform's `AbortError`, never a `TamrApiError`.
46
+
47
+ ## Errors
48
+
49
+ A refusal throws a `TamrApiError` with `status`, `code` (stable, such as `rate_limited` or `session_expired`; `network` when Tamr wasn't reached), `requestId`, `retryAfter` and `data`.
50
+
51
+ ## Examples
52
+
53
+ `examples/node/chat.mjs` (a headless turn in Node) and `examples/chat-ui/` (a minimal custom chat in the browser), both against Tamr's SDK test venue. See the comment at the top of each.
54
+
55
+ ## License
56
+
57
+ MIT
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The Client API (`docs/sdk/api.md`): an app that draws its own waiter UI,
3
+ * with its publishable key and the diner's session. One `onSessionExpired`
4
+ * call and one retry when a session ends; anything more is the app's.
5
+ */
6
+ /** How the diner signs in: your backend's signed token, a one-time code, or, on a key with guest mode, this device. */
7
+ export type Launch = {
8
+ token: string;
9
+ } | {
10
+ code: string;
11
+ } | {
12
+ device: string;
13
+ };
14
+ export interface ClientOptions {
15
+ /** Your publishable key (`tamr_pk_live_…` or `tamr_pk_test_…`). */
16
+ appKey: string;
17
+ /** Defaults to Tamr's API. */
18
+ baseUrl?: string;
19
+ fetch?: typeof fetch;
20
+ /** This device's id, kept by your app; one is made if you don't pass it. */
21
+ device?: string;
22
+ /**
23
+ * The session ended (`session_expired`): return a new launch for the
24
+ * diner, or null. Called once per call that met it, then that call is
25
+ * sent again once.
26
+ */
27
+ onSessionExpired?: () => Promise<Launch | null>;
28
+ }
29
+ export declare const TAMR_API = "https://tamr.link/api";
30
+ export declare function createClient(options: ClientOptions): {
31
+ menu: (query?: {
32
+ branch?: string;
33
+ mode?: import("./generated/api.g.js").ClientMenuMode;
34
+ }, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").MenuResponse>;
35
+ waiter: (query?: {
36
+ branch?: string;
37
+ mode?: import("./generated/api.g.js").ClientWaiterMode;
38
+ }, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").WaiterFace>;
39
+ chat: (body: import("./generated/api.g.js").ChatRequest, options?: import("./generated/api.g.js").CallOptions) => AsyncIterable<import("./generated/api.g.js").ClientChatEvent>;
40
+ warmup: (body: import("./generated/api.g.js").ClientWarmupRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientWarmupResponse>;
41
+ conversationsList: (options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ConversationList>;
42
+ conversationsGet: (conversationId: string, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ConversationResponse>;
43
+ conversationsClose: (conversationId: string, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientConversationsCloseResponse>;
44
+ transcribe: (body: import("./generated/api.g.js").ClientTranscribeRequest | FormData, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientTranscribeResponse>;
45
+ cartMatch: (body: import("./generated/api.g.js").ClientCartMatchRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientCartMatchResponse>;
46
+ usual: (query?: {
47
+ branch?: string;
48
+ mode?: import("./generated/api.g.js").ClientUsualMode;
49
+ }, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientUsualResponse>;
50
+ tableGet: (query?: {
51
+ branch?: string;
52
+ }, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientTableGetResponse>;
53
+ tableSeat: (body: import("./generated/api.g.js").ClientTableSeatRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientTableSeatResponse>;
54
+ tableOrdersSend: (body: import("./generated/api.g.js").ClientTableOrdersSendRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientTableOrdersSendResponse>;
55
+ pickupOptions: (query?: {
56
+ branch?: string;
57
+ }, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientPickupOptionsResponse>;
58
+ pickupOrdersList: (options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientPickupOrdersListResponse>;
59
+ pickupOrdersPlace: (body: import("./generated/api.g.js").ClientPickupOrdersPlaceRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientPickupOrdersPlaceResponse>;
60
+ goalGet: (options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientGoalGetResponse>;
61
+ goalPut: (body: import("./generated/api.g.js").ClientGoalPutRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientGoalPutResponse>;
62
+ payOptions: (query?: {
63
+ branch?: string;
64
+ orderId?: string;
65
+ }, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientPayOptionsResponse>;
66
+ payStart: (body: import("./generated/api.g.js").ClientPayStartRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientPayStartResponse>;
67
+ payGet: (paymentId: string, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientPayGetResponse>;
68
+ reviewsMatch: (body: import("./generated/api.g.js").ClientReviewsMatchRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientReviewsMatchResponse>;
69
+ reviewsSubmit: (body: import("./generated/api.g.js").ClientReviewsSubmitRequest, options?: import("./generated/api.g.js").CallOptions) => Promise<import("./generated/api.g.js").ClientReviewsSubmitResponse>;
70
+ /** Sign the diner in; every later call carries the session. */
71
+ startSession: (launch: Launch) => Promise<import("./generated/api.g.js").SdkSessionResponse>;
72
+ /** The diner logged out: the session ends at Tamr and here. */
73
+ endSession(): Promise<void>;
74
+ session: string | null;
75
+ /** The device id every call carries. */
76
+ device: string;
77
+ };
78
+ export type TamrClient = ReturnType<typeof createClient>;
package/lib/client.js ADDED
@@ -0,0 +1,92 @@
1
+ import { clientOperations, decodeSdkSessionResponse, } from "./generated/api.g.js";
2
+ import { createTransport, TamrApiError } from "./transport.js";
3
+ import { SDK_VERSION } from "./version.js";
4
+ export const TAMR_API = "https://tamr.link/api";
5
+ export function createClient(options) {
6
+ const fetchImpl = options.fetch ??
7
+ ((...args) => fetch(...args));
8
+ const baseUrl = options.baseUrl ?? TAMR_API;
9
+ const device = options.device ?? crypto.randomUUID().replaceAll("-", "");
10
+ let session = null;
11
+ const headers = () => ({
12
+ "x-tamr-key": options.appKey,
13
+ "x-tamr-device": device,
14
+ ...(session ? { "x-tamr-session": session } : {}),
15
+ });
16
+ async function startSession(launch) {
17
+ const response = await fetchImpl(`${baseUrl.replace(/\/$/, "")}/v1/sdk/session`, {
18
+ method: "POST",
19
+ headers: {
20
+ ...headers(),
21
+ "content-type": "application/json",
22
+ accept: "application/json",
23
+ },
24
+ body: JSON.stringify({ ...launch, sdk: SDK_VERSION }),
25
+ }).catch((cause) => {
26
+ throw new TamrApiError(0, "network", cause instanceof Error
27
+ ? cause.message
28
+ : "Tamr couldn't be reached", null, null, {});
29
+ });
30
+ const body = (await response.json().catch(() => null));
31
+ const issued = response.headers.get("x-tamr-session");
32
+ if (!response.ok || !issued) {
33
+ const data = body?.data ?? {};
34
+ throw new TamrApiError(response.status, typeof data["code"] === "string" ? data["code"] : "other", typeof body?.message === "string"
35
+ ? body.message
36
+ : response.statusText, typeof data["requestId"] === "string"
37
+ ? data["requestId"]
38
+ : response.headers.get("x-request-id"), null, data);
39
+ }
40
+ session = issued;
41
+ return decodeSdkSessionResponse(body, "session");
42
+ }
43
+ const transport = createTransport({
44
+ baseUrl,
45
+ fetch: fetchImpl,
46
+ headers,
47
+ async renew(error) {
48
+ if (error.code !== "session_expired" || !options.onSessionExpired) {
49
+ return false;
50
+ }
51
+ const launch = await options.onSessionExpired();
52
+ if (!launch) {
53
+ return false;
54
+ }
55
+ await startSession(launch);
56
+ return true;
57
+ },
58
+ });
59
+ // The raw session routes stay inside: `startSession` keeps the session the
60
+ // exchange answers in a header, and `endSession` forgets it here too.
61
+ const { sdkSession: _start, sdkEndSession: _end, ...operations } = clientOperations(transport);
62
+ // Logging out never renews: an ended session is already logged out.
63
+ const { sdkEndSession } = clientOperations(createTransport({ baseUrl, fetch: fetchImpl, headers }));
64
+ return {
65
+ ...operations,
66
+ /** Sign the diner in; every later call carries the session. */
67
+ startSession,
68
+ /** The diner logged out: the session ends at Tamr and here. */
69
+ async endSession() {
70
+ try {
71
+ if (session) {
72
+ await sdkEndSession();
73
+ }
74
+ }
75
+ catch (error) {
76
+ if (!(error instanceof TamrApiError &&
77
+ error.code === "session_expired")) {
78
+ throw error;
79
+ }
80
+ }
81
+ finally {
82
+ session = null;
83
+ }
84
+ },
85
+ /** The session the calls carry now, or null. */
86
+ get session() {
87
+ return session;
88
+ },
89
+ /** The device id every call carries. */
90
+ device,
91
+ };
92
+ }