@viakite/node 0.0.0-stage → 1.0.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,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # @viakite/node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Viakite Analytics for Node.js servers: send purchases, signups and webhooks from your server with a secret key. Events are batched, sent in the background and retried, so none are lost to a passing network error.
4
+
5
+ Needs Node.js 18 or later.
6
+
7
+ ## Set up
8
+
9
+ Create a secret key with the `analytics.send` scope in **Settings → API keys**, and copy your project's id (`prj_…`).
10
+
11
+ ```ts
12
+ import { Viakite } from "@viakite/node";
13
+
14
+ const viakite = new Viakite({
15
+ secretKey: process.env.VIAKITE_SECRET_KEY!,
16
+ project: "prj_…",
17
+ });
18
+ ```
19
+
20
+ Keep the secret key on your server. A wrong key or project throws when the client is made.
21
+
22
+ ## Track an event
23
+
24
+ ```ts
25
+ viakite.track("Purchase", { revenue: 49, currency: "USD", plan: "pro" }, { userId: "u_123" });
26
+ ```
27
+
28
+ Pass the visitor's address and user agent from the incoming request to tell visitors apart and to get their device and browser. They are hashed and dropped, never stored:
29
+
30
+ ```ts
31
+ viakite.track("Signup", { method: "google" }, {
32
+ userId: user.id,
33
+ ip: req.ip,
34
+ userAgent: req.headers["user-agent"],
35
+ });
36
+ ```
37
+
38
+ Without them, an event with a `userId` counts that user as one visitor for the day. Events from a server have no location.
39
+
40
+ ## Identify a user
41
+
42
+ ```ts
43
+ viakite.identify("u_123", { plan: "pro" });
44
+ ```
45
+
46
+ ## Send before exit
47
+
48
+ Events go when 20 are waiting, every 10 seconds, and on `flush()`. Call `shutdown()` before the process exits, or the events still waiting are lost:
49
+
50
+ ```ts
51
+ process.on("SIGTERM", async () => {
52
+ await viakite.shutdown();
53
+ process.exit(0);
54
+ });
55
+ ```
56
+
57
+ In a serverless function, `await viakite.flush()` before you return.
58
+
59
+ ## Options
60
+
61
+ | Option | Default | Does |
62
+ |---|---|---|
63
+ | `secretKey` | required | A secret key, `sk_live_…` or `sk_test_…`, with the `analytics.send` scope |
64
+ | `project` | required | The project's id, `prj_…` |
65
+ | `endpoint` | your region | Send to another address, such as a proxy |
66
+ | `flushAt` | `20` | Send once this many events wait (at most 100) |
67
+ | `flushInterval` | `10000` | Send what waits every this many milliseconds; `0` turns it off |
68
+ | `maxRetries` | `3` | Tries again after a network error, a timeout, `429` or `5xx` |
69
+ | `timeout` | `10000` | How long one request may take, in milliseconds |
70
+ | `maxQueueSize` | `10000` | The most events that may wait; newer ones are dropped |
71
+ | `onError` | a console warning | Called with a `ViakiteError` when events can't be sent |
72
+ | `debug` | `false` | Log every request and answer |
@@ -0,0 +1,29 @@
1
+ import type { IdentifyOptions, Options, Props, TrackOptions } from "./types";
2
+ /**
3
+ * Viakite sends events from a server with a secret key. Events wait in
4
+ * memory and go in batches: when flushAt of them wait, every flushInterval,
5
+ * and on flush() or shutdown(). Failed requests are tried again; events
6
+ * still unsent when the process exits without shutdown() are lost.
7
+ */
8
+ export declare class Viakite {
9
+ private readonly cfg;
10
+ private queue;
11
+ private sending;
12
+ private timer;
13
+ private closed;
14
+ constructor(options: Options);
15
+ /** track records a custom event, such as a purchase or a signup. */
16
+ track(name: string, props?: Props, options?: TrackOptions): void;
17
+ /** identify ties a user id to traits such as their plan. */
18
+ identify(userId: string, traits?: Props, options?: IdentifyOptions): void;
19
+ /**
20
+ * flush sends every event waiting now. It resolves once they are sent or
21
+ * have failed for good (onError hears about those); it never rejects.
22
+ */
23
+ flush(): Promise<void>;
24
+ /** shutdown stops the timer and sends what waits. Call it before the process exits. */
25
+ shutdown(): Promise<void>;
26
+ private add;
27
+ private drain;
28
+ private next;
29
+ }
@@ -0,0 +1,24 @@
1
+ import type { Options, ViakiteError } from "./types";
2
+ /** MAX_BATCH is the most events one request carries (the API's limit). */
3
+ export declare const MAX_BATCH = 100;
4
+ /** Config is the client's settings after defaults and checks. */
5
+ export interface Config {
6
+ secretKey: string;
7
+ project: string;
8
+ endpoint: string;
9
+ flushAt: number;
10
+ flushInterval: number;
11
+ maxRetries: number;
12
+ timeout: number;
13
+ maxQueueSize: number;
14
+ debug: boolean;
15
+ onError: (error: ViakiteError) => void;
16
+ fetch: typeof fetch;
17
+ }
18
+ /**
19
+ * resolveConfig checks the options and fills the defaults. A wrong key or
20
+ * project throws at once, so a server never runs without sending. The key
21
+ * carries the region: sk_live_us_… sends to https://us.e.<DOMAIN>/v1/events
22
+ * unless endpoint points elsewhere.
23
+ */
24
+ export declare function resolveConfig(o: Options): Config;
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var c=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var O=(e,t)=>{for(var r in t)c(e,r,{get:t[r],enumerable:!0})},S=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of E(t))!A.call(e,i)&&i!==r&&c(e,i,{get:()=>t[i],enumerable:!(n=x(t,i))||n.enumerable});return e};var V=e=>S(c({},"__esModule",{value:!0}),e);var q={};O(q,{Viakite:()=>f,ViakiteError:()=>s});module.exports=V(q);var P=/^sk_(live|test)_([a-z]{2})_[a-z0-9]+$/;function a(e,t,r){return typeof e=="number"&&Number.isFinite(e)&&e>=r?Math.floor(e):t}function g(e){let t=String(e?.secretKey??"").trim(),r=P.exec(t);if(!r)throw new Error("Viakite: secretKey must be a secret key, sk_live_\u2026 or sk_test_\u2026 (Settings \u2192 API keys)");let n=String(e.project??"").trim();if(!/^prj_[A-Za-z0-9]+$/.test(n))throw new Error("Viakite: project must be the project's id, prj_\u2026");let i=e.fetch??globalThis.fetch;if(typeof i!="function")throw new Error("Viakite: no fetch found; use Node.js 18 or later, or pass fetch");return{secretKey:t,project:n,endpoint:e.endpoint||`https://${r[2]}.e.vk.viabio.me/v1/events`,flushAt:Math.min(a(e.flushAt,20,1),100),flushInterval:a(e.flushInterval,1e4,0),maxRetries:a(e.maxRetries,3,0),timeout:a(e.timeout,1e4,1),maxQueueSize:a(e.maxQueueSize,1e4,1),debug:!!e.debug,onError:e.onError??(o=>console.warn(`[viakite] ${o.message}`)),fetch:i}}var s=class extends Error{status;code;events;constructor(t,r,n,i){super(t),this.name="ViakiteError",this.status=r,this.code=n,this.events=i}};var _=e=>new Promise(t=>setTimeout(t,e));function I(e,t){if(t!==void 0)return Math.min(t*1e3,6e4);let r=Math.min(500*2**(e-1),3e4);return r/2+Math.random()*(r/2)}var j=e=>e===429||e>=500;async function l(e,t,r=_){let n=new s("not sent",0,"",t.length);for(let i=0;i<=e.maxRetries;i++){i>0&&await r(I(i,T(n)));try{let o=Date.now(),u=await e.fetch(e.endpoint,{method:"POST",headers:{Authorization:`Bearer ${e.secretKey}`,"Content-Type":"application/json","User-Agent":"viakite-node/1.0.0"},body:JSON.stringify(t.map(w=>({...w,sent:o}))),signal:AbortSignal.timeout(e.timeout)}),p=await C(u);if(u.ok){e.debug&&console.log(`[viakite] sent ${t.length}:`,p);return}let m=Number(u.headers.get("retry-after"));if(n=$(u.status,p,t.length,Number.isFinite(m)&&m>0?m:void 0),e.debug&&console.log(`[viakite] ${u.status}:`,p),!j(u.status))throw n}catch(o){if(o instanceof s)throw o;n=new s(`could not reach Viakite: ${o?.message??o}`,0,"",t.length),e.debug&&console.log(`[viakite] ${n.message}`)}}throw n}var b=new WeakMap;function T(e){return b.get(e)}function $(e,t,r,n){let i=t?.error,o=new s(`${r} event(s) not sent: ${e} ${i?.code??""} ${i?.message??""}`.trim(),e,i?.code??"",r);return n!==void 0&&b.set(o,n),o}async function C(e){try{return await e.json()}catch{return}}var y=require("node:crypto"),M="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function d(e=Date.now()){let t=(0,y.randomBytes)(16),r="";for(let n=0;n<26;n++)r+=M[n<10?Math.floor(e/2**(45-5*n))%32:t[n-10]%32];return r}var R=450*1024,h=e=>console.warn(`[viakite] ${e}`),f=class{cfg;queue=[];sending=Promise.resolve();timer;closed=!1;constructor(t){this.cfg=g(t),this.cfg.flushInterval>0&&(this.timer=setInterval(()=>{this.flush()},this.cfg.flushInterval),this.timer.unref?.())}track(t,r,n={}){if(typeof t!="string"||!t.trim()){h("track needs an event name; event not sent");return}this.add({type:"event",id:n.id||d(),project:this.cfg.project,ts:v(n.timestamp),name:t,...r&&{props:{...r}},...k(n),...n.url&&{url:n.url}})}identify(t,r,n={}){if(typeof t!="string"||!t.trim()){h("identify needs a user id; not sent");return}this.add({type:"identify",id:d(),project:this.cfg.project,ts:v(n.timestamp),...r&&{traits:{...r}},...k({...n,userId:t})})}flush(){return this.sending=this.sending.then(()=>this.drain()),this.sending}async shutdown(){this.closed=!0,this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}add(t){if(this.closed){h("the client is shut down; event not sent");return}if(this.queue.length>=this.cfg.maxQueueSize){this.cfg.onError(new s("the queue is full; event dropped",0,"queue_full",1));return}this.queue.push(t),this.queue.length>=this.cfg.flushAt&&this.flush()}async drain(){for(;this.queue.length>0;){let t=this.next();try{await l(this.cfg,t)}catch(r){this.cfg.onError(r instanceof s?r:new s(String(r),0,"",t.length))}}}next(){let t=2,r=0;for(;r<this.queue.length&&r<100&&(t+=JSON.stringify(this.queue[r]).length+1,!(r>0&&t>R));)r++;return this.queue.splice(0,r)}};function v(e){let t=e instanceof Date?e.getTime():NaN;return Number.isFinite(t)?t:Date.now()}function k(e){return{...e.userId&&{user_id:String(e.userId)},...e.ip&&{ip:String(e.ip)},...e.userAgent&&{user_agent:String(e.userAgent)}}}0&&(module.exports={Viakite,ViakiteError});
@@ -0,0 +1,3 @@
1
+ export { Viakite } from "./client";
2
+ export { ViakiteError } from "./types";
3
+ export type { IdentifyOptions, Options, PropValue, Props, TrackOptions, Visitor } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ var k=/^sk_(live|test)_([a-z]{2})_[a-z0-9]+$/;function a(e,t,r){return typeof e=="number"&&Number.isFinite(e)&&e>=r?Math.floor(e):t}function h(e){let t=String(e?.secretKey??"").trim(),r=k.exec(t);if(!r)throw new Error("Viakite: secretKey must be a secret key, sk_live_\u2026 or sk_test_\u2026 (Settings \u2192 API keys)");let n=String(e.project??"").trim();if(!/^prj_[A-Za-z0-9]+$/.test(n))throw new Error("Viakite: project must be the project's id, prj_\u2026");let i=e.fetch??globalThis.fetch;if(typeof i!="function")throw new Error("Viakite: no fetch found; use Node.js 18 or later, or pass fetch");return{secretKey:t,project:n,endpoint:e.endpoint||`https://${r[2]}.e.vk.viabio.me/v1/events`,flushAt:Math.min(a(e.flushAt,20,1),100),flushInterval:a(e.flushInterval,1e4,0),maxRetries:a(e.maxRetries,3,0),timeout:a(e.timeout,1e4,1),maxQueueSize:a(e.maxQueueSize,1e4,1),debug:!!e.debug,onError:e.onError??(o=>console.warn(`[viakite] ${o.message}`)),fetch:i}}var s=class extends Error{status;code;events;constructor(t,r,n,i){super(t),this.name="ViakiteError",this.status=r,this.code=n,this.events=i}};var w=e=>new Promise(t=>setTimeout(t,e));function x(e,t){if(t!==void 0)return Math.min(t*1e3,6e4);let r=Math.min(500*2**(e-1),3e4);return r/2+Math.random()*(r/2)}var E=e=>e===429||e>=500;async function g(e,t,r=w){let n=new s("not sent",0,"",t.length);for(let i=0;i<=e.maxRetries;i++){i>0&&await r(x(i,A(n)));try{let o=Date.now(),u=await e.fetch(e.endpoint,{method:"POST",headers:{Authorization:`Bearer ${e.secretKey}`,"Content-Type":"application/json","User-Agent":"viakite-node/1.0.0"},body:JSON.stringify(t.map(v=>({...v,sent:o}))),signal:AbortSignal.timeout(e.timeout)}),f=await S(u);if(u.ok){e.debug&&console.log(`[viakite] sent ${t.length}:`,f);return}let p=Number(u.headers.get("retry-after"));if(n=O(u.status,f,t.length,Number.isFinite(p)&&p>0?p:void 0),e.debug&&console.log(`[viakite] ${u.status}:`,f),!E(u.status))throw n}catch(o){if(o instanceof s)throw o;n=new s(`could not reach Viakite: ${o?.message??o}`,0,"",t.length),e.debug&&console.log(`[viakite] ${n.message}`)}}throw n}var l=new WeakMap;function A(e){return l.get(e)}function O(e,t,r,n){let i=t?.error,o=new s(`${r} event(s) not sent: ${e} ${i?.code??""} ${i?.message??""}`.trim(),e,i?.code??"",r);return n!==void 0&&l.set(o,n),o}async function S(e){try{return await e.json()}catch{return}}import{randomBytes as V}from"node:crypto";var P="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function m(e=Date.now()){let t=V(16),r="";for(let n=0;n<26;n++)r+=P[n<10?Math.floor(e/2**(45-5*n))%32:t[n-10]%32];return r}var I=450*1024,c=e=>console.warn(`[viakite] ${e}`),d=class{cfg;queue=[];sending=Promise.resolve();timer;closed=!1;constructor(t){this.cfg=h(t),this.cfg.flushInterval>0&&(this.timer=setInterval(()=>{this.flush()},this.cfg.flushInterval),this.timer.unref?.())}track(t,r,n={}){if(typeof t!="string"||!t.trim()){c("track needs an event name; event not sent");return}this.add({type:"event",id:n.id||m(),project:this.cfg.project,ts:b(n.timestamp),name:t,...r&&{props:{...r}},...y(n),...n.url&&{url:n.url}})}identify(t,r,n={}){if(typeof t!="string"||!t.trim()){c("identify needs a user id; not sent");return}this.add({type:"identify",id:m(),project:this.cfg.project,ts:b(n.timestamp),...r&&{traits:{...r}},...y({...n,userId:t})})}flush(){return this.sending=this.sending.then(()=>this.drain()),this.sending}async shutdown(){this.closed=!0,this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}add(t){if(this.closed){c("the client is shut down; event not sent");return}if(this.queue.length>=this.cfg.maxQueueSize){this.cfg.onError(new s("the queue is full; event dropped",0,"queue_full",1));return}this.queue.push(t),this.queue.length>=this.cfg.flushAt&&this.flush()}async drain(){for(;this.queue.length>0;){let t=this.next();try{await g(this.cfg,t)}catch(r){this.cfg.onError(r instanceof s?r:new s(String(r),0,"",t.length))}}}next(){let t=2,r=0;for(;r<this.queue.length&&r<100&&(t+=JSON.stringify(this.queue[r]).length+1,!(r>0&&t>I));)r++;return this.queue.splice(0,r)}};function b(e){let t=e instanceof Date?e.getTime():NaN;return Number.isFinite(t)?t:Date.now()}function y(e){return{...e.userId&&{user_id:String(e.userId)},...e.ip&&{ip:String(e.ip)},...e.userAgent&&{user_agent:String(e.userAgent)}}}export{d as Viakite,s as ViakiteError};
@@ -0,0 +1,28 @@
1
+ import type { Config } from "./config";
2
+ /** WireEvent is one event as POST /v1/events takes it. */
3
+ export interface WireEvent {
4
+ type: "event" | "identify";
5
+ id: string;
6
+ project: string;
7
+ ts: number;
8
+ sent?: number;
9
+ name?: string;
10
+ props?: Record<string, unknown>;
11
+ user_id?: string;
12
+ traits?: Record<string, unknown>;
13
+ url?: string;
14
+ ip?: string;
15
+ user_agent?: string;
16
+ }
17
+ /** Sleep waits ms milliseconds; tests replace it. */
18
+ export type Sleep = (ms: number) => Promise<void>;
19
+ /** backoff is the wait before try n (1, 2, …): 0.5 s doubling, up to 30 s, with jitter. */
20
+ export declare function backoff(n: number, retryAfter?: number): number;
21
+ /**
22
+ * send posts one batch, trying again on network errors, timeouts, 429 and
23
+ * 5xx up to maxRetries times. Every try sets `sent`, so the server corrects
24
+ * the clock from the same moment. Every event keeps its id, so a batch that
25
+ * reached the server before a timeout is still stored once. A batch that
26
+ * fails for good rejects with a ViakiteError.
27
+ */
28
+ export declare function send(cfg: Config, events: WireEvent[], sleep?: Sleep): Promise<void>;
@@ -0,0 +1,63 @@
1
+ /** A flat property value: nested objects and lists are not kept. */
2
+ export type PropValue = string | number | boolean | null;
3
+ /** Props are an event's properties or a user's traits: up to 20 flat values. */
4
+ export type Props = Record<string, PropValue>;
5
+ /** Options set up a client. */
6
+ export interface Options {
7
+ /** A secret key (`sk_live_…` or `sk_test_…`) with the `analytics.send` scope. Keep it on your server. */
8
+ secretKey: string;
9
+ /** The project's id, `prj_…`, from the project's settings. */
10
+ project: string;
11
+ /** Send to another address, such as a proxy. Default: your key's region, `https://<region>.e.<domain>/v1/events`. */
12
+ endpoint?: string;
13
+ /** Send once this many events wait. Default 20, at most 100. */
14
+ flushAt?: number;
15
+ /** Send what waits every this many milliseconds. Default 10000; 0 turns the timer off. */
16
+ flushInterval?: number;
17
+ /** How many times a failed request is tried again. Default 3. */
18
+ maxRetries?: number;
19
+ /** How long one request may take, in milliseconds. Default 10000. */
20
+ timeout?: number;
21
+ /** The most events that may wait; newer ones are dropped past it. Default 10000. */
22
+ maxQueueSize?: number;
23
+ /** Called when events can't be sent, after every retry. Default: a warning in the console. */
24
+ onError?: (error: ViakiteError) => void;
25
+ /** Log every request and answer in the console. */
26
+ debug?: boolean;
27
+ /** The fetch to use. Default: the global fetch (Node.js 18 and later). */
28
+ fetch?: typeof fetch;
29
+ }
30
+ /** Visitor says who the event is about. All fields are optional. */
31
+ export interface Visitor {
32
+ /** Your own id for the signed-in user. Never an e-mail address or phone number. */
33
+ userId?: string;
34
+ /** The visitor's IP address, from the incoming request. Hashed into the visitor id, never stored. */
35
+ ip?: string;
36
+ /** The visitor's user agent, from the incoming request. Gives the device and browser. */
37
+ userAgent?: string;
38
+ }
39
+ /** TrackOptions are the optional parts of a custom event. */
40
+ export interface TrackOptions extends Visitor {
41
+ /** The page the event belongs to, a full address. */
42
+ url?: string;
43
+ /** When it happened. Default: now. */
44
+ timestamp?: Date;
45
+ /** Your own unique id for the event, so sending it twice stores it once. Default: a new ULID. */
46
+ id?: string;
47
+ }
48
+ /** IdentifyOptions are the optional parts of an identify call. */
49
+ export interface IdentifyOptions {
50
+ ip?: string;
51
+ userAgent?: string;
52
+ timestamp?: Date;
53
+ }
54
+ /** ViakiteError is a request that failed for good. */
55
+ export declare class ViakiteError extends Error {
56
+ /** The HTTP status, or 0 when the request never got an answer. */
57
+ readonly status: number;
58
+ /** The API's error code, such as `unauthorized`, when it sent one. */
59
+ readonly code: string;
60
+ /** How many events were in the request. */
61
+ readonly events: number;
62
+ constructor(message: string, status: number, code: string, events: number);
63
+ }
package/dist/ulid.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * ulid makes a ULID: 10 characters of time in milliseconds, then 16 random
3
+ * ones. The server keeps each id once, so a retried event is never counted
4
+ * twice.
5
+ */
6
+ export declare function ulid(now?: number): string;
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@viakite/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Viakite Analytics for Node.js servers: send events with a secret key, batched and retried.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ },
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "sideEffects": false,
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "scripts": {
26
+ "build": "node scripts/build.mjs",
27
+ "lint": "eslint .",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "26.6.6",
33
+ "esbuild": "0.28.2",
34
+ "eslint": "10.15.0",
35
+ "typescript": "6.0.3",
36
+ "typescript-eslint": "8.73.0",
37
+ "vitest": "5.1.1"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }