@onemrr/node 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +78 -2
- package/dist/index.d.ts +183 -0
- package/dist/index.js +337 -0
- package/package.json +40 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chris McCaw
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @onemrr/node
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
7
|
+
|
|
8
|
+
No dependencies. Node 20 or later.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install @onemrr/node
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Use
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { OneMRR } from "@onemrr/node";
|
|
18
|
+
|
|
19
|
+
const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
|
|
20
|
+
|
|
21
|
+
// Once per account (and whenever its billing changes): link your account ID to the
|
|
22
|
+
// customer in your billing source.
|
|
23
|
+
await onemrr.identify({
|
|
24
|
+
accountId: "merchant_123",
|
|
25
|
+
email: "merchant@example.com", // optional
|
|
26
|
+
source: "shopify",
|
|
27
|
+
externalCustomerId: "merchant-123.myshopify.com",
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// Whenever something meaningful happens. Queued and sent in batches.
|
|
31
|
+
onemrr.track({ accountId: "merchant_123", event: "event_published" });
|
|
32
|
+
|
|
33
|
+
// In serverless functions, before returning:
|
|
34
|
+
await onemrr.flush();
|
|
35
|
+
```
|
|
36
|
+
|
|
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.
|
|
61
|
+
|
|
62
|
+
## What is sent
|
|
63
|
+
|
|
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()`.
|
|
65
|
+
|
|
66
|
+
## API
|
|
67
|
+
|
|
68
|
+
- `identify({ accountId, name?, email?, links?, source?, sourceId?, externalCustomerId? })`: creates or updates the account and its billing links. Resolves the result, including each link's status (`linked`, `pending_customer`, `conflict`), or `null` if it couldn't be sent.
|
|
69
|
+
- `identifyMany(inputs)`: the same for up to 500 accounts per request.
|
|
70
|
+
- `track({ accountId, event, timestamp?, id? })`: queues an event. Never throws.
|
|
71
|
+
- `flush()`: sends the queue now.
|
|
72
|
+
- `verify()`: checks the key and reports the last event OneMRR received.
|
|
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`.
|
|
76
|
+
|
|
77
|
+
Options: `baseUrl`, `flushAt` (default 50), `flushInterval` (default 5000 ms), `timeout` (default 10000 ms), `maxRetries` (default 3), `onError`, `disabled`.
|
|
78
|
+
|
|
79
|
+
The REST API is documented at <https://app.onemrr.dev/api/v1/openapi.json>.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @onemrr/node — tell OneMRR which accounts use your product, and the free trials your app
|
|
3
|
+
* starts, from your server.
|
|
4
|
+
*
|
|
5
|
+
* import { OneMRR } from "@onemrr/node";
|
|
6
|
+
* const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
|
|
7
|
+
* await onemrr.identify({ accountId: "merchant_123", source: "shopify", externalCustomerId: "shop.myshopify.com" });
|
|
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 });
|
|
10
|
+
* await onemrr.flush(); // before a serverless function returns
|
|
11
|
+
*
|
|
12
|
+
* Events are queued and sent in batches, each with a unique id, so a retry never counts
|
|
13
|
+
* twice. Tracking never throws: problems go to `onError`. No dependencies; Node 20+.
|
|
14
|
+
*/
|
|
15
|
+
export type BillingSource = "stripe" | "shopify" | "wix" | "paddle" | "lemonsqueezy" | "csv" | "custom";
|
|
16
|
+
export interface OneMRROptions {
|
|
17
|
+
/** A secret key (sk_live_…) from OneMRR Settings → API keys. Keep it on your server. */
|
|
18
|
+
apiKey: string;
|
|
19
|
+
/** Defaults to https://app.onemrr.dev. */
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
/** Send once this many events are queued (default 50, at most 500). */
|
|
22
|
+
flushAt?: number;
|
|
23
|
+
/** And at least this often, in milliseconds (default 5000). */
|
|
24
|
+
flushInterval?: number;
|
|
25
|
+
/** Per request, in milliseconds (default 10000). */
|
|
26
|
+
timeout?: number;
|
|
27
|
+
/** Retries for network errors, 429 and 5xx (default 3). */
|
|
28
|
+
maxRetries?: number;
|
|
29
|
+
/** Called with every failure. Defaults to console.warn. */
|
|
30
|
+
onError?: (error: OneMRRError) => void;
|
|
31
|
+
/** Don't send anything (tests, local development). */
|
|
32
|
+
disabled?: boolean;
|
|
33
|
+
/** A fetch implementation (defaults to the global one). */
|
|
34
|
+
fetch?: typeof fetch;
|
|
35
|
+
}
|
|
36
|
+
export interface Link {
|
|
37
|
+
/** The billing source kind, when you have one source of that kind. */
|
|
38
|
+
source?: BillingSource;
|
|
39
|
+
/** Or the source's ID, from OneMRR's Sources page. */
|
|
40
|
+
sourceId?: number;
|
|
41
|
+
/** The customer's ID in that source: Stripe customer ID, myshopify domain, Wix instance ID. */
|
|
42
|
+
externalCustomerId: string;
|
|
43
|
+
}
|
|
44
|
+
export interface IdentifyInput {
|
|
45
|
+
/** Your own ID for the customer account. */
|
|
46
|
+
accountId: string;
|
|
47
|
+
name?: string | null;
|
|
48
|
+
/** Optional. Used only for retention emails when billing has no email. */
|
|
49
|
+
email?: string | null;
|
|
50
|
+
/** The billing customers this account pays through. */
|
|
51
|
+
links?: Link[];
|
|
52
|
+
/** Shorthand for a single link. */
|
|
53
|
+
source?: BillingSource;
|
|
54
|
+
sourceId?: number;
|
|
55
|
+
externalCustomerId?: string;
|
|
56
|
+
}
|
|
57
|
+
export interface TrackInput {
|
|
58
|
+
accountId: string;
|
|
59
|
+
/** A short name such as "event_published": letters, numbers, _ . : or -. */
|
|
60
|
+
event: string;
|
|
61
|
+
/** When it happened; defaults to now. */
|
|
62
|
+
timestamp?: string | Date;
|
|
63
|
+
/** A unique event ID; generated when left out. */
|
|
64
|
+
id?: string;
|
|
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
|
+
}
|
|
91
|
+
export interface IdentifyResult {
|
|
92
|
+
account_id: string;
|
|
93
|
+
status: "created" | "updated" | "unchanged";
|
|
94
|
+
links: {
|
|
95
|
+
source_id: number | null;
|
|
96
|
+
external_customer_id: string;
|
|
97
|
+
status: "linked" | "unchanged" | "pending_customer" | "conflict" | "error";
|
|
98
|
+
linked_to?: string;
|
|
99
|
+
error?: string;
|
|
100
|
+
}[];
|
|
101
|
+
}
|
|
102
|
+
export interface FlushResult {
|
|
103
|
+
sent: number;
|
|
104
|
+
accepted: number;
|
|
105
|
+
duplicates: number;
|
|
106
|
+
rejected: {
|
|
107
|
+
id: string;
|
|
108
|
+
event: string;
|
|
109
|
+
reason: string;
|
|
110
|
+
error: string;
|
|
111
|
+
}[];
|
|
112
|
+
failed: number;
|
|
113
|
+
}
|
|
114
|
+
export declare class OneMRRError extends Error {
|
|
115
|
+
readonly status?: number | undefined;
|
|
116
|
+
readonly type?: string | undefined;
|
|
117
|
+
constructor(message: string, status?: number | undefined, type?: string | undefined);
|
|
118
|
+
}
|
|
119
|
+
export declare const VERSION = "0.2.0";
|
|
120
|
+
/** A UUID v7: time-ordered, so OneMRR's dedup index stays compact. */
|
|
121
|
+
export declare function eventId(now?: number): string;
|
|
122
|
+
export declare class OneMRR {
|
|
123
|
+
private readonly key;
|
|
124
|
+
private readonly base;
|
|
125
|
+
private readonly flushAt;
|
|
126
|
+
private readonly interval;
|
|
127
|
+
private readonly timeout;
|
|
128
|
+
private readonly retries;
|
|
129
|
+
private readonly onError;
|
|
130
|
+
private readonly disabled;
|
|
131
|
+
private readonly fetchImpl;
|
|
132
|
+
private queue;
|
|
133
|
+
private timer;
|
|
134
|
+
private inflight;
|
|
135
|
+
private totals;
|
|
136
|
+
constructor(opts: OneMRROptions);
|
|
137
|
+
/** Creates or updates an account and its billing links. Resolves null if it couldn't be sent. */
|
|
138
|
+
identify(input: IdentifyInput): Promise<IdentifyResult | null>;
|
|
139
|
+
/** Identifies up to 500 accounts per request (for a backfill). */
|
|
140
|
+
identifyMany(inputs: IdentifyInput[]): Promise<{
|
|
141
|
+
results: IdentifyResult[];
|
|
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;
|
|
161
|
+
/** Queues an event. Never throws; invalid events are reported to onError and dropped. */
|
|
162
|
+
track(input: TrackInput): void;
|
|
163
|
+
/**
|
|
164
|
+
* Sends everything queued. Call before a short-lived process or function exits. Reports
|
|
165
|
+
* every event sent since the last flush() returned, including automatic batches.
|
|
166
|
+
*/
|
|
167
|
+
flush(): Promise<FlushResult>;
|
|
168
|
+
private send;
|
|
169
|
+
/** Checks the key and reports when OneMRR last received an event. */
|
|
170
|
+
verify(): Promise<{
|
|
171
|
+
ok: boolean;
|
|
172
|
+
lastEventAt: string | null;
|
|
173
|
+
message: string;
|
|
174
|
+
}>;
|
|
175
|
+
/** Flushes and stops the timer. */
|
|
176
|
+
shutdown(): Promise<FlushResult>;
|
|
177
|
+
/** Starts sending in the background; results are reported by the next flush(). */
|
|
178
|
+
private kick;
|
|
179
|
+
private schedule;
|
|
180
|
+
private fail;
|
|
181
|
+
/** JSON request with retries on network errors, 429 and 5xx. Resolves null after reporting a failure. */
|
|
182
|
+
private request;
|
|
183
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @onemrr/node — tell OneMRR which accounts use your product, and the free trials your app
|
|
3
|
+
* starts, from your server.
|
|
4
|
+
*
|
|
5
|
+
* import { OneMRR } from "@onemrr/node";
|
|
6
|
+
* const onemrr = new OneMRR({ apiKey: process.env.ONEMRR_API_KEY! });
|
|
7
|
+
* await onemrr.identify({ accountId: "merchant_123", source: "shopify", externalCustomerId: "shop.myshopify.com" });
|
|
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 });
|
|
10
|
+
* await onemrr.flush(); // before a serverless function returns
|
|
11
|
+
*
|
|
12
|
+
* Events are queued and sent in batches, each with a unique id, so a retry never counts
|
|
13
|
+
* twice. Tracking never throws: problems go to `onError`. No dependencies; Node 20+.
|
|
14
|
+
*/
|
|
15
|
+
export class OneMRRError extends Error {
|
|
16
|
+
status;
|
|
17
|
+
type;
|
|
18
|
+
constructor(message, status, type) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.type = type;
|
|
22
|
+
this.name = "OneMRRError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const EVENT_RE = /^[a-z0-9][a-z0-9_.:-]{0,63}$/i;
|
|
26
|
+
const MAX_QUEUE = 10_000;
|
|
27
|
+
const BATCH = 500;
|
|
28
|
+
export const VERSION = "0.2.0";
|
|
29
|
+
/** A UUID v7: time-ordered, so OneMRR's dedup index stays compact. */
|
|
30
|
+
export function eventId(now = Date.now()) {
|
|
31
|
+
const b = new Uint8Array(16);
|
|
32
|
+
crypto.getRandomValues(b);
|
|
33
|
+
let t = now;
|
|
34
|
+
for (let i = 5; i >= 0; i--) {
|
|
35
|
+
b[i] = t & 0xff;
|
|
36
|
+
t = Math.floor(t / 256);
|
|
37
|
+
}
|
|
38
|
+
b[6] = (b[6] & 0x0f) | 0x70;
|
|
39
|
+
b[8] = (b[8] & 0x3f) | 0x80;
|
|
40
|
+
const h = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
41
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
42
|
+
}
|
|
43
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
44
|
+
export class OneMRR {
|
|
45
|
+
key;
|
|
46
|
+
base;
|
|
47
|
+
flushAt;
|
|
48
|
+
interval;
|
|
49
|
+
timeout;
|
|
50
|
+
retries;
|
|
51
|
+
onError;
|
|
52
|
+
disabled;
|
|
53
|
+
fetchImpl;
|
|
54
|
+
queue = [];
|
|
55
|
+
timer = null;
|
|
56
|
+
inflight = null;
|
|
57
|
+
totals = { sent: 0, accepted: 0, duplicates: 0, rejected: [], failed: 0 };
|
|
58
|
+
constructor(opts) {
|
|
59
|
+
if (!opts?.apiKey && !opts?.disabled)
|
|
60
|
+
throw new OneMRRError("OneMRR: apiKey is required (sk_live_…)");
|
|
61
|
+
if (opts.apiKey?.startsWith("pk_"))
|
|
62
|
+
throw new OneMRRError("OneMRR: that's a publishable key. @onemrr/node needs a secret key (sk_live_…) from Settings → API keys.");
|
|
63
|
+
const g = globalThis;
|
|
64
|
+
if (g.window !== undefined && g.document !== undefined)
|
|
65
|
+
throw new OneMRRError("OneMRR: @onemrr/node runs on your server. Never put a secret key in browser code.");
|
|
66
|
+
this.key = opts.apiKey;
|
|
67
|
+
this.base = (opts.baseUrl ?? "https://app.onemrr.dev").replace(/\/$/, "");
|
|
68
|
+
this.flushAt = Math.min(BATCH, Math.max(1, opts.flushAt ?? 50));
|
|
69
|
+
this.interval = Math.max(100, opts.flushInterval ?? 5000);
|
|
70
|
+
this.timeout = opts.timeout ?? 10_000;
|
|
71
|
+
this.retries = Math.max(0, opts.maxRetries ?? 3);
|
|
72
|
+
this.onError = opts.onError ?? ((e) => console.warn(`[onemrr] ${e.message}`));
|
|
73
|
+
this.disabled = Boolean(opts.disabled);
|
|
74
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
75
|
+
}
|
|
76
|
+
/** Creates or updates an account and its billing links. Resolves null if it couldn't be sent. */
|
|
77
|
+
async identify(input) {
|
|
78
|
+
if (this.disabled)
|
|
79
|
+
return null;
|
|
80
|
+
const body = toIdentify(input);
|
|
81
|
+
if (!body) {
|
|
82
|
+
this.fail(new OneMRRError("identify needs accountId"));
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
const r = await this.request("POST", "/api/v1/identify", body);
|
|
86
|
+
for (const l of r?.links ?? []) {
|
|
87
|
+
if (l.status === "conflict")
|
|
88
|
+
this.fail(new OneMRRError(`${l.external_customer_id} is already linked to account ${l.linked_to}; resolve it in OneMRR (Churn → Activity).`, 409, "conflict"));
|
|
89
|
+
if (l.status === "error")
|
|
90
|
+
this.fail(new OneMRRError(l.error ?? "Link failed", 422, "invalid_request"));
|
|
91
|
+
}
|
|
92
|
+
return r;
|
|
93
|
+
}
|
|
94
|
+
/** Identifies up to 500 accounts per request (for a backfill). */
|
|
95
|
+
async identifyMany(inputs) {
|
|
96
|
+
if (this.disabled)
|
|
97
|
+
return null;
|
|
98
|
+
const out = [];
|
|
99
|
+
for (let i = 0; i < inputs.length; i += BATCH) {
|
|
100
|
+
const identities = inputs.slice(i, i + BATCH).map(toIdentify).filter(Boolean);
|
|
101
|
+
const r = await this.request("POST", "/api/v1/identify/batch", { identities });
|
|
102
|
+
if (!r)
|
|
103
|
+
return null;
|
|
104
|
+
out.push(...r.results);
|
|
105
|
+
}
|
|
106
|
+
return { results: out };
|
|
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
|
+
}
|
|
177
|
+
/** Queues an event. Never throws; invalid events are reported to onError and dropped. */
|
|
178
|
+
track(input) {
|
|
179
|
+
if (this.disabled)
|
|
180
|
+
return;
|
|
181
|
+
const accountId = input?.accountId == null ? "" : String(input.accountId).trim();
|
|
182
|
+
if (!accountId || accountId.length > 200)
|
|
183
|
+
return this.fail(new OneMRRError("track needs accountId (up to 200 characters)"));
|
|
184
|
+
if (typeof input.event !== "string" || !EVENT_RE.test(input.event))
|
|
185
|
+
return this.fail(new OneMRRError(`Invalid event name "${String(input.event)}": use 1–64 letters, numbers, _ . : or -`));
|
|
186
|
+
const at = input.timestamp == null ? new Date() : new Date(input.timestamp);
|
|
187
|
+
if (Number.isNaN(at.getTime()))
|
|
188
|
+
return this.fail(new OneMRRError(`Invalid timestamp for ${input.event}`));
|
|
189
|
+
if (this.queue.length >= MAX_QUEUE) {
|
|
190
|
+
this.queue.shift();
|
|
191
|
+
this.fail(new OneMRRError("Queue full; dropped the oldest event. Is OneMRR reachable?"));
|
|
192
|
+
}
|
|
193
|
+
this.queue.push({ id: input.id ?? eventId(), account_id: accountId, event: input.event.toLowerCase(), timestamp: at.toISOString() });
|
|
194
|
+
if (this.queue.length >= this.flushAt)
|
|
195
|
+
this.kick();
|
|
196
|
+
else
|
|
197
|
+
this.schedule();
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Sends everything queued. Call before a short-lived process or function exits. Reports
|
|
201
|
+
* every event sent since the last flush() returned, including automatic batches.
|
|
202
|
+
*/
|
|
203
|
+
async flush() {
|
|
204
|
+
if (this.timer)
|
|
205
|
+
clearTimeout(this.timer);
|
|
206
|
+
this.timer = null;
|
|
207
|
+
while (this.inflight)
|
|
208
|
+
await this.inflight;
|
|
209
|
+
if (this.queue.length) {
|
|
210
|
+
this.inflight = this.send().finally(() => (this.inflight = null));
|
|
211
|
+
await this.inflight;
|
|
212
|
+
}
|
|
213
|
+
const out = this.totals;
|
|
214
|
+
this.totals = { sent: 0, accepted: 0, duplicates: 0, rejected: [], failed: 0 };
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
217
|
+
async send() {
|
|
218
|
+
const total = this.totals;
|
|
219
|
+
while (this.queue.length) {
|
|
220
|
+
const batch = this.queue.splice(0, BATCH);
|
|
221
|
+
const r = await this.request("POST", "/api/v1/track", { events: batch }, true);
|
|
222
|
+
total.sent += batch.length;
|
|
223
|
+
if (!r) {
|
|
224
|
+
total.failed += batch.length;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
total.accepted += r.accepted;
|
|
228
|
+
total.duplicates += r.duplicates;
|
|
229
|
+
for (const x of r.rejected ?? []) {
|
|
230
|
+
const e = batch[x.index];
|
|
231
|
+
total.rejected.push({ id: e?.id ?? "", event: e?.event ?? "", reason: x.reason, error: x.error });
|
|
232
|
+
this.fail(new OneMRRError(`Event ${e?.event ?? x.index} rejected: ${x.error}`, 400, x.reason));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** Checks the key and reports when OneMRR last received an event. */
|
|
237
|
+
async verify() {
|
|
238
|
+
const r = await this.request("GET", "/api/v1/tracking/status");
|
|
239
|
+
if (!r)
|
|
240
|
+
return { ok: false, lastEventAt: null, message: "Couldn't reach OneMRR with this key; see onError for the reason." };
|
|
241
|
+
return { ok: true, lastEventAt: r.last_event_at, message: r.last_event_at ? `Connected. Last event ${r.last_event_at}, ${r.events.today} today.` : "Connected. No events yet." };
|
|
242
|
+
}
|
|
243
|
+
/** Flushes and stops the timer. */
|
|
244
|
+
async shutdown() {
|
|
245
|
+
return this.flush();
|
|
246
|
+
}
|
|
247
|
+
/** Starts sending in the background; results are reported by the next flush(). */
|
|
248
|
+
kick() {
|
|
249
|
+
if (this.timer)
|
|
250
|
+
clearTimeout(this.timer);
|
|
251
|
+
this.timer = null;
|
|
252
|
+
if (this.inflight || !this.queue.length)
|
|
253
|
+
return;
|
|
254
|
+
this.inflight = this.send().finally(() => {
|
|
255
|
+
this.inflight = null;
|
|
256
|
+
if (this.queue.length)
|
|
257
|
+
this.schedule();
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
schedule() {
|
|
261
|
+
if (this.timer)
|
|
262
|
+
return;
|
|
263
|
+
this.timer = setTimeout(() => {
|
|
264
|
+
this.timer = null;
|
|
265
|
+
this.kick();
|
|
266
|
+
}, this.interval);
|
|
267
|
+
this.timer.unref?.();
|
|
268
|
+
}
|
|
269
|
+
fail(e) {
|
|
270
|
+
try {
|
|
271
|
+
this.onError(e);
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
/* an onError that throws must not break the caller */
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/** JSON request with retries on network errors, 429 and 5xx. Resolves null after reporting a failure. */
|
|
278
|
+
async request(method, path, body, acceptPartial = false) {
|
|
279
|
+
let last = null;
|
|
280
|
+
for (let attempt = 0; attempt <= this.retries; attempt++) {
|
|
281
|
+
if (attempt)
|
|
282
|
+
await sleep(Math.min(8000, 500 * 2 ** (attempt - 1)) * (0.75 + Math.random() / 2));
|
|
283
|
+
const ctl = new AbortController();
|
|
284
|
+
const t = setTimeout(() => ctl.abort(), this.timeout);
|
|
285
|
+
try {
|
|
286
|
+
const res = await this.fetchImpl(this.base + path, {
|
|
287
|
+
method,
|
|
288
|
+
headers: { Authorization: `Bearer ${this.key}`, "Content-Type": "application/json", "User-Agent": `onemrr-node/${VERSION}` },
|
|
289
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
290
|
+
signal: ctl.signal,
|
|
291
|
+
});
|
|
292
|
+
const json = (await res.json().catch(() => null));
|
|
293
|
+
if (res.ok)
|
|
294
|
+
return json;
|
|
295
|
+
const msg = json?.error?.message ?? `HTTP ${res.status}`;
|
|
296
|
+
last = new OneMRRError(msg, res.status, json?.error?.type);
|
|
297
|
+
if (res.status === 429) {
|
|
298
|
+
const wait = Number(res.headers.get("retry-after"));
|
|
299
|
+
if (wait > 0 && attempt < this.retries)
|
|
300
|
+
await sleep(Math.min(60, wait) * 1000);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
if (res.status >= 500)
|
|
304
|
+
continue;
|
|
305
|
+
// A track request where every event was refused is a 400 with per-event issues.
|
|
306
|
+
if (acceptPartial && res.status === 400 && json?.error && "issues" in json.error) {
|
|
307
|
+
const issues = json.error.issues ?? [];
|
|
308
|
+
return { accepted: 0, duplicates: 0, rejected: issues.map((i) => ({ index: Number(i.path.split(".")[1]), reason: "invalid", error: i.message })) };
|
|
309
|
+
}
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
last = new OneMRRError(err instanceof Error && err.name === "AbortError" ? `Timed out after ${this.timeout} ms` : `Network error: ${err instanceof Error ? err.message : String(err)}`);
|
|
314
|
+
}
|
|
315
|
+
finally {
|
|
316
|
+
clearTimeout(t);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (last)
|
|
320
|
+
this.fail(last);
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function toIdentify(i) {
|
|
325
|
+
if (!i?.accountId)
|
|
326
|
+
return null;
|
|
327
|
+
const link = (l) => ({ ...(l.sourceId != null ? { source_id: l.sourceId } : {}), ...(l.source ? { source: l.source } : {}), external_customer_id: l.externalCustomerId });
|
|
328
|
+
const links = [...(i.links ?? [])];
|
|
329
|
+
if (i.externalCustomerId)
|
|
330
|
+
links.push({ source: i.source, sourceId: i.sourceId, externalCustomerId: i.externalCustomerId });
|
|
331
|
+
return {
|
|
332
|
+
account_id: String(i.accountId),
|
|
333
|
+
...(i.name !== undefined ? { name: i.name } : {}),
|
|
334
|
+
...(i.email !== undefined ? { email: i.email } : {}),
|
|
335
|
+
...(links.length ? { links: links.map(link) } : {}),
|
|
336
|
+
};
|
|
337
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onemrr/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
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
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=20"
|
|
21
|
+
},
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"homepage": "https://app.onemrr.dev/api/v1/openapi.json",
|
|
25
|
+
"keywords": [
|
|
26
|
+
"onemrr",
|
|
27
|
+
"churn",
|
|
28
|
+
"mrr",
|
|
29
|
+
"analytics",
|
|
30
|
+
"saas",
|
|
31
|
+
"trials"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.build.json",
|
|
35
|
+
"prepublishOnly": "tsc -p tsconfig.build.json"
|
|
36
|
+
},
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/chrismccaw/OneMRR.git",
|
|
40
|
+
"directory": "packages/node"
|
|
41
|
+
}
|
|
42
|
+
}
|