@clikgate/node 2.0.0 → 2.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 +35 -0
- package/README.md +126 -6
- package/SECURITY.md +2 -1
- package/dist/cjs/client.d.ts +54 -10
- package/dist/cjs/client.js +75 -16
- package/dist/cjs/currency.d.ts +7 -0
- package/dist/cjs/currency.js +75 -0
- package/dist/cjs/customer-id.d.ts +26 -0
- package/dist/cjs/customer-id.js +52 -0
- package/dist/cjs/enums.js +1 -1
- package/dist/cjs/errors.d.ts +1 -1
- package/dist/cjs/event-types.d.ts +108 -0
- package/dist/cjs/event-types.js +109 -0
- package/dist/cjs/express.d.ts +11 -2
- package/dist/cjs/express.js +3 -2
- package/dist/cjs/fastify.d.ts +4 -1
- package/dist/cjs/fastify.js +3 -2
- package/dist/cjs/generated/index.d.ts +2015 -83
- package/dist/cjs/generated/index.js +83 -3
- package/dist/cjs/identity.d.ts +12 -2
- package/dist/cjs/identity.js +37 -3
- package/dist/cjs/index.d.ts +11 -1
- package/dist/cjs/index.js +21 -1
- package/dist/cjs/installation.d.ts +47 -0
- package/dist/cjs/installation.js +83 -0
- package/dist/cjs/known-customers.d.ts +45 -0
- package/dist/cjs/known-customers.js +95 -0
- package/dist/cjs/lookups.d.ts +128 -0
- package/dist/cjs/lookups.js +149 -0
- package/dist/cjs/models.d.ts +342 -0
- package/dist/cjs/models.js +2 -0
- package/dist/cjs/next.d.ts +22 -0
- package/dist/cjs/next.js +20 -0
- package/dist/cjs/pager.d.ts +5 -0
- package/dist/cjs/pager.js +40 -0
- package/dist/cjs/referrals.d.ts +169 -0
- package/dist/cjs/referrals.js +208 -0
- package/dist/cjs/resources.d.ts +34 -5
- package/dist/cjs/resources.js +43 -42
- package/dist/cjs/types.d.ts +57 -10
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/webhooks.d.ts +3 -2
- package/dist/cjs/webhooks.js +43 -2
- package/dist/esm/client.d.ts +54 -10
- package/dist/esm/client.js +75 -16
- package/dist/esm/currency.d.ts +7 -0
- package/dist/esm/currency.js +67 -0
- package/dist/esm/customer-id.d.ts +26 -0
- package/dist/esm/customer-id.js +47 -0
- package/dist/esm/enums.js +1 -1
- package/dist/esm/errors.d.ts +1 -1
- package/dist/esm/event-types.d.ts +108 -0
- package/dist/esm/event-types.js +106 -0
- package/dist/esm/express.d.ts +11 -2
- package/dist/esm/express.js +3 -2
- package/dist/esm/fastify.d.ts +4 -1
- package/dist/esm/fastify.js +3 -2
- package/dist/esm/generated/index.d.ts +2015 -83
- package/dist/esm/generated/index.js +80 -1
- package/dist/esm/identity.d.ts +12 -2
- package/dist/esm/identity.js +36 -3
- package/dist/esm/index.d.ts +11 -1
- package/dist/esm/index.js +6 -0
- package/dist/esm/installation.d.ts +47 -0
- package/dist/esm/installation.js +77 -0
- package/dist/esm/known-customers.d.ts +45 -0
- package/dist/esm/known-customers.js +90 -0
- package/dist/esm/lookups.d.ts +128 -0
- package/dist/esm/lookups.js +142 -0
- package/dist/esm/models.d.ts +342 -0
- package/dist/esm/models.js +1 -0
- package/dist/esm/next.d.ts +22 -0
- package/dist/esm/next.js +19 -0
- package/dist/esm/pager.d.ts +5 -0
- package/dist/esm/pager.js +36 -0
- package/dist/esm/referrals.d.ts +169 -0
- package/dist/esm/referrals.js +204 -0
- package/dist/esm/resources.d.ts +34 -5
- package/dist/esm/resources.js +43 -42
- package/dist/esm/types.d.ts +57 -10
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/webhooks.d.ts +3 -2
- package/dist/esm/webhooks.js +42 -2
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,41 @@
|
|
|
3
3
|
All notable changes to this package. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package uses [semantic versioning](https://semver.org/). Deprecations are announced at least 6 months ahead, and Node versions are dropped only after their end of life.
|
|
4
4
|
|
|
5
5
|
|
|
6
|
+
## [2.1.0] - unreleased
|
|
7
|
+
|
|
8
|
+
### Typed referrals, webhook events, privacy, people, installs and codes
|
|
9
|
+
|
|
10
|
+
Additive: nothing is removed or renamed, and nothing changes on the wire.
|
|
11
|
+
|
|
12
|
+
- **Added:** `identifyUser({ installation })` also takes the parsed `Installation` the framework helpers return (`req.clikgate.installation`, `getInstallation(...)`), not only the raw header string, with the same strict check.
|
|
13
|
+
- **Added:** `clikgate.referrals`: `getOrCreateReferrer(programId, { customerId, displayName?, externalCode? })` (`created` is true when the referrer is new), `getReferrer`, `findReferrer(programId, { customerId } | { code })` (`null` when there is none), `get`, `list` (auto-paging) and `listPage`, `qualify`, `disqualify`, `completeStep` (`occurredAt` is required), `importReferrers` (1000 rows per request, one job per request), `blockReferrer`, `unblockReferrer` and `updateReferrer`. Results are typed: `Referrer`, `Referral`, `RewardInfo`, `Job`.
|
|
14
|
+
- **Added:** reward sides keep `amount_minor` and gain `amount`, the same value in normal units as a decimal string with the currency's digits (`50000` NGN is `"500.00"`). `minorToAmount()` and `currencyExponent()` are exported.
|
|
15
|
+
- **Added:** `customerId` next to `customer_user_id` on referrers and on a referral's `referrer` and `referee`.
|
|
16
|
+
- **Added:** verified webhook events have `asReferral()`, `asReferrer()`, `asGoalEvent()`, `asInstall()`, `asPayment()`, `asConversion()` and `asDeviceChange()` (`person.device_changed`) (each `null` for an event of another family) and `typed()`, which gives the event as `TypedWebhookEvent`, a union narrowed by `type`. The accessors are non-enumerable, so `JSON.stringify(event)` and `event.data` are unchanged.
|
|
17
|
+
- **Added:** `EventType`, every webhook event type as a string constant (`EventType.ReferralQualified === 'referral.qualified'`).
|
|
18
|
+
- **Added:** `clikgate.privacy` (`createRequest`, `getRequest`), `clikgate.people` (`get`, `search` (auto-paging) and `searchPage`, `setLabel`), `clikgate.installs` (`getByCustomer`, `getByInstallation`) and `clikgate.codes.redeem` (with `subject`, `agentId` and `location`), with typed results.
|
|
19
|
+
- **Added:** `links.archive`, `links.pause`, `links.resume` and `links.getByReference`. `links.create` and `links.update` take the typed `LinkCreateParams` / `LinkUpdateParams`; plain objects still work. `Link` has every field of the API's link.
|
|
20
|
+
|
|
21
|
+
## [2.0.3] - unreleased
|
|
22
|
+
|
|
23
|
+
### Identify users with the installation header
|
|
24
|
+
|
|
25
|
+
- **Added:** `identifyUser({ installation })` takes the raw `Clikgate-Installation` header your app sends (`<app_id>:<installation_id>`, from the mobile SDK) and fills `appId` and `installationId` from it, so your server never needs to know which Clikgate app ID belongs to which platform. A missing or invalid header is ignored, never sent and never logged. `installationId` given explicitly wins over the header.
|
|
26
|
+
- **Changed:** `appId` is optional with `installationId`: Clikgate finds the app. `appId` without `installationId` is still refused locally (`invalid_request`, param `installation_id`). Calls that send both behave as before.
|
|
27
|
+
- **Added:** `parseInstallationHeader(value)` → `{ appId, installationId }` or `null` (strict: `app_…`, one colon, a lowercase UUID, at most 128 characters, trimmed; never throws), `installationFromRequest(req)` and `INSTALLATION_HEADER`.
|
|
28
|
+
- **Added:** `req.clikgate.installation` from the Express middleware, `request.clikgate.installation` from the Fastify plugin, and `getInstallation(await headers())` from `@clikgate/node/next`.
|
|
29
|
+
- **Docs:** when the installation ID is active in several of your apps, the API answers `409 installation_in_several_apps` (a `ConflictError`, param `app_id`): send `appId` too. Call `identifyUser` only after your own sign-in check, with your signed-in user's ID; never read the customer ID from the request.
|
|
30
|
+
|
|
31
|
+
## [2.0.1] - unreleased
|
|
32
|
+
|
|
33
|
+
### Existing users
|
|
34
|
+
|
|
35
|
+
- **Added:** `createIdentityToken(customerId, { customerSince })` (also `clikgate.createIdentityToken`): with an account date (`Date` or Unix seconds) the token is version 2, `signature.issuedAt.customerSince`, so Clikgate can tell a customer from before you added Clikgate from a new one (referrals, new customers). Account dates before 1990 or after the issue time are a local `invalid_argument` (param `customer_since`). Tested against the shared version 2 vectors.
|
|
36
|
+
- **Added:** `identifyUser({ customerId, customerSince, customerSinceReplace })`: the account date from your server (`'YYYY-MM-DD'`, an ISO 8601 date-time, a `Date` or Unix seconds). `PersonIdentified` gains `customer_since_ignored` and `customer_id_warning`.
|
|
37
|
+
- **Added:** `clikgate.knownCustomers.import(customers)` (batches of 10,000, counts summed; refused rows counted by reason, never returned) and `clikgate.knownCustomers.remove(customerId)`.
|
|
38
|
+
- **Added:** `canonicalCustomerId()` and `customerIdWarning()`: the canonical customer ID (NFC, trimmed) and why an ID looks like an email, phone number or national ID, against the shared vectors.
|
|
39
|
+
- Refused in private mode: the guard refuses `customer_since`, and known customers raise a conflict with code `private_mode_conflict` before any request. Customer IDs and dates are never logged. Guide: https://clikgate.com/docs/identify-users.
|
|
40
|
+
|
|
6
41
|
## [2.0.0] - unreleased
|
|
7
42
|
|
|
8
43
|
### Breaking: track() removed in favour of goal()
|
package/README.md
CHANGED
|
@@ -50,11 +50,61 @@ The email is trimmed and lowercased. The phone must include its country code (`+
|
|
|
50
50
|
|
|
51
51
|
In private mode, hash on your own server: Clikgate never hashes for you there.
|
|
52
52
|
|
|
53
|
+
## End to end
|
|
54
|
+
|
|
55
|
+
One Express app that uses only the typed methods: the identity token, the installation header, goals, payments, a
|
|
56
|
+
webhook and a referrer.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import express from 'express';
|
|
60
|
+
import { Clikgate, EventType, Provider, createIdentityToken, webhooks } from '@clikgate/node';
|
|
61
|
+
import { clikgateMiddleware } from '@clikgate/node/express';
|
|
62
|
+
|
|
63
|
+
const clikgate = new Clikgate(); // CLIKGATE_API_KEY
|
|
64
|
+
const PROGRAM_ID = 'rpg_01J…'; // your referral program
|
|
65
|
+
const app = express();
|
|
66
|
+
|
|
67
|
+
// Webhooks need the raw body: register this before express.json()
|
|
68
|
+
app.post('/webhooks/clikgate', express.raw({ type: 'application/json' }), async (req, res) => {
|
|
69
|
+
const event = webhooks.verify(req.body, req.get('Clikgate-Signature'), process.env.CLIKGATE_WEBHOOK_SECRET!);
|
|
70
|
+
const referral = event.asReferral(); // null for other event types
|
|
71
|
+
if (referral && event.type === EventType.ReferralQualified) {
|
|
72
|
+
const reward = referral.reward_snapshot?.referrer; // amount_minor 50000 → amount "500.00"
|
|
73
|
+
await creditWallet(referral.referrer.customerId, reward?.amount, reward?.currency);
|
|
74
|
+
}
|
|
75
|
+
res.sendStatus(200); // deliveries are at-least-once: dedupe on event.id
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
app.use(express.json(), clikgateMiddleware(clikgate));
|
|
79
|
+
|
|
80
|
+
app.post('/login', async (req, res) => {
|
|
81
|
+
const user = await signIn(req.body); // your own sign-in check first
|
|
82
|
+
// Path B: the app's Clikgate-Installation header; the customer ID is always your signed-in user
|
|
83
|
+
if (req.clikgate.installation) await clikgate.identifyUser({ installation: req.clikgate.installation, customerId: user.id });
|
|
84
|
+
// Path A: an identity token the app passes to the mobile SDK
|
|
85
|
+
const referrer = await clikgate.referrals.getOrCreateReferrer(PROGRAM_ID, { customerId: user.id, displayName: user.firstName });
|
|
86
|
+
res.json({ user, clikgateIdentityToken: createIdentityToken(user.id), referralCode: referrer.code, referralUrl: referrer.url });
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
app.post('/accounts', async (req, res) => {
|
|
90
|
+
const account = await openAccount(req.body);
|
|
91
|
+
clikgate.goal('account_opened', { clickId: req.clikgate.clickId, reference: account.id }); // never throws
|
|
92
|
+
res.json(account);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
app.post('/orders/:ref/verify', async (req, res) => {
|
|
96
|
+
const verified = await paystack.verify(req.params.ref); // your own verification with the gateway
|
|
97
|
+
await clikgate.payments.fromPaystack(verified, { goal: 'order_paid' });
|
|
98
|
+
// or: await clikgate.goals.send('order_paid', { reference: req.params.ref, provider: Provider.Paystack, value: '7500', currency: 'NGN' });
|
|
99
|
+
res.sendStatus(204);
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
53
103
|
## Identify your users
|
|
54
104
|
|
|
55
105
|
Two ways to tell Clikgate which of your users is using the app. Full guide: https://clikgate.com/docs/identify-users. The customer ID is your own user ID from your database, never an email, phone number or ID number. Anonymous users don't need either path.
|
|
56
106
|
|
|
57
|
-
**Path A (default): identity token.** Create the identity secret in
|
|
107
|
+
**Path A (default): identity token.** Create the identity secret in Developers › SDKs › your app › Set up identity › Identity secret and store it as `CLIKGATE_IDENTITY_SECRET` on your server only. `createIdentityToken(customerId, { appId? })` (also `clikgate.createIdentityToken()`, with the `identitySecret` / `identitySecrets` options) signs a token with no network call; return it in the responses the app already calls, and the app passes it to the mobile SDK's `identifyUser()`. Tokens last 30 days by default and are never force-refreshed. Throws `ClikgateServerOnlyError` in a browser or React Native.
|
|
58
108
|
|
|
59
109
|
```ts
|
|
60
110
|
import { createIdentityToken } from '@clikgate/node';
|
|
@@ -63,11 +113,37 @@ res.json({ user, clikgateIdentityToken: createIdentityToken(user.id) }); // re
|
|
|
63
113
|
createIdentityToken(user.id, { appId: 'app_…' }); // several apps: CLIKGATE_IDENTITY_SECRETS
|
|
64
114
|
```
|
|
65
115
|
|
|
66
|
-
**Path B: installation
|
|
116
|
+
**Path B: the installation header, no secret or token.** The mobile SDK gives your app a `Clikgate-Installation` header (`<app_id>:<installation_id>`, not a secret), which the app sends to your server with its sign-in request and signed-in requests. After your own sign-in check succeeds, and at every signed-in app open, pass it to `identifyUser` with your signed-in user's ID. Your server never needs to know which Clikgate app ID belongs to which platform. Clikgate accepts installations active in the last 7 days.
|
|
117
|
+
|
|
118
|
+
- **The customer ID always comes from your own authenticated user.** The header only names the app installation. Call `identifyUser` only after your sign-in check succeeds, and never read the customer ID from the request.
|
|
119
|
+
- **A missing or invalid header is ignored** (`null`, never an error or a log line): skip the call. Parsing is strict: `app_…`, one colon, a lowercase UUID, at most 128 characters, trimmed.
|
|
120
|
+
- **`appId` is optional.** With only an installation ID, Clikgate finds the app. If the same installation ID is active in several of your apps (iOS apps sharing a Keychain access group can share one), the API answers `409 installation_in_several_apps`, a `ConflictError` with param `app_id`: send `appId` too.
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import { clikgateMiddleware } from '@clikgate/node/express';
|
|
124
|
+
app.use(clikgateMiddleware(clikgate)); // also reads the Clikgate-Installation header
|
|
125
|
+
app.post('/login', async (req, res) => {
|
|
126
|
+
const user = await signIn(req.body); // your own sign-in check first
|
|
127
|
+
if (req.clikgate.installation) {
|
|
128
|
+
await clikgate.identifyUser({ installation: req.clikgate.installation, customerId: user.id }); // the parsed installation
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// Without the middleware: pass the raw header value (ignored when missing or invalid)
|
|
133
|
+
await clikgate.identifyUser({ installation: req.get('Clikgate-Installation'), customerId: user.id });
|
|
134
|
+
// Or parse it yourself: { appId, installationId } or null
|
|
135
|
+
const installation = parseInstallationHeader(req.get('Clikgate-Installation'));
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## Customers from before Clikgate
|
|
139
|
+
|
|
140
|
+
Tell Clikgate who was already your customer before you added it, so they are never counted as a referral or a new customer. Send the account's creation date with the identity token (version 2) or from your server, and import the rest of your existing customers once. Use your own customer IDs, never emails or phone numbers: Clikgate stores a keyed fingerprint of each imported ID, not the ID itself. Not available in private mode. Guide: https://clikgate.com/docs/identify-users.
|
|
67
141
|
|
|
68
142
|
```ts
|
|
69
|
-
|
|
70
|
-
|
|
143
|
+
res.json({ user, clikgateIdentityToken: createIdentityToken(user.id, { customerSince: user.createdAt }) }); // version 2
|
|
144
|
+
await clikgate.identifyUser({ installation: req.get('Clikgate-Installation'), customerId: user.id, customerSince: user.createdAt });
|
|
145
|
+
const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]); // batches of 10,000
|
|
146
|
+
console.log(result.accepted, result.refused_by_reason); // refused rows are counted by reason, never returned
|
|
71
147
|
```
|
|
72
148
|
|
|
73
149
|
## People: identify a user and label them
|
|
@@ -99,6 +175,7 @@ clikgate.goal('account_opened', { clickId: application.clickId, reference: appli
|
|
|
99
175
|
- **Fastify:** `await app.register(clikgatePlugin, { client: clikgate })` from `@clikgate/node/fastify`, then read `request.clikgate.clickId`.
|
|
100
176
|
- **Next.js 16+:** in `proxy.ts`, `export { clikgateProxy as proxy } from '@clikgate/node/next'`. Then read it with `getClickId(await cookies())`.
|
|
101
177
|
- **Without a framework:** `clikgate.clickIds.fromRequest(req)` and `clikgate.clickIds.persist(res, clickId)`.
|
|
178
|
+
- **The app's installation** (`Clikgate-Installation` header, for `identifyUser`): Express `req.clikgate.installation`, Fastify `request.clikgate.installation`, Next.js `getInstallation(await headers())` from `@clikgate/node/next`, and without a framework `installationFromRequest(req)` or `parseInstallationHeader(value)`. Each is `{ appId, installationId }` or `null`, and can be passed to `identifyUser` as `installation`, like the raw header.
|
|
102
179
|
- **From payment payloads** (Paystack, Flutterwave, Shopify, WooCommerce): `clikgate.clickIds.fromPaymentMetadata(payload)`.
|
|
103
180
|
|
|
104
181
|
## Keep the click ID longer (Safari)
|
|
@@ -207,6 +284,13 @@ app.post('/webhooks/clikgate', express.raw({ type: 'application/json' }), (req,
|
|
|
207
284
|
});
|
|
208
285
|
```
|
|
209
286
|
|
|
287
|
+
- Typed accessors read `event.data.object`: `asReferral()` (`referral.*`), `asReferrer()` (`referrer.*`),
|
|
288
|
+
`asGoalEvent()` (`goal.completed`, `goal.reversed`), `asInstall()` (`install.*`), `asPayment()` (`payment.*`) and
|
|
289
|
+
`asConversion()` (`conversion.*`) and `asDeviceChange()` (`person.device_changed`). Each returns `null` for an event of another family, so the same handler can take
|
|
290
|
+
every event. `event.data` stays the raw payload.
|
|
291
|
+
- `EventType` holds every event type as a string (`EventType.ReferralQualified === 'referral.qualified'`); `event.type`
|
|
292
|
+
stays a plain string, so a type added later is never an error. `event.typed()` gives the same event as a union
|
|
293
|
+
narrowed by `type`.
|
|
210
294
|
- Use `webhooks.verifyAny(body, header, [newSecret, oldSecret])` while you rotate your own secrets.
|
|
211
295
|
- Next.js route handlers: pass `await request.text()` as the body.
|
|
212
296
|
|
|
@@ -240,6 +324,42 @@ const ada = await clikgate.api.analytics.analyticsSummary({ from: '2026-10-01T00
|
|
|
240
324
|
|
|
241
325
|
- With a `cg_test_` key, links use `dev.ciz.to`. Their destination may be one of Clikgate's test pages: `clikgate-test:inspect`, `clikgate-test:checkout`, `clikgate-test:app-open` or `clikgate-test:store`.
|
|
242
326
|
- A locked link throws `LinkLockedError`.
|
|
327
|
+
- `links.create` and `links.update` take `LinkCreateParams` / `LinkUpdateParams` (the API's fields, typed); plain
|
|
328
|
+
objects still work. `Link` has every field of the API's link.
|
|
329
|
+
- `links.archive(id)`, `links.pause(id)`, `links.resume(id)` and `links.getByReference('order-1001')` return the link.
|
|
330
|
+
|
|
331
|
+
## Referrals
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
const referrer = await clikgate.referrals.getOrCreateReferrer(programId, { customerId: user.id, displayName: user.firstName });
|
|
335
|
+
referrer.code; referrer.url; referrer.created; // created: true when it was just made
|
|
336
|
+
const existing = await clikgate.referrals.findReferrer(programId, { code: 'ADA42' }); // null when there is none
|
|
337
|
+
|
|
338
|
+
for await (const referral of clikgate.referrals.list({ programId, status: 'qualified' })) {
|
|
339
|
+
console.log(referral.referee.customerId, referral.reward_snapshot?.referrer?.amount);
|
|
340
|
+
}
|
|
341
|
+
await clikgate.referrals.completeStep(referralId, { goal: 'first_order', occurredAt: order.paidAt, value: '1500.50', currency: 'NGN' });
|
|
342
|
+
await clikgate.referrals.qualify(referralId, { reason: 'Checked by support' }); // or disqualify
|
|
343
|
+
const jobs = await clikgate.referrals.importReferrers(programId, [{ customerId: 'user-42', externalCode: 'ADA-OLD' }]);
|
|
344
|
+
await clikgate.referrals.blockReferrer(referrer.id, { reason: 'Fake installs' }); // unblockReferrer, updateReferrer
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
- Results are typed (`Referrer`, `Referral`, `RewardInfo`, `Job`) with the API's keys. The SDK adds `customerId` next
|
|
348
|
+
to `customer_user_id` on referrers and on a referral's `referrer` and `referee`.
|
|
349
|
+
- Reward sides keep `amount_minor` (minor units) and gain `amount`, the same value in normal units as a decimal string
|
|
350
|
+
with the currency's digits (`50000` NGN is `"500.00"`, `1500` JPY is `"1500"`). Clikgate never pays rewards.
|
|
351
|
+
- `importReferrers` sends 1000 rows per request and returns one job per request.
|
|
352
|
+
|
|
353
|
+
## Privacy, people, installs and codes
|
|
354
|
+
|
|
355
|
+
```ts
|
|
356
|
+
await clikgate.privacy.createRequest({ type: 'erasure', subjectType: 'customer_user', subjectId: user.id });
|
|
357
|
+
const person = await clikgate.people.get('per_01J…');
|
|
358
|
+
for await (const p of clikgate.people.search('Ada')) console.log(p.id, p.label); // the text is sent in the body
|
|
359
|
+
await clikgate.people.setLabel(person.id, 'Ada (VIP)');
|
|
360
|
+
const install = await clikgate.installs.getByCustomer(user.id, { appId: 'app_01J…' }); // or getByInstallation
|
|
361
|
+
const redemption = await clikgate.codes.redeem({ externalId: 'POS-991', code: 'ADA42', channel: 'pos', agentId: 'agent-9' });
|
|
362
|
+
```
|
|
243
363
|
|
|
244
364
|
## Errors
|
|
245
365
|
|
|
@@ -285,7 +405,7 @@ Every error extends `ClikgateError`, with `code`, `httpStatus`, `requestId` and
|
|
|
285
405
|
|
|
286
406
|
`clikgate.api.<resource>.<operation>()` covers every API-key operation, generated from the OpenAPI spec (for example `clikgate.api.campaigns.listCampaigns()`). It uses the same transport, retries and errors.
|
|
287
407
|
|
|
288
|
-
The behaviour of all five Clikgate server SDKs is defined in [`server/SPEC.md`](
|
|
408
|
+
The behaviour of all five Clikgate server SDKs is defined in [`server/SPEC.md`](https://github.com/clikgate/clikgate-sdks/blob/main/server/SPEC.md) and checked by the shared conformance suite.
|
|
289
409
|
|
|
290
410
|
## Development
|
|
291
411
|
|
|
@@ -298,4 +418,4 @@ npm run check:package # exports resolve from import and require, and the tarb
|
|
|
298
418
|
npm run generate # regenerate src/generated from server/openapi (needs Java 11+)
|
|
299
419
|
```
|
|
300
420
|
|
|
301
|
-
Licence: MIT. Security: see [
|
|
421
|
+
Licence: MIT. Security: report vulnerabilities to support@clikgate.com; see the [trust centre](https://clikgate.com/trust).
|
package/SECURITY.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Reporting a vulnerability
|
|
4
4
|
|
|
5
|
-
Email **
|
|
5
|
+
Email **support@clikgate.com** (trust centre: https://clikgate.com/trust). Please don't open a public issue.
|
|
6
6
|
|
|
7
7
|
- We acknowledge reports within 2 working days and keep you informed until the issue is fixed.
|
|
8
8
|
- Include the package and version, a description, and steps to reproduce.
|
|
@@ -12,6 +12,7 @@ Email **security@clikgate.com** (trust centre: https://clikgate.com/trust). Plea
|
|
|
12
12
|
|
|
13
13
|
| Package | Supported |
|
|
14
14
|
|---|---|
|
|
15
|
+
| `@clikgate/node` 2.x | yes |
|
|
15
16
|
| `@clikgate/node` 1.x | yes |
|
|
16
17
|
|
|
17
18
|
Security fixes go to the latest minor version of each supported major version.
|
package/dist/cjs/client.d.ts
CHANGED
|
@@ -1,28 +1,47 @@
|
|
|
1
1
|
import { ClickIds } from './click-ids.js';
|
|
2
2
|
import { type OnError } from './core.js';
|
|
3
3
|
import { type IdentityTokenOptions } from './identity.js';
|
|
4
|
+
import { type Installation } from './installation.js';
|
|
4
5
|
import type { RequestOptions } from './http.js';
|
|
5
6
|
import { ApiClient } from './generated/index.js';
|
|
6
7
|
import { Goals, type GoalOptions } from './goals.js';
|
|
7
8
|
import { type Clock } from './http.js';
|
|
8
9
|
import { type Logger } from './logger.js';
|
|
9
10
|
import { Payments } from './payments.js';
|
|
11
|
+
import { KnownCustomers } from './known-customers.js';
|
|
10
12
|
import { Clicks, Conversions, Links } from './resources.js';
|
|
13
|
+
import { Referrals } from './referrals.js';
|
|
14
|
+
import { Codes, Installs, People, Privacy } from './lookups.js';
|
|
11
15
|
import { type FetchLike } from './transport.js';
|
|
12
16
|
import type { ServerSdkConfig } from './types.js';
|
|
13
17
|
import { webhooks } from './webhooks.js';
|
|
14
18
|
/** Client options (SPEC section 3). Every option is optional. */
|
|
15
|
-
/** `identifyUser()`: at least one of `clickId`, `
|
|
19
|
+
/** `identifyUser()`: at least one of `clickId`, an installation (`installation` or `installationId`), `customerId`. */
|
|
16
20
|
export interface IdentifyUserParams {
|
|
17
21
|
/** The Clikgate click ID you kept (`clk_…`). */
|
|
18
22
|
clickId?: string | null;
|
|
19
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* The app's installation: the raw `Clikgate-Installation` header your app sent (`<app_id>:<installation_id>`), or
|
|
25
|
+
* the parsed `Installation` the framework helpers give (`req.clikgate.installation`, `getInstallation(...)`). It
|
|
26
|
+
* fills `appId` and `installationId`. Missing or invalid values (either form) are ignored, never sent. Not used when
|
|
27
|
+
* `installationId` is given.
|
|
28
|
+
*/
|
|
29
|
+
installation?: string | Installation | null;
|
|
30
|
+
/** The app the installation belongs to. Optional: without it Clikgate finds the app. Only with `installationId`. */
|
|
20
31
|
appId?: string | null;
|
|
32
|
+
/** The SDK's installation ID, sent by your app. */
|
|
21
33
|
installationId?: string | null;
|
|
22
|
-
/** Your
|
|
34
|
+
/** Your signed-in user's ID. Never read it from the request. With a click or installation, links it to this customer. */
|
|
23
35
|
customerId?: string | null;
|
|
24
36
|
/** A label your team sees instead of the click ID (1–80 characters, `''` clears it). */
|
|
25
37
|
label?: string | null;
|
|
38
|
+
/**
|
|
39
|
+
* When this customer became your customer: `'YYYY-MM-DD'`, an ISO 8601 date-time with offset, a
|
|
40
|
+
* `Date` or Unix seconds. Needs `customerId`. Clikgate keeps the earliest date it gets. Not in private mode.
|
|
41
|
+
*/
|
|
42
|
+
customerSince?: string | Date | number | null;
|
|
43
|
+
/** `true` lets `customerSince` move a wrong date later (audit-logged). Default: the earliest date is kept. */
|
|
44
|
+
customerSinceReplace?: boolean | null;
|
|
26
45
|
}
|
|
27
46
|
/** The answer of `identifyUser()`. */
|
|
28
47
|
export interface PersonIdentified {
|
|
@@ -30,6 +49,10 @@ export interface PersonIdentified {
|
|
|
30
49
|
person_id: string;
|
|
31
50
|
/** `plan`: below Growth the label isn't stored; `lower_rank`: a label your team set was kept. */
|
|
32
51
|
label_ignored: 'plan' | 'lower_rank' | null;
|
|
52
|
+
/** Why `customerSince` wasn't used: `unverified` or `invalid`. */
|
|
53
|
+
customer_since_ignored?: 'unverified' | 'invalid' | null;
|
|
54
|
+
/** The customer ID looks like an email, phone number or national ID: use your own user ID instead. */
|
|
55
|
+
customer_id_warning?: 'looks_like_email' | 'looks_like_phone' | 'looks_like_national_id' | null;
|
|
33
56
|
}
|
|
34
57
|
export interface ClikgateOptions {
|
|
35
58
|
/** `cg_live_…` or `cg_test_…`. Default: `process.env.CLIKGATE_API_KEY`. The mode comes from the prefix. */
|
|
@@ -92,6 +115,18 @@ export declare class Clikgate {
|
|
|
92
115
|
readonly links: Links;
|
|
93
116
|
/** Clicks. */
|
|
94
117
|
readonly clicks: Clicks;
|
|
118
|
+
/** Existing customers from before you added Clikgate: `import()` and `remove()`. */
|
|
119
|
+
readonly knownCustomers: KnownCustomers;
|
|
120
|
+
/** Referrals: referrers (`getOrCreateReferrer`, `findReferrer`), referrals, overrides, steps and imports. */
|
|
121
|
+
readonly referrals: Referrals;
|
|
122
|
+
/** Privacy requests: `createRequest`, `getRequest`. */
|
|
123
|
+
readonly privacy: Privacy;
|
|
124
|
+
/** People: `get`, `search`, `setLabel`. */
|
|
125
|
+
readonly people: People;
|
|
126
|
+
/** Installs: `getByCustomer`, `getByInstallation`. */
|
|
127
|
+
readonly installs: Installs;
|
|
128
|
+
/** Offline and referral codes: `redeem`. */
|
|
129
|
+
readonly codes: Codes;
|
|
95
130
|
/** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
|
|
96
131
|
readonly clickIds: ClickIds;
|
|
97
132
|
/** Every API-key operation, generated from openapi.json ("advanced"). */
|
|
@@ -129,20 +164,29 @@ export declare class Clikgate {
|
|
|
129
164
|
*/
|
|
130
165
|
createIdentityToken(customerId: string, options?: IdentityTokenOptions): string;
|
|
131
166
|
/**
|
|
132
|
-
* Tell Clikgate who a person is (`POST /v1/people/identify`): a click (`clickId`), an app installation
|
|
133
|
-
* `installationId`) or your `customerId`, at least one. With a click or installation, `customerId` links it to that
|
|
167
|
+
* Tell Clikgate who a person is (`POST /v1/people/identify`): a click (`clickId`), an app installation
|
|
168
|
+
* (`installation`, or `installationId` with an optional `appId`) or your `customerId`, at least one. With a click or installation, `customerId` links it to that
|
|
134
169
|
* customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
|
|
135
170
|
* up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
|
|
136
171
|
* In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
|
|
172
|
+
* `customerSince` is when they became your customer, so existing customers are never counted as
|
|
173
|
+
* referrals or new customers; it is refused in private mode too.
|
|
137
174
|
*
|
|
138
|
-
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app
|
|
139
|
-
* `
|
|
140
|
-
*
|
|
141
|
-
*
|
|
175
|
+
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app sends the
|
|
176
|
+
* `Clikgate-Installation` header (from the mobile SDK) to your server. After your own sign-in check succeeds, and at
|
|
177
|
+
* every signed-in app open, pass the header as `installation` with your signed-in user's ID as `customerId` (never a
|
|
178
|
+
* customer ID read from the request). When the header is missing or invalid (tracking is off), skip the call.
|
|
179
|
+
* `appId` is optional: Clikgate finds the app. If the installation ID is in several of your apps, the API answers
|
|
180
|
+
* `409 installation_in_several_apps` (a `ConflictError`, param `app_id`): send `appId` too. Clikgate accepts
|
|
181
|
+
* installations active in the last 7 days.
|
|
142
182
|
*
|
|
143
183
|
* @example
|
|
144
184
|
* await clikgate.identifyUser({ clickId: order.clickId, customerId: 'user_42', label: 'Ada (VIP)' });
|
|
145
|
-
*
|
|
185
|
+
* // after your sign-in check: the header from the app, your user's ID
|
|
186
|
+
* const installation = req.get('Clikgate-Installation');
|
|
187
|
+
* if (parseInstallationHeader(installation)) await clikgate.identifyUser({ installation, customerId: req.user.id });
|
|
188
|
+
* // or the parsed installation from the Express middleware
|
|
189
|
+
* if (req.clikgate.installation) await clikgate.identifyUser({ installation: req.clikgate.installation, customerId: req.user.id });
|
|
146
190
|
*/
|
|
147
191
|
identifyUser(params: IdentifyUserParams, requestOptions?: RequestOptions): Promise<PersonIdentified>;
|
|
148
192
|
/**
|
package/dist/cjs/client.js
CHANGED
|
@@ -7,16 +7,32 @@ const core_js_1 = require("./core.js");
|
|
|
7
7
|
const errors_js_1 = require("./errors.js");
|
|
8
8
|
const identity_js_1 = require("./identity.js");
|
|
9
9
|
const guard_js_1 = require("./guard.js");
|
|
10
|
+
const installation_js_1 = require("./installation.js");
|
|
10
11
|
const index_js_1 = require("./generated/index.js");
|
|
11
12
|
const goals_js_1 = require("./goals.js");
|
|
12
13
|
const http_js_1 = require("./http.js");
|
|
13
14
|
const logger_js_1 = require("./logger.js");
|
|
14
15
|
const payments_js_1 = require("./payments.js");
|
|
16
|
+
const known_customers_js_1 = require("./known-customers.js");
|
|
15
17
|
const resources_js_1 = require("./resources.js");
|
|
18
|
+
const referrals_js_1 = require("./referrals.js");
|
|
19
|
+
const lookups_js_1 = require("./lookups.js");
|
|
16
20
|
const shutdown_js_1 = require("./shutdown.js");
|
|
17
21
|
const transport_js_1 = require("./transport.js");
|
|
18
22
|
const user_agent_js_1 = require("./user-agent.js");
|
|
19
23
|
const webhooks_js_1 = require("./webhooks.js");
|
|
24
|
+
/** @internal The wire form of identifyUser's customerSince. */
|
|
25
|
+
function sinceWire(value) {
|
|
26
|
+
if (typeof value === 'string') {
|
|
27
|
+
if (!/^\d{4}-\d{2}-\d{2}(T.+)?$/.test(value))
|
|
28
|
+
throw (0, errors_js_1.localError)('invalid_argument', "customerSince must be 'YYYY-MM-DD', an ISO 8601 date-time, a Date or Unix seconds.", 'customer_since');
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
const ms = value instanceof Date ? value.getTime() : typeof value === 'number' && Number.isSafeInteger(value) ? value * 1000 : Number.NaN;
|
|
32
|
+
if (!Number.isFinite(ms))
|
|
33
|
+
throw (0, errors_js_1.localError)('invalid_argument', "customerSince must be 'YYYY-MM-DD', an ISO 8601 date-time, a Date or Unix seconds.", 'customer_since');
|
|
34
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
35
|
+
}
|
|
20
36
|
const KEY = /^cg_(live|test)_[A-Za-z0-9_]+$/;
|
|
21
37
|
const PARAM = /^[A-Za-z0-9_]{1,32}$/;
|
|
22
38
|
const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
@@ -57,6 +73,18 @@ class Clikgate {
|
|
|
57
73
|
links;
|
|
58
74
|
/** Clicks. */
|
|
59
75
|
clicks;
|
|
76
|
+
/** Existing customers from before you added Clikgate: `import()` and `remove()`. */
|
|
77
|
+
knownCustomers;
|
|
78
|
+
/** Referrals: referrers (`getOrCreateReferrer`, `findReferrer`), referrals, overrides, steps and imports. */
|
|
79
|
+
referrals;
|
|
80
|
+
/** Privacy requests: `createRequest`, `getRequest`. */
|
|
81
|
+
privacy;
|
|
82
|
+
/** People: `get`, `search`, `setLabel`. */
|
|
83
|
+
people;
|
|
84
|
+
/** Installs: `getByCustomer`, `getByInstallation`. */
|
|
85
|
+
installs;
|
|
86
|
+
/** Offline and referral codes: `redeem`. */
|
|
87
|
+
codes;
|
|
60
88
|
/** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
|
|
61
89
|
clickIds;
|
|
62
90
|
/** Every API-key operation, generated from openapi.json ("advanced"). */
|
|
@@ -75,7 +103,7 @@ class Clikgate {
|
|
|
75
103
|
throw new errors_js_1.ConfigurationError({ message: 'No API key: pass { apiKey } or set CLIKGATE_API_KEY (cg_live_… or cg_test_…).', code: 'missing_api_key', param: 'apiKey' });
|
|
76
104
|
const m = KEY.exec(apiKey);
|
|
77
105
|
if (!m)
|
|
78
|
-
throw new errors_js_1.ConfigurationError({ message: `The API key is ${keyType(apiKey)}. Server SDKs need a cg_live_… or cg_test_… API key from Developers
|
|
106
|
+
throw new errors_js_1.ConfigurationError({ message: `The API key is ${keyType(apiKey)}. Server SDKs need a cg_live_… or cg_test_… API key from Developers › API keys & clients.`, code: 'invalid_api_key', param: 'apiKey' });
|
|
79
107
|
this.mode = m[1];
|
|
80
108
|
const baseUrl = (options.baseUrl ?? process.env.CLIKGATE_BASE_URL ?? 'https://api.clikgate.com').replace(/\/+$/, '');
|
|
81
109
|
let parsed;
|
|
@@ -116,6 +144,12 @@ class Clikgate {
|
|
|
116
144
|
this.payments = new payments_js_1.Payments(this.core);
|
|
117
145
|
this.links = new resources_js_1.Links(this.core);
|
|
118
146
|
this.clicks = new resources_js_1.Clicks(this.core);
|
|
147
|
+
this.knownCustomers = new known_customers_js_1.KnownCustomers(this.core);
|
|
148
|
+
this.referrals = new referrals_js_1.Referrals(this.core);
|
|
149
|
+
this.privacy = new lookups_js_1.Privacy(this.core);
|
|
150
|
+
this.people = new lookups_js_1.People(this.core);
|
|
151
|
+
this.installs = new lookups_js_1.Installs(this.core);
|
|
152
|
+
this.codes = new lookups_js_1.Codes(this.core);
|
|
119
153
|
const explicitParam = options.clickIdParam;
|
|
120
154
|
this.clickIds = new click_ids_js_1.ClickIds(() => explicitParam ?? configCache.peek()?.click_id_param ?? 'cgid');
|
|
121
155
|
this.api = new index_js_1.ApiClient(requester);
|
|
@@ -183,40 +217,65 @@ class Clikgate {
|
|
|
183
217
|
return (0, identity_js_1.createIdentityTokenWith)(this.identitySource, customerId, options);
|
|
184
218
|
}
|
|
185
219
|
/**
|
|
186
|
-
* Tell Clikgate who a person is (`POST /v1/people/identify`): a click (`clickId`), an app installation
|
|
187
|
-
* `installationId`) or your `customerId`, at least one. With a click or installation, `customerId` links it to that
|
|
220
|
+
* Tell Clikgate who a person is (`POST /v1/people/identify`): a click (`clickId`), an app installation
|
|
221
|
+
* (`installation`, or `installationId` with an optional `appId`) or your `customerId`, at least one. With a click or installation, `customerId` links it to that
|
|
188
222
|
* customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
|
|
189
223
|
* up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
|
|
190
224
|
* In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
|
|
225
|
+
* `customerSince` is when they became your customer, so existing customers are never counted as
|
|
226
|
+
* referrals or new customers; it is refused in private mode too.
|
|
191
227
|
*
|
|
192
|
-
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app
|
|
193
|
-
* `
|
|
194
|
-
*
|
|
195
|
-
*
|
|
228
|
+
* Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app sends the
|
|
229
|
+
* `Clikgate-Installation` header (from the mobile SDK) to your server. After your own sign-in check succeeds, and at
|
|
230
|
+
* every signed-in app open, pass the header as `installation` with your signed-in user's ID as `customerId` (never a
|
|
231
|
+
* customer ID read from the request). When the header is missing or invalid (tracking is off), skip the call.
|
|
232
|
+
* `appId` is optional: Clikgate finds the app. If the installation ID is in several of your apps, the API answers
|
|
233
|
+
* `409 installation_in_several_apps` (a `ConflictError`, param `app_id`): send `appId` too. Clikgate accepts
|
|
234
|
+
* installations active in the last 7 days.
|
|
196
235
|
*
|
|
197
236
|
* @example
|
|
198
237
|
* await clikgate.identifyUser({ clickId: order.clickId, customerId: 'user_42', label: 'Ada (VIP)' });
|
|
199
|
-
*
|
|
238
|
+
* // after your sign-in check: the header from the app, your user's ID
|
|
239
|
+
* const installation = req.get('Clikgate-Installation');
|
|
240
|
+
* if (parseInstallationHeader(installation)) await clikgate.identifyUser({ installation, customerId: req.user.id });
|
|
241
|
+
* // or the parsed installation from the Express middleware
|
|
242
|
+
* if (req.clikgate.installation) await clikgate.identifyUser({ installation: req.clikgate.installation, customerId: req.user.id });
|
|
200
243
|
*/
|
|
201
244
|
async identifyUser(params, requestOptions = {}) {
|
|
202
245
|
const p = (params ?? {});
|
|
203
|
-
|
|
204
|
-
|
|
246
|
+
let appId = p.appId;
|
|
247
|
+
let installationId = p.installationId;
|
|
248
|
+
if (installationId == null && p.installation != null) {
|
|
249
|
+
const fromHeader = (0, installation_js_1.toInstallation)(p.installation);
|
|
250
|
+
if (fromHeader) {
|
|
251
|
+
appId = appId ?? fromHeader.appId;
|
|
252
|
+
installationId = fromHeader.installationId;
|
|
253
|
+
}
|
|
205
254
|
}
|
|
206
|
-
if (
|
|
207
|
-
throw (0, errors_js_1.localError)('invalid_request', 'Send
|
|
255
|
+
if (appId != null && installationId == null) {
|
|
256
|
+
throw (0, errors_js_1.localError)('invalid_request', 'Send installationId with appId.', 'installation_id');
|
|
257
|
+
}
|
|
258
|
+
if (p.clickId == null && installationId == null && p.customerId == null) {
|
|
259
|
+
throw (0, errors_js_1.localError)('invalid_request', 'Send clickId, an installation (installation or installationId), or customerId.', 'click_id');
|
|
208
260
|
}
|
|
209
261
|
const body = {};
|
|
210
262
|
if (p.clickId != null)
|
|
211
263
|
body.click_id = p.clickId;
|
|
212
|
-
if (
|
|
213
|
-
body.app_id =
|
|
214
|
-
if (
|
|
215
|
-
body.installation_id =
|
|
264
|
+
if (appId != null)
|
|
265
|
+
body.app_id = appId;
|
|
266
|
+
if (installationId != null)
|
|
267
|
+
body.installation_id = installationId;
|
|
216
268
|
if (p.customerId != null)
|
|
217
269
|
body.customer_id = p.customerId;
|
|
218
270
|
if (p.label != null)
|
|
219
271
|
body.label = p.label;
|
|
272
|
+
if (p.customerSince != null) {
|
|
273
|
+
if (p.customerId == null)
|
|
274
|
+
throw (0, errors_js_1.localError)('invalid_request', 'customerSince needs customerId.', 'customer_since');
|
|
275
|
+
body.customer_since = sinceWire(p.customerSince);
|
|
276
|
+
}
|
|
277
|
+
if (p.customerSinceReplace === true)
|
|
278
|
+
body.customer_since_replace = true;
|
|
220
279
|
const state = await this.core.guardState();
|
|
221
280
|
if (state.guard)
|
|
222
281
|
(0, guard_js_1.guardPayload)('identify', body);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** The ISO 4217 minor-unit exponent of a currency (2 when unknown). */
|
|
2
|
+
export declare function currencyExponent(currency: string): number;
|
|
3
|
+
/**
|
|
4
|
+
* Minor units to a decimal string in normal units, with exactly the currency's exponent of fraction digits
|
|
5
|
+
* (`50000` NGN → `"500.00"`, `1500` JPY → `"1500"`). No float is involved.
|
|
6
|
+
*/
|
|
7
|
+
export declare function minorToAmount(amountMinor: number | bigint, currency: string): string;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.currencyExponent = currencyExponent;
|
|
4
|
+
exports.minorToAmount = minorToAmount;
|
|
5
|
+
exports.rewardInfo = rewardInfo;
|
|
6
|
+
exports.toReferral = toReferral;
|
|
7
|
+
exports.toReferrer = toReferrer;
|
|
8
|
+
exports.toReferrerResult = toReferrerResult;
|
|
9
|
+
/** ISO 4217 exponents other than 2 (the backend's list); every other code has 2. */
|
|
10
|
+
const EXPONENTS = {
|
|
11
|
+
BHD: 3, BIF: 0, CLF: 4, CLP: 0, DJF: 0, GNF: 0, IQD: 3, ISK: 0, JOD: 3, JPY: 0, KMF: 0, KRW: 0, KWD: 3,
|
|
12
|
+
LYD: 3, OMR: 3, PYG: 0, RWF: 0, TND: 3, UGX: 0, UYI: 0, UYW: 4, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
|
|
13
|
+
};
|
|
14
|
+
/** The ISO 4217 minor-unit exponent of a currency (2 when unknown). */
|
|
15
|
+
function currencyExponent(currency) {
|
|
16
|
+
return EXPONENTS[currency.toUpperCase()] ?? 2;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Minor units to a decimal string in normal units, with exactly the currency's exponent of fraction digits
|
|
20
|
+
* (`50000` NGN → `"500.00"`, `1500` JPY → `"1500"`). No float is involved.
|
|
21
|
+
*/
|
|
22
|
+
function minorToAmount(amountMinor, currency) {
|
|
23
|
+
const exp = currencyExponent(currency);
|
|
24
|
+
const n = typeof amountMinor === 'bigint' ? amountMinor : BigInt(Math.trunc(amountMinor));
|
|
25
|
+
const negative = n < 0n;
|
|
26
|
+
const digits = (negative ? -n : n).toString().padStart(exp + 1, '0');
|
|
27
|
+
const whole = exp === 0 ? digits : `${digits.slice(0, -exp)}.${digits.slice(-exp)}`;
|
|
28
|
+
return negative ? `-${whole}` : whole;
|
|
29
|
+
}
|
|
30
|
+
function isObject(v) {
|
|
31
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
32
|
+
}
|
|
33
|
+
function side(v) {
|
|
34
|
+
if (!isObject(v))
|
|
35
|
+
return v;
|
|
36
|
+
const out = { ...v };
|
|
37
|
+
if ((typeof v.amount_minor === 'number' || typeof v.amount_minor === 'bigint') && typeof v.currency === 'string' && v.currency !== '') {
|
|
38
|
+
out.amount = minorToAmount(v.amount_minor, v.currency);
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
/** @internal Add `amount` next to each reward side's `amount_minor`. */
|
|
43
|
+
function rewardInfo(v) {
|
|
44
|
+
if (!isObject(v))
|
|
45
|
+
return v;
|
|
46
|
+
const out = { ...v };
|
|
47
|
+
if ('referrer' in v)
|
|
48
|
+
out.referrer = side(v.referrer);
|
|
49
|
+
if ('referee' in v)
|
|
50
|
+
out.referee = side(v.referee);
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
/** @internal A referral with reward amounts. */
|
|
54
|
+
function toReferral(data) {
|
|
55
|
+
if (!isObject(data))
|
|
56
|
+
return data;
|
|
57
|
+
const out = { ...data };
|
|
58
|
+
if (isObject(data.reward_snapshot))
|
|
59
|
+
out.reward_snapshot = rewardInfo(data.reward_snapshot);
|
|
60
|
+
if (isObject(data.referrer))
|
|
61
|
+
out.referrer = { ...data.referrer, customerId: data.referrer.customer_user_id };
|
|
62
|
+
if (isObject(data.referee))
|
|
63
|
+
out.referee = { ...data.referee, customerId: data.referee.customer_user_id ?? null };
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
/** @internal A referrer with `customerId` next to `customer_user_id`. */
|
|
67
|
+
function toReferrer(data) {
|
|
68
|
+
if (!isObject(data))
|
|
69
|
+
return data;
|
|
70
|
+
return { ...data, customerId: data.customer_user_id };
|
|
71
|
+
}
|
|
72
|
+
/** @internal A referrer with `created`. */
|
|
73
|
+
function toReferrerResult(data, status) {
|
|
74
|
+
return { ...toReferrer(data), created: status === 201 };
|
|
75
|
+
}
|