diff --git a/.github/workflows/check-metrics.yml b/.github/workflows/check-metrics.yml new file mode 100644 index 0000000..75f26fb --- /dev/null +++ b/.github/workflows/check-metrics.yml @@ -0,0 +1,42 @@ +name: Check metrics plugin + +on: + pull_request: + paths: + - metrics/** + - indexer/** + - package.json + - pnpm-lock.yaml + - .github/workflows/check-metrics.yml + push: + branches: [main] + paths: + - metrics/** + - indexer/** + - package.json + - pnpm-lock.yaml + - .github/workflows/check-metrics.yml + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + - run: corepack enable + - run: pnpm install --frozen-lockfile + - run: pnpm test + - run: pnpm validate fixtures/index.json + - run: pnpm -C metrics install --frozen-lockfile + - run: pnpm -C metrics check + - name: Verify the committed runtime is reproducible + run: git diff --exit-code -- metrics/plugin.js + - run: pnpm run check-plugin metrics diff --git a/README.md b/README.md index 7166f60..2faf828 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ https://raw.githubusercontent.com/block/buzz-plugins/index/index.json | [`.github/`](./.github) | The workflows that publish the index and check new sources, and the list-a-plugin issue form | | [`marketplace/`](./marketplace) | The Community Marketplace Buzz plugin that browses the index | | [`template/`](./template) | A starter plugin for authors | +| [`metrics/`](./metrics) | Default-off metrics example with redacted local inspection; not listed or published automatically | | [`PUBLISHING.md`](./PUBLISHING.md) | The checklist for getting a plugin listed, and the local check to run first | | [`SPEC.md`](./SPEC.md) | The contract: listing keys, publicity check, audit, `index.json`, publishing | | [`VERIFICATION.md`](./VERIFICATION.md) | How a listing becomes Verified by Buzz, and how that is withdrawn | diff --git a/SPEC.md b/SPEC.md index d62f477..6a9b522 100644 --- a/SPEC.md +++ b/SPEC.md @@ -17,6 +17,7 @@ indexer/ crawl, publicity check, audit, listing metadata, build ind .github/ publish and check workflows, and the list-a-plugin issue form marketplace/ the Community Marketplace Buzz plugin template/ a minimal plugin for authors to copy +metrics/ a default-off metrics example; separate draft, no automatic listing ``` ## Listing key diff --git a/metrics/.gitignore b/metrics/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/metrics/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/metrics/README.md b/metrics/README.md new file mode 100644 index 0000000..5895fec --- /dev/null +++ b/metrics/README.md @@ -0,0 +1,81 @@ +# Buzz Metrics — preview + +An opt-in example plugin consuming Buzz's optional `ctx.telemetry` service. This is a draft for API/design feedback, not production analytics. It is separate from developer diagnostics and never uploads metrics records to a community relay automatically. While enabled, observed allowlisted searches carry the host's ephemeral query join fields; separately enabled Linked tracing adds `traceparent` to allowed relay requests. + +## Consent and local inspection + +1. Install the built folder, then open **Settings → Privacy → Metrics** or **Metrics preview**. +2. Enter exact HTTPS community origins separated by commas. Leave personal communities out. An unknown, malformed or non-allowlisted community is never recorded or traced. +3. Choose a level and **Apply settings and clear pending data**. Collection is still off. +4. Explicitly enable collection. Tracing and export are separate opt-ins. Closing the page does not disable enabled collection. +5. Turn collection off, disable/reload the plugin, or choose **Clear pending data** to discard pending records and private search state. Reload resets every setting and consent to off. Already exported data cannot be recalled. + +Granularity buttons and consent switches apply immediately and clear pending data. Community/backend text fields use **Apply settings**. Invalid settings stop collection and reset the confirmed configuration instead of leaving an old allowlist or export target running behind an error. + +The search subscription itself is admitted only while the host exposes a ready origin:viewer snapshot for a selected allowlisted community. It detaches and clears private search state when that scope changes or becomes unknown. A host without that capability keeps search collection off; this is subscription admission, never attribution of a completed UI timing. Other plugins can independently enable host observers outside this plugin's control. + +The preview displays only the exact redacted records eligible for export. No settings, consent, metrics or raw query state is written to disk by this plugin. The consumer must trust installed plugins; same-process plugins are not sandboxed. + +### Granularity + +- **Off** by default: no telemetry subscriptions, trace provider or plugin timers. +- **Level 1 — Counts:** aggregate request counts and one search-session summary on close. Request categories combine the allowlisted communities and omit community identifiers too. No IDs, timings, query order or per-query/click records. An unused dialog produces no record. +- **Level 2 — Linked:** request timings and bytes, ephemeral session/query/attempt joins, query shape/relation, and result activation metadata. Opened message event IDs and positions may let a backend link to content it can access. Raw query text, result labels, filter values and message content are never records. +- **Level 3** query-text export is deliberately unavailable. + +Counts omits IDs from plugin records. The current host still adds its own ephemeral `query_id`/`attempt` to observed searches, including Counts, while this plugin's search subscription is active in an allowlisted community. Those join fields are not a trace-context provider and do not enter Counts export records. + +Navigation-only sessions (at least one non-message open and no message open) are retained with `navigation_session: true`, including their group/bucket opens and Linked `below_messages`. The local queued-message open-rate and session-success preview explicitly exclude those sessions. Until a host supplies explicit dispatch evidence, current-host rates cover only queries positively established by relay-ranked results: unproven empty/failed searches are omitted. These are incomplete-coverage diagnostics, not overall search-quality rates. A backend must apply the same exclusion. Rates describe only session summaries currently in the bounded local queue, not lifetime totals. + +## Search aggregation and redaction + +Raw host events are projected through explicit allowlists; no raw payload is spread into a record. Counts discards query content after classification. In Linked mode, query content and filter signatures exist only in private bounded in-memory state for classification. They expire after 30 seconds, and all private state is cleared on scope/privacy/settings changes or disposal. Result labels and message content are never retained. + +A proven eligible query has text and evidence that it sent a message search. Finished/failed results must remain shown for 2 seconds, or be acted on, to settle. Queries replaced/closed first are marked superseded/unsettled. Filter-only queries are not eligible. Settled eligible/empty/failed/opened counts are summarized at dialog close. Linked records preserve the host's `query_id` and `attempt` and add a local sequence. + +The optional session `queries` count and Linked `seq` track logical host query IDs. A higher `attempt` on the current query ID is a retry/re-evaluation, not another query: it keeps seq, relation, eligibility and opened evidence, updates the latest attempt, and restarts unfinished-result waiting. It cannot add another eligible denominator or a phantom superseded query. Only settled dispatch-proven `eligible` fields belong in message search rates. Relations are computed on device against the previous dispatch-proven query within a 30-second issuance gap, including across dialog openings: same, refilter, extends, shortens, edits (shared word), or new. Only shape (counts, flags and operator names) leaves that classifier; never tokens or filter values. + +### Draft host-contract gaps + +The preview expects the passive requests/ui/search contracts from the telemetry-service prototype, and safely tolerates missing services/topics: + +- Current `uiTiming` events lack a community. They are dropped, not attributed to the currently selected community. A host should add an authoritative `community` field. +- Current `queryIssued` fires before an actual message request and lacks explicit dispatch evidence. The plugin accepts an optional boolean `messageSearch: true`; otherwise relay-ranked result rows establish dispatch. Empty/failed searches without that evidence are **not counted eligible**, rather than invented as empty/failed searches. The host should expose dispatch explicitly. +- Session summaries preserve a bounded `reason`, including `subscribers_changed`, so backends can identify observer-cohort fragments rather than assume every summary is a complete dialog. Reconnects or unknown selected scope detach search and discard the open session conservatively. +- Group projection uses known English display labels and falls back to `other`; a stable host group ID is a follow-up for localization/custom groups. +- Host activation `kind` is a destination kind, not open/action. Known message/channel/person/agent/chat/page/plugin destinations map to open; explicit action/other map to action. Current host Search actions that emit no activation cannot be counted. Unknown group labels become `other`, never free-form strings. +- This draft reports `app_version: "unknown"` because the current contract does not expose it. +- Request 4xx other than 429 follow the host's current network outcome classification. Browser operational WS/live-phase and native media coverage remain host work; the plugin cannot manufacture missing events. +- Trace and query IDs are transport joins only. Relay recording/extraction and a production deployment test remain separate work; they are not established by this plugin. + +## Bounded buffers, export and teardown + +The record/count queue holds at most 200 records, dropping oldest on overflow; one in-flight batch holds at most 25 additional records. At most 8 search sessions are active and each retains at most 64 already-redacted Linked records until close so its navigation flag can be determined. Session overflow is marked `truncated`. Private current/previous query strings are bounded to 4096 characters and 30 seconds. No replay or retry queue is persisted. + +Export sends one at-most-once JSON batch every 10 seconds (or **Send one batch**) only after separate export consent. Errors drop that batch without retrying, logging response bodies, or displaying arbitrary error text. The ring is shared: heavy request traffic can evict pending search records; delivery is not reliable and per-type quotas remain a design question. Turning off or reconfiguring invalidates in-flight completion and protected-request eligibility, removes all listeners/providers, and cancels all plugin clocks. A request already delivered to a backend cannot be undone. + +### Local-only default / pluggable backend + +`manifest.json` deliberately declares an empty `host.networkOrigins`. The default build cannot export. A distributor can add its chosen backend's exact HTTPS origin, rebuild, and install/review that changed manifest. For example, a backend at an operator-owned origin would receive: + +```json +{ "schema": 1, "records": [] } +``` + +The Settings endpoint may be any path at a declared origin, but cannot contain credentials, query parameters or a fragment. Transport uses only `ctx.host.requestOnce` with a 10-second native deadline and a live eligibility callback; there is no direct-fetch or older-request fallback. An old host without that protected API remains local-only. Export authentication is not implemented in the example adapter; a distributor can provide another `MetricsBackend` implementation using its permitted host capabilities and appropriate secret handling. Do not put credentials in the endpoint URL. + +Tracing is Linked-only, separately enabled, and generates valid random W3C version-00 IDs only for exact allowlisted relay origins. Flags are `00` (no sampling request). Only context generated by this plugin can enter its request records. Opt-out/disposal unregisters the provider immediately. W3C mode is implemented; a separately configured correlation-ID mode is deferred. + +## Development / listing + +Requires Node 24 and pnpm, following the repository template. The pinned preview author types remain vendored; newer optional services are structurally feature-detected rather than forced into `inject`. + +```sh +pnpm install --frozen-lockfile +pnpm -C metrics install --frozen-lockfile +pnpm -C metrics check +pnpm test +pnpm run check-plugin metrics +``` + +`check` type-checks, builds one self-contained `plugin.js`, and tests logic, Settings interactions with real Cordis lifetime ownership, protected export, privacy bounds, and the indexer's manifest/listing/audit rules. `plugin.js` must be tracked next to the manifest. The local listing CLI correctly fails while built files are uncommitted or commits are unpushed; rerun it after the authorized local commit/push. No `sources.txt` entry or automatic listing/publishing is added by this draft. diff --git a/metrics/buzz-listing.yaml b/metrics/buzz-listing.yaml new file mode 100644 index 0000000..fb1ddd6 --- /dev/null +++ b/metrics/buzz-listing.yaml @@ -0,0 +1,20 @@ +tagline: Opt-in metrics with local redaction and an explicit community allowlist +description: | + Collection starts off and resets on plugin reload. Inspect bounded, redacted + records on this device. Raw search query text stays only in short-lived memory + for settle/relation classification and is never placed in the record queue, + preview, or export. Linked mode preserves ephemeral query join fields. + + The default build declares no network origins and is local-only. A distributor + can declare its metrics backend origin and rebuild; export uses only Buzz's + protected host request API. Metrics records are not uploaded to a community + relay automatically. While enabled, allowlisted searches carry the host's + ephemeral query join fields; optional Linked tracing adds trace context to + allowed relay requests. +category: developer-tools-and-integrations +tags: [metrics, privacy, search] +setup: + - title: Choose communities and granularity + detail: Open Settings → Privacy → Metrics, enter exact community origins, and choose Counts or Linked. + - title: Opt in explicitly + detail: Enable collection for this plugin activation. Export and tracing are separate opt-ins. diff --git a/metrics/manifest.json b/metrics/manifest.json new file mode 100644 index 0000000..14477ac --- /dev/null +++ b/metrics/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "xyz.block.metrics", + "name": "Buzz Metrics", + "apiVersion": 1, + "description": "Default-off, community-scoped metrics with redacted local inspection and optional export.", + "host": { "networkOrigins": [] }, + "discovery": { + "category": "developer-tools-and-integrations", + "tags": ["Metrics", "Privacy", "Search"] + } +} diff --git a/metrics/package.json b/metrics/package.json new file mode 100644 index 0000000..4ffd818 --- /dev/null +++ b/metrics/package.json @@ -0,0 +1,28 @@ +{ + "name": "xyz.block.metrics", + "private": true, + "type": "module", + "packageManager": "pnpm@11.8.0", + "engines": { + "node": "24.x" + }, + "scripts": { + "build": "tsc && vite build", + "test": "vite build && vitest run", + "check": "tsc && vite build && vitest run" + }, + "devDependencies": { + "@buzz/author": "file:vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz", + "@deepseek-ai/cordis": "4.0.2", + "@testing-library/react": "16.3.3", + "@types/node": "24.13.6", + "@types/react": "19.2.18", + "@types/react-dom": "19.2.7", + "jsdom": "30.0.1", + "react": "19.2.8", + "react-dom": "19.2.8", + "typescript": "7.0.2", + "vite": "8.2.2", + "vitest": "4.1.11" + } +} diff --git a/metrics/plugin.js b/metrics/plugin.js new file mode 100644 index 0000000..20e238c --- /dev/null +++ b/metrics/plugin.js @@ -0,0 +1,1106 @@ +var manifest_default = { + id: "xyz.block.metrics", + name: "Buzz Metrics", + apiVersion: 1, + description: "Default-off, community-scoped metrics with redacted local inspection and optional export.", + host: { "networkOrigins": [] }, + discovery: { + "category": "developer-tools-and-integrations", + "tags": [ + "Metrics", + "Privacy", + "Search" + ] + } +}; +// src/contract.ts +/** Old author types intentionally remain pinned: optional new services are +* discovered structurally, never required in inject on older hosts. */ +function capability(ctx, name) { + try { + return ctx.reflect.get(name); + } catch { + return; + } +} +function telemetryCapability(value) { + if (!value || typeof value !== "object" || typeof value.subscribe !== "function") return; + return value; +} +function protectedHostCapability(value) { + if (!value || typeof value !== "object" || typeof value.requestOnce !== "function") return; + return value; +} +function object(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : void 0; +} +function oneOf(value, values) { + return typeof value === "string" && values.includes(value) ? value : void 0; +} +function count(value, max = 1e9) { + return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max ? Math.round(value) : void 0; +} +function community(value) { + if (typeof value !== "string" || value.length > 256) return; + try { + const url = new URL(value.replace(/^wss:/, "https:")); + if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !["", "/"].includes(url.pathname)) return; + return url.origin; + } catch { + return; + } +} +// src/config.ts +var DEFAULTS = Object.freeze({ + enabled: false, + level: 1, + communities: Object.freeze([]), + tracing: false, + exportEnabled: false, + endpoint: "" +}); +function endpoint(value, origins) { + if (!value || value.length > 2048) return; + try { + const url = new URL(value); + if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !origins.includes(url.origin)) return; + return url.href; + } catch { + return; + } +} +function settings(input, declaredOrigins) { + if (input.level !== 1 && input.level !== 2) return; + if (!Array.isArray(input.communities) || input.communities.length > 16) return; + const allowed = []; + for (const raw of input.communities) { + const origin = community(raw); + if (!origin) return; + if (!allowed.includes(origin)) allowed.push(origin); + } + if (input.enabled && !allowed.length) return; + if (typeof input.endpoint !== "string") return; + const target = input.endpoint ? endpoint(input.endpoint, declaredOrigins) : ""; + if (input.endpoint && !target) return; + if (input.exportEnabled && !target) return; + return Object.freeze({ + enabled: input.enabled === true, + level: input.level, + communities: Object.freeze(allowed), + tracing: input.tracing === true && input.level === 2, + exportEnabled: input.exportEnabled === true, + endpoint: target ?? "" + }); +} +// src/records.ts +var OPERATORS = [ + "from", + "in", + "after", + "before", + "on", + "during" +]; +function messageMetrics(records) { + let eligible = 0, opened = 0, sessions = 0, successful = 0; + for (const record of records) { + if (record.type !== "search_session" || record.navigation_session || record.eligible === 0) continue; + eligible += record.eligible; + opened += record.eligible_opened; + sessions++; + if (record.eligible_opened > 0) successful++; + } + return Object.freeze({ + eligible, + opened, + sessions, + successful, + open_rate: eligible ? opened / eligible : null, + session_success: sessions ? successful / sessions : null + }); +} +function uuid(value) { + return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : void 0; +} +function eventId(value) { + return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) ? value : void 0; +} +function positive(value, max = 1e4) { + const n = count(value, max); + return n !== void 0 && n >= 1 && n === value ? n : void 0; +} +function group(value) { + switch (value) { + case "Messages": return "messages"; + case "Channels": return "channels"; + case "People": return "people"; + case "Agents": return "agents"; + case "Chats": return "chats"; + case "Direct messages": return "direct_messages"; + case "Pages": return "pages"; + case "Recents": return "recents"; + case "Unread": return "unread"; + case "Settings": return "settings"; + case "Plugins": return "plugins"; + default: return "other"; + } +} +function bucket(position) { + return position <= 3 ? String(position) : position <= 5 ? "4-5" : position <= 10 ? "6-10" : "11+"; +} +function freeze(record) { + return Object.freeze(record); +} +/** No raw payload object or arbitrary string is ever copied to a record. */ +function projectRequest(raw, allowed, appVersion, ownedTrace) { + const value = object(raw); + if (value?.version !== 1 || value.type !== "request") return; + const origin = community(value.community); + if (!origin || !allowed.has(origin)) return; + const operation = oneOf(value.operation, [ + "query", + "search", + "publish", + "auth", + "media", + "other" + ]); + const priority = oneOf(value.priority, ["foreground", "background"]); + const outcome = oneOf(value.outcome, [ + "ok", + "timeout", + "rate_limited", + "http_5xx", + "aborted", + "network" + ]); + const duration = count(value.durationMs, 36e5), bytes = count(value.bytes); + if (!operation || !priority || !outcome || duration === void 0 || bytes === void 0) return; + return freeze({ + schema: 1, + type: "request", + level: 2, + app_version: appVersion, + community: origin, + operation, + priority, + duration_ms: duration, + bytes, + outcome, + ...ownedTrace ? { traceparent: ownedTrace } : {} + }); +} +function projectUi(raw, allowed, appVersion) { + const value = object(raw); + if (value?.version !== 1 || value.type !== "uiTiming") return; + const origin = community(value.community); + if (!origin || !allowed.has(origin) || value.operation !== "channel_open_to_visible_rows") return; + const trigger = oneOf(value.trigger, ["click", "keyboard"]); + const outcome = oneOf(value.outcome, [ + "ok", + "empty", + "error" + ]); + const duration = count(value.durationMs, 36e5); + if (!trigger || !outcome || duration === void 0) return; + return freeze({ + schema: 1, + type: "ui", + level: 2, + app_version: appVersion, + community: origin, + operation: "channel_open_to_visible_rows", + trigger, + outcome, + duration_ms: duration + }); +} +/** Only short-lived aggregation state may hold body/signature. Shape is safe. */ +function queryParts(text, rawFilters) { + const filters = object(rawFilters) ?? {}; + const values = [ + "from", + "in", + "since", + "until", + "channelId" + ].map((key) => { + const value = filters[key]; + return typeof value === "string" ? value.slice(0, 256) : typeof value === "number" && Number.isFinite(value) ? value : null; + }); + const names = /* @__PURE__ */ new Set(); + const body = text.replace(/(?:^|\s)(from|in|after|before|on|during):(?:"[^"\n]*"|\S+)/gi, (whole, name) => { + const operator = name.toLowerCase(); + if (!(operator === "from" ? values[0] !== null : operator === "in" ? values[1] !== null : operator === "after" ? values[2] !== null : values[3] !== null)) return whole; + names.add(operator); + return " "; + }).trim().replace(/\s+/g, " ").toLowerCase(); + const words = body.match(/[\p{L}\p{N}_-]+/gu) ?? []; + return { + body, + signature: JSON.stringify(values), + shape: Object.freeze({ + char_count: body.length, + word_count: words.length, + quoted: /"/.test(body), + has_url: /https?:\/\/|www\./i.test(body), + operators: Object.freeze(OPERATORS.filter((name) => names.has(name))) + }) + }; +} +function relation(previous, current) { + if (!previous) return "new"; + if (previous.body === current.body) return previous.signature === current.signature ? "same" : "refilter"; + if (previous.body && current.body.startsWith(previous.body)) return "extends"; + if (current.body && previous.body.startsWith(current.body)) return "shortens"; + const old = new Set(previous.body.match(/[\p{L}\p{N}_-]+/gu) ?? []); + return (current.body.match(/[\p{L}\p{N}_-]+/gu) ?? []).some((word) => old.has(word)) ? "edits" : "new"; +} +// src/search.ts +var SETTLE_MS = 2e3; +var RELATION_MS = 3e4; +var clock = { + now: () => performance.now(), + set: (run, ms) => setTimeout(run, ms), + clear: (timer) => clearTimeout(timer) +}; +/** Raw text exists ONLY in private current/previous query state, never records. +* Sessions wait until close so navigation-only sessions can be marked before +* their summary is exported; consumers exclude that flag from message rates. */ +function createSearchAggregator(options) { + const time = options.clock ?? clock; + const sessions = /* @__PURE__ */ new Map(); + const previous = /* @__PURE__ */ new Map(); + let disposed = false; + const clearQuery = (query) => { + if (query?.timer !== void 0) time.clear(query.timer); + if (query) query.timer = void 0; + }; + const clearSession = (session) => { + clearQuery(session.query); + if (session.query?.rawTimer !== void 0) time.clear(session.query.rawTimer); + if (session.query) { + session.query.body = ""; + session.query.signature = ""; + } + session.query = void 0; + session.records.length = 0; + session.opens.clear(); + }; + const add = (session, record) => { + if (session.records.length >= 64) { + session.truncated = true; + options.dropped(); + return; + } + session.records.push(record); + }; + const settle = (session, query) => { + if (disposed || sessions.get(session.id) !== session || session.query !== query || !query.eligible || !query.finished) return; + clearQuery(query); + query.settled = true; + }; + const endQuery = (session, replaced) => { + const query = session.query; + if (!query) return; + clearQuery(query); + if (query.rawTimer !== void 0) time.clear(query.rawTimer); + query.rawTimer = void 0; + const outcome = query.settled ? query.status : replaced ? "superseded" : "unsettled"; + if (query.eligible) { + if (query.settled) { + session.eligible++; + if (outcome === "empty") session.empty++; + if (outcome === "failed") session.failed++; + if (query.opened) session.opened++; + } else if (replaced) session.superseded++; + else session.unsettled++; + if (options.level === 2) { + const record = freeze({ + schema: 1, + type: "search_query", + level: 2, + app_version: options.appVersion, + session_id: session.id, + seq: query.seq, + query_id: query.id, + attempt: query.attempt, + scope: query.scope, + outcome, + relation: query.relation, + since_previous: query.since, + previous_query_id: query.previous, + char_count: query.shape.char_count, + word_count: query.shape.word_count, + quoted: query.shape.quoted, + has_url: query.shape.has_url, + operators: query.shape.operators + }); + add(session, record); + const old = previous.get(session.community); + if (old) { + time.clear(old.timer); + previous.delete(session.community); + } + const remaining = RELATION_MS - (time.now() - query.at); + if (remaining > 0) { + const origin = session.community; + const entry = { + body: query.body, + signature: query.signature, + id: query.id, + at: query.at, + timer: time.set(() => { + if (previous.get(origin) === entry) previous.delete(origin); + }, remaining) + }; + previous.set(origin, entry); + } + } + } + query.body = ""; + query.signature = ""; + session.query = void 0; + }; + const endSession = (session, reason) => { + endQuery(session, false); + sessions.delete(session.id); + if (!session.sawText && (options.level === 1 || !(session.otherOpens || session.messageOpens || session.actions))) { + clearSession(session); + return; + } + const navigation = session.otherOpens > 0 && session.messageOpens === 0; + const opens = Object.freeze([...session.opens.values()].sort((a, b) => a.group.localeCompare(b.group) || a.position.localeCompare(b.position))); + const summary = freeze({ + schema: 1, + type: "search_session", + level: options.level, + app_version: options.appVersion, + ...options.level === 2 ? { + session_id: session.id, + event_count: session.records.length + 1, + truncated: session.truncated + } : {}, + eligible: session.eligible, + eligible_empty: session.empty, + eligible_failed: session.failed, + eligible_opened: session.opened, + navigation_session: navigation, + reason, + opens, + queries: session.queries, + superseded: session.superseded, + unsettled: session.unsettled, + actions: session.actions + }); + options.emit(Object.freeze([...session.records, summary])); + clearSession(session); + }; + const matchingQuery = (session, value) => { + const query = session.query; + return query && query.id === value.queryId && query.attempt === value.attempt ? query : void 0; + }; + return { + receive(raw) { + if (disposed) return; + const value = object(raw); + if (value?.version !== 1) return; + const sessionId = uuid(value.sessionId); + if (!sessionId) return; + if (value.type === "sessionStart") { + const old = sessions.get(sessionId); + if (old) { + clearSession(old); + sessions.delete(sessionId); + } + const origin = community(value.community), scope = oneOf(value.scope, ["global", "conversation"]); + if (!origin || !scope || !options.allowed.has(origin)) return; + if (sessions.size >= 8) { + const first = sessions.values().next().value; + if (first) { + clearSession(first); + sessions.delete(first.id); + options.dropped(); + } + } + sessions.set(sessionId, { + id: sessionId, + community: origin, + scope, + records: [], + opens: /* @__PURE__ */ new Map(), + messageOpens: 0, + otherOpens: 0, + actions: 0, + queries: 0, + eligible: 0, + empty: 0, + failed: 0, + opened: 0, + superseded: 0, + unsettled: 0, + sawText: false, + truncated: false + }); + return; + } + const session = sessions.get(sessionId); + if (!session) return; + if (value.type === "queryIssued") { + const origin = community(value.community), scope = oneOf(value.scope, ["global", "conversation"]); + const queryId = uuid(value.queryId), attempt = positive(value.attempt); + if (origin !== session.community || !scope || !queryId || !attempt || typeof value.queryText !== "string" || value.queryText.length > 4096) { + clearSession(session); + sessions.delete(sessionId); + options.dropped(); + return; + } + const active = session.query; + if (active?.id === queryId) { + if (attempt <= active.attempt || scope !== active.scope) return; + clearQuery(active); + active.attempt = attempt; + active.finished = false; + active.eligible ||= active.hasText && value.messageSearch === true; + return; + } + endQuery(session, true); + const parts = queryParts(value.queryText, value.filters); + const now = time.now(), last = previous.get(origin); + const related = last && now - last.at <= 3e4 ? last : void 0; + session.queries = Math.min(1e6, session.queries + 1); + session.sawText ||= !!value.queryText.trim(); + session.query = { + id: queryId, + attempt, + seq: session.queries, + scope, + body: options.level === 2 ? parts.body : "", + signature: options.level === 2 ? parts.signature : "", + hasText: !!parts.body, + shape: parts.shape, + at: now, + eligible: !!parts.body && value.messageSearch === true, + finished: false, + settled: false, + opened: false, + status: "empty", + relation: relation(related, parts), + since: related ? Math.max(0, Math.round(now - related.at)) : null, + previous: related?.id ?? null + }; + const current = session.query; + if (options.level === 2) current.rawTimer = time.set(() => { + current.body = ""; + current.signature = ""; + current.rawTimer = void 0; + }, RELATION_MS); + return; + } + if (value.type === "sessionEnd") { + endSession(session, oneOf(value.reason, [ + "closed", + "scope_changed", + "disposed", + "subscribers_changed" + ]) ?? "other"); + return; + } + const query = matchingQuery(session, value); + if (!query) return; + if (value.type === "resultsUpdated") { + const outcome = oneOf(value.outcome, [ + "loading", + "ok", + "error", + "offline" + ]); + if (!outcome || !Array.isArray(value.groups) || value.groups.length > 32) return; + let messages = false, relay = false; + for (const rawGroup of value.groups) { + const entry = object(rawGroup); + if (!Array.isArray(entry?.results) || entry.results.length > 1e3) continue; + for (const rawRow of entry.results) { + const row = object(rawRow); + if (row?.kind !== "message" || !eventId(row.eventId)) continue; + messages = true; + if ((row.source === "relay" || row.source === "device") && positive(row.relayRank)) relay = true; + } + } + query.eligible ||= query.hasText && relay; + if (outcome === "ok" || outcome === "error") { + query.finished = true; + query.status = outcome === "error" ? "failed" : messages ? "results" : "empty"; + if (query.eligible && !query.settled) { + clearQuery(query); + query.timer = time.set(() => settle(session, query), SETTLE_MS); + } + } else if (!query.settled) { + query.finished = false; + clearQuery(query); + } + return; + } + if (value.type === "resultActivated") { + const kind = oneOf(value.kind, [ + "message", + "channel", + "person", + "agent", + "chat", + "page", + "plugin", + "action", + "other" + ]); + const position = positive(value.position); + if (!kind || !position) return; + const message = kind === "message", action = kind === "action" || kind === "other"; + const openedId = message ? eventId(value.eventId) : void 0; + if (message && !openedId) return; + if (!message && typeof value.belowMessages !== "boolean") return; + const mapped = group(value.group), rank = positive(value.relayRank), source = oneOf(value.source, [ + "relay", + "device", + "local", + "unknown" + ]); + if (action) session.actions++; + else { + if (message) { + session.messageOpens++; + query.opened = true; + query.finished = true; + query.status = "results"; + query.eligible ||= query.hasText && !!rank && (source === "relay" || source === "device"); + } else session.otherOpens++; + const key = `${mapped}/${bucket(position)}`, old = session.opens.get(key); + session.opens.set(key, Object.freeze({ + group: mapped, + position: bucket(position), + count: Math.min(1e6, (old?.count ?? 0) + 1) + })); + } + settle(session, query); + if (options.level === 2) { + const click = freeze({ + schema: 1, + type: "search_click", + level: 2, + app_version: options.appVersion, + session_id: session.id, + seq: query.seq, + query_id: query.id, + attempt: query.attempt, + kind: action ? "action" : "open", + group: mapped, + position, + ...message ? { + id: openedId, + ...rank ? { relay_rank: rank } : {} + } : { below_messages: value.belowMessages }, + ...source ? { source } : {} + }); + add(session, click); + } + } + }, + dispose() { + disposed = true; + for (const session of sessions.values()) clearSession(session); + sessions.clear(); + for (const entry of previous.values()) time.clear(entry.timer); + previous.clear(); + } + }; +} +var FLUSH_MS = 1e4; +function trace() { + try { + const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(24)); + if (bytes.slice(0, 16).every((byte) => byte === 0)) bytes[0] = 1; + if (bytes.slice(16).every((byte) => byte === 0)) bytes[16] = 1; + const hex = (part) => [...part].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return Object.freeze({ traceparent: `00-${hex(bytes.slice(0, 16))}-${hex(bytes.slice(16))}-00` }); + } catch { + return; + } +} +function createCollector(options) { + const time = options.clock ?? clock; + const appVersion = options.appVersion && /^[a-zA-Z0-9.+_-]{1,64}$/.test(options.appVersion) ? options.appVersion : "unknown"; + let config = DEFAULTS, allowed = /* @__PURE__ */ new Set(); + let generation = 0, disposed = false, tracing = false, exporting = false; + let dropped = 0, exported = 0; + let error; + const queue = []; + const counts = /* @__PURE__ */ new Map(); + const issuedTraces = /* @__PURE__ */ new Map(); + const topics = /* @__PURE__ */ new Set(); + const listeners = /* @__PURE__ */ new Set(); + let stops = []; + let timer; + let pending; + let search; + let searchStop; + let searchOrigin; + let searchGeneration = 0; + let state = Object.freeze({ + config, + active: false, + tracing: false, + topics: Object.freeze([]), + records: Object.freeze([]), + dropped: 0, + exported: 0, + exporting: false, + error: void 0 + }); + const publish = () => { + state = Object.freeze({ + config, + active: topics.size > 0, + tracing, + topics: Object.freeze([...topics]), + records: Object.freeze([...queue, ...[...counts.values()].sort((a, b) => `${a.operation}/${a.outcome}`.localeCompare(`${b.operation}/${b.outcome}`))]), + dropped, + exported, + exporting, + error + }); + for (const listener of listeners) try { + listener(); + } catch {} + }; + const room = () => { + while (queue.length + counts.size >= 200) { + if (queue.length) queue.shift(); + else { + const first = counts.keys().next().value; + if (first !== void 0) counts.delete(first); + } + dropped++; + } + }; + const enqueue = (records) => { + for (const record of records) { + room(); + queue.push(record); + } + publish(); + }; + const stopSearch = () => { + searchGeneration++; + const off = searchStop; + searchStop = void 0; + try { + off?.(); + } catch {} + search?.dispose(); + search = void 0; + searchOrigin = void 0; + topics.delete("search"); + }; + const stop = () => { + generation++; + stopSearch(); + if (timer !== void 0) time.clear(timer); + timer = void 0; + pending?.abort(); + pending = void 0; + exporting = false; + const owned = stops; + stops = []; + for (const dispose of owned) try { + dispose(); + } catch {} + topics.clear(); + tracing = false; + queue.length = 0; + counts.clear(); + issuedTraces.clear(); + }; + const flush = async () => { + if (disposed || !config.enabled || !config.exportEnabled || !options.backend || exporting) return; + const aggregated = [...counts.values()].sort((a, b) => `${a.operation}/${a.outcome}`.localeCompare(`${b.operation}/${b.outcome}`)); + counts.clear(); + for (const record of aggregated) queue.push(record); + if (!queue.length) return; + const epoch = generation; + const batch = Object.freeze(queue.splice(0, 25)); + const controller = new AbortController(); + pending = controller; + const target = config.endpoint; + const eligible = () => !disposed && config.enabled && config.exportEnabled && generation === epoch && !controller.signal.aborted; + exporting = true; + error = void 0; + publish(); + try { + if (!eligible()) return; + await options.backend.send(target, batch, { + signal: controller.signal, + isEligible: eligible + }); + if (eligible()) exported += batch.length; + } catch { + if (eligible()) { + dropped += batch.length; + error = "export"; + } + } finally { + if (generation === epoch && !disposed) { + exporting = false; + pending = void 0; + publish(); + } + } + }; + const start = () => { + if (!config.enabled || !options.telemetry || !allowed.size) return; + const epoch = generation; + const receive = (topic, raw) => { + if (disposed || !config.enabled || generation !== epoch) return; + try { + if (topic === "search") search?.receive(raw); + else if (topic === "ui") { + const record = projectUi(raw, allowed, appVersion); + if (record && config.level === 2) enqueue([record]); + } else { + const value = object(raw), context = object(value?.traceContext); + const parent = typeof context?.traceparent === "string" && issuedTraces.get(context.traceparent) === community(value?.community) ? context.traceparent : void 0; + if (parent) issuedTraces.delete(parent); + const record = projectRequest(raw, allowed, appVersion, parent); + if (record) { + if (config.level === 2) enqueue([record]); + else { + const key = `${record.operation}/${record.outcome}`; + const old = counts.get(key); + if (!old) room(); + counts.set(key, freeze({ + schema: 1, + type: "request_count", + level: 1, + app_version: appVersion, + operation: record.operation, + outcome: record.outcome, + count: Math.min(1e9, (old?.count ?? 0) + 1) + })); + } + } + } + publish(); + } catch { + dropped++; + publish(); + } + }; + for (const topic of ["requests", "ui"]) try { + stops.push(options.own(() => options.telemetry.subscribe(topic, (event) => receive(topic, event)))); + topics.add(topic); + } catch {} + const syncSearch = () => { + if (disposed || !config.enabled || generation !== epoch) return; + let origin; + try { + origin = community(options.communityReader?.current()); + } catch {} + if (!origin || !allowed.has(origin)) { + stopSearch(); + publish(); + return; + } + if (searchOrigin === origin) return; + stopSearch(); + searchOrigin = origin; + const searchEpoch = searchGeneration; + search = createSearchAggregator({ + level: config.level, + allowed, + appVersion, + clock: time, + emit: enqueue, + dropped: () => { + dropped++; + } + }); + try { + searchStop = options.own(() => options.telemetry.subscribe("search", (event) => { + if (searchGeneration === searchEpoch) receive("search", event); + })); + topics.add("search"); + } catch { + search.dispose(); + search = void 0; + } + publish(); + }; + if (options.communityReader) try { + stops.push(options.own(() => options.communityReader.subscribe(syncSearch))); + syncSearch(); + } catch { + stopSearch(); + } + if (config.tracing && options.telemetry.registerTraceContextProvider) try { + stops.push(options.own(() => options.telemetry.registerTraceContextProvider((request) => { + if (disposed || generation !== epoch || !config.enabled || !config.tracing) return; + const origin = community(request.community); + if (!origin || !allowed.has(origin) || !oneOf(request.operation, [ + "query", + "search", + "publish", + "auth", + "media", + "other" + ]) || !oneOf(request.priority, ["foreground", "background"])) return; + const context = trace(); + if (context) { + if (issuedTraces.size >= 200) { + const first = issuedTraces.keys().next().value; + if (first) issuedTraces.delete(first); + } + issuedTraces.set(context.traceparent, origin); + } + return context; + }))); + tracing = true; + } catch {} + if (config.exportEnabled && options.backend) { + const schedule = () => { + if (disposed || generation !== epoch || !config.enabled || !config.exportEnabled) return; + timer = time.set(() => { + if (disposed || generation !== epoch || !config.enabled) return; + flush(); + schedule(); + }, FLUSH_MS); + }; + schedule(); + } + }; + return { + snapshot: () => state, + subscribe(listener) { + if (disposed) return () => {}; + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + configure(input) { + if (disposed) return false; + let next; + try { + next = settings(input, options.declaredOrigins); + } catch {} + if (!next) { + stop(); + config = DEFAULTS; + allowed = /* @__PURE__ */ new Set(); + error = "settings"; + publish(); + return false; + } + stop(); + config = next; + allowed = new Set(next.communities); + dropped = 0; + exported = 0; + error = void 0; + start(); + publish(); + return true; + }, + flush, + clear() { + if (disposed) return; + stop(); + start(); + publish(); + }, + dispose() { + if (disposed) return; + disposed = true; + stop(); + config = DEFAULTS; + publish(); + listeners.clear(); + } + }; +} +// src/backend.ts +/** Distributor supplies the manifest origins. Never use global fetch or a relay +* endpoint, and never fall back to an older uncancellable host request API. */ +function hostBackend(host, declaredOrigins) { + if (!host) return; + return { async send(target, records, context) { + const url = endpoint(target, declaredOrigins); + if (!url || context.signal.aborted || !context.isEligible()) throw new Error("Export unavailable"); + const response = await host.requestOnce({ + url, + method: "POST", + timeoutMs: 1e4, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + schema: 1, + records + }) + }, { + callId: crypto.randomUUID(), + isEligible: () => !context.signal.aborted && context.isEligible() + }); + if (context.signal.aborted || !context.isEligible() || response.status < 200 || response.status >= 300) throw new Error("Export dropped"); + } }; +} +// src/community.ts +/** Controls subscription admission, never attribution of a completed sample. +* Ready RelayData snapshots bind origin:viewer; reject stale/unknown shapes. */ +function communityReaderCapability(value) { + const relay = value; + if (!relay || typeof relay.snapshot !== "function" || typeof relay.subscribe !== "function") return; + return { + current() { + const snapshot = object(relay.snapshot()); + if (snapshot?.status !== "ready" || typeof snapshot.scope !== "string" || typeof snapshot.viewer !== "string" || !/^[0-9a-f]{64}$/.test(snapshot.viewer)) return; + const at = snapshot.scope.lastIndexOf(":"); + if (at < 0 || snapshot.scope.slice(at + 1) !== snapshot.viewer) return; + return community(snapshot.scope.slice(0, at)); + }, + subscribe(listener) { + return relay.subscribe(listener); + } + }; +} +// src/index.tsx +var inject = [ + "react", + "pages", + "settingsCards" +]; +function uiCapability(value) { + if (!value || typeof value !== "object") return; + const ui = value; + return [ + ui.Button, + ui.Input, + ui.Field, + ui.Switch + ].every((component) => typeof component === "function") ? ui : void 0; +} +function apply(ctx) { + const React = ctx.react; + const telemetry = telemetryCapability(capability(ctx, "telemetry")); + const ui = uiCapability(capability(ctx, "ui")); + const origins = manifest_default.host.networkOrigins; + const backend = hostBackend(protectedHostCapability(capability(ctx, "host")), origins); + const collector = createCollector({ + telemetry, + communityReader: communityReaderCapability(capability(ctx, "relay")), + own: (setup) => ctx.effect(setup), + declaredOrigins: origins, + backend + }); + ctx.effect(() => () => collector.dispose()); + function MetricsSettings() { + const state = React.useSyncExternalStore(collector.subscribe, collector.snapshot); + const [communities, setCommunities] = React.useState(state.config.communities.join(", ")); + const [target, setTarget] = React.useState(state.config.endpoint); + const level = state.config.level; + const rates = messageMetrics(state.records); + if (!ui) return /* @__PURE__ */ React.createElement("section", null, /* @__PURE__ */ React.createElement("h1", null, "Buzz Metrics"), /* @__PURE__ */ React.createElement("p", null, "This host lacks shared plugin controls. Collection stays off; update the host to opt in.")); + return /* @__PURE__ */ React.createElement("section", { + className: "ui-card", + style: { padding: "var(--space-panel-inset)" } + }, /* @__PURE__ */ React.createElement("h1", null, "Buzz Metrics"), /* @__PURE__ */ React.createElement("p", null, "Collection, tracing and export start off and reset when this plugin reloads. No disk storage. Closing this page does not stop enabled collection. Turning collection off discards all pending records and short-lived raw query state; data already received by a backend cannot be recalled."), !telemetry && /* @__PURE__ */ React.createElement("p", { role: "status" }, "This host has no telemetry service. No collection is active."), /* @__PURE__ */ React.createElement(ui.Field, { + label: "Allowed communities", + description: "Exact HTTPS community origins, separated by commas. Leave personal communities out. Nothing from another community is recorded or traced." + }, /* @__PURE__ */ React.createElement(ui.Input, { + value: communities, + onValueChange: setCommunities, + maxLength: 4096, + "aria-label": "Allowed communities" + })), /* @__PURE__ */ React.createElement("div", { + role: "group", + "aria-label": "Granularity" + }, /* @__PURE__ */ React.createElement("p", null, "Granularity: ", level === 1 ? "Counts" : "Linked", ". Level 3 query-text export is not implemented. Level changes apply immediately and clear pending data."), /* @__PURE__ */ React.createElement(ui.Button, { + onClick: () => collector.configure({ + ...state.config, + level: 1 + }), + variant: level === 1 ? "prominent" : "subtle" + }, "Level 1 — Counts"), /* @__PURE__ */ React.createElement(ui.Button, { + onClick: () => collector.configure({ + ...state.config, + level: 2 + }), + variant: level === 2 ? "prominent" : "subtle" + }, "Level 2 — Linked")), /* @__PURE__ */ React.createElement("p", null, "Counts contains aggregate request counts and search-session totals, not query IDs, timings or query order. Linked adds request timings, ephemeral search joins, shapes and activation metadata, including opened message event IDs and positions that a backend may link to accessible content. Raw query text, result labels, filter values and message content never enter the record buffer, preview or export."), /* @__PURE__ */ React.createElement("p", null, "Search observes only a ready allowlisted selection. While observed, the host may attach its ephemeral search join IDs in that community, including Counts; Counts omits those IDs from plugin records."), /* @__PURE__ */ React.createElement(ui.Field, { + label: "Metrics backend endpoint", + description: origins.length ? "HTTPS endpoint on an origin declared by this build; no URL credentials, query or fragment." : "This local-only build declares no network origins. A distributor must declare its backend origin in manifest.json and rebuild before export can be enabled." + }, /* @__PURE__ */ React.createElement(ui.Input, { + value: target, + onValueChange: setTarget, + maxLength: 2048, + "aria-label": "Metrics backend endpoint" + })), /* @__PURE__ */ React.createElement("div", { style: { + display: "grid", + gap: "var(--space-3)", + justifyItems: "start" + } }, /* @__PURE__ */ React.createElement(ui.Button, { onClick: () => collector.configure({ + ...state.config, + communities: communities.split(",").map((value) => value.trim()).filter(Boolean), + endpoint: target.trim(), + level + }) }, "Apply settings and clear pending data"), /* @__PURE__ */ React.createElement(ui.Switch, { + label: "Enable collection for this activation", + checked: state.config.enabled, + disabled: !telemetry, + onCheckedChange: (enabled) => collector.configure({ + ...state.config, + enabled + }) + }), /* @__PURE__ */ React.createElement(ui.Switch, { + label: "Attach trace context to allowed relay requests", + checked: state.config.tracing, + disabled: state.config.level !== 2, + onCheckedChange: (tracing) => collector.configure({ + ...state.config, + tracing + }) + }), /* @__PURE__ */ React.createElement(ui.Switch, { + label: "Export redacted batches to the configured backend", + checked: state.config.exportEnabled, + disabled: !backend || !origins.length, + onCheckedChange: (exportEnabled) => collector.configure({ + ...state.config, + exportEnabled + }) + })), state.error && /* @__PURE__ */ React.createElement("p", { role: "alert" }, state.error === "settings" ? "Settings were not applied; collection was stopped and pending data cleared. Correct and Apply the community/backend text fields first, then enable collection. Use exact HTTPS community origins and, for export, a declared backend origin." : "An export batch was dropped. It will not be retried."), /* @__PURE__ */ React.createElement("p", { role: "status" }, "Collection ", state.active ? "ON" : "OFF", " · topics:", " ", state.topics.join(", ") || "none", " · ", state.records.length, "/200 waiting · ", state.exported, " exported · ", state.dropped, " dropped"), /* @__PURE__ */ React.createElement("p", null, "Draft host coverage: unscoped UI timings are dropped because their community is unknown. Current search events prove dispatch only when relay-ranked rows arrive, so unproven empty/failed searches are not counted eligible. Server-side trace/search joins are a relay follow-up. This draft reports app version as unknown."), /* @__PURE__ */ React.createElement("div", { style: { + display: "flex", + gap: "var(--space-2)", + flexWrap: "wrap" + } }, /* @__PURE__ */ React.createElement(ui.Button, { + onClick: () => { + collector.flush(); + }, + disabled: !state.config.enabled || !state.config.exportEnabled || !backend || state.exporting + }, "Send one batch"), /* @__PURE__ */ React.createElement(ui.Button, { onClick: () => collector.clear() }, "Clear pending data")), /* @__PURE__ */ React.createElement("h2", null, "Queued message-search metrics — incomplete coverage"), /* @__PURE__ */ React.createElement("p", null, "Navigation-only sessions are retained but excluded from these rates. On current hosts, eligibility is proven only by relay-ranked results; unproven empty/failed searches are omitted. These are not overall search-quality rates. In the current queue: ", rates.eligible, " settled eligible searches; ", rates.opened, " opened. Message open rate:", " ", rates.open_rate === null ? "not enough data" : `${Math.round(rates.open_rate * 100)}%`, ". Session success:", " ", rates.session_success === null ? "not enough data" : `${Math.round(rates.session_success * 100)}%`, "."), /* @__PURE__ */ React.createElement("h2", null, "Redacted export preview"), /* @__PURE__ */ React.createElement("pre", { + "aria-label": "Redacted metrics preview", + style: { + whiteSpace: "pre-wrap", + overflowWrap: "anywhere" + } + }, JSON.stringify(state.records, null, 2))); + } + ctx.settingsCards.register({ + id: "metrics", + title: "Metrics", + group: "Privacy", + component: MetricsSettings + }); + ctx.pages.register({ + id: "main", + title: "Metrics preview", + primary: true, + component: MetricsSettings + }); +} +export { apply, inject }; diff --git a/metrics/pnpm-lock.yaml b/metrics/pnpm-lock.yaml new file mode 100644 index 0000000..49a27e2 --- /dev/null +++ b/metrics/pnpm-lock.yaml @@ -0,0 +1,1623 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@buzz/author': + specifier: file:vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz + version: file:vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz(typescript@7.0.2) + '@deepseek-ai/cordis': + specifier: 4.0.2 + version: 4.0.2 + '@testing-library/react': + specifier: 16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + '@types/node': + specifier: 24.13.6 + version: 24.13.6 + '@types/react': + specifier: 19.2.18 + version: 19.2.18 + '@types/react-dom': + specifier: 19.2.7 + version: 19.2.7(@types/react@19.2.18) + jsdom: + specifier: 30.0.1 + version: 30.0.1(@noble/hashes@2.0.1) + react: + specifier: 19.2.8 + version: 19.2.8 + react-dom: + specifier: 19.2.8 + version: 19.2.8(react@19.2.8) + typescript: + specifier: 7.0.2 + version: 7.0.2 + vite: + specifier: 8.2.2 + version: 8.2.2(@types/node@24.13.6) + vitest: + specifier: 4.1.11 + version: 4.1.11(@types/node@24.13.6)(jsdom@30.0.1(@noble/hashes@2.0.1))(vite@8.2.2(@types/node@24.13.6)) + +packages: + + '@asamuzakjp/css-color@6.0.7': + resolution: {integrity: sha512-vC/bk1Lz7Tn/EfU9/apOTBk80/8dyGyWMowPoV1tJ52muDGsDqt2HPT2klrFUiY60MQmQv9q8yIht15JnBgDGw==} + engines: {node: ^22.13.0 || >=24.0.0} + + '@asamuzakjp/dom-selector@8.3.2': + resolution: {integrity: sha512-93Z1N+BQNXysodoicpOIyNh2drHfz/CTf9nnT0FEx72GJcIiwgydD7tGAr78j41LsYn3hlRn+LdGPuBLn1Bl8Q==} + engines: {node: ^22.13.0 || >=24.0.0} + + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/runtime@7.29.16': + resolution: {integrity: sha512-LKBjGopxrQE0aFucNL69OyyyF143MOWUULEOftU3oCgyD35Sy84UUpVnt/sNvTb7ZmCyALSt7om+fojlW35zYQ==} + engines: {node: '>=6.9.0'} + + '@bramus/specificity@2.4.5': + resolution: {integrity: sha512-TWjoxMCb5z1j19ZAVlGIkRkoq22F9F1+s+sTcJcw3GN+sEj/ZhWD+PPyol0feaRGZyajOA22FTCv95Ow26i6iA==} + hasBin: true + + '@buzz/author@file:vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz': + resolution: {integrity: sha512-YajODjcCyaRqRnUvtqhDUfoX8MBP4G55wc087xzv2mJydUfujkmSVfMib65Q66ozlwlGjG5uT9mRsp7pZZ0WHA==, tarball: file:vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz} + version: 0.0.0-preview.1 + + '@csstools/color-helpers@6.1.3': + resolution: {integrity: sha512-c6CpX5G1pvuOKTXiRFJ54Lzc8zQrZ3qUjp44QC5DJNt1OmA1vmfUxOMCcKdDqsvffVDG0/MHnY63J+Mn0nmdUg==} + engines: {node: '>=20.19.0'} + + '@csstools/css-calc@3.4.4': + resolution: {integrity: sha512-Jwo1Z8DUsZ8xVOLBdLMfhjJFvWD6pqaUTlBNQZ+qIB2i9g7yG8kd/UBJj2c9J9Twr+u87cjy9BjkmfvMbyOk3Q==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.3 + '@csstools/css-tokenizer': ^4.0.3 + + '@csstools/css-color-parser@4.2.8': + resolution: {integrity: sha512-JLsKBee9dmnA3L+H+vYK4lQ6n5CoY3yEnh33zdlMutRfrTxtqt+hFeoZ1maHRt5vLw67huDLpOkDb3rl9A51MQ==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.3 + '@csstools/css-tokenizer': ^4.0.3 + + '@csstools/css-parser-algorithms@4.0.3': + resolution: {integrity: sha512-EpCfUDaJtwohPHC7egoXxPGT/R1/WyyAhw87MKB/7BPPZvZU+IcEqo4er5FpLnby2Gvwt9Lpxy+WNEDyFjoXtA==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-tokenizer': ^4.0.3 + + '@csstools/css-syntax-patches-for-csstree@1.1.17': + resolution: {integrity: sha512-IPx9W33+t0Yt5TVb+Y7oICrThOIry0TY6GuXfSHOatxA0uiHqbzi98Gai905lpBAX1m/LH7iI96e9jcI7Dkvxw==} + peerDependencies: + css-tree: ^3.2.1 + peerDependenciesMeta: + css-tree: + optional: true + + '@csstools/css-tokenizer@4.0.3': + resolution: {integrity: sha512-gdkFe/Z4KU1q8Y5S3GYScXGcOnO56dgWwIs5+97Ij1VIKISItOIUlCXUq4VLbdnRclF+SSQ49sLsn3KeV111AA==} + engines: {node: '>=20.19.0'} + + '@deepseek-ai/cordis@4.0.2': + resolution: {integrity: sha512-asOnXP1TzFSFQlHb1iegDZp0z/8WD1c7YNrwJR/Tx2bzNuMXfcekE/I67Iv6SQXeLB4csxqCngzQKANP7gdw0g==} + hasBin: true + peerDependencies: + '@deepseek-ai/cordis-plugin-include': ^1.0.7 + '@deepseek-ai/cordis-plugin-loader': ^1.0.3 + peerDependenciesMeta: + '@deepseek-ai/cordis-plugin-include': + optional: true + '@deepseek-ai/cordis-plugin-loader': + optional: true + + '@deepseek-ai/cosmokit@1.9.0': + resolution: {integrity: sha512-5O1S53mZiJyZYcvxxD0Qv1EY7qFPSxbGyD8CbVK6gw7W9FvcXZj2YIX1ZkOqyQQ3Xt2rFkZDHJv0+V3Zmmp8CA==} + + '@emnapi/core@2.0.0-beta.2': + resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==} + + '@emnapi/runtime@2.0.0-beta.2': + resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==} + + '@emnapi/wasi-threads@2.2.0': + resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==} + + '@exodus/bytes@1.16.0': + resolution: {integrity: sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + peerDependencies: + '@noble/hashes': ^1.8.0 || ^2.0.0 + peerDependenciesMeta: + '@noble/hashes': + optional: true + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@napi-rs/wasm-runtime@1.2.6': + resolution: {integrity: sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + peerDependencies: + '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 + '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 + + '@noble/ciphers@2.1.1': + resolution: {integrity: sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw==} + engines: {node: '>= 20.19.0'} + + '@noble/curves@2.0.1': + resolution: {integrity: sha512-vs1Az2OOTBiP4q0pwjW5aF0xp9n4MxVrmkFBxc6EKZc6ddYx5gaZiAsZoq0uRRXWbi3AT/sBqn05eRPtn1JCPw==} + engines: {node: '>= 20.19.0'} + + '@noble/hashes@2.0.1': + resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==} + engines: {node: '>= 20.19.0'} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@rolldown/binding-android-arm-eabi@1.2.19': + resolution: {integrity: sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.19': + resolution: {integrity: sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.19': + resolution: {integrity: sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.19': + resolution: {integrity: sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.19': + resolution: {integrity: sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': + resolution: {integrity: sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.19': + resolution: {integrity: sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.19': + resolution: {integrity: sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.19': + resolution: {integrity: sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.19': + resolution: {integrity: sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.19': + resolution: {integrity: sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.19': + resolution: {integrity: sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.19': + resolution: {integrity: sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.2.19': + resolution: {integrity: sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + cpu: [wasm32] + + '@rolldown/binding-win32-arm64-msvc@1.2.19': + resolution: {integrity: sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.19': + resolution: {integrity: sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.1.1': + resolution: {integrity: sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==} + + '@scure/base@2.0.0': + resolution: {integrity: sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==} + + '@scure/bip32@2.0.1': + resolution: {integrity: sha512-4Md1NI5BzoVP+bhyJaY3K6yMesEFzNS1sE/cP+9nuvE7p/b0kx9XbpDHHFl8dHtufcbdHRUUQdRqLIPHN/s7yA==} + + '@scure/bip39@2.0.1': + resolution: {integrity: sha512-PsxdFj/d2AcJcZDX1FXN3dDgitDDTmwf78rKZq1a6c1P1Nan1X/Sxc7667zU3U+AN60g7SxxP0YCVw2H/hBycg==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@testing-library/dom@10.4.2': + resolution: {integrity: sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==} + engines: {node: '>=18'} + + '@testing-library/react@16.3.3': + resolution: {integrity: sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==} + engines: {node: '>=18'} + peerDependencies: + '@testing-library/dom': ^10.0.0 + '@types/react': ^18.0.0 || ^19.0.0 + '@types/react-dom': ^18.0.0 || ^19.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@tybys/wasm-util@0.10.5': + resolution: {integrity: sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==} + + '@types/aria-query@5.0.4': + resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.11': + resolution: {integrity: sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==} + + '@types/node@24.13.6': + resolution: {integrity: sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg==} + + '@types/react-dom@19.2.7': + resolution: {integrity: sha512-I8bPpDLcHBv1qiIiXDCy71Rt8eQDKJP0sMSWJphDdAcdqiJ1sGpZamavoEIRZmYzjia9LuEb2HlYdDpmoENpvQ==} + peerDependencies: + '@types/react': ^19.2.0 + + '@types/react@19.2.18': + resolution: {integrity: sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} + + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} + + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} + + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} + + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} + + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + + aria-query@5.3.0: + resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + bidi-js@1.1.0: + resolution: {integrity: sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + css-tree@3.2.1: + resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + + csstype@3.2.4: + resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==} + + data-urls@7.0.0: + resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + dom-accessibility-api@0.5.16: + resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + + entities@9.0.0: + resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} + engines: {node: '>=20.19.0'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + html-encoding-sniffer@6.0.0: + resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + jsdom@30.0.1: + resolution: {integrity: sha512-52v7mUVUfNQVYYqE1lcdaymWL0njO7lTLUog6ZvW2U5KsbiLk/GnZlVJ+qx0xfNJZ6Gn+KSpPNE52vurbxZwrA==} + engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + peerDependencies: + canvas: ^3.2.3 + peerDependenciesMeta: + canvas: + optional: true + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lru-cache@11.5.4: + resolution: {integrity: sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw==} + engines: {node: 20 || >=22} + + lz-string@1.5.0: + resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + hasBin: true + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + mdn-data@2.27.1: + resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + nostr-tools@2.25.2: + resolution: {integrity: sha512-7JAx+brEPmqGz1yzaK9MOxvis/Nl1B38j9hVsBSRDMRmxk5XSc0+5LlPEYbzeiUyk41RURBDcfuMzmaT754HAg==} + peerDependencies: + typescript: '>=5.0.0' + peerDependenciesMeta: + typescript: + optional: true + + nostr-wasm@0.1.0: + resolution: {integrity: sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==} + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + parse5@8.1.1: + resolution: {integrity: sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.34: + resolution: {integrity: sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw==} + engines: {node: ^10 || ^12 || >=14} + + pretty-format@27.5.1: + resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + react-dom@19.2.8: + resolution: {integrity: sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==} + peerDependencies: + react: ^19.2.8 + + react-is@17.0.2: + resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + + react@19.2.8: + resolution: {integrity: sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==} + engines: {node: '>=0.10.0'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + rolldown@1.2.19: + resolution: {integrity: sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + + scheduler@0.27.0: + resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.3.0: + resolution: {integrity: sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==} + engines: {node: '>=6.0.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.4.0: + resolution: {integrity: sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyrainbow@3.2.0: + resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==} + engines: {node: '>=14.0.0'} + + tldts-core@7.6.4: + resolution: {integrity: sha512-QywQ9lgQyZMuc3NVlqmuxHOhlwirSdvgD/vDLvX8dZYcYgy1cdri5rY/TXDHcF4J3VBSdJLcJNIJI6zGJ7jE+w==} + + tldts@7.6.4: + resolution: {integrity: sha512-wp+ZdvQyov404xynNcjbXoJyeGM28W/aCwMmry/rJ+Y0SsObukJYkWwuxWGbNpIjeqMaEbNUtXPNtPPfI5cTFA==} + hasBin: true + + tough-cookie@6.1.0: + resolution: {integrity: sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==} + engines: {node: '>=16'} + + tr46@6.0.0: + resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==} + engines: {node: '>=20'} + + tr46@7.0.0: + resolution: {integrity: sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==} + engines: {node: ^22.14.0 || >=24.0.0} + + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + undici-types@7.18.2: + resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} + + undici@8.14.0: + resolution: {integrity: sha512-MqM6wqORYo0jb1WFUwFKZTFWFz6VeBMPj9op5Hq+RvlrQjISQCyLEfx5+/iqOLWC/LL1HliJ5t0NP1BgYpXeVQ==} + engines: {node: '>=22.19.0'} + + vite@8.2.2: + resolution: {integrity: sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.4.0 || ^0.5.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + + webidl-conversions@8.0.1: + resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} + engines: {node: '>=20'} + + whatwg-mimetype@5.0.0: + resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==} + engines: {node: '>=20'} + + whatwg-url@16.0.1: + resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + whatwg-url@17.3.0: + resolution: {integrity: sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==} + engines: {node: ^22.14.0 || >=24.0.0} + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + +snapshots: + + '@asamuzakjp/css-color@6.0.7': + dependencies: + '@csstools/css-calc': 3.4.4(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3) + '@csstools/css-color-parser': 4.2.8(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3) + '@csstools/css-parser-algorithms': 4.0.3(@csstools/css-tokenizer@4.0.3) + '@csstools/css-tokenizer': 4.0.3 + lru-cache: 11.5.4 + + '@asamuzakjp/dom-selector@8.3.2': + dependencies: + bidi-js: 1.1.0 + css-tree: 3.2.1 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.5.4 + + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/runtime@7.29.16': {} + + '@bramus/specificity@2.4.5': + dependencies: + css-tree: 3.2.1 + + '@buzz/author@file:vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz(typescript@7.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + '@types/react': 19.2.18 + nostr-tools: 2.25.2(typescript@7.0.2) + transitivePeerDependencies: + - '@deepseek-ai/cordis-plugin-include' + - '@deepseek-ai/cordis-plugin-loader' + - typescript + + '@csstools/color-helpers@6.1.3': {} + + '@csstools/css-calc@3.4.4(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3)': + dependencies: + '@csstools/css-parser-algorithms': 4.0.3(@csstools/css-tokenizer@4.0.3) + '@csstools/css-tokenizer': 4.0.3 + + '@csstools/css-color-parser@4.2.8(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3)': + dependencies: + '@csstools/color-helpers': 6.1.3 + '@csstools/css-calc': 3.4.4(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3) + '@csstools/css-parser-algorithms': 4.0.3(@csstools/css-tokenizer@4.0.3) + '@csstools/css-tokenizer': 4.0.3 + + '@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3)': + dependencies: + '@csstools/css-tokenizer': 4.0.3 + + '@csstools/css-syntax-patches-for-csstree@1.1.17(css-tree@3.2.1)': + optionalDependencies: + css-tree: 3.2.1 + + '@csstools/css-tokenizer@4.0.3': {} + + '@deepseek-ai/cordis@4.0.2': + dependencies: + '@deepseek-ai/cosmokit': 1.9.0 + '@standard-schema/spec': 1.1.0 + + '@deepseek-ai/cosmokit@1.9.0': {} + + '@emnapi/core@2.0.0-beta.2': + dependencies: + '@emnapi/wasi-threads': 2.2.0 + tslib: 2.9.1 + optional: true + + '@emnapi/runtime@2.0.0-beta.2': + dependencies: + tslib: 2.9.1 + optional: true + + '@emnapi/wasi-threads@2.2.0': + dependencies: + tslib: 2.9.1 + optional: true + + '@exodus/bytes@1.16.0(@noble/hashes@2.0.1)': + optionalDependencies: + '@noble/hashes': 2.0.1 + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)': + dependencies: + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@tybys/wasm-util': 0.10.5 + optional: true + + '@noble/ciphers@2.1.1': {} + + '@noble/curves@2.0.1': + dependencies: + '@noble/hashes': 2.0.1 + + '@noble/hashes@2.0.1': {} + + '@oxc-project/types@0.156.0': {} + + '@rolldown/binding-android-arm-eabi@1.2.19': + optional: true + + '@rolldown/binding-android-arm64@1.2.19': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.19': + optional: true + + '@rolldown/binding-darwin-x64@1.2.19': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.19': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.19': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.19': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.19': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.19': + optional: true + + '@rolldown/binding-wasm32-wasi@1.2.19': + dependencies: + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2) + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.19': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.19': + optional: true + + '@rolldown/pluginutils@1.1.1': {} + + '@scure/base@2.0.0': {} + + '@scure/bip32@2.0.1': + dependencies: + '@noble/curves': 2.0.1 + '@noble/hashes': 2.0.1 + '@scure/base': 2.0.0 + + '@scure/bip39@2.0.1': + dependencies: + '@noble/hashes': 2.0.1 + '@scure/base': 2.0.0 + + '@standard-schema/spec@1.1.0': {} + + '@testing-library/dom@10.4.2': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/runtime': 7.29.16 + '@types/aria-query': 5.0.4 + aria-query: 5.3.0 + dom-accessibility-api: 0.5.16 + lz-string: 1.5.0 + picocolors: 1.1.1 + pretty-format: 27.5.1 + + '@testing-library/react@16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + dependencies: + '@babel/runtime': 7.29.16 + '@testing-library/dom': 10.4.2 + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) + optionalDependencies: + '@types/react': 19.2.18 + '@types/react-dom': 19.2.7(@types/react@19.2.18) + + '@tybys/wasm-util@0.10.5': + dependencies: + tslib: 2.9.1 + optional: true + + '@types/aria-query@5.0.4': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.11': {} + + '@types/node@24.13.6': + dependencies: + undici-types: 7.18.2 + + '@types/react-dom@19.2.7(@types/react@19.2.18)': + dependencies: + '@types/react': 19.2.18 + + '@types/react@19.2.18': + dependencies: + csstype: 3.2.4 + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitest/expect@4.1.11': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + chai: 6.3.0 + tinyrainbow: 3.2.0 + + '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@24.13.6))': + dependencies: + '@vitest/spy': 4.1.11 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.2.2(@types/node@24.13.6) + + '@vitest/pretty-format@4.1.11': + dependencies: + tinyrainbow: 3.2.0 + + '@vitest/runner@4.1.11': + dependencies: + '@vitest/utils': 4.1.11 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.11': {} + + '@vitest/utils@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.0 + + ansi-regex@5.0.1: {} + + ansi-styles@5.2.0: {} + + aria-query@5.3.0: + dependencies: + dequal: 2.0.3 + + assertion-error@2.0.1: {} + + bidi-js@1.1.0: + dependencies: + require-from-string: 2.0.2 + + chai@6.3.0: {} + + convert-source-map@2.0.0: {} + + css-tree@3.2.1: + dependencies: + mdn-data: 2.27.1 + source-map-js: 1.3.0 + + csstype@3.2.4: {} + + data-urls@7.0.0(@noble/hashes@2.0.1): + dependencies: + whatwg-mimetype: 5.0.0 + whatwg-url: 16.0.1(@noble/hashes@2.0.1) + transitivePeerDependencies: + - '@noble/hashes' + + decimal.js@10.6.0: {} + + dequal@2.0.3: {} + + detect-libc@2.1.2: {} + + dom-accessibility-api@0.5.16: {} + + entities@9.0.0: {} + + es-module-lexer@2.3.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.11 + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + html-encoding-sniffer@6.0.0(@noble/hashes@2.0.1): + dependencies: + '@exodus/bytes': 1.16.0(@noble/hashes@2.0.1) + transitivePeerDependencies: + - '@noble/hashes' + + is-potential-custom-element-name@1.0.1: {} + + js-tokens@4.0.0: {} + + jsdom@30.0.1(@noble/hashes@2.0.1): + dependencies: + '@asamuzakjp/css-color': 6.0.7 + '@asamuzakjp/dom-selector': 8.3.2 + '@bramus/specificity': 2.4.5 + '@csstools/css-syntax-patches-for-csstree': 1.1.17(css-tree@3.2.1) + '@exodus/bytes': 1.16.0(@noble/hashes@2.0.1) + css-tree: 3.2.1 + data-urls: 7.0.0(@noble/hashes@2.0.1) + decimal.js: 10.6.0 + html-encoding-sniffer: 6.0.0(@noble/hashes@2.0.1) + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.5.4 + parse5: 8.1.1 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 6.1.0 + undici: 8.14.0 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 8.0.1 + whatwg-mimetype: 5.0.0 + whatwg-url: 17.3.0(@noble/hashes@2.0.1) + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - '@noble/hashes' + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lru-cache@11.5.4: {} + + lz-string@1.5.0: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + mdn-data@2.27.1: {} + + nanoid@3.3.20: {} + + nostr-tools@2.25.2(typescript@7.0.2): + dependencies: + '@noble/ciphers': 2.1.1 + '@noble/curves': 2.0.1 + '@noble/hashes': 2.0.1 + '@scure/base': 2.0.0 + '@scure/bip32': 2.0.1 + '@scure/bip39': 2.0.1 + nostr-wasm: 0.1.0 + optionalDependencies: + typescript: 7.0.2 + + nostr-wasm@0.1.0: {} + + obug@2.2.1: {} + + parse5@8.1.1: + dependencies: + entities: 9.0.0 + + pathe@2.0.3: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.34: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.3.0 + + pretty-format@27.5.1: + dependencies: + ansi-regex: 5.0.1 + ansi-styles: 5.2.0 + react-is: 17.0.2 + + punycode@2.3.1: {} + + react-dom@19.2.8(react@19.2.8): + dependencies: + react: 19.2.8 + scheduler: 0.27.0 + + react-is@17.0.2: {} + + react@19.2.8: {} + + require-from-string@2.0.2: {} + + rolldown@1.2.19: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.1.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.19 + '@rolldown/binding-android-arm64': 1.2.19 + '@rolldown/binding-darwin-arm64': 1.2.19 + '@rolldown/binding-darwin-x64': 1.2.19 + '@rolldown/binding-freebsd-x64': 1.2.19 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.19 + '@rolldown/binding-linux-arm64-gnu': 1.2.19 + '@rolldown/binding-linux-arm64-musl': 1.2.19 + '@rolldown/binding-linux-ppc64-gnu': 1.2.19 + '@rolldown/binding-linux-s390x-gnu': 1.2.19 + '@rolldown/binding-linux-x64-gnu': 1.2.19 + '@rolldown/binding-linux-x64-musl': 1.2.19 + '@rolldown/binding-openharmony-arm64': 1.2.19 + '@rolldown/binding-wasm32-wasi': 1.2.19 + '@rolldown/binding-win32-arm64-msvc': 1.2.19 + '@rolldown/binding-win32-x64-msvc': 1.2.19 + + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + + scheduler@0.27.0: {} + + siginfo@2.0.0: {} + + source-map-js@1.3.0: {} + + stackback@0.0.2: {} + + std-env@4.3.0: {} + + symbol-tree@3.2.4: {} + + tinybench@2.9.0: {} + + tinyexec@1.4.0: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinyrainbow@3.2.0: {} + + tldts-core@7.6.4: {} + + tldts@7.6.4: + dependencies: + tldts-core: 7.6.4 + + tough-cookie@6.1.0: + dependencies: + tldts: 7.6.4 + + tr46@6.0.0: + dependencies: + punycode: 2.3.1 + + tr46@7.0.0: + dependencies: + punycode: 2.3.1 + + tslib@2.9.1: + optional: true + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + undici-types@7.18.2: {} + + undici@8.14.0: {} + + vite@8.2.2(@types/node@24.13.6): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.34 + rolldown: 1.2.19 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.13.6 + fsevents: 2.3.3 + + vitest@4.1.11(@types/node@24.13.6)(jsdom@30.0.1(@noble/hashes@2.0.1))(vite@8.2.2(@types/node@24.13.6)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.2.2(@types/node@24.13.6)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.2.1 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 2.9.0 + tinyexec: 1.4.0 + tinyglobby: 0.2.17 + tinyrainbow: 3.2.0 + vite: 8.2.2(@types/node@24.13.6) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.13.6 + jsdom: 30.0.1(@noble/hashes@2.0.1) + transitivePeerDependencies: + - msw + + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@8.0.1: {} + + whatwg-mimetype@5.0.0: {} + + whatwg-url@16.0.1(@noble/hashes@2.0.1): + dependencies: + '@exodus/bytes': 1.16.0(@noble/hashes@2.0.1) + tr46: 6.0.0 + webidl-conversions: 8.0.1 + transitivePeerDependencies: + - '@noble/hashes' + + whatwg-url@17.3.0(@noble/hashes@2.0.1): + dependencies: + '@exodus/bytes': 1.16.0(@noble/hashes@2.0.1) + tr46: 7.0.0 + webidl-conversions: 8.0.1 + transitivePeerDependencies: + - '@noble/hashes' + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} diff --git a/metrics/src/backend.test.ts b/metrics/src/backend.test.ts new file mode 100644 index 0000000..54affa4 --- /dev/null +++ b/metrics/src/backend.test.ts @@ -0,0 +1,76 @@ +import { expect, it, vi } from "vitest"; +import { hostBackend } from "./backend.ts"; +import { protectedHostCapability, type ProtectedHost } from "./contract.ts"; +import { endpoint } from "./config.ts"; +import { ORIGINS, PERSONAL, TARGET, TEXT } from "./testkit.ts"; + +it("uses only protected host requests to a manifest-declared TLS origin", async () => { + const request = vi.fn(); + expect( + hostBackend(protectedHostCapability({ request }), ORIGINS), + ).toBeUndefined(); + expect(endpoint(TARGET, [])).toBeUndefined(); + for (const url of [ + PERSONAL, + "http://metrics.example/ingest", + "https://metrics.example.evil/", + "https://user:pass@metrics.example/", + `${TARGET}?token=secret`, + `${TARGET}#fragment`, + ]) + expect(endpoint(url, ORIGINS)).toBeUndefined(); + const requestOnce = vi.fn(async () => ({ + status: 204, + headers: {}, + body: TEXT, + })); + const backend = hostBackend({ requestOnce }, ORIGINS)!; + const signal = new AbortController().signal; + await expect( + backend.send(PERSONAL, [], { signal, isEligible: () => true }), + ).rejects.toThrow("unavailable"); + expect(requestOnce).not.toHaveBeenCalled(); + await backend.send(TARGET, [], { signal, isEligible: () => true }); + expect(requestOnce.mock.calls[0]?.[0]).toMatchObject({ + url: TARGET, + method: "POST", + timeoutMs: 10000, + body: JSON.stringify({ schema: 1, records: [] }), + }); + expect(request).not.toHaveBeenCalled(); +}); + +it("passes opt-out eligibility to the host before dispatch and drops stale/error responses without echoing them", async () => { + let eligible = true, + finish!: (value: { status: number; headers: {}; body: string }) => void; + const requestOnce = vi.fn( + () => + new Promise<{ status: number; headers: {}; body: string }>((resolve) => { + finish = resolve; + }), + ); + const backend = hostBackend({ requestOnce }, ORIGINS)!; + const controller = new AbortController(); + const work = backend.send(TARGET, [], { + signal: controller.signal, + isEligible: () => eligible, + }); + const guard = requestOnce.mock.calls[0]?.[1] as unknown as { + callId: string; + isEligible(): boolean; + }; + expect(guard.callId).toMatch(/^[a-f0-9-]{36}$/); + expect(guard.isEligible()).toBe(true); + eligible = false; + controller.abort(); + expect(guard.isEligible()).toBe(false); + finish({ status: 500, headers: {}, body: TEXT }); + await expect(work).rejects.toThrow("Export dropped"); + await expect( + backend.send(TARGET, [], { + signal: controller.signal, + isEligible: () => true, + }), + ).rejects.toThrow("unavailable"); + expect(requestOnce).toHaveBeenCalledOnce(); +}); diff --git a/metrics/src/backend.ts b/metrics/src/backend.ts new file mode 100644 index 0000000..9fbac47 --- /dev/null +++ b/metrics/src/backend.ts @@ -0,0 +1,40 @@ +import type { ProtectedHost } from "./contract.ts"; +import { endpoint } from "./config.ts"; +import type { MetricsBackend } from "./collector.ts"; + +/** Distributor supplies the manifest origins. Never use global fetch or a relay + * endpoint, and never fall back to an older uncancellable host request API. */ +export function hostBackend( + host: ProtectedHost | undefined, + declaredOrigins: readonly string[], +): MetricsBackend | undefined { + if (!host) return; + return { + async send(target, records, context) { + const url = endpoint(target, declaredOrigins); + if (!url || context.signal.aborted || !context.isEligible()) + throw new Error("Export unavailable"); + const response = await host.requestOnce( + { + url, + method: "POST", + timeoutMs: 10_000, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ schema: 1, records }), + }, + { + callId: crypto.randomUUID(), + isEligible: () => !context.signal.aborted && context.isEligible(), + }, + ); + if ( + context.signal.aborted || + !context.isEligible() || + response.status < 200 || + response.status >= 300 + ) + throw new Error("Export dropped"); + // Do not retain or display response bodies/headers or arbitrary errors. + }, + }; +} diff --git a/metrics/src/bundle.test.ts b/metrics/src/bundle.test.ts new file mode 100644 index 0000000..1ffd0de --- /dev/null +++ b/metrics/src/bundle.test.ts @@ -0,0 +1,69 @@ +import { readFileSync, statSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { expect, it, vi } from "vitest"; +import { checkPlugin } from "../../indexer/check-plugin.ts"; +import { scanPlugin } from "../../indexer/audit.ts"; +import { parseManifest } from "../../indexer/manifest.ts"; +import { TEXT, WORK, PERSONAL, TARGET } from "./testkit.ts"; + +const folder = new URL("../", import.meta.url); +const read = (name: string) => readFileSync(new URL(name, folder), "utf8"); +it("builds one self-contained default-off plugin that passes the repository's content/listing/audit checks", async () => { + const text = read("plugin.js"); + const manifest = read("manifest.json"); + const parsed = parseManifest(manifest); + if (!("manifest" in parsed)) throw new Error("Invalid manifest"); + expect(parsed.manifest.host.networkOrigins).toEqual([]); + expect( + scanPlugin( + { + text, + bytes: statSync(new URL("plugin.js", folder)).size, + truncated: false, + }, + parsed.manifest.host, + ), + ).toEqual([]); + // Content check only: the CLI's actual commit/push gate cannot pass until + // the local publisher commits the indexed patch. Do not falsify that state. + const findings = checkPlugin({ + manifest, + plugin: { text, bytes: Buffer.byteLength(text) }, + listing: read("buzz-listing.yaml"), + readme: true, + }); + expect(findings.filter((finding) => finding.level === "fail")).toEqual([]); + expect(text).not.toContain(TEXT); + expect(text).not.toContain(WORK); + expect(text).not.toContain(PERSONAL); + expect(text).not.toContain(TARGET); + const module = await import( + /* @vite-ignore */ new URL("plugin.js", folder).href + ); + expect(Object.keys(module).sort()).toEqual(["apply", "inject"]); + const telemetry = { + subscribe: vi.fn(), + registerTraceContextProvider: vi.fn(), + }; + const get = (name: string) => (name === "telemetry" ? telemetry : undefined); + const page = vi.fn(), + card = vi.fn(), + stops: (() => void)[] = []; + module.apply({ + react: {}, + reflect: { get }, + pages: { register: page }, + settingsCards: { register: card }, + effect(setup: () => () => void) { + const stop = setup(); + stops.push(stop); + return stop; + }, + }); + expect(page).toHaveBeenCalledOnce(); + expect(card).toHaveBeenCalledOnce(); + expect(telemetry.subscribe).not.toHaveBeenCalled(); + expect(telemetry.registerTraceContextProvider).not.toHaveBeenCalled(); + for (const stop of stops.reverse()) stop(); + expect(fileURLToPath(folder)).toContain("metrics"); +}); diff --git a/metrics/src/collector.test.ts b/metrics/src/collector.test.ts new file mode 100644 index 0000000..9c82d5f --- /dev/null +++ b/metrics/src/collector.test.ts @@ -0,0 +1,446 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { + createCollector, + BATCH_SIZE, + FLUSH_MS, + MAX_RECORDS, + type MetricsBackend, +} from "./collector.ts"; +import { DEFAULTS } from "./config.ts"; +import { + click, + enabled, + end, + EVENT, + fakeClock, + host, + ORIGINS, + PERSONAL, + query, + request, + results, + selection, + start, + TARGET, + TEXT, + WORK, +} from "./testkit.ts"; + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(0); +}); +afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); +}); +const setup = (extra: Partial[0]> = {}) => { + const h = host(); + const scope = selection(); + const collector = createCollector({ + telemetry: h.telemetry, + communityReader: scope.reader, + own: (run) => run(), + declaredOrigins: ORIGINS, + clock: fakeClock, + ...extra, + }); + return { h, collector, scope }; +}; + +it("defaults off, activates nothing without explicit consent and an allowlist, and tolerates old hosts/topics", () => { + const { h, collector, scope } = setup(); + expect(scope.current).not.toHaveBeenCalled(); + expect(scope.listeners.size).toBe(0); + expect(collector.snapshot().config).toEqual(DEFAULTS); + expect(h.subscribe).not.toHaveBeenCalled(); + expect(h.providers.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + expect(collector.configure({ ...enabled(), communities: [] })).toBe(false); + expect(h.active()).toBe(0); + const old = createCollector({ own: (run) => run(), declaredOrigins: [] }); + old.configure(enabled()); + expect(old.snapshot().active).toBe(false); + old.dispose(); + const partial = host(["requests"]); + const one = createCollector({ + telemetry: partial.telemetry, + own: (run) => run(), + declaredOrigins: [], + }); + expect(one.configure(enabled())).toBe(true); + expect(one.snapshot().topics).toEqual(["requests"]); + one.dispose(); + collector.dispose(); + expect(partial.active()).toBe(0); +}); + +it.each(["allowlist", "endpoint"] as const)( + "invalid %s privacy changes stop the old configuration instead of leaving it active", + async (invalid) => { + const send = vi.fn(async () => {}); + const { h, collector, scope } = setup({ backend: { send } }); + const initial = { + ...enabled(), + tracing: true, + exportEnabled: true, + endpoint: TARGET, + }; + collector.configure(initial); + h.send("requests", request()); + h.send("search", start()); + h.send("search", query()); + h.send("search", results()); + expect(h.providers.size).toBe(1); + expect(vi.getTimerCount()).toBeGreaterThan(0); + const candidate = + invalid === "allowlist" + ? { ...initial, communities: [] } + : { ...initial, endpoint: PERSONAL }; + expect(collector.configure(candidate)).toBe(false); + expect(collector.snapshot().config).toEqual(DEFAULTS); + expect(collector.snapshot().active).toBe(false); + expect(collector.snapshot().records).toEqual([]); + expect(h.active()).toBe(0); + expect(h.providers.size).toBe(0); + expect(scope.listeners.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + // Re-enabling cannot accidentally reuse the revoked old origins/target. + expect( + collector.configure({ ...collector.snapshot().config, enabled: true }), + ).toBe(false); + await vi.advanceTimersByTimeAsync(FLUSH_MS * 2); + expect(send).not.toHaveBeenCalled(); + collector.dispose(); + }, +); + +it("admits the search subscription only for a ready allowlisted selection and fences scope changes", () => { + const scope = selection(PERSONAL); + const { h, collector } = setup({ communityReader: scope.reader }); + expect(scope.listeners.size).toBe(0); + collector.configure({ ...enabled(), tracing: true }); + expect(scope.listeners.size).toBe(1); + expect(collector.snapshot().topics).not.toContain("search"); + expect(h.listeners.get("search")?.size ?? 0).toBe(0); + scope.select(WORK); + expect(collector.snapshot().topics).toContain("search"); + const stale = [...h.listeners.get("search")!][0]; + h.send("search", start()); + h.send("search", query()); + h.send("search", results()); + expect(vi.getTimerCount()).toBeGreaterThan(0); + scope.select(PERSONAL); + expect(collector.snapshot().topics).not.toContain("search"); + expect(h.listeners.get("search")?.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + scope.select(WORK); + const read = vi.fn(); + stale({ + get version() { + read(); + return 1; + }, + }); + expect(read).not.toHaveBeenCalled(); + h.send("search", start(undefined, PERSONAL)); + h.send("search", query(undefined, TEXT, { community: PERSONAL })); + h.send("search", results()); + h.send("search", click()); + h.send("search", end()); + expect(collector.snapshot().records).toEqual([]); + scope.select(undefined); + expect(collector.snapshot().topics).not.toContain("search"); + collector.configure({ ...enabled(), enabled: false }); + expect(scope.listeners.size).toBe(0); + expect(h.active()).toBe(0); + expect(h.providers.size).toBe(0); + scope.select(WORK); + expect(h.active()).toBe(0); + collector.dispose(); +}); + +it("keeps search unsubscribed without an authoritative selection capability", () => { + const { h, collector } = setup({ communityReader: undefined }); + collector.configure(enabled()); + expect(collector.snapshot().topics).toEqual(["requests", "ui"]); + expect(h.listeners.get("search")).toBeUndefined(); + collector.dispose(); +}); + +it("projects only allowed fields/communities, drops current unscoped UI events, and never queues raw text", () => { + const { h, collector } = setup(); + collector.configure(enabled()); + h.send("requests", request(PERSONAL)); + h.send("requests", request(`${WORK}.evil`)); + h.send("requests", request(`${WORK}/private-path`)); + h.send("requests", request()); + h.send("ui", { + version: 1, + type: "uiTiming", + operation: "channel_open_to_visible_rows", + trigger: "click", + durationMs: 20, + outcome: "ok", + queryText: TEXT, + }); + h.send("ui", { + version: 1, + type: "uiTiming", + community: PERSONAL, + operation: "channel_open_to_visible_rows", + trigger: "click", + durationMs: 20, + outcome: "ok", + }); + h.send("ui", { + version: 1, + type: "uiTiming", + community: WORK, + operation: "channel_open_to_visible_rows", + trigger: "click", + durationMs: 20, + outcome: "ok", + nested: { queryText: TEXT }, + }); + expect(collector.snapshot().records).toHaveLength(2); + expect(collector.snapshot().records[0]).toEqual({ + schema: 1, + type: "request", + level: 2, + app_version: "unknown", + community: WORK, + operation: "search", + priority: "background", + duration_ms: 12, + bytes: 42, + outcome: "ok", + }); + expect(JSON.stringify(collector.snapshot())).not.toContain(TEXT); + expect(JSON.stringify(collector.snapshot().records)).not.toContain(PERSONAL); + expect(Object.isFrozen(collector.snapshot().records[0])).toBe(true); + collector.dispose(); + expect(h.active()).toBe(0); + expect(vi.getTimerCount()).toBe(0); +}); + +it("aggregates Level 1 request counts without IDs, per-event timings or order, and clears on downgrade", () => { + const { h, collector } = setup(); + collector.configure(enabled()); + h.send("requests", request()); + collector.configure(enabled(1)); + expect(collector.snapshot().records).toEqual([]); + for (let i = 0; i < 10; i++) h.send("requests", request()); + expect(collector.snapshot().records).toEqual([ + { + schema: 1, + type: "request_count", + level: 1, + app_version: "unknown", + operation: "search", + outcome: "ok", + count: 10, + }, + ]); + expect(JSON.stringify(collector.snapshot().records)).not.toMatch( + /duration|bytes|traceparent|query_id|session_id|community|priority/, + ); + collector.dispose(); +}); + +it("gates synchronous W3C trace generation before crypto and retains only its own context", () => { + const { h, collector } = setup(); + collector.configure({ ...enabled(), tracing: true }); + const provider = [...h.providers][0]; + expect(provider).toBeDefined(); + const random = vi.spyOn(crypto, "getRandomValues"); + expect( + provider({ + community: PERSONAL, + operation: "query", + priority: "foreground", + }), + ).toBeUndefined(); + expect( + provider({ + community: `${WORK}.evil`, + operation: "query", + priority: "foreground", + }), + ).toBeUndefined(); + expect(random).not.toHaveBeenCalled(); + const context = provider({ + community: WORK.replace("https:", "wss:"), + operation: "query", + priority: "foreground", + }); + expect(context?.traceparent).toMatch( + /^00-(?!0{32}-)[0-9a-f]{32}-(?!0{16}-)[0-9a-f]{16}-00$/, + ); + expect(Object.isFrozen(context)).toBe(true); + h.send("requests", { + ...request(), + traceContext: { ...context, queryText: TEXT }, + }); + expect(collector.snapshot().records[0]).toMatchObject({ + traceparent: context?.traceparent, + }); + h.send("requests", { + ...request(), + traceContext: { + traceparent: "00-11111111111111111111111111111111-2222222222222222-00", + correlationId: TEXT, + }, + }); + expect(collector.snapshot().records[1]).not.toHaveProperty("traceparent"); + collector.configure({ ...enabled(), tracing: false }); + expect(h.providers.size).toBe(0); + expect( + provider({ community: WORK, operation: "query", priority: "foreground" }), + ).toBeUndefined(); + expect(collector.snapshot().records).toEqual([]); + collector.dispose(); + random.mockRestore(); +}); + +it("fails open when trace randomness is unavailable without leaking the failure", () => { + const { h, collector } = setup(); + collector.configure({ ...enabled(), tracing: true }); + const provider = [...h.providers][0]; + vi.spyOn(crypto, "getRandomValues").mockImplementation(() => { + throw new Error(TEXT); + }); + expect( + provider({ community: WORK, operation: "query", priority: "foreground" }), + ).toBeUndefined(); + h.send("requests", request()); + expect(collector.snapshot().records).toHaveLength(1); + expect(collector.snapshot().records[0]).not.toHaveProperty("traceparent"); + expect(JSON.stringify(collector.snapshot())).not.toContain(TEXT); + collector.dispose(); +}); + +it("bounds its ring and batch, drops export failures without retries, and tears down its clock", async () => { + const send = vi.fn().mockRejectedValue(new Error(TEXT)); + const { h, collector } = setup({ backend: { send } }); + collector.configure({ ...enabled(), exportEnabled: true, endpoint: TARGET }); + for (let i = 0; i < MAX_RECORDS + 50; i++) + h.send("requests", request(WORK, i)); + expect(collector.snapshot().records).toHaveLength(MAX_RECORDS); + expect(collector.snapshot().dropped).toBe(50); + expect(collector.snapshot().records[0]).toMatchObject({ duration_ms: 50 }); + await collector.flush(); + expect(send).toHaveBeenCalledOnce(); + expect(send.mock.calls[0][1]).toHaveLength(BATCH_SIZE); + expect(collector.snapshot().records).toHaveLength(MAX_RECORDS - BATCH_SIZE); + expect(collector.snapshot().dropped).toBe(50 + BATCH_SIZE); + expect(collector.snapshot().error).toBe("export"); + expect(JSON.stringify(collector.snapshot())).not.toContain(TEXT); + collector.configure({ ...enabled(), exportEnabled: false }); + await vi.advanceTimersByTimeAsync(FLUSH_MS * 3); + expect(send).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + collector.dispose(); +}); + +it("does not dispatch or recreate an export timer if opt-out happens during an inspection notification", async () => { + const send = vi.fn(async () => {}); + const { h, collector } = setup({ backend: { send } }); + collector.configure({ ...enabled(), exportEnabled: true, endpoint: TARGET }); + const off = collector.subscribe(() => { + if (collector.snapshot().exporting) + collector.configure({ ...enabled(), enabled: false }); + }); + h.send("requests", request()); + await vi.advanceTimersByTimeAsync(FLUSH_MS); + expect(send).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + expect(h.active()).toBe(0); + expect(collector.snapshot().records).toEqual([]); + off(); + collector.dispose(); +}); + +it("invalidates an in-flight batch and stale callbacks on opt-out without restoring old data", async () => { + let finish!: () => void; + const send = vi.fn( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const { h, collector } = setup({ backend: { send } }); + collector.configure({ + ...enabled(), + tracing: true, + exportEnabled: true, + endpoint: TARGET, + }); + h.send("requests", request()); + h.send("search", start()); + h.send("search", query()); + h.send("search", results()); + const stale = [...h.listeners.get("requests")!][0]; + const running = collector.flush(); + const context = send.mock.calls[0]?.[2] as unknown as { + signal: AbortSignal; + isEligible(): boolean; + }; + expect(context.isEligible()).toBe(true); + collector.configure({ ...enabled(), enabled: false }); + expect(context.signal.aborted).toBe(true); + expect(context.isEligible()).toBe(false); + expect(h.active()).toBe(0); + expect(h.providers.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + const read = vi.fn(); + stale({ + get version() { + read(); + return 1; + }, + }); + expect(read).not.toHaveBeenCalled(); + finish(); + await running; + expect(collector.snapshot().records).toEqual([]); + expect(collector.snapshot().exported).toBe(0); + collector.dispose(); +}); + +it("never buffers, previews or sends raw queryText, labels, filter values or host error bodies", async () => { + const bodies: string[] = []; + const send = vi.fn(async (_target, records) => { + bodies.push(JSON.stringify(records)); + }); + const { h, collector } = setup({ backend: { send } }); + collector.configure({ ...enabled(), exportEnabled: true, endpoint: TARGET }); + h.send("search", start()); + h.send( + "search", + query(undefined, `from:SECRET_FILTER ${TEXT}`, { + filters: { from: "SECRET_FILTER", nested: { queryText: TEXT } }, + }), + ); + h.send("search", results()); + h.send("search", click(undefined, { group: TEXT, label: TEXT, error: TEXT })); + h.send("search", end()); + const records = collector.snapshot().records; + expect(records.some((record) => record.type === "search_query")).toBe(true); + expect( + records.some( + (record) => record.type === "search_click" && record.id === EVENT, + ), + ).toBe(true); + const encoded = JSON.stringify(records); + expect(encoded).not.toContain(TEXT); + expect(encoded).not.toContain("SECRET_FILTER"); + expect(encoded).not.toContain("queryText"); + expect(encoded).not.toContain("label"); + await collector.flush(); + expect(send).toHaveBeenCalledOnce(); + expect(bodies.join("")).not.toContain(TEXT); + expect(bodies.join("")).not.toContain("SECRET_FILTER"); + collector.dispose(); + expect(vi.getTimerCount()).toBe(0); +}); diff --git a/metrics/src/collector.ts b/metrics/src/collector.ts new file mode 100644 index 0000000..c1a4343 --- /dev/null +++ b/metrics/src/collector.ts @@ -0,0 +1,476 @@ +import { + community, + object, + oneOf, + type Own, + type Telemetry, + type Topic, + type TraceContext, + type TraceRequest, +} from "./contract.ts"; +import { DEFAULTS, settings, type Settings } from "./config.ts"; +import { clock, createSearchAggregator, type Clock } from "./search.ts"; +import { + freeze, + projectRequest, + projectUi, + type MetricsRecord, + type RequestCount, +} from "./records.ts"; + +export const MAX_RECORDS = 200; +export const BATCH_SIZE = 25; +export const FLUSH_MS = 10_000; +export type MetricsBackend = Readonly<{ + send( + endpoint: string, + records: readonly MetricsRecord[], + context: { signal: AbortSignal; isEligible(): boolean }, + ): Promise; +}>; +export type Snapshot = Readonly<{ + config: Settings; + active: boolean; + tracing: boolean; + topics: readonly Topic[]; + records: readonly MetricsRecord[]; + dropped: number; + exported: number; + exporting: boolean; + error: "settings" | "export" | undefined; +}>; +export type CollectorOptions = { + telemetry?: Telemetry; + communityReader?: import("./community.ts").CommunityReader; + own: Own; + declaredOrigins: readonly string[]; + backend?: MetricsBackend; + appVersion?: string; + clock?: Clock; +}; + +function trace(): TraceContext | undefined { + try { + const bytes = crypto.getRandomValues(new Uint8Array(24)); + if (bytes.slice(0, 16).every((byte) => byte === 0)) bytes[0] = 1; + if (bytes.slice(16).every((byte) => byte === 0)) bytes[16] = 1; + const hex = (part: Uint8Array) => + [...part].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + // Do not request server sampling. The receiving relay owns its sampler. + return Object.freeze({ + traceparent: `00-${hex(bytes.slice(0, 16))}-${hex(bytes.slice(16))}-00`, + }); + } catch { + return undefined; + } +} + +export function createCollector(options: CollectorOptions) { + const time = options.clock ?? clock; + const appVersion = + options.appVersion && /^[a-zA-Z0-9.+_-]{1,64}$/.test(options.appVersion) + ? options.appVersion + : "unknown"; + let config = DEFAULTS, + allowed = new Set(); + let generation = 0, + disposed = false, + tracing = false, + exporting = false; + let dropped = 0, + exported = 0; + let error: Snapshot["error"]; + const queue: MetricsRecord[] = []; + const counts = new Map(); + const issuedTraces = new Map(); + const topics = new Set(); + const listeners = new Set<() => void>(); + let stops: (() => void)[] = []; + let timer: ReturnType | undefined; + let pending: AbortController | undefined; + let search: ReturnType | undefined; + let searchStop: (() => void) | undefined; + let searchOrigin: string | undefined; + let searchGeneration = 0; + let state: Snapshot = Object.freeze({ + config, + active: false, + tracing: false, + topics: Object.freeze([]), + records: Object.freeze([]), + dropped: 0, + exported: 0, + exporting: false, + error: undefined, + }); + const publish = () => { + state = Object.freeze({ + config, + active: topics.size > 0, + tracing, + topics: Object.freeze([...topics]), + records: Object.freeze([ + ...queue, + ...[...counts.values()].sort((a, b) => + `${a.operation}/${a.outcome}`.localeCompare( + `${b.operation}/${b.outcome}`, + ), + ), + ]), + dropped, + exported, + exporting, + error, + }); + for (const listener of listeners) { + try { + listener(); + } catch { + /* Inspection cannot break collection. */ + } + } + }; + const room = () => { + while (queue.length + counts.size >= MAX_RECORDS) { + if (queue.length) queue.shift(); + else { + const first = counts.keys().next().value; + if (first !== undefined) counts.delete(first); + } + dropped++; + } + }; + const enqueue = (records: readonly MetricsRecord[]) => { + for (const record of records) { + room(); + queue.push(record); + } + publish(); + }; + const stopSearch = () => { + searchGeneration++; + const off = searchStop; + searchStop = undefined; + try { + off?.(); + } catch { + /* Old-host teardown still fails closed. */ + } + search?.dispose(); + search = undefined; + searchOrigin = undefined; + topics.delete("search"); + }; + const stop = () => { + generation++; + stopSearch(); + if (timer !== undefined) time.clear(timer); + timer = undefined; + pending?.abort(); + pending = undefined; + exporting = false; + const owned = stops; + stops = []; + for (const dispose of owned) { + try { + dispose(); + } catch { + /* Fail closed even on old hosts. */ + } + } + topics.clear(); + tracing = false; + queue.length = 0; + counts.clear(); + issuedTraces.clear(); + }; + const flush = async () => { + if ( + disposed || + !config.enabled || + !config.exportEnabled || + !options.backend || + exporting + ) + return; + // Counts have no individual event order or timing. Materialize only their + // bounded, projected aggregates, never raw request events. + const aggregated = [...counts.values()].sort((a, b) => + `${a.operation}/${a.outcome}`.localeCompare( + `${b.operation}/${b.outcome}`, + ), + ); + counts.clear(); + for (const record of aggregated) queue.push(record); + if (!queue.length) return; + const epoch = generation; + const batch = Object.freeze(queue.splice(0, BATCH_SIZE)); + const controller = new AbortController(); + pending = controller; + const target = config.endpoint; + const eligible = () => + !disposed && + config.enabled && + config.exportEnabled && + generation === epoch && + !controller.signal.aborted; + exporting = true; + error = undefined; + publish(); + try { + if (!eligible()) return; + await options.backend.send(target, batch, { + signal: controller.signal, + isEligible: eligible, + }); + if (eligible()) exported += batch.length; + } catch { + if (eligible()) { + dropped += batch.length; + error = "export"; + } + } finally { + // Never restore records or publish an old completion after opt-out/reload. + if (generation === epoch && !disposed) { + exporting = false; + pending = undefined; + publish(); + } + } + }; + const start = () => { + if (!config.enabled || !options.telemetry || !allowed.size) return; + const epoch = generation; + const receive = (topic: Topic, raw: unknown) => { + if (disposed || !config.enabled || generation !== epoch) return; + try { + if (topic === "search") search?.receive(raw); + else if (topic === "ui") { + const record = projectUi(raw, allowed, appVersion); + if (record && config.level === 2) enqueue([record]); + } else { + const value = object(raw), + context = object(value?.traceContext); + const parent = + typeof context?.traceparent === "string" && + issuedTraces.get(context.traceparent) === + community(value?.community) + ? context.traceparent + : undefined; + if (parent) issuedTraces.delete(parent); + const record = projectRequest(raw, allowed, appVersion, parent); + if (record) { + if (config.level === 2) enqueue([record]); + else { + const key = `${record.operation}/${record.outcome}`; + const old = counts.get(key); + if (!old) room(); + counts.set( + key, + freeze({ + schema: 1, + type: "request_count", + level: 1, + app_version: appVersion, + operation: record.operation, + outcome: record.outcome, + count: Math.min(1_000_000_000, (old?.count ?? 0) + 1), + }), + ); + } + } + } + publish(); + } catch { + dropped++; + publish(); + } + }; + for (const topic of ["requests", "ui"] as const) { + try { + stops.push( + options.own(() => + options.telemetry!.subscribe(topic, (event) => + receive(topic, event), + ), + ), + ); + topics.add(topic); + } catch { + /* Missing/newer topics do not prevent supported collection. */ + } + } + // Registering a search observer itself enables host join fields. Admit + // that observer only while the ready selected community is allowlisted. + const syncSearch = () => { + if (disposed || !config.enabled || generation !== epoch) return; + let origin: string | undefined; + try { + origin = community(options.communityReader?.current()); + } catch { + /* Unknown scope is not consent. */ + } + if (!origin || !allowed.has(origin)) { + stopSearch(); + publish(); + return; + } + if (searchOrigin === origin) return; + stopSearch(); + searchOrigin = origin; + const searchEpoch = searchGeneration; + search = createSearchAggregator({ + level: config.level, + allowed, + appVersion, + clock: time, + emit: enqueue, + dropped: () => { + dropped++; + }, + }); + try { + searchStop = options.own(() => + options.telemetry!.subscribe("search", (event) => { + if (searchGeneration === searchEpoch) receive("search", event); + }), + ); + topics.add("search"); + } catch { + search.dispose(); + search = undefined; + } + publish(); + }; + if (options.communityReader) { + try { + stops.push( + options.own(() => options.communityReader!.subscribe(syncSearch)), + ); + syncSearch(); + } catch { + stopSearch(); + } + } + if (config.tracing && options.telemetry.registerTraceContextProvider) { + try { + stops.push( + options.own(() => + options.telemetry!.registerTraceContextProvider!( + (request: TraceRequest) => { + if ( + disposed || + generation !== epoch || + !config.enabled || + !config.tracing + ) + return; + const origin = community(request.community); + if ( + !origin || + !allowed.has(origin) || + !oneOf(request.operation, [ + "query", + "search", + "publish", + "auth", + "media", + "other", + ] as const) || + !oneOf(request.priority, [ + "foreground", + "background", + ] as const) + ) + return; + const context = trace(); + if (context) { + if (issuedTraces.size >= MAX_RECORDS) { + const first = issuedTraces.keys().next().value; + if (first) issuedTraces.delete(first); + } + issuedTraces.set(context.traceparent, origin); + } + return context; + }, + ), + ), + ); + tracing = true; + } catch { + /* Optional context provider fails open. */ + } + } + if (config.exportEnabled && options.backend) { + const schedule = () => { + if ( + disposed || + generation !== epoch || + !config.enabled || + !config.exportEnabled + ) + return; + timer = time.set(() => { + if (disposed || generation !== epoch || !config.enabled) return; + void flush(); + schedule(); + }, FLUSH_MS); + }; + schedule(); + } + }; + return { + snapshot: () => state, + subscribe(listener: () => void) { + if (disposed) return () => {}; + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + configure(input: Settings): boolean { + if (disposed) return false; + let next: Settings | undefined; + try { + next = settings(input, options.declaredOrigins); + } catch { + /* Bad UI/config input is not consent. */ + } + if (!next) { + // A malformed privacy change must not leave the previous collection, + // trace provider or export target running behind an error message. + stop(); + config = DEFAULTS; + allowed = new Set(); + error = "settings"; + publish(); + return false; + } + stop(); + config = next; + allowed = new Set(next.communities); + dropped = 0; + exported = 0; + error = undefined; + start(); + publish(); + return true; + }, + flush, + clear() { + if (disposed) return; + stop(); + start(); + publish(); + }, + dispose() { + if (disposed) return; + disposed = true; + stop(); + config = DEFAULTS; + publish(); + listeners.clear(); + }, + }; +} +export type Collector = ReturnType; diff --git a/metrics/src/community.test.ts b/metrics/src/community.test.ts new file mode 100644 index 0000000..283ef8b --- /dev/null +++ b/metrics/src/community.test.ts @@ -0,0 +1,32 @@ +import { expect, it, vi } from "vitest"; +import { communityReaderCapability } from "./community.ts"; +import { WORK } from "./testkit.ts"; + +it("feature-detects a ready origin:viewer scope rather than guessing from a selected label", () => { + expect(communityReaderCapability(undefined)).toBeUndefined(); + expect(communityReaderCapability({ snapshot() {} })).toBeUndefined(); + const viewer = "a".repeat(64); + let value: unknown = { status: "ready", scope: `${WORK}:${viewer}`, viewer }; + const subscribe = vi.fn(() => () => {}); + const reader = communityReaderCapability({ + snapshot: () => value, + subscribe, + })!; + expect(reader.current()).toBe(WORK); + for (const invalid of [ + { status: "connecting", scope: `${WORK}:${viewer}`, viewer }, + { status: "ready", scope: WORK, viewer }, + { status: "ready", scope: `${WORK}:${"b".repeat(64)}`, viewer }, + { status: "ready", scope: `http://work.example:${viewer}`, viewer }, + { status: "ready", scope: `${WORK}/personal:${viewer}`, viewer }, + { status: "ready", scope: `${WORK}:${viewer}` }, + { status: "ready", selected: WORK }, + ]) { + value = invalid; + expect(reader.current()).toBeUndefined(); + } + const change = () => {}; + const off = reader.subscribe(change); + expect(subscribe).toHaveBeenCalledWith(change); + off(); +}); diff --git a/metrics/src/community.ts b/metrics/src/community.ts new file mode 100644 index 0000000..ed4c338 --- /dev/null +++ b/metrics/src/community.ts @@ -0,0 +1,39 @@ +import { community, object } from "./contract.ts"; + +export type CommunityReader = Readonly<{ + current(): string | undefined; + subscribe(listener: () => void): () => void; +}>; +/** Controls subscription admission, never attribution of a completed sample. + * Ready RelayData snapshots bind origin:viewer; reject stale/unknown shapes. */ +export function communityReaderCapability( + value: unknown, +): CommunityReader | undefined { + const relay = value as + | { snapshot?(): unknown; subscribe?(listener: () => void): () => void } + | undefined; + if ( + !relay || + typeof relay.snapshot !== "function" || + typeof relay.subscribe !== "function" + ) + return; + return { + current() { + const snapshot = object(relay.snapshot!()); + if ( + snapshot?.status !== "ready" || + typeof snapshot.scope !== "string" || + typeof snapshot.viewer !== "string" || + !/^[0-9a-f]{64}$/.test(snapshot.viewer) + ) + return; + const at = snapshot.scope.lastIndexOf(":"); + if (at < 0 || snapshot.scope.slice(at + 1) !== snapshot.viewer) return; + return community(snapshot.scope.slice(0, at)); + }, + subscribe(listener) { + return relay.subscribe!(listener); + }, + }; +} diff --git a/metrics/src/config.ts b/metrics/src/config.ts new file mode 100644 index 0000000..ececf2a --- /dev/null +++ b/metrics/src/config.ts @@ -0,0 +1,67 @@ +import { community } from "./contract.ts"; +export type Settings = Readonly<{ + enabled: boolean; + level: 1 | 2; + communities: readonly string[]; + tracing: boolean; + exportEnabled: boolean; + endpoint: string; +}>; +export const DEFAULTS: Settings = Object.freeze({ + enabled: false, + level: 1, + communities: Object.freeze([]), + tracing: false, + exportEnabled: false, + endpoint: "", +}); +export function endpoint( + value: string, + origins: readonly string[], +): string | undefined { + if (!value || value.length > 2048) return; + try { + const url = new URL(value); + if ( + url.protocol !== "https:" || + url.username || + url.password || + url.search || + url.hash || + !origins.includes(url.origin) + ) + return; + return url.href; + } catch { + return undefined; + } +} +export function settings( + input: Settings, + declaredOrigins: readonly string[], +): Settings | undefined { + if (input.level !== 1 && input.level !== 2) return; + if (!Array.isArray(input.communities) || input.communities.length > 16) + return; + const allowed: string[] = []; + for (const raw of input.communities) { + const origin = community(raw); + if (!origin) return; + if (!allowed.includes(origin)) allowed.push(origin); + } + if (input.enabled && !allowed.length) return; + if (typeof input.endpoint !== "string") return; + const target = input.endpoint + ? endpoint(input.endpoint, declaredOrigins) + : ""; + if (input.endpoint && !target) return; + if (input.exportEnabled && !target) return; + return Object.freeze({ + enabled: input.enabled === true, + level: input.level, + communities: Object.freeze(allowed), + tracing: input.tracing === true && input.level === 2, + exportEnabled: input.exportEnabled === true, + endpoint: target ?? "", + }); +} diff --git a/metrics/src/contract.ts b/metrics/src/contract.ts new file mode 100644 index 0000000..1201b0a --- /dev/null +++ b/metrics/src/contract.ts @@ -0,0 +1,96 @@ +import type { Context, HostRequest, HostResponse } from "@buzz/author"; + +export type Topic = "requests" | "ui" | "search"; +export type TraceRequest = Readonly<{ + community: string; + operation: string; + priority: string; +}>; +export type TraceContext = Readonly<{ traceparent: string }>; +export type Telemetry = Readonly<{ + subscribe(topic: Topic, listener: (event: unknown) => void): () => void; + registerTraceContextProvider?: ( + provider: (request: TraceRequest) => TraceContext | undefined, + ) => () => void; +}>; +export type ProtectedHost = Readonly<{ + requestOnce( + input: HostRequest, + options: { callId: string; isEligible(): boolean }, + ): Promise; +}>; +export type Own = (setup: () => () => void) => () => void; + +/** Old author types intentionally remain pinned: optional new services are + * discovered structurally, never required in inject on older hosts. */ +export function capability(ctx: Context, name: string): unknown { + try { + return (ctx.reflect as unknown as { get(name: string): unknown }).get(name); + } catch { + return undefined; + } +} +export function telemetryCapability(value: unknown): Telemetry | undefined { + if ( + !value || + typeof value !== "object" || + typeof (value as Telemetry).subscribe !== "function" + ) + return; + return value as Telemetry; +} +export function protectedHostCapability( + value: unknown, +): ProtectedHost | undefined { + if ( + !value || + typeof value !== "object" || + typeof (value as ProtectedHost).requestOnce !== "function" + ) + return; + return value as ProtectedHost; +} +export function object(value: unknown): Record | undefined { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; +} +export function oneOf( + value: unknown, + values: T, +): T[number] | undefined { + return typeof value === "string" && values.includes(value) + ? value + : undefined; +} +export function count(value: unknown, max = 1_000_000_000): number | undefined { + return typeof value === "number" && + Number.isFinite(value) && + value >= 0 && + value <= max + ? Math.round(value) + : undefined; +} +export function id(value: unknown): string | undefined { + return typeof value === "string" && /^[a-zA-Z0-9._:-]{1,128}$/.test(value) + ? value + : undefined; +} +export function community(value: unknown): string | undefined { + if (typeof value !== "string" || value.length > 256) return; + try { + const url = new URL(value.replace(/^wss:/, "https:")); + if ( + url.protocol !== "https:" || + url.username || + url.password || + url.search || + url.hash || + !["", "/"].includes(url.pathname) + ) + return; + return url.origin; + } catch { + return undefined; + } +} diff --git a/metrics/src/index.tsx b/metrics/src/index.tsx new file mode 100644 index 0000000..7be6664 --- /dev/null +++ b/metrics/src/index.tsx @@ -0,0 +1,291 @@ +import type { Context } from "@buzz/author"; +import type { ComponentType, ReactNode } from "react"; +import manifest from "../manifest.json"; +import { + capability, + protectedHostCapability, + telemetryCapability, +} from "./contract.ts"; +import { createCollector } from "./collector.ts"; +import { hostBackend } from "./backend.ts"; +import { messageMetrics } from "./records.ts"; +import { communityReaderCapability } from "./community.ts"; + +// Telemetry, shared UI and protected export are optional for older-host safety. +export const inject = ["react", "pages", "settingsCards"]; +type Ui = { + Button: ComponentType<{ + children?: ReactNode; + onClick?: () => void; + disabled?: boolean; + variant?: "prominent" | "subtle" | "ghost"; + "aria-label"?: string; + }>; + Input: ComponentType<{ + value: string; + onValueChange(value: string): void; + "aria-label"?: string; + maxLength?: number; + }>; + Field: ComponentType<{ + label: ReactNode; + description?: ReactNode; + children?: ReactNode; + }>; + Switch: ComponentType<{ + label: string; + checked: boolean; + disabled?: boolean; + onCheckedChange(value: boolean): void; + }>; +}; +function uiCapability(value: unknown): Ui | undefined { + if (!value || typeof value !== "object") return; + const ui = value as Ui; + return [ui.Button, ui.Input, ui.Field, ui.Switch].every( + (component) => typeof component === "function", + ) + ? ui + : undefined; +} + +export function apply(ctx: Context) { + const React = ctx.react; + const telemetry = telemetryCapability(capability(ctx, "telemetry")); + const ui = uiCapability(capability(ctx, "ui")); + const origins: readonly string[] = manifest.host.networkOrigins; + const backend = hostBackend( + protectedHostCapability(capability(ctx, "host")), + origins, + ); + const collector = createCollector({ + telemetry, + communityReader: communityReaderCapability(capability(ctx, "relay")), + own: (setup) => ctx.effect(setup), + declaredOrigins: origins, + backend, + }); + ctx.effect(() => () => collector.dispose()); + + function MetricsSettings() { + const state = React.useSyncExternalStore( + collector.subscribe, + collector.snapshot, + ); + const [communities, setCommunities] = React.useState( + state.config.communities.join(", "), + ); + const [target, setTarget] = React.useState(state.config.endpoint); + const level = state.config.level; + const rates = messageMetrics(state.records); + if (!ui) + return ( +
+

