ai-visibility-stats 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aurevant LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,167 @@
1
- # Temporary Holding Version
1
+ # ai-visibility-stats
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ How often does an AI platform mention your brand, cite your site, or name you before a competitor? Ask the same question many times and the answers vary, so a single percentage isn't enough. This package turns repeated AI answers into **mention rate, citation rate and competitor share, each with a 95% interval and a flag that says whether there is enough data**.
4
+
5
+ - Works with answers from any source: ChatGPT, Perplexity, Gemini, Google AI Overviews, Copilot, DeepSeek, Doubao, your own scraper or a CSV export.
6
+ - No dependencies, no network. Node.js 18+, ESM, types included.
7
+ - The same input always gives the same result, whatever the order of the answers.
8
+ - If it can't see a difference or doesn't have enough data, it says so: `enough: false`, and `null` (never 0%) when something wasn't measured.
9
+
10
+ ```bash
11
+ npm install ai-visibility-stats
12
+ ```
13
+
14
+ ## Quick start
15
+
16
+ ```js
17
+ import { visibility } from "ai-visibility-stats";
18
+
19
+ const answers = [
20
+ { prompt: "best crm for small business", engine: "chatgpt", search_triggered: true, text: "HubSpot is a good start. Zoho is cheaper…",
21
+ citations: [{ url: "https://www.hubspot.com/products/crm", cited: true }, { url: "https://www.zoho.com/crm/", cited: false }] },
22
+ { prompt: "best crm for small business", engine: "chatgpt", search_triggered: true, text: "Zoho CRM and Pipedrive…", citations: [] },
23
+ // … more samples of the same prompts, and other engines
24
+ ];
25
+
26
+ const report = visibility(answers, { brand: "HubSpot", domains: ["hubspot.com"] }, { competitors: [{ brand: "Zoho", aliases: ["Zoho CRM"] }, { brand: "Pipedrive" }] });
27
+
28
+ for (const row of report.rows) {
29
+ const { value, low, high, enough } = row.mention_rate;
30
+ console.log(row.engine, `mentioned in ${value} (95% ${low}–${high})`, enough ? "" : "(not enough data)");
31
+ for (const each of row.brands) console.log(" ", each.brand, "mentioned first in", each.first_share.value);
32
+ }
33
+ ```
34
+
35
+ Each answer needs only `prompt` and `engine`. The rest is optional:
36
+
37
+ | Field | Meaning |
38
+ |---|---|
39
+ | `prompt` | The question. Answers to the same prompt are samples of one prompt |
40
+ | `engine` | The AI platform, any label you like (`"chatgpt"`, `"perplexity.web"`) |
41
+ | `status` | `answered` (default), `no_answer`, `refused`, `failed` or `pending` |
42
+ | `text`, `markdown` | The answer body. `text` is used first. Neither means the mention can't be judged |
43
+ | `search_triggered` | `true` if the platform searched the web, `false` if not. Missing means unknown, and the answer is left out of the citation rate |
44
+ | `citations` | `[{ url, domain, cited }]`. `cited: true` used in the answer, `false` only found while searching, missing or `null` can't tell. `[]` means no citations; a missing list means unknown |
45
+ | `id` | Optional. The same id twice throws |
46
+ | `channel_id`, `tier`, `conditions` | Optional collection details (surface, login, thinking, requested and actual country/region). Answers are grouped by them |
47
+
48
+ Answers from the [AskCrawl API](https://www.askcrawl.com) already have this shape, so you can pass them as they are:
49
+
50
+ ```js
51
+ import { AskCrawl } from "askcrawl";
52
+ import { visibility } from "ai-visibility-stats";
53
+
54
+ const client = new AskCrawl();
55
+ const answers = [];
56
+ for await (const answer of client.answers(jobId)) answers.push(answer);
57
+ visibility(answers, { brand: "HubSpot", domains: ["hubspot.com"] });
58
+ ```
59
+
60
+ ## What you get
61
+
62
+ One row per engine (and per distinct set of collection conditions):
63
+
64
+ ```js
65
+ {
66
+ engine: "chatgpt",
67
+ prompt_count, // prompts with answers in this row
68
+ status_counts: { answered, no_answer, refused, failed, pending },
69
+ answer_rate: { count, sample_size, prompt_count, value, low, high, method, enough },
70
+ mention_rate: { … }, // same shape; value, low and high are null when not measured
71
+ citation_rate: { … },
72
+ search_unknown, // answered, but can't tell whether it searched
73
+ cited_unknown, // searched, but can't tell which sources were used
74
+ brands: [{ brand, key, mention_rate: { … }, first_share: { … } }, …] // null without competitors
75
+ }
76
+ ```
77
+
78
+ `method` is `"wilson_95"` with one prompt and `"cluster_bootstrap_95"` with several. Values are rounded to 6 decimal places.
79
+
80
+ `report.method` records the method version, the denominators, the brand rules and the random seed, so anyone can reproduce the numbers.
81
+
82
+ ### Denominators
83
+
84
+ | Metric | Numerator | Denominator |
85
+ |---|---|---|
86
+ | `answer_rate` | `answered` | `answered` + `no_answer` + `refused` |
87
+ | `mention_rate` | answers that mention the brand | all `answered` results with a body, including those without a search |
88
+ | `citation_rate` | answers with at least one target domain cited in the body | `answered` results that searched and where every source is marked as cited or not cited |
89
+ | `brands[].mention_rate` | answers that mention this brand | the same as `mention_rate` |
90
+ | `brands[].first_share` | answers where this brand comes first | `answered` results with a body that mention at least one of the brands given. The brands add up to about 100% |
91
+
92
+ - `failed` and `pending` are never in a denominator. They are counted separately.
93
+ - If an answered result has no body, it is left out of the mention rate. An empty string counts as no mention.
94
+ - If we can't tell whether an answer searched, it counts in `search_unknown`, even if it has citations: including only answers with citations would bias the rate.
95
+ - **A `null` citation list counts in `cited_unknown`; an empty list (`[]`) counts as not cited**, unless every non-empty list in the group is unclear.
96
+ - **Whether an answer is included never depends on the target domain.** If any source is unclear, the whole answer is left out. Otherwise only "not cited" answers would remain, and the rate would always be 0%.
97
+ - Without `brand`, the mention rate isn't measured; without a valid domain, the citation rate isn't measured. Both are then `null`, **not 0%**.
98
+ - **A name or alias can belong to only one brand**, or an error is thrown: if two brands shared an alias, which one a mention counts for would depend on the order of the list.
99
+
100
+ ### Values and intervals
101
+
102
+ - **One prompt:** the rate is `count / sample_size`, with a Wilson score interval.
103
+ - **Several prompts:** each prompt gets its own rate and the rates are averaged, so **each prompt counts equally**. The interval comes from resampling prompts, not answers (repeated answers to one prompt are alike), 5,000 times, with Hesterberg's expanded percentile method.
104
+ - **Resampling alone can give false certainty**, so with fewer than 10 prompts, or fewer than 6 that differ from the most common result, the interval is widened to the Wilson interval that counts each prompt as one sample. Example: 20 prompts × 30 samples, all 0%, give an upper limit of 16%, not the 0.6% you'd get from 600 samples. If 5% of similar prompts always mentioned the brand, there would be a 36% chance that none of them were among your 20.
105
+
106
+ ### How much data is enough
107
+
108
+ `enough` is `true` only if all of these are met. Otherwise rates and intervals are still shown, but they can't support a conclusion.
109
+
110
+ | Requirement | Threshold | Why |
111
+ |---|---|---|
112
+ | Answers | 30 | With 30, the widest Wilson interval is about ±17 points |
113
+ | Prompts, when there are several | 10 | With fewer, the interval misses cases not seen. 10 is the minimum from simulations |
114
+ | Failed and pending | at most 20% | Failures often aren't random |
115
+ | Unknown outcomes | at most 5% | Why a result is unknown often depends on what it is |
116
+ | Citation rate | at least one non-empty list with every source marked | Empty lists alone can't show that the platform marks cited sources |
117
+
118
+ In simulations (1,000 runs per case), rate intervals covered the true value 93.1%–100% of the time, for 10–100 prompts with 1–10 samples each.
119
+
120
+ ## Brand rules (version 2)
121
+
122
+ **We check whether the brand is mentioned, not whether the mention is positive. "I don't recommend Acme" counts.** Only the body is checked, never citation titles or URLs.
123
+
124
+ | Content | Rule |
125
+ |---|---|
126
+ | Markdown links | Only the visible text counts |
127
+ | Source labels | Ignored: links whose visible text is their own domain and that point to an inner page, such as `[example.com](https://example.com/guide)` |
128
+ | Source lists | Ignored: lines that start with `[1]` or `[^1]` and end with a URL, plus footnote and reference definitions |
129
+ | Reference markers | Ignored: `[1]`, `[1, 2]`, `[^1]`, `【1】`, `<cite>`, superscript and circled numbers |
130
+ | Images, URLs, emails, fenced code | Ignored. Inline code counts; a bare domain such as `Monday.com` counts |
131
+ | HTML | Tags removed, text kept |
132
+
133
+ - Text is normalized: Unicode NFKC (full-width = half-width), lower case, quotes and dashes unified, invisible characters and `™ ® ©` removed, accents removed from Latin letters only (`Nestlé` = `Nestle`), and no space between Chinese/Japanese/Korean and Latin or digits (`小米 SU7` = `小米SU7`).
134
+ - **Letters and digits need a word boundary:** `AI` doesn't match `said`, `Qwen` doesn't match `Qwen3`, `GPT-5` doesn't match `GPT-5.1`, `.NET` doesn't match `example.net`.
135
+ - **Chinese, Hiragana, Thai, Lao, Khmer and Burmese don't need a boundary.** Use `exclude` for common words.
136
+ - **Katakana needs a boundary on both sides** (`ライン` doesn't match `オンライン`); **Hangul only on the left** (`삼성` matches `삼성은`).
137
+ - **Excluded phrases:** a match is ignored only if it lies entirely inside an excluded phrase. Other mentions still count.
138
+ - **Several brands** are ordered by where each is first mentioned; at the same place the longer match comes first (`Zoho CRM` before `Zoho`). Only the brands given are ranked; other brands are never guessed.
139
+ - **Domains** include their subdomains (`example.com` matches `blog.example.com`, not `notexample.com`). A leading `www.` or `*.` is removed from targets, except where that would leave a shared suffix such as `gov.uk`.
140
+
141
+ ## Lower-level functions
142
+
143
+ ```js
144
+ import { wilson, newcombe, rateInterval, differenceInterval, mentionsBrand, brandMentions, domainMatcher } from "ai-visibility-stats";
145
+
146
+ wilson(15 / 30, 30); // { low: 0.3315…, high: 0.6685… }
147
+ rateInterval([0.2, 0.4, 0, 1, 0.6]); // interval of the average of per-prompt rates, with the safeguards above
148
+ differenceInterval(before, after); // b − a for the same prompts measured twice: [{ rate, n }]
149
+ mentionsBrand("Try HubSpot", { brand: "hubspot" }); // true
150
+ brandMentions(text, citations, [{ brand: "HubSpot", domains: ["hubspot.com"] }, { brand: "Zoho" }]);
151
+ // [{ brand: "HubSpot", key: "hubspot", position: 1, cited: true }, …]
152
+ ```
153
+
154
+ ## What the results can't tell you
155
+
156
+ - **30 samples aren't enough for rankings.** With 15 of 30, the interval is about 33%–67%. A 10–20 point gap between brands could be chance. `enough: true` doesn't mean you can rank them.
157
+ - Back-to-back samples of one prompt usually aren't independent, so the real error may be larger than the interval for one prompt. Use at least 10 prompts and spread samples over time.
158
+ - Intervals apply to prompts like the ones you used, not to everything users might ask.
159
+ - Intervals don't include errors from brand matching or bias from failures.
160
+
161
+ ## Reproducing a result
162
+
163
+ Use the same answers (including failed and pending ones), the same target, and the same `method.version`. Prompts are sorted in JavaScript's default string order; the generator is mulberry32 from `method.seed`, restarted for every group and metric; values are rounded to 6 decimal places.
164
+
165
+ ## License
166
+
167
+ MIT © Aurevant LLC. Questions: support@askcrawl.com
package/index.d.ts ADDED
@@ -0,0 +1,194 @@
1
+ // Types for ai-visibility-stats.
2
+
3
+ export interface Interval {
4
+ low: number;
5
+ high: number;
6
+ }
7
+
8
+ // --- Input ---------------------------------------------------------------------------
9
+
10
+ export type Status = "answered" | "no_answer" | "refused" | "failed" | "pending";
11
+
12
+ export interface Source {
13
+ url?: string | null;
14
+ domain?: string | null;
15
+ }
16
+ export interface CitedSource extends Source {
17
+ /** true: used in the answer; false: only found while searching; null or missing: can't tell. */
18
+ cited?: boolean | null;
19
+ }
20
+
21
+ export interface Location {
22
+ country?: string | null;
23
+ region?: string | null;
24
+ }
25
+
26
+ /** One AI answer. Only prompt and engine are required. AskCrawl answers can be passed as they come from the API. */
27
+ export interface AnswerInput {
28
+ /** Optional. When given, the same id twice throws: an answer counted twice would narrow the interval. */
29
+ id?: string | number | null;
30
+ prompt: string;
31
+ /** The AI platform, e.g. "chatgpt" or "perplexity.web". Rows are per engine (and per condition below). */
32
+ engine: string;
33
+ /** Default "answered". failed and pending are counted separately and never enter a rate. */
34
+ status?: Status;
35
+ /** Whether the platform searched the web. null or missing: unknown, and then the answer is not in the citation rate. */
36
+ search_triggered?: boolean | null;
37
+ /** The answer body. text is used first, markdown when text is null. Neither: the mention can't be judged. */
38
+ text?: string | null;
39
+ markdown?: string | null;
40
+ /** null or missing: no list available. []: available, and nothing was cited. */
41
+ citations?: readonly CitedSource[] | null;
42
+ /** Optional collection details. Answers are grouped by them; a missing value is its own "unknown" value. */
43
+ channel_id?: string | null;
44
+ tier?: "basic" | "full";
45
+ channel?: { id?: string | null; tier?: "basic" | "full" } | null;
46
+ conditions?: {
47
+ surface?: string | null;
48
+ interface?: string | null;
49
+ login?: string | null;
50
+ thinking?: boolean | null;
51
+ requested?: Location | null;
52
+ actual?: Location | null;
53
+ } | null;
54
+ }
55
+
56
+ export interface BrandTarget {
57
+ brand?: string | null;
58
+ /** Other ways the brand is written. */
59
+ aliases?: readonly string[] | null;
60
+ /** Phrases that contain the name but aren't the brand, such as "Apple Pie" for Apple. */
61
+ exclude?: readonly string[] | null;
62
+ }
63
+ export interface Target extends BrandTarget {
64
+ /** Domains that count as the brand's, subdomains included. */
65
+ domains?: readonly string[] | null;
66
+ }
67
+
68
+ // --- Output --------------------------------------------------------------------------
69
+
70
+ export interface Rate {
71
+ count: number;
72
+ sample_size: number;
73
+ /** Prompts with data. With several prompts, value is the average of per-prompt rates. */
74
+ prompt_count: number;
75
+ /** null: no data, or not measured. Never the same as 0%. */
76
+ value: number | null;
77
+ low: number | null;
78
+ high: number | null;
79
+ method: "wilson_95" | "cluster_bootstrap_95" | null;
80
+ /** true only when every threshold is met (MIN_SAMPLES, MIN_PROMPTS, MAX_MISSING_SHARE, MAX_UNKNOWN_SHARE). */
81
+ enough: boolean;
82
+ }
83
+ export interface StatusCounts {
84
+ answered: number;
85
+ no_answer: number;
86
+ refused: number;
87
+ failed: number;
88
+ pending: number;
89
+ }
90
+ export interface BrandShare {
91
+ brand: string;
92
+ key: string;
93
+ mention_rate: Rate;
94
+ /** Share of answers mentioning at least one given brand where this brand comes first. */
95
+ first_share: Rate;
96
+ }
97
+ export interface VisibilityRow {
98
+ engine: string;
99
+ channel_id: string | null;
100
+ tier: "basic" | "full";
101
+ conditions: {
102
+ surface: string | null;
103
+ interface: string | null;
104
+ login: string | null;
105
+ thinking: boolean | null;
106
+ country: string | null;
107
+ region: string | null;
108
+ /** Only set when the actual location is unknown; used for grouping, says nothing about the actual location. */
109
+ requested_country: string | null;
110
+ requested_region: string | null;
111
+ };
112
+ prompt_count: number;
113
+ status_counts: StatusCounts;
114
+ answer_rate: Rate;
115
+ mention_rate: Rate;
116
+ citation_rate: Rate;
117
+ search_unknown: number;
118
+ cited_unknown: number;
119
+ /** null without competitors. */
120
+ brands: BrandShare[] | null;
121
+ }
122
+ export interface Method {
123
+ version: string;
124
+ denominators: Record<"answer_rate" | "mention_rate" | "citation_rate" | "first_share", string>;
125
+ brand_rules: string;
126
+ seed: number;
127
+ }
128
+ export interface VisibilityReport {
129
+ method: Method;
130
+ rows: VisibilityRow[];
131
+ }
132
+
133
+ export declare function visibility(answers: readonly AnswerInput[], target?: Target, options?: { competitors?: readonly BrandTarget[] }): VisibilityReport;
134
+
135
+ export declare const METHOD_VERSION: string;
136
+ export declare const MIN_SAMPLES: number;
137
+ export declare const MAX_MISSING_SHARE: number;
138
+ export declare const MAX_UNKNOWN_SHARE: number;
139
+
140
+ // --- Intervals -----------------------------------------------------------------------
141
+
142
+ export declare const Z95: number;
143
+ export declare const SEED: number;
144
+ export declare const RESAMPLES: number;
145
+ export declare const MIN_PROMPTS: number;
146
+ export declare const MIN_INFORMATIVE_PROMPTS: number;
147
+ /** Wilson score interval for a rate from 0 to 1 over n samples. */
148
+ export declare function wilson(rate: number, n: number): Interval;
149
+ /** Newcombe method 10: interval for b − a of two independent rates. */
150
+ export declare function newcombe(a: number, nA: number, b: number, nB: number): Interval;
151
+ export declare function union(a: Interval, b: Interval): Interval;
152
+ /** Interval of the average of per-prompt rates, resampling prompts, with the safeguards described in the README. */
153
+ export declare function rateInterval(rates: readonly number[], seed?: number): Interval;
154
+ export declare function rateIntervals(list: readonly (readonly number[])[], seed?: number): Interval[];
155
+ /** Resampled interval of a mean, without safeguards. */
156
+ export declare function bootstrapMean(values: readonly number[], seed?: number): Interval;
157
+ export declare function bootstrapMeans(list: readonly (readonly number[])[], seed?: number): Interval[];
158
+ /** Interval of b − a for the same prompts measured twice, a[i] and b[i] being the same prompt. */
159
+ export declare function differenceInterval(a: readonly { rate: number; n: number }[], b: readonly { rate: number; n: number }[], seed?: number): Interval;
160
+ export declare function mean(values: readonly number[]): number;
161
+ /** mulberry32. Not for security. */
162
+ export declare function random(seed: number): () => number;
163
+ export declare function t975(df: number): number;
164
+
165
+ // --- Brands and domains ----------------------------------------------------------------
166
+
167
+ export declare const BRAND_RULES_VERSION: string;
168
+ export declare const BRAND_RULES: string;
169
+ export interface Found {
170
+ index: number;
171
+ start: number;
172
+ end: number;
173
+ }
174
+ export interface BrandMention {
175
+ brand: string;
176
+ key: string;
177
+ /** Order of first mention among the brands given, from 1. Not the rank among every brand in the answer. */
178
+ position: number;
179
+ /** Whether a source used in the answer is on the brand's domains; null without domains or when unclear. */
180
+ cited: boolean | null;
181
+ }
182
+ export declare function readableText(source: string): string;
183
+ export declare function normalizeText(source: string): string;
184
+ export declare function bodyText(body: string): string;
185
+ export declare function brandKey(name: string): string;
186
+ export declare function brandMatcher(target: BrandTarget): ((body: string) => boolean) | null;
187
+ export declare function mentionsBrand(body: string, target: BrandTarget): boolean | null;
188
+ export declare function nameClash(brands: readonly BrandTarget[]): { first: { brand: number; alias: number | null; name: string }; second: { brand: number; alias: number | null; name: string } } | null;
189
+ export declare function brandsFinder(targets: readonly BrandTarget[]): (text: string) => Found[];
190
+ export declare function hostname(source: string): string | null;
191
+ export declare function normalizeDomain(source: string): string | null;
192
+ export declare function domainMatcher(domains: readonly string[] | null | undefined): ((source: Source) => boolean) | null;
193
+ export declare function brandReader(brands: readonly Target[]): (body: string | null, citations: readonly CitedSource[] | null) => BrandMention[] | null;
194
+ export declare function brandMentions(body: string | null, citations: readonly CitedSource[] | null, brands: readonly Target[]): BrandMention[] | null;
package/index.js ADDED
@@ -0,0 +1,22 @@
1
+ // ai-visibility-stats: brand mention rates, citation rates and competitor share in AI answers, with 95% intervals.
2
+ // No dependencies, no network. https://github.com/askcrawlhq/ai-visibility-stats
3
+ export { visibility, METHOD_VERSION, MIN_SAMPLES, MAX_MISSING_SHARE, MAX_UNKNOWN_SHARE } from "./src/visibility.js";
4
+ export { wilson, newcombe, union, Z95 } from "./src/wilson.js";
5
+ export { rateInterval, rateIntervals, bootstrapMean, bootstrapMeans, differenceInterval, mean, random, t975, SEED, RESAMPLES, MIN_PROMPTS, MIN_INFORMATIVE_PROMPTS } from "./src/bootstrap.js";
6
+ export {
7
+ BRAND_RULES,
8
+ BRAND_RULES_VERSION,
9
+ bodyText,
10
+ brandKey,
11
+ brandMatcher,
12
+ brandMentions,
13
+ brandReader,
14
+ brandsFinder,
15
+ domainMatcher,
16
+ hostname,
17
+ mentionsBrand,
18
+ nameClash,
19
+ normalizeDomain,
20
+ normalizeText,
21
+ readableText,
22
+ } from "./src/brand.js";
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "ai-visibility-stats",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Brand mention rate, citation rate and competitor share in AI answers (ChatGPT, Perplexity, Gemini, AI Overviews…), with Wilson and cluster-bootstrap 95% intervals and a not-enough-data flag. No dependencies.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./index.d.ts",
9
+ "default": "./index.js"
10
+ }
11
+ },
12
+ "types": "./index.d.ts",
13
+ "files": ["index.js", "index.d.ts", "src", "README.md", "LICENSE"],
14
+ "sideEffects": false,
15
+ "engines": { "node": ">=18" },
16
+ "scripts": { "test": "node --test" },
17
+ "keywords": ["ai visibility", "generative engine optimization", "geo", "llm visibility", "share of voice", "brand mentions", "citation rate", "wilson interval", "bootstrap", "confidence interval", "chatgpt", "perplexity", "ai overviews"],
18
+ "homepage": "https://github.com/askcrawlhq/ai-visibility-stats#readme",
19
+ "repository": { "type": "git", "url": "git+https://github.com/askcrawlhq/ai-visibility-stats.git" },
20
+ "bugs": { "email": "support@askcrawl.com" },
21
+ "author": "AskCrawl <support@askcrawl.com>",
22
+ "license": "MIT"
23
+ }
@@ -0,0 +1,163 @@
1
+ // 95% intervals with several prompts: resample prompts, not answers.
2
+ //
3
+ // Repeated answers to the same prompt are alike, so they are not independent samples. Each prompt gets its own rate,
4
+ // the rates are averaged, and every prompt has the same weight.
5
+ import { newcombe, union, wilson, Z95 } from "./wilson.js";
6
+
7
+ export const SEED = 20261130;
8
+ export const RESAMPLES = 5_000;
9
+
10
+ /** With fewer prompts, there is no conclusion: resampling keeps drawing the same few, and cases never seen are missing from the interval. */
11
+ export const MIN_PROMPTS = 10;
12
+
13
+ /**
14
+ * At least this many prompts must differ from the most common result before resampling is used on its own.
15
+ * Two-sided sign test: 5 prompts all moving one way gives p = 2 × 0.5^5 = 0.0625; 6 gives 0.031.
16
+ */
17
+ export const MIN_INFORMATIVE_PROMPTS = 6;
18
+
19
+ // Two differences can disagree in the last bit (0.3 − 0.2 and 0.4 − 0.3), so values are compared at 1e-9.
20
+ const SCALE = 1e9;
21
+
22
+ /** mulberry32: a public 32-bit generator using integer arithmetic only, so every runtime gives the same numbers. Not for security. */
23
+ export function random(seed) {
24
+ let state = seed >>> 0;
25
+ return () => {
26
+ state = (state + 0x6d2b79f5) >>> 0;
27
+ let t = Math.imul(state ^ (state >>> 15), state | 1);
28
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
29
+ return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
30
+ };
31
+ }
32
+
33
+ // Upper tail of the standard normal distribution, x ≥ 0. Abramowitz & Stegun 26.2.17, error below 7.5e-8.
34
+ function upperTail(x) {
35
+ const t = 1 / (1 + 0.2316419 * x);
36
+ const density = Math.exp((-x * x) / 2) / Math.sqrt(2 * Math.PI);
37
+ return density * t * (0.31938153 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));
38
+ }
39
+
40
+ /** The 97.5% quantile of Student's t. Abramowitz & Stegun 26.7.5; error below 0.001 from 9 degrees of freedom. */
41
+ export function t975(df) {
42
+ const z = Z95;
43
+ return (
44
+ z +
45
+ (z ** 3 + z) / (4 * df) +
46
+ (5 * z ** 5 + 16 * z ** 3 + 3 * z) / (96 * df ** 2) +
47
+ (3 * z ** 7 + 19 * z ** 5 + 17 * z ** 3 - 15 * z) / (384 * df ** 3)
48
+ );
49
+ }
50
+
51
+ export function mean(values) {
52
+ let sum = 0;
53
+ for (const value of values) sum += value;
54
+ return sum / values.length;
55
+ }
56
+
57
+ /**
58
+ * Resampled interval of a mean, without the safeguards below. Pass values in a fixed order.
59
+ * Hesterberg (2015) expanded percentile: each tail is Φ(−√(m/(m−1)) × t), t with m−1 degrees of freedom.
60
+ */
61
+ export function bootstrapMean(values, seed = SEED) {
62
+ return bootstrapMeans([values], seed)[0];
63
+ }
64
+
65
+ /**
66
+ * Several lists with the same number of prompts, resampled together: each starts from the same seed and draws the same
67
+ * prompt indexes, so the result equals computing them one by one.
68
+ */
69
+ export function bootstrapMeans(list, seed = SEED) {
70
+ const size = list[0]?.length ?? 0;
71
+ if (size < 2 || list.some((values) => values.length !== size)) throw new RangeError("bootstrapMeans needs two or more prompts, the same number in every list");
72
+ const sources = list.map((values) => Float64Array.from(values));
73
+ const means = list.map(() => new Float64Array(RESAMPLES));
74
+ const sums = new Float64Array(list.length);
75
+ const next = random(seed);
76
+ for (let round = 0; round < RESAMPLES; round++) {
77
+ sums.fill(0);
78
+ for (let i = 0; i < size; i++) {
79
+ const index = Math.floor(next() * size);
80
+ for (let k = 0; k < sources.length; k++) sums[k] += sources[k][index];
81
+ }
82
+ for (let k = 0; k < sources.length; k++) means[k][round] = sums[k] / size;
83
+ }
84
+ // Symmetric positions, so swapping a and b mirrors the interval exactly.
85
+ const index = Math.floor(upperTail(Math.sqrt(size / (size - 1)) * t975(size - 1)) * RESAMPLES);
86
+ return means.map((each) => {
87
+ each.sort();
88
+ return { low: each[index], high: each[RESAMPLES - 1 - index] };
89
+ });
90
+ }
91
+
92
+ // Too few prompts, or nearly all the same: the data cannot show how much prompts differ.
93
+ // All 0% or all 100% is the extreme case, where resampling gives a zero-width interval.
94
+ function tooLittleVariation(values) {
95
+ if (values.length < MIN_PROMPTS) return true;
96
+ const times = new Map();
97
+ let most = 0;
98
+ for (const value of values) {
99
+ const key = Math.round(value * SCALE);
100
+ const seen = (times.get(key) ?? 0) + 1;
101
+ times.set(key, seen);
102
+ if (seen > most) most = seen;
103
+ }
104
+ return values.length - most < MIN_INFORMATIVE_PROMPTS;
105
+ }
106
+
107
+ /**
108
+ * The interval of the average of per-prompt rates.
109
+ * When the variation between prompts can't be seen, it is widened to include the Wilson interval that counts each
110
+ * prompt as one sample. That is the most conservative choice: for values in [0, 1] with mean p, the variance is at
111
+ * most p(1−p) (Bhatia–Davis). So 20 prompts × 30 samples, all 0%, give an upper limit of 16%, not 0.6%.
112
+ */
113
+ export function rateInterval(rates, seed = SEED) {
114
+ return rateIntervals([rates], seed)[0];
115
+ }
116
+
117
+ /** Several lists at once; the same result as calling rateInterval on each. Every list needs at least one prompt. */
118
+ export function rateIntervals(list, seed = SEED) {
119
+ const resampled = new Map();
120
+ const bySize = new Map();
121
+ list.forEach((rates, index) => {
122
+ const indexes = bySize.get(rates.length);
123
+ if (indexes) indexes.push(index);
124
+ else bySize.set(rates.length, [index]);
125
+ });
126
+ for (const [size, indexes] of bySize) {
127
+ if (size < 2) continue;
128
+ bootstrapMeans(indexes.map((index) => list[index]), seed).forEach((interval, k) => resampled.set(indexes[k], interval));
129
+ }
130
+ return list.map((rates, index) => {
131
+ if (rates.length === 0) throw new RangeError("rateIntervals needs at least one prompt in every list");
132
+ const conservative = wilson(mean(rates), rates.length);
133
+ if (rates.length < 2) return conservative;
134
+ return tooLittleVariation(rates) ? union(resampled.get(index), conservative) : resampled.get(index);
135
+ });
136
+ }
137
+
138
+ /**
139
+ * The interval of b − a for the same prompts measured twice. a[i] and b[i] are the same prompt ({ rate, n }); a drawn
140
+ * prompt brings both its before and after results.
141
+ */
142
+ export function differenceInterval(a, b, seed = SEED) {
143
+ const size = a.length;
144
+ if (size < 2 || b.length !== size) throw new RangeError("differenceInterval needs the same two or more prompts on both sides");
145
+ const before = a.map((each) => each.rate);
146
+ const after = b.map((each) => each.rate);
147
+ const changes = after.map((rate, i) => rate - before[i]);
148
+ let result = bootstrapMean(changes, seed);
149
+
150
+ if (tooLittleVariation(changes)) {
151
+ // The changes barely differ between prompts: count each prompt as one sample, as above.
152
+ result = union(result, newcombe(mean(before), size, mean(after), size));
153
+ } else if (tooLittleVariation(before) || tooLittleVariation(after)) {
154
+ // The changes vary, but one side is almost all 0% or 100%, and its own sampling error is missing from the changes.
155
+ // Count answers instead: prompts × the smallest sample count of any prompt.
156
+ const samples = (side) => size * side.reduce((least, each) => Math.min(least, each.n), Infinity);
157
+ result = union(result, newcombe(mean(before), samples(a), mean(after), samples(b)));
158
+ }
159
+
160
+ // With too few changed prompts, the sign test can't rule out "no change", so the interval must contain 0.
161
+ const changed = changes.filter((change) => Math.round(change * SCALE) !== 0).length;
162
+ return changed < MIN_INFORMATIVE_PROMPTS ? union(result, { low: 0, high: 0 }) : result;
163
+ }
package/src/brand.js ADDED
@@ -0,0 +1,249 @@
1
+ // Brand and domain matching. The rules are public and versioned: the full description is in README.md.
2
+ // Any change to a rule bumps BRAND_RULES_VERSION (and METHOD_VERSION in visibility.js).
3
+ //
4
+ // Only whether a brand is mentioned is checked, not whether the mention is positive: "I don't recommend Acme" counts.
5
+ const BRAND_RULES_VERSION = "2";
6
+ const BRAND_RULES = `brand-rules/${BRAND_RULES_VERSION}: checks the answer body only, never citation titles or URLs. Markdown links count by their visible text. Reference markers, numbered source lists, source labels, image alt text, emails and fenced code (also inside block quotes) are ignored; inline code counts. Text is normalized (NFKC, lower case, Latin accents removed, quotes, dashes and spaces unified, no space between CJK and Latin or digits). Letters and digits need a word boundary. Chinese, Hiragana and Thai do not. Katakana needs a boundary on both sides, Hangul only on the left. A match inside an excluded phrase does not count; other matches still do. Negative mentions count. Domains include their subdomains. Several brands are ordered by where each is first mentioned in the normalized body; at the same place the longer match comes first. A name or alias can belong to only one brand. See the README for the full rules.`;
7
+ const SOURCE_LINE_START = /^\s*(?:[-*+]\s+)?\[\^?\d+\]/;
8
+ const SOURCE_LINE_END = /https?:\/\/\S+$/i;
9
+ const FOOTNOTE_OR_REFERENCE = /^\s*\[(?:\^[^\]]+\]:|[^\]]+\]:\s*<?https?:\/\/)/i;
10
+ const LINK_TARGET = String.raw`\(\s*(<[^<>\n]{0,4000}>|(?:[^\s()<>]|\([^\s()]{0,500}\)){0,4000})(?:\s+(?:"[^"\n]{0,500}"|'[^'\n]{0,500}'))?\s*\)`;
11
+ const LINK_LABEL = String.raw`\[((?:[^\[\]\n]|\[[^\[\]\n]{0,200}\]){0,500})\]`;
12
+ const IMAGE = new RegExp(`!${LINK_LABEL}${LINK_TARGET}`, "g");
13
+ const LINK = new RegExp(`${LINK_LABEL}${LINK_TARGET}`, "g");
14
+ const BARE_URL = /(?:https?:\/\/(?:[\p{L}\p{N}-]{1,63}\.){0,10}|\bwww\.)(?:\([!#-'*-;=?-Z^_a-z~]{0,500}\)|[!#-'+-;=?-Z^_a-z~])+/giu;
15
+ const EMAIL = /[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63})+/g;
16
+ const BLOCK_TAG = /<\/?(?:br|p|div|li|ul|ol|tr|td|th|table|h[1-6])\b[^<>]*>/gi;
17
+ const REFERENCE = /\[\^[^\]\s]{1,50}\]|\[\d{1,3}(?:\s*[,,、–-]\s*\d{1,3})*\]|【(?:\d+|turn\d+)[^】\n]{0,50}】/g;
18
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", "#39": "'", nbsp: " " };
19
+ const BLOCK_START = /^\s*(?:#{1,6}\s|[-*+•]\s|\d+[.)、]|>|\|)/;
20
+ const STANDALONE = /^\s*(?:#{1,6}\s|\|)/;
21
+ function isSourceLabel(label, target) {
22
+ const text = label.replace(/[*`_]/g, "").trim();
23
+ if (/^\[?\^?\d+\]?$/.test(text)) return true;
24
+ if (!/^[\p{L}\p{N}.-]+\.\p{L}{2,}$/u.test(text)) return false;
25
+ const address = target.replace(/^<|>$/g, "");
26
+ const host = hostname(address);
27
+ if (host === null || host.replace(/^www\./, "") !== hostname(text)?.replace(/^www\./, "")) return false;
28
+ const path = /^[a-z]+:\/\/[^/?#]+(\/[^?#]*)?/i.exec(address)?.[1];
29
+ return path !== void 0 && path !== "/";
30
+ }
31
+ const QUOTED = /^[ \t]*((?:>[ \t]*)*)(.*)$/;
32
+ function withoutFences(text) {
33
+ const lines = text.split("\n");
34
+ const parts = lines.map((line) => {
35
+ const [, quotes, rest] = QUOTED.exec(line);
36
+ return { depth: quotes.split(">").length - 1, rest };
37
+ });
38
+ const kept = [];
39
+ for (let i = 0; i < lines.length; i++) {
40
+ const fence = /^(`{3,}|~{3,})/.exec(parts[i].rest)?.[1];
41
+ let end = -1;
42
+ if (fence !== void 0) {
43
+ const { depth } = parts[i];
44
+ for (let j = i + 1; j < lines.length; j++) {
45
+ const { depth: inner, rest } = parts[j];
46
+ if (depth > 0 && inner < depth) break;
47
+ if (inner === depth && rest.startsWith(fence) && /^[`~]*[ \t]*$/.test(rest.slice(fence.length))) {
48
+ end = j;
49
+ break;
50
+ }
51
+ }
52
+ }
53
+ if (end < 0) kept.push(lines[i]);
54
+ else {
55
+ kept.push("\n\n");
56
+ i = end;
57
+ }
58
+ }
59
+ return kept.join("\n");
60
+ }
61
+ /** The text a reader sees in a markdown answer: no fenced code, URLs, emails, images, reference markers or source lists. */
62
+ function readableText(source) {
63
+ const withoutCode = withoutFences(source.replace(/\r\n?/g, "\n")).replace(/<(cite|script|style)\b[^<>]*>[\s\S]*?<\/\1\s*>/gi, " ");
64
+ const lines = withoutCode.split("\n").map((line) => {
65
+ if (FOOTNOTE_OR_REFERENCE.test(line)) return "";
66
+ return SOURCE_LINE_START.test(line) && SOURCE_LINE_END.test(line.trimEnd()) ? "" : line;
67
+ });
68
+ const inline = lines.join("\n").replace(IMAGE, " ").replace(LINK, (_, label, target) => isSourceLabel(label, target) ? " " : label).replace(BARE_URL, " ").replace(EMAIL, " ").replace(BLOCK_TAG, "\n\n").replace(/<\/?[a-z][a-z0-9-]*(?:\s[^<>]*)?\/?>/gi, "").replace(REFERENCE, " ").replace(/[¹²³⁰⁴-⁹₀-₉①-⓿❶-➓]+/g, " ").replace(/`+|\*{2,}|~~/g, "").replace(/(?<![\p{L}\p{N}*\\])\*(?=[^\s*])([^*\n]{1,300})(?<=[^\s*])\*/gu, "$1").replace(/\\([!-/:-@[-`{-~])/g, "$1").replace(/&(amp|lt|gt|quot|apos|#39|nbsp);/g, (_, name) => ENTITIES[name]);
69
+ let text = "";
70
+ let previous = "";
71
+ for (const line of inline.split("\n")) {
72
+ const separate = !line.trim() || !previous.trim() || BLOCK_START.test(line) || STANDALONE.test(previous);
73
+ text += (separate ? "\n" : " ") + line;
74
+ previous = line;
75
+ }
76
+ return text;
77
+ }
78
+ const CJK = String.raw`[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}ー]`;
79
+ const LATIN = String.raw`[\p{Script=Latin}\p{Nd}]`;
80
+ const MIXED_SPACE = new RegExp(`(?<=${CJK}) (?=${LATIN})|(?<=${LATIN}) (?=${CJK})`, "gu");
81
+ /** NFKC, lower case, Latin accents removed, quotes, dashes and spaces unified, no space between CJK and Latin or digits. Bodies and names use the same steps. */
82
+ function normalizeText(source) {
83
+ let text = source.replace(/[™℠®©]/g, "").replace(/[‘’‚‛ʼ′´`]/g, "'").normalize("NFKC").toLowerCase().replace(/[­​-‏⁠-⁤︀-️]/g, "").replace(/[‐-―−]/g, "-").replace(/ς/g, "\u03C3");
84
+ if (/[^\x00-\x7f]/.test(text)) {
85
+ text = text.normalize("NFD").replace(/(\p{Script=Latin})[̀-ͯ]+/gu, "$1").normalize("NFC");
86
+ }
87
+ return text.replace(/[^\S\n]+/g, " ").replace(MIXED_SPACE, "");
88
+ }
89
+ const normalizeNames = (names) => [
90
+ ...new Set(names.map((name) => normalizeText((name ?? "").replace(/\s+/g, " ")).trim()).filter(Boolean))
91
+ ];
92
+ function kindOf(char) {
93
+ if (char === "") return "other";
94
+ if (/[\p{Script=Katakana}ー]/u.test(char)) return "katakana";
95
+ if (/\p{Script=Hangul}/u.test(char)) return "hangul";
96
+ if (/\p{M}/u.test(char)) return "mark";
97
+ if (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Bopomofo}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u.test(char)) return "unspaced";
98
+ return /[\p{L}\p{N}]/u.test(char) ? "word" : "other";
99
+ }
100
+ const charAt = (text, index) => {
101
+ const point = text.codePointAt(index);
102
+ return point === void 0 ? "" : String.fromCodePoint(point);
103
+ };
104
+ function charBefore(text, index) {
105
+ if (index <= 0) return "";
106
+ const low = text.charCodeAt(index - 1);
107
+ return low >= 56320 && low <= 57343 && index >= 2 ? text.slice(index - 2, index) : text[index - 1];
108
+ }
109
+ const isDigit = (char) => char !== void 0 && char >= "0" && char <= "9";
110
+ function bounded(text, start, end) {
111
+ const before = kindOf(charBefore(text, start));
112
+ const first = kindOf(charAt(text, start));
113
+ if ((first === "word" || first === "katakana" || first === "hangul") && before === first) return false;
114
+ if (first === "word" && before === "mark") return false;
115
+ if (first === "other" && before === "word") return false;
116
+ if (isDigit(text[start]) && text[start - 1] === "." && isDigit(text[start - 2])) return false;
117
+ const after = kindOf(charAt(text, end));
118
+ const last = kindOf(charBefore(text, end));
119
+ if (after === "mark") return false;
120
+ if ((last === "word" || last === "katakana") && after === last) return false;
121
+ return !(isDigit(text[end - 1]) && text[end] === "." && isDigit(text[end + 1]));
122
+ }
123
+ function* occurrences(text, name) {
124
+ for (let start = text.indexOf(name); start >= 0; start = text.indexOf(name, start + 1)) {
125
+ const end = start + name.length;
126
+ if (bounded(text, start, end)) yield [start, end];
127
+ }
128
+ }
129
+ function namesOf(target) {
130
+ if (normalizeNames([target.brand]).length === 0) return null;
131
+ return { names: normalizeNames([target.brand, ...target.aliases ?? []]), excluded: normalizeNames(target.exclude ?? []) };
132
+ }
133
+ function firstSpan(text, { names, excluded }) {
134
+ let blocked;
135
+ let first = null;
136
+ for (const name of names) {
137
+ for (const [start, end] of occurrences(text, name)) {
138
+ if (first !== null && start > first[0]) break;
139
+ blocked ??= excluded.flatMap((phrase) => [...occurrences(text, phrase)]);
140
+ if (blocked.some(([from, to]) => from <= start && end <= to)) continue;
141
+ if (first === null || start < first[0] || end > first[1]) first = [start, end];
142
+ break;
143
+ }
144
+ }
145
+ return first;
146
+ }
147
+ /** readableText, then normalizeText. Compute once per answer when checking several brands. */
148
+ const bodyText = (body) => normalizeText(readableText(body));
149
+ /** A brand name as compared: spellings that differ only in case, width or spacing get the same key. */
150
+ const brandKey = (name) => normalizeNames([name])[0] ?? "";
151
+ /** Returns a test for one brand ({ brand, aliases, exclude }), or null when no brand name is given (not measured, not "no mention"). */
152
+ function brandMatcher(target) {
153
+ const names = namesOf(target);
154
+ if (names === null) return null;
155
+ return (body) => firstSpan(bodyText(body), names) !== null;
156
+ }
157
+ /** Whether the body mentions the brand; null when no brand name is given. */
158
+ function mentionsBrand(body, target) {
159
+ return brandMatcher(target)?.(body) ?? null;
160
+ }
161
+ /** The first name or alias (after normalization) that belongs to two brands, or null. */
162
+ function nameClash(brands) {
163
+ const owners = /* @__PURE__ */ new Map();
164
+ for (const [index, target] of brands.entries()) {
165
+ const names = [[null, target.brand ?? ""], ...(target.aliases ?? []).map((name, alias) => [alias, name])];
166
+ for (const [alias, name] of names) {
167
+ const key = brandKey(name);
168
+ if (key === "") continue;
169
+ const seen = owners.get(key);
170
+ if (seen === void 0) owners.set(key, { brand: index, alias, name });
171
+ else if (seen.brand !== index) return { first: seen, second: { brand: index, alias, name } };
172
+ }
173
+ }
174
+ return null;
175
+ }
176
+ /** Returns a function that takes bodyText(body) and lists the brands mentioned, in order of first mention; at the same place the longer match comes first. */
177
+ function brandsFinder(targets) {
178
+ const compiled = targets.map(namesOf);
179
+ return (text) => compiled.flatMap((names, index) => {
180
+ const found = names === null ? null : firstSpan(text, names);
181
+ return found === null ? [] : [{ index, start: found[0], end: found[1] }];
182
+ }).sort((a, b) => a.start - b.start || b.end - a.end || a.index - b.index);
183
+ }
184
+ /** The hostname of a URL or bare domain (WHATWG URL rules, IDN as punycode), or null. */
185
+ function hostname(source) {
186
+ const text = source.trim();
187
+ const address = /^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text.replace(/^\/\//, "")}`;
188
+ let parsed;
189
+ try {
190
+ parsed = new URL(address);
191
+ } catch {
192
+ return null;
193
+ }
194
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
195
+ const host = parsed.hostname.replace(/\.+$/, "");
196
+ return host.includes(".") ? host : null;
197
+ }
198
+ const SHARED_SUFFIX = /^(?:com|net|org|edu|gov|gob|gouv|ac|co|go|or|ne|re|mil|nhs)\.[a-z]{2}$/;
199
+ /** A target domain without a leading "*." or "www." (kept when the rest would be a shared suffix such as gov.uk). */
200
+ function normalizeDomain(source) {
201
+ const host = hostname(source.trim().replace(/^\*?\./, ""));
202
+ if (host === null || !host.startsWith("www.")) return host;
203
+ const rest = host.slice(4);
204
+ return rest.includes(".") && !SHARED_SUFFIX.test(rest) ? rest : host;
205
+ }
206
+ /** Returns a test for sources ({ url, domain }) on the domains or their subdomains, or null when no domain is valid (not measured). */
207
+ function domainMatcher(domains) {
208
+ const targets = [...new Set((domains ?? []).map(normalizeDomain).filter((each) => each !== null))];
209
+ if (targets.length === 0) return null;
210
+ return (source) => {
211
+ const host = (source.url ? hostname(source.url) : null) ?? (source.domain ? hostname(source.domain) : null);
212
+ return host !== null && targets.some((target) => host === target || host.endsWith(`.${target}`));
213
+ };
214
+ }
215
+ function citedFor(isTarget, citations) {
216
+ if (isTarget === null || citations === null) return null;
217
+ const own = citations.filter(isTarget);
218
+ if (own.some((each) => each.cited === true)) return true;
219
+ return own.some((each) => each.cited === null) ? null : false;
220
+ }
221
+ /** Compiles the brands once; returns (body, citations) => the mentioned brands with position (from 1) and cited, or null without a body. */
222
+ function brandReader(brands) {
223
+ const find = brandsFinder(brands);
224
+ const keys = brands.map((each) => brandKey(each.brand ?? ""));
225
+ const domains = brands.map((each) => domainMatcher(each.domains));
226
+ return (body, citations) => {
227
+ if (body === null) return null;
228
+ return find(bodyText(body)).map((found, i) => ({ brand: brands[found.index].brand, key: keys[found.index], position: i + 1, cited: citedFor(domains[found.index], citations) }));
229
+ };
230
+ }
231
+ /** The brands given that one answer mentions, in order. Only the brands given are recognised; others are never guessed. */
232
+ const brandMentions = (body, citations, brands) => brandReader(brands)(body, citations);
233
+ export {
234
+ BRAND_RULES,
235
+ BRAND_RULES_VERSION,
236
+ bodyText,
237
+ brandKey,
238
+ brandMatcher,
239
+ brandMentions,
240
+ brandReader,
241
+ brandsFinder,
242
+ domainMatcher,
243
+ hostname,
244
+ mentionsBrand,
245
+ nameClash,
246
+ normalizeDomain,
247
+ normalizeText,
248
+ readableText
249
+ };
@@ -0,0 +1,315 @@
1
+ // Visibility of a brand in AI answers: answer rate, mention rate, citation rate and competitor share, each with a 95%
2
+ // interval and an `enough` flag. The same input always gives the same result, whatever the order of the answers.
3
+ import { mean, MIN_PROMPTS, rateIntervals, SEED } from "./bootstrap.js";
4
+ import { BRAND_RULES, brandKey, brandMatcher, brandsFinder, bodyText, domainMatcher, nameClash } from "./brand.js";
5
+ import { wilson } from "./wilson.js";
6
+
7
+ /** Bumped whenever a denominator, interval, matching rule or threshold changes. Same version, same results. */
8
+ export const METHOD_VERSION = "1.1.0";
9
+
10
+ /** A rate needs at least 30 answers. At 30, the widest Wilson interval is about ±17 points: enough to read the interval, not to rank. */
11
+ export const MIN_SAMPLES = 30;
12
+ /** Failed and pending answers may be at most 20% (per-prompt average): failures are rarely random. */
13
+ export const MAX_MISSING_SHARE = 0.2;
14
+ /** Unknown outcomes (search or citation status unclear) may be at most 5%: why an outcome is unknown often depends on what it is. */
15
+ export const MAX_UNKNOWN_SHARE = 0.05;
16
+
17
+ const PER_PROMPT = "With more than one prompt, value is the average of the per-prompt rates, so each prompt counts equally and value can differ from count / sample_size.";
18
+ const method = () => ({
19
+ version: METHOD_VERSION,
20
+ denominators: {
21
+ answer_rate: `answered / (answered + no_answer + refused). failed and pending are counted separately. ${PER_PROMPT}`,
22
+ mention_rate: `answered results that mention the brand / all answered results, including those without a search. Positive and negative mentions both count. ${PER_PROMPT}`,
23
+ citation_rate: `answered results with at least one target domain cited in the answer / answered results that searched and whose citations are all marked as cited or not cited. An empty citation list counts as not cited, unless every non-empty list in the group is unclear. A missing list is unknown. Inclusion never depends on the target domains. ${PER_PROMPT}`,
24
+ first_share: `answered results where the brand is mentioned before every other brand in brands / answered results that mention at least one of them. Only the brands given are ranked, not every brand in the answer. Each brand's mention_rate in brands uses the mention_rate denominator. ${PER_PROMPT}`
25
+ },
26
+ brand_rules: BRAND_RULES,
27
+ seed: SEED
28
+ });
29
+ // Map.groupBy, for Node.js versions before 21.
30
+ function groupBy(items, keyOf) {
31
+ const groups = new Map();
32
+ for (const item of items) {
33
+ const key = keyOf(item);
34
+ const list = groups.get(key);
35
+ if (list) list.push(item);
36
+ else groups.set(key, [item]);
37
+ }
38
+ return groups;
39
+ }
40
+ const byText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
41
+ const isMissing = (answer) => answer.status === "failed" || answer.status === "pending";
42
+ const planKey = ({ engine, tier, conditions: { requested } }) => JSON.stringify([engine, tier, requested.country, requested.region]);
43
+ function fieldsOf(answer) {
44
+ const { surface, interface: entry, login, thinking, actual, requested } = answer.conditions;
45
+ return {
46
+ engine: answer.engine,
47
+ channel_id: answer.channel_id,
48
+ tier: answer.tier,
49
+ conditions: {
50
+ surface,
51
+ interface: entry,
52
+ login,
53
+ thinking,
54
+ country: actual.country,
55
+ region: actual.region,
56
+ // Country and region are separate: with only the country known, different requested regions stay apart.
57
+ requested_country: actual.country === null ? requested.country : null,
58
+ requested_region: actual.region === null ? requested.region : null
59
+ }
60
+ };
61
+ }
62
+ const flatten = ({ conditions, ...rest }) => ({ ...rest, ...conditions });
63
+ const keyOf = (fields) => JSON.stringify(Object.values(flatten(fields)));
64
+ function group(answers) {
65
+ const groups = /* @__PURE__ */ new Map();
66
+ const ids = /* @__PURE__ */ new Set();
67
+ const add = (answer, fields = fieldsOf(answer)) => {
68
+ const key = keyOf(fields);
69
+ let found = groups.get(key);
70
+ if (!found) groups.set(key, found = { key, fields, answers: [], plans: /* @__PURE__ */ new Set(), planned: [] });
71
+ found.answers.push(answer);
72
+ found.plans.add(planKey(answer));
73
+ };
74
+ for (const answer of answers) {
75
+ if (ids.has(answer.id)) throw new Error(`Duplicate answer id: ${answer.id}`);
76
+ ids.add(answer.id);
77
+ if (!isMissing(answer)) add(answer);
78
+ }
79
+ const finished = [...groups.values()].map((each) => ({ fields: each.fields, plans: new Set(each.plans) }));
80
+ for (const answer of answers) {
81
+ if (!isMissing(answer)) continue;
82
+ const own = fieldsOf(answer);
83
+ const plan = planKey(answer);
84
+ const matches = finished.filter(
85
+ ({ fields, plans }) => plans.has(plan) && (own.channel_id === null || fields.channel_id === own.channel_id) && ["surface", "interface", "login", "thinking", "country", "region"].every((name) => own.conditions[name] === null || own.conditions[name] === fields.conditions[name])
86
+ );
87
+ add(answer, matches.length === 1 ? matches[0].fields : own);
88
+ }
89
+ const byPlan = groupBy(answers, planKey);
90
+ const sorted = [...groups.values()].sort((a, b) => byText(a.key, b.key));
91
+ for (const each of sorted) {
92
+ const { thinking } = each.fields.conditions;
93
+ each.planned = [...each.plans].flatMap((plan) => byPlan.get(plan)).filter((answer) => {
94
+ const other = answer.conditions.thinking;
95
+ return other === thinking || isMissing(answer) && (other === null || thinking === null);
96
+ });
97
+ }
98
+ return sorted;
99
+ }
100
+ function tally(answers, outcome, reliable = true) {
101
+ const seen = /* @__PURE__ */ new Map();
102
+ for (const answer of answers) {
103
+ const result = outcome(answer);
104
+ if (result === void 0) continue;
105
+ let prompt = seen.get(answer.prompt);
106
+ if (!prompt) seen.set(answer.prompt, prompt = { count: 0, n: 0, unknown: 0 });
107
+ if (result === null) prompt.unknown++;
108
+ else {
109
+ prompt.n++;
110
+ if (result) prompt.count++;
111
+ }
112
+ }
113
+ const sorted = [...seen].sort(([a], [b]) => byText(a, b));
114
+ return {
115
+ prompts: new Map(sorted.filter(([, each]) => each.n > 0).map(([prompt, { count, n }]) => [prompt, { count, n }])),
116
+ due: new Set(seen.keys()),
117
+ unknownShare: sorted.length ? mean(sorted.map(([, each]) => each.unknown / (each.unknown + each.n))) : 0,
118
+ reliable
119
+ };
120
+ }
121
+ function citationClarity(answers) {
122
+ let clearLists = 0;
123
+ let unclearLists = 0;
124
+ for (const { status, search_triggered, citations } of answers) {
125
+ if (status !== "answered" || search_triggered !== true || !citations?.length) continue;
126
+ if (citations.every((each) => each.cited !== null)) clearLists++;
127
+ else unclearLists++;
128
+ }
129
+ const emptyCounts = clearLists > 0 || unclearLists === 0;
130
+ return {
131
+ clear: ({ citations }) => citations !== null && (citations.length ? citations.every((each) => each.cited !== null) : emptyCounts),
132
+ // Only empty lists seen: nothing shows the channel can tell cited sources apart, so no conclusion.
133
+ proven: clearLists > 0
134
+ };
135
+ }
136
+ function mentionTest(target) {
137
+ const matches = brandMatcher(target);
138
+ if (matches === null) return null;
139
+ return (answer) => {
140
+ const body = answer.text ?? answer.markdown;
141
+ return body === null ? null : matches(body);
142
+ };
143
+ }
144
+ function measure(answers, target, mentions = mentionTest(target)) {
145
+ const isTarget = domainMatcher(target.domains);
146
+ return group(answers).map((each) => {
147
+ const clarity = citationClarity(each.answers);
148
+ const answered = each.answers.filter((answer) => answer.status === "answered");
149
+ const tallies = {
150
+ answer_rate: tally(each.answers, (answer) => isMissing(answer) ? void 0 : answer.status === "answered")
151
+ };
152
+ if (mentions) {
153
+ tallies.mention_rate = tally(answered, mentions);
154
+ }
155
+ if (isTarget) {
156
+ tallies.citation_rate = tally(
157
+ answered,
158
+ (answer) => {
159
+ if (answer.search_triggered === false) return void 0;
160
+ if (answer.search_triggered === null || !clarity.clear(answer)) return null;
161
+ return answer.citations.some((citation) => citation.cited === true && isTarget(citation));
162
+ },
163
+ clarity.proven
164
+ );
165
+ }
166
+ return {
167
+ ...each,
168
+ tallies,
169
+ asked: new Set(each.planned.map((answer) => answer.prompt)),
170
+ present: new Set(each.answers.filter((answer) => !isMissing(answer)).map((answer) => answer.prompt)),
171
+ missingShare: mean(
172
+ [...groupBy(each.planned, (answer) => answer.prompt)].sort(([a], [b]) => byText(a, b)).map(([, list]) => list.filter(isMissing).length / list.length)
173
+ ),
174
+ searchUnknown: answered.filter((answer) => answer.search_triggered === null).length,
175
+ citedUnknown: answered.filter((answer) => answer.search_triggered === true && !clarity.clear(answer)).length
176
+ };
177
+ });
178
+ }
179
+ const round = (value) => Math.round(value * 1e6) / 1e6 + 0;
180
+ const rateOf = ({ count, n }) => ({ rate: count / n, n });
181
+ // several: the plan has more than one prompt. Even if only one has data, it can't stand for the whole set.
182
+ function rates(results, source, several, only) {
183
+ const prompts = results.map((result) => [...result?.prompts ?? []].filter(([prompt]) => !only || only.has(prompt)).map(([, each]) => each));
184
+ const values = prompts.map((list) => list.map((each) => rateOf(each).rate));
185
+ const measured = [...values.keys()].filter((index) => values[index].length > 0);
186
+ const intervals = new Map(several ? rateIntervals(measured.map((index) => values[index])).map((interval, k) => [measured[k], interval]) : []);
187
+ return results.map((result, index) => {
188
+ const list = prompts[index];
189
+ if (!result || list.length === 0) {
190
+ return { count: 0, sample_size: 0, prompt_count: 0, value: null, low: null, high: null, method: null, enough: false };
191
+ }
192
+ const value = mean(values[index]);
193
+ const samples = list.reduce((sum, each) => sum + each.n, 0);
194
+ const interval = several ? intervals.get(index) : wilson(value, samples);
195
+ return {
196
+ count: list.reduce((sum, each) => sum + each.count, 0),
197
+ sample_size: samples,
198
+ prompt_count: list.length,
199
+ value: round(value),
200
+ low: round(interval.low),
201
+ high: round(interval.high),
202
+ method: several ? "cluster_bootstrap_95" : "wilson_95",
203
+ enough: samples >= MIN_SAMPLES && (!several || list.length >= MIN_PROMPTS) && // Round first: an average of 0.2s can be 0.2000…01.
204
+ round(source.missingShare) <= MAX_MISSING_SHARE && round(result.unknownShare) <= MAX_UNKNOWN_SHARE && result.reliable
205
+ };
206
+ });
207
+ }
208
+ function shares(each, several, brands, found, own) {
209
+ const answered = each.answers.filter((answer) => answer.status === "answered");
210
+ const listed = (answer) => found.get(answer);
211
+ const mentions = brands.map(
212
+ (_, index) => index === 0 && own !== null ? void 0 : tally(answered, (answer) => listed(answer)?.some((one) => one.index === index) ?? null)
213
+ );
214
+ const firsts = brands.map(
215
+ (_, index) => tally(answered, (answer) => {
216
+ const list = listed(answer);
217
+ return list === null ? null : list.length === 0 ? void 0 : list[0].index === index;
218
+ })
219
+ );
220
+ const mentionRates = rates(mentions, each, several);
221
+ const firstShares = rates(firsts, each, several);
222
+ return brands.map((brand, index) => ({
223
+ brand: brand.brand,
224
+ key: brandKey(brand.brand),
225
+ mention_rate: index === 0 && own !== null ? own : mentionRates[index],
226
+ first_share: firstShares[index]
227
+ }));
228
+ }
229
+ function report(answers, target, competitors) {
230
+ const named = (each) => brandKey(each.brand ?? "") !== "";
231
+ const ownBrand = named(target);
232
+ const brands = competitors.length === 0 ? [] : [...ownBrand ? [target] : [], ...competitors.filter(named)];
233
+ const clash = nameClash(brands);
234
+ if (clash) throw new Error(`The name "${clash.second.name}" belongs to more than one brand`);
235
+ const find = brandsFinder(brands);
236
+ const found = /* @__PURE__ */ new Map();
237
+ if (brands.length > 0) {
238
+ for (const answer of answers) {
239
+ if (answer.status !== "answered") continue;
240
+ const body = answer.text ?? answer.markdown;
241
+ found.set(answer, body === null ? null : find(bodyText(body)));
242
+ }
243
+ }
244
+ const mentions = brands.length === 0 || !ownBrand ? mentionTest(target) : (answer) => found.get(answer)?.some((one) => one.index === 0) ?? null;
245
+ return {
246
+ method: method(),
247
+ rows: measure(answers, target, mentions).map((each) => {
248
+ const several = each.asked.size > 1;
249
+ const counts = { answered: 0, no_answer: 0, refused: 0, failed: 0, pending: 0 };
250
+ for (const answer of each.answers) counts[answer.status]++;
251
+ const [answerRate, mentionRate, citationRate] = rates([each.tallies.answer_rate, each.tallies.mention_rate, each.tallies.citation_rate], each, several);
252
+ return {
253
+ ...each.fields,
254
+ prompt_count: new Set(each.answers.map((answer) => answer.prompt)).size,
255
+ status_counts: counts,
256
+ answer_rate: answerRate,
257
+ mention_rate: mentionRate,
258
+ citation_rate: citationRate,
259
+ search_unknown: each.searchUnknown,
260
+ cited_unknown: each.citedUnknown,
261
+ brands: brands.length === 0 ? null : shares(each, several, brands, found, ownBrand ? mentionRate : null)
262
+ };
263
+ })
264
+ };
265
+ }
266
+ const STATUSES = ["answered", "no_answer", "refused", "failed", "pending"];
267
+ const orNull = (value) => (value === undefined ? null : value);
268
+ const textOrNull = (value) => (typeof value === "string" ? value : null);
269
+
270
+ // Fills in the optional fields of one answer. AskCrawl answers can be passed as they come from the API.
271
+ function input(answer, index) {
272
+ const at = `answers[${index}]`;
273
+ if (typeof answer?.prompt !== "string") throw new TypeError(`${at}.prompt must be a string`);
274
+ if (typeof answer.engine !== "string" || answer.engine === "") throw new TypeError(`${at}.engine must name the AI platform, for example "chatgpt"`);
275
+ const status = answer.status ?? "answered";
276
+ if (!STATUSES.includes(status)) throw new TypeError(`${at}.status must be one of ${STATUSES.join(", ")}`);
277
+ if (answer.citations != null && !Array.isArray(answer.citations)) throw new TypeError(`${at}.citations must be an array or null`);
278
+ const conditions = answer.conditions ?? {};
279
+ const place = (where) => ({ country: orNull(where?.country), region: orNull(where?.region) });
280
+ return {
281
+ // Ids are only used to refuse duplicates; an answer without one gets a private id.
282
+ id: answer.id == null ? Symbol(at) : String(answer.id),
283
+ prompt: answer.prompt,
284
+ engine: answer.engine,
285
+ channel_id: orNull(answer.channel_id ?? answer.channel?.id),
286
+ tier: answer.tier ?? answer.channel?.tier ?? "basic",
287
+ status,
288
+ search_triggered: orNull(answer.search_triggered),
289
+ text: textOrNull(answer.text),
290
+ markdown: textOrNull(answer.markdown),
291
+ citations: Array.isArray(answer.citations) ? answer.citations.map((each) => ({ url: orNull(each?.url), domain: orNull(each?.domain), cited: orNull(each?.cited) })) : null,
292
+ conditions: {
293
+ surface: orNull(conditions.surface),
294
+ interface: orNull(conditions.interface),
295
+ login: orNull(conditions.login),
296
+ thinking: orNull(conditions.thinking),
297
+ requested: place(conditions.requested),
298
+ actual: place(conditions.actual),
299
+ },
300
+ prompt_set: null,
301
+ };
302
+ }
303
+
304
+ /**
305
+ * Rates with 95% intervals, one row per group of answers collected under the same conditions (engine, channel, tier,
306
+ * surface, login, thinking, location; a field you leave out is one "unknown" value).
307
+ *
308
+ * target: { brand, aliases, exclude, domains }. Without brand, the mention rate is not measured; without a valid
309
+ * domain, the citation rate is not measured (value null, not 0%). options.competitors: [{ brand, aliases, exclude }];
310
+ * with them, each row gets brands[] with every brand's mention_rate and first_share.
311
+ */
312
+ export function visibility(answers, target = {}, { competitors = [] } = {}) {
313
+ if (!Array.isArray(answers)) throw new TypeError("answers must be an array");
314
+ return report(answers.map(input), target ?? {}, competitors);
315
+ }
package/src/wilson.js ADDED
@@ -0,0 +1,34 @@
1
+ // 95% intervals for one proportion, and for the difference of two independent proportions.
2
+
3
+ /** The 97.5% quantile of the standard normal distribution. */
4
+ export const Z95 = 1.959963984540054;
5
+
6
+ /** The smallest interval that contains both. */
7
+ export function union(a, b) {
8
+ return { low: Math.min(a.low, b.low), high: Math.max(a.high, b.high) };
9
+ }
10
+
11
+ /**
12
+ * Wilson (1927) score interval, without continuity correction.
13
+ * Not p ± 1.96·√(p(1−p)/n): that has zero width at 0% and 100%, and is too narrow for small samples.
14
+ * Takes a rate rather than a count, because an average of per-prompt rates need not be a whole number of hits.
15
+ */
16
+ export function wilson(rate, n) {
17
+ if (!(n > 0) || !(rate >= 0 && rate <= 1)) throw new RangeError("wilson needs a rate from 0 to 1 and n above 0");
18
+ const z2 = Z95 * Z95;
19
+ const center = (rate + z2 / (2 * n)) / (1 + z2 / n);
20
+ const half = (Z95 / (1 + z2 / n)) * Math.sqrt((rate * (1 - rate)) / n + z2 / (4 * n * n));
21
+ // The ends are exact, so floating point never gives -1e-17 or 0.9999….
22
+ return { low: rate === 0 ? 0 : center - half, high: rate === 1 ? 1 : center + half };
23
+ }
24
+
25
+ /** Newcombe (1998) method 10: the interval for b − a from two Wilson intervals, assuming independent groups. */
26
+ export function newcombe(a, nA, b, nB) {
27
+ const left = wilson(a, nA);
28
+ const right = wilson(b, nB);
29
+ const difference = b - a;
30
+ return {
31
+ low: difference - Math.hypot(b - right.low, left.high - a),
32
+ high: difference + Math.hypot(right.high - b, a - left.low),
33
+ };
34
+ }