@onemrr/node 0.1.0 → 0.2.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
@@ -1,6 +1,9 @@
1
1
  # @onemrr/node
2
2
 
3
- Server-side activity tracking for [OneMRR](https://app.onemrr.dev) Churn Signals. Tell OneMRR which of your customer accounts are using your product, so it can spot paying customers whose usage drops before they cancel.
3
+ Server-side client for [OneMRR](https://app.onemrr.dev):
4
+
5
+ - **Churn Signals:** tell OneMRR which of your customer accounts are using your product, so it can spot paying customers whose usage drops before they cancel.
6
+ - **Trial conversion:** record the free trials your app starts, so OneMRR counts every trial, including the ones your billing provider never sees, and how many convert.
4
7
 
5
8
  No dependencies. Node 20 or later.
6
9
 
@@ -31,11 +34,34 @@ onemrr.track({ accountId: "merchant_123", event: "event_published" });
31
34
  await onemrr.flush();
32
35
  ```
33
36
 
34
- Create a secret key in OneMRR under **Settings → API keys**. A key limited to tracking can only identify accounts and track events. Keep it on your server: the SDK refuses to run in a browser, and OneMRR refuses secret keys sent from one.
37
+ ## Trials
38
+
39
+ If your app starts free trials itself (before anyone picks a plan in Stripe or Shopify), send each one when it starts. It converts when the same customer's first payment arrives in billing.
40
+
41
+ ```ts
42
+ await onemrr.trial({
43
+ externalId: `shop_${shop.id}:${startedAt.toISOString()}`, // a restarted trial gets a new ID
44
+ unitKey: String(shop.id), // what you count by in OneMRR, or the billing customer's ID
45
+ name: shop.name,
46
+ startedAt,
47
+ endsAt, // optional: defaults to the trial length in Settings → Trials
48
+ links: { shopifyDomain: shop.domain }, // optional: for shops billed through your Shopify app
49
+ attributes: { channel: "etsy" }, // optional: to split trials by
50
+ });
51
+
52
+ // Past trials, 500 a request. Sending the same externalId again is safe.
53
+ await onemrr.trialMany(pastTrials);
54
+ ```
55
+
56
+ Set **Settings → Trials** in OneMRR to say your trials start **In our app**. See [Trial conversion](https://docs.onemrr.dev/analytics/trials).
57
+
58
+ ## Keys
59
+
60
+ Create a secret key in OneMRR under **Settings → API keys**. A key limited to tracking can only identify accounts and track events; recording trials needs a full secret key. Keep it on your server: the SDK refuses to run in a browser, and OneMRR refuses secret keys sent from one.
35
61
 
36
62
  ## What is sent
37
63
 
38
- Only your account ID, the event name and its time. No properties, page URLs, IP addresses or user details. Each event carries a generated ID, so retries are counted once.
64
+ For tracking, only your account ID, the event name and its time. No properties, page URLs, IP addresses or user details. Each event carries a generated ID, so retries are counted once. Trials send only the fields you pass to `trial()`.
39
65
 
40
66
  ## API
41
67
 
@@ -45,6 +71,8 @@ Only your account ID, the event name and its time. No properties, page URLs, IP
45
71
  - `flush()`: sends the queue now.
46
72
  - `verify()`: checks the key and reports the last event OneMRR received.
47
73
  - `shutdown()`: flushes before your process exits.
74
+ - `trial({ externalId, unitKey?, name?, startedAt, endsAt?, links?, attributes? })`: records a free trial. Needs `unitKey` or one of `links.shopifyDomain`, `links.stripeCustomer`, `links.customerExternalId`. Resolves `{ external_id, status, matched }`, or `null` if it couldn't be sent. Never throws.
75
+ - `trialMany(inputs)`: the same for any number of trials, 500 per request. Resolves the counts and each result, by its index in `inputs`.
48
76
 
49
77
  Options: `baseUrl`, `flushAt` (default 50), `flushInterval` (default 5000 ms), `timeout` (default 10000 ms), `maxRetries` (default 3), `onError`, `disabled`.
50
78
 
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
- * @onemrr/node — tell OneMRR which accounts use your product, from your server.
2
+ * @onemrr/node — tell OneMRR which accounts use your product, and the free trials your app
3
+ * starts, from your server.
3
4
  *
4
5
  * import { OneMRR } from "@onemrr/node";
5
6
  * const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
6
7
  * await onemrr.identify({ accountId: "merchant_123", source: "shopify", externalCustomerId: "shop.myshopify.com" });
7
8
  * onemrr.track({ accountId: "merchant_123", event: "event_published" });
9
+ * await onemrr.trial({ externalId: "shop_48213:2026-11-02", unitKey: "48213", startedAt: new Date(), endsAt: inSevenDays });
8
10
  * await onemrr.flush(); // before a serverless function returns
9
11
  *
10
12
  * Events are queued and sent in batches, each with a unique id, so a retry never counts
@@ -61,6 +63,31 @@ export interface TrackInput {
61
63
  /** A unique event ID; generated when left out. */
62
64
  id?: string;
63
65
  }
66
+ export interface TrialInput {
67
+ /** Your ID for this trial. Sending it again updates the trial; a restarted trial gets a new one. */
68
+ externalId: string;
69
+ /** What the trial belongs to: with Count by, the subscription metadata value you count by (a shop ID); otherwise the billing customer's ID. */
70
+ unitKey?: string;
71
+ /** What to call it until billing knows the customer. */
72
+ name?: string;
73
+ startedAt: string | Date;
74
+ /** When it ends; without it, the trial length in Settings → Trials. */
75
+ endsAt?: string | Date | null;
76
+ /** The billing customer, when billing doesn't carry your unit key. */
77
+ links?: {
78
+ shopifyDomain?: string;
79
+ stripeCustomer?: string;
80
+ customerExternalId?: string;
81
+ };
82
+ /** Up to 50 strings to split and leave out trials by, such as the channel. */
83
+ attributes?: Record<string, string>;
84
+ }
85
+ export interface TrialResult {
86
+ external_id: string;
87
+ status: "created" | "updated" | "unchanged";
88
+ /** Whether OneMRR already knows the unit or billing customer. Unmatched trials still count. */
89
+ matched: boolean;
90
+ }
64
91
  export interface IdentifyResult {
65
92
  account_id: string;
66
93
  status: "created" | "updated" | "unchanged";
@@ -89,7 +116,7 @@ export declare class OneMRRError extends Error {
89
116
  readonly type?: string | undefined;
90
117
  constructor(message: string, status?: number | undefined, type?: string | undefined);
91
118
  }
92
- export declare const VERSION = "0.1.0";
119
+ export declare const VERSION = "0.2.0";
93
120
  /** A UUID v7: time-ordered, so OneMRR's dedup index stays compact. */
94
121
  export declare function eventId(now?: number): string;
95
122
  export declare class OneMRR {
@@ -113,6 +140,24 @@ export declare class OneMRR {
113
140
  identifyMany(inputs: IdentifyInput[]): Promise<{
114
141
  results: IdentifyResult[];
115
142
  } | null>;
143
+ /**
144
+ * Records a free trial your app started (POST /api/v1/trials). Needs a full secret key, not one
145
+ * limited to tracking. Never throws: resolves null, after reporting to onError, if it couldn't be sent.
146
+ */
147
+ trial(input: TrialInput): Promise<TrialResult | null>;
148
+ /** Records up to 500 trials per request, for a backfill of past trials. Resolves null if a batch couldn't be sent. */
149
+ trialMany(inputs: TrialInput[]): Promise<{
150
+ counts: {
151
+ created: number;
152
+ updated: number;
153
+ unchanged: number;
154
+ failed: number;
155
+ };
156
+ results: (TrialResult & {
157
+ index: number;
158
+ })[];
159
+ } | null>;
160
+ private toTrial;
116
161
  /** Queues an event. Never throws; invalid events are reported to onError and dropped. */
117
162
  track(input: TrackInput): void;
118
163
  /**
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
- * @onemrr/node — tell OneMRR which accounts use your product, from your server.
2
+ * @onemrr/node — tell OneMRR which accounts use your product, and the free trials your app
3
+ * starts, from your server.
3
4
  *
4
5
  * import { OneMRR } from "@onemrr/node";
5
6
  * const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
6
7
  * await onemrr.identify({ accountId: "merchant_123", source: "shopify", externalCustomerId: "shop.myshopify.com" });
7
8
  * onemrr.track({ accountId: "merchant_123", event: "event_published" });
9
+ * await onemrr.trial({ externalId: "shop_48213:2026-11-02", unitKey: "48213", startedAt: new Date(), endsAt: inSevenDays });
8
10
  * await onemrr.flush(); // before a serverless function returns
9
11
  *
10
12
  * Events are queued and sent in batches, each with a unique id, so a retry never counts
@@ -23,7 +25,7 @@ export class OneMRRError extends Error {
23
25
  const EVENT_RE = /^[a-z0-9][a-z0-9_.:-]{0,63}$/i;
24
26
  const MAX_QUEUE = 10_000;
25
27
  const BATCH = 500;
26
- export const VERSION = "0.1.0";
28
+ export const VERSION = "0.2.0";
27
29
  /** A UUID v7: time-ordered, so OneMRR's dedup index stays compact. */
28
30
  export function eventId(now = Date.now()) {
29
31
  const b = new Uint8Array(16);
@@ -103,6 +105,75 @@ export class OneMRR {
103
105
  }
104
106
  return { results: out };
105
107
  }
108
+ /**
109
+ * Records a free trial your app started (POST /api/v1/trials). Needs a full secret key, not one
110
+ * limited to tracking. Never throws: resolves null, after reporting to onError, if it couldn't be sent.
111
+ */
112
+ async trial(input) {
113
+ if (this.disabled)
114
+ return null;
115
+ const body = this.toTrial(input);
116
+ if (!body)
117
+ return null;
118
+ return this.request("POST", "/api/v1/trials", body);
119
+ }
120
+ /** Records up to 500 trials per request, for a backfill of past trials. Resolves null if a batch couldn't be sent. */
121
+ async trialMany(inputs) {
122
+ if (this.disabled)
123
+ return null;
124
+ const counts = { created: 0, updated: 0, unchanged: 0, failed: 0 };
125
+ const results = [];
126
+ for (let i = 0; i < inputs.length; i += BATCH) {
127
+ const chunk = inputs.slice(i, i + BATCH);
128
+ const trials = chunk.map((t) => this.toTrial(t));
129
+ const valid = trials.filter((t) => t != null);
130
+ counts.failed += trials.length - valid.length;
131
+ if (!valid.length)
132
+ continue;
133
+ const r = await this.request("POST", "/api/v1/trials/batch", { trials: valid });
134
+ if (!r)
135
+ return null;
136
+ for (const k of Object.keys(counts))
137
+ counts[k] += r.counts[k] ?? 0;
138
+ // Indexes into `inputs`, skipping the ones refused locally.
139
+ const sent = trials.map((t, n) => (t ? i + n : -1)).filter((n) => n >= 0);
140
+ results.push(...r.results.map((x) => ({ ...x, index: sent[x.index] ?? x.index })));
141
+ }
142
+ return { counts, results };
143
+ }
144
+ toTrial(t) {
145
+ const iso = (v) => {
146
+ if (v == null)
147
+ return undefined;
148
+ const d = new Date(v);
149
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
150
+ };
151
+ const started = iso(t?.startedAt);
152
+ const ends = iso(t?.endsAt);
153
+ const links = Object.fromEntries(Object.entries({ shopify_domain: t?.links?.shopifyDomain, stripe_customer: t?.links?.stripeCustomer, customer_external_id: t?.links?.customerExternalId }).filter(([, v]) => v));
154
+ const problem = !t?.externalId
155
+ ? "trial needs externalId"
156
+ : !started
157
+ ? `Invalid startedAt for trial ${t.externalId}`
158
+ : ends === null
159
+ ? `Invalid endsAt for trial ${t.externalId}`
160
+ : !t.unitKey && !Object.keys(links).length
161
+ ? `Trial ${t.externalId} needs unitKey or a link to the billing customer`
162
+ : null;
163
+ if (problem) {
164
+ this.fail(new OneMRRError(problem, 400, "invalid_request"));
165
+ return null;
166
+ }
167
+ return {
168
+ external_id: String(t.externalId),
169
+ ...(t.unitKey ? { unit_key: String(t.unitKey) } : {}),
170
+ ...(t.name ? { name: t.name } : {}),
171
+ started_at: started,
172
+ ...(ends ? { ends_at: ends } : {}),
173
+ ...(Object.keys(links).length ? { links } : {}),
174
+ ...(t.attributes ? { attributes: t.attributes } : {}),
175
+ };
176
+ }
106
177
  /** Queues an event. Never throws; invalid events are reported to onError and dropped. */
107
178
  track(input) {
108
179
  if (this.disabled)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@onemrr/node",
3
- "version": "0.1.0",
4
- "description": "Server-side activity tracking for OneMRR Churn Signals: identify accounts, track key events.",
3
+ "version": "0.2.0",
4
+ "description": "Server-side client for OneMRR: identify accounts and track key events for Churn Signals, and record free trials for trial conversion.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -27,7 +27,8 @@
27
27
  "churn",
28
28
  "mrr",
29
29
  "analytics",
30
- "saas"
30
+ "saas",
31
+ "trials"
31
32
  ],
32
33
  "scripts": {
33
34
  "build": "tsc -p tsconfig.build.json",