@loyaltte/node 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +238 -2
- package/dist/cjs/client.d.ts +105 -0
- package/dist/cjs/client.js +278 -0
- package/dist/cjs/errors.d.ts +61 -0
- package/dist/cjs/errors.js +96 -0
- package/dist/cjs/identity.d.ts +23 -0
- package/dist/cjs/identity.js +27 -0
- package/dist/cjs/index.d.ts +11 -0
- package/dist/cjs/index.js +27 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/transport.d.ts +50 -0
- package/dist/cjs/transport.js +212 -0
- package/dist/cjs/types.d.ts +195 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +27 -0
- package/dist/cjs/webhooks.js +71 -0
- package/dist/esm/client.d.ts +105 -0
- package/dist/esm/client.js +273 -0
- package/dist/esm/errors.d.ts +61 -0
- package/dist/esm/errors.js +81 -0
- package/dist/esm/identity.d.ts +23 -0
- package/dist/esm/identity.js +24 -0
- package/dist/esm/index.d.ts +11 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/transport.d.ts +50 -0
- package/dist/esm/transport.js +206 -0
- package/dist/esm/types.d.ts +195 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +27 -0
- package/dist/esm/webhooks.js +66 -0
- package/package.json +57 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Loyaltte
|
|
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,239 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loyaltte/node 0.1.1
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Loyaltte for Node.js servers: record bills and returns **exactly once**, look up customers and their points, send events, sign customers in for the app SDKs, and verify webhooks.
|
|
4
|
+
|
|
5
|
+
**Zero runtime dependencies.** It uses the global `fetch` and `node:crypto`, ships ES modules, CommonJS and TypeScript types, and needs Node 18 or newer.
|
|
6
|
+
|
|
7
|
+
| | |
|
|
8
|
+
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
9
|
+
| Needs | Node **18+** (global `fetch`) |
|
|
10
|
+
| Key | a **secret** key (`lyt_live_…` or `lyt_test_…`), for your servers only |
|
|
11
|
+
| Source of truth | the contract in [`packages/sdk-spec`](../sdk-spec): `openapi.yaml`, the rules in `contract/rules/` (webhooks, server SDK, identity) and `contract/server/` |
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm install @loyaltte/node # or: yarn add / pnpm add @loyaltte/node
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Keys
|
|
20
|
+
|
|
21
|
+
Loyaltte has two kinds of key, and this package takes only one of them.
|
|
22
|
+
|
|
23
|
+
- **Secret key** (`lyt_live_…`, `lyt_test_…`, from Settings › API keys): for your servers. It does whatever its permissions allow. Keep it in an environment variable or a secrets manager. **Never put it in an app, a web page or a repository.**
|
|
24
|
+
- **Publishable key** (`lak_…`): for apps and web pages, with the app and web SDKs. It cannot call the server API, so `new Loyaltte("lak_…")` throws before anything is sent. The same goes for an identify secret (`lps_…`): that signs sign-ins (see below) and is not an API key.
|
|
25
|
+
|
|
26
|
+
The client keeps the key in a private field. It is not a property, and it does not appear when you print the client (`lyt_live_...wxyz`), in an error, or in a log. The SDK writes no logs.
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { Loyaltte } from "@loyaltte/node";
|
|
32
|
+
|
|
33
|
+
const loyaltte = new Loyaltte(process.env.LOYALTTE_SECRET_KEY!);
|
|
34
|
+
|
|
35
|
+
const key = await loyaltte.key.retrieve(); // which account and mode, its permissions and stores
|
|
36
|
+
|
|
37
|
+
const { found, customer } = await loyaltte.customers.lookup({ phone: "9876543210" });
|
|
38
|
+
if (found) {
|
|
39
|
+
const points = await loyaltte.customers.points(customer!.id);
|
|
40
|
+
console.log(points.balance, points.expiring_soon);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
CommonJS works too: `const { Loyaltte } = require("@loyaltte/node");`
|
|
45
|
+
|
|
46
|
+
### Options
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
new Loyaltte(secretKey, {
|
|
50
|
+
baseUrl: "https://api.loyaltte.com", // default; https only (plain http just for localhost)
|
|
51
|
+
timeoutMs: 30000, // per attempt
|
|
52
|
+
maxRetries: 7, // after the first attempt; 0 turns retries off
|
|
53
|
+
fetch: myFetch, // your own fetch (a proxy, a test double)
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Everything it can do
|
|
58
|
+
|
|
59
|
+
| Call | Endpoint | Permission |
|
|
60
|
+
| -------------------------------------------------------------- | ------------------------------- | ---------------- |
|
|
61
|
+
| `loyaltte.key.retrieve()` | `GET /v1/key` | any server key |
|
|
62
|
+
| `loyaltte.events.send(events)` | `POST /v1/events` | `events:write` |
|
|
63
|
+
| `loyaltte.visitors.identify({ anonymous_id, … })` | `POST /v1/identify` | `events:write` |
|
|
64
|
+
| `loyaltte.customers.lookup({ phone \| email \| external_id })` | `GET /v1/customers/lookup` | `customers:read` |
|
|
65
|
+
| `loyaltte.customers.retrieve(id)` | `GET /v1/customers/{id}` | `customers:read` |
|
|
66
|
+
| `loyaltte.customers.points(id)` | `GET /v1/customers/{id}/points` | `points:read` |
|
|
67
|
+
| `loyaltte.bills.preview(body)` | `POST /v1/bills/preview` | `bills:write` |
|
|
68
|
+
| `loyaltte.bills.create(body, { idempotencyKey? })` | `POST /v1/bills` | `bills:write` |
|
|
69
|
+
| `loyaltte.returns.create(body, { idempotencyKey? })` | `POST /v1/returns` | `bills:write` |
|
|
70
|
+
|
|
71
|
+
Answers are the API's JSON, typed. Every type is exported (`Bill`, `Customer`, `Points`, `KeyInfo`, …).
|
|
72
|
+
|
|
73
|
+
## Bills, exactly once
|
|
74
|
+
|
|
75
|
+
Money is **always a decimal string** such as `"4200.00"`, going in and coming out. Floats lose paise, so a number for an amount is refused before anything is sent.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
const bill = await loyaltte.bills.create(
|
|
79
|
+
{
|
|
80
|
+
store_id: "8a2d4e6f-1b3c-4d5e-8f70-9a1b2c3d4e5f",
|
|
81
|
+
bill_number: "BLR-IND-000482", // unique per bill
|
|
82
|
+
amount: "4200.00",
|
|
83
|
+
customer: { phone: "9876543210" }, // leave out for a walk-in
|
|
84
|
+
redeem_points: 400,
|
|
85
|
+
},
|
|
86
|
+
{ idempotencyKey: "order-10442" }, // optional: see below
|
|
87
|
+
);
|
|
88
|
+
console.log(bill.points_earned, bill.payable, bill.replayed);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Every bill and return carries an `Idempotency-Key`. If you give none, the SDK makes a UUID v4 for the call and **sends the same key on every retry**. So when the reply is lost (a timeout, a dropped connection) and the SDK tries again, Loyaltte answers with the first receipt (`replayed: true`) and records nothing twice. Give your own key (your order id) and a retry from a process that crashed in between is safe too. The same key with a different body is a `ConflictError`.
|
|
92
|
+
|
|
93
|
+
`loyaltte.bills.preview(body)` works a bill out without recording it: the points a customer can spend, what is payable, what it will earn, and any `problems` that would stop it.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
await loyaltte.returns.create({
|
|
97
|
+
bill_number: "BLR-IND-000482",
|
|
98
|
+
return_number: "RET-17",
|
|
99
|
+
amount: "2100.00",
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Events and visitors
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
await loyaltte.events.send([
|
|
107
|
+
{
|
|
108
|
+
id: "evt-1001",
|
|
109
|
+
type: "cart_updated",
|
|
110
|
+
anonymous_id: "anon_8f3a9c1d7b",
|
|
111
|
+
properties: { cart_value: 4200 },
|
|
112
|
+
},
|
|
113
|
+
{ id: "evt-1002", type: "checkout_started", customer: { phone: "9876543210" } },
|
|
114
|
+
]);
|
|
115
|
+
|
|
116
|
+
await loyaltte.visitors.identify({ anonymous_id: "anon_8f3a9c1d7b", phone: "9876543210" });
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
A longer list is sent in order as several requests of at most 100 events and 64 KiB each, and the counts are summed (`rejected` entries keep the index the server gave, within their batch). An empty list throws a `ValidationError` before anything is sent. If a batch fails, its error is raised and the earlier batches stay accepted: give every event an `id` and resend them all, a repeat is counted once.
|
|
120
|
+
|
|
121
|
+
## Sign a customer in for the app
|
|
122
|
+
|
|
123
|
+
The app SDKs never decide who the customer is. Your server signs the login with the identify secret (`lps_…`, Settings › App push) and the app passes the result to the SDK's `identify`. Sign only a customer your own session has authenticated.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import express from "express";
|
|
127
|
+
import { Loyaltte } from "@loyaltte/node";
|
|
128
|
+
|
|
129
|
+
const app = express();
|
|
130
|
+
app.use(express.json());
|
|
131
|
+
|
|
132
|
+
app.post("/loyaltte/sign-in", (req, res) => {
|
|
133
|
+
const customerId = req.session?.customerId; // YOUR login: never trust an id sent by the app
|
|
134
|
+
if (!customerId) return res.sendStatus(401);
|
|
135
|
+
const { installId } = req.body; // the app's SDK installId
|
|
136
|
+
if (typeof installId !== "string" || !/^[A-Za-z0-9._:-]{8,128}$/.test(installId))
|
|
137
|
+
return res.sendStatus(400);
|
|
138
|
+
|
|
139
|
+
res.set("Cache-Control", "no-store").json(
|
|
140
|
+
Loyaltte.signIdentity({
|
|
141
|
+
secret: process.env.LOYALTTE_IDENTIFY_SECRET!,
|
|
142
|
+
customerId,
|
|
143
|
+
installId, // with it the signature works for that install only (recommended)
|
|
144
|
+
}),
|
|
145
|
+
);
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`signIdentity` returns `{ customer_id, timestamp, signature, bind }`. The signature is the hex HMAC-SHA256 of `customer_id:timestamp:install_id` and is valid for 15 minutes.
|
|
150
|
+
|
|
151
|
+
## Webhooks
|
|
152
|
+
|
|
153
|
+
Loyaltte signs every webhook in the `Loyaltte-Signature` header. Verify it against the **raw body, exactly as received**. If a JSON parser runs first and you stringify the result again, the bytes change and the signature will not match.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import express from "express";
|
|
157
|
+
import { Loyaltte, WebhookSignatureError } from "@loyaltte/node";
|
|
158
|
+
|
|
159
|
+
const app = express();
|
|
160
|
+
|
|
161
|
+
// express.raw, NOT express.json, on this route
|
|
162
|
+
app.post("/loyaltte/webhooks", express.raw({ type: "application/json" }), (req, res) => {
|
|
163
|
+
try {
|
|
164
|
+
const event = Loyaltte.webhooks.constructEvent({
|
|
165
|
+
secret: process.env.LOYALTTE_WEBHOOK_SECRET!, // whsec_…
|
|
166
|
+
header: req.get("Loyaltte-Signature"),
|
|
167
|
+
rawBody: req.body, // a Buffer
|
|
168
|
+
});
|
|
169
|
+
// event.id is unique: ignore one you have handled. Any 2xx counts as delivered.
|
|
170
|
+
console.log(event.type, event.data);
|
|
171
|
+
res.sendStatus(200);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
if (error instanceof WebhookSignatureError) return res.sendStatus(400);
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
- `Loyaltte.webhooks.verify({ secret | secrets, header, rawBody, toleranceSeconds = 300 })` returns a boolean and never throws. `constructEvent` takes the same options and throws `WebhookSignatureError` or returns the parsed event.
|
|
180
|
+
- A signature older (or newer) than `toleranceSeconds` is refused: that is a replay.
|
|
181
|
+
- During a signing-secret rotation, pass both secrets as `secrets: [new, old]`. A rotation also sends two `v1` values in the header, and either may match.
|
|
182
|
+
- The comparison is constant time.
|
|
183
|
+
|
|
184
|
+
## Errors
|
|
185
|
+
|
|
186
|
+
Every error is a `LoyaltteError` with `status`, `code`, `message`, `fields`, `requestId` (quote it to support) and `retryAfter` (seconds, when the server sent it).
|
|
187
|
+
|
|
188
|
+
| Class | When |
|
|
189
|
+
| ----------------------- | ----------------------------------------------------------------------------------- |
|
|
190
|
+
| `AuthenticationError` | 401: no key, or the key is revoked, expired or mistyped |
|
|
191
|
+
| `PermissionError` | 403: the key lacks a permission (`error.fields.scope` names it) |
|
|
192
|
+
| `NotFoundError` | 404 |
|
|
193
|
+
| `ConflictError` | 409: an Idempotency-Key, bill number or return number used for a different request |
|
|
194
|
+
| `ValidationError` | 400 or 422 from the API, or an argument refused before sending (`status` is `null`) |
|
|
195
|
+
| `RateLimitError` | 429, once retries are used up |
|
|
196
|
+
| `ApiError` | any other status (5xx, 413, …) once retries are used up |
|
|
197
|
+
| `ConnectionError` | no answer: no connection, DNS failure, reset, timeout (`status` is `null`) |
|
|
198
|
+
| `WebhookSignatureError` | `constructEvent` could not verify a webhook |
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
try {
|
|
202
|
+
await loyaltte.bills.create(body);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
if (error instanceof PermissionError) console.error("missing permission", error.fields?.scope);
|
|
205
|
+
else if (error instanceof ConflictError) console.error("already used for another bill");
|
|
206
|
+
else throw error;
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Retries
|
|
211
|
+
|
|
212
|
+
The SDK retries what is safe to repeat, with exponential backoff and full jitter (1 s, doubling, up to 60 s), up to `maxRetries` times (default 7, the spec's 8 attempts), and waits at least `Retry-After` on a 429 or 503. **One call sleeps at most 300 s in total**: a `Retry-After` longer than what is left of that ends the call at once with the 429/503 error (`error.retryAfter` says how long the server asked).
|
|
213
|
+
|
|
214
|
+
- **Reads** (`key`, `customers.*`) are retried on 408, 425, 429, 500, 502, 503, 504 and on any network error.
|
|
215
|
+
- **Bills and returns** are retried the same way, always with the same `Idempotency-Key`. If the call still fails, `error.idempotencyKey` is the key it used: resend with `{ idempotencyKey: error.idempotencyKey }` to stay safe.
|
|
216
|
+
- **Events, identify and preview** are POSTs the server cannot tell from a new call, so they are retried only when the server certainly did nothing: a connection that was never made, or a 429 that carries `Retry-After`. After a 503, a reset or a timeout you get the error and decide (a resend of events with the same ids is counted once).
|
|
217
|
+
- A **TLS certificate failure** is never retried: `ConnectionError` with code `TLS_VERIFICATION_FAILED`.
|
|
218
|
+
- Any other status (400, 401, 403, 404, 409, 413, …) is never retried. Redirects are not followed.
|
|
219
|
+
|
|
220
|
+
## Develop
|
|
221
|
+
|
|
222
|
+
```sh
|
|
223
|
+
pnpm -C packages/sdk-node build # tsc, twice: dist/esm and dist/cjs, each with .d.ts
|
|
224
|
+
pnpm -C packages/sdk-node type-check
|
|
225
|
+
pnpm -C packages/sdk-node lint
|
|
226
|
+
pnpm -C packages/sdk-node test # unit tests, the webhook and identity vectors, and the server contract against the mock
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
The tests drive this SDK through the language-neutral server contract (`packages/sdk-spec/contract/server/scenarios`) with the harness in `harness/harness.mjs`:
|
|
230
|
+
|
|
231
|
+
```sh
|
|
232
|
+
node packages/sdk-spec/contract/server-run.mjs --harness "node packages/sdk-node/harness/harness.mjs"
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Releases are published by GitHub Actions from [github.com/loyaltte/sdks](https://github.com/loyaltte/sdks) with npm provenance.
|
|
236
|
+
|
|
237
|
+
## License
|
|
238
|
+
|
|
239
|
+
MIT
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { signIdentity } from "./identity.js";
|
|
2
|
+
import { Transport, type FetchLike, type Operation } from "./transport.js";
|
|
3
|
+
import type { Bill, BillParams, BillPreview, BillPreviewParams, BillReturn, CustomerResult, EventsResult, IdentifyParams, IdentifyResult, KeyInfo, LookupParams, LookupResult, Points, ReturnParams, ServerEvent } from "./types.js";
|
|
4
|
+
/** `x-limits.maxEventsPerBatch` in the spec. */
|
|
5
|
+
export declare const MAX_EVENTS_PER_BATCH = 100;
|
|
6
|
+
/** `x-limits.maxBodyBytes` in the spec. */
|
|
7
|
+
export declare const MAX_BODY_BYTES = 65536;
|
|
8
|
+
export interface LoyaltteOptions {
|
|
9
|
+
/** Default `https://api.loyaltte.com`. */
|
|
10
|
+
baseUrl?: string;
|
|
11
|
+
/** Per attempt, in milliseconds. Default 30000. */
|
|
12
|
+
timeoutMs?: number;
|
|
13
|
+
/** Retries after the first attempt. Default 7 (the spec's 8 attempts); 0 turns retries off. */
|
|
14
|
+
maxRetries?: number;
|
|
15
|
+
/** Your own `fetch` (a proxy, a test double). Default: the global one. */
|
|
16
|
+
fetch?: FetchLike;
|
|
17
|
+
/** @internal Tests replace the wait between attempts. */
|
|
18
|
+
sleep?: (ms: number) => Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export interface IdempotencyOptions {
|
|
21
|
+
/**
|
|
22
|
+
* 1-255 characters. Use your own order id and a retry from a crashed process is safe too. When left out the SDK
|
|
23
|
+
* makes a UUID v4 for the call and reuses it on every retry.
|
|
24
|
+
*/
|
|
25
|
+
idempotencyKey?: string;
|
|
26
|
+
}
|
|
27
|
+
/** `lyt_live_abcd…wxyz` -> `lyt_live_...wxyz`: enough to tell keys apart, never the key. */
|
|
28
|
+
export declare function maskKey(key: string): string;
|
|
29
|
+
declare class Resource {
|
|
30
|
+
#private;
|
|
31
|
+
constructor(transport: Transport);
|
|
32
|
+
protected call<T>(operation: Operation, input?: Parameters<Transport["request"]>[1]): Promise<T>;
|
|
33
|
+
}
|
|
34
|
+
/** `GET /v1/key`. */
|
|
35
|
+
declare class KeyResource extends Resource {
|
|
36
|
+
/** Which account and mode the key is for, its permissions and stores. A good first call. */
|
|
37
|
+
retrieve(): Promise<KeyInfo>;
|
|
38
|
+
}
|
|
39
|
+
declare class EventsResource extends Resource {
|
|
40
|
+
#private;
|
|
41
|
+
/**
|
|
42
|
+
* Sends events (`POST /v1/events`). A longer list is sent in order as several requests of at most 100 events and
|
|
43
|
+
* 64 KiB each, and the answers are summed (`accepted`, `duplicates`; `rejected` entries keep the index the server gave,
|
|
44
|
+
* which is within their own batch). An empty list is a ValidationError before anything is sent. If a batch fails the error is raised and the
|
|
45
|
+
* earlier batches stay accepted: give every event an `id` and resend them all, a repeat is counted once.
|
|
46
|
+
*/
|
|
47
|
+
send(events: ServerEvent[]): Promise<EventsResult>;
|
|
48
|
+
}
|
|
49
|
+
declare class VisitorsResource extends Resource {
|
|
50
|
+
/** Ties a visitor's `anonymous_id` to a customer (`POST /v1/identify`); their earlier events become the customer's. */
|
|
51
|
+
identify(params: IdentifyParams): Promise<IdentifyResult>;
|
|
52
|
+
}
|
|
53
|
+
declare class CustomersResource extends Resource {
|
|
54
|
+
/** Finds a customer by `phone`, `email` or `external_id` (`GET /v1/customers/lookup`). `found` is false when there is none. */
|
|
55
|
+
lookup(params: LookupParams): Promise<LookupResult>;
|
|
56
|
+
/** The profile summary (`GET /v1/customers/{id}`): membership, tier, points, lifetime spend, consent. */
|
|
57
|
+
retrieve(customerId: string): Promise<CustomerResult>;
|
|
58
|
+
/** The balance, lifetime earned and redeemed, and points expiring soon (`GET /v1/customers/{id}/points`). */
|
|
59
|
+
points(customerId: string): Promise<Points>;
|
|
60
|
+
}
|
|
61
|
+
declare class BillsResource extends Resource {
|
|
62
|
+
/** Works a bill out without recording it (`POST /v1/bills/preview`). Amounts are decimal strings. */
|
|
63
|
+
preview(body: BillPreviewParams): Promise<BillPreview>;
|
|
64
|
+
/**
|
|
65
|
+
* Records a bill (`POST /v1/bills`), exactly once: the call carries an Idempotency-Key (yours, or one the SDK
|
|
66
|
+
* makes) that every retry reuses, so a lost reply never records the bill twice. A repeat comes back with
|
|
67
|
+
* `replayed: true`.
|
|
68
|
+
*/
|
|
69
|
+
create(body: BillParams, options?: IdempotencyOptions): Promise<Bill>;
|
|
70
|
+
}
|
|
71
|
+
declare class ReturnsResource extends Resource {
|
|
72
|
+
/** Records a full or part return against an earlier bill (`POST /v1/returns`), exactly once like `bills.create`. */
|
|
73
|
+
create(body: ReturnParams, options?: IdempotencyOptions): Promise<BillReturn>;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The Loyaltte server client. Use a SECRET key (`lyt_live_…` / `lyt_test_…`) and only on your server.
|
|
77
|
+
*
|
|
78
|
+
* ```ts
|
|
79
|
+
* const loyaltte = new Loyaltte(process.env.LOYALTTE_SECRET_KEY!);
|
|
80
|
+
* const key = await loyaltte.key.retrieve();
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export declare class Loyaltte {
|
|
84
|
+
/** Signs a customer in for the app SDK: see {@link signIdentity}. */
|
|
85
|
+
static readonly signIdentity: typeof signIdentity;
|
|
86
|
+
/** Checks and parses the webhooks Loyaltte sends. */
|
|
87
|
+
static readonly webhooks: {
|
|
88
|
+
verify: typeof import("./webhooks.js").verify;
|
|
89
|
+
constructEvent: typeof import("./webhooks.js").constructEvent;
|
|
90
|
+
};
|
|
91
|
+
readonly key: KeyResource;
|
|
92
|
+
readonly events: EventsResource;
|
|
93
|
+
readonly visitors: VisitorsResource;
|
|
94
|
+
readonly customers: CustomersResource;
|
|
95
|
+
readonly bills: BillsResource;
|
|
96
|
+
readonly returns: ReturnsResource;
|
|
97
|
+
/** The key, masked: `lyt_live_...wxyz`. The key itself is not kept anywhere you can read it. */
|
|
98
|
+
readonly maskedKey: string;
|
|
99
|
+
constructor(secretKey: string, options?: LoyaltteOptions);
|
|
100
|
+
toString(): string;
|
|
101
|
+
toJSON(): {
|
|
102
|
+
key: string;
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
export {};
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Loyaltte = exports.MAX_BODY_BYTES = exports.MAX_EVENTS_PER_BATCH = void 0;
|
|
4
|
+
exports.maskKey = maskKey;
|
|
5
|
+
const errors_js_1 = require("./errors.js");
|
|
6
|
+
const identity_js_1 = require("./identity.js");
|
|
7
|
+
const transport_js_1 = require("./transport.js");
|
|
8
|
+
const webhooks_js_1 = require("./webhooks.js");
|
|
9
|
+
/** `x-limits.maxEventsPerBatch` in the spec. */
|
|
10
|
+
exports.MAX_EVENTS_PER_BATCH = 100;
|
|
11
|
+
/** `x-limits.maxBodyBytes` in the spec. */
|
|
12
|
+
exports.MAX_BODY_BYTES = 65_536;
|
|
13
|
+
const EVENTS_ENVELOPE_BYTES = '{"events":[]}'.length;
|
|
14
|
+
const DECIMAL = /^\d+(\.\d+)?$/;
|
|
15
|
+
const op = (method, path, retry) => ({
|
|
16
|
+
method,
|
|
17
|
+
path,
|
|
18
|
+
retry,
|
|
19
|
+
});
|
|
20
|
+
const OPS = {
|
|
21
|
+
checkKey: op("GET", "/v1/key", "always"),
|
|
22
|
+
events: op("POST", "/v1/events", "refused-only"),
|
|
23
|
+
identify: op("POST", "/v1/identify", "refused-only"),
|
|
24
|
+
lookup: op("GET", "/v1/customers/lookup", "always"),
|
|
25
|
+
customer: (id) => op("GET", `/v1/customers/${encodeURIComponent(id)}`, "always"),
|
|
26
|
+
points: (id) => op("GET", `/v1/customers/${encodeURIComponent(id)}/points`, "always"),
|
|
27
|
+
preview: op("POST", "/v1/bills/preview", "refused-only"),
|
|
28
|
+
bill: op("POST", "/v1/bills", "idempotency-key"),
|
|
29
|
+
returns: op("POST", "/v1/returns", "idempotency-key"),
|
|
30
|
+
};
|
|
31
|
+
function requireId(id, what, inPath = false) {
|
|
32
|
+
if (typeof id !== "string" || id === "")
|
|
33
|
+
throw (0, errors_js_1.invalidArgument)(`${what} is required.`, { [what]: "required" });
|
|
34
|
+
if (inPath && /^\.+$/.test(id))
|
|
35
|
+
throw (0, errors_js_1.invalidArgument)(`${what} is not valid.`, { [what]: "invalid" });
|
|
36
|
+
return id;
|
|
37
|
+
}
|
|
38
|
+
/** Money is a decimal string: a number (a float) is refused before anything is sent. */
|
|
39
|
+
function requireMoney(value, field) {
|
|
40
|
+
if (typeof value !== "string" || !DECIMAL.test(value))
|
|
41
|
+
throw (0, errors_js_1.invalidArgument)(`${field} must be a decimal string like "4200.00" (never a number: floats lose paise).`, { [field]: "must be a decimal string" });
|
|
42
|
+
}
|
|
43
|
+
function checkBill(body) {
|
|
44
|
+
if (body === null || typeof body !== "object")
|
|
45
|
+
throw (0, errors_js_1.invalidArgument)("body is required.", { body: "required" });
|
|
46
|
+
requireMoney(body.amount, "amount");
|
|
47
|
+
if (body.items !== undefined) {
|
|
48
|
+
if (!Array.isArray(body.items))
|
|
49
|
+
throw (0, errors_js_1.invalidArgument)("items must be a list.", { items: "invalid" });
|
|
50
|
+
body.items.forEach((line, i) => requireMoney(line?.amount, `items[${i}].amount`));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function idempotencyKeyFor(options) {
|
|
54
|
+
const given = options?.idempotencyKey;
|
|
55
|
+
if (given === undefined)
|
|
56
|
+
return (0, transport_js_1.newIdempotencyKey)();
|
|
57
|
+
if (typeof given !== "string" || !/^[\x20-\x7e]{1,255}$/.test(given))
|
|
58
|
+
throw (0, errors_js_1.invalidArgument)("idempotencyKey must be 1 to 255 printable ASCII characters.", {
|
|
59
|
+
idempotencyKey: "invalid",
|
|
60
|
+
});
|
|
61
|
+
return given;
|
|
62
|
+
}
|
|
63
|
+
/** `lyt_live_abcd…wxyz` -> `lyt_live_...wxyz`: enough to tell keys apart, never the key. */
|
|
64
|
+
function maskKey(key) {
|
|
65
|
+
const prefix = /^lyt_(?:live|test)_/.exec(key)?.[0] ?? "";
|
|
66
|
+
return `${prefix}...${key.length >= 12 ? key.slice(-4) : ""}`;
|
|
67
|
+
}
|
|
68
|
+
class Resource {
|
|
69
|
+
#transport;
|
|
70
|
+
constructor(transport) {
|
|
71
|
+
this.#transport = transport;
|
|
72
|
+
}
|
|
73
|
+
call(operation, input) {
|
|
74
|
+
return this.#transport.request(operation, input);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** `GET /v1/key`. */
|
|
78
|
+
class KeyResource extends Resource {
|
|
79
|
+
/** Which account and mode the key is for, its permissions and stores. A good first call. */
|
|
80
|
+
retrieve() {
|
|
81
|
+
return this.call(OPS.checkKey);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
class EventsResource extends Resource {
|
|
85
|
+
/**
|
|
86
|
+
* Sends events (`POST /v1/events`). A longer list is sent in order as several requests of at most 100 events and
|
|
87
|
+
* 64 KiB each, and the answers are summed (`accepted`, `duplicates`; `rejected` entries keep the index the server gave,
|
|
88
|
+
* which is within their own batch). An empty list is a ValidationError before anything is sent. If a batch fails the error is raised and the
|
|
89
|
+
* earlier batches stay accepted: give every event an `id` and resend them all, a repeat is counted once.
|
|
90
|
+
*/
|
|
91
|
+
send(events) {
|
|
92
|
+
if (!Array.isArray(events) || events.length === 0)
|
|
93
|
+
throw (0, errors_js_1.invalidArgument)("Send at least one event.", { events: "empty" });
|
|
94
|
+
const batches = [];
|
|
95
|
+
let current = [];
|
|
96
|
+
let size = EVENTS_ENVELOPE_BYTES;
|
|
97
|
+
events.forEach((event, i) => {
|
|
98
|
+
const bytes = Buffer.byteLength(JSON.stringify(event) ?? "null", "utf8") + 1; // + the comma
|
|
99
|
+
if (bytes + EVENTS_ENVELOPE_BYTES > exports.MAX_BODY_BYTES)
|
|
100
|
+
throw (0, errors_js_1.invalidArgument)(`Event ${i} is larger than ${exports.MAX_BODY_BYTES} bytes.`, {
|
|
101
|
+
events: "too_large",
|
|
102
|
+
});
|
|
103
|
+
if (current.length > 0 &&
|
|
104
|
+
(current.length >= exports.MAX_EVENTS_PER_BATCH || size + bytes > exports.MAX_BODY_BYTES)) {
|
|
105
|
+
batches.push(current);
|
|
106
|
+
current = [];
|
|
107
|
+
size = EVENTS_ENVELOPE_BYTES;
|
|
108
|
+
}
|
|
109
|
+
current.push(event);
|
|
110
|
+
size += bytes;
|
|
111
|
+
});
|
|
112
|
+
batches.push(current);
|
|
113
|
+
return this.#sendAll(batches);
|
|
114
|
+
}
|
|
115
|
+
async #sendAll(batches) {
|
|
116
|
+
const total = {
|
|
117
|
+
accepted: 0,
|
|
118
|
+
duplicates: 0,
|
|
119
|
+
rejected: [],
|
|
120
|
+
dropped_properties: [],
|
|
121
|
+
};
|
|
122
|
+
for (const batch of batches) {
|
|
123
|
+
const answer = await this.call(OPS.events, { body: { events: batch } });
|
|
124
|
+
total.accepted += answer.accepted ?? 0;
|
|
125
|
+
total.duplicates += answer.duplicates ?? 0;
|
|
126
|
+
total.rejected.push(...(answer.rejected ?? []));
|
|
127
|
+
total.dropped_properties.push(...(answer.dropped_properties ?? []));
|
|
128
|
+
}
|
|
129
|
+
return total;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
class VisitorsResource extends Resource {
|
|
133
|
+
/** Ties a visitor's `anonymous_id` to a customer (`POST /v1/identify`); their earlier events become the customer's. */
|
|
134
|
+
identify(params) {
|
|
135
|
+
if (!params || typeof params.anonymous_id !== "string" || params.anonymous_id === "")
|
|
136
|
+
throw (0, errors_js_1.invalidArgument)("anonymous_id is required.", { anonymous_id: "required" });
|
|
137
|
+
if (!params.phone && !params.email && !params.external_id)
|
|
138
|
+
throw (0, errors_js_1.invalidArgument)("Give phone, email or external_id.", { customer: "required" });
|
|
139
|
+
return this.call(OPS.identify, { body: params });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
class CustomersResource extends Resource {
|
|
143
|
+
/** Finds a customer by `phone`, `email` or `external_id` (`GET /v1/customers/lookup`). `found` is false when there is none. */
|
|
144
|
+
lookup(params) {
|
|
145
|
+
const { phone, email, external_id } = params ?? {};
|
|
146
|
+
if (!phone && !email && !external_id)
|
|
147
|
+
throw (0, errors_js_1.invalidArgument)("Give phone, email or external_id.", { customer: "required" });
|
|
148
|
+
return this.call(OPS.lookup, { query: { phone, email, external_id } });
|
|
149
|
+
}
|
|
150
|
+
/** The profile summary (`GET /v1/customers/{id}`): membership, tier, points, lifetime spend, consent. */
|
|
151
|
+
retrieve(customerId) {
|
|
152
|
+
return this.call(OPS.customer(requireId(customerId, "customerId", true)));
|
|
153
|
+
}
|
|
154
|
+
/** The balance, lifetime earned and redeemed, and points expiring soon (`GET /v1/customers/{id}/points`). */
|
|
155
|
+
points(customerId) {
|
|
156
|
+
return this.call(OPS.points(requireId(customerId, "customerId", true)));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
class BillsResource extends Resource {
|
|
160
|
+
/** Works a bill out without recording it (`POST /v1/bills/preview`). Amounts are decimal strings. */
|
|
161
|
+
preview(body) {
|
|
162
|
+
checkBill(body);
|
|
163
|
+
return this.call(OPS.preview, { body });
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Records a bill (`POST /v1/bills`), exactly once: the call carries an Idempotency-Key (yours, or one the SDK
|
|
167
|
+
* makes) that every retry reuses, so a lost reply never records the bill twice. A repeat comes back with
|
|
168
|
+
* `replayed: true`.
|
|
169
|
+
*/
|
|
170
|
+
create(body, options) {
|
|
171
|
+
checkBill(body);
|
|
172
|
+
requireId(body.bill_number, "bill_number");
|
|
173
|
+
return this.call(OPS.bill, { body, idempotencyKey: idempotencyKeyFor(options) });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
class ReturnsResource extends Resource {
|
|
177
|
+
/** Records a full or part return against an earlier bill (`POST /v1/returns`), exactly once like `bills.create`. */
|
|
178
|
+
create(body, options) {
|
|
179
|
+
if (body === null || typeof body !== "object")
|
|
180
|
+
throw (0, errors_js_1.invalidArgument)("body is required.", { body: "required" });
|
|
181
|
+
requireId(body.bill_number, "bill_number");
|
|
182
|
+
requireId(body.return_number, "return_number");
|
|
183
|
+
requireMoney(body.amount, "amount");
|
|
184
|
+
return this.call(OPS.returns, { body, idempotencyKey: idempotencyKeyFor(options) });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const DEFAULT_BASE_URL = "https://api.loyaltte.com";
|
|
188
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
189
|
+
/** https only (the key travels in every request); plain http just for localhost, in tests. */
|
|
190
|
+
function checkBaseUrl(value) {
|
|
191
|
+
let url;
|
|
192
|
+
try {
|
|
193
|
+
url = new URL(value);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
throw (0, errors_js_1.invalidArgument)("baseUrl is not a URL.", { baseUrl: "invalid" });
|
|
197
|
+
}
|
|
198
|
+
const ok = url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.has(url.hostname));
|
|
199
|
+
if (!ok || url.username || url.password || url.search || url.hash)
|
|
200
|
+
throw (0, errors_js_1.invalidArgument)("baseUrl must be an https:// address without credentials, query or fragment (plain http is only for localhost).", { baseUrl: "invalid" });
|
|
201
|
+
return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* The Loyaltte server client. Use a SECRET key (`lyt_live_…` / `lyt_test_…`) and only on your server.
|
|
205
|
+
*
|
|
206
|
+
* ```ts
|
|
207
|
+
* const loyaltte = new Loyaltte(process.env.LOYALTTE_SECRET_KEY!);
|
|
208
|
+
* const key = await loyaltte.key.retrieve();
|
|
209
|
+
* ```
|
|
210
|
+
*/
|
|
211
|
+
class Loyaltte {
|
|
212
|
+
/** Signs a customer in for the app SDK: see {@link signIdentity}. */
|
|
213
|
+
static signIdentity = identity_js_1.signIdentity;
|
|
214
|
+
/** Checks and parses the webhooks Loyaltte sends. */
|
|
215
|
+
static webhooks = webhooks_js_1.webhooks;
|
|
216
|
+
key;
|
|
217
|
+
events;
|
|
218
|
+
visitors;
|
|
219
|
+
customers;
|
|
220
|
+
bills;
|
|
221
|
+
returns;
|
|
222
|
+
/** The key, masked: `lyt_live_...wxyz`. The key itself is not kept anywhere you can read it. */
|
|
223
|
+
maskedKey;
|
|
224
|
+
constructor(secretKey, options = {}) {
|
|
225
|
+
if (typeof secretKey !== "string" || secretKey.trim() === "")
|
|
226
|
+
throw new errors_js_1.LoyaltteError({
|
|
227
|
+
message: "Pass your secret key (lyt_live_… or lyt_test_…) from Settings › API keys.",
|
|
228
|
+
code: "INVALID_KEY",
|
|
229
|
+
});
|
|
230
|
+
if (secretKey.startsWith("lak_"))
|
|
231
|
+
throw new errors_js_1.LoyaltteError({
|
|
232
|
+
message: "That is a publishable key (lak_…): it is for apps and web pages and cannot call the Server API. Use a secret key (lyt_live_… or lyt_test_…).",
|
|
233
|
+
code: "INVALID_KEY",
|
|
234
|
+
});
|
|
235
|
+
if (secretKey.startsWith("lps_"))
|
|
236
|
+
throw new errors_js_1.LoyaltteError({
|
|
237
|
+
message: "That is an identify secret (lps_…): it signs sign-ins (Loyaltte.signIdentity) and is not an API key. Use a secret key (lyt_live_… or lyt_test_…).",
|
|
238
|
+
code: "INVALID_KEY",
|
|
239
|
+
});
|
|
240
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
241
|
+
if (!fetchImpl)
|
|
242
|
+
throw new errors_js_1.LoyaltteError({
|
|
243
|
+
message: "This runtime has no global fetch (Node 18 or newer has it). Pass one as options.fetch.",
|
|
244
|
+
code: "NO_FETCH",
|
|
245
|
+
});
|
|
246
|
+
const maxRetries = options.maxRetries ?? transport_js_1.RETRY.maxAttempts - 1;
|
|
247
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
248
|
+
if (!Number.isInteger(maxRetries) || maxRetries < 0)
|
|
249
|
+
throw (0, errors_js_1.invalidArgument)("maxRetries is a whole number, 0 or more.", { maxRetries: "invalid" });
|
|
250
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
|
|
251
|
+
throw (0, errors_js_1.invalidArgument)("timeoutMs is milliseconds, more than 0.", { timeoutMs: "invalid" });
|
|
252
|
+
const transport = new transport_js_1.Transport({
|
|
253
|
+
secretKey,
|
|
254
|
+
baseUrl: checkBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL),
|
|
255
|
+
timeoutMs,
|
|
256
|
+
maxRetries,
|
|
257
|
+
fetch: fetchImpl,
|
|
258
|
+
sleep: options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
259
|
+
});
|
|
260
|
+
this.maskedKey = maskKey(secretKey);
|
|
261
|
+
this.key = new KeyResource(transport);
|
|
262
|
+
this.events = new EventsResource(transport);
|
|
263
|
+
this.visitors = new VisitorsResource(transport);
|
|
264
|
+
this.customers = new CustomersResource(transport);
|
|
265
|
+
this.bills = new BillsResource(transport);
|
|
266
|
+
this.returns = new ReturnsResource(transport);
|
|
267
|
+
}
|
|
268
|
+
toString() {
|
|
269
|
+
return `Loyaltte(${this.maskedKey})`;
|
|
270
|
+
}
|
|
271
|
+
toJSON() {
|
|
272
|
+
return { key: this.maskedKey };
|
|
273
|
+
}
|
|
274
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
275
|
+
return this.toString();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
exports.Loyaltte = Loyaltte;
|