@n-dream/builders-sdk 1.6.0 → 1.7.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 +28 -3
- package/dist/analytics-rules.d.ts +43 -0
- package/dist/analytics-rules.js +146 -0
- package/dist/analytics.d.ts +40 -0
- package/dist/analytics.js +262 -0
- package/dist/engine.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/memory-storage.d.ts +1 -1
- package/dist/memory-storage.js +1 -1
- package/dist/rules.d.ts +3 -0
- package/dist/rules.js +7 -2
- package/dist/testing.d.ts +2 -0
- package/dist/testing.js +8 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -59,6 +59,29 @@ const stop = notes.watch({ where: { folder: "work" } }, (items) => render(items)
|
|
|
59
59
|
tab), Builders refuses it with `user-changed`: nothing is read or
|
|
60
60
|
saved, `auth.onChange` gets the new user, and watches start again.
|
|
61
61
|
|
|
62
|
+
## Analytics
|
|
63
|
+
|
|
64
|
+
Counts of what users do (docs/login-and-data.md 23, D174). Signed-out
|
|
65
|
+
users count too; no `builders.data.json` is needed.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
builders.analytics.log("open"); // at the start: every user counts
|
|
69
|
+
builders.analytics.log("level_won", { level: 3, stars: 2 }, { time: 41.7, moves: 18 });
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
- `log(event, dims?, values?)`: names and keys 1 to 40 of `a-z`, `0-9`,
|
|
73
|
+
`_`. `dims`: at most 3, strings of at most 40 characters, whole numbers
|
|
74
|
+
or booleans (the combination). `values`: at most 3 finite numbers
|
|
75
|
+
(count, sum, min, max, percentiles).
|
|
76
|
+
- It never throws and returns nothing. A bad call is dropped with one
|
|
77
|
+
console warning. Batches go to `POST /_api/analytics` every 5 s and
|
|
78
|
+
when the page hides.
|
|
79
|
+
- Users without an id: once a UTC day the device sends the day it was
|
|
80
|
+
first seen (in `localStorage`), and if it is new this week or month.
|
|
81
|
+
- Never personal data in dims: only categories and numbers.
|
|
82
|
+
- Local mode: nothing is sent; `analyticsLog()` of `/testing` gives the
|
|
83
|
+
logs.
|
|
84
|
+
|
|
62
85
|
## Files
|
|
63
86
|
|
|
64
87
|
A file set is declared in `builders.data.json` as `"files": { "photos":
|
|
@@ -100,17 +123,19 @@ export default defineConfig({ plugins: [builders(), react()] });
|
|
|
100
123
|
Headless tests use:
|
|
101
124
|
|
|
102
125
|
```ts
|
|
103
|
-
import { signInAs, signOut, reset, seed, setLoginMode } from "@n-dream/builders-sdk/testing";
|
|
126
|
+
import { analyticsLog, signInAs, signOut, reset, seed, setLoginMode } from "@n-dream/builders-sdk/testing";
|
|
104
127
|
|
|
105
128
|
signInAs("Ann"); // the same name gives the same user id
|
|
106
129
|
signInAs("Dev", { developer: true });
|
|
107
130
|
await seed("posts", [{ data: { text: "Hi" } }], { as: "Bob" });
|
|
108
131
|
setLoginMode("emails", ["ann@example.com"]); // then signInAs takes the email
|
|
109
132
|
signOut();
|
|
110
|
-
reset(); // no users, no data
|
|
133
|
+
reset(); // no users, no data, no analytics logs
|
|
134
|
+
analyticsLog(); // the analytics.log() calls: [{ e, d?, v? }]
|
|
111
135
|
```
|
|
112
136
|
|
|
113
137
|
The SDK never uses the local mode on other hosts.
|
|
114
138
|
|
|
115
|
-
Release: the owner publishes with the
|
|
139
|
+
Release: the owner publishes with the dist-tag `latest`
|
|
140
|
+
(docs/setup/production.md, "Release the npm packages"). `pnpm pack`
|
|
116
141
|
builds `dist/` first.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export declare const ANALYTICS_NAME: RegExp;
|
|
2
|
+
export declare const ANALYTICS_PATH = "/_api/analytics";
|
|
3
|
+
export declare const ANALYTICS_DIMS_MAX = 3;
|
|
4
|
+
export declare const ANALYTICS_VALUES_MAX = 3;
|
|
5
|
+
export declare const ANALYTICS_STRING_MAX = 40;
|
|
6
|
+
export declare const ANALYTICS_BATCH_MAX = 100;
|
|
7
|
+
export declare const ANALYTICS_BODY_MAX: number;
|
|
8
|
+
export declare const ANALYTICS_EVENTS_PER_DAY = 50;
|
|
9
|
+
export declare const ANALYTICS_COMBOS_PER_EVENT = 200;
|
|
10
|
+
export declare const ANALYTICS_OTHER = "(other)";
|
|
11
|
+
export declare const ANALYTICS_RETENTION_DAYS = 90;
|
|
12
|
+
export declare const ANALYTICS_VALUE_MAX = 1000000000000;
|
|
13
|
+
export declare const ANALYTICS_VALUE_MIN = 0.000001;
|
|
14
|
+
export declare function clampValue(v: number): number;
|
|
15
|
+
export declare const ANALYTICS_PLATFORMS: readonly ["ios-browser", "other"];
|
|
16
|
+
export type AnalyticsPlatform = (typeof ANALYTICS_PLATFORMS)[number];
|
|
17
|
+
export type DimValue = string | number | boolean;
|
|
18
|
+
export interface AnalyticsEntry {
|
|
19
|
+
e: string;
|
|
20
|
+
d?: Record<string, DimValue>;
|
|
21
|
+
v?: Record<string, number>;
|
|
22
|
+
}
|
|
23
|
+
export interface ActiveMark {
|
|
24
|
+
firstDay: string;
|
|
25
|
+
newWeek: boolean;
|
|
26
|
+
newMonth: boolean;
|
|
27
|
+
platform: AnalyticsPlatform;
|
|
28
|
+
}
|
|
29
|
+
export interface AnalyticsBody {
|
|
30
|
+
events: AnalyticsEntry[];
|
|
31
|
+
user?: ActiveMark;
|
|
32
|
+
}
|
|
33
|
+
export declare function entryProblem(event: unknown, dims: unknown, values: unknown): string | null;
|
|
34
|
+
export declare function entryOf(event: string, dims?: Record<string, DimValue> | null, values?: Record<string, number> | null): AnalyticsEntry;
|
|
35
|
+
export declare const DAY: RegExp;
|
|
36
|
+
export declare function utcDay(ms: number): string;
|
|
37
|
+
export declare function utcMonth(ms: number): string;
|
|
38
|
+
export declare function isoWeek(ms: number): string;
|
|
39
|
+
export declare function parseAnalyticsBody(raw: unknown): {
|
|
40
|
+
body: AnalyticsBody;
|
|
41
|
+
dropped: number;
|
|
42
|
+
} | null;
|
|
43
|
+
export declare function comboKey(d: Record<string, DimValue> | undefined): string;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The rules of app analytics (D174): one module for analytics.log() in the
|
|
2
|
+
// SDK and for POST /_api/analytics in the data service, so that they
|
|
3
|
+
// cannot differ. It has no imports and no state.
|
|
4
|
+
// Event names and the keys of dims and values.
|
|
5
|
+
export const ANALYTICS_NAME = /^[a-z0-9_]{1,40}$/;
|
|
6
|
+
export const ANALYTICS_PATH = "/_api/analytics";
|
|
7
|
+
export const ANALYTICS_DIMS_MAX = 3;
|
|
8
|
+
export const ANALYTICS_VALUES_MAX = 3;
|
|
9
|
+
export const ANALYTICS_STRING_MAX = 40;
|
|
10
|
+
// The entries of one request (the SDK sends at most this many at a time).
|
|
11
|
+
export const ANALYTICS_BATCH_MAX = 100;
|
|
12
|
+
// The body of one request. A fetch with keepalive can send at most 64 KB.
|
|
13
|
+
export const ANALYTICS_BODY_MAX = 48 * 1024;
|
|
14
|
+
// Per app space and UTC day: events, and combinations per event. More go
|
|
15
|
+
// into OTHER.
|
|
16
|
+
export const ANALYTICS_EVENTS_PER_DAY = 50;
|
|
17
|
+
export const ANALYTICS_COMBOS_PER_EVENT = 200;
|
|
18
|
+
export const ANALYTICS_OTHER = "(other)";
|
|
19
|
+
export const ANALYTICS_RETENTION_DAYS = 90;
|
|
20
|
+
// The service clamps each value: |v| above ANALYTICS_VALUE_MAX becomes
|
|
21
|
+
// +/-ANALYTICS_VALUE_MAX, |v| below ANALYTICS_VALUE_MIN becomes 0. So sums
|
|
22
|
+
// stay finite and a histogram has a fixed range of buckets.
|
|
23
|
+
export const ANALYTICS_VALUE_MAX = 1e12;
|
|
24
|
+
export const ANALYTICS_VALUE_MIN = 1e-6;
|
|
25
|
+
export function clampValue(v) {
|
|
26
|
+
const a = Math.abs(v);
|
|
27
|
+
if (a < ANALYTICS_VALUE_MIN)
|
|
28
|
+
return 0;
|
|
29
|
+
if (a > ANALYTICS_VALUE_MAX)
|
|
30
|
+
return v < 0 ? -ANALYTICS_VALUE_MAX : ANALYTICS_VALUE_MAX;
|
|
31
|
+
return v;
|
|
32
|
+
}
|
|
33
|
+
export const ANALYTICS_PLATFORMS = ["ios-browser", "other"];
|
|
34
|
+
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
35
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
36
|
+
// The problem of one log() call, or null. Each problem is one plain
|
|
37
|
+
// sentence for the console.
|
|
38
|
+
export function entryProblem(event, dims, values) {
|
|
39
|
+
if (typeof event !== "string" || !ANALYTICS_NAME.test(event))
|
|
40
|
+
return "The event name must be 1 to 40 lowercase letters, digits or _.";
|
|
41
|
+
if (dims !== undefined && dims !== null) {
|
|
42
|
+
if (!isObject(dims))
|
|
43
|
+
return "dims must be an object.";
|
|
44
|
+
const keys = Object.keys(dims);
|
|
45
|
+
if (keys.length > ANALYTICS_DIMS_MAX)
|
|
46
|
+
return `dims can have at most ${ANALYTICS_DIMS_MAX} keys.`;
|
|
47
|
+
for (const k of keys) {
|
|
48
|
+
if (!ANALYTICS_NAME.test(k))
|
|
49
|
+
return "Each key of dims must be 1 to 40 lowercase letters, digits or _.";
|
|
50
|
+
const v = dims[k];
|
|
51
|
+
if (typeof v === "string" ? v.length > ANALYTICS_STRING_MAX : typeof v === "number" ? !Number.isSafeInteger(v) : typeof v !== "boolean") {
|
|
52
|
+
return `Each value of dims must be a string of at most ${ANALYTICS_STRING_MAX} characters, a whole number or true/false.`;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (values !== undefined && values !== null) {
|
|
57
|
+
if (!isObject(values))
|
|
58
|
+
return "values must be an object.";
|
|
59
|
+
const keys = Object.keys(values);
|
|
60
|
+
if (keys.length > ANALYTICS_VALUES_MAX)
|
|
61
|
+
return `values can have at most ${ANALYTICS_VALUES_MAX} keys.`;
|
|
62
|
+
for (const k of keys) {
|
|
63
|
+
if (!ANALYTICS_NAME.test(k))
|
|
64
|
+
return "Each key of values must be 1 to 40 lowercase letters, digits or _.";
|
|
65
|
+
const v = values[k];
|
|
66
|
+
if (typeof v !== "number" || !Number.isFinite(v))
|
|
67
|
+
return "Each value of values must be a finite number.";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
// The entry as it is sent (no empty objects).
|
|
73
|
+
export function entryOf(event, dims, values) {
|
|
74
|
+
const e = { e: event };
|
|
75
|
+
if (dims && Object.keys(dims).length)
|
|
76
|
+
e.d = { ...dims };
|
|
77
|
+
if (values && Object.keys(values).length)
|
|
78
|
+
e.v = { ...values };
|
|
79
|
+
return e;
|
|
80
|
+
}
|
|
81
|
+
// A UTC day as YYYY-MM-DD.
|
|
82
|
+
export const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
83
|
+
export function utcDay(ms) {
|
|
84
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
85
|
+
}
|
|
86
|
+
export function utcMonth(ms) {
|
|
87
|
+
return new Date(ms).toISOString().slice(0, 7);
|
|
88
|
+
}
|
|
89
|
+
// The ISO week of a UTC time: YYYY-Www.
|
|
90
|
+
export function isoWeek(ms) {
|
|
91
|
+
const d = new Date(ms);
|
|
92
|
+
const t = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
|
|
93
|
+
const dow = (new Date(t).getUTCDay() + 6) % 7; // Monday 0
|
|
94
|
+
const thursday = new Date(t + (3 - dow) * 86_400_000);
|
|
95
|
+
const year = thursday.getUTCFullYear();
|
|
96
|
+
const week = 1 + Math.floor((thursday.getTime() - Date.UTC(year, 0, 1)) / (7 * 86_400_000));
|
|
97
|
+
return `${year}-W${String(week).padStart(2, "0")}`;
|
|
98
|
+
}
|
|
99
|
+
function markOf(v) {
|
|
100
|
+
if (!isObject(v))
|
|
101
|
+
return null;
|
|
102
|
+
const { firstDay, newWeek, newMonth, platform } = v;
|
|
103
|
+
if (typeof firstDay !== "string" || !DAY.test(firstDay) || Number.isNaN(Date.parse(`${firstDay}T00:00:00Z`)))
|
|
104
|
+
return null;
|
|
105
|
+
if (typeof newWeek !== "boolean" || typeof newMonth !== "boolean")
|
|
106
|
+
return null;
|
|
107
|
+
if (typeof platform !== "string" || !ANALYTICS_PLATFORMS.includes(platform))
|
|
108
|
+
return null;
|
|
109
|
+
return { firstDay, newWeek, newMonth, platform: platform };
|
|
110
|
+
}
|
|
111
|
+
// The body of POST /_api/analytics, checked. Entries with a problem are
|
|
112
|
+
// left out (counted in `dropped`); a body that is not of this form is null.
|
|
113
|
+
export function parseAnalyticsBody(raw) {
|
|
114
|
+
if (!isObject(raw))
|
|
115
|
+
return null;
|
|
116
|
+
const events = raw.events ?? [];
|
|
117
|
+
if (!Array.isArray(events) || events.length > ANALYTICS_BATCH_MAX)
|
|
118
|
+
return null;
|
|
119
|
+
const out = [];
|
|
120
|
+
let dropped = 0;
|
|
121
|
+
for (const x of events) {
|
|
122
|
+
if (!isObject(x) || entryProblem(x.e, x.d, x.v) !== null) {
|
|
123
|
+
dropped++;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const v = x.v ? Object.fromEntries(Object.entries(x.v).map(([k, n]) => [k, clampValue(n)])) : undefined;
|
|
127
|
+
out.push(entryOf(x.e, x.d, v));
|
|
128
|
+
}
|
|
129
|
+
const body = { events: out };
|
|
130
|
+
if (own(raw, "user") && raw.user !== undefined && raw.user !== null) {
|
|
131
|
+
const m = markOf(raw.user);
|
|
132
|
+
if (!m)
|
|
133
|
+
dropped++;
|
|
134
|
+
else
|
|
135
|
+
body.user = m;
|
|
136
|
+
}
|
|
137
|
+
return { body, dropped };
|
|
138
|
+
}
|
|
139
|
+
// The combination of dims as one string: the keys in order, as JSON. No
|
|
140
|
+
// dims: "{}".
|
|
141
|
+
export function comboKey(d) {
|
|
142
|
+
if (!d)
|
|
143
|
+
return "{}";
|
|
144
|
+
const keys = Object.keys(d).sort();
|
|
145
|
+
return JSON.stringify(Object.fromEntries(keys.map((k) => [k, d[k]])));
|
|
146
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type ActiveMark, type AnalyticsEntry, type AnalyticsPlatform, type DimValue } from "./analytics-rules.js";
|
|
2
|
+
export interface Analytics {
|
|
3
|
+
log(event: string, dims?: Record<string, DimValue>, values?: Record<string, number>): void;
|
|
4
|
+
}
|
|
5
|
+
export declare const FLUSH_MS = 5000;
|
|
6
|
+
export declare const QUEUE_MAX = 1000;
|
|
7
|
+
export declare const SEND_BYTES: number;
|
|
8
|
+
export declare const ANALYTICS_STORAGE_KEY = "builders-analytics";
|
|
9
|
+
interface Nav {
|
|
10
|
+
userAgent?: string;
|
|
11
|
+
platform?: string;
|
|
12
|
+
maxTouchPoints?: number;
|
|
13
|
+
standalone?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface AnalyticsEnv {
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
now: () => number;
|
|
18
|
+
hostname?: string;
|
|
19
|
+
storage: () => Pick<Storage, "getItem" | "setItem"> | null;
|
|
20
|
+
navigator?: Nav;
|
|
21
|
+
standalone?: () => boolean;
|
|
22
|
+
document?: Pick<Document, "addEventListener" | "visibilityState">;
|
|
23
|
+
window?: Pick<Window, "addEventListener">;
|
|
24
|
+
setTimeout: (f: () => void, ms: number) => unknown;
|
|
25
|
+
clearTimeout: (t: unknown) => void;
|
|
26
|
+
warn: (msg: string) => void;
|
|
27
|
+
debug: (...a: unknown[]) => void;
|
|
28
|
+
}
|
|
29
|
+
export declare function platformOf(nav: Nav | undefined, standalone: boolean): AnalyticsPlatform;
|
|
30
|
+
export declare function activeMark(storage: Pick<Storage, "getItem" | "setItem"> | null, now: number, platform: AnalyticsPlatform): {
|
|
31
|
+
mark: ActiveMark;
|
|
32
|
+
save: () => void;
|
|
33
|
+
} | null;
|
|
34
|
+
export declare function byteLength(s: string): number;
|
|
35
|
+
export declare const localAnalytics: AnalyticsEntry[];
|
|
36
|
+
export declare function createAnalytics(envOf?: () => AnalyticsEnv): Analytics & {
|
|
37
|
+
flush(keepalive?: boolean): void;
|
|
38
|
+
};
|
|
39
|
+
export declare const analytics: Analytics;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { ANALYTICS_BATCH_MAX, ANALYTICS_PATH, entryOf, entryProblem, isoWeek, utcDay, utcMonth, DAY } from "./analytics-rules.js";
|
|
2
|
+
import { isLocalHost } from "./local.js";
|
|
3
|
+
export const FLUSH_MS = 5_000;
|
|
4
|
+
// Entries that wait at most. More are lost (an app that logs in a loop).
|
|
5
|
+
export const QUEUE_MAX = 1_000;
|
|
6
|
+
// The JSON of one request at most, in UTF-8 bytes (the service takes 48 KB;
|
|
7
|
+
// all keepalive fetches of a page together can send 64 KB).
|
|
8
|
+
export const SEND_BYTES = 40 * 1024;
|
|
9
|
+
// The device's state in localStorage.
|
|
10
|
+
export const ANALYTICS_STORAGE_KEY = "builders-analytics";
|
|
11
|
+
// "ios-browser": iPhone, iPad or iPod, in a browser (not an app on the home
|
|
12
|
+
// screen). iOS deletes the storage of a site after 7 days without a visit,
|
|
13
|
+
// so the retention of these users looks lower than it is.
|
|
14
|
+
export function platformOf(nav, standalone) {
|
|
15
|
+
if (!nav)
|
|
16
|
+
return "other";
|
|
17
|
+
const ua = nav.userAgent ?? "";
|
|
18
|
+
// iPadOS 13 and later says "Macintosh"; only the iPad has touch.
|
|
19
|
+
const ios = /iPad|iPhone|iPod/.test(ua) || ((nav.platform === "MacIntel" || /Macintosh/.test(ua)) && (nav.maxTouchPoints ?? 0) > 1);
|
|
20
|
+
return ios && !standalone && nav.standalone !== true ? "ios-browser" : "other";
|
|
21
|
+
}
|
|
22
|
+
// The mark of the first log of this UTC day on this device, or null (the
|
|
23
|
+
// device sent it already today, or localStorage does not work). save()
|
|
24
|
+
// keeps the day in localStorage: call it only after the service took the
|
|
25
|
+
// mark (a 2xx). A lost answer of a request that went through can count
|
|
26
|
+
// the device twice that day: rare, and accepted.
|
|
27
|
+
export function activeMark(storage, now, platform) {
|
|
28
|
+
if (!storage)
|
|
29
|
+
return null;
|
|
30
|
+
try {
|
|
31
|
+
const day = utcDay(now);
|
|
32
|
+
const week = isoWeek(now);
|
|
33
|
+
const month = utcMonth(now);
|
|
34
|
+
let s = {};
|
|
35
|
+
try {
|
|
36
|
+
const raw = storage.getItem(ANALYTICS_STORAGE_KEY);
|
|
37
|
+
const v = raw ? JSON.parse(raw) : null;
|
|
38
|
+
if (typeof v === "object" && v !== null)
|
|
39
|
+
s = v;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
s = {};
|
|
43
|
+
}
|
|
44
|
+
if (s.day === day)
|
|
45
|
+
return null;
|
|
46
|
+
const first = typeof s.first === "string" && DAY.test(s.first) && s.first <= day ? s.first : day;
|
|
47
|
+
// The first day is kept at once (a write that fails: no mark, else each
|
|
48
|
+
// page load would count); the day of the mark after the send.
|
|
49
|
+
storage.setItem(ANALYTICS_STORAGE_KEY, JSON.stringify({ ...s, first }));
|
|
50
|
+
const save = () => {
|
|
51
|
+
try {
|
|
52
|
+
storage.setItem(ANALYTICS_STORAGE_KEY, JSON.stringify({ first, day, week, month }));
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// The next page load sends the mark again.
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
return { mark: { firstDay: first, newWeek: s.week !== week, newMonth: s.month !== month, platform }, save };
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// No storage (private mode, blocked): no users, the events go on.
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const encoder = typeof TextEncoder === "function" ? new TextEncoder() : null;
|
|
66
|
+
// UTF-8 bytes (a character of another script can take 3 or 4 bytes).
|
|
67
|
+
export function byteLength(s) {
|
|
68
|
+
return encoder ? encoder.encode(s).length : s.length * 4;
|
|
69
|
+
}
|
|
70
|
+
function defaultEnv() {
|
|
71
|
+
const g = globalThis;
|
|
72
|
+
return {
|
|
73
|
+
fetch: g.fetch?.bind(globalThis),
|
|
74
|
+
now: () => Date.now(),
|
|
75
|
+
hostname: g.location?.hostname,
|
|
76
|
+
storage: () => {
|
|
77
|
+
try {
|
|
78
|
+
return g.localStorage ?? null;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
navigator: g.navigator,
|
|
85
|
+
standalone: () => {
|
|
86
|
+
try {
|
|
87
|
+
return !!g.matchMedia?.("(display-mode: standalone)").matches;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
document: g.document,
|
|
94
|
+
window: g.window,
|
|
95
|
+
setTimeout: (f, ms) => setTimeout(f, ms),
|
|
96
|
+
clearTimeout: (t) => clearTimeout(t),
|
|
97
|
+
warn: (m) => console.warn(m),
|
|
98
|
+
debug: (...a) => console.debug(...a),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
// The entries of the local mode (localhost), for tests (/testing).
|
|
102
|
+
export const localAnalytics = [];
|
|
103
|
+
export function createAnalytics(envOf = defaultEnv) {
|
|
104
|
+
let env = null;
|
|
105
|
+
const queue = [];
|
|
106
|
+
let mark = null;
|
|
107
|
+
let markedDay = null;
|
|
108
|
+
let timer = null;
|
|
109
|
+
let listening = false;
|
|
110
|
+
let full = false;
|
|
111
|
+
const warned = new Set();
|
|
112
|
+
const e = () => (env ??= envOf());
|
|
113
|
+
function warnOnce(key, msg) {
|
|
114
|
+
if (warned.has(key) || warned.size > 100)
|
|
115
|
+
return;
|
|
116
|
+
warned.add(key);
|
|
117
|
+
e().warn(`builders.analytics: ${msg}`);
|
|
118
|
+
}
|
|
119
|
+
function listen() {
|
|
120
|
+
if (listening)
|
|
121
|
+
return;
|
|
122
|
+
listening = true;
|
|
123
|
+
const x = e();
|
|
124
|
+
x.window?.addEventListener("pagehide", () => flush(true));
|
|
125
|
+
x.document?.addEventListener("visibilitychange", () => {
|
|
126
|
+
if (x.document?.visibilityState === "hidden")
|
|
127
|
+
flush(true);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
function schedule() {
|
|
131
|
+
if (timer !== null)
|
|
132
|
+
return;
|
|
133
|
+
timer = e().setTimeout(() => {
|
|
134
|
+
timer = null;
|
|
135
|
+
flush(false);
|
|
136
|
+
}, FLUSH_MS);
|
|
137
|
+
}
|
|
138
|
+
function flush(keepalive = false) {
|
|
139
|
+
try {
|
|
140
|
+
const x = e();
|
|
141
|
+
if (timer !== null) {
|
|
142
|
+
x.clearTimeout(timer);
|
|
143
|
+
timer = null;
|
|
144
|
+
}
|
|
145
|
+
while (queue.length || mark) {
|
|
146
|
+
const events = [];
|
|
147
|
+
const sent = mark;
|
|
148
|
+
mark = null;
|
|
149
|
+
// The bytes of the body: {"events":[...],"user":{...}}.
|
|
150
|
+
let bytes = 64 + (sent ? byteLength(JSON.stringify(sent.mark)) : 0);
|
|
151
|
+
while (queue.length && events.length < ANALYTICS_BATCH_MAX) {
|
|
152
|
+
const n = byteLength(JSON.stringify(queue[0])) + 1;
|
|
153
|
+
if (bytes + n > SEND_BYTES) {
|
|
154
|
+
// One entry is never this large (40 characters a string); drop
|
|
155
|
+
// it rather than block the queue.
|
|
156
|
+
if (!events.length)
|
|
157
|
+
queue.shift();
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
bytes += n;
|
|
161
|
+
events.push(queue.shift());
|
|
162
|
+
}
|
|
163
|
+
const body = JSON.stringify(sent ? { events, user: sent.mark } : { events });
|
|
164
|
+
if (!x.fetch)
|
|
165
|
+
return;
|
|
166
|
+
// At page hide the page can be gone before the answer comes: keep
|
|
167
|
+
// the day at once, so that the next page of the site sends no
|
|
168
|
+
// second mark. When the page lives on (hidden only) and the send
|
|
169
|
+
// fails, the mark goes again with the next batch.
|
|
170
|
+
if (keepalive && sent)
|
|
171
|
+
sent.save();
|
|
172
|
+
void x
|
|
173
|
+
.fetch(ANALYTICS_PATH, {
|
|
174
|
+
method: "POST",
|
|
175
|
+
credentials: "same-origin",
|
|
176
|
+
cache: "no-store",
|
|
177
|
+
keepalive,
|
|
178
|
+
// The headers of every changing request (docs/login-and-data.md 4.7).
|
|
179
|
+
headers: { "content-type": "application/json", "x-builders": "1" },
|
|
180
|
+
body,
|
|
181
|
+
})
|
|
182
|
+
.then((res) => {
|
|
183
|
+
if (!sent)
|
|
184
|
+
return;
|
|
185
|
+
if (res.ok) {
|
|
186
|
+
if (!keepalive)
|
|
187
|
+
sent.save();
|
|
188
|
+
}
|
|
189
|
+
// Busy or paused: the mark goes again with the next batch.
|
|
190
|
+
else if (res.status === 429 || res.status >= 500)
|
|
191
|
+
retryMark(sent);
|
|
192
|
+
}, () => sent && retryMark(sent))
|
|
193
|
+
.catch(() => { });
|
|
194
|
+
// keepalive: at most 64 KB in flight, so one request.
|
|
195
|
+
if (keepalive)
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
if (queue.length)
|
|
199
|
+
schedule();
|
|
200
|
+
full = false;
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
// Never an error for the app.
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function retryMark(m) {
|
|
207
|
+
mark ??= m;
|
|
208
|
+
schedule();
|
|
209
|
+
}
|
|
210
|
+
function log(event, dims, values) {
|
|
211
|
+
try {
|
|
212
|
+
const problem = entryProblem(event, dims, values);
|
|
213
|
+
if (problem)
|
|
214
|
+
return warnOnce(`${String(event).slice(0, 40)}|${problem}`, `${problem} This log was not saved.`);
|
|
215
|
+
const entry = entryOf(event, dims, values);
|
|
216
|
+
const x = e();
|
|
217
|
+
if (isLocalHost(x.hostname)) {
|
|
218
|
+
// The local mode (8.4): nothing leaves the page.
|
|
219
|
+
localAnalytics.push(entry);
|
|
220
|
+
if (localAnalytics.length > QUEUE_MAX)
|
|
221
|
+
localAnalytics.shift();
|
|
222
|
+
x.debug("builders.analytics.log", entry.e, entry.d ?? {}, entry.v ?? {});
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (x.hostname === undefined || !x.fetch)
|
|
226
|
+
return;
|
|
227
|
+
if (queue.length >= QUEUE_MAX) {
|
|
228
|
+
if (!full)
|
|
229
|
+
warnOnce("full", "Too many logs in a short time. Some were not saved.");
|
|
230
|
+
full = true;
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const now = x.now();
|
|
234
|
+
const day = utcDay(now);
|
|
235
|
+
if (markedDay !== day) {
|
|
236
|
+
markedDay = day;
|
|
237
|
+
try {
|
|
238
|
+
const m = activeMark(x.storage(), now, platformOf(x.navigator, x.standalone?.() ?? false));
|
|
239
|
+
if (m)
|
|
240
|
+
mark = m;
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
// No storage: no users, the events go on.
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
queue.push(entry);
|
|
247
|
+
listen();
|
|
248
|
+
if (queue.length >= ANALYTICS_BATCH_MAX)
|
|
249
|
+
flush(false);
|
|
250
|
+
else
|
|
251
|
+
schedule();
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
// Never an error for the app.
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return { log, flush };
|
|
258
|
+
}
|
|
259
|
+
export const analytics = (() => {
|
|
260
|
+
const a = createAnalytics();
|
|
261
|
+
return { log: (event, dims, values) => a.log(event, dims, values) };
|
|
262
|
+
})();
|
package/dist/engine.d.ts
CHANGED
|
@@ -43,7 +43,7 @@ export interface DataStorage {
|
|
|
43
43
|
readUs: number;
|
|
44
44
|
}>;
|
|
45
45
|
setMarker(path: string, removed: boolean): Promise<number>;
|
|
46
|
-
docsByPrefix(space: string, prefix: string, after: string | null, limit: number, sub?: "docs" | "files" | "marks"): Promise<Row[]>;
|
|
46
|
+
docsByPrefix(space: string, prefix: string, after: string | null, limit: number, sub?: "docs" | "files" | "marks" | "analytics"): Promise<Row[]>;
|
|
47
47
|
countByPrefix(space: string, prefix: string, max: number, sub?: "docs" | "files"): Promise<number>;
|
|
48
48
|
docsOfUser(space: string, uid: string, after: string | null, limit: number, sub?: "docs" | "files"): Promise<Row[]>;
|
|
49
49
|
listSub(space: string, sub: "marks" | "usage" | "colls" | "jobs", after: string | null, limit: number): Promise<Row[]>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { analytics, type Analytics } from "./analytics.js";
|
|
1
2
|
export { appInfo, APP_INFO_PATH, type AppInfo, type Environment } from "./app-info.js";
|
|
2
3
|
export { auth, type Auth, type User } from "./auth.js";
|
|
3
4
|
export { db, type Collection, type Db, type FileSet, type Item, type Page, type Query, type StoredFile } from "./data.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// @n-dream/builders-sdk (design 4.5, D13). Each platform service adds one
|
|
2
2
|
// named export here. The guidance uses `import * as builders from
|
|
3
3
|
// "@n-dream/builders-sdk"` (docs/login-and-data.md 8.1).
|
|
4
|
+
export { analytics } from "./analytics.js";
|
|
4
5
|
export { appInfo, APP_INFO_PATH } from "./app-info.js";
|
|
5
6
|
export { auth } from "./auth.js";
|
|
6
7
|
export { db } from "./data.js";
|
package/dist/memory-storage.d.ts
CHANGED
|
@@ -40,7 +40,7 @@ export declare class MemoryStorage implements DataStorage {
|
|
|
40
40
|
readUs: number;
|
|
41
41
|
}>;
|
|
42
42
|
setMarker(path: string, removed: boolean): Promise<number>;
|
|
43
|
-
docsByPrefix(space: string, prefix: string, after: string | null, limit: number, sub?: "docs" | "files" | "marks"): Promise<Row[]>;
|
|
43
|
+
docsByPrefix(space: string, prefix: string, after: string | null, limit: number, sub?: "docs" | "files" | "marks" | "analytics"): Promise<Row[]>;
|
|
44
44
|
countByPrefix(space: string, prefix: string, max: number, sub?: "docs" | "files"): Promise<number>;
|
|
45
45
|
docsOfUser(space: string, uid: string, after: string | null, limit: number, sub?: "docs" | "files"): Promise<Row[]>;
|
|
46
46
|
listSub(space: string, sub: "marks" | "usage" | "colls" | "jobs", after: string | null, limit: number): Promise<Row[]>;
|
package/dist/memory-storage.js
CHANGED
|
@@ -229,7 +229,7 @@ export class MemoryStorage {
|
|
|
229
229
|
}
|
|
230
230
|
async resetSpace(space) {
|
|
231
231
|
const marks = [...(this.sub(space, "marks")?.keys() ?? [])];
|
|
232
|
-
this.dropSubs(space, (name) => name === "removed" || name === "colls");
|
|
232
|
+
this.dropSubs(space, (name) => name === "removed" || name === "colls" || name === "analytics");
|
|
233
233
|
if (marks.length)
|
|
234
234
|
this.commit(marks.map((id) => ({ path: `spaces/${space}/marks/${id}`, data: { at: SERVER_TIME, resetAt: SERVER_TIME } })));
|
|
235
235
|
}
|
package/dist/rules.d.ts
CHANGED
|
@@ -91,6 +91,8 @@ export interface DataLimits {
|
|
|
91
91
|
downloadBytesPerAppPerMonth: number;
|
|
92
92
|
downloadBytesPerUserPerDay: number;
|
|
93
93
|
uploadBytesPerUserPerDay: number;
|
|
94
|
+
analyticsPointsPerMinute: number;
|
|
95
|
+
analyticsRequestsPerAppPerSecond: number;
|
|
94
96
|
}
|
|
95
97
|
export declare const DATA_LIMITS: Readonly<DataLimits>;
|
|
96
98
|
export declare function spaceLimits(space: "live" | "test", base?: Readonly<DataLimits>): DataLimits;
|
|
@@ -218,3 +220,4 @@ export interface FileOut {
|
|
|
218
220
|
createdAt: string;
|
|
219
221
|
url: string;
|
|
220
222
|
}
|
|
223
|
+
export * from "./analytics-rules.js";
|
package/dist/rules.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The rules of app data (docs/login-and-data.md 6, 8.3, 11.1). One module
|
|
2
2
|
// for the data service, the api, the CLI and the local mode of the SDK, so
|
|
3
|
-
// that they cannot differ (LD15, D135). It has no
|
|
3
|
+
// that they cannot differ (LD15, D135). It has no state; its only import is
|
|
4
|
+
// the analytics rules (analytics-rules.ts, also without imports).
|
|
4
5
|
const STATUS = {
|
|
5
6
|
"sign-in-required": 401,
|
|
6
7
|
"not-allowed": 403,
|
|
@@ -134,10 +135,12 @@ export const DATA_LIMITS = {
|
|
|
134
135
|
downloadBytesPerAppPerMonth: 50 * GB,
|
|
135
136
|
downloadBytesPerUserPerDay: 2 * GB,
|
|
136
137
|
uploadBytesPerUserPerDay: 1 * GB,
|
|
138
|
+
analyticsPointsPerMinute: 600,
|
|
139
|
+
analyticsRequestsPerAppPerSecond: 200,
|
|
137
140
|
};
|
|
138
141
|
// The per-app values that the test space gets one tenth of (11.1). The
|
|
139
142
|
// per-user values stay the same.
|
|
140
|
-
const PER_APP = ["mineBytesPerApp", "publicItemsPerApp", "publicBytesPerApp", "requestsPerAppPerSecond", "readsPerAppPerMonth", "writesPerAppPerMonth", "waitsPerApp", "fileBytesPerApp", "downloadBytesPerAppPerMonth"];
|
|
143
|
+
const PER_APP = ["mineBytesPerApp", "publicItemsPerApp", "publicBytesPerApp", "requestsPerAppPerSecond", "readsPerAppPerMonth", "writesPerAppPerMonth", "waitsPerApp", "fileBytesPerApp", "downloadBytesPerAppPerMonth", "analyticsRequestsPerAppPerSecond"];
|
|
141
144
|
export function spaceLimits(space, base = DATA_LIMITS) {
|
|
142
145
|
const out = { ...base };
|
|
143
146
|
if (space === "test")
|
|
@@ -822,3 +825,5 @@ export function downloadNameOf(name, type) {
|
|
|
822
825
|
const stem = name.replace(/[\\/]/g, "_").replace(/\.[A-Za-z0-9]{1,5}$/, "") || "file";
|
|
823
826
|
return `${stem}.${ext}`;
|
|
824
827
|
}
|
|
828
|
+
// --- Analytics (D174). ---
|
|
829
|
+
export * from "./analytics-rules.js";
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import type { AnalyticsEntry } from "./analytics-rules.js";
|
|
1
2
|
import type { LoginMode } from "./rules.js";
|
|
2
3
|
export declare function signInAs(name: string, opts?: {
|
|
3
4
|
developer?: boolean;
|
|
4
5
|
}): void;
|
|
5
6
|
export declare function signOut(): void;
|
|
6
7
|
export declare function reset(): void;
|
|
8
|
+
export declare function analyticsLog(): AnalyticsEntry[];
|
|
7
9
|
export declare function setLoginMode(mode: LoginMode, list?: string[]): void;
|
|
8
10
|
export declare function seed(collection: string, items: Array<{
|
|
9
11
|
id?: string;
|
package/dist/testing.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @n-dream/builders-sdk/testing: helpers for headless tests in the local
|
|
2
2
|
// mode (docs/login-and-data.md 8.4). They work only on localhost.
|
|
3
|
+
import { localAnalytics } from "./analytics.js";
|
|
3
4
|
import { isLocalHost, local, localUserId, setLocalUser } from "./local.js";
|
|
4
5
|
import { localLoginRefusal, resetLocal, seedLocal, setLocalLoginMode } from "./local-db.js";
|
|
5
6
|
function check() {
|
|
@@ -26,6 +27,13 @@ export function reset() {
|
|
|
26
27
|
check();
|
|
27
28
|
resetLocal();
|
|
28
29
|
setLocalUser(null);
|
|
30
|
+
localAnalytics.length = 0;
|
|
31
|
+
}
|
|
32
|
+
// The analytics.log() calls of this page in the local mode (D174), oldest
|
|
33
|
+
// first: { e: event, d?: dims, v?: values }.
|
|
34
|
+
export function analyticsLog() {
|
|
35
|
+
check();
|
|
36
|
+
return localAnalytics.map((x) => structuredClone(x));
|
|
29
37
|
}
|
|
30
38
|
// Who can sign in (4.4). With "domains" or "emails", public lists need
|
|
31
39
|
// sign-in to read (LD9).
|