Buzz Metrics

+

+ This host lacks shared plugin controls. Collection stays off; update + the host to opt in. +

+
+ ); + return ( +
+

Buzz Metrics

+

+ Collection, tracing and export start off and reset when this plugin + reloads. No disk storage. Closing this page does not stop enabled + collection. Turning collection off discards all pending records and + short-lived raw query state; data already received by a backend cannot + be recalled. +

+ {!telemetry && ( +

+ This host has no telemetry service. No collection is active. +

+ )} + + + +
+

+ Granularity: {level === 1 ? "Counts" : "Linked"}. Level 3 query-text + export is not implemented. Level changes apply immediately and clear + pending data. +

+ collector.configure({ ...state.config, level: 1 })} + variant={level === 1 ? "prominent" : "subtle"} + > + Level 1 — Counts + + collector.configure({ ...state.config, level: 2 })} + variant={level === 2 ? "prominent" : "subtle"} + > + Level 2 — Linked + +
+

+ Counts contains aggregate request counts and search-session totals, + not query IDs, timings or query order. Linked adds request timings, + ephemeral search joins, shapes and activation metadata, including + opened message event IDs and positions that a backend may link to + accessible content. Raw query text, result labels, filter values and + message content never enter the record buffer, preview or export. +

+

+ Search observes only a ready allowlisted selection. While observed, + the host may attach its ephemeral search join IDs in that community, + including Counts; Counts omits those IDs from plugin records. +

