@supermetry/node 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +68 -2
- package/dist/index.cjs +353 -0
- package/dist/index.d.ts +110 -0
- package/dist/index.js +313 -0
- package/dist/validate.d.ts +36 -0
- package/package.json +47 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,69 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@supermetry/node`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server-side SDK for [Supermetry](https://github.com/velixio/supermetry) self-hosted analytics. Zero runtime dependencies; uses the global `fetch` (Node.js 18+). See the [event contract](https://github.com/velixio/supermetry/blob/main/sdk/SPEC.md) for payload details.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @supermetry/node
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { Supermetry } from "@supermetry/node";
|
|
15
|
+
|
|
16
|
+
const supermetry = new Supermetry({
|
|
17
|
+
site: "your-site-id",
|
|
18
|
+
host: "https://analytics.example.com",
|
|
19
|
+
url: "https://shop.example.com/", // optional default page URL
|
|
20
|
+
onError: (error) => console.error(error),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// Fire-and-forget: never throws, never rejects.
|
|
24
|
+
supermetry.track("Signup", {
|
|
25
|
+
url: "https://shop.example.com/signup",
|
|
26
|
+
props: { plan: "pro", seats: 3 },
|
|
27
|
+
revenue: { amount: "49.90", currency: "USD" },
|
|
28
|
+
profileId: "user_42",
|
|
29
|
+
userAgent: req.headers["user-agent"], // forward the visitor's UA
|
|
30
|
+
ip: req.ip, // forwarded as X-Forwarded-For
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
supermetry.pageview({ url: "/pricing", userAgent, ip }); // relative URLs resolve against `url`
|
|
34
|
+
supermetry.identify("user_42", { email: "ada@example.com", plan: "pro" }, { userAgent, ip });
|
|
35
|
+
|
|
36
|
+
// Before the process exits (serverless handlers, scripts, graceful shutdown):
|
|
37
|
+
await supermetry.flush(); // or: await supermetry.close();
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Every call returns a `Promise<SendResult>` (`{ ok, status?, error? }`) that never rejects, so you can `await` it when you need to know the outcome.
|
|
41
|
+
|
|
42
|
+
## Options
|
|
43
|
+
|
|
44
|
+
| option | default | |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| `site` | required | Public site ID |
|
|
47
|
+
| `host` | required | Supermetry origin; events go to `host + /api/public/v1/events` |
|
|
48
|
+
| `endpoint` | | Full endpoint URL override |
|
|
49
|
+
| `url` | | Default event URL; base for relative event URLs |
|
|
50
|
+
| `userAgent` | `supermetry-node/0.1.0` | UA when the call does not forward a visitor UA |
|
|
51
|
+
| `disabled` | `false` | Send nothing |
|
|
52
|
+
| `onError` | no-op | Receives a `SupermetryError` (validation, network, HTTP status) |
|
|
53
|
+
| `fetch` | `globalThis.fetch` | Custom fetch |
|
|
54
|
+
| `timeout` | `10000` | Per-attempt timeout (ms) |
|
|
55
|
+
| `retry` | `true` | Retry once on network error / 429 / 5xx with the same event `id` |
|
|
56
|
+
| `sendOrigin` | `false` | Send `Origin` derived from the event URL |
|
|
57
|
+
|
|
58
|
+
Per-call context (`track`, `pageview`, third argument of `identify`): `url`, `referrer`, `profileId`, `userAgent`, `ip`, `screenWidth`, `timestamp`.
|
|
59
|
+
|
|
60
|
+
## Notes
|
|
61
|
+
|
|
62
|
+
- **User-Agent matters.** Generic HTTP-client UAs (`node-fetch`, `axios`, `undici`…) are filtered as bots. Forward the visitor's UA when you have it; otherwise the SDK sends `supermetry-node/0.1.0`.
|
|
63
|
+
- **Visitor IP** is sent as `X-Forwarded-For`. The Supermetry server only trusts it from addresses listed in `SUPERMETRY_TRUSTED_PROXIES`; add your app servers there, or every event counts as one visitor.
|
|
64
|
+
- **Strict origin**: turn it off for sites that receive server-side events (or set `sendOrigin: true`).
|
|
65
|
+
- **`identify` does not store the profile ID.** A server client is shared across visitors, so a stored ID would leak between users. Pass `profileId` on every call for identified users. `identify` sends the traits (string values, max 20; invalid traits are dropped locally since the server rejects the whole event otherwise).
|
|
66
|
+
- Props are limited to 30 keys of string/number/boolean values; others are dropped.
|
|
67
|
+
- Event `url` hosts must be allowed hosts of the site, or the server answers `400`.
|
|
68
|
+
|
|
69
|
+
License: Apache-2.0
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
function __accessProp(key) {
|
|
6
|
+
return this[key];
|
|
7
|
+
}
|
|
8
|
+
var __toCommonJS = (from) => {
|
|
9
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
10
|
+
if (entry)
|
|
11
|
+
return entry;
|
|
12
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (var key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(entry, key))
|
|
16
|
+
__defProp(entry, key, {
|
|
17
|
+
get: __accessProp.bind(from, key),
|
|
18
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
__moduleCache.set(from, entry);
|
|
22
|
+
return entry;
|
|
23
|
+
};
|
|
24
|
+
var __moduleCache;
|
|
25
|
+
var __returnValue = (v) => v;
|
|
26
|
+
function __exportSetter(name, newValue) {
|
|
27
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
28
|
+
}
|
|
29
|
+
var __export = (target, all) => {
|
|
30
|
+
for (var name in all)
|
|
31
|
+
__defProp(target, name, {
|
|
32
|
+
get: all[name],
|
|
33
|
+
enumerable: true,
|
|
34
|
+
configurable: true,
|
|
35
|
+
set: __exportSetter.bind(all, name)
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// src/index.ts
|
|
40
|
+
var exports_src = {};
|
|
41
|
+
__export(exports_src, {
|
|
42
|
+
DEFAULT_USER_AGENT: () => DEFAULT_USER_AGENT,
|
|
43
|
+
EVENTS_PATH: () => EVENTS_PATH,
|
|
44
|
+
Supermetry: () => Supermetry,
|
|
45
|
+
SupermetryError: () => SupermetryError,
|
|
46
|
+
VERSION: () => VERSION,
|
|
47
|
+
createSupermetry: () => createSupermetry,
|
|
48
|
+
newEventId: () => newEventId,
|
|
49
|
+
sanitizeProps: () => sanitizeProps,
|
|
50
|
+
sanitizeRevenue: () => sanitizeRevenue,
|
|
51
|
+
sanitizeTraits: () => sanitizeTraits
|
|
52
|
+
});
|
|
53
|
+
module.exports = __toCommonJS(exports_src);
|
|
54
|
+
var import_node_crypto = require("node:crypto");
|
|
55
|
+
|
|
56
|
+
// src/validate.ts
|
|
57
|
+
var MAX_PROPS = 30;
|
|
58
|
+
var MAX_KEY_BYTES = 300;
|
|
59
|
+
var MAX_VALUE_BYTES = 2000;
|
|
60
|
+
var MAX_URL_BYTES = 2000;
|
|
61
|
+
var MAX_NAME_BYTES = 300;
|
|
62
|
+
var MAX_BODY_BYTES = 8 * 1024;
|
|
63
|
+
var MAX_PROFILE_ID_CHARS = 128;
|
|
64
|
+
var MAX_TRAITS = 20;
|
|
65
|
+
var MAX_TRAIT_KEY_CHARS = 64;
|
|
66
|
+
var MAX_TRAIT_VALUE_CHARS = 256;
|
|
67
|
+
var encoder = new TextEncoder;
|
|
68
|
+
function byteLength(value) {
|
|
69
|
+
return encoder.encode(value).length;
|
|
70
|
+
}
|
|
71
|
+
function charLength(value) {
|
|
72
|
+
let count = 0;
|
|
73
|
+
for (const _ of value)
|
|
74
|
+
count++;
|
|
75
|
+
return count;
|
|
76
|
+
}
|
|
77
|
+
function truncateBytes(value, max) {
|
|
78
|
+
if (byteLength(value) <= max)
|
|
79
|
+
return value;
|
|
80
|
+
let out = "";
|
|
81
|
+
let size = 0;
|
|
82
|
+
for (const ch of value) {
|
|
83
|
+
const n = byteLength(ch);
|
|
84
|
+
if (size + n > max)
|
|
85
|
+
break;
|
|
86
|
+
out += ch;
|
|
87
|
+
size += n;
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
function validName(name) {
|
|
92
|
+
return typeof name === "string" && name.length > 0 && byteLength(name) <= MAX_NAME_BYTES;
|
|
93
|
+
}
|
|
94
|
+
function validEventUrl(value) {
|
|
95
|
+
if (typeof value !== "string" || value === "" || byteLength(value) > MAX_URL_BYTES)
|
|
96
|
+
return false;
|
|
97
|
+
try {
|
|
98
|
+
const parsed = new URL(value);
|
|
99
|
+
return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.hostname !== "" && parsed.username === "" && parsed.password === "";
|
|
100
|
+
} catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function validProfileId(value) {
|
|
105
|
+
return typeof value === "string" && value !== "" && charLength(value) <= MAX_PROFILE_ID_CHARS;
|
|
106
|
+
}
|
|
107
|
+
function sanitizeProps(props) {
|
|
108
|
+
if (!props || typeof props !== "object")
|
|
109
|
+
return;
|
|
110
|
+
const out = {};
|
|
111
|
+
let count = 0;
|
|
112
|
+
for (const [key, raw] of Object.entries(props)) {
|
|
113
|
+
if (count >= MAX_PROPS)
|
|
114
|
+
break;
|
|
115
|
+
if (key === "" || byteLength(key) > MAX_KEY_BYTES)
|
|
116
|
+
continue;
|
|
117
|
+
let value;
|
|
118
|
+
if (typeof raw === "string")
|
|
119
|
+
value = truncateBytes(raw, MAX_VALUE_BYTES);
|
|
120
|
+
else if (typeof raw === "boolean")
|
|
121
|
+
value = raw;
|
|
122
|
+
else if (typeof raw === "number" && Number.isFinite(raw))
|
|
123
|
+
value = raw;
|
|
124
|
+
else
|
|
125
|
+
continue;
|
|
126
|
+
out[key] = value;
|
|
127
|
+
count++;
|
|
128
|
+
}
|
|
129
|
+
return count > 0 ? out : undefined;
|
|
130
|
+
}
|
|
131
|
+
function sanitizeTraits(traits) {
|
|
132
|
+
if (!traits || typeof traits !== "object")
|
|
133
|
+
return;
|
|
134
|
+
const out = {};
|
|
135
|
+
let count = 0;
|
|
136
|
+
for (const [key, raw] of Object.entries(traits)) {
|
|
137
|
+
if (count >= MAX_TRAITS)
|
|
138
|
+
break;
|
|
139
|
+
if (key === "" || charLength(key) > MAX_TRAIT_KEY_CHARS)
|
|
140
|
+
continue;
|
|
141
|
+
let value;
|
|
142
|
+
if (typeof raw === "string")
|
|
143
|
+
value = raw;
|
|
144
|
+
else if (typeof raw === "boolean" || typeof raw === "number" && Number.isFinite(raw))
|
|
145
|
+
value = String(raw);
|
|
146
|
+
else
|
|
147
|
+
continue;
|
|
148
|
+
if (charLength(value) > MAX_TRAIT_VALUE_CHARS)
|
|
149
|
+
continue;
|
|
150
|
+
out[key] = value;
|
|
151
|
+
count++;
|
|
152
|
+
}
|
|
153
|
+
return count > 0 ? out : undefined;
|
|
154
|
+
}
|
|
155
|
+
var amountPattern = /^\d+(\.\d{1,6})?$/;
|
|
156
|
+
function sanitizeRevenue(revenue) {
|
|
157
|
+
if (!revenue || typeof revenue !== "object")
|
|
158
|
+
return;
|
|
159
|
+
let { amount } = revenue;
|
|
160
|
+
const { currency } = revenue;
|
|
161
|
+
if (typeof amount === "number") {
|
|
162
|
+
amount = Math.round(amount * 1e6) / 1e6;
|
|
163
|
+
if (!Number.isFinite(amount) || amount <= 0 || amount > 1000000000000)
|
|
164
|
+
return;
|
|
165
|
+
} else if (typeof amount !== "string" || !amountPattern.test(amount) || Number(amount) <= 0) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (currency !== undefined && currency !== "" && !/^[A-Z]{3}$/.test(currency))
|
|
169
|
+
return;
|
|
170
|
+
return currency ? { amount, currency } : { amount };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/index.ts
|
|
174
|
+
var VERSION = "0.1.0";
|
|
175
|
+
var DEFAULT_USER_AGENT = `supermetry-node/${VERSION}`;
|
|
176
|
+
var EVENTS_PATH = "/api/public/v1/events";
|
|
177
|
+
|
|
178
|
+
class SupermetryError extends Error {
|
|
179
|
+
status;
|
|
180
|
+
event;
|
|
181
|
+
constructor(message, options = {}) {
|
|
182
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
183
|
+
this.name = "SupermetryError";
|
|
184
|
+
this.status = options.status;
|
|
185
|
+
this.event = options.event;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function newEventId() {
|
|
189
|
+
return import_node_crypto.randomUUID().replace(/-/g, "");
|
|
190
|
+
}
|
|
191
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
192
|
+
|
|
193
|
+
class Supermetry {
|
|
194
|
+
site;
|
|
195
|
+
endpoint;
|
|
196
|
+
options;
|
|
197
|
+
inflight = new Set;
|
|
198
|
+
closed = false;
|
|
199
|
+
constructor(options) {
|
|
200
|
+
if (!options || typeof options.site !== "string" || options.site === "") {
|
|
201
|
+
throw new TypeError("@supermetry/node: `site` is required");
|
|
202
|
+
}
|
|
203
|
+
if (!options.endpoint && (typeof options.host !== "string" || options.host === "")) {
|
|
204
|
+
throw new TypeError("@supermetry/node: `host` is required");
|
|
205
|
+
}
|
|
206
|
+
this.options = options;
|
|
207
|
+
this.site = options.site;
|
|
208
|
+
this.endpoint = options.endpoint ?? options.host.replace(/\/+$/, "") + EVENTS_PATH;
|
|
209
|
+
}
|
|
210
|
+
track(name, options = {}) {
|
|
211
|
+
return this.capture(() => {
|
|
212
|
+
if (name === "identify")
|
|
213
|
+
throw new SupermetryError('use identify() instead of track("identify")');
|
|
214
|
+
return this.build(name, options, { props: options.props, revenue: options.revenue });
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
pageview(options = {}) {
|
|
218
|
+
return this.capture(() => this.build("pageview", options, { props: options.props }));
|
|
219
|
+
}
|
|
220
|
+
identify(profileId, traits, context = {}) {
|
|
221
|
+
return this.capture(() => {
|
|
222
|
+
if (!validProfileId(profileId))
|
|
223
|
+
throw new SupermetryError("identify: profileId must be 1-128 characters");
|
|
224
|
+
return this.build("identify", { ...context, profileId }, { traits: sanitizeTraits(traits) });
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
async flush() {
|
|
228
|
+
while (this.inflight.size > 0)
|
|
229
|
+
await Promise.allSettled([...this.inflight]);
|
|
230
|
+
}
|
|
231
|
+
async close() {
|
|
232
|
+
this.closed = true;
|
|
233
|
+
await this.flush();
|
|
234
|
+
}
|
|
235
|
+
capture(build) {
|
|
236
|
+
if (this.options.disabled || this.closed)
|
|
237
|
+
return Promise.resolve({ ok: false });
|
|
238
|
+
let built;
|
|
239
|
+
try {
|
|
240
|
+
built = build();
|
|
241
|
+
} catch (error) {
|
|
242
|
+
const err = error instanceof SupermetryError ? error : new SupermetryError(String(error), { cause: error });
|
|
243
|
+
this.report(err);
|
|
244
|
+
return Promise.resolve({ ok: false, error: err });
|
|
245
|
+
}
|
|
246
|
+
const promise = this.send(built.event, built.context);
|
|
247
|
+
this.inflight.add(promise);
|
|
248
|
+
promise.finally(() => this.inflight.delete(promise));
|
|
249
|
+
return promise;
|
|
250
|
+
}
|
|
251
|
+
build(name, context, extra) {
|
|
252
|
+
if (!validName(name))
|
|
253
|
+
throw new SupermetryError("event name must be 1-300 bytes");
|
|
254
|
+
const url = this.resolveUrl(context.url);
|
|
255
|
+
if (!url)
|
|
256
|
+
throw new SupermetryError("event url must be an absolute http(s) URL (pass `url` or configure a default)");
|
|
257
|
+
const ts = context.timestamp instanceof Date ? context.timestamp.getTime() : typeof context.timestamp === "number" ? Math.trunc(context.timestamp) : Date.now();
|
|
258
|
+
const event = { v: 1, id: newEventId(), ts, site: this.site, name, url };
|
|
259
|
+
if (typeof context.referrer === "string" && context.referrer !== "" && byteLength(context.referrer) <= MAX_VALUE_BYTES) {
|
|
260
|
+
event.referrer = context.referrer;
|
|
261
|
+
}
|
|
262
|
+
if (typeof context.screenWidth === "number" && Number.isInteger(context.screenWidth) && context.screenWidth > 0 && context.screenWidth <= 32767) {
|
|
263
|
+
event.screen_width = context.screenWidth;
|
|
264
|
+
}
|
|
265
|
+
const props = sanitizeProps(extra.props);
|
|
266
|
+
if (props)
|
|
267
|
+
event.props = props;
|
|
268
|
+
if (name !== "pageview") {
|
|
269
|
+
const revenue = sanitizeRevenue(extra.revenue);
|
|
270
|
+
if (revenue)
|
|
271
|
+
event.revenue = revenue;
|
|
272
|
+
}
|
|
273
|
+
if (context.profileId !== undefined && context.profileId !== null) {
|
|
274
|
+
if (validProfileId(context.profileId))
|
|
275
|
+
event.profile_id = context.profileId;
|
|
276
|
+
else
|
|
277
|
+
this.report(new SupermetryError("profileId must be 1-128 characters; sent without it"));
|
|
278
|
+
}
|
|
279
|
+
if (name === "identify" && extra.traits)
|
|
280
|
+
event.traits = extra.traits;
|
|
281
|
+
if (byteLength(JSON.stringify(event)) > MAX_BODY_BYTES) {
|
|
282
|
+
throw new SupermetryError("event body exceeds 8 KB", { event });
|
|
283
|
+
}
|
|
284
|
+
return { event, context };
|
|
285
|
+
}
|
|
286
|
+
resolveUrl(url) {
|
|
287
|
+
const base = this.options.url;
|
|
288
|
+
if (url === undefined || url === "")
|
|
289
|
+
return validEventUrl(base) ? base : undefined;
|
|
290
|
+
if (validEventUrl(url))
|
|
291
|
+
return url;
|
|
292
|
+
if (!base)
|
|
293
|
+
return;
|
|
294
|
+
try {
|
|
295
|
+
const resolved = new URL(url, base).toString();
|
|
296
|
+
return validEventUrl(resolved) ? resolved : undefined;
|
|
297
|
+
} catch {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async send(event, context) {
|
|
302
|
+
const doFetch = this.options.fetch ?? globalThis.fetch;
|
|
303
|
+
const headers = {
|
|
304
|
+
"Content-Type": "application/json",
|
|
305
|
+
"User-Agent": context.userAgent || this.options.userAgent || DEFAULT_USER_AGENT
|
|
306
|
+
};
|
|
307
|
+
if (context.ip)
|
|
308
|
+
headers["X-Forwarded-For"] = context.ip;
|
|
309
|
+
if (this.options.sendOrigin)
|
|
310
|
+
headers["Origin"] = new URL(event.url).origin;
|
|
311
|
+
const body = JSON.stringify(event);
|
|
312
|
+
const attempts = this.options.retry === false ? 1 : 2;
|
|
313
|
+
let last = { ok: false };
|
|
314
|
+
for (let attempt = 1;attempt <= attempts; attempt++) {
|
|
315
|
+
let retryDelay = 250;
|
|
316
|
+
const controller = new AbortController;
|
|
317
|
+
const timer = setTimeout(() => controller.abort(), this.options.timeout ?? 1e4);
|
|
318
|
+
timer.unref?.();
|
|
319
|
+
try {
|
|
320
|
+
const response = await doFetch(this.endpoint, { method: "POST", headers, body, signal: controller.signal });
|
|
321
|
+
await response.arrayBuffer().catch(() => {
|
|
322
|
+
return;
|
|
323
|
+
});
|
|
324
|
+
if (response.ok)
|
|
325
|
+
return { ok: true, status: response.status };
|
|
326
|
+
const error = new SupermetryError(`Supermetry responded ${response.status}`, { status: response.status, event });
|
|
327
|
+
last = { ok: false, status: response.status, error };
|
|
328
|
+
if (response.status !== 429 && response.status < 500)
|
|
329
|
+
break;
|
|
330
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
331
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0)
|
|
332
|
+
retryDelay = Math.min(retryAfter * 1000, 5000);
|
|
333
|
+
} catch (cause) {
|
|
334
|
+
last = { ok: false, error: new SupermetryError("Supermetry request failed", { event, cause }) };
|
|
335
|
+
} finally {
|
|
336
|
+
clearTimeout(timer);
|
|
337
|
+
}
|
|
338
|
+
if (attempt < attempts)
|
|
339
|
+
await sleep(retryDelay);
|
|
340
|
+
}
|
|
341
|
+
if (last.error)
|
|
342
|
+
this.report(last.error);
|
|
343
|
+
return last;
|
|
344
|
+
}
|
|
345
|
+
report(error) {
|
|
346
|
+
try {
|
|
347
|
+
this.options.onError?.(error);
|
|
348
|
+
} catch {}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function createSupermetry(options) {
|
|
352
|
+
return new Supermetry(options);
|
|
353
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { type PropValue, type Props, type Revenue, type Traits } from "./validate.js";
|
|
2
|
+
export type { PropValue, Props, Revenue, Traits } from "./validate.js";
|
|
3
|
+
export { sanitizeProps, sanitizeRevenue, sanitizeTraits } from "./validate.js";
|
|
4
|
+
export declare const VERSION = "0.1.0";
|
|
5
|
+
export declare const DEFAULT_USER_AGENT = "supermetry-node/0.1.0";
|
|
6
|
+
export declare const EVENTS_PATH = "/api/public/v1/events";
|
|
7
|
+
/** The JSON body sent to `POST /api/public/v1/events`. */
|
|
8
|
+
export interface EventPayload {
|
|
9
|
+
v: 1;
|
|
10
|
+
id: string;
|
|
11
|
+
ts: number;
|
|
12
|
+
site: string;
|
|
13
|
+
name: string;
|
|
14
|
+
url: string;
|
|
15
|
+
referrer?: string;
|
|
16
|
+
screen_width?: number;
|
|
17
|
+
props?: Record<string, PropValue>;
|
|
18
|
+
revenue?: {
|
|
19
|
+
amount: string | number;
|
|
20
|
+
currency?: string;
|
|
21
|
+
};
|
|
22
|
+
profile_id?: string;
|
|
23
|
+
traits?: Record<string, string>;
|
|
24
|
+
}
|
|
25
|
+
export interface SupermetryOptions {
|
|
26
|
+
/** Public site ID. */
|
|
27
|
+
site: string;
|
|
28
|
+
/** Supermetry origin, e.g. `https://analytics.example.com`. */
|
|
29
|
+
host: string;
|
|
30
|
+
/** Full events endpoint; defaults to `host + "/api/public/v1/events"`. */
|
|
31
|
+
endpoint?: string;
|
|
32
|
+
/** Default page URL for events that do not pass one. Relative event URLs resolve against it. */
|
|
33
|
+
url?: string;
|
|
34
|
+
/** User-Agent used when no visitor UA is forwarded. Defaults to `supermetry-node/0.1.0`. */
|
|
35
|
+
userAgent?: string;
|
|
36
|
+
/** Send nothing (every call resolves immediately). */
|
|
37
|
+
disabled?: boolean;
|
|
38
|
+
/** Called for validation, network and HTTP errors. Tracking never throws. */
|
|
39
|
+
onError?: (error: SupermetryError) => void;
|
|
40
|
+
/** Custom fetch implementation; defaults to the global `fetch`. */
|
|
41
|
+
fetch?: typeof fetch;
|
|
42
|
+
/** Per-attempt timeout in milliseconds (default 10000). */
|
|
43
|
+
timeout?: number;
|
|
44
|
+
/** Retry once on network errors, 429 and 5xx (default true). */
|
|
45
|
+
retry?: boolean;
|
|
46
|
+
/** Send an `Origin` header derived from the event URL (for sites with strict origin). */
|
|
47
|
+
sendOrigin?: boolean;
|
|
48
|
+
}
|
|
49
|
+
/** Per-event request context. Server SDK calls are stateless: pass `profileId` on each call. */
|
|
50
|
+
export interface EventContext {
|
|
51
|
+
/** Absolute page URL (or relative to the configured `url`). */
|
|
52
|
+
url?: string;
|
|
53
|
+
referrer?: string;
|
|
54
|
+
/** Profile ID set by `identify`; attach it to every event of that user. */
|
|
55
|
+
profileId?: string;
|
|
56
|
+
/** Visitor User-Agent, forwarded as `User-Agent`. */
|
|
57
|
+
userAgent?: string;
|
|
58
|
+
/** Visitor IP, forwarded as `X-Forwarded-For`. */
|
|
59
|
+
ip?: string;
|
|
60
|
+
screenWidth?: number;
|
|
61
|
+
/** Event time; defaults to now. */
|
|
62
|
+
timestamp?: Date | number;
|
|
63
|
+
}
|
|
64
|
+
export interface TrackOptions extends EventContext {
|
|
65
|
+
props?: Props;
|
|
66
|
+
revenue?: Revenue;
|
|
67
|
+
}
|
|
68
|
+
export interface PageviewOptions extends EventContext {
|
|
69
|
+
props?: Props;
|
|
70
|
+
}
|
|
71
|
+
export interface SendResult {
|
|
72
|
+
ok: boolean;
|
|
73
|
+
/** HTTP status of the last attempt, when a response was received. */
|
|
74
|
+
status?: number;
|
|
75
|
+
error?: SupermetryError;
|
|
76
|
+
}
|
|
77
|
+
export declare class SupermetryError extends Error {
|
|
78
|
+
readonly status?: number;
|
|
79
|
+
readonly event?: EventPayload;
|
|
80
|
+
constructor(message: string, options?: {
|
|
81
|
+
status?: number;
|
|
82
|
+
event?: EventPayload;
|
|
83
|
+
cause?: unknown;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
export declare function newEventId(): string;
|
|
87
|
+
export declare class Supermetry {
|
|
88
|
+
readonly site: string;
|
|
89
|
+
readonly endpoint: string;
|
|
90
|
+
private readonly options;
|
|
91
|
+
private readonly inflight;
|
|
92
|
+
private closed;
|
|
93
|
+
constructor(options: SupermetryOptions);
|
|
94
|
+
/** Sends a custom event. Never rejects; await it to wait for delivery. */
|
|
95
|
+
track(name: string, options?: TrackOptions): Promise<SendResult>;
|
|
96
|
+
/** Sends a pageview for `url` (or the configured default URL). */
|
|
97
|
+
pageview(options?: PageviewOptions): Promise<SendResult>;
|
|
98
|
+
/** Links the visitor to `profileId` and records traits (string → string, max 20). */
|
|
99
|
+
identify(profileId: string, traits?: Traits, context?: EventContext): Promise<SendResult>;
|
|
100
|
+
/** Resolves once every in-flight send has finished. */
|
|
101
|
+
flush(): Promise<void>;
|
|
102
|
+
/** Flushes and stops accepting new events. */
|
|
103
|
+
close(): Promise<void>;
|
|
104
|
+
private capture;
|
|
105
|
+
private build;
|
|
106
|
+
private resolveUrl;
|
|
107
|
+
private send;
|
|
108
|
+
private report;
|
|
109
|
+
}
|
|
110
|
+
export declare function createSupermetry(options: SupermetryOptions): Supermetry;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
// src/validate.ts
|
|
5
|
+
var MAX_PROPS = 30;
|
|
6
|
+
var MAX_KEY_BYTES = 300;
|
|
7
|
+
var MAX_VALUE_BYTES = 2000;
|
|
8
|
+
var MAX_URL_BYTES = 2000;
|
|
9
|
+
var MAX_NAME_BYTES = 300;
|
|
10
|
+
var MAX_BODY_BYTES = 8 * 1024;
|
|
11
|
+
var MAX_PROFILE_ID_CHARS = 128;
|
|
12
|
+
var MAX_TRAITS = 20;
|
|
13
|
+
var MAX_TRAIT_KEY_CHARS = 64;
|
|
14
|
+
var MAX_TRAIT_VALUE_CHARS = 256;
|
|
15
|
+
var encoder = new TextEncoder;
|
|
16
|
+
function byteLength(value) {
|
|
17
|
+
return encoder.encode(value).length;
|
|
18
|
+
}
|
|
19
|
+
function charLength(value) {
|
|
20
|
+
let count = 0;
|
|
21
|
+
for (const _ of value)
|
|
22
|
+
count++;
|
|
23
|
+
return count;
|
|
24
|
+
}
|
|
25
|
+
function truncateBytes(value, max) {
|
|
26
|
+
if (byteLength(value) <= max)
|
|
27
|
+
return value;
|
|
28
|
+
let out = "";
|
|
29
|
+
let size = 0;
|
|
30
|
+
for (const ch of value) {
|
|
31
|
+
const n = byteLength(ch);
|
|
32
|
+
if (size + n > max)
|
|
33
|
+
break;
|
|
34
|
+
out += ch;
|
|
35
|
+
size += n;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
function validName(name) {
|
|
40
|
+
return typeof name === "string" && name.length > 0 && byteLength(name) <= MAX_NAME_BYTES;
|
|
41
|
+
}
|
|
42
|
+
function validEventUrl(value) {
|
|
43
|
+
if (typeof value !== "string" || value === "" || byteLength(value) > MAX_URL_BYTES)
|
|
44
|
+
return false;
|
|
45
|
+
try {
|
|
46
|
+
const parsed = new URL(value);
|
|
47
|
+
return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.hostname !== "" && parsed.username === "" && parsed.password === "";
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function validProfileId(value) {
|
|
53
|
+
return typeof value === "string" && value !== "" && charLength(value) <= MAX_PROFILE_ID_CHARS;
|
|
54
|
+
}
|
|
55
|
+
function sanitizeProps(props) {
|
|
56
|
+
if (!props || typeof props !== "object")
|
|
57
|
+
return;
|
|
58
|
+
const out = {};
|
|
59
|
+
let count = 0;
|
|
60
|
+
for (const [key, raw] of Object.entries(props)) {
|
|
61
|
+
if (count >= MAX_PROPS)
|
|
62
|
+
break;
|
|
63
|
+
if (key === "" || byteLength(key) > MAX_KEY_BYTES)
|
|
64
|
+
continue;
|
|
65
|
+
let value;
|
|
66
|
+
if (typeof raw === "string")
|
|
67
|
+
value = truncateBytes(raw, MAX_VALUE_BYTES);
|
|
68
|
+
else if (typeof raw === "boolean")
|
|
69
|
+
value = raw;
|
|
70
|
+
else if (typeof raw === "number" && Number.isFinite(raw))
|
|
71
|
+
value = raw;
|
|
72
|
+
else
|
|
73
|
+
continue;
|
|
74
|
+
out[key] = value;
|
|
75
|
+
count++;
|
|
76
|
+
}
|
|
77
|
+
return count > 0 ? out : undefined;
|
|
78
|
+
}
|
|
79
|
+
function sanitizeTraits(traits) {
|
|
80
|
+
if (!traits || typeof traits !== "object")
|
|
81
|
+
return;
|
|
82
|
+
const out = {};
|
|
83
|
+
let count = 0;
|
|
84
|
+
for (const [key, raw] of Object.entries(traits)) {
|
|
85
|
+
if (count >= MAX_TRAITS)
|
|
86
|
+
break;
|
|
87
|
+
if (key === "" || charLength(key) > MAX_TRAIT_KEY_CHARS)
|
|
88
|
+
continue;
|
|
89
|
+
let value;
|
|
90
|
+
if (typeof raw === "string")
|
|
91
|
+
value = raw;
|
|
92
|
+
else if (typeof raw === "boolean" || typeof raw === "number" && Number.isFinite(raw))
|
|
93
|
+
value = String(raw);
|
|
94
|
+
else
|
|
95
|
+
continue;
|
|
96
|
+
if (charLength(value) > MAX_TRAIT_VALUE_CHARS)
|
|
97
|
+
continue;
|
|
98
|
+
out[key] = value;
|
|
99
|
+
count++;
|
|
100
|
+
}
|
|
101
|
+
return count > 0 ? out : undefined;
|
|
102
|
+
}
|
|
103
|
+
var amountPattern = /^\d+(\.\d{1,6})?$/;
|
|
104
|
+
function sanitizeRevenue(revenue) {
|
|
105
|
+
if (!revenue || typeof revenue !== "object")
|
|
106
|
+
return;
|
|
107
|
+
let { amount } = revenue;
|
|
108
|
+
const { currency } = revenue;
|
|
109
|
+
if (typeof amount === "number") {
|
|
110
|
+
amount = Math.round(amount * 1e6) / 1e6;
|
|
111
|
+
if (!Number.isFinite(amount) || amount <= 0 || amount > 1000000000000)
|
|
112
|
+
return;
|
|
113
|
+
} else if (typeof amount !== "string" || !amountPattern.test(amount) || Number(amount) <= 0) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (currency !== undefined && currency !== "" && !/^[A-Z]{3}$/.test(currency))
|
|
117
|
+
return;
|
|
118
|
+
return currency ? { amount, currency } : { amount };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/index.ts
|
|
122
|
+
var VERSION = "0.1.0";
|
|
123
|
+
var DEFAULT_USER_AGENT = `supermetry-node/${VERSION}`;
|
|
124
|
+
var EVENTS_PATH = "/api/public/v1/events";
|
|
125
|
+
|
|
126
|
+
class SupermetryError extends Error {
|
|
127
|
+
status;
|
|
128
|
+
event;
|
|
129
|
+
constructor(message, options = {}) {
|
|
130
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
131
|
+
this.name = "SupermetryError";
|
|
132
|
+
this.status = options.status;
|
|
133
|
+
this.event = options.event;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function newEventId() {
|
|
137
|
+
return randomUUID().replace(/-/g, "");
|
|
138
|
+
}
|
|
139
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
140
|
+
|
|
141
|
+
class Supermetry {
|
|
142
|
+
site;
|
|
143
|
+
endpoint;
|
|
144
|
+
options;
|
|
145
|
+
inflight = new Set;
|
|
146
|
+
closed = false;
|
|
147
|
+
constructor(options) {
|
|
148
|
+
if (!options || typeof options.site !== "string" || options.site === "") {
|
|
149
|
+
throw new TypeError("@supermetry/node: `site` is required");
|
|
150
|
+
}
|
|
151
|
+
if (!options.endpoint && (typeof options.host !== "string" || options.host === "")) {
|
|
152
|
+
throw new TypeError("@supermetry/node: `host` is required");
|
|
153
|
+
}
|
|
154
|
+
this.options = options;
|
|
155
|
+
this.site = options.site;
|
|
156
|
+
this.endpoint = options.endpoint ?? options.host.replace(/\/+$/, "") + EVENTS_PATH;
|
|
157
|
+
}
|
|
158
|
+
track(name, options = {}) {
|
|
159
|
+
return this.capture(() => {
|
|
160
|
+
if (name === "identify")
|
|
161
|
+
throw new SupermetryError('use identify() instead of track("identify")');
|
|
162
|
+
return this.build(name, options, { props: options.props, revenue: options.revenue });
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
pageview(options = {}) {
|
|
166
|
+
return this.capture(() => this.build("pageview", options, { props: options.props }));
|
|
167
|
+
}
|
|
168
|
+
identify(profileId, traits, context = {}) {
|
|
169
|
+
return this.capture(() => {
|
|
170
|
+
if (!validProfileId(profileId))
|
|
171
|
+
throw new SupermetryError("identify: profileId must be 1-128 characters");
|
|
172
|
+
return this.build("identify", { ...context, profileId }, { traits: sanitizeTraits(traits) });
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
async flush() {
|
|
176
|
+
while (this.inflight.size > 0)
|
|
177
|
+
await Promise.allSettled([...this.inflight]);
|
|
178
|
+
}
|
|
179
|
+
async close() {
|
|
180
|
+
this.closed = true;
|
|
181
|
+
await this.flush();
|
|
182
|
+
}
|
|
183
|
+
capture(build) {
|
|
184
|
+
if (this.options.disabled || this.closed)
|
|
185
|
+
return Promise.resolve({ ok: false });
|
|
186
|
+
let built;
|
|
187
|
+
try {
|
|
188
|
+
built = build();
|
|
189
|
+
} catch (error) {
|
|
190
|
+
const err = error instanceof SupermetryError ? error : new SupermetryError(String(error), { cause: error });
|
|
191
|
+
this.report(err);
|
|
192
|
+
return Promise.resolve({ ok: false, error: err });
|
|
193
|
+
}
|
|
194
|
+
const promise = this.send(built.event, built.context);
|
|
195
|
+
this.inflight.add(promise);
|
|
196
|
+
promise.finally(() => this.inflight.delete(promise));
|
|
197
|
+
return promise;
|
|
198
|
+
}
|
|
199
|
+
build(name, context, extra) {
|
|
200
|
+
if (!validName(name))
|
|
201
|
+
throw new SupermetryError("event name must be 1-300 bytes");
|
|
202
|
+
const url = this.resolveUrl(context.url);
|
|
203
|
+
if (!url)
|
|
204
|
+
throw new SupermetryError("event url must be an absolute http(s) URL (pass `url` or configure a default)");
|
|
205
|
+
const ts = context.timestamp instanceof Date ? context.timestamp.getTime() : typeof context.timestamp === "number" ? Math.trunc(context.timestamp) : Date.now();
|
|
206
|
+
const event = { v: 1, id: newEventId(), ts, site: this.site, name, url };
|
|
207
|
+
if (typeof context.referrer === "string" && context.referrer !== "" && byteLength(context.referrer) <= MAX_VALUE_BYTES) {
|
|
208
|
+
event.referrer = context.referrer;
|
|
209
|
+
}
|
|
210
|
+
if (typeof context.screenWidth === "number" && Number.isInteger(context.screenWidth) && context.screenWidth > 0 && context.screenWidth <= 32767) {
|
|
211
|
+
event.screen_width = context.screenWidth;
|
|
212
|
+
}
|
|
213
|
+
const props = sanitizeProps(extra.props);
|
|
214
|
+
if (props)
|
|
215
|
+
event.props = props;
|
|
216
|
+
if (name !== "pageview") {
|
|
217
|
+
const revenue = sanitizeRevenue(extra.revenue);
|
|
218
|
+
if (revenue)
|
|
219
|
+
event.revenue = revenue;
|
|
220
|
+
}
|
|
221
|
+
if (context.profileId !== undefined && context.profileId !== null) {
|
|
222
|
+
if (validProfileId(context.profileId))
|
|
223
|
+
event.profile_id = context.profileId;
|
|
224
|
+
else
|
|
225
|
+
this.report(new SupermetryError("profileId must be 1-128 characters; sent without it"));
|
|
226
|
+
}
|
|
227
|
+
if (name === "identify" && extra.traits)
|
|
228
|
+
event.traits = extra.traits;
|
|
229
|
+
if (byteLength(JSON.stringify(event)) > MAX_BODY_BYTES) {
|
|
230
|
+
throw new SupermetryError("event body exceeds 8 KB", { event });
|
|
231
|
+
}
|
|
232
|
+
return { event, context };
|
|
233
|
+
}
|
|
234
|
+
resolveUrl(url) {
|
|
235
|
+
const base = this.options.url;
|
|
236
|
+
if (url === undefined || url === "")
|
|
237
|
+
return validEventUrl(base) ? base : undefined;
|
|
238
|
+
if (validEventUrl(url))
|
|
239
|
+
return url;
|
|
240
|
+
if (!base)
|
|
241
|
+
return;
|
|
242
|
+
try {
|
|
243
|
+
const resolved = new URL(url, base).toString();
|
|
244
|
+
return validEventUrl(resolved) ? resolved : undefined;
|
|
245
|
+
} catch {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async send(event, context) {
|
|
250
|
+
const doFetch = this.options.fetch ?? globalThis.fetch;
|
|
251
|
+
const headers = {
|
|
252
|
+
"Content-Type": "application/json",
|
|
253
|
+
"User-Agent": context.userAgent || this.options.userAgent || DEFAULT_USER_AGENT
|
|
254
|
+
};
|
|
255
|
+
if (context.ip)
|
|
256
|
+
headers["X-Forwarded-For"] = context.ip;
|
|
257
|
+
if (this.options.sendOrigin)
|
|
258
|
+
headers["Origin"] = new URL(event.url).origin;
|
|
259
|
+
const body = JSON.stringify(event);
|
|
260
|
+
const attempts = this.options.retry === false ? 1 : 2;
|
|
261
|
+
let last = { ok: false };
|
|
262
|
+
for (let attempt = 1;attempt <= attempts; attempt++) {
|
|
263
|
+
let retryDelay = 250;
|
|
264
|
+
const controller = new AbortController;
|
|
265
|
+
const timer = setTimeout(() => controller.abort(), this.options.timeout ?? 1e4);
|
|
266
|
+
timer.unref?.();
|
|
267
|
+
try {
|
|
268
|
+
const response = await doFetch(this.endpoint, { method: "POST", headers, body, signal: controller.signal });
|
|
269
|
+
await response.arrayBuffer().catch(() => {
|
|
270
|
+
return;
|
|
271
|
+
});
|
|
272
|
+
if (response.ok)
|
|
273
|
+
return { ok: true, status: response.status };
|
|
274
|
+
const error = new SupermetryError(`Supermetry responded ${response.status}`, { status: response.status, event });
|
|
275
|
+
last = { ok: false, status: response.status, error };
|
|
276
|
+
if (response.status !== 429 && response.status < 500)
|
|
277
|
+
break;
|
|
278
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
279
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0)
|
|
280
|
+
retryDelay = Math.min(retryAfter * 1000, 5000);
|
|
281
|
+
} catch (cause) {
|
|
282
|
+
last = { ok: false, error: new SupermetryError("Supermetry request failed", { event, cause }) };
|
|
283
|
+
} finally {
|
|
284
|
+
clearTimeout(timer);
|
|
285
|
+
}
|
|
286
|
+
if (attempt < attempts)
|
|
287
|
+
await sleep(retryDelay);
|
|
288
|
+
}
|
|
289
|
+
if (last.error)
|
|
290
|
+
this.report(last.error);
|
|
291
|
+
return last;
|
|
292
|
+
}
|
|
293
|
+
report(error) {
|
|
294
|
+
try {
|
|
295
|
+
this.options.onError?.(error);
|
|
296
|
+
} catch {}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function createSupermetry(options) {
|
|
300
|
+
return new Supermetry(options);
|
|
301
|
+
}
|
|
302
|
+
export {
|
|
303
|
+
DEFAULT_USER_AGENT,
|
|
304
|
+
EVENTS_PATH,
|
|
305
|
+
Supermetry,
|
|
306
|
+
SupermetryError,
|
|
307
|
+
VERSION,
|
|
308
|
+
createSupermetry,
|
|
309
|
+
newEventId,
|
|
310
|
+
sanitizeProps,
|
|
311
|
+
sanitizeRevenue,
|
|
312
|
+
sanitizeTraits
|
|
313
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type PropValue = string | number | boolean;
|
|
2
|
+
export type Props = Record<string, PropValue | null | undefined>;
|
|
3
|
+
export type Traits = Record<string, string | number | boolean | null | undefined>;
|
|
4
|
+
export interface Revenue {
|
|
5
|
+
/** Positive amount, at most 6 decimals, e.g. `49.9` or `"49.90"`. */
|
|
6
|
+
amount: string | number;
|
|
7
|
+
/** ISO 4217 code; must match the site currency (or be omitted). */
|
|
8
|
+
currency?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare const MAX_PROPS = 30;
|
|
11
|
+
export declare const MAX_KEY_BYTES = 300;
|
|
12
|
+
export declare const MAX_VALUE_BYTES = 2000;
|
|
13
|
+
export declare const MAX_URL_BYTES = 2000;
|
|
14
|
+
export declare const MAX_NAME_BYTES = 300;
|
|
15
|
+
export declare const MAX_BODY_BYTES: number;
|
|
16
|
+
export declare const MAX_PROFILE_ID_CHARS = 128;
|
|
17
|
+
export declare const MAX_TRAITS = 20;
|
|
18
|
+
export declare const MAX_TRAIT_KEY_CHARS = 64;
|
|
19
|
+
export declare const MAX_TRAIT_VALUE_CHARS = 256;
|
|
20
|
+
export declare function byteLength(value: string): number;
|
|
21
|
+
export declare function charLength(value: string): number;
|
|
22
|
+
/** Truncates to at most `max` UTF-8 bytes without splitting a code point. */
|
|
23
|
+
export declare function truncateBytes(value: string, max: number): string;
|
|
24
|
+
export declare function validName(name: unknown): name is string;
|
|
25
|
+
/** Absolute http(s) URL without userinfo, at most 2000 bytes. */
|
|
26
|
+
export declare function validEventUrl(value: unknown): value is string;
|
|
27
|
+
export declare function validProfileId(value: unknown): value is string;
|
|
28
|
+
/** Keeps string/number/boolean values, drops invalid keys, caps at 30 keys. */
|
|
29
|
+
export declare function sanitizeProps(props: Props | undefined | null): Record<string, PropValue> | undefined;
|
|
30
|
+
/** Keeps valid string traits (numbers/booleans are stringified), at most 20. */
|
|
31
|
+
export declare function sanitizeTraits(traits: Traits | undefined | null): Record<string, string> | undefined;
|
|
32
|
+
/** Returns a revenue object the server will accept, or undefined. */
|
|
33
|
+
export declare function sanitizeRevenue(revenue: Revenue | undefined | null): {
|
|
34
|
+
amount: string | number;
|
|
35
|
+
currency?: string;
|
|
36
|
+
} | undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supermetry/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Server-side Node.js SDK for Supermetry self-hosted web analytics",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/velixio/supermetry.git",
|
|
9
|
+
"directory": "sdk/node"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/velixio/supermetry/tree/main/sdk/node#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/velixio/supermetry/issues"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public",
|
|
17
|
+
"provenance": true
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"main": "./dist/index.cjs",
|
|
21
|
+
"module": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js",
|
|
27
|
+
"require": "./dist/index.cjs"
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"],
|
|
32
|
+
"sideEffects": false,
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=18"
|
|
35
|
+
},
|
|
36
|
+
"keywords": ["analytics", "supermetry", "server-side", "tracking"],
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "rm -rf dist && bun build src/index.ts --outfile dist/index.js --format esm --target node --packages external && bun build src/index.ts --outfile dist/index.cjs --format cjs --target node --packages external && tsc -p tsconfig.build.json",
|
|
39
|
+
"package:check": "bun run scripts/smoke-package.mjs",
|
|
40
|
+
"prepack": "bun run build",
|
|
41
|
+
"test": "bun test",
|
|
42
|
+
"typecheck": "tsc --noEmit"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/bun": "^1.3.1",
|
|
46
|
+
"@types/node": "^22.0.0",
|
|
47
|
+
"typescript": "^5.9.3"
|
|
48
|
+
}
|
|
49
|
+
}
|