cursedbelt-server 4.58.0 β†’ 4.60.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.
Files changed (45) hide show
  1. package/dist/server/engagement/api.d.ts +6 -0
  2. package/dist/server/engagement/api.js +3 -0
  3. package/dist/server/engagement/d1.d.ts +7 -0
  4. package/dist/server/engagement/d1.js +4 -0
  5. package/dist/server/engagement/events.d.ts +26 -0
  6. package/dist/server/engagement/events.js +52 -0
  7. package/dist/server/engagement/policy.d.ts +2 -1
  8. package/dist/server/engagement/policy.js +11 -3
  9. package/dist/server/events/actions.d.ts +46 -0
  10. package/dist/server/events/actions.js +62 -0
  11. package/dist/server/events/actor.d.ts +19 -0
  12. package/dist/server/events/actor.js +30 -0
  13. package/dist/server/events/gauge.d.ts +21 -0
  14. package/dist/server/events/gauge.js +60 -0
  15. package/dist/server/events/index.d.ts +14 -0
  16. package/dist/server/events/index.js +14 -0
  17. package/dist/server/events/point.d.ts +77 -0
  18. package/dist/server/events/point.js +149 -0
  19. package/dist/server/events/sink.d.ts +97 -0
  20. package/dist/server/events/sink.js +113 -0
  21. package/dist/server/events/views.d.ts +24 -0
  22. package/dist/server/events/views.js +41 -0
  23. package/dist/server/youtube/ytdlp.d.ts +14 -4
  24. package/dist/server/youtube/ytdlp.js +11 -4
  25. package/package.json +8 -2
  26. package/src/server/bench/cpuBudget.spec.ts +12 -8
  27. package/src/server/engagement/api.ts +8 -0
  28. package/src/server/engagement/d1.ts +9 -0
  29. package/src/server/engagement/engagement.spec.ts +15 -1
  30. package/src/server/engagement/events.ts +79 -0
  31. package/src/server/engagement/policy.ts +10 -3
  32. package/src/server/events/actions.spec.ts +126 -0
  33. package/src/server/events/actions.ts +113 -0
  34. package/src/server/events/actor.ts +34 -0
  35. package/src/server/events/gauge.spec.ts +75 -0
  36. package/src/server/events/gauge.ts +81 -0
  37. package/src/server/events/index.ts +47 -0
  38. package/src/server/events/point.spec.ts +145 -0
  39. package/src/server/events/point.ts +197 -0
  40. package/src/server/events/sink.spec.ts +289 -0
  41. package/src/server/events/sink.ts +221 -0
  42. package/src/server/events/views.ts +62 -0
  43. package/src/server/telemetryIsWorkerSafe.spec.ts +23 -0
  44. package/src/server/youtube/ytdlp.spec.ts +14 -2
  45. package/src/server/youtube/ytdlp.ts +25 -7
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The user-event data point β€” the ONE schema every app in every workspace writes to its own
3
+ * `<app>_events` Analytics Engine dataset (the event schema, v1, 2026-10-31). A collector on the
4
+ * Mac reads every dataset through the account's SQL API, so nothing here is read back by an app.
5
+ *
6
+ * πŸ”΄ **The layout is a WIRE FORMAT.** Analytics Engine columns are positional (`blob1`,
7
+ * `double1`, …) and the collector's queries name them by position: append only, never reorder,
8
+ * never repurpose. `point.spec.ts` pins every position.
9
+ *
10
+ * ```
11
+ * index1 = `${kind}:${name}`, ≀96 bytes
12
+ * blob1 = "e1" (schema) blob2 = app blob3 = kind blob4 = name
13
+ * blob5 = place blob6 = actor blob7 = actorKind blob8 = actorLabel
14
+ * blob9 = tenant blob10 = via blob11 = purpose blob12 = device
15
+ * blob13 = country blob14 = outcome blob15 = referrer blob16 = build
16
+ * double1 = 1 (count) double2 = ms double3 = bytes double4 = value
17
+ * ```
18
+ *
19
+ * Every vocabulary below is CLOSED: the collector groups by these words, and a new one is a
20
+ * schema change for every workspace, not a local choice. Nothing private goes in a blob β€” no
21
+ * titles, file names, query strings, search terms, raw addresses: a place is a route PATTERN.
22
+ */
23
+ export const EVENT_SCHEMA = "e1";
24
+ export const EVENT_KINDS = ["view", "action", "auth", "storage", "error"];
25
+ export const ACTOR_KINDS = ["owner", "user", "anon", "agent", "smoke", "bot"];
26
+ export const EVENT_VIAS = ["web", "api", "mcp", "agent", "cli", "cron", "hook"];
27
+ export const EVENT_PURPOSES = [
28
+ "read",
29
+ "create",
30
+ "edit",
31
+ "organize",
32
+ "search",
33
+ "ask",
34
+ "share",
35
+ "play",
36
+ "upload",
37
+ "download",
38
+ "account",
39
+ "admin",
40
+ "support",
41
+ "land",
42
+ ];
43
+ /** The platform's index limit; a blob is capped well under the 5,120-byte total for 16 of them. */
44
+ const INDEX_MAX_BYTES = 96;
45
+ const BLOB_MAX_BYTES = 256;
46
+ /**
47
+ * Truncate to at most `maxBytes` UTF-8 bytes without splitting a code point β€” `String.slice`
48
+ * counts UTF-16 units, so a name with one multi-byte character can be ≀96 chars and still exceed
49
+ * the 96-BYTE index limit. (The same rule `metrics/telemetrySink.ts` keeps for its index.)
50
+ */
51
+ export function truncateUtf8(value, maxBytes) {
52
+ const encoded = new TextEncoder().encode(value);
53
+ if (encoded.length <= maxBytes)
54
+ return value;
55
+ return new TextDecoder("utf-8", { fatal: false }).decode(encoded.subarray(0, maxBytes)).replace(/οΏ½+$/, "");
56
+ }
57
+ const finite = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
58
+ const blob = (value) => truncateUtf8(value ?? "", BLOB_MAX_BYTES);
59
+ /** The documented layout above, as data. Exported so the spec asserts the wire format itself. */
60
+ export function toEventPoint(event) {
61
+ const name = blob(event.name);
62
+ return {
63
+ indexes: [truncateUtf8(`${event.kind}:${name}`, INDEX_MAX_BYTES)],
64
+ blobs: [
65
+ EVENT_SCHEMA,
66
+ blob(event.app),
67
+ event.kind,
68
+ name,
69
+ blob(event.place),
70
+ blob(event.actor),
71
+ event.actorKind,
72
+ blob(event.actorLabel),
73
+ blob(event.tenant),
74
+ event.via,
75
+ event.purpose,
76
+ event.device,
77
+ blob(event.country),
78
+ event.outcome,
79
+ blob(event.referrer),
80
+ blob(event.build),
81
+ ],
82
+ doubles: [1, finite(event.ms), finite(event.bytes), finite(event.value)],
83
+ };
84
+ }
85
+ /** The schema's crawler words, matched case-insensitively anywhere in the User-Agent. */
86
+ export const BOT_USER_AGENT_WORDS = [
87
+ "googlebot",
88
+ "bingbot",
89
+ "bot",
90
+ "crawl",
91
+ "spider",
92
+ "slurp",
93
+ "preview",
94
+ "facebookexternalhit",
95
+ "headless",
96
+ ];
97
+ const BOT_RE = new RegExp(BOT_USER_AGENT_WORDS.join("|"), "i");
98
+ /** A tool, not a browser and not a crawler: the schema's `other` device. */
99
+ const TOOL_RE = /^(curl|wget|bun|node|python|go-http-client|okhttp|java|libwww|httpie)\b|\b(python-requests|undici|axios)\b/i;
100
+ const PHONE_RE = /\b(iphone|ipod|windows phone|mobile)\b/i;
101
+ const TABLET_RE = /\b(ipad|tablet|kindle|silk|playbook)\b/i;
102
+ export function isBotUserAgent(userAgent) {
103
+ return !!userAgent && BOT_RE.test(userAgent);
104
+ }
105
+ /** The schema's device classes, from the User-Agent alone. */
106
+ export function classifyDevice(userAgent) {
107
+ const ua = (userAgent ?? "").trim();
108
+ if (!ua)
109
+ return "other";
110
+ if (isBotUserAgent(ua))
111
+ return "bot";
112
+ if (TOOL_RE.test(ua))
113
+ return "other";
114
+ // An Android tablet says `Android` without `Mobile`; a phone says both β€” so phones first.
115
+ if (PHONE_RE.test(ua))
116
+ return "phone";
117
+ if (TABLET_RE.test(ua) || /\bandroid\b/i.test(ua))
118
+ return "tablet";
119
+ if (/\b(mozilla|opera|safari|chrome|firefox|edge)\b/i.test(ua))
120
+ return "desktop";
121
+ return "other";
122
+ }
123
+ /** `ok` | `fail` (4xx) | `refused` (401/403) | `error` (5xx), from a response status. */
124
+ export function outcomeOf(status) {
125
+ if (typeof status !== "number" || !Number.isFinite(status))
126
+ return "ok";
127
+ if (status === 401 || status === 403)
128
+ return "refused";
129
+ if (status >= 500)
130
+ return "error";
131
+ if (status >= 400)
132
+ return "fail";
133
+ return "ok";
134
+ }
135
+ /** The Referer's HOST and nothing else β€” never a path, never a query. `''` when absent or unparsable. */
136
+ export function referrerHost(referer) {
137
+ if (!referer)
138
+ return "";
139
+ try {
140
+ return new URL(referer).hostname.toLowerCase();
141
+ }
142
+ catch {
143
+ return "";
144
+ }
145
+ }
146
+ /** `YYYY-MM-DD` in UTC β€” the day an anonymous actor's hash rotates on. */
147
+ export function utcDay(ms) {
148
+ return new Date(ms).toISOString().slice(0, 10); // tz:utc β€” the schema's day: the anonymous hash rotates at UTC midnight
149
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `createEventSink(binding, options)` β€” the one seam an app records user events through.
3
+ *
4
+ * ```ts
5
+ * const events = createEventSink(env.EVENTS, { app: "music", salt: env.EVENTS_SALT, build: env.MUSIC_BUILD_COMMIT,
6
+ * defer: (work) => ctx.waitUntil(work) });
7
+ * events.record(c.req.raw, { kind: "action", name: "file.upload", place: "upload", purpose: "upload",
8
+ * actor: { id: user.email, owner: user.isOwner }, status: 200, ms, bytes });
9
+ * ```
10
+ *
11
+ * `record` is synchronous, never throws, and is never awaited by a caller: a known actor writes
12
+ * at once; an anonymous one hashes first (Web Crypto is async) and writes when the digest lands,
13
+ * which `defer` (a Worker's `ctx.waitUntil`) keeps alive past the response. A write that fails is
14
+ * counted nowhere else β€” the schema's "a failure must never reach the user".
15
+ *
16
+ * What the request supplies, and the body never does: the address and User-Agent (the anonymous
17
+ * hash, the device, the bot verdict), `request.cf.country`, the Referer HOST for a public view,
18
+ * and whether an Access service token (`cf-access-client-id`) β€” a deploy smoke β€” sent it.
19
+ */
20
+ import type { AnalyticsEngineDataset } from "../metrics/telemetrySink.js";
21
+ import { type ActorKind, type EventKind, type EventOutcome, type EventPurpose, type EventVia } from "./point.js";
22
+ /** The `EVENTS` binding β€” the same shape as the `AE` binding `requestLogger` writes to. */
23
+ export type EventsDataset = AnalyticsEngineDataset;
24
+ /** Who did it, as far as the app knows. Absent or `id: null` β†’ the anonymous hash. */
25
+ export interface EventActor {
26
+ /** The stable id the app already uses for the person β€” the email `requestLogger` writes. */
27
+ id?: string | null;
28
+ /** Human-readable: the display name or email. Default: the id. */
29
+ label?: string | null;
30
+ /** The app owner's own account (`SsoUser.isOwner`). */
31
+ owner?: boolean;
32
+ /** Said outright β€” `agent` for a bearer/service token, `smoke` for a deploy identity β€” else resolved. */
33
+ kind?: ActorKind;
34
+ }
35
+ export interface EventFields {
36
+ kind: EventKind;
37
+ name: string;
38
+ /** The page/view it happened on (a view's own name for a `view`). */
39
+ place?: string;
40
+ purpose: EventPurpose;
41
+ /** Default `web`. */
42
+ via?: EventVia;
43
+ actor?: EventActor | null;
44
+ tenant?: string;
45
+ /** The response status, read as the outcome (`outcomeOf`) unless `outcome` is given. */
46
+ status?: number;
47
+ outcome?: EventOutcome;
48
+ ms?: number;
49
+ bytes?: number;
50
+ value?: number;
51
+ /** A PUBLIC page's view: the Referer host is recorded. Never for anything behind a session. */
52
+ public?: boolean;
53
+ /** Overrides the sink's build stamp for this one point. */
54
+ build?: string;
55
+ }
56
+ export interface EventSinkOptions {
57
+ /** The registry id β€” `music`, `family`, `patterns`. */
58
+ app: string;
59
+ /** `EVENTS_SALT`; absent β†’ `LOCAL_EVENTS_SALT` (local dev), and the write still happens. */
60
+ salt?: string | null;
61
+ /** The deploy's build stamp (`<APP>_BUILD_COMMIT`), for blob16. */
62
+ build?: string | null;
63
+ /** Accounts whose activity is a deploy smoke or stage walk. Default: `smoke@auth.local`. */
64
+ smokeAccounts?: readonly string[];
65
+ /** Keeps the anonymous hash's write alive past the response β€” a Worker's `ctx.waitUntil`. */
66
+ defer?: (work: Promise<unknown>) => void;
67
+ now?: () => number;
68
+ }
69
+ export interface EventSink {
70
+ /** False when no binding was passed: every `record` is then a no-op. */
71
+ readonly bound: boolean;
72
+ /** Record one event. Synchronous, never throws, never awaited. */
73
+ record(request: Request | null | undefined, fields: EventFields): void;
74
+ }
75
+ /** The stage walk's account (`apps/auth-stage/scripts/accessWalk.ts` β†’ `SMOKE_ACCOUNT`). */
76
+ export declare const DEFAULT_SMOKE_ACCOUNTS: readonly string[];
77
+ /** Is this actor id a deploy smoke's or a stage walk's? `smokeAccounts` adds an app's own. */
78
+ export declare function isSmokeAccount(id: string, smokeAccounts?: readonly string[]): boolean;
79
+ /** What one request says about its sender β€” everything the point takes from headers. */
80
+ export interface RequestFacts {
81
+ ip: string;
82
+ userAgent: string;
83
+ country: string;
84
+ referrer: string;
85
+ /** An Access service token sent it β€” the deploy smokes' identity. */
86
+ serviceToken: boolean;
87
+ }
88
+ export declare function requestFacts(request: Request | null | undefined): RequestFacts;
89
+ /** The schema's actorKind rule, as one pure decision β€” `sink.spec.ts` pins each branch. */
90
+ export declare function resolveActorKind(input: {
91
+ actor: EventActor | null | undefined;
92
+ facts: Pick<RequestFacts, "userAgent" | "serviceToken">;
93
+ smokeAccounts: readonly string[];
94
+ }): ActorKind;
95
+ export declare function createEventSink(binding: EventsDataset | null | undefined, options: EventSinkOptions): EventSink;
96
+ /** One event through a throwaway sink β€” for a caller with no sink to keep. */
97
+ export declare function recordEvent(binding: EventsDataset | null | undefined, request: Request | null | undefined, fields: EventFields, options: EventSinkOptions): void;
@@ -0,0 +1,113 @@
1
+ import { anonymousActor } from "./actor.js";
2
+ import { classifyDevice, isBotUserAgent, outcomeOf, referrerHost, toEventPoint, } from "./point.js";
3
+ /** The stage walk's account (`apps/auth-stage/scripts/accessWalk.ts` β†’ `SMOKE_ACCOUNT`). */
4
+ export const DEFAULT_SMOKE_ACCOUNTS = ["smoke@auth.local"];
5
+ /**
6
+ * The stage registry's seeded accounts (`apps/auth-stage/scripts/seed.ts`): `stage-owner@` and
7
+ * `stage-user-<i>-<seed>@cursedalchemy.com`, which every app's stage walk signs in as. They exist on
8
+ * no production registry, so a point they make is a walk's β€” `smoke`, never a person.
9
+ */
10
+ const STAGE_SEED_ACCOUNT = /^stage-(?:owner|user-\d+-[0-9a-f]+)@cursedalchemy\.com$/;
11
+ /** Is this actor id a deploy smoke's or a stage walk's? `smokeAccounts` adds an app's own. */
12
+ export function isSmokeAccount(id, smokeAccounts = DEFAULT_SMOKE_ACCOUNTS) {
13
+ const lower = id.trim().toLowerCase();
14
+ if (lower === "")
15
+ return false;
16
+ return STAGE_SEED_ACCOUNT.test(lower) || smokeAccounts.some((account) => account.toLowerCase() === lower);
17
+ }
18
+ export function requestFacts(request) {
19
+ if (!request)
20
+ return { ip: "", userAgent: "", country: "", referrer: "", serviceToken: false };
21
+ const headers = request.headers;
22
+ const forwarded = headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "";
23
+ const cf = request.cf;
24
+ return {
25
+ ip: headers.get("cf-connecting-ip")?.trim() || forwarded,
26
+ userAgent: headers.get("user-agent") ?? "",
27
+ country: typeof cf?.country === "string" ? cf.country : "",
28
+ referrer: referrerHost(headers.get("referer")),
29
+ serviceToken: headers.has("cf-access-client-id"),
30
+ };
31
+ }
32
+ /** The schema's actorKind rule, as one pure decision β€” `sink.spec.ts` pins each branch. */
33
+ export function resolveActorKind(input) {
34
+ const { actor, facts } = input;
35
+ if (actor?.kind)
36
+ return actor.kind;
37
+ const id = actor?.id?.trim().toLowerCase() ?? "";
38
+ if (isSmokeAccount(id, input.smokeAccounts))
39
+ return "smoke";
40
+ if (facts.serviceToken)
41
+ return "smoke";
42
+ if (isBotUserAgent(facts.userAgent))
43
+ return "bot";
44
+ if (id)
45
+ return actor?.owner ? "owner" : "user";
46
+ return "anon";
47
+ }
48
+ export function createEventSink(binding, options) {
49
+ const now = options.now ?? (() => Date.now());
50
+ const smokeAccounts = options.smokeAccounts ?? DEFAULT_SMOKE_ACCOUNTS;
51
+ const build = options.build ?? "";
52
+ const write = (point) => {
53
+ try {
54
+ binding?.writeDataPoint(toEventPoint(point));
55
+ }
56
+ catch (error) {
57
+ console.warn(`[events] a ${point.kind}:${point.name} point was not written: ${String(error)}`);
58
+ }
59
+ };
60
+ return {
61
+ bound: !!binding,
62
+ record(request, fields) {
63
+ if (!binding)
64
+ return;
65
+ try {
66
+ const facts = requestFacts(request);
67
+ const actorKind = resolveActorKind({ actor: fields.actor, facts, smokeAccounts });
68
+ const id = fields.actor?.id?.trim() ?? "";
69
+ const base = {
70
+ app: options.app,
71
+ kind: fields.kind,
72
+ name: fields.name,
73
+ place: fields.place ?? "",
74
+ actorKind,
75
+ actorLabel: id ? (fields.actor?.label ?? id) : "",
76
+ tenant: fields.tenant ?? "",
77
+ via: fields.via ?? "web",
78
+ purpose: fields.purpose,
79
+ device: classifyDevice(facts.userAgent),
80
+ country: facts.country,
81
+ outcome: fields.outcome ?? outcomeOf(fields.status),
82
+ referrer: fields.public && fields.kind === "view" ? facts.referrer : "",
83
+ build: fields.build ?? build,
84
+ ms: fields.ms ?? 0,
85
+ bytes: fields.bytes ?? 0,
86
+ value: fields.value ?? 0,
87
+ };
88
+ if (id) {
89
+ write({ ...base, actor: id });
90
+ return;
91
+ }
92
+ // Machine traffic with no address at all (a cron, a gauge) has no identity to hash.
93
+ if (!facts.ip && !facts.userAgent) {
94
+ write({ ...base, actor: "" });
95
+ return;
96
+ }
97
+ const pending = anonymousActor({ ip: facts.ip, userAgent: facts.userAgent, salt: options.salt, now: now() })
98
+ .then((actor) => write({ ...base, actor }))
99
+ .catch((error) => {
100
+ console.warn(`[events] a ${fields.kind}:${fields.name} point was not written: ${String(error)}`);
101
+ });
102
+ options.defer?.(pending);
103
+ }
104
+ catch (error) {
105
+ console.warn(`[events] a ${fields.kind}:${fields.name} point was not written: ${String(error)}`);
106
+ }
107
+ },
108
+ };
109
+ }
110
+ /** One event through a throwaway sink β€” for a caller with no sink to keep. */
111
+ export function recordEvent(binding, request, fields, options) {
112
+ createEventSink(binding, options).record(request, fields);
113
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A server-side `view` for a public page: the schema's rule for prerendered and shell pages β€”
3
+ * record in the Worker's fetch path on an HTML navigation (GET, `Accept` includes `text/html`,
4
+ * status 200, not `/assets/*`, not `/api/*`, not `/healthz`, not a file), with the anonymous
5
+ * hashed actor or the session's, and the Referer HOST.
6
+ */
7
+ import type { EventActor, EventFields, EventSink } from "./sink.js";
8
+ export interface HtmlNavigation {
9
+ /** The route PATTERN recorded as the view's name β€” never the concrete path. */
10
+ route: string;
11
+ }
12
+ /**
13
+ * The view this request is, or null when it is not an HTML navigation. `routeOf` maps the path to
14
+ * a pattern (`/` β†’ `"/"`, `/docs/abc` β†’ `"/docs/:id"`); the default keeps `/` and collapses every
15
+ * other path to its first segment (`/sign-in/anything` β†’ `/sign-in`).
16
+ */
17
+ export declare function htmlNavigationOf(request: Request, status: number, routeOf?: (pathname: string) => string | null): HtmlNavigation | null;
18
+ /** Record the view an HTML navigation is, when it is one. Returns whether it was. */
19
+ export declare function recordHtmlView(events: EventSink, request: Request, status: number, fields: {
20
+ purpose: EventFields["purpose"];
21
+ actor?: EventActor | null;
22
+ public?: boolean;
23
+ tenant?: string;
24
+ }, routeOf?: (pathname: string) => string | null): boolean;
@@ -0,0 +1,41 @@
1
+ const NEVER_A_VIEW = /^\/(api\/|assets\/|healthz$|\.well-known\/|_)/;
2
+ /**
3
+ * The view this request is, or null when it is not an HTML navigation. `routeOf` maps the path to
4
+ * a pattern (`/` β†’ `"/"`, `/docs/abc` β†’ `"/docs/:id"`); the default keeps `/` and collapses every
5
+ * other path to its first segment (`/sign-in/anything` β†’ `/sign-in`).
6
+ */
7
+ export function htmlNavigationOf(request, status, routeOf = firstSegment) {
8
+ if (request.method !== "GET" || status !== 200)
9
+ return null;
10
+ if (!(request.headers.get("accept") ?? "").includes("text/html"))
11
+ return null;
12
+ const pathname = new URL(request.url).pathname;
13
+ if (NEVER_A_VIEW.test(pathname))
14
+ return null;
15
+ // A file (`/favicon.ico`, `/manifest.webmanifest`) is never a page.
16
+ if (pathname.slice(pathname.lastIndexOf("/") + 1).includes("."))
17
+ return null;
18
+ const route = routeOf(pathname);
19
+ return route ? { route } : null;
20
+ }
21
+ function firstSegment(pathname) {
22
+ const first = pathname.split("/").filter(Boolean)[0];
23
+ return first ? `/${first}` : "/";
24
+ }
25
+ /** Record the view an HTML navigation is, when it is one. Returns whether it was. */
26
+ export function recordHtmlView(events, request, status, fields, routeOf) {
27
+ const navigation = htmlNavigationOf(request, status, routeOf);
28
+ if (!navigation)
29
+ return false;
30
+ events.record(request, {
31
+ kind: "view",
32
+ name: navigation.route,
33
+ place: navigation.route,
34
+ purpose: fields.purpose,
35
+ actor: fields.actor ?? null,
36
+ public: fields.public ?? true,
37
+ ...(fields.tenant ? { tenant: fields.tenant } : {}),
38
+ status,
39
+ });
40
+ return true;
41
+ }
@@ -65,9 +65,17 @@ interface YtDlpCallOptions {
65
65
  }
66
66
  /**
67
67
  * Fetch one video. `target` is a YouTube video id, or a page URL (`https://…`) of any site yt-dlp
68
- * reads β€” Collections' pasted links (forge task 4003). `onProgress` gets the fraction received, 0–1.
68
+ * reads β€” Collections' pasted links (forge task 4003). `onProgress` gets the fraction received, 0–1,
69
+ * and what the same line said about the speed and the size.
69
70
  */
70
- export type YtDlpFetch = (target: string, onProgress?: (fraction: number) => void, options?: YtDlpCallOptions) => Promise<YtDownload>;
71
+ export type YtDlpFetch = (target: string, onProgress?: YtProgress, options?: YtDlpCallOptions) => Promise<YtDownload>;
72
+ /** How a download is going, beyond its fraction. A field yt-dlp does not know is absent. */
73
+ export interface YtProgressSample {
74
+ bytesPerSecond?: number;
75
+ /** The exact size, or yt-dlp's estimate of it when the stream has no `content-length`. */
76
+ totalBytes?: number;
77
+ }
78
+ export type YtProgress = (fraction: number, sample?: YtProgressSample) => void;
71
79
  /**
72
80
  * Why a download failed, sorted by what the owner can do about it.
73
81
  *
@@ -90,11 +98,13 @@ export declare const isFinalYtDlpFailure: (kind: YtDlpFailure) => boolean;
90
98
  /**
91
99
  * One progress line, as a fraction β€” or `null` for any other line.
92
100
  *
93
- * The template prints `downloaded total estimate`, and yt-dlp writes `NA` for a field it does
94
- * not know. The exact total wins; the estimate is what a stream without a `content-length`
101
+ * The template prints `downloaded total estimate speed`, and yt-dlp writes `NA` for a field it
102
+ * does not know. The exact total wins; the estimate is what a stream without a `content-length`
95
103
  * has. With neither there is no honest fraction, so none is claimed.
96
104
  */
97
105
  export declare function parseYtProgress(line: string): number | null;
106
+ /** The speed and size on a progress line {@link parseYtProgress} read. `NA` is an absent field. */
107
+ export declare function parseYtSample(line: string): YtProgressSample;
98
108
  /** The info JSON printed after the file is in place, or `null` for any other line. */
99
109
  export declare function parseYtInfo(line: string): YtInfo | null;
100
110
  /** Sort a failure by what can be done about it β€” see {@link YtDlpFailure}. `target` is what was fetched. */
@@ -89,8 +89,8 @@ export const isFinalYtDlpFailure = (kind) => kind === "unavailable" || kind ===
89
89
  /**
90
90
  * One progress line, as a fraction β€” or `null` for any other line.
91
91
  *
92
- * The template prints `downloaded total estimate`, and yt-dlp writes `NA` for a field it does
93
- * not know. The exact total wins; the estimate is what a stream without a `content-length`
92
+ * The template prints `downloaded total estimate speed`, and yt-dlp writes `NA` for a field it
93
+ * does not know. The exact total wins; the estimate is what a stream without a `content-length`
94
94
  * has. With neither there is no honest fraction, so none is claimed.
95
95
  */
96
96
  export function parseYtProgress(line) {
@@ -102,6 +102,13 @@ export function parseYtProgress(line) {
102
102
  return null;
103
103
  return Math.min(Math.max(downloaded / whole, 0), 1);
104
104
  }
105
+ /** The speed and size on a progress line {@link parseYtProgress} read. `NA` is an absent field. */
106
+ export function parseYtSample(line) {
107
+ const [, total, estimate, speed] = line.slice(PROGRESS_MARK.length).trim().split(/\s+/).map(Number);
108
+ const known = (n) => Number.isFinite(n) && n > 0;
109
+ const totalBytes = known(total) ? total : estimate;
110
+ return { ...(known(speed) ? { bytesPerSecond: speed } : {}), ...(known(totalBytes) ? { totalBytes } : {}) };
111
+ }
105
112
  /** The info JSON printed after the file is in place, or `null` for any other line. */
106
113
  export function parseYtInfo(line) {
107
114
  if (!line.startsWith(INFO_MARK))
@@ -188,7 +195,7 @@ export function ytDlpArgs(target, outDir, profile, options = {}) {
188
195
  // `--print` implies `--quiet`, which would swallow the progress lines β€” hence `--progress`.
189
196
  "--progress",
190
197
  "--progress-template",
191
- `download:${PROGRESS_MARK}%(progress.downloaded_bytes)s %(progress.total_bytes)s %(progress.total_bytes_estimate)s`,
198
+ `download:${PROGRESS_MARK}%(progress.downloaded_bytes)s %(progress.total_bytes)s %(progress.total_bytes_estimate)s %(progress.speed)s`,
192
199
  "--print",
193
200
  `after_move:${INFO_MARK}%()j`,
194
201
  "-o",
@@ -313,7 +320,7 @@ export function createYtDlp(options) {
313
320
  }), (line) => {
314
321
  const fraction = parseYtProgress(line);
315
322
  if (fraction !== null)
316
- onProgress?.(fraction);
323
+ onProgress?.(fraction, parseYtSample(line));
317
324
  info = parseYtInfo(line) ?? info;
318
325
  });
319
326
  const found = info;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.58.0",
3
+ "version": "4.60.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split β€” storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -150,6 +150,12 @@
150
150
  "source": "./src/server/engagement/d1.ts",
151
151
  "import": "./dist/server/engagement/d1.js"
152
152
  },
153
+ "./events": {
154
+ "types": "./dist/server/events/index.d.ts",
155
+ "bun": "./src/server/events/index.ts",
156
+ "source": "./src/server/events/index.ts",
157
+ "import": "./dist/server/events/index.js"
158
+ },
153
159
  "./errors": {
154
160
  "types": "./dist/server/errors.d.ts",
155
161
  "bun": "./src/server/errors.ts",
@@ -417,7 +423,7 @@
417
423
  "@node-rs/argon2": "^2.0.2",
418
424
  "@types/bun": "^1.3.14",
419
425
  "@types/node": "^24",
420
- "cursedbelt": "^5.102.0",
426
+ "cursedbelt": "^5.105.1",
421
427
  "hono": "4.12.28",
422
428
  "kysely": "^0.28.17",
423
429
  "kysely-bun-sqlite": "^0.4.0",
@@ -46,6 +46,8 @@ function burnCpu(ms: number): number {
46
46
  }
47
47
 
48
48
  const SLOW_MS = 30; // ~3Γ— the 9.9 ms budget β€” far outside measurement noise.
49
+ // A cheap route's ceiling, still a third of SLOW_MS: 5 was read at 4.6 on a busy machine (task 4214).
50
+ const CHEAP_BUDGET_MS = 10;
49
51
 
50
52
  function buildApp(config: CpuBudgetConfig, clock = processCpuClock()) {
51
53
  const recorder = createCpuRecorder({ clock, config });
@@ -59,7 +61,7 @@ function buildApp(config: CpuBudgetConfig, clock = processCpuClock()) {
59
61
 
60
62
  describe('direction 1 β€” a route under budget PASSES', () => {
61
63
  it('measures a cheap JSON route and asserts green', async () => {
62
- const { app, recorder } = buildApp({ routes: { 'GET /api/cheap': 5 } });
64
+ const { app, recorder } = buildApp({ routes: { 'GET /api/cheap': CHEAP_BUDGET_MS } });
63
65
  const report = await runCpuBench({
64
66
  app,
65
67
  recorder,
@@ -71,7 +73,7 @@ describe('direction 1 β€” a route under budget PASSES', () => {
71
73
  const row = report.routes[0];
72
74
  expect(row.key).toBe('GET /api/cheap');
73
75
  expect(row.samples).toBe(25);
74
- expect(row.p99).toBeLessThan(5);
76
+ expect(row.p99).toBeLessThan(CHEAP_BUDGET_MS);
75
77
  // Does not throw β€” that IS the assertion under test.
76
78
  expect(assertCpuBudgets(report)).toEqual([]);
77
79
  });
@@ -113,7 +115,7 @@ describe('direction 2 β€” a route over budget FAILS, and names itself', () => {
113
115
  });
114
116
 
115
117
  it('attributes cost to the RIGHT route when a cheap and an expensive one share an app', async () => {
116
- const { app, recorder } = buildApp({ routes: { 'GET /api/cheap': 5, 'GET /api/slow': 5 } });
118
+ const { app, recorder } = buildApp({ routes: { 'GET /api/cheap': CHEAP_BUDGET_MS, 'GET /api/slow': 5 } });
117
119
  const report = await runCpuBench({
118
120
  app,
119
121
  recorder,
@@ -124,7 +126,7 @@ describe('direction 2 β€” a route over budget FAILS, and names itself', () => {
124
126
 
125
127
  const cheap = report.routes.find((r) => r.route === '/api/cheap');
126
128
  const slow = report.routes.find((r) => r.route === '/api/slow');
127
- expect(cheap?.p99).toBeLessThan(5);
129
+ expect(cheap?.p99).toBeLessThan(CHEAP_BUDGET_MS);
128
130
  expect(slow?.p99).toBeGreaterThan(SLOW_MS * 0.5);
129
131
 
130
132
  const violations = checkCpuBudgets(report);
@@ -379,7 +381,9 @@ describe('a destructive case β€” the fixture rebuild between iterations', () =>
379
381
 
380
382
  const row = report.routes[0];
381
383
  expect(row.max).toBeGreaterThan(POPULATED_MS * 0.5); // the route really does cost this
382
- expect(row.p99).toBeLessThan(2); // …and the number the budget is read off says it does not
384
+ // …and the number the budget is read off says it does not. The WITH-hook test below holds the
385
+ // same line from above; an absolute 2ms read 2.9 on a busy machine and red a publish (task 4214).
386
+ expect(row.p99).toBeLessThan(POPULATED_MS * 0.5);
383
387
  expect(assertCpuBudgets(report)).toEqual([]); // green, and meaningless. That is the bug.
384
388
  });
385
389
 
@@ -445,7 +449,7 @@ describe('a destructive case β€” the fixture rebuild between iterations', () =>
445
449
  expect(d.purged).toHaveLength(21);
446
450
  const cheap = report.routes.find((r) => r.route === '/api/cheap');
447
451
  const purge = report.routes.find((r) => r.route === '/api/purge');
448
- expect(cheap?.p99).toBeLessThan(2);
452
+ expect(cheap?.p99).toBeLessThan(POPULATED_MS * 0.5);
449
453
  expect(purge?.p99).toBeGreaterThan(POPULATED_MS * 0.5);
450
454
  });
451
455
 
@@ -457,7 +461,7 @@ describe('a destructive case β€” the fixture rebuild between iterations', () =>
457
461
  * feature a worse lie than the hole it closes.
458
462
  */
459
463
  it("πŸ”΄ does NOT record the hook's own CPU, however expensive the rebuild is", async () => {
460
- const { app, recorder } = buildApp({ routes: { 'GET /api/cheap': 5 } });
464
+ const { app, recorder } = buildApp({ routes: { 'GET /api/cheap': CHEAP_BUDGET_MS } });
461
465
  let rebuilds = 0;
462
466
  const report = await runCpuBench({
463
467
  app,
@@ -480,7 +484,7 @@ describe('a destructive case β€” the fixture rebuild between iterations', () =>
480
484
  expect(row.samples).toBe(20);
481
485
  // …and none of it is in these numbers. Even the MAX stays far under one rebuild.
482
486
  expect(row.max).toBeLessThan(SLOW_MS / 3);
483
- expect(row.p99).toBeLessThan(5);
487
+ expect(row.p99).toBeLessThan(CHEAP_BUDGET_MS);
484
488
  expect(assertCpuBudgets(report)).toEqual([]);
485
489
  });
486
490
 
@@ -36,6 +36,7 @@
36
36
  import { Hono } from "hono";
37
37
  import type { Context } from "hono";
38
38
  import { actionDoor } from "./actions.js";
39
+ import { type EngagementEvents, recordEngagementActions, recordEngagementView } from "./events.js";
39
40
  import { type ActionRef, OTHER_PLACE, type PlaceRef, resolvePlace } from "./policy.js";
40
41
  import type { EngagementStore } from "./store.js";
41
42
  import { type AppEngagement, returnCurve, summarize } from "./summary.js";
@@ -58,6 +59,11 @@ export interface EngagementApiOptions {
58
59
  actions?: readonly ActionRef[];
59
60
  /** Resolve the CURRENT request's account. Null β†’ 401, nothing recorded. */
60
61
  resolveUser: (c: Context) => string | null;
62
+ /**
63
+ * The app's `EVENTS` sink (`cursedbelt-server/events`): present, every accepted view and action
64
+ * is also a user-event point (`./events.ts`). Absent, nothing changes.
65
+ */
66
+ events?: EngagementEvents;
61
67
  /** Injectable clock, so the tests are not timing-dependent. */
62
68
  now?: () => number;
63
69
  }
@@ -85,6 +91,7 @@ export function createEngagementRecorder(options: EngagementApiOptions): Hono {
85
91
  const place = resolvePlace(claimed, options.places);
86
92
 
87
93
  const fold = options.store.recordView({ userKey, place, ts: now() });
94
+ recordEngagementView(options.events, c, userKey, place);
88
95
  // Echo the RESOLVED place, not the claimed one. A client that sent
89
96
  // something off-manifest learns that it was bucketed, which is how a
90
97
  // missing manifest entry gets noticed instead of quietly reading as an
@@ -106,6 +113,7 @@ export function createEngagementRecorder(options: EngagementApiOptions): Hono {
106
113
  const door = actionDoor(body, { userKey, now: now(), places: options.places, actions });
107
114
  if ("error" in door) return c.json({ error: door.error }, 400);
108
115
  options.store.recordActions(door.uses);
116
+ recordEngagementActions(options.events, c, userKey, door.uses);
109
117
  return c.json(door.reply);
110
118
  });
111
119
  }