+ + + +
+ + collector.configure({ + ...state.config, + communities: communities + .split(",") + .map((value) => value.trim()) + .filter(Boolean), + endpoint: target.trim(), + level, + }) + } + > + Apply settings and clear pending data + + + collector.configure({ ...state.config, enabled }) + } + /> + + collector.configure({ ...state.config, tracing }) + } + /> + + collector.configure({ ...state.config, exportEnabled }) + } + /> +
+ {state.error && ( +

+ {state.error === "settings" + ? "Settings were not applied; collection was stopped and pending data cleared. Correct and Apply the community/backend text fields first, then enable collection. Use exact HTTPS community origins and, for export, a declared backend origin." + : "An export batch was dropped. It will not be retried."} +

+ )} +

+ Collection {state.active ? "ON" : "OFF"} · topics:{" "} + {state.topics.join(", ") || "none"} · {state.records.length}/200 + waiting · {state.exported} exported · {state.dropped} dropped +

+

+ Draft host coverage: unscoped UI timings are dropped because their + community is unknown. Current search events prove dispatch only when + relay-ranked rows arrive, so unproven empty/failed searches are not + counted eligible. Server-side trace/search joins are a relay + follow-up. This draft reports app version as unknown. +

+
+ { + void collector.flush(); + }} + disabled={ + !state.config.enabled || + !state.config.exportEnabled || + !backend || + state.exporting + } + > + Send one batch + + collector.clear()}> + Clear pending data + +
+

