@yougrowai/node 0.3.0 → 0.5.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/README.md CHANGED
@@ -10,8 +10,8 @@ https://yougrow.ai/developers are the contract. The source on GitHub isn't: its
10
10
  main branch can be ahead of what's been released.
11
11
 
12
12
  > **2026-09-25:** API v1 (`POST /api/v1/events`, HMAC signing) was removed.
13
- > 0.3.0 is the client for API v2; 0.1.x only spoke v1, so upgrade to keep
14
- > sending. See [Upgrading from 0.1.x](#upgrading-from-01x).
13
+ > 0.3.0 and later are the client for API v2; 0.1.x only spoke v1, so upgrade to
14
+ > keep sending. See [Upgrading from 0.1.x](#upgrading-from-01x).
15
15
 
16
16
  ```sh
17
17
  npm install @yougrowai/node
@@ -41,6 +41,9 @@ const yg = new YouGrow({
41
41
  origin: process.env.YOUGROW_ORIGIN, // optional; defaults to https://yougrow.ai
42
42
  });
43
43
 
44
+ // Check the key (e.g. when you deploy): which connection and environment it's for
45
+ const { connection } = await yg.me(); // { name, environment: "production", status: "active", … }
46
+
44
47
  // At sign-up: who they are, and the basis for emailing them
45
48
  await yg.users.update(user.id, {
46
49
  email: user.email,
@@ -135,11 +138,34 @@ record an event twice. A key that was already recorded resolves
135
138
  - A step's value is when it was done (`null`: not done). Timestamps are ISO 8601
136
139
  with a zone (`Z` or `+01:00`), e.g. from `toISOString()`.
137
140
  - `email`, `firstName`, `lastName`, `timezone` and `locale` are fields of their
138
- own, never traits. Unknown fields are refused (400), so a typo can't be
139
- silently dropped.
141
+ own, never traits. An invalid one doesn't sink the update: the rest applies,
142
+ that field keeps its stored value, and the result lists it in
143
+ `ignoredFields`. Anything else invalid, including an unknown field, is
144
+ refused (400), so a typo can't be silently dropped.
140
145
  - Up to 50 steps, 50 facts and 50 traits per user. Step ids are lower-case
141
146
  letters, digits, `_` and `-`; trait keys start with a letter.
142
147
 
148
+ ### Several workspaces, brands or projects
149
+
150
+ When a person can have several of something, send them as `entities`, by your
151
+ own id. Each has a `kind` (your word for it; required the first time), a
152
+ `name`, the `parentId` it sits inside, the person's `role` (`owner`, `member` or
153
+ `invited`), and its own `steps` and `facts`. Each merges like the user, and
154
+ `null` removes one:
155
+
156
+ ```ts
157
+ await yg.users.update(user.id, {
158
+ entities: {
159
+ brand_123: { kind: "brand", name: "Acme", role: "owner", steps: { run_audit: audit.finishedAt } },
160
+ brand_456: null, // deleted in your product
161
+ },
162
+ });
163
+ await yg.events.track(user.id, "audit.completed", { entityId: "brand_123" });
164
+ ```
165
+
166
+ Journeys choose which of them each email is about, so send them all rather than
167
+ picking one. Up to 50 per user.
168
+
143
169
  A user YouGrow hasn't seen is created by their first update.
144
170
  `users.get(userId)` returns the state as YouGrow holds it, plus what YouGrow
145
171
  decided: journey `enrolments`, and `optOuts` (unsubscribes made in YouGrow's
@@ -178,8 +204,13 @@ Every method returns a promise; await it.
178
204
  `code` (the API's `error`, e.g. `invalid`, `unauthorized`, `body_too_large`),
179
205
  `fields` for a 400, and a message such as
180
206
  `YouGrow API 400 invalid: traits.plan: …`. A 429 or 5xx that outlasts the
181
- retries rejects the same way; a network error or timeout rejects with that
182
- error.
207
+ retries rejects the same way, and so does a network failure or timeout
208
+ (`status` 0, `code` `network_error` or `timeout`, the original error as
209
+ `cause`).
210
+ - `err.retryable` says whether trying again later may work: true for a 429, a
211
+ 5xx, a timeout or a network failure. In a queue worker, or a trigger with
212
+ retries on, rethrow those so the work is redelivered, and log the rest: a
213
+ 400 won't succeed as it is. Every write is safe to repeat.
183
214
  - A user id the API can't take (empty, over 256 characters, `"batch"`, `"."`
184
215
  or `".."`) rejects with a `TypeError` before anything is sent.
185
216
 
@@ -189,8 +220,9 @@ import { YouGrowError } from "@yougrowai/node";
189
220
  try {
190
221
  await yg.users.update(user.id, patch);
191
222
  } catch (err) {
192
- if (err instanceof YouGrowError && err.status === 400) console.error(err.message, err.fields); // [{ path, message }]
193
- throw err;
223
+ if (err instanceof YouGrowError && err.retryable) throw err; // 429, 5xx, timeout, network: let it be retried
224
+ if (err instanceof YouGrowError) console.error(err.message, err.fields); // e.g. a 400: [{ path, message }]; fix it
225
+ else throw err;
194
226
  }
195
227
  ```
196
228
 
@@ -285,10 +317,20 @@ never invents them.
285
317
 
286
318
  ### Webhooks
287
319
 
288
- YouGrow tells your webhook endpoint about preference changes, e.g. an
289
- unsubscribe from onboarding tips. Verify it with
290
- `verifier.verify({ …, direction: "webhook" })`. Webhook ids (`jti` in the
291
- token, `id` in the body) are unique, so you can drop duplicates.
320
+ YouGrow tells your webhook endpoint about changes to mirror. Verify each request
321
+ with `verifier.verify({ …, direction: "webhook" })`, then read the body as a
322
+ `WebhookEvent` (a type from `@yougrowai/node/server`):
323
+
324
+ - `email_preferences.updated`: the person unsubscribed from one of YouGrow's
325
+ emails (`data.scope` is `all` or `category`).
326
+ - `email.suppressed`: YouGrow stopped emailing them, because their address
327
+ hard-bounced (`data.reason` `hard_bounce`) or they reported an email as spam
328
+ (`complaint`).
329
+ - `connection.test`: the Test webhook button.
330
+
331
+ Reply 2xx to any type you don't handle. Webhook ids (`jti` in the token, `id` in
332
+ the body) are unique and the same on every retry, so you can drop duplicates.
333
+ API writes never trigger a webhook, so echoing a change back can't loop.
292
334
 
293
335
  ## Without the SDK
294
336
 
@@ -322,9 +364,23 @@ at https://yougrow.ai/developers.
322
364
  `test/vectors.json` (included in this package) holds reference tokens for
323
365
  checking your own verifier.
324
366
 
367
+ ## Upgrading from 0.4
368
+
369
+ - New: `entities` in `users.update` and on the state it returns, `entityId` on
370
+ `events.track`, and `entityId` on enrolments from `users.get`. Nothing
371
+ existing changed.
372
+
373
+ ## Upgrading from 0.3
374
+
375
+ - A network failure or timeout that outlasts the retries now rejects with a
376
+ `YouGrowError` (`status` 0, `code` `network_error` or `timeout`) instead of
377
+ the raw error, which is its `cause`.
378
+ - New: `yg.me()`, `err.retryable`, `ignoredFields` on update results (and
379
+ `fields_ignored` in batch results), and the `WebhookEvent` type.
380
+
325
381
  ## Upgrading from 0.1.x
326
382
 
327
- | 0.1.x (API v1) | 0.3.0 (API v2) |
383
+ | 0.1.x (API v1) | 0.3.0 and later (API v2) |
328
384
  |---|---|
329
385
  | `identify({ userId, traits, consent })` | `users.update(userId, { email, firstName, …, consent, traits })`: profile fields are top-level, and `consent` is the basis itself, e.g. `"soft_opt_in"` |
330
386
  | `track({ event: "user.signed_up" })` | `signedUpAt` in `users.update` |
@@ -12,6 +12,34 @@
12
12
  * status throws a YouGrowError straight away.
13
13
  */
14
14
  export type ConsentBasis = "consent" | "soft_opt_in" | "corporate_subscriber" | "none";
15
+ /** How a person relates to one of their entities. Only what they own counts toward their onboarding. */
16
+ export type EntityRole = "owner" | "member" | "invited";
17
+ /**
18
+ * One of the things a person has several of — a workspace, a brand, a project —
19
+ * in a write. It merges like the user; `kind` is required the first time.
20
+ */
21
+ export interface EntityPatch {
22
+ /** What it is, in your product's words: "brand", "workspace", "project". */
23
+ kind?: string;
24
+ name?: string | null;
25
+ /** The entity it sits inside, e.g. a brand's workspace. */
26
+ parentId?: string | null;
27
+ role?: EntityRole | null;
28
+ steps?: Record<string, string | null>;
29
+ facts?: Record<string, number | string | boolean | null>;
30
+ /** When the person last worked on it. */
31
+ activeAt?: string | null;
32
+ }
33
+ /** One entity as YouGrow holds it. */
34
+ export interface EntityState {
35
+ kind: string;
36
+ name: string | null;
37
+ parentId: string | null;
38
+ role: EntityRole | null;
39
+ steps: Record<string, string>;
40
+ facts: Record<string, string | number | boolean>;
41
+ activeAt: string | null;
42
+ }
15
43
  /**
16
44
  * Any subset of a user's state, as a JSON Merge Patch (RFC 7396): fields sent
17
45
  * replace YouGrow's, fields left out stay, `null` clears, and `steps`, `facts`
@@ -42,6 +70,8 @@ export interface UserPatch {
42
70
  facts?: Record<string, number | string | boolean | null>;
43
71
  /** Anything else journeys branch on (null removes a key). */
44
72
  traits?: Record<string, string | number | boolean | null>;
73
+ /** The things this person has several of (workspaces, brands…), by your id; null removes one. */
74
+ entities?: Record<string, EntityPatch | null>;
45
75
  /** When you read this state. A write older than the stored one is ignored. */
46
76
  updatedAt?: string;
47
77
  }
