@clikgate/node 2.0.0 → 2.0.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/CHANGELOG.md CHANGED
@@ -3,6 +3,16 @@
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.0.1] - unreleased
7
+
8
+ ### Existing users
9
+
10
+ - **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.
11
+ - **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`.
12
+ - **Added:** `clikgate.knownCustomers.import(customers)` (batches of 10,000, counts summed; refused rows counted by reason, never returned) and `clikgate.knownCustomers.remove(customerId)`.
13
+ - **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.
14
+ - 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.
15
+
6
16
  ## [2.0.0] - unreleased
7
17
 
8
18
  ### Breaking: track() removed in favour of goal()
package/README.md CHANGED
@@ -70,6 +70,17 @@ createIdentityToken(user.id, { appId: 'app_…' }); //
70
70
  if (body.installationId) await clikgate.identifyUser({ appId: 'app_…', installationId: body.installationId, customerId: user.id });
71
71
  ```
72
72
 
73
+ ## Customers from before Clikgate
74
+
75
+ 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.
76
+
77
+ ```ts
78
+ res.json({ user, clikgateIdentityToken: createIdentityToken(user.id, { customerSince: user.createdAt }) }); // version 2
79
+ await clikgate.identifyUser({ appId: 'app_…', installationId, customerId: user.id, customerSince: user.createdAt });
80
+ const result = await clikgate.knownCustomers.import([{ customerId: 'u_10482', customerSince: '2024-03-02' }]); // batches of 10,000
81
+ console.log(result.accepted, result.refused_by_reason); // refused rows are counted by reason, never returned
82
+ ```
83
+
73
84
  ## People: identify a user and label them
74
85
 
75
86
  Link a click, an app installation or your customer ID to a person, and give them a label your team sees instead of the click ID (1-80 characters; Growth and up). From your server this is always verified. Goals take the same `label`, and `isFirst` from your server is what counts a new customer. Don't put information in labels that your customers wouldn't expect you to keep.
@@ -7,6 +7,7 @@ import { Goals, type GoalOptions } from './goals.js';
7
7
  import { type Clock } from './http.js';
8
8
  import { type Logger } from './logger.js';
9
9
  import { Payments } from './payments.js';
10
+ import { KnownCustomers } from './known-customers.js';
10
11
  import { Clicks, Conversions, Links } from './resources.js';
11
12
  import { type FetchLike } from './transport.js';
12
13
  import type { ServerSdkConfig } from './types.js';
@@ -23,6 +24,13 @@ export interface IdentifyUserParams {
23
24
  customerId?: string | null;
24
25
  /** A label your team sees instead of the click ID (1–80 characters, `''` clears it). */
25
26
  label?: string | null;
27
+ /**
28
+ * When this customer became your customer: `'YYYY-MM-DD'`, an ISO 8601 date-time with offset, a
29
+ * `Date` or Unix seconds. Needs `customerId`. Clikgate keeps the earliest date it gets. Not in private mode.
30
+ */
31
+ customerSince?: string | Date | number | null;
32
+ /** `true` lets `customerSince` move a wrong date later (audit-logged). Default: the earliest date is kept. */
33
+ customerSinceReplace?: boolean | null;
26
34
  }
27
35
  /** The answer of `identifyUser()`. */