Queued message-search metrics — incomplete coverage

+

+ Navigation-only sessions are retained but excluded from these rates. + On current hosts, eligibility is proven only by relay-ranked results; + unproven empty/failed searches are omitted. These are not overall + search-quality rates. In the current queue: {rates.eligible} settled + eligible searches; {rates.opened} opened. Message open rate:{" "} + {rates.open_rate === null + ? "not enough data" + : `${Math.round(rates.open_rate * 100)}%`} + . Session success:{" "} + {rates.session_success === null + ? "not enough data" + : `${Math.round(rates.session_success * 100)}%`} + . +

+

Redacted export preview

+
+          {JSON.stringify(state.records, null, 2)}
+        
+
+ ); + } + ctx.settingsCards.register({ + id: "metrics", + title: "Metrics", + group: "Privacy", + component: MetricsSettings, + }); + ctx.pages.register({ + id: "main", + title: "Metrics preview", + primary: true, + component: MetricsSettings, + }); +} diff --git a/metrics/src/plugin.test.tsx b/metrics/src/plugin.test.tsx new file mode 100644 index 0000000..63b4a79 --- /dev/null +++ b/metrics/src/plugin.test.tsx @@ -0,0 +1,244 @@ +// @vitest-environment jsdom +import * as React from "react"; +import { Context } from "@deepseek-ai/cordis"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { apply, inject } from "./index.tsx"; +import { + click, + end, + host, + query, + request, + results, + start, + TEXT, + WORK, +} from "./testkit.ts"; + +const ui = { + Button: ({ + children, + onClick, + disabled, + }: { + children?: React.ReactNode; + onClick?: () => void; + disabled?: boolean; + }) => ( + + ), + Input: ({ + value, + onValueChange, + "aria-label": label, + }: { + value: string; + onValueChange(value: string): void; + "aria-label"?: string; + }) => ( + onValueChange(event.currentTarget.value)} + /> + ), + Field: ({ + label, + description, + children, + }: { + label: React.ReactNode; + description?: React.ReactNode; + children?: React.ReactNode; + }) => ( +
+

