@adport/provider-matomo 0.16.1 → 0.16.2
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/dist/index.js +78 -15
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -80,7 +80,7 @@ import {
|
|
|
80
80
|
} from "@adport/core";
|
|
81
81
|
|
|
82
82
|
// src/acquisition.ts
|
|
83
|
-
import { AdportError as AdportError2 } from "@adport/core";
|
|
83
|
+
import { AdportError as AdportError2, rangeDayCount } from "@adport/core";
|
|
84
84
|
var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
85
85
|
function records(raw) {
|
|
86
86
|
const list = Array.isArray(raw) ? raw : object(raw) ? Object.values(raw) : null;
|
|
@@ -93,8 +93,75 @@ function table(raw) {
|
|
|
93
93
|
if (rows.length > maxRows) throw new AdportError2("PROVIDER_ERROR", "This Matomo archive exceeds the report limit. Choose a shorter date range.");
|
|
94
94
|
return rows;
|
|
95
95
|
}
|
|
96
|
-
var summary = (r) => r.label === "Others" || r.label === "-1" || Boolean(Number(r.is_summary));
|
|
96
|
+
var summary = (r) => r.label === "Others" || r.label === "-1" || r.label === -1 || Boolean(Number(r.is_summary));
|
|
97
97
|
var numeric = (v) => (typeof v === "number" || typeof v === "string" && v.trim()) && Number.isFinite(Number(v)) ? Number(v) : null;
|
|
98
|
+
function archiveLabel(row2) {
|
|
99
|
+
if (!summary(row2) && typeof row2.label === "string" && row2.label) return row2.label;
|
|
100
|
+
}
|
|
101
|
+
function labels(rows) {
|
|
102
|
+
const values = /* @__PURE__ */ new Set();
|
|
103
|
+
let complete = true;
|
|
104
|
+
for (const row2 of rows) {
|
|
105
|
+
const label = archiveLabel(row2);
|
|
106
|
+
if (label) values.add(label);
|
|
107
|
+
else complete = false;
|
|
108
|
+
}
|
|
109
|
+
return { values, complete };
|
|
110
|
+
}
|
|
111
|
+
function archiveVisits(rows) {
|
|
112
|
+
const byLabel = /* @__PURE__ */ new Map();
|
|
113
|
+
let total = 0;
|
|
114
|
+
for (const row2 of rows) {
|
|
115
|
+
const count = numeric(row2.nb_visits);
|
|
116
|
+
if (count === null || !Number.isSafeInteger(count) || count < 0) return;
|
|
117
|
+
total += count;
|
|
118
|
+
const label = archiveLabel(row2);
|
|
119
|
+
if (label) byLabel.set(label, (byLabel.get(label) ?? 0) + count);
|
|
120
|
+
}
|
|
121
|
+
if (Number.isSafeInteger(total)) return { total, byLabel };
|
|
122
|
+
}
|
|
123
|
+
async function campaignLabels(client, method, params, rows) {
|
|
124
|
+
const rangeLabels = labels(rows);
|
|
125
|
+
if (rangeLabels.complete || params.period !== "range") return rangeLabels;
|
|
126
|
+
const [start, end] = params.date.split(",");
|
|
127
|
+
const days = rangeDayCount({ start, end });
|
|
128
|
+
const range = archiveVisits(rows);
|
|
129
|
+
if (days > 31 || !range) return rangeLabels;
|
|
130
|
+
try {
|
|
131
|
+
const archives = await client.call("MarketingCampaignsReporting." + method, { ...params, period: "day" });
|
|
132
|
+
if (!object(archives)) return rangeLabels;
|
|
133
|
+
const daily = /* @__PURE__ */ new Map();
|
|
134
|
+
let dailyVisits = 0;
|
|
135
|
+
const startTime = Date.parse(start + "T00:00:00Z");
|
|
136
|
+
for (let offset = 0; offset < days; offset++) {
|
|
137
|
+
const date = new Date(startTime + offset * 864e5).toISOString().slice(0, 10);
|
|
138
|
+
if (!Object.hasOwn(archives, date)) return rangeLabels;
|
|
139
|
+
const day = table(archives[date]);
|
|
140
|
+
const counts = archiveVisits(day);
|
|
141
|
+
if (!counts || counts.byLabel.size !== day.length) return rangeLabels;
|
|
142
|
+
for (const [label, count] of counts.byLabel) daily.set(label, (daily.get(label) ?? 0) + count);
|
|
143
|
+
if (daily.size > maxRows) return rangeLabels;
|
|
144
|
+
dailyVisits += counts.total;
|
|
145
|
+
}
|
|
146
|
+
return dailyVisits === range.total && [...range.byLabel].every(([label, count]) => daily.get(label) === count) ? { values: new Set(daily.keys()), complete: true } : rangeLabels;
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (!(error instanceof AdportError2 && error.code === "PROVIDER_ERROR")) throw error;
|
|
149
|
+
return rangeLabels;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function sourceMedium(label, sources, media) {
|
|
153
|
+
const candidates = [];
|
|
154
|
+
if (!sources.complete || sources.values.has(label)) candidates.push([label, null]);
|
|
155
|
+
if (!media.complete || media.values.has(label)) candidates.push([null, label]);
|
|
156
|
+
for (let pos = label.indexOf(" - "); pos >= 0; pos = label.indexOf(" - ", pos + 1)) {
|
|
157
|
+
const source = label.slice(0, pos), medium = label.slice(pos + 3);
|
|
158
|
+
if (source && medium && (!sources.complete || sources.values.has(source)) && (!media.complete || media.values.has(medium))) {
|
|
159
|
+
candidates.push([source, medium]);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const match = candidates.length === 1 ? candidates[0] : void 0;
|
|
163
|
+
if (match && (match[0] === null || sources.values.has(match[0])) && (match[1] === null || media.values.has(match[1]))) return match;
|
|
164
|
+
}
|
|
98
165
|
function measures(r, site, ids) {
|
|
99
166
|
const goals = object(r.goals) ? r.goals : {};
|
|
100
167
|
const goalMetric = (id, field) => {
|
|
@@ -157,22 +224,18 @@ async function groups(client, params, site, plugin, ids, notes) {
|
|
|
157
224
|
let siteTotal = zero, namedTotal = zero;
|
|
158
225
|
for (const channel of channels) siteTotal = combine(siteTotal, measuresFor(channel));
|
|
159
226
|
const namedChildren = /* @__PURE__ */ new Map(), rows = [];
|
|
160
|
-
const sourceLabels
|
|
161
|
-
|
|
227
|
+
const [sourceLabels, mediumLabels] = pairs.some(archiveLabel) ? await Promise.all([
|
|
228
|
+
campaignLabels(client, "getSource", params, sources),
|
|
229
|
+
campaignLabels(client, "getMedium", params, media)
|
|
230
|
+
]) : [labels(sources), labels(media)];
|
|
162
231
|
for (const pair of pairs) {
|
|
163
|
-
|
|
164
|
-
const
|
|
165
|
-
if (
|
|
166
|
-
|
|
167
|
-
for (let pos = label.indexOf(" - "); pos >= 0; pos = label.indexOf(" - ", pos + 1)) {
|
|
168
|
-
const source2 = label.slice(0, pos), medium2 = label.slice(pos + 3);
|
|
169
|
-
if (sourceLabels.has(source2) && mediumLabels.has(medium2)) candidates.push([source2, medium2]);
|
|
170
|
-
}
|
|
171
|
-
if (candidates.length !== 1 || archivedLabels) {
|
|
172
|
-
notes.add("Matomo returned an ambiguous or archived source/medium label. Its traffic stays in the unresolved dimensions.");
|
|
232
|
+
const label = archiveLabel(pair);
|
|
233
|
+
const dimensions = label ? sourceMedium(label, sourceLabels, mediumLabels) : void 0;
|
|
234
|
+
if (!dimensions) {
|
|
235
|
+
notes.add("Some Matomo source and medium labels remain unresolved. Their counts appear in the campaign or site totals.");
|
|
173
236
|
continue;
|
|
174
237
|
}
|
|
175
|
-
const [source, medium] =
|
|
238
|
+
const [source, medium] = dimensions;
|
|
176
239
|
let children = zero;
|
|
177
240
|
const parent = measuresFor(pair);
|
|
178
241
|
for (const child of table(pair.subtable ?? [])) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/provider.ts","../src/acquisition.ts"],"sourcesContent":["import { normalizeMatomoUrl, type CredentialStore, type ProviderModule } from '@adport/core';\nimport { MatomoClient, type MatomoCredentials } from './client.js';\nimport { MatomoProvider } from './provider.js';\nexport { MatomoClient, MATOMO_READ_METHODS, type MatomoBearerCredentials, type MatomoCredentials } from './client.js';\nexport { MatomoProvider, matomoSiteId, type MatomoSite } from './provider.js';\nexport { matomoBaseUrl, normalizeMatomoUrl } from '@adport/core';\n\n/** Stored data uses { url, token_auth }; both values are required. */\nexport function matomoCredentialsFromData(data: Record<string, string> | undefined): MatomoCredentials | undefined {\n const url = data?.url?.trim(), tokenAuth = data?.token_auth?.trim();\n return url && tokenAuth ? { url: normalizeMatomoUrl(url), tokenAuth } : undefined;\n}\nexport function matomoEnvironmentData(): Record<string, string> {\n return { url: process.env.MATOMO_URL ?? '', token_auth: process.env.MATOMO_TOKEN_AUTH ?? '' };\n}\n/** Unusable values (e.g. a non-https URL) count as absent so one bad pair never stops other providers from loading. */\nfunction usableCredentials(data: Record<string, string> | undefined): MatomoCredentials | undefined {\n try { return matomoCredentialsFromData(data); } catch { return undefined; }\n}\nexport async function resolveMatomoCredentials(store: CredentialStore): Promise<MatomoCredentials | undefined> {\n return usableCredentials((await store.get('matomo'))?.data) ?? usableCredentials(matomoEnvironmentData());\n}\nexport async function createMatomoModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveMatomoCredentials(store);\n if (!credentials) return undefined;\n let client: MatomoClient;\n try { client = new MatomoClient(credentials); } catch { return undefined; }\n const provider = new MatomoProvider(client);\n return { provider, tools: [] };\n}\n","import { AdportError, normalizeMatomoUrl } from '@adport/core';\n\ntype MatomoFetch = (url: string, init: {\n method: 'POST'; redirect: 'error'; signal: AbortSignal; headers: Record<string, string>; body: URLSearchParams;\n}) => Promise<Pick<Response, 'ok' | 'status' | 'text'>>;\n\nexport interface MatomoCredentials {\n /** Instance base URL, e.g. https://example.matomo.cloud or https://analytics.example.com/matomo. */\n url: string;\n /** Personal auth token of a user with view access to the sites. */\n tokenAuth: string;\n}\n\nexport interface MatomoBearerCredentials {\n url: string;\n accessToken(): Promise<string>;\n}\n\n/** Documented read methods only. Every other Matomo API method is refused before any request. */\nexport const MATOMO_READ_METHODS = new Set([\n 'API.getReportMetadata', 'SitesManager.getSitesWithAtLeastViewAccess', 'SitesManager.getSiteFromId', 'Goals.getGoals',\n 'Referrers.getReferrerType', 'Referrers.getCampaigns', 'MarketingCampaignsReporting.getName',\n 'MarketingCampaignsReporting.getSource', 'MarketingCampaignsReporting.getMedium', 'MarketingCampaignsReporting.getSourceMedium', 'Actions.getEntryPageUrls',\n]);\nconst RESERVED = new Set(['module', 'method', 'format', 'token_auth', 'force_api_session']);\n\n/**\n * Matomo Reporting API over POST so token_auth never appears in a URL. Matomo\n * answers most failures with HTTP 200 and {\"result\":\"error\"}; messages are\n * classified but never echoed, since they can contain instance details.\n */\nexport class MatomoClient {\n readonly baseUrl: string;\n constructor(private readonly credentials: MatomoCredentials | MatomoBearerCredentials, private readonly fetchImpl: MatomoFetch = fetch) {\n this.baseUrl = normalizeMatomoUrl(credentials.url);\n if ('tokenAuth' in credentials && !credentials.tokenAuth.trim()) throw new AdportError('INVALID_INPUT', 'matomo: token_auth is empty');\n }\n\n async call(method: string, params: Record<string, string> = {}): Promise<unknown> {\n if (!MATOMO_READ_METHODS.has(method)) throw new AdportError('INVALID_INPUT', 'Unsupported Matomo read method.');\n if (Object.keys(params).some(key => RESERVED.has(key))) throw new AdportError('INVALID_INPUT', 'Reserved Matomo request parameter.');\n const body = new URLSearchParams({ ...params, module: 'API', method, format: 'JSON' });\n const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };\n if ('accessToken' in this.credentials) headers.authorization = 'Bearer ' + await this.credentials.accessToken();\n else body.set('token_auth', this.credentials.tokenAuth.trim());\n let response: Awaited<ReturnType<MatomoFetch>>;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/index.php`, {\n method: 'POST', redirect: 'error', signal: AbortSignal.timeout(30_000),\n headers, body,\n });\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'Matomo could not be reached (network error, redirect or timeout). Check MATOMO_URL.');\n }\n if (response.status === 401) throw new AdportError('NOT_CONNECTED', 'Matomo rejected the auth token. Reconnect Matomo to renew access.');\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `Matomo read failed (HTTP ${response.status}).`, { status: response.status });\n let data: unknown;\n try { data = JSON.parse(await response.text()); }\n catch { throw new AdportError('PROVIDER_ERROR', 'Matomo returned a non-JSON response. Check that MATOMO_URL points to the Matomo instance, not a login page or proxy.'); }\n if (data && typeof data === 'object' && !Array.isArray(data) && (data as Record<string, unknown>).result === 'error') {\n throw classify(String((data as Record<string, unknown>).message ?? ''), method);\n }\n return data;\n }\n}\n\nfunction classify(message: string, method: string): AdportError {\n const authFailure = /\\b(?:unable to authenticate|authentication (?:failed|required)|not logged in|(?:must|please|need to) (?:log in|login))\\b/i;\n const badToken = /\\btoken_auth\\b.{0,60}\\b(?:invalid|not valid|expired|missing)|\\b(?:invalid|expired|missing) (?:authentication token|token_auth)\\b/i;\n if (authFailure.test(message) || badToken.test(message)) {\n return new AdportError('NOT_CONNECTED', 'Matomo rejected the auth token. Reconnect Matomo to renew access.', { reason: 'auth' });\n }\n // Before access: \"not enough permission to access the segment X\" is a segment problem, not a bad token.\n if (/segment/i.test(message)) return new AdportError('PROVIDER_ERROR', 'Matomo rejected the segment. This site must support aggregate entry-page segmentation to group by landing page.', { reason: 'segment' });\n if (/access|permission|not allowed/i.test(message)) {\n return new AdportError('PROVIDER_ERROR', 'Matomo denied access: the token is invalid or its user lacks view access to this site.', { reason: 'access_denied' });\n }\n if (/date|period/i.test(message)) return new AdportError('PROVIDER_ERROR', 'Matomo rejected the date or period.', { reason: 'date' });\n return new AdportError('PROVIDER_ERROR', `Matomo returned an error for ${method}. Check the site ID and parameters.`, { reason: 'provider' });\n}\n","import { AdportError, type AdProvider, type Account, type AnalyticsGoal, type AcquisitionQuery, type AcquisitionReport,\n type NormalizedQuery, type Report, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport type { MatomoClient } from './client.js';\nimport { readAcquisition, records } from './acquisition.js';\n\nexport function matomoSiteId(value: unknown): string {\n if ((typeof value !== 'string' && typeof value !== 'number') || !/^[1-9]\\d{0,9}$/.test(String(value)))\n throw new AdportError('INVALID_INPUT', 'Matomo requires a positive numeric site ID.');\n return String(value);\n}\n\nexport interface MatomoSite { id: string; name: string; timezone?: string; currency?: string; ecommerce: boolean }\nfunction returnedSiteId(value: unknown) {\n try { return matomoSiteId(value); } catch { throw new AdportError('PROVIDER_ERROR', 'Matomo returned an invalid site ID.'); }\n}\nconst siteInfo = (raw: Record<string, unknown>): MatomoSite => ({\n id: returnedSiteId(raw.idsite), name: String(raw.name ?? raw.idsite),\n ...(typeof raw.timezone === 'string' ? { timezone: raw.timezone } : {}),\n ...(typeof raw.currency === 'string' ? { currency: raw.currency } : {}), ecommerce: Number(raw.ecommerce) === 1,\n});\n\nexport class MatomoProvider implements AdProvider {\n readonly id = 'matomo';\n get acquisitionAnalytics() { return this; }\n constructor(private readonly client: MatomoClient) {}\n capabilities() { return { serverDryRun: false, reporting: false }; }\n async report(_query: NormalizedQuery): Promise<Report> { throw new AdportError('INVALID_INPUT', 'Use analytics_acquisition_report for this website.'); }\n async previewWrite(_op: WriteOperation): Promise<WritePreview> { throw new AdportError('POLICY_VIOLATION', 'Website analytics is read-only.'); }\n async applyWrite(_op: WriteOperation): Promise<WriteResult> { throw new AdportError('POLICY_VIOLATION', 'Website analytics is read-only.'); }\n\n async listAccounts(): Promise<Account[]> {\n return records(await this.client.call('SitesManager.getSitesWithAtLeastViewAccess')).map(siteInfo).map(({ id, name, currency, timezone }) =>\n ({ provider: this.id, id, name, currency, timezone }));\n }\n\n private async site(accountId: string): Promise<MatomoSite> {\n const id = matomoSiteId(accountId);\n const raw = await this.client.call('SitesManager.getSiteFromId', { idSite: id });\n if (!raw || typeof raw !== 'object' || Array.isArray(raw) || String((raw as Record<string, unknown>).idsite) !== id)\n throw new AdportError('PROVIDER_ERROR', 'Matomo returned no settings for the requested site.');\n return siteInfo(raw as Record<string, unknown>);\n }\n\n private async configuredGoals(site: MatomoSite): Promise<AnalyticsGoal[]> {\n const raw = await this.client.call('Goals.getGoals', { idSite: site.id });\n const goals: AnalyticsGoal[] = records(raw).filter(g => !Number(g.deleted)).map(g => {\n if (!/^[1-9]\\d*$/.test(String(g.idgoal)) || typeof g.name !== 'string' || (g.idsite != null && String(g.idsite) !== site.id))\n throw new AdportError('PROVIDER_ERROR', 'Matomo returned an invalid goal for this site.');\n return { id: String(g.idgoal), name: g.name, counting_method: Number(g.allow_multiple) === 1 ? 'per_conversion' : 'once_per_visit' };\n });\n if (site.ecommerce) goals.push({ id: 'ecommerceOrder', name: 'Ecommerce orders', counting_method: 'per_order' });\n return goals;\n }\n\n async listGoals(accountId: string) { return this.configuredGoals(await this.site(accountId)); }\n\n async acquisitionReport(query: AcquisitionQuery): Promise<AcquisitionReport> {\n const site = await this.site(query.account_id);\n if (query.goal_ids) {\n const goals = await this.configuredGoals(site);\n if (query.goal_ids.some(id => !goals.some(g => g.id === id))) throw new AdportError('INVALID_INPUT', 'A selected goal is missing from this site. Refresh analytics_goals.');\n }\n return readAcquisition(this.client, site, query);\n }\n}\n","import { AdportError, type AcquisitionQuery, type AcquisitionReport, type AcquisitionRow } from '@adport/core';\nimport type { MatomoClient } from './client.js';\nimport type { MatomoSite } from './provider.js';\n\ntype Row = Record<string, unknown>;\nconst object = (v: unknown): v is Row => typeof v === 'object' && v !== null && !Array.isArray(v);\nexport function records(raw: unknown): Row[] {\n const list = Array.isArray(raw) ? raw : object(raw) ? Object.values(raw) : null;\n if (!list || !list.every(object)) throw new AdportError('PROVIDER_ERROR', 'Unexpected Matomo report shape.');\n return list;\n}\nconst maxRows = 10000;\nfunction table(raw: unknown): Row[] {\n const rows = records(raw);\n if (rows.length > maxRows) throw new AdportError('PROVIDER_ERROR', 'This Matomo archive exceeds the report limit. Choose a shorter date range.');\n return rows;\n}\nconst summary = (r: Row) => r.label === 'Others' || r.label === '-1' || Boolean(Number(r.is_summary));\nconst numeric = (v: unknown): number | null => (typeof v === 'number' || typeof v === 'string' && v.trim()) && Number.isFinite(Number(v)) ? Number(v) : null;\n\ntype Measures = { sessions: number | null; conversions: number | null; revenue: number | null; [key: string]: number | null };\nfunction measures(r: Row, site: MatomoSite, ids: string[]): Measures {\n const goals = object(r.goals) ? r.goals : {};\n const goalMetric = (id: string, field: string) => {\n const goal = goals['idgoal=' + id];\n return goal === undefined ? 0 : object(goal) ? numeric(goal[field]) : null;\n };\n const m: Measures = {\n sessions: numeric(r.nb_visits), conversions: numeric(r.nb_conversions ?? (Object.keys(goals).length ? undefined : 0)),\n revenue: site.ecommerce ? goalMetric('ecommerceOrder', 'revenue') : numeric(r.revenue ?? (Object.keys(goals).length ? undefined : 0)),\n };\n for (const id of ids) m['goal:' + id] = goalMetric(id, 'nb_conversions');\n return m;\n}\n\nfunction combine(a: Measures, b: Measures, sign = 1): Measures {\n const result = { ...a };\n for (const key of Object.keys(a)) {\n const x = a[key], y = b[key];\n result[key] = x == null || y == null ? null : x + sign * y;\n }\n return result;\n}\nfunction hasData(m: Measures) { return Object.values(m).some(x => x === null || Math.abs(x) > 0.000001); }\nfunction residual(total: Measures, used: Measures, notes: Set<string>): Measures {\n const diff = combine(total, used, -1);\n for (const [key, value] of Object.entries(diff)) {\n if (value !== null && Math.abs(value) < 0.000001) diff[key] = 0;\n else if (key !== 'revenue' && value !== null && value < 0) {\n diff[key] = null;\n notes.add('Matomo archives disagree on a subtotal. An unreconciled measure is unavailable.');\n }\n }\n return diff;\n}\nfunction row(dims: AcquisitionRow['dimensions'], m: Measures, ids: string[]): AcquisitionRow {\n const counts = ids.map(id => m['goal:' + id] ?? null);\n return { dimensions: dims, metrics: { sessions: m.sessions, revenue: m.revenue,\n conversions: ids.length ? counts.some(v => v === null) ? null : counts.reduce<number>((a, b) => a + b!, 0) : m.conversions },\n ...(ids.length ? { goal_counts: Object.fromEntries(ids.map((id, i) => [id, counts[i] ?? null])) } : {}) };\n}\n\n/** Only the source/medium archive contains joint rows. The name archive retains campaigns whose source or medium was never captured. */\nasync function groups(client: MatomoClient, params: Record<string, string>, site: MatomoSite, plugin: boolean, ids: string[], notes: Set<string>) {\n const read = async (method: string, options = {}) => table(await client.call(method, { ...params, ...options }));\n const [channels, names, pairs, sources, media] = await Promise.all([\n read('Referrers.getReferrerType'), read(plugin ? 'MarketingCampaignsReporting.getName' : 'Referrers.getCampaigns'),\n plugin ? read('MarketingCampaignsReporting.getSourceMedium', { expanded: '1' }) : [],\n plugin ? read('MarketingCampaignsReporting.getSource') : [], plugin ? read('MarketingCampaignsReporting.getMedium') : [],\n ]);\n const zero = measures({ nb_visits: 0 }, site, ids);\n const measuresFor = (r: Row) => measures(r, site, ids);\n let siteTotal = zero, namedTotal = zero;\n for (const channel of channels) siteTotal = combine(siteTotal, measuresFor(channel));\n const namedChildren = new Map<string, Measures>(), rows: AcquisitionRow[] = [];\n const sourceLabels = new Set(sources.map(r => r.label)), mediumLabels = new Set(media.map(r => r.label));\n const archivedLabels = sources.some(summary) || media.some(summary);\n for (const pair of pairs) {\n if (summary(pair)) continue;\n const label = String(pair.label), candidates: Array<[string | null, string | null]> = [];\n // Matomo omits empty components and joins the others with a literal separator, also legal inside a UTM value.\n if (sourceLabels.has(label)) candidates.push([label, null]);\n if (mediumLabels.has(label)) candidates.push([null, label]);\n for (let pos = label.indexOf(' - '); pos >= 0; pos = label.indexOf(' - ', pos + 1)) {\n const source = label.slice(0, pos), medium = label.slice(pos + 3);\n if (sourceLabels.has(source) && mediumLabels.has(medium)) candidates.push([source, medium]);\n }\n if (candidates.length !== 1 || archivedLabels) {\n notes.add('Matomo returned an ambiguous or archived source/medium label. Its traffic stays in the unresolved dimensions.');\n continue;\n }\n const [source, medium] = candidates[0]!;\n let children = zero;\n const parent = measuresFor(pair);\n for (const child of table(pair.subtable ?? [])) {\n if (summary(child) || typeof child.label !== 'string' || !child.label) continue;\n const m = measuresFor(child);\n children = combine(children, m);\n namedChildren.set(child.label, combine(namedChildren.get(child.label) ?? zero, m));\n rows.push(row({ source, medium, campaign: child.label }, m, ids));\n }\n const remainder = residual(parent, children, notes);\n if (hasData(remainder)) rows.push(row({ source, medium, campaign: null }, remainder, ids));\n namedTotal = combine(namedTotal, parent);\n }\n for (const name of names) {\n if (summary(name) || typeof name.label !== 'string' || !name.label) continue;\n const m = residual(measuresFor(name), namedChildren.get(name.label) ?? zero, notes);\n if (hasData(m)) rows.push(row({ source: null, medium: null, campaign: name.label }, m, ids));\n namedTotal = combine(namedTotal, m);\n }\n const rest = residual(siteTotal, namedTotal, notes);\n if (hasData(rest)) rows.push(row({ source: null, medium: null, campaign: null }, rest, ids));\n return { rows, sessions: siteTotal.sessions };\n}\n\ninterface Landing { path: string; urls: Set<string>; visits: number }\nasync function landingPages(client: MatomoClient, params: Record<string, string>, notes: Set<string>): Promise<Landing[]> {\n const entries = table(await client.call('Actions.getEntryPageUrls', { ...params, flat: '1', showColumns: 'label,url,entry_nb_visits' }));\n const paths = new Map<string, Landing>();\n for (const entry of entries) {\n if (summary(entry) || typeof entry.url !== 'string') { notes.add('Matomo omitted exact URLs for some archived entry pages.'); continue; }\n const url = new URL(entry.url);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) continue;\n const path = url.origin + url.pathname;\n const page = paths.get(path) ?? { path, urls: new Set<string>(), visits: 0 };\n page.urls.add(entry.url);\n page.visits += numeric(entry.entry_nb_visits) ?? 0;\n paths.set(path, page);\n }\n return [...paths.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);\n}\n\nexport async function readAcquisition(client: MatomoClient, site: MatomoSite, q: AcquisitionQuery): Promise<AcquisitionReport> {\n const cursor = q.cursor ?? '0.0';\n if (!/^\\d{1,6}\\.\\d{1,7}$/.test(cursor)) throw new AdportError('INVALID_INPUT', 'Invalid Matomo report cursor.');\n const [bucket, offset] = cursor.split('.').map(Number) as [number, number];\n if (!q.landing_page && bucket !== 0) throw new AdportError('INVALID_INPUT', 'This cursor belongs to a landing-page report.');\n const params = { idSite: site.id, period: q.start_date === q.end_date ? 'day' : 'range',\n date: q.start_date === q.end_date ? q.start_date : q.start_date + ',' + q.end_date,\n filter_limit: String(maxRows + 1), filter_limit_subtable: String(maxRows + 1), format_metrics: '0', language: 'en' };\n const metadata = records(await client.call('API.getReportMetadata', { idSite: site.id, idSites: site.id, apiModule: 'MarketingCampaignsReporting', hideMetricsDoc: '1' }));\n const plugin = metadata.some(r => r.module === 'MarketingCampaignsReporting' && r.action === 'getSourceMedium');\n const notes = new Set<string>();\n if (!plugin) notes.add('This site lacks the Marketing Campaigns Reporting source/medium archive. Campaign names are available; source and medium are unavailable.');\n const pages = q.landing_page ? await landingPages(client, params, notes) : undefined;\n const page = pages?.[bucket];\n const rows: AcquisitionRow[] = [];\n let next: string | undefined;\n if (!pages || page) {\n const segment = page ? [...page.urls].map(url => 'entryPageUrl==' + encodeURIComponent(url)).join(',') : undefined;\n const result = await groups(client, { ...params, ...(segment ? { segment } : {}) }, site, plugin, q.goal_ids ?? [], notes);\n if (page && result.sessions !== page.visits) throw new AdportError('PROVIDER_ERROR', 'Matomo has no matching segmented archive for this entry page. Enable read-time segment archiving or run the report without landing_page.');\n const sorted = result.rows.sort((a, b) => {\n const x = JSON.stringify(a.dimensions), y = JSON.stringify(b.dimensions);\n return x < y ? -1 : x > y ? 1 : 0;\n });\n rows.push(...sorted.slice(offset, offset + q.limit));\n if (page) for (const r of rows) r.dimensions.landing_page = page.path;\n if (offset + rows.length < sorted.length) next = `${bucket}.${offset + rows.length}`;\n else if (pages && bucket + 1 < pages.length) next = `${bucket + 1}.0`;\n }\n return { rows, date_range: { start: q.start_date, end: q.end_date, timezone: site.timezone ?? null }, currency: site.currency ?? null,\n attribution: 'Matomo archived campaign parameters and native conversion attribution. Null dimensions include untagged or unresolved traffic.',\n revenue_basis: site.ecommerce ? 'Recorded ecommerce order revenue in site currency, across all goals.' : 'Recorded converted goal revenue in site currency, across all goals.',\n notes: [...notes], ...(next ? { next_cursor: next } : {}) };\n}\n"],"mappings":";AAAA,SAAS,sBAAAA,2BAAqE;;;ACA9E,SAAS,aAAa,0BAA0B;AAmBzC,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EACzC;AAAA,EAAyB;AAAA,EAA8C;AAAA,EAA8B;AAAA,EACrG;AAAA,EAA6B;AAAA,EAA0B;AAAA,EACvD;AAAA,EAAyC;AAAA,EAAyC;AAAA,EAA+C;AACnI,CAAC;AACD,IAAM,WAAW,oBAAI,IAAI,CAAC,UAAU,UAAU,UAAU,cAAc,mBAAmB,CAAC;AAOnF,IAAM,eAAN,MAAmB;AAAA,EAExB,YAA6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M,MAAM,MAAM,KAAK,KAAK,GAAG,YAAY,MAAM,YAAY,KAAK;AAClE,SAAO,OAAO,YAAY,EAAE,KAAKA,oBAAmB,GAAG,GAAG,UAAU,IAAI;AAC1E;AACO,SAAS,wBAAgD;AAC9D,SAAO,EAAE,KAAK,QAAQ,IAAI,cAAc,IAAI,YAAY,QAAQ,IAAI,qBAAqB,GAAG;AAC9F;AAEA,SAAS,kBAAkB,MAAyE;AAClG,MAAI;AAAE,WAAO,0BAA0B,IAAI;AAAA,EAAG,QAAQ;AAAE,WAAO;AAAA,EAAW;AAC5E;AACA,eAAsB,yBAAyB,OAAgE;AAC7G,SAAO,mBAAmB,MAAM,MAAM,IAAI,QAAQ,IAAI,IAAI,KAAK,kBAAkB,sBAAsB,CAAC;AAC1G;AACA,eAAsB,mBAAmB,OAA6D;AACpG,QAAM,cAAc,MAAM,yBAAyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,MAAI;AACJ,MAAI;AAAE,aAAS,IAAI,aAAa,WAAW;AAAA,EAAG,QAAQ;AAAE,WAAO;AAAA,EAAW;AAC1E,QAAM,WAAW,IAAI,eAAe,MAAM;AAC1C,SAAO,EAAE,UAAU,OAAO,CAAC,EAAE;AAC/B;","names":["normalizeMatomoUrl","AdportError","AdportError","source","medium","AdportError","normalizeMatomoUrl"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/provider.ts","../src/acquisition.ts"],"sourcesContent":["import { normalizeMatomoUrl, type CredentialStore, type ProviderModule } from '@adport/core';\nimport { MatomoClient, type MatomoCredentials } from './client.js';\nimport { MatomoProvider } from './provider.js';\nexport { MatomoClient, MATOMO_READ_METHODS, type MatomoBearerCredentials, type MatomoCredentials } from './client.js';\nexport { MatomoProvider, matomoSiteId, type MatomoSite } from './provider.js';\nexport { matomoBaseUrl, normalizeMatomoUrl } from '@adport/core';\n\n/** Stored data uses { url, token_auth }; both values are required. */\nexport function matomoCredentialsFromData(data: Record<string, string> | undefined): MatomoCredentials | undefined {\n const url = data?.url?.trim(), tokenAuth = data?.token_auth?.trim();\n return url && tokenAuth ? { url: normalizeMatomoUrl(url), tokenAuth } : undefined;\n}\nexport function matomoEnvironmentData(): Record<string, string> {\n return { url: process.env.MATOMO_URL ?? '', token_auth: process.env.MATOMO_TOKEN_AUTH ?? '' };\n}\n/** Unusable values (e.g. a non-https URL) count as absent so one bad pair never stops other providers from loading. */\nfunction usableCredentials(data: Record<string, string> | undefined): MatomoCredentials | undefined {\n try { return matomoCredentialsFromData(data); } catch { return undefined; }\n}\nexport async function resolveMatomoCredentials(store: CredentialStore): Promise<MatomoCredentials | undefined> {\n return usableCredentials((await store.get('matomo'))?.data) ?? usableCredentials(matomoEnvironmentData());\n}\nexport async function createMatomoModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveMatomoCredentials(store);\n if (!credentials) return undefined;\n let client: MatomoClient;\n try { client = new MatomoClient(credentials); } catch { return undefined; }\n const provider = new MatomoProvider(client);\n return { provider, tools: [] };\n}\n","import { AdportError, normalizeMatomoUrl } from '@adport/core';\n\ntype MatomoFetch = (url: string, init: {\n method: 'POST'; redirect: 'error'; signal: AbortSignal; headers: Record<string, string>; body: URLSearchParams;\n}) => Promise<Pick<Response, 'ok' | 'status' | 'text'>>;\n\nexport interface MatomoCredentials {\n /** Instance base URL, e.g. https://example.matomo.cloud or https://analytics.example.com/matomo. */\n url: string;\n /** Personal auth token of a user with view access to the sites. */\n tokenAuth: string;\n}\n\nexport interface MatomoBearerCredentials {\n url: string;\n accessToken(): Promise<string>;\n}\n\n/** Documented read methods only. Every other Matomo API method is refused before any request. */\nexport const MATOMO_READ_METHODS = new Set([\n 'API.getReportMetadata', 'SitesManager.getSitesWithAtLeastViewAccess', 'SitesManager.getSiteFromId', 'Goals.getGoals',\n 'Referrers.getReferrerType', 'Referrers.getCampaigns', 'MarketingCampaignsReporting.getName',\n 'MarketingCampaignsReporting.getSource', 'MarketingCampaignsReporting.getMedium', 'MarketingCampaignsReporting.getSourceMedium', 'Actions.getEntryPageUrls',\n]);\nconst RESERVED = new Set(['module', 'method', 'format', 'token_auth', 'force_api_session']);\n\n/**\n * Matomo Reporting API over POST so token_auth never appears in a URL. Matomo\n * answers most failures with HTTP 200 and {\"result\":\"error\"}; messages are\n * classified but never echoed, since they can contain instance details.\n */\nexport class MatomoClient {\n readonly baseUrl: string;\n constructor(private readonly credentials: MatomoCredentials | MatomoBearerCredentials, private readonly fetchImpl: MatomoFetch = fetch) {\n this.baseUrl = normalizeMatomoUrl(credentials.url);\n if ('tokenAuth' in credentials && !credentials.tokenAuth.trim()) throw new AdportError('INVALID_INPUT', 'matomo: token_auth is empty');\n }\n\n async call(method: string, params: Record<string, string> = {}): Promise<unknown> {\n if (!MATOMO_READ_METHODS.has(method)) throw new AdportError('INVALID_INPUT', 'Unsupported Matomo read method.');\n if (Object.keys(params).some(key => RESERVED.has(key))) throw new AdportError('INVALID_INPUT', 'Reserved Matomo request parameter.');\n const body = new URLSearchParams({ ...params, module: 'API', method, format: 'JSON' });\n const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };\n if ('accessToken' in this.credentials) headers.authorization = 'Bearer ' + await this.credentials.accessToken();\n else body.set('token_auth', this.credentials.tokenAuth.trim());\n let response: Awaited<ReturnType<MatomoFetch>>;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/index.php`, {\n method: 'POST', redirect: 'error', signal: AbortSignal.timeout(30_000),\n headers, body,\n });\n } catch {\n throw new AdportError('PROVIDER_ERROR', 'Matomo could not be reached (network error, redirect or timeout). Check MATOMO_URL.');\n }\n if (response.status === 401) throw new AdportError('NOT_CONNECTED', 'Matomo rejected the auth token. Reconnect Matomo to renew access.');\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `Matomo read failed (HTTP ${response.status}).`, { status: response.status });\n let data: unknown;\n try { data = JSON.parse(await response.text()); }\n catch { throw new AdportError('PROVIDER_ERROR', 'Matomo returned a non-JSON response. Check that MATOMO_URL points to the Matomo instance, not a login page or proxy.'); }\n if (data && typeof data === 'object' && !Array.isArray(data) && (data as Record<string, unknown>).result === 'error') {\n throw classify(String((data as Record<string, unknown>).message ?? ''), method);\n }\n return data;\n }\n}\n\nfunction classify(message: string, method: string): AdportError {\n const authFailure = /\\b(?:unable to authenticate|authentication (?:failed|required)|not logged in|(?:must|please|need to) (?:log in|login))\\b/i;\n const badToken = /\\btoken_auth\\b.{0,60}\\b(?:invalid|not valid|expired|missing)|\\b(?:invalid|expired|missing) (?:authentication token|token_auth)\\b/i;\n if (authFailure.test(message) || badToken.test(message)) {\n return new AdportError('NOT_CONNECTED', 'Matomo rejected the auth token. Reconnect Matomo to renew access.', { reason: 'auth' });\n }\n // Before access: \"not enough permission to access the segment X\" is a segment problem, not a bad token.\n if (/segment/i.test(message)) return new AdportError('PROVIDER_ERROR', 'Matomo rejected the segment. This site must support aggregate entry-page segmentation to group by landing page.', { reason: 'segment' });\n if (/access|permission|not allowed/i.test(message)) {\n return new AdportError('PROVIDER_ERROR', 'Matomo denied access: the token is invalid or its user lacks view access to this site.', { reason: 'access_denied' });\n }\n if (/date|period/i.test(message)) return new AdportError('PROVIDER_ERROR', 'Matomo rejected the date or period.', { reason: 'date' });\n return new AdportError('PROVIDER_ERROR', `Matomo returned an error for ${method}. Check the site ID and parameters.`, { reason: 'provider' });\n}\n","import { AdportError, type AdProvider, type Account, type AnalyticsGoal, type AcquisitionQuery, type AcquisitionReport,\n type NormalizedQuery, type Report, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport type { MatomoClient } from './client.js';\nimport { readAcquisition, records } from './acquisition.js';\n\nexport function matomoSiteId(value: unknown): string {\n if ((typeof value !== 'string' && typeof value !== 'number') || !/^[1-9]\\d{0,9}$/.test(String(value)))\n throw new AdportError('INVALID_INPUT', 'Matomo requires a positive numeric site ID.');\n return String(value);\n}\n\nexport interface MatomoSite { id: string; name: string; timezone?: string; currency?: string; ecommerce: boolean }\nfunction returnedSiteId(value: unknown) {\n try { return matomoSiteId(value); } catch { throw new AdportError('PROVIDER_ERROR', 'Matomo returned an invalid site ID.'); }\n}\nconst siteInfo = (raw: Record<string, unknown>): MatomoSite => ({\n id: returnedSiteId(raw.idsite), name: String(raw.name ?? raw.idsite),\n ...(typeof raw.timezone === 'string' ? { timezone: raw.timezone } : {}),\n ...(typeof raw.currency === 'string' ? { currency: raw.currency } : {}), ecommerce: Number(raw.ecommerce) === 1,\n});\n\nexport class MatomoProvider implements AdProvider {\n readonly id = 'matomo';\n get acquisitionAnalytics() { return this; }\n constructor(private readonly client: MatomoClient) {}\n capabilities() { return { serverDryRun: false, reporting: false }; }\n async report(_query: NormalizedQuery): Promise<Report> { throw new AdportError('INVALID_INPUT', 'Use analytics_acquisition_report for this website.'); }\n async previewWrite(_op: WriteOperation): Promise<WritePreview> { throw new AdportError('POLICY_VIOLATION', 'Website analytics is read-only.'); }\n async applyWrite(_op: WriteOperation): Promise<WriteResult> { throw new AdportError('POLICY_VIOLATION', 'Website analytics is read-only.'); }\n\n async listAccounts(): Promise<Account[]> {\n return records(await this.client.call('SitesManager.getSitesWithAtLeastViewAccess')).map(siteInfo).map(({ id, name, currency, timezone }) =>\n ({ provider: this.id, id, name, currency, timezone }));\n }\n\n private async site(accountId: string): Promise<MatomoSite> {\n const id = matomoSiteId(accountId);\n const raw = await this.client.call('SitesManager.getSiteFromId', { idSite: id });\n if (!raw || typeof raw !== 'object' || Array.isArray(raw) || String((raw as Record<string, unknown>).idsite) !== id)\n throw new AdportError('PROVIDER_ERROR', 'Matomo returned no settings for the requested site.');\n return siteInfo(raw as Record<string, unknown>);\n }\n\n private async configuredGoals(site: MatomoSite): Promise<AnalyticsGoal[]> {\n const raw = await this.client.call('Goals.getGoals', { idSite: site.id });\n const goals: AnalyticsGoal[] = records(raw).filter(g => !Number(g.deleted)).map(g => {\n if (!/^[1-9]\\d*$/.test(String(g.idgoal)) || typeof g.name !== 'string' || (g.idsite != null && String(g.idsite) !== site.id))\n throw new AdportError('PROVIDER_ERROR', 'Matomo returned an invalid goal for this site.');\n return { id: String(g.idgoal), name: g.name, counting_method: Number(g.allow_multiple) === 1 ? 'per_conversion' : 'once_per_visit' };\n });\n if (site.ecommerce) goals.push({ id: 'ecommerceOrder', name: 'Ecommerce orders', counting_method: 'per_order' });\n return goals;\n }\n\n async listGoals(accountId: string) { return this.configuredGoals(await this.site(accountId)); }\n\n async acquisitionReport(query: AcquisitionQuery): Promise<AcquisitionReport> {\n const site = await this.site(query.account_id);\n if (query.goal_ids) {\n const goals = await this.configuredGoals(site);\n if (query.goal_ids.some(id => !goals.some(g => g.id === id))) throw new AdportError('INVALID_INPUT', 'A selected goal is missing from this site. Refresh analytics_goals.');\n }\n return readAcquisition(this.client, site, query);\n }\n}\n","import { AdportError, rangeDayCount, type AcquisitionQuery, type AcquisitionReport, type AcquisitionRow } from '@adport/core';\nimport type { MatomoClient } from './client.js';\nimport type { MatomoSite } from './provider.js';\n\ntype Row = Record<string, unknown>;\nconst object = (v: unknown): v is Row => typeof v === 'object' && v !== null && !Array.isArray(v);\nexport function records(raw: unknown): Row[] {\n const list = Array.isArray(raw) ? raw : object(raw) ? Object.values(raw) : null;\n if (!list || !list.every(object)) throw new AdportError('PROVIDER_ERROR', 'Unexpected Matomo report shape.');\n return list;\n}\nconst maxRows = 10000;\nfunction table(raw: unknown): Row[] {\n const rows = records(raw);\n if (rows.length > maxRows) throw new AdportError('PROVIDER_ERROR', 'This Matomo archive exceeds the report limit. Choose a shorter date range.');\n return rows;\n}\nconst summary = (r: Row) => r.label === 'Others' || r.label === '-1' || r.label === -1 || Boolean(Number(r.is_summary));\nconst numeric = (v: unknown): number | null => (typeof v === 'number' || typeof v === 'string' && v.trim()) && Number.isFinite(Number(v)) ? Number(v) : null;\n\nfunction archiveLabel(row: Row): string | undefined {\n if (!summary(row) && typeof row.label === 'string' && row.label) return row.label;\n}\n\nfunction labels(rows: Row[]) {\n const values = new Set<string>();\n let complete = true;\n for (const row of rows) {\n const label = archiveLabel(row);\n if (label) values.add(label);\n else complete = false;\n }\n return { values, complete };\n}\n\nfunction archiveVisits(rows: Row[]) {\n const byLabel = new Map<string, number>();\n let total = 0;\n for (const row of rows) {\n const count = numeric(row.nb_visits);\n if (count === null || !Number.isSafeInteger(count) || count < 0) return;\n total += count;\n const label = archiveLabel(row);\n if (label) byLabel.set(label, (byLabel.get(label) ?? 0) + count);\n }\n if (Number.isSafeInteger(total)) return { total, byLabel };\n}\n\nasync function campaignLabels(client: MatomoClient, method: 'getSource' | 'getMedium', params: Record<string, string>, rows: Row[]) {\n const rangeLabels = labels(rows);\n if (rangeLabels.complete || params.period !== 'range') return rangeLabels;\n const [start, end] = params.date!.split(',') as [string, string];\n const days = rangeDayCount({ start, end });\n const range = archiveVisits(rows);\n if (days > 31 || !range) return rangeLabels;\n try {\n // Use daily archives only to resolve labels. The range archive supplies all reported metrics.\n const archives = await client.call('MarketingCampaignsReporting.' + method, { ...params, period: 'day' });\n if (!object(archives)) return rangeLabels;\n const daily = new Map<string, number>();\n let dailyVisits = 0;\n const startTime = Date.parse(start + 'T00:00:00Z');\n for (let offset = 0; offset < days; offset++) {\n const date = new Date(startTime + offset * 86_400_000).toISOString().slice(0, 10);\n if (!Object.hasOwn(archives, date)) return rangeLabels;\n const day = table(archives[date]);\n const counts = archiveVisits(day);\n if (!counts || counts.byLabel.size !== day.length) return rangeLabels;\n for (const [label, count] of counts.byLabel) daily.set(label, (daily.get(label) ?? 0) + count);\n if (daily.size > maxRows) return rangeLabels;\n dailyVisits += counts.total;\n }\n return dailyVisits === range.total && [...range.byLabel].every(([label, count]) => daily.get(label) === count)\n ? { values: new Set(daily.keys()), complete: true } : rangeLabels;\n } catch (error) {\n if (!(error instanceof AdportError && error.code === 'PROVIDER_ERROR')) throw error;\n return rangeLabels;\n }\n}\n\nfunction sourceMedium(label: string, sources: ReturnType<typeof labels>, media: ReturnType<typeof labels>) {\n const candidates: Array<[string | null, string | null]> = [];\n if (!sources.complete || sources.values.has(label)) candidates.push([label, null]);\n if (!media.complete || media.values.has(label)) candidates.push([null, label]);\n // Matomo joins dimensions with a separator that is also legal inside a tag.\n for (let pos = label.indexOf(' - '); pos >= 0; pos = label.indexOf(' - ', pos + 1)) {\n const source = label.slice(0, pos), medium = label.slice(pos + 3);\n if (source && medium && (!sources.complete || sources.values.has(source)) && (!media.complete || media.values.has(medium))) {\n candidates.push([source, medium]);\n }\n }\n const match = candidates.length === 1 ? candidates[0] : undefined;\n if (match && (match[0] === null || sources.values.has(match[0])) && (match[1] === null || media.values.has(match[1]))) return match;\n}\n\ntype Measures = { sessions: number | null; conversions: number | null; revenue: number | null; [key: string]: number | null };\nfunction measures(r: Row, site: MatomoSite, ids: string[]): Measures {\n const goals = object(r.goals) ? r.goals : {};\n const goalMetric = (id: string, field: string) => {\n const goal = goals['idgoal=' + id];\n return goal === undefined ? 0 : object(goal) ? numeric(goal[field]) : null;\n };\n const m: Measures = {\n sessions: numeric(r.nb_visits), conversions: numeric(r.nb_conversions ?? (Object.keys(goals).length ? undefined : 0)),\n revenue: site.ecommerce ? goalMetric('ecommerceOrder', 'revenue') : numeric(r.revenue ?? (Object.keys(goals).length ? undefined : 0)),\n };\n for (const id of ids) m['goal:' + id] = goalMetric(id, 'nb_conversions');\n return m;\n}\n\nfunction combine(a: Measures, b: Measures, sign = 1): Measures {\n const result = { ...a };\n for (const key of Object.keys(a)) {\n const x = a[key], y = b[key];\n result[key] = x == null || y == null ? null : x + sign * y;\n }\n return result;\n}\nfunction hasData(m: Measures) { return Object.values(m).some(x => x === null || Math.abs(x) > 0.000001); }\nfunction residual(total: Measures, used: Measures, notes: Set<string>): Measures {\n const diff = combine(total, used, -1);\n for (const [key, value] of Object.entries(diff)) {\n if (value !== null && Math.abs(value) < 0.000001) diff[key] = 0;\n else if (key !== 'revenue' && value !== null && value < 0) {\n diff[key] = null;\n notes.add('Matomo archives disagree on a subtotal. An unreconciled measure is unavailable.');\n }\n }\n return diff;\n}\nfunction row(dims: AcquisitionRow['dimensions'], m: Measures, ids: string[]): AcquisitionRow {\n const counts = ids.map(id => m['goal:' + id] ?? null);\n return { dimensions: dims, metrics: { sessions: m.sessions, revenue: m.revenue,\n conversions: ids.length ? counts.some(v => v === null) ? null : counts.reduce<number>((a, b) => a + b!, 0) : m.conversions },\n ...(ids.length ? { goal_counts: Object.fromEntries(ids.map((id, i) => [id, counts[i] ?? null])) } : {}) };\n}\n\n/** Only the source/medium archive contains joint rows. The name archive retains campaigns whose source or medium was never captured. */\nasync function groups(client: MatomoClient, params: Record<string, string>, site: MatomoSite, plugin: boolean, ids: string[], notes: Set<string>) {\n const read = async (method: string, options = {}) => table(await client.call(method, { ...params, ...options }));\n const [channels, names, pairs, sources, media] = await Promise.all([\n read('Referrers.getReferrerType'), read(plugin ? 'MarketingCampaignsReporting.getName' : 'Referrers.getCampaigns'),\n plugin ? read('MarketingCampaignsReporting.getSourceMedium', { expanded: '1' }) : [],\n plugin ? read('MarketingCampaignsReporting.getSource') : [], plugin ? read('MarketingCampaignsReporting.getMedium') : [],\n ]);\n const zero = measures({ nb_visits: 0 }, site, ids);\n const measuresFor = (r: Row) => measures(r, site, ids);\n let siteTotal = zero, namedTotal = zero;\n for (const channel of channels) siteTotal = combine(siteTotal, measuresFor(channel));\n const namedChildren = new Map<string, Measures>(), rows: AcquisitionRow[] = [];\n const [sourceLabels, mediumLabels] = pairs.some(archiveLabel) ? await Promise.all([\n campaignLabels(client, 'getSource', params, sources), campaignLabels(client, 'getMedium', params, media),\n ]) : [labels(sources), labels(media)];\n for (const pair of pairs) {\n const label = archiveLabel(pair);\n const dimensions = label ? sourceMedium(label, sourceLabels, mediumLabels) : undefined;\n if (!dimensions) {\n notes.add('Some Matomo source and medium labels remain unresolved. Their counts appear in the campaign or site totals.');\n continue;\n }\n const [source, medium] = dimensions;\n let children = zero;\n const parent = measuresFor(pair);\n for (const child of table(pair.subtable ?? [])) {\n if (summary(child) || typeof child.label !== 'string' || !child.label) continue;\n const m = measuresFor(child);\n children = combine(children, m);\n namedChildren.set(child.label, combine(namedChildren.get(child.label) ?? zero, m));\n rows.push(row({ source, medium, campaign: child.label }, m, ids));\n }\n const remainder = residual(parent, children, notes);\n if (hasData(remainder)) rows.push(row({ source, medium, campaign: null }, remainder, ids));\n namedTotal = combine(namedTotal, parent);\n }\n for (const name of names) {\n if (summary(name) || typeof name.label !== 'string' || !name.label) continue;\n const m = residual(measuresFor(name), namedChildren.get(name.label) ?? zero, notes);\n if (hasData(m)) rows.push(row({ source: null, medium: null, campaign: name.label }, m, ids));\n namedTotal = combine(namedTotal, m);\n }\n const rest = residual(siteTotal, namedTotal, notes);\n if (hasData(rest)) rows.push(row({ source: null, medium: null, campaign: null }, rest, ids));\n return { rows, sessions: siteTotal.sessions };\n}\n\ninterface Landing { path: string; urls: Set<string>; visits: number }\nasync function landingPages(client: MatomoClient, params: Record<string, string>, notes: Set<string>): Promise<Landing[]> {\n const entries = table(await client.call('Actions.getEntryPageUrls', { ...params, flat: '1', showColumns: 'label,url,entry_nb_visits' }));\n const paths = new Map<string, Landing>();\n for (const entry of entries) {\n if (summary(entry) || typeof entry.url !== 'string') { notes.add('Matomo omitted exact URLs for some archived entry pages.'); continue; }\n const url = new URL(entry.url);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) continue;\n const path = url.origin + url.pathname;\n const page = paths.get(path) ?? { path, urls: new Set<string>(), visits: 0 };\n page.urls.add(entry.url);\n page.visits += numeric(entry.entry_nb_visits) ?? 0;\n paths.set(path, page);\n }\n return [...paths.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);\n}\n\nexport async function readAcquisition(client: MatomoClient, site: MatomoSite, q: AcquisitionQuery): Promise<AcquisitionReport> {\n const cursor = q.cursor ?? '0.0';\n if (!/^\\d{1,6}\\.\\d{1,7}$/.test(cursor)) throw new AdportError('INVALID_INPUT', 'Invalid Matomo report cursor.');\n const [bucket, offset] = cursor.split('.').map(Number) as [number, number];\n if (!q.landing_page && bucket !== 0) throw new AdportError('INVALID_INPUT', 'This cursor belongs to a landing-page report.');\n const params = { idSite: site.id, period: q.start_date === q.end_date ? 'day' : 'range',\n date: q.start_date === q.end_date ? q.start_date : q.start_date + ',' + q.end_date,\n filter_limit: String(maxRows + 1), filter_limit_subtable: String(maxRows + 1), format_metrics: '0', language: 'en' };\n const metadata = records(await client.call('API.getReportMetadata', { idSite: site.id, idSites: site.id, apiModule: 'MarketingCampaignsReporting', hideMetricsDoc: '1' }));\n const plugin = metadata.some(r => r.module === 'MarketingCampaignsReporting' && r.action === 'getSourceMedium');\n const notes = new Set<string>();\n if (!plugin) notes.add('This site lacks the Marketing Campaigns Reporting source/medium archive. Campaign names are available; source and medium are unavailable.');\n const pages = q.landing_page ? await landingPages(client, params, notes) : undefined;\n const page = pages?.[bucket];\n const rows: AcquisitionRow[] = [];\n let next: string | undefined;\n if (!pages || page) {\n const segment = page ? [...page.urls].map(url => 'entryPageUrl==' + encodeURIComponent(url)).join(',') : undefined;\n const result = await groups(client, { ...params, ...(segment ? { segment } : {}) }, site, plugin, q.goal_ids ?? [], notes);\n if (page && result.sessions !== page.visits) throw new AdportError('PROVIDER_ERROR', 'Matomo has no matching segmented archive for this entry page. Enable read-time segment archiving or run the report without landing_page.');\n const sorted = result.rows.sort((a, b) => {\n const x = JSON.stringify(a.dimensions), y = JSON.stringify(b.dimensions);\n return x < y ? -1 : x > y ? 1 : 0;\n });\n rows.push(...sorted.slice(offset, offset + q.limit));\n if (page) for (const r of rows) r.dimensions.landing_page = page.path;\n if (offset + rows.length < sorted.length) next = `${bucket}.${offset + rows.length}`;\n else if (pages && bucket + 1 < pages.length) next = `${bucket + 1}.0`;\n }\n return { rows, date_range: { start: q.start_date, end: q.end_date, timezone: site.timezone ?? null }, currency: site.currency ?? null,\n attribution: 'Matomo archived campaign parameters and native conversion attribution. Null dimensions include untagged or unresolved traffic.',\n revenue_basis: site.ecommerce ? 'Recorded ecommerce order revenue in site currency, across all goals.' : 'Recorded converted goal revenue in site currency, across all go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AAI,eAAe,MAAM;AAC1C,SAAO,EAAE,UAAU,OAAO,CAAC,EAAE;AAC/B;","names":["normalizeMatomoUrl","AdportError","AdportError","row","AdportError","normalizeMatomoUrl"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adport/provider-matomo",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.2",
|
|
4
4
|
"description": "Read-only Matomo analytics provider for adport",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
],
|
|
18
18
|
"dependencies": {
|
|
19
19
|
"zod": "^4.6.7",
|
|
20
|
-
"@adport/core": "0.16.
|
|
20
|
+
"@adport/core": "0.16.2"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"@types/node": "^26.6.6",
|