28
36
  export interface PersonIdentified {
@@ -30,6 +38,10 @@ export interface PersonIdentified {
30
38
  person_id: string;
31
39
  /** `plan`: below Growth the label isn't stored; `lower_rank`: a label your team set was kept. */
32
40
  label_ignored: 'plan' | 'lower_rank' | null;
41
+ /** Why `customerSince` wasn't used: `unverified` or `invalid`. */
42
+ customer_since_ignored?: 'unverified' | 'invalid' | null;
43
+ /** The customer ID looks like an email, phone number or national ID: use your own user ID instead. */
44
+ customer_id_warning?: 'looks_like_email' | 'looks_like_phone' | 'looks_like_national_id' | null;
33
45
  }
34
46
  export interface ClikgateOptions {
35
47
  /** `cg_live_…` or `cg_test_…`. Default: `process.env.CLIKGATE_API_KEY`. The mode comes from the prefix. */
@@ -92,6 +104,8 @@ export declare class Clikgate {
92
104
  readonly links: Links;
93
105
  /** Clicks. */
94
106
  readonly clicks: Clicks;
107
+ /** Existing customers from before you added Clikgate: `import()` and `remove()`. */
108
+ readonly knownCustomers: KnownCustomers;
95
109
  /** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
96
110
  readonly clickIds: ClickIds;
97
111
  /** Every API-key operation, generated from openapi.json ("advanced"). */
@@ -134,6 +148,8 @@ export declare class Clikgate {
134
148
  * customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
135
149
  * up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
136
150
  * In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
151
+ * `customerSince` is when they became your customer, so existing customers are never counted as
152
+ * referrals or new customers; it is refused in private mode too.
137
153
  *
138
154
  * Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app reads
139
155
  * `getInstallationId()` and sends it in its sign-in request; your server calls this with
@@ -12,11 +12,24 @@ const goals_js_1 = require("./goals.js");
12
12
  const http_js_1 = require("./http.js");
13
13
  const logger_js_1 = require("./logger.js");
14
14
  const payments_js_1 = require("./payments.js");
15
+ const known_customers_js_1 = require("./known-customers.js");
15
16
  const resources_js_1 = require("./resources.js");
16
17
  const shutdown_js_1 = require("./shutdown.js");
17
18
  const transport_js_1 = require("./transport.js");
18
19
  const user_agent_js_1 = require("./user-agent.js");
19
20
  const webhooks_js_1 = require("./webhooks.js");
21
+ /** @internal The wire form of identifyUser's customerSince. */
22
+ function sinceWire(value) {
23
+ if (typeof value === 'string') {
24
+ if (!/^\d{4}-\d{2}-\d{2}(T.+)?$/.test(value))
25
+ 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');
26
+ return value;
27
+ }
28
+ const ms = value instanceof Date ? value.getTime() : typeof value === 'number' && Number.isSafeInteger(value) ? value * 1000 : Number.NaN;
29
+ if (!Number.isFinite(ms))
30
+ 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');
31
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
32
+ }
20
33
  const KEY = /^cg_(live|test)_[A-Za-z0-9_]+$/;
21
34
  const PARAM = /^[A-Za-z0-9_]{1,32}$/;
22
35
  const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);
@@ -57,6 +70,8 @@ class Clikgate {
57
70
  links;
58
71
  /** Clicks. */
59
72
  clicks;
73
+ /** Existing customers from before you added Clikgate: `import()` and `remove()`. */
74
+ knownCustomers;
60
75
  /** Click-ID helpers using this client's `clickIdParam` (or the organisation's from config). */
61
76
  clickIds;
62
77
  /** Every API-key operation, generated from openapi.json ("advanced"). */
@@ -116,6 +131,7 @@ class Clikgate {
116
131
  this.payments = new payments_js_1.Payments(this.core);
117
132
  this.links = new resources_js_1.Links(this.core);
118
133
  this.clicks = new resources_js_1.Clicks(this.core);
134
+ this.knownCustomers = new known_customers_js_1.KnownCustomers(this.core);
119
135
  const explicitParam = options.clickIdParam;
120
136
  this.clickIds = new click_ids_js_1.ClickIds(() => explicitParam ?? configCache.peek()?.click_id_param ?? 'cgid');
121
137
  this.api = new index_js_1.ApiClient(requester);
@@ -188,6 +204,8 @@ class Clikgate {
188
204
  * customer. `label` is what your team sees instead of the click ID (1–80 characters, `''` clears it; Growth and
189
205
  * up). Always verified (your server), so it also satisfies a referral program's `require_identity_token`.
190
206
  * In private mode `customerId` is refused locally (the guard) and `label` needs "Allow labels in private mode".
207
+ * `customerSince` is when they became your customer, so existing customers are never counted as
208
+ * referrals or new customers; it is refused in private mode too.
191
209
  *
192
210
  * Path B of https://clikgate.com/docs/identify-users (no identity secret or token): the app reads
193
211
  * `getInstallationId()` and sends it in its sign-in request; your server calls this with
@@ -217,6 +235,13 @@ class Clikgate {
217
235
  body.customer_id = p.customerId;
218
236
  if (p.label != null)
219
237
  body.label = p.label;
238
+ if (p.customerSince != null) {
239
+ if (p.customerId == null)
240
+ throw (0, errors_js_1.localError)('invalid_request', 'customerSince needs customerId.', 'customer_since');
241
+ body.customer_since = sinceWire(p.customerSince);
242
+ }
243
+ if (p.customerSinceReplace === true)
244
+ body.customer_since_replace = true;
220
245
  const state = await this.core.guardState();
221
246
  if (state.guard)
222
247
  (0, guard_js_1.guardPayload)('identify', body);
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Your customer IDs, in one canonical form: the same form the API stores and checks, so an ID
3
+ * sent from your server, an import and an identity token always match.
4
+ *
5
+ * - canonical form: Unicode NFC, trimmed of Unicode whitespace (and U+FEFF) at both ends, case kept;
6
+ * - warnings (first match wins): `empty`, `too_long` (more than 128 characters), `looks_like_email`,
7
+ * `looks_like_national_id` (exactly 11 digits, unless `allow11DigitIds`), `looks_like_phone`.
8
+ *
9
+ * Use your own stable user ID (for example `u_10482`), never an email, phone number, BVN or NIN.
10
+ */
11
+ /** The longest customer ID kept as a known customer, in Unicode code points. */
12
+ export declare const CUSTOMER_ID_MAX_LENGTH = 128;
13
+ /** Why a customer ID can't be used as a known customer (the API's refusal reasons for the same checks). */
14
+ export type CustomerIdWarning = 'empty' | 'too_long' | 'looks_like_email' | 'looks_like_national_id' | 'looks_like_phone';
15
+ /** The canonical form of a customer ID: NFC, trimmed, case kept. */
16
+ export declare function canonicalCustomerId(customerId: string): string;
17
+ /**
18
+ * Why Clikgate wouldn't keep this ID as a known customer, or `null` when it's fine.
19
+ *
20
+ * @example
21
+ * customerIdWarning('ada@example.com'); // 'looks_like_email'
22
+ * customerIdWarning('u_10482'); // null
23
+ */
24
+ export declare function customerIdWarning(customerId: string, options?: {
25
+ allow11DigitIds?: boolean;
26
+ }): CustomerIdWarning | null;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * Your customer IDs, in one canonical form: the same form the API stores and checks, so an ID
4
+ * sent from your server, an import and an identity token always match.
5
+ *
6
+ * - canonical form: Unicode NFC, trimmed of Unicode whitespace (and U+FEFF) at both ends, case kept;
7
+ * - warnings (first match wins): `empty`, `too_long` (more than 128 characters), `looks_like_email`,
8
+ * `looks_like_national_id` (exactly 11 digits, unless `allow11DigitIds`), `looks_like_phone`.
9
+ *
10
+ * Use your own stable user ID (for example `u_10482`), never an email, phone number, BVN or NIN.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.CUSTOMER_ID_MAX_LENGTH = void 0;
14
+ exports.canonicalCustomerId = canonicalCustomerId;
15
+ exports.customerIdWarning = customerIdWarning;
16
+ /** Unicode White_Space characters plus U+FEFF (the byte-order mark). */
17
+ const TRIM = '\t\n\u000b\u000c\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
18
+ /** The longest customer ID kept as a known customer, in Unicode code points. */
19
+ exports.CUSTOMER_ID_MAX_LENGTH = 128;
20
+ /** The canonical form of a customer ID: NFC, trimmed, case kept. */
21
+ function canonicalCustomerId(customerId) {
22
+ const s = customerId.normalize('NFC');
23
+ let start = 0;
24
+ let end = s.length;
25
+ while (start < end && TRIM.includes(s[start]))
26
+ start++;
27
+ while (end > start && TRIM.includes(s[end - 1]))
28
+ end--;
29
+ return s.slice(start, end);
30
+ }
31
+ /**
32
+ * Why Clikgate wouldn't keep this ID as a known customer, or `null` when it's fine.
33
+ *
34
+ * @example
35
+ * customerIdWarning('ada@example.com'); // 'looks_like_email'
36
+ * customerIdWarning('u_10482'); // null
37
+ */
38
+ function customerIdWarning(customerId, options = {}) {
39
+ const cid = canonicalCustomerId(customerId);
40
+ if (cid === '')
41
+ return 'empty';
42
+ if ([...cid].length > exports.CUSTOMER_ID_MAX_LENGTH)
43
+ return 'too_long';
44
+ const at = cid.indexOf('@');
45
+ if (at >= 0 && cid.slice(at + 1).includes('.'))
46
+ return 'looks_like_email';
47
+ if (/^[0-9]{11}$/.test(cid))
48
+ return options.allow11DigitIds ? null : 'looks_like_national_id';
49
+ if (/^\+?[0-9]{10,15}$/.test(cid.replace(/[ -]/g, '')))
50
+ return 'looks_like_phone';
51
+ return null;
52
+ }
package/dist/cjs/enums.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  // Generated by server/codegen/generate.mjs from openapi.json (GoalKind, GoalStatus, Provider). Do not edit by hand.
3
- // Source sha256 d39834b71974ddd58b7ba177f00c450738a641f18add17189a2f707bf724c796.
3
+ // Source sha256 86cb28d5c8c70cb6793d1c9145f99790d749cc09b447fa0f702d4c9cbbeeabd8.
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.Provider = exports.GoalStatus = exports.GoalKind = void 0;
6
6
  /** A goal's kind, set in the goal's settings (never in a goal call): `standard` or `payment`. */
@@ -12,7 +12,7 @@
12
12
  * }
13
13
  */
14
14
  /** Error codes with documented meaning (SPEC section 5). Other codes can appear; `code` is a plain string. */
15
- export type KnownErrorCode = 'invalid_goal_key' | 'invalid_reference' | 'invalid_value' | 'click_id_and_code' | 'batch_too_large' | 'batch_empty' | 'invalid_argument' | 'invalid_click_id' | 'queue_full' | 'client_closed' | 'missing_api_key' | 'invalid_api_key' | 'invalid_option' | 'network_error' | 'timeout' | 'unexpected_status' | 'rate_limit_exceeded' | 'private_mode_field_rejected' | 'link_locked' | 'idempotency_key_reused' | 'idempotency_request_in_progress' | 'goal_archived' | 'goal_not_found' | 'value_required' | 'value_not_allowed' | 'domain_mode_mismatch' | 'https_required' | 'destination_not_allowlisted' | 'test_destination_not_allowed' | 'test_link_limit_reached' | 'plan_limit_reached' | 'plan_upgrade_required' | 'plan_feature_unavailable' | 'feature_disabled' | 'invalid_provider' | 'unknown_provider' | 'code_not_supported' | 'payment_goal_needs_confirmation' | 'unknown_goal' | 'cli_scope' | 'missing_signature' | 'malformed_signature' | 'timestamp_outside_tolerance' | 'no_matching_signature' | 'invalid_payload' | 'server_only' | 'invalid_customer_id' | 'missing_identity_secret' | 'invalid_identity_secrets';
15
+ export type KnownErrorCode = 'invalid_goal_key' | 'invalid_reference' | 'invalid_value' | 'click_id_and_code' | 'batch_too_large' | 'batch_empty' | 'invalid_argument' | 'invalid_click_id' | 'queue_full' | 'client_closed' | 'missing_api_key' | 'invalid_api_key' | 'invalid_option' | 'network_error' | 'timeout' | 'unexpected_status' | 'rate_limit_exceeded' | 'private_mode_field_rejected' | 'private_mode_conflict' | 'link_locked' | 'idempotency_key_reused' | 'idempotency_request_in_progress' | 'goal_archived' | 'goal_not_found' | 'value_required' | 'value_not_allowed' | 'domain_mode_mismatch' | 'https_required' | 'destination_not_allowlisted' | 'test_destination_not_allowed' | 'test_link_limit_reached' | 'plan_limit_reached' | 'plan_upgrade_required' | 'plan_feature_unavailable' | 'feature_disabled' | 'invalid_provider' | 'unknown_provider' | 'code_not_supported' | 'payment_goal_needs_confirmation' | 'unknown_goal' | 'cli_scope' | 'missing_signature' | 'malformed_signature' | 'timestamp_outside_tolerance' | 'no_matching_signature' | 'invalid_payload' | 'server_only' | 'invalid_customer_id' | 'missing_identity_secret' | 'invalid_identity_secrets';
16
16
  /** Fields every Clikgate error carries. */
17
17
  export interface ClikgateErrorInit {
18
18
  message: string;