{label}

+

{description}

+ {children} +
+ ), + Switch: ({ + label, + checked, + onCheckedChange, + disabled, + }: { + label: string; + checked: boolean; + disabled?: boolean; + onCheckedChange(value: boolean): void; + }) => ( + + ), +}; +function provide(ctx: Context, name: string, value: unknown) { + ctx.provide(name, value); +} +async function setup(withTelemetry = true) { + const root = new Context(), + h = host(); + let Page: React.ComponentType = () => null; + const cards: { id: string; group: string }[] = []; + provide(root, "react", React); + provide(root, "ui", ui); + const scopes = new Set<() => void>(); + const viewer = "a".repeat(64); + provide(root, "relay", { + snapshot: () => ({ status: "ready", scope: `${WORK}:${viewer}`, viewer }), + subscribe(listener: () => void) { + scopes.add(listener); + return () => { + scopes.delete(listener); + }; + }, + }); + provide(root, "pages", { + register(value: { component: React.ComponentType }) { + Page = value.component; + }, + }); + provide(root, "settingsCards", { + register(value: { id: string; group: string }) { + cards.push(value); + }, + }); + if (withTelemetry) provide(root, "telemetry", h.telemetry); + const fiber = root.plugin((ctx: Context) => apply(ctx)); + await fiber.await(); + return { root, fiber, h, cards, scopes, view: () => render() }; +} +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +it("uses optional host telemetry rather than a hard injection and renders a safe older-host state", async () => { + expect(inject).not.toContain("telemetry"); + const f = await setup(false); + f.view(); + expect(screen.getByText(/This host has no telemetry service/)).toBeDefined(); + expect( + ( + screen.getByRole("checkbox", { + name: "Enable collection for this activation", + }) as HTMLInputElement + ).disabled, + ).toBe(true); + expect(f.h.subscribe).not.toHaveBeenCalled(); + await act(() => f.fiber.dispose()); + await f.root.fiber.dispose(); +}); + +it("requires settings then explicit opt-in, shows only redacted records, and scope-disposes listeners/providers/timers", async () => { + vi.useFakeTimers(); + const f = await setup(); + f.view(); + expect(f.scopes.size).toBe(0); + expect(f.cards).toEqual([ + expect.objectContaining({ id: "metrics", group: "Privacy" }), + ]); + expect(f.h.active()).toBe(0); + expect(f.h.providers.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + fireEvent.click( + screen.getByRole("checkbox", { + name: "Enable collection for this activation", + }), + ); + expect(f.h.active()).toBe(0); + expect(screen.getByRole("alert").textContent).toContain( + "Settings were not applied", + ); + fireEvent.change(screen.getByLabelText("Allowed communities"), { + target: { value: WORK }, + }); + fireEvent.click(screen.getByRole("button", { name: "Level 2 — Linked" })); + fireEvent.click( + screen.getByRole("button", { + name: "Apply settings and clear pending data", + }), + ); + expect(f.h.active()).toBe(0); + fireEvent.click( + screen.getByRole("checkbox", { + name: "Enable collection for this activation", + }), + ); + expect(f.h.active()).toBe(3); + fireEvent.click( + screen.getByRole("checkbox", { + name: "Attach trace context to allowed relay requests", + }), + ); + expect(f.h.providers.size).toBe(1); + act(() => { + f.h.send("requests", request()); + f.h.send("search", start()); + f.h.send("search", query()); + f.h.send("search", results()); + f.h.send("search", click()); + f.h.send("search", end()); + }); + const preview = + screen.getByLabelText("Redacted metrics preview").textContent ?? ""; + expect(preview).toContain("search_query"); + expect(preview).toContain("search_click"); + expect(preview).not.toContain(TEXT); + expect(preview).not.toContain("queryText"); + expect( + ( + screen.getByRole("checkbox", { + name: "Export redacted batches to the configured backend", + }) as HTMLInputElement + ).disabled, + ).toBe(true); + expect(screen.getByText(/Queued message-search metrics/)).toBeDefined(); + // Granularity is an immediate privacy control, not a misleading draft + // label while the previous Linked configuration keeps collecting. + fireEvent.click(screen.getByRole("button", { name: "Level 1 — Counts" })); + expect(screen.getByLabelText("Redacted metrics preview").textContent).toBe( + "[]", + ); + expect(f.h.providers.size).toBe(0); + act(() => f.h.send("requests", request())); + const counts = + screen.getByLabelText("Redacted metrics preview").textContent ?? ""; + expect(counts).toContain("request_count"); + expect(counts).not.toMatch( + /query_id|session_id|traceparent|duration_ms|community/, + ); + fireEvent.click(screen.getByRole("button", { name: "Level 2 — Linked" })); + act(() => { + f.h.send("requests", request()); + f.h.send("search", start()); + f.h.send("search", query()); + f.h.send("search", results()); + }); + expect(vi.getTimerCount()).toBeGreaterThan(0); + await act(() => f.fiber.dispose()); + expect(f.scopes.size).toBe(0); + expect(f.h.active()).toBe(0); + expect(f.h.providers.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + expect(screen.getByLabelText("Redacted metrics preview").textContent).toBe( + "[]", + ); + await f.root.fiber.dispose(); +}); diff --git a/metrics/src/records.ts b/metrics/src/records.ts new file mode 100644 index 0000000..f5d9693 --- /dev/null +++ b/metrics/src/records.ts @@ -0,0 +1,382 @@ +import { community, count, object, oneOf } from "./contract.ts"; + +export const GROUPS = [ + "messages", + "channels", + "people", + "agents", + "chats", + "direct_messages", + "pages", + "recents", + "unread", + "settings", + "plugins", + "other", +] as const; +export type Group = (typeof GROUPS)[number]; +export const BUCKETS = ["1", "2", "3", "4-5", "6-10", "11+"] as const; +export type Bucket = (typeof BUCKETS)[number]; +export type Scope = "global" | "conversation"; +export type Outcome = + | "results" + | "empty" + | "failed" + | "superseded" + | "unsettled"; +export type Relation = + | "extends" + | "shortens" + | "edits" + | "new" + | "same" + | "refilter"; +export const OPERATORS = [ + "from", + "in", + "after", + "before", + "on", + "during", +] as const; +export type Operator = (typeof OPERATORS)[number]; +export type Shape = Readonly<{ + char_count: number; + word_count: number; + quoted: boolean; + has_url: boolean; + operators: readonly Operator[]; +}>; +type Base = Readonly<{ schema: 1; app_version: string }>; +export type RequestRecord = Base & + Readonly<{ + type: "request"; + level: 2; + community: string; + operation: string; + priority: "foreground" | "background"; + duration_ms: number; + bytes: number; + outcome: string; + traceparent?: string; + }>; +export type RequestCount = Base & + Readonly<{ + type: "request_count"; + level: 1; + operation: string; + outcome: string; + count: number; + }>; +export type UiRecord = Base & + Readonly<{ + type: "ui"; + level: 2; + community: string; + operation: "channel_open_to_visible_rows"; + trigger: "click" | "keyboard"; + duration_ms: number; + outcome: "ok" | "empty" | "error"; + }>; +export type OpenCount = Readonly<{ + group: Group; + position: Bucket; + count: number; +}>; +export type SessionRecord = Base & + Readonly<{ + type: "search_session"; + level: 1 | 2; + session_id?: string; + eligible: number; + eligible_empty: number; + eligible_failed: number; + eligible_opened: number; + navigation_session: boolean; + reason: + | "closed" + | "scope_changed" + | "disposed" + | "subscribers_changed" + | "other"; + opens: readonly OpenCount[]; + event_count?: number; + truncated?: boolean; + queries: number; + superseded: number; + unsettled: number; + actions: number; + }>; +export type QueryRecord = Base & + Shape & + Readonly<{ + type: "search_query"; + level: 2; + session_id: string; + seq: number; + query_id: string; + attempt: number; + scope: Scope; + outcome: Outcome; + relation: Relation; + since_previous: number | null; + previous_query_id: string | null; + }>; +export type ClickRecord = Base & + Readonly<{ + type: "search_click"; + level: 2; + session_id: string; + seq: number; + query_id: string; + attempt: number; + kind: "open" | "action"; + group: Group; + position: number; + id?: string; + relay_rank?: number; + below_messages?: boolean; + source?: "relay" | "device" | "local" | "unknown"; + }>; +export type MetricsRecord = + | RequestRecord + | RequestCount + | UiRecord + | SessionRecord + | QueryRecord + | ClickRecord; + +export function messageMetrics(records: readonly MetricsRecord[]) { + let eligible = 0, + opened = 0, + sessions = 0, + successful = 0; + for (const record of records) { + if ( + record.type !== "search_session" || + record.navigation_session || + record.eligible === 0 + ) + continue; + eligible += record.eligible; + opened += record.eligible_opened; + sessions++; + if (record.eligible_opened > 0) successful++; + } + return Object.freeze({ + eligible, + opened, + sessions, + successful, + open_rate: eligible ? opened / eligible : null, + session_success: sessions ? successful / sessions : null, + }); +} + +export function uuid(value: unknown): string | undefined { + return typeof value === "string" && + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test( + value, + ) + ? value + : undefined; +} +export function eventId(value: unknown): string | undefined { + return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) + ? value + : undefined; +} +export function positive(value: unknown, max = 10_000): number | undefined { + const n = count(value, max); + return n !== undefined && n >= 1 && n === value ? n : undefined; +} +export function group(value: unknown): Group { + switch (value) { + case "Messages": + return "messages"; + case "Channels": + return "channels"; + case "People": + return "people"; + case "Agents": + return "agents"; + case "Chats": + return "chats"; + case "Direct messages": + return "direct_messages"; + case "Pages": + return "pages"; + case "Recents": + return "recents"; + case "Unread": + return "unread"; + case "Settings": + return "settings"; + case "Plugins": + return "plugins"; + default: + return "other"; + } +} +export function bucket(position: number): Bucket { + return position <= 3 + ? (String(position) as Bucket) + : position <= 5 + ? "4-5" + : position <= 10 + ? "6-10" + : "11+"; +} +export function freeze(record: T): T { + return Object.freeze(record); +} + +/** No raw payload object or arbitrary string is ever copied to a record. */ +export function projectRequest( + raw: unknown, + allowed: ReadonlySet, + appVersion: string, + ownedTrace?: string, +): RequestRecord | undefined { + const value = object(raw); + if (value?.version !== 1 || value.type !== "request") return; + const origin = community(value.community); + if (!origin || !allowed.has(origin)) return; + const operation = oneOf(value.operation, [ + "query", + "search", + "publish", + "auth", + "media", + "other", + ] as const); + const priority = oneOf(value.priority, ["foreground", "background"] as const); + const outcome = oneOf(value.outcome, [ + "ok", + "timeout", + "rate_limited", + "http_5xx", + "aborted", + "network", + ] as const); + const duration = count(value.durationMs, 3_600_000), + bytes = count(value.bytes); + if ( + !operation || + !priority || + !outcome || + duration === undefined || + bytes === undefined + ) + return; + return freeze({ + schema: 1, + type: "request", + level: 2, + app_version: appVersion, + community: origin, + operation, + priority, + duration_ms: duration, + bytes, + outcome, + ...(ownedTrace ? { traceparent: ownedTrace } : {}), + }); +} +export function projectUi( + raw: unknown, + allowed: ReadonlySet, + appVersion: string, +): UiRecord | undefined { + const value = object(raw); + if (value?.version !== 1 || value.type !== "uiTiming") return; + // Current host v1 lacks this authority. Never guess from selected community. + const origin = community(value.community); + if ( + !origin || + !allowed.has(origin) || + value.operation !== "channel_open_to_visible_rows" + ) + return; + const trigger = oneOf(value.trigger, ["click", "keyboard"] as const); + const outcome = oneOf(value.outcome, ["ok", "empty", "error"] as const); + const duration = count(value.durationMs, 3_600_000); + if (!trigger || !outcome || duration === undefined) return; + return freeze({ + schema: 1, + type: "ui", + level: 2, + app_version: appVersion, + community: origin, + operation: "channel_open_to_visible_rows", + trigger, + outcome, + duration_ms: duration, + }); +} + +/** Only short-lived aggregation state may hold body/signature. Shape is safe. */ +export function queryParts( + text: string, + rawFilters: unknown, +): { body: string; signature: string; shape: Shape } { + const filters = object(rawFilters) ?? {}; + const values = ["from", "in", "since", "until", "channelId"].map((key) => { + const value = filters[key]; + return typeof value === "string" + ? value.slice(0, 256) + : typeof value === "number" && Number.isFinite(value) + ? value + : null; + }); + const names = new Set(); + const body = text + .replace( + /(?:^|\s)(from|in|after|before|on|during):(?:"[^"\n]*"|\S+)/gi, + (whole, name: string) => { + const operator = name.toLowerCase() as Operator; + const accepted = + operator === "from" + ? values[0] !== null + : operator === "in" + ? values[1] !== null + : operator === "after" + ? values[2] !== null + : values[3] !== null; + if (!accepted) return whole; + names.add(operator); + return " "; + }, + ) + .trim() + .replace(/\s+/g, " ") + .toLowerCase(); + const words = body.match(/[\p{L}\p{N}_-]+/gu) ?? []; + return { + body, + signature: JSON.stringify(values), + shape: Object.freeze({ + char_count: body.length, + word_count: words.length, + quoted: /"/.test(body), + has_url: /https?:\/\/|www\./i.test(body), + operators: Object.freeze(OPERATORS.filter((name) => names.has(name))), + }), + }; +} +export function relation( + previous: { body: string; signature: string } | undefined, + current: { body: string; signature: string }, +): Relation { + if (!previous) return "new"; + if (previous.body === current.body) + return previous.signature === current.signature ? "same" : "refilter"; + if (previous.body && current.body.startsWith(previous.body)) return "extends"; + if (current.body && previous.body.startsWith(current.body)) return "shortens"; + const old = new Set(previous.body.match(/[\p{L}\p{N}_-]+/gu) ?? []); + return (current.body.match(/[\p{L}\p{N}_-]+/gu) ?? []).some((word) => + old.has(word), + ) + ? "edits" + : "new"; +} diff --git a/metrics/src/search.test.ts b/metrics/src/search.test.ts new file mode 100644 index 0000000..864b943 --- /dev/null +++ b/metrics/src/search.test.ts @@ -0,0 +1,472 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { + createSearchAggregator, + MAX_SESSION_RECORDS, + MAX_SESSIONS, + RELATION_MS, + SETTLE_MS, +} from "./search.ts"; +import { messageMetrics, type MetricsRecord } from "./records.ts"; +import { + click, + end, + fakeClock, + PERSONAL, + query, + results, + sid, + start, + TEXT, + WORK, +} from "./testkit.ts"; + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(0); +}); +afterEach(() => vi.useRealTimers()); +function setup(level: 1 | 2 = 2) { + const records: MetricsRecord[] = []; + const dropped = vi.fn(); + const search = createSearchAggregator({ + level, + allowed: new Set([WORK]), + appVersion: "unknown", + clock: fakeClock, + emit: (batch) => records.push(...batch), + dropped, + }); + return { search, records, dropped }; +} + +it.each([SETTLE_MS - 1, SETTLE_MS])( + "requires finished results to remain for 2s or be acted on (%i)", + async (wait) => { + const { search, records } = setup(); + search.receive(start()); + search.receive(query()); + search.receive(results()); + await vi.advanceTimersByTimeAsync(wait); + expect(records).toEqual([]); // Nothing can escape before the navigation-session flag is known. + search.receive(end()); + const summary = records.find((record) => record.type === "search_session"); + expect(summary).toMatchObject({ + eligible: wait < SETTLE_MS ? 0 : 1, + eligible_empty: 0, + eligible_failed: 0, + eligible_opened: 0, + }); + expect( + records.find((record) => record.type === "search_query"), + ).toMatchObject({ outcome: wait < SETTLE_MS ? "unsettled" : "results" }); + expect(JSON.stringify(records)).not.toContain(TEXT); + search.dispose(); + expect(vi.getTimerCount()).toBe(0); + }, +); + +it.each([ + { level: 1 as const, wait: 500 }, + { level: 1 as const, wait: 2500 }, + { level: 2 as const, wait: 500 }, + { level: 2 as const, wait: 2500 }, +])( + "coalesces host re-evaluations of one query at Level $level after $wait ms", + async ({ level, wait }) => { + const { search, records } = setup(level); + search.receive(start()); + search.receive(query()); + search.receive(results()); + await vi.advanceTimersByTimeAsync(wait); + search.receive(query(sid(2), TEXT, { attempt: 2 })); + expect(vi.getTimerCount()).toBe(level === 2 ? 1 : 0); // Raw expiry only; old settle wait is retired. + search.receive(results(sid(2), { attempt: 2 })); + search.receive(click(sid(2), { attempt: 2 })); + search.receive(end()); + expect( + records.filter((record) => record.type === "search_session"), + ).toEqual([ + expect.objectContaining({ + queries: 1, + eligible: 1, + eligible_opened: 1, + superseded: 0, + }), + ]); + expect(messageMetrics(records)).toMatchObject({ + eligible: 1, + opened: 1, + open_rate: 1, + session_success: 1, + }); + const queries = records.filter((record) => record.type === "search_query"); + if (level === 2) + expect(queries).toEqual([ + expect.objectContaining({ + query_id: sid(2), + attempt: 2, + seq: 1, + relation: "new", + previous_query_id: null, + }), + ]); + else expect(queries).toEqual([]); + search.dispose(); + expect(vi.getTimerCount()).toBe(0); + }, +); + +it("does not settle a re-evaluation from an old attempt's late result", async () => { + const { search, records } = setup(); + search.receive(start()); + search.receive(query()); + search.receive(results()); + await vi.advanceTimersByTimeAsync(500); + search.receive(query(sid(2), TEXT, { attempt: 2 })); + search.receive(results()); // Late attempt 1 must not mark attempt 2 finished. + await vi.advanceTimersByTimeAsync(SETTLE_MS); + search.receive(end()); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ queries: 1, eligible: 0, superseded: 0, unsettled: 1 }); + expect( + records.find((record) => record.type === "search_query"), + ).toMatchObject({ attempt: 2, outcome: "unsettled" }); + search.dispose(); +}); + +it("settles an opened message immediately and preserves exact ephemeral joins with bucketed counts", () => { + const { search, records } = setup(); + search.receive(start()); + search.receive(query(sid(2), TEXT, { attempt: 3 })); + search.receive(results(sid(2), { attempt: 3 })); + search.receive(click(sid(2), { attempt: 3, position: 5 })); + search.receive(end()); + expect( + records.find((record) => record.type === "search_click"), + ).toMatchObject({ + session_id: sid(1), + query_id: sid(2), + attempt: 3, + kind: "open", + position: 5, + relay_rank: 1, + }); + expect( + records.find((record) => record.type === "search_query"), + ).toMatchObject({ query_id: sid(2), attempt: 3, outcome: "results" }); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ + eligible: 1, + eligible_opened: 1, + opens: [{ group: "messages", position: "4-5", count: 1 }], + }); + search.dispose(); +}); + +it.each(["empty", "failed"] as const)( + "counts proven %s dispatches but never guesses dispatch for today's unmarked empty host events", + async (kind) => { + const { search, records } = setup(); + search.receive(start()); + search.receive(query(sid(2), TEXT, { messageSearch: true })); + search.receive( + results(sid(2), { + outcome: kind === "failed" ? "error" : "ok", + groups: [], + }), + ); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + search.receive(end()); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ + eligible: 1, + eligible_empty: kind === "empty" ? 1 : 0, + eligible_failed: kind === "failed" ? 1 : 0, + }); + expect( + records.find((record) => record.type === "search_query"), + ).toMatchObject({ outcome: kind }); + records.length = 0; + search.receive(start(sid(3))); + search.receive(query(sid(4), TEXT, { sessionId: sid(3) })); + search.receive( + results(sid(4), { + sessionId: sid(3), + outcome: kind === "failed" ? "error" : "ok", + groups: [], + }), + ); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + search.receive(end(sid(3))); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ eligible: 0, eligible_empty: 0, eligible_failed: 0 }); + expect(records.some((record) => record.type === "search_query")).toBe( + false, + ); + search.dispose(); + }, +); + +it("excludes no-query dialogs and flags navigation-only sessions without losing their opens", async () => { + const { search, records } = setup(); + search.receive(start()); + search.receive(end()); + expect(records).toEqual([]); + search.receive(start()); + search.receive( + query(sid(2), "from:me", { filters: { from: "me" }, messageSearch: true }), + ); + search.receive(end()); + expect(records).toEqual([ + expect.objectContaining({ type: "search_session", eligible: 0 }), + ]); + records.length = 0; + search.receive(start()); + search.receive(query()); + search.receive(results()); + search.receive(query(sid(3), `${TEXT} more`, { messageSearch: true })); + search.receive(results(sid(3))); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + search.receive( + click(sid(3), { + kind: "channel", + eventId: null, + relayRank: null, + group: "Channels", + belowMessages: true, + }), + ); + search.receive(end()); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ + navigation_session: true, + opens: [{ group: "channels", position: "1", count: 1 }], + }); + expect( + records.find((record) => record.type === "search_click"), + ).toMatchObject({ kind: "open", group: "channels", below_messages: true }); + expect(messageMetrics(records)).toMatchObject({ + eligible: 0, + sessions: 0, + open_rate: null, + session_success: null, + }); + records.length = 0; + search.receive(start()); + search.receive(query()); + search.receive(results()); + search.receive( + click(sid(2), { + kind: "action", + group: "Pages", + eventId: null, + relayRank: null, + belowMessages: true, + }), + ); + search.receive(click()); + search.receive(end()); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ + eligible: 1, + eligible_opened: 1, + actions: 1, + navigation_session: false, + }); + expect(messageMetrics(records)).toMatchObject({ + eligible: 1, + opened: 1, + sessions: 1, + successful: 1, + open_rate: 1, + session_success: 1, + }); + search.dispose(); +}); + +it("classifies query relations across dialogs for only 30s and never exports filter values", async () => { + const { search, records } = setup(); + const issue = async (n: number, text: string, filters = {}) => { + search.receive(start(sid(n))); + search.receive( + query(sid(n + 100), text, { + sessionId: sid(n), + filters, + messageSearch: true, + }), + ); + search.receive(results(sid(n + 100), { sessionId: sid(n) })); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + search.receive(end(sid(n))); + }; + await issue(1, "deploy"); + await issue(2, "deploy production"); + await issue(3, "deploy"); + await issue(4, "again deploy"); + await issue(5, "other words"); + await issue(6, "other words"); + await issue(7, "from:SECRET_FILTER other words", { from: "SECRET_FILTER" }); + const queries = records.filter((record) => record.type === "search_query"); + expect(queries.map((record) => record.relation)).toEqual([ + "new", + "extends", + "shortens", + "edits", + "new", + "same", + "refilter", + ]); + expect(queries[1]).toMatchObject({ + previous_query_id: sid(101), + since_previous: SETTLE_MS, + }); + expect(JSON.stringify(records)).not.toContain("SECRET_FILTER"); + expect(queries.at(-1)).toMatchObject({ operators: ["from"] }); + await vi.advanceTimersByTimeAsync(RELATION_MS + 1); + await issue(8, "other words"); + expect( + records.filter((record) => record.type === "search_query").at(-1), + ).toMatchObject({ + relation: "new", + previous_query_id: null, + since_previous: null, + }); + search.dispose(); + expect(vi.getTimerCount()).toBe(0); +}); + +it("checks the 30s relation age even when background expiry callbacks are delayed", () => { + const { search, records } = setup(); + search.receive(start()); + search.receive(query()); + search.receive(results()); + search.receive(click()); + search.receive(end()); + expect(vi.getTimerCount()).toBeGreaterThan(0); + vi.setSystemTime(RELATION_MS + 1); // Advance the clock without delivering timer callbacks. + search.receive(start(sid(3))); + search.receive(query(sid(4), TEXT, { sessionId: sid(3) })); + search.receive(results(sid(4), { sessionId: sid(3) })); + search.receive(click(sid(4), { sessionId: sid(3) })); + search.receive(end(sid(3))); + expect( + records.filter((record) => record.type === "search_query").at(-1), + ).toMatchObject({ + relation: "new", + previous_query_id: null, + since_previous: null, + }); + search.dispose(); + expect(vi.getTimerCount()).toBe(0); +}); + +it("keeps Level 1 to counts with no IDs, order, timings or per-query records", async () => { + const { search, records } = setup(1); + search.receive(start()); + search.receive(query()); + search.receive(results()); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + search.receive(click()); + search.receive(end()); + expect(records).toHaveLength(1); + expect(records[0]).toMatchObject({ + type: "search_session", + level: 1, + eligible: 1, + eligible_opened: 1, + }); + expect(JSON.stringify(records)).not.toMatch( + /query_id|session_id|event_count|truncated|duration|since_previous|relay_rank|"seq"/, + ); + expect(JSON.stringify(records)).not.toContain(TEXT); + search.dispose(); +}); + +it("rejects personal/conflicting communities and stale query tuples, and drops all raw state on dispose", async () => { + const { search, records } = setup(); + search.receive(start(sid(1), PERSONAL)); + search.receive(query(sid(2), TEXT, { community: PERSONAL })); + search.receive(results()); + search.receive(click()); + search.receive(end()); + expect(records).toEqual([]); + search.receive(start()); + search.receive(query()); + search.receive(results()); + search.receive(start(sid(1), PERSONAL)); // Retire the old identity even when the replacement is denied. + search.receive(click()); + search.receive(end()); + expect(records).toEqual([]); + search.receive(start()); + search.receive(query()); + search.receive(results(sid(999))); + search.receive(click(sid(2), { attempt: 2 })); + expect(vi.getTimerCount()).toBe(1); // Only the bounded raw-relation expiry, no settle clock. + search.receive(results()); + expect(vi.getTimerCount()).toBe(2); + search.dispose(); + expect(vi.getTimerCount()).toBe(0); + await vi.advanceTimersByTimeAsync(60_000); + search.receive(end()); + expect(records).toEqual([]); +}); + +it("preserves bounded session-end reasons without copying arbitrary host strings", () => { + const { search, records } = setup(); + search.receive(start()); + search.receive(query()); + search.receive(results()); + search.receive(click()); + search.receive({ ...end(), reason: TEXT }); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ reason: "other" }); + expect(JSON.stringify(records)).not.toContain(TEXT); + search.dispose(); +}); + +it("expires raw relation state after 30s without losing eligibility for a slow response", async () => { + const { search, records } = setup(); + search.receive(start()); + search.receive(query()); + await vi.advanceTimersByTimeAsync(RELATION_MS + 1); + expect(vi.getTimerCount()).toBe(0); + search.receive(results()); + search.receive(click()); + search.receive(end()); + expect( + records.find((record) => record.type === "search_session"), + ).toMatchObject({ eligible: 1, eligible_opened: 1 }); + expect(JSON.stringify(records)).not.toContain(TEXT); + search.dispose(); + expect(vi.getTimerCount()).toBe(0); +}); + +it("bounds simultaneous sessions, linked records, and teardown even under a long query stream", () => { + const { search, records, dropped } = setup(); + for (let i = 1; i <= MAX_SESSIONS + 3; i++) search.receive(start(sid(i))); + expect(dropped).toHaveBeenCalledTimes(3); + search.receive(start()); + for (let i = 0; i < MAX_SESSION_RECORDS + 20; i++) { + const queryId = sid(100 + i); + search.receive(query(queryId)); + search.receive(results(queryId)); + search.receive(click(queryId)); + } + search.receive(end()); + const summary = records.find((record) => record.type === "search_session"); + expect(summary).toMatchObject({ + truncated: true, + event_count: MAX_SESSION_RECORDS + 1, + }); + expect(records).toHaveLength(MAX_SESSION_RECORDS + 1); + expect(JSON.stringify(records)).not.toContain(TEXT); + search.dispose(); + expect(vi.getTimerCount()).toBe(0); +}); diff --git a/metrics/src/search.ts b/metrics/src/search.ts new file mode 100644 index 0000000..61e1b31 --- /dev/null +++ b/metrics/src/search.ts @@ -0,0 +1,521 @@ +import { community, object, oneOf } from "./contract.ts"; +import { + bucket, + eventId, + freeze, + group, + positive, + queryParts, + relation, + uuid, + type ClickRecord, + type MetricsRecord, + type OpenCount, + type Outcome, + type QueryRecord, + type Relation, + type Scope, + type Shape, +} from "./records.ts"; + +export const SETTLE_MS = 2_000; +export const RELATION_MS = 30_000; +export const MAX_SESSIONS = 8; +export const MAX_SESSION_RECORDS = 64; +type Timer = ReturnType; +export type Clock = { + now(): number; + set(run: () => void, ms: number): Timer; + clear(timer: Timer): void; +}; +export const clock: Clock = { + now: () => performance.now(), + set: (run, ms) => setTimeout(run, ms), + clear: (timer) => clearTimeout(timer), +}; +type Query = { + id: string; + attempt: number; + seq: number; + scope: Scope; + body: string; + signature: string; + hasText: boolean; + rawTimer?: Timer; + shape: Shape; + at: number; + eligible: boolean; + finished: boolean; + settled: boolean; + opened: boolean; + status: "results" | "empty" | "failed"; + relation: Relation; + since: number | null; + previous: string | null; + timer?: Timer; +}; +type Session = { + id: string; + community: string; + scope: Scope; + query?: Query; + records: MetricsRecord[]; + opens: Map; + messageOpens: number; + otherOpens: number; + actions: number; + queries: number; + eligible: number; + empty: number; + failed: number; + opened: number; + superseded: number; + unsettled: number; + sawText: boolean; + truncated: boolean; +}; +type Previous = { + body: string; + signature: string; + id: string; + at: number; + timer: Timer; +}; +export type SearchOptions = { + level: 1 | 2; + allowed: ReadonlySet; + appVersion: string; + emit(records: readonly MetricsRecord[]): void; + dropped(): void; + clock?: Clock; +}; + +/** Raw text exists ONLY in private current/previous query state, never records. + * Sessions wait until close so navigation-only sessions can be marked before + * their summary is exported; consumers exclude that flag from message rates. */ +export function createSearchAggregator(options: SearchOptions) { + const time = options.clock ?? clock; + const sessions = new Map(); + const previous = new Map(); + let disposed = false; + const clearQuery = (query: Query | undefined) => { + if (query?.timer !== undefined) time.clear(query.timer); + if (query) query.timer = undefined; + }; + const clearSession = (session: Session) => { + clearQuery(session.query); + if (session.query?.rawTimer !== undefined) + time.clear(session.query.rawTimer); + if (session.query) { + session.query.body = ""; + session.query.signature = ""; + } + session.query = undefined; + session.records.length = 0; + session.opens.clear(); + }; + const add = (session: Session, record: MetricsRecord) => { + if (session.records.length >= MAX_SESSION_RECORDS) { + session.truncated = true; + options.dropped(); + return; + } + session.records.push(record); + }; + const settle = (session: Session, query: Query) => { + if ( + disposed || + sessions.get(session.id) !== session || + session.query !== query || + !query.eligible || + !query.finished + ) + return; + clearQuery(query); + query.settled = true; + }; + const endQuery = (session: Session, replaced: boolean) => { + const query = session.query; + if (!query) return; + clearQuery(query); + if (query.rawTimer !== undefined) time.clear(query.rawTimer); + query.rawTimer = undefined; + const outcome: Outcome = query.settled + ? query.status + : replaced + ? "superseded" + : "unsettled"; + if (query.eligible) { + if (query.settled) { + session.eligible++; + if (outcome === "empty") session.empty++; + if (outcome === "failed") session.failed++; + if (query.opened) session.opened++; + } else if (replaced) session.superseded++; + else session.unsettled++; + if (options.level === 2) { + const record: QueryRecord = freeze({ + schema: 1, + type: "search_query", + level: 2, + app_version: options.appVersion, + session_id: session.id, + seq: query.seq, + query_id: query.id, + attempt: query.attempt, + scope: query.scope, + outcome, + relation: query.relation, + since_previous: query.since, + previous_query_id: query.previous, + char_count: query.shape.char_count, + word_count: query.shape.word_count, + quoted: query.shape.quoted, + has_url: query.shape.has_url, + operators: query.shape.operators, + }); + add(session, record); + const old = previous.get(session.community); + if (old) { + time.clear(old.timer); + previous.delete(session.community); + } + const remaining = RELATION_MS - (time.now() - query.at); + if (remaining > 0) { + const origin = session.community; + const entry: Previous = { + body: query.body, + signature: query.signature, + id: query.id, + at: query.at, + timer: time.set(() => { + if (previous.get(origin) === entry) previous.delete(origin); + }, remaining), + }; + previous.set(origin, entry); + } + } + } + query.body = ""; + query.signature = ""; + session.query = undefined; // Drop this raw body/signature even for rejected or unknown queries. + }; + const endSession = ( + session: Session, + reason: + | "closed" + | "scope_changed" + | "disposed" + | "subscribers_changed" + | "other", + ) => { + endQuery(session, false); + sessions.delete(session.id); + // Level 1 sends nothing for a dialog with no typed query. Linked mode can + // retain actual navigation opens, but never an unused empty dialog. + if ( + !session.sawText && + (options.level === 1 || + !(session.otherOpens || session.messageOpens || session.actions)) + ) { + clearSession(session); + return; + } + const navigation = session.otherOpens > 0 && session.messageOpens === 0; + const opens = Object.freeze( + [...session.opens.values()].sort( + (a, b) => + a.group.localeCompare(b.group) || + a.position.localeCompare(b.position), + ), + ); + const summary = freeze({ + schema: 1 as const, + type: "search_session" as const, + level: options.level, + app_version: options.appVersion, + ...(options.level === 2 + ? { + session_id: session.id, + event_count: session.records.length + 1, + truncated: session.truncated, + } + : {}), + eligible: session.eligible, + eligible_empty: session.empty, + eligible_failed: session.failed, + eligible_opened: session.opened, + navigation_session: navigation, + reason, + opens, + queries: session.queries, + superseded: session.superseded, + unsettled: session.unsettled, + actions: session.actions, + }); + options.emit(Object.freeze([...session.records, summary])); + clearSession(session); + }; + const matchingQuery = (session: Session, value: Record) => { + const query = session.query; + return query && + query.id === value.queryId && + query.attempt === value.attempt + ? query + : undefined; + }; + return { + receive(raw: unknown) { + if (disposed) return; + const value = object(raw); + if (value?.version !== 1) return; + const sessionId = uuid(value.sessionId); + if (!sessionId) return; + if (value.type === "sessionStart") { + const old = sessions.get(sessionId); + if (old) { + clearSession(old); + sessions.delete(sessionId); + } + const origin = community(value.community), + scope = oneOf(value.scope, ["global", "conversation"] as const); + if (!origin || !scope || !options.allowed.has(origin)) return; + if (sessions.size >= MAX_SESSIONS) { + const first = sessions.values().next().value as Session | undefined; + if (first) { + clearSession(first); + sessions.delete(first.id); + options.dropped(); + } + } + sessions.set(sessionId, { + id: sessionId, + community: origin, + scope, + records: [], + opens: new Map(), + messageOpens: 0, + otherOpens: 0, + actions: 0, + queries: 0, + eligible: 0, + empty: 0, + failed: 0, + opened: 0, + superseded: 0, + unsettled: 0, + sawText: false, + truncated: false, + }); + return; + } + const session = sessions.get(sessionId); + if (!session) return; + if (value.type === "queryIssued") { + const origin = community(value.community), + scope = oneOf(value.scope, ["global", "conversation"] as const); + const queryId = uuid(value.queryId), + attempt = positive(value.attempt); + if ( + origin !== session.community || + !scope || + !queryId || + !attempt || + typeof value.queryText !== "string" || + value.queryText.length > 4096 + ) { + clearSession(session); + sessions.delete(sessionId); + options.dropped(); + return; + } + const active = session.query; + if (active?.id === queryId) { + // Host retries/name-authority/capability re-evaluations advance the + // attempt, not the logical query or denominator. Keep prior settled + // eligibility/opened evidence; restart unfinished-result waiting. + if (attempt <= active.attempt || scope !== active.scope) return; + clearQuery(active); + active.attempt = attempt; + active.finished = false; + active.eligible ||= active.hasText && value.messageSearch === true; + return; + } + endQuery(session, true); + const parts = queryParts(value.queryText, value.filters); + const now = time.now(), + last = previous.get(origin); + const related = last && now - last.at <= RELATION_MS ? last : undefined; + session.queries = Math.min(1_000_000, session.queries + 1); + session.sawText ||= !!value.queryText.trim(); + session.query = { + id: queryId, + attempt, + seq: session.queries, + scope, + body: options.level === 2 ? parts.body : "", + signature: options.level === 2 ? parts.signature : "", + hasText: !!parts.body, + shape: parts.shape, + at: now, + // Optional forward-compatible evidence. Today's host lacks this flag; + // relay-ranked rows below positively establish dispatch instead. + eligible: !!parts.body && value.messageSearch === true, + finished: false, + settled: false, + opened: false, + status: "empty", + relation: relation(related, parts), + since: related ? Math.max(0, Math.round(now - related.at)) : null, + previous: related?.id ?? null, + }; + const current = session.query; + if (options.level === 2) + current.rawTimer = time.set(() => { + current.body = ""; + current.signature = ""; + current.rawTimer = undefined; + }, RELATION_MS); + return; + } + if (value.type === "sessionEnd") { + endSession( + session, + oneOf(value.reason, [ + "closed", + "scope_changed", + "disposed", + "subscribers_changed", + ] as const) ?? "other", + ); + return; + } + const query = matchingQuery(session, value); + if (!query) return; + if (value.type === "resultsUpdated") { + const outcome = oneOf(value.outcome, [ + "loading", + "ok", + "error", + "offline", + ] as const); + if ( + !outcome || + !Array.isArray(value.groups) || + value.groups.length > 32 + ) + return; + let messages = false, + relay = false; + for (const rawGroup of value.groups) { + const entry = object(rawGroup); + if (!Array.isArray(entry?.results) || entry.results.length > 1000) + continue; + for (const rawRow of entry.results) { + const row = object(rawRow); + if (row?.kind !== "message" || !eventId(row.eventId)) continue; + messages = true; + if ( + (row.source === "relay" || row.source === "device") && + positive(row.relayRank) + ) + relay = true; + } + } + query.eligible ||= query.hasText && relay; + if (outcome === "ok" || outcome === "error") { + query.finished = true; + query.status = + outcome === "error" ? "failed" : messages ? "results" : "empty"; + if (query.eligible && !query.settled) { + clearQuery(query); + query.timer = time.set(() => settle(session, query), SETTLE_MS); + } + } else if (!query.settled) { + query.finished = false; + clearQuery(query); + } + return; + } + if (value.type === "resultActivated") { + const kind = oneOf(value.kind, [ + "message", + "channel", + "person", + "agent", + "chat", + "page", + "plugin", + "action", + "other", + ] as const); + const position = positive(value.position); + if (!kind || !position) return; + const message = kind === "message", + action = kind === "action" || kind === "other"; + const openedId = message ? eventId(value.eventId) : undefined; + if (message && !openedId) return; + if (!message && typeof value.belowMessages !== "boolean") return; + const mapped = group(value.group), + rank = positive(value.relayRank), + source = oneOf(value.source, [ + "relay", + "device", + "local", + "unknown", + ] as const); + if (action) session.actions++; + else { + if (message) { + session.messageOpens++; + query.opened = true; + query.finished = true; + query.status = "results"; + query.eligible ||= + query.hasText && + !!rank && + (source === "relay" || source === "device"); + } else session.otherOpens++; + const key = `${mapped}/${bucket(position)}`, + old = session.opens.get(key); + session.opens.set( + key, + Object.freeze({ + group: mapped, + position: bucket(position), + count: Math.min(1_000_000, (old?.count ?? 0) + 1), + }), + ); + } + settle(session, query); // Acting on a finished result settles without waiting. + if (options.level === 2) { + const click: ClickRecord = freeze({ + schema: 1, + type: "search_click", + level: 2, + app_version: options.appVersion, + session_id: session.id, + seq: query.seq, + query_id: query.id, + attempt: query.attempt, + kind: action ? "action" : "open", + group: mapped, + position, + ...(message + ? { id: openedId, ...(rank ? { relay_rank: rank } : {}) } + : { below_messages: value.belowMessages as boolean }), + ...(source ? { source } : {}), + }); + add(session, click); + } + } + }, + dispose() { + disposed = true; + for (const session of sessions.values()) clearSession(session); + sessions.clear(); + for (const entry of previous.values()) time.clear(entry.timer); + previous.clear(); + }, + }; +} diff --git a/metrics/src/testkit.ts b/metrics/src/testkit.ts new file mode 100644 index 0000000..767561b --- /dev/null +++ b/metrics/src/testkit.ts @@ -0,0 +1,191 @@ +import { vi } from "vitest"; +import type { + Telemetry, + Topic, + TraceContext, + TraceRequest, +} from "./contract.ts"; +import type { Clock } from "./search.ts"; +import type { Settings } from "./config.ts"; + +export const WORK = "https://work.example"; +export const PERSONAL = "https://personal.example"; +export const ORIGINS = ["https://metrics.example"]; +export const TARGET = "https://metrics.example/ingest"; +export const TEXT = "sensitive query text must never leave private memory"; +export const EVENT = "a".repeat(64); +export const sid = (n: number) => + `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`; +export const fakeClock: Clock = { + now: () => Date.now(), + set: (run, ms) => setTimeout(run, ms), + clear: (timer) => clearTimeout(timer), +}; +export const enabled = (level: 1 | 2 = 2): Settings => ({ + enabled: true, + level, + communities: [WORK], + tracing: false, + exportEnabled: false, + endpoint: "", +}); +export const request = (community = WORK, durationMs = 12) => ({ + version: 1, + type: "request", + community, + operation: "search", + priority: "background", + durationMs, + bytes: 42, + outcome: "ok", + queryText: TEXT, + url: TEXT, + error: TEXT, + filters: { secret: TEXT }, + traceContext: { correlationId: TEXT }, +}); +export function selection(initial: string | undefined = WORK) { + let origin: string | undefined = initial; + const listeners = new Set<() => void>(); + const current = vi.fn(() => origin); + return { + reader: { + current, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }, + current, + listeners, + select(next: string | undefined) { + origin = next; + for (const listener of [...listeners]) listener(); + }, + }; +} + +export function host( + supported: readonly Topic[] = ["requests", "ui", "search"], +) { + const listeners = new Map void>>(); + const providers = new Set< + (request: TraceRequest) => TraceContext | undefined + >(); + const subscribe = vi.fn( + (topic: Topic, listener: (event: unknown) => void) => { + if (!supported.includes(topic)) throw new Error("unsupported"); + const entries = listeners.get(topic) ?? new Set(); + listeners.set(topic, entries); + entries.add(listener); + return () => { + entries.delete(listener); + }; + }, + ); + const telemetry: Telemetry = { + subscribe, + registerTraceContextProvider: (provider) => { + providers.add(provider); + return () => { + providers.delete(provider); + }; + }, + }; + return { + telemetry, + subscribe, + listeners, + providers, + send(topic: Topic, event: unknown) { + for (const listener of [...(listeners.get(topic) ?? [])]) listener(event); + }, + active() { + return [...listeners.values()].reduce( + (sum, entries) => sum + entries.size, + 0, + ); + }, + }; +} +export function start(session = sid(1), community = WORK) { + return { + version: 1, + type: "sessionStart", + sessionId: session, + community, + scope: "global", + }; +} +export function query(queryId = sid(2), queryText = TEXT, extras = {}) { + return { + version: 1, + type: "queryIssued", + sessionId: sid(1), + queryId, + attempt: 1, + community: WORK, + scope: "global", + queryText, + filters: {}, + sort: "relevance", + ...extras, + }; +} +export function results(queryId = sid(2), extras = {}) { + return { + version: 1, + type: "resultsUpdated", + sessionId: sid(1), + queryId, + attempt: 1, + outcome: "ok", + durationMs: 42, + groups: [ + { + group: "Messages", + results: [ + { + key: EVENT, + kind: "message", + eventId: EVENT, + relayRank: 1, + source: "relay", + label: TEXT, + }, + ], + }, + ], + ...extras, + }; +} +export function click(queryId = sid(2), extras = {}) { + return { + version: 1, + type: "resultActivated", + sessionId: sid(1), + queryId, + attempt: 1, + kind: "message", + group: "Messages", + position: 1, + belowMessages: false, + eventId: EVENT, + relayRank: 1, + source: "relay", + label: TEXT, + queryText: TEXT, + ...extras, + }; +} +export function end(sessionId = sid(1)) { + return { + version: 1, + type: "sessionEnd", + sessionId, + reason: "closed", + queryText: TEXT, + }; +} diff --git a/metrics/tsconfig.json b/metrics/tsconfig.json new file mode 100644 index 0000000..ba33570 --- /dev/null +++ b/metrics/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/metrics/vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz b/metrics/vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz new file mode 100644 index 0000000..8a81782 Binary files /dev/null and b/metrics/vendor/buzz-author-0.0.0-preview.1-89e2d15.tgz differ diff --git a/metrics/vite.config.ts b/metrics/vite.config.ts new file mode 100644 index 0000000..85b02f9 --- /dev/null +++ b/metrics/vite.config.ts @@ -0,0 +1,45 @@ +import { defineConfig } from "vite"; + +export default defineConfig({ + publicDir: false, + oxc: { jsx: { runtime: "classic" } }, + build: { + outDir: ".", + emptyOutDir: false, + copyPublicDir: false, + lib: { + entry: "src/index.tsx", + formats: ["es"], + fileName: () => "plugin.js", + }, + rolldownOptions: { output: { codeSplitting: false } }, + minify: false, + }, + plugins: [ + { + name: "plugin-contract", + enforce: "pre", + apply: "build", + resolveId(id) { + if (/^react(?:-dom)?(?:\/|$)/.test(id) || id === "@buzz/author") + throw new Error( + "Buzz supplies React and the plugin API at runtime; import them as types only", + ); + }, + generateBundle(_options, bundle) { + const outputs = Object.values(bundle); + const module = outputs[0]; + if ( + outputs.length !== 1 || + module?.type !== "chunk" || + module.imports.length + ) + throw new Error( + "A Buzz plugin is one self-contained plugin.js module", + ); + if (!module.exports.includes("apply")) + throw new Error("plugin.js must export apply(ctx)"); + }, + }, + ], +});