@@ -62,15 +92,18 @@ export interface UserState {
62
92
  steps: Record<string, string>;
63
93
  facts: Record<string, string | number | boolean>;
64
94
  traits: Record<string, string | number | boolean>;
95
+ entities: Record<string, EntityState>;
65
96
  updatedAt: string | null;
66
97
  }
67
98
  /** `users.get` adds what YouGrow decided: journeys and opt-outs. */
68
99
  export interface UserView extends UserState {
100
+ /** `entityId`: the entity an enrolment is about, when its journey is about one of them. */
69
101
  enrolments: Array<{
70
102
  journeyId: string;
71
103
  status: string;
72
104
  mode: string;
73
105
  enrolledAt: string;
106
+ entityId?: string | null;
74
107
  }>;
75
108
  /** Unsubscribes made in YouGrow's emails. They hold until the person lifts them; the API can't. */
76
109
  optOuts: Array<{
@@ -81,9 +114,12 @@ export interface UserView extends UserState {
81
114
  }
82
115
  /** Why a write was ignored: older than the stored state, or than the user's deletion. */
83
116
  export type SkipReason = "stale_write" | "deleted_later";
84
- export type PatchResponse = {
117
+ export type PatchResponse =
118
+ /** `ignoredFields`: profile fields whose value was invalid, so left as they were; the rest applied. */
119
+ {
85
120
  applied: true;
86
121
  user: UserState;
122
+ ignoredFields?: FieldError[];
87
123
  } | {
88
124
  applied: false;
89
125
  reason: SkipReason;
@@ -103,15 +139,30 @@ export interface BatchResponse {
103
139
  applied: number;
104
140
  ignored: number;
105
141
  failed: number;
106
- /** Only the ignored and failed items; applied ones are counted. `index` is the item's position in your array. */
142
+ /**
143
+ * The ignored and failed items, and applied ones whose invalid profile fields were
144
+ * left as they were (reason `fields_ignored`). `index` is the item's position in your array.
145
+ */
107
146
  results: Array<{
108
147
  index: number;
109
148
  userId: string | null;
110
- status: "ignored" | "failed";
149
+ status: "applied" | "ignored" | "failed";
111
150
  reason: string;
112
151
  fields?: FieldError[];
113
152
  }>;
114
153
  }
154
+ /** The connection behind your key (`GET /api/v2/me`). */
155
+ export interface MeResponse {
156
+ connection: {
157
+ id: string;
158
+ name: string;
159
+ environment: "staging" | "production" | null;
160
+ status: "active" | "paused" | "revoked";
161
+ };
162
+ keyId: string;
163
+ /** A new secret was issued in the last 24 hours; the previous one works until then. */
164
+ rotating: boolean;
165
+ }
115
166
  export interface EventResult {
116
167
  recorded: boolean;
117
168
  duplicate: boolean;
@@ -147,6 +198,8 @@ export interface TrackOptions {
147
198
  occurredAt?: string;
148
199
  /** The same key is recorded once. Defaults to a random key per call, so the SDK's own retries never count twice. */
149
200
  idempotencyKey?: string;
201
+ /** The entity it happened to (one of the user's `entities`), e.g. the brand an audit ran on. */
202
+ entityId?: string;
150
203
  }
151
204
  export interface UsersApi {
152
205
  /** Merge a patch into one user's state; creates the user if YouGrow hasn't seen them. */
@@ -166,15 +219,26 @@ export interface EventsApi {
166
219
  /** Record a milestone, e.g. "report.exported". Optional: journeys run on state. */
167
220
  track(userId: string, event: string, opts?: TrackOptions): Promise<EventResult>;
168
221
  }
169
- /** The API refused a request, or still failed (429, 5xx) after the retries. */
222
+ /**
223
+ * The API refused a request, or it still failed after the retries: a 429, a 5xx,
224
+ * or a timeout or network failure (`status` 0, `code` `timeout` or `network_error`).
225
+ */
170
226
  export declare class YouGrowError extends Error {
171
227
  readonly status: number;
172
228
  readonly body?: unknown | undefined;
173
- /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), or `http_<status>` when the body has none. */
229
+ /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), `timeout` or `network_error`, or `http_<status>`. */
174
230
  readonly code: string;
175
231
  /** For a 400: which fields were wrong, and why. */
176
232
  readonly fields?: FieldError[];
177
- constructor(message: string, status: number, body?: unknown | undefined);
233
+ /**
234
+ * True for a 429, a 5xx, a timeout or a network failure: trying again later may
235
+ * work, so a queue or trigger should rethrow it for redelivery. Anything else
236
+ * (a 400, 401, 404…) won't succeed as it is.
237
+ */
238
+ readonly retryable: boolean;
239
+ constructor(message: string, status: number, body?: unknown | undefined, options?: {
240
+ cause?: unknown;
241
+ });
178
242
  }
179
243
  /** From `users.batch` with `throwOnItemError`: some items failed. The rest were applied; `result` says which. */
180
244
  export declare class YouGrowBatchError extends Error {
@@ -186,4 +250,9 @@ export declare class YouGrow {
186
250
  readonly users: UsersApi;
187
251
  readonly events: EventsApi;
188
252
  constructor(opts: YouGrowOptions);
253
+ /**
254
+ * The connection behind your key: its name, environment and status. A credential
255
+ * check — and a way to catch a key from the wrong environment — before you send.
256
+ */
257
+ me(): Promise<MeResponse>;
189
258
  }
package/dist/cjs/index.js CHANGED
@@ -11,16 +11,25 @@ const BATCH_ENVELOPE_BYTES = '{"users":[]}'.length;
11
11
  const MAX_USER_ID = 256;
12
12
  /** The longest delay a Node timer accepts. */
13
13
  const MAX_TIMER_MS = 2_147_483_647;
14
- /** The API refused a request, or still failed (429, 5xx) after the retries. */
14
+ /**
15
+ * The API refused a request, or it still failed after the retries: a 429, a 5xx,
16
+ * or a timeout or network failure (`status` 0, `code` `timeout` or `network_error`).
17
+ */
15
18
  class YouGrowError extends Error {
16
19
  status;
17
20
  body;
18
- /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), or `http_<status>` when the body has none. */
21
+ /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), `timeout` or `network_error`, or `http_<status>`. */
19
22
  code;
20
23
  /** For a 400: which fields were wrong, and why. */
21
24
  fields;
22
- constructor(message, status, body) {
23
- super(message);
25
+ /**
26
+ * True for a 429, a 5xx, a timeout or a network failure: trying again later may
27
+ * work, so a queue or trigger should rethrow it for redelivery. Anything else
28
+ * (a 400, 401, 404…) won't succeed as it is.
29
+ */
30
+ retryable;
31
+ constructor(message, status, body, options) {
32
+ super(message, options);
24
33
  this.status = status;
25
34
  this.body = body;
26
35
  this.name = "YouGrowError";
@@ -28,6 +37,7 @@ class YouGrowError extends Error {
28
37
  this.code = typeof b?.error === "string" ? b.error : `http_${status}`;
29
38
  if (Array.isArray(b?.fields))
30
39
  this.fields = b.fields;
40
+ this.retryable = status === 0 || status === 429 || status >= 500;
31
41
  }
32
42
  }
33
43
  exports.YouGrowError = YouGrowError;
@@ -83,13 +93,20 @@ class YouGrow {
83
93
  this.events = {
84
94
  track: async (userId, event, options = {}) => {
85
95
  const path = `${userPath(userId)}/events`;
86
- const { properties, occurredAt } = options;
96
+ const { properties, occurredAt, entityId } = options;
87
97
  // One key for every attempt, so a retry is never recorded twice.
88
- const body = { event, properties, occurredAt, idempotencyKey: options.idempotencyKey ?? (0, node_crypto_1.randomUUID)() };
98
+ const body = { event, properties, occurredAt, entityId, idempotencyKey: options.idempotencyKey ?? (0, node_crypto_1.randomUUID)() };
89
99
  return (await this.#send("POST", path, JSON.stringify(body)));
90
100
  },
91
101
  };
92
102
  }
103
+ /**
104
+ * The connection behind your key: its name, environment and status. A credential
105
+ * check — and a way to catch a key from the wrong environment — before you send.
106
+ */
107
+ async me() {
108
+ return (await this.#send("GET", "/api/v2/me"));
109
+ }
93
110
  async #patchMany(items, opts = {}) {
94
111
  if (!Array.isArray(items))
95
112
  throw new TypeError("YouGrow: users.batch takes an array of { userId, ...patch }");
@@ -137,7 +154,7 @@ class YouGrow {
137
154
  catch (err) {
138
155
  // Network error or timeout.
139
156
  if (attempt >= this.#maxRetries)
140
- throw err;
157
+ throw transportError(err);
141
158
  await sleep(this.#retryWait(attempt));
142
159
  continue;
143
160
  }
@@ -212,6 +229,12 @@ function failureSummary(r, count) {
212
229
  return `users.batch: ${r.failed} of ${count} users failed${shown.length > 0 ? ` (${shown.join(", ")})` : ""}`;
213
230
  }
214
231
  /** e.g. "YouGrow API 400 invalid: traits.plan: …". */
232
+ /** A timeout or network failure that outlasted the retries: status 0, retryable, the original error as `cause`. */
233
+ function transportError(err) {
234
+ const code = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError") ? "timeout" : "network_error";
235
+ const detail = err instanceof Error ? err.message : String(err);
236
+ return new YouGrowError(`YouGrow API ${code}: ${detail}`, 0, { error: code }, { cause: err });
237
+ }
215
238
  function apiError(status, body) {
216
239
  const b = asRecord(body);
217
240
  const fields = Array.isArray(b?.fields) ? b.fields : [];
@@ -28,6 +28,30 @@ export type VerifyResult = {
28
28
  ok: false;
29
29
  reason: JwtFailure | "keys_unavailable";
30
30
  };
31
+ /** What YouGrow POSTs to your webhook endpoint: one of these, by `type`. Reply 2xx to any type you don't handle. */
32
+ export type WebhookEvent = WebhookEnvelope<"email_preferences.updated",
33
+ /** The person unsubscribed from one of YouGrow's emails: from one category, or all of them. */
34
+ {
35
+ userId: string;
36
+ category: string;
37
+ subscribed: false;
38
+ scope: "all" | "category";
39
+ source: string;
40
+ }>
41
+ /** YouGrow stopped emailing the person: their address hard-bounced, or they reported an email as spam. */
42
+ | WebhookEnvelope<"email.suppressed", {
43
+ userId: string;
44
+ reason: "hard_bounce" | "complaint";
45
+ }>
46
+ /** The Test webhook button. */
47
+ | WebhookEnvelope<"connection.test", Record<string, never>>;
48
+ export interface WebhookEnvelope<T extends string, D> {
49
+ /** Unique per webhook, and the same on every retry: drop ones you've seen. */
50
+ id: string;
51
+ type: T;
52
+ createdAt: string;
53
+ data: D;
54
+ }
31
55
  export interface VerifierOptions {
32
56
  /** Your connection's key id — the token's audience. */
33
57
  keyId: string;
package/dist/index.d.ts CHANGED
@@ -12,6 +12,34 @@
12
12
  * status throws a YouGrowError straight away.
13
13
  */
14
14
  export type ConsentBasis = "consent" | "soft_opt_in" | "corporate_subscriber" | "none";
15
+ /** How a person relates to one of their entities. Only what they own counts toward their onboarding. */
16
+ export type EntityRole = "owner" | "member" | "invited";
17
+ /**
18
+ * One of the things a person has several of — a workspace, a brand, a project —
19
+ * in a write. It merges like the user; `kind` is required the first time.
20
+ */
21
+ export interface EntityPatch {
22
+ /** What it is, in your product's words: "brand", "workspace", "project". */
23
+ kind?: string;
24
+ name?: string | null;
25
+ /** The entity it sits inside, e.g. a brand's workspace. */
26
+ parentId?: string | null;
27
+ role?: EntityRole | null;
28
+ steps?: Record<string, string | null>;
29
+ facts?: Record<string, number | string | boolean | null>;
30
+ /** When the person last worked on it. */
31
+ activeAt?: string | null;
32
+ }
33
+ /** One entity as YouGrow holds it. */
34
+ export interface EntityState {
35
+ kind: string;
36
+ name: string | null;
37
+ parentId: string | null;
38
+ role: EntityRole | null;
39
+ steps: Record<string, string>;
40
+ facts: Record<string, string | number | boolean>;
41
+ activeAt: string | null;
42
+ }
15
43
  /**
16
44
  * Any subset of a user's state, as a JSON Merge Patch (RFC 7396): fields sent
17
45
  * replace YouGrow's, fields left out stay, `null` clears, and `steps`, `facts`
@@ -42,6 +70,8 @@ export interface UserPatch {
42
70
  facts?: Record<string, number | string | boolean | null>;
43
71
  /** Anything else journeys branch on (null removes a key). */
44
72
  traits?: Record<string, string | number | boolean | null>;
73
+ /** The things this person has several of (workspaces, brands…), by your id; null removes one. */
74
+ entities?: Record<string, EntityPatch | null>;
45
75
  /** When you read this state. A write older than the stored one is ignored. */
46
76
  updatedAt?: string;
47
77
  }
@@ -62,15 +92,18 @@ export interface UserState {
62
92
  steps: Record<string, string>;
63
93
  facts: Record<string, string | number | boolean>;
64
94
  traits: Record<string, string | number | boolean>;
95
+ entities: Record<string, EntityState>;
65
96
  updatedAt: string | null;
66
97
  }
67
98
  /** `users.get` adds what YouGrow decided: journeys and opt-outs. */
68
99
  export interface UserView extends UserState {
100
+ /** `entityId`: the entity an enrolment is about, when its journey is about one of them. */
69
101
  enrolments: Array<{
70
102
  journeyId: string;
71
103
  status: string;
72
104
  mode: string;
73
105
  enrolledAt: string;
106
+ entityId?: string | null;
74
107
  }>;
75
108
  /** Unsubscribes made in YouGrow's emails. They hold until the person lifts them; the API can't. */
76
109
  optOuts: Array<{
@@ -81,9 +114,12 @@ export interface UserView extends UserState {
81
114
  }
82
115
  /** Why a write was ignored: older than the stored state, or than the user's deletion. */
83
116
  export type SkipReason = "stale_write" | "deleted_later";
84
- export type PatchResponse = {
117
+ export type PatchResponse =
118
+ /** `ignoredFields`: profile fields whose value was invalid, so left as they were; the rest applied. */
119
+ {
85
120
  applied: true;
86
121
  user: UserState;
122
+ ignoredFields?: FieldError[];
87
123
  } | {
88
124
  applied: false;
89
125
  reason: SkipReason;
@@ -103,15 +139,30 @@ export interface BatchResponse {
103
139
  applied: number;
104
140
  ignored: number;
105
141
  failed: number;
106
- /** Only the ignored and failed items; applied ones are counted. `index` is the item's position in your array. */
142
+ /**
143
+ * The ignored and failed items, and applied ones whose invalid profile fields were
144
+ * left as they were (reason `fields_ignored`). `index` is the item's position in your array.
145
+ */
107
146
  results: Array<{
108
147
  index: number;
109
148
  userId: string | null;
110
- status: "ignored" | "failed";
149
+ status: "applied" | "ignored" | "failed";
111
150
  reason: string;
112
151
  fields?: FieldError[];
113
152
  }>;
114
153
  }
154
+ /** The connection behind your key (`GET /api/v2/me`). */
155
+ export interface MeResponse {
156
+ connection: {
157
+ id: string;
158
+ name: string;
159
+ environment: "staging" | "production" | null;
160
+ status: "active" | "paused" | "revoked";
161
+ };
162
+ keyId: string;
163
+ /** A new secret was issued in the last 24 hours; the previous one works until then. */
164
+ rotating: boolean;
165
+ }
115
166
  export interface EventResult {
116
167
  recorded: boolean;
117
168
  duplicate: boolean;
@@ -147,6 +198,8 @@ export interface TrackOptions {
147
198
  occurredAt?: string;
148
199
  /** The same key is recorded once. Defaults to a random key per call, so the SDK's own retries never count twice. */
149
200
  idempotencyKey?: string;
201
+ /** The entity it happened to (one of the user's `entities`), e.g. the brand an audit ran on. */
202
+ entityId?: string;
150
203
  }
151
204
  export interface UsersApi {
152
205
  /** Merge a patch into one user's state; creates the user if YouGrow hasn't seen them. */
@@ -166,15 +219,26 @@ export interface EventsApi {
166
219
  /** Record a milestone, e.g. "report.exported". Optional: journeys run on state. */
167
220
  track(userId: string, event: string, opts?: TrackOptions): Promise<EventResult>;
168
221
  }
169
- /** The API refused a request, or still failed (429, 5xx) after the retries. */
222
+ /**
223
+ * The API refused a request, or it still failed after the retries: a 429, a 5xx,
224
+ * or a timeout or network failure (`status` 0, `code` `timeout` or `network_error`).
225
+ */
170
226
  export declare class YouGrowError extends Error {
171
227
  readonly status: number;
172
228
  readonly body?: unknown | undefined;
173
- /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), or `http_<status>` when the body has none. */
229
+ /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), `timeout` or `network_error`, or `http_<status>`. */
174
230
  readonly code: string;
175
231
  /** For a 400: which fields were wrong, and why. */
176
232
  readonly fields?: FieldError[];
177
- constructor(message: string, status: number, body?: unknown | undefined);
233
+ /**
234
+ * True for a 429, a 5xx, a timeout or a network failure: trying again later may
235
+ * work, so a queue or trigger should rethrow it for redelivery. Anything else
236
+ * (a 400, 401, 404…) won't succeed as it is.
237
+ */
238
+ readonly retryable: boolean;
239
+ constructor(message: string, status: number, body?: unknown | undefined, options?: {
240
+ cause?: unknown;
241
+ });
178
242
  }
179
243
  /** From `users.batch` with `throwOnItemError`: some items failed. The rest were applied; `result` says which. */
180
244
  export declare class YouGrowBatchError extends Error {
@@ -186,4 +250,9 @@ export declare class YouGrow {
186
250
  readonly users: UsersApi;
187
251
  readonly events: EventsApi;
188
252
  constructor(opts: YouGrowOptions);
253
+ /**
254
+ * The connection behind your key: its name, environment and status. A credential
255
+ * check — and a way to catch a key from the wrong environment — before you send.
256
+ */
257
+ me(): Promise<MeResponse>;
189
258
  }
package/dist/index.js CHANGED
@@ -8,16 +8,25 @@ const BATCH_ENVELOPE_BYTES = '{"users":[]}'.length;
8
8
  const MAX_USER_ID = 256;
9
9
  /** The longest delay a Node timer accepts. */
10
10
  const MAX_TIMER_MS = 2_147_483_647;
11
- /** The API refused a request, or still failed (429, 5xx) after the retries. */
11
+ /**
12
+ * The API refused a request, or it still failed after the retries: a 429, a 5xx,
13
+ * or a timeout or network failure (`status` 0, `code` `timeout` or `network_error`).
14
+ */
12
15
  export class YouGrowError extends Error {
13
16
  status;
14
17
  body;
15
- /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), or `http_<status>` when the body has none. */
18
+ /** The API's error code (`invalid`, `unauthorized`, `rate_limited`…), `timeout` or `network_error`, or `http_<status>`. */
16
19
  code;
17
20
  /** For a 400: which fields were wrong, and why. */
18
21
  fields;
19
- constructor(message, status, body) {
20
- super(message);
22
+ /**
23
+ * True for a 429, a 5xx, a timeout or a network failure: trying again later may
24
+ * work, so a queue or trigger should rethrow it for redelivery. Anything else
25
+ * (a 400, 401, 404…) won't succeed as it is.
26
+ */
27
+ retryable;
28
+ constructor(message, status, body, options) {
29
+ super(message, options);
21
30
  this.status = status;
22
31
  this.body = body;
23
32
  this.name = "YouGrowError";
@@ -25,6 +34,7 @@ export class YouGrowError extends Error {
25
34
  this.code = typeof b?.error === "string" ? b.error : `http_${status}`;
26
35
  if (Array.isArray(b?.fields))
27
36
  this.fields = b.fields;
37
+ this.retryable = status === 0 || status === 429 || status >= 500;
28
38
  }
29
39
  }
30
40
  /** From `users.batch` with `throwOnItemError`: some items failed. The rest were applied; `result` says which. */
@@ -78,13 +88,20 @@ export class YouGrow {
78
88
  this.events = {
79
89
  track: async (userId, event, options = {}) => {
80
90
  const path = `${userPath(userId)}/events`;
81
- const { properties, occurredAt } = options;
91
+ const { properties, occurredAt, entityId } = options;
82
92
  // One key for every attempt, so a retry is never recorded twice.
83
- const body = { event, properties, occurredAt, idempotencyKey: options.idempotencyKey ?? randomUUID() };
93
+ const body = { event, properties, occurredAt, entityId, idempotencyKey: options.idempotencyKey ?? randomUUID() };
84
94
  return (await this.#send("POST", path, JSON.stringify(body)));
85
95
  },
86
96
  };
87
97
  }
98
+ /**
99
+ * The connection behind your key: its name, environment and status. A credential
100
+ * check — and a way to catch a key from the wrong environment — before you send.
101
+ */
102
+ async me() {
103
+ return (await this.#send("GET", "/api/v2/me"));
104
+ }
88
105
  async #patchMany(items, opts = {}) {
89
106
  if (!Array.isArray(items))
90
107
  throw new TypeError("YouGrow: users.batch takes an array of { userId, ...patch }");
@@ -132,7 +149,7 @@ export class YouGrow {
132
149
  catch (err) {
133
150
  // Network error or timeout.
134
151
  if (attempt >= this.#maxRetries)
135
- throw err;
152
+ throw transportError(err);
136
153
  await sleep(this.#retryWait(attempt));
137
154
  continue;
138
155
  }
@@ -206,6 +223,12 @@ function failureSummary(r, count) {
206
223
  return `users.batch: ${r.failed} of ${count} users failed${shown.length > 0 ? ` (${shown.join(", ")})` : ""}`;
207
224
  }
208
225
  /** e.g. "YouGrow API 400 invalid: traits.plan: …". */
226
+ /** A timeout or network failure that outlasted the retries: status 0, retryable, the original error as `cause`. */
227
+ function transportError(err) {
228
+ const code = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError") ? "timeout" : "network_error";
229
+ const detail = err instanceof Error ? err.message : String(err);
230
+ return new YouGrowError(`YouGrow API ${code}: ${detail}`, 0, { error: code }, { cause: err });
231
+ }
209
232
  function apiError(status, body) {
210
233
  const b = asRecord(body);
211
234
  const fields = Array.isArray(b?.fields) ? b.fields : [];
package/dist/server.d.ts CHANGED
@@ -28,6 +28,30 @@ export type VerifyResult = {
28
28
  ok: false;
29
29
  reason: JwtFailure | "keys_unavailable";
30
30
  };
31
+ /** What YouGrow POSTs to your webhook endpoint: one of these, by `type`. Reply 2xx to any type you don't handle. */
32
+ export type WebhookEvent = WebhookEnvelope<"email_preferences.updated",
33
+ /** The person unsubscribed from one of YouGrow's emails: from one category, or all of them. */
34
+ {
35
+ userId: string;
36
+ category: string;
37
+ subscribed: false;
38
+ scope: "all" | "category";
39
+ source: string;
40
+ }>
41
+ /** YouGrow stopped emailing the person: their address hard-bounced, or they reported an email as spam. */
42
+ | WebhookEnvelope<"email.suppressed", {
43
+ userId: string;
44
+ reason: "hard_bounce" | "complaint";
45
+ }>
46
+ /** The Test webhook button. */
47
+ | WebhookEnvelope<"connection.test", Record<string, never>>;
48
+ export interface WebhookEnvelope<T extends string, D> {
49
+ /** Unique per webhook, and the same on every retry: drop ones you've seen. */
50
+ id: string;
51
+ type: T;
52
+ createdAt: string;
53
+ data: D;
54
+ }
31
55
  export interface VerifierOptions {
32
56
  /** Your connection's key id — the token's audience. */
33
57
  keyId: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yougrowai/node",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Keep your users' state in YouGrow lifecycle journeys, and verify the requests YouGrow sends you.",
5
5
  "license": "MIT",
6
6
  "author": "YouGrow.AI Limited",
@@ -22,7 +22,8 @@
22
22
  "./server": {
23
23
  "import": { "types": "./dist/server.d.ts", "default": "./dist/server.js" },
24
24
  "require": { "types": "./dist/cjs/server.d.ts", "default": "./dist/cjs/server.js" }
25
- }
25
+ },
26
+ "./package.json": "./package.json"
26
27
  },
27
28
  "typesVersions": {
28
29
  "*": { "server": ["./dist/cjs/server.d.ts"] }