@kawapress/plugin-analytics 0.1.1 → 0.1.3

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kawapress/plugin-analytics",
3
3
  "type": "module",
4
- "version": "0.1.1",
4
+ "version": "0.1.3",
5
5
  "description": "Web analytics for KawaPress: Google Analytics, Plausible, Umami and Cloudflare Web Analytics, with in-site navigation counted",
6
6
  "license": "MIT",
7
7
  "homepage": "https://kawapress.dev/",
@@ -20,13 +20,13 @@
20
20
  "exports": {
21
21
  ".": {
22
22
  "types": "./src/index.ts",
23
- "import": "./src/index.ts",
24
- "default": "./src/index.ts"
23
+ "import": "./src/index.js",
24
+ "default": "./src/index.js"
25
25
  },
26
26
  "./runtime-plugin": {
27
27
  "types": "./src/runtime-plugin.ts",
28
- "import": "./src/runtime-plugin.ts",
29
- "default": "./src/runtime-plugin.ts"
28
+ "import": "./src/runtime-plugin.js",
29
+ "default": "./src/runtime-plugin.js"
30
30
  },
31
31
  "./package.json": "./package.json"
32
32
  },
@@ -42,11 +42,11 @@
42
42
  "registry": "https://registry.npmjs.org/"
43
43
  },
44
44
  "peerDependencies": {
45
- "kawapress": ">=0.8.3 <0.10.0",
45
+ "kawapress": ">=0.8.3 <0.11.0",
46
46
  "vite": "^8.2.2"
47
47
  },
48
48
  "devDependencies": {
49
49
  "vite": "^8.2.2",
50
- "kawapress": "0.9.0"
50
+ "kawapress": "0.10.1"
51
51
  }
52
52
  }
package/src/head.js ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `<head>` tags of every configured service. All scripts are `async` or
3
+ * `defer`, so none of them blocks rendering.
4
+ */
5
+ export function createAnalyticsHead(options) {
6
+ const head = [];
7
+ if (options.google) {
8
+ const { id } = options.google;
9
+ head.push(['script', { async: true, src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(id)}` }],
10
+ // `send_page_view: false`: the runtime plugin sends every page_view, the
11
+ // first page included, so a visit is never counted twice.
12
+ ['script', {}, `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag('js',new Date());gtag('config',${JSON.stringify(id)},{send_page_view:false})`]);
13
+ }
14
+ if (options.plausible) {
15
+ head.push(['script', { 'defer': true, 'data-domain': options.plausible.domain, 'src': options.plausible.src }]);
16
+ }
17
+ if (options.umami) {
18
+ head.push(['script', { 'defer': true, 'src': options.umami.src, 'data-website-id': options.umami.websiteId }]);
19
+ }
20
+ if (options.cloudflare) {
21
+ head.push(['script', {
22
+ 'defer': true,
23
+ 'src': 'https://static.cloudflareinsights.com/beacon.min.js',
24
+ 'data-cf-beacon': JSON.stringify({ token: options.cloudflare.token, spa: true }),
25
+ }]);
26
+ }
27
+ return head;
28
+ }
package/src/index.js ADDED
@@ -0,0 +1,40 @@
1
+ import process from "node:process";
2
+ import { definePlugin } from "kawapress";
3
+ import { createAnalyticsHead } from "./head.js";
4
+ import { resolveAnalyticsOptions } from "./options.js";
5
+ import { analyticsOptionsPlugin } from "./vite-plugin.js";
6
+ export const ANALYTICS_PLUGIN_NAME = '@kawapress/plugin-analytics';
7
+ /**
8
+ * Whether this process was started by `kawapress build`.
9
+ *
10
+ * The public plugin API does not tell `config()` which command is running
11
+ * (Vite's `command` only exists after the site head is frozen), so the CLI
12
+ * arguments decide. A program that calls the build in-process gets no scripts,
13
+ * which is the safe side for analytics.
14
+ */
15
+ export function isBuildCommand(argv = process.argv) {
16
+ return argv.slice(2).includes('build');
17
+ }
18
+ /**
19
+ * Adds web analytics scripts to the site `<head>` and, for Google, reports a
20
+ * page view for every in-site navigation.
21
+ */
22
+ export function analyticsPlugin(options) {
23
+ const resolved = resolveAnalyticsOptions(options);
24
+ return definePlugin({
25
+ name: ANALYTICS_PLUGIN_NAME,
26
+ setup(api) {
27
+ api.config((config) => {
28
+ if (!resolved.dev && !isBuildCommand()) {
29
+ return;
30
+ }
31
+ config.head = [...(config.head ?? []), ...createAnalyticsHead(resolved)];
32
+ });
33
+ api.vite((config) => {
34
+ config.plugins ??= [];
35
+ config.plugins.push(analyticsOptionsPlugin({ google: resolved.google !== undefined }));
36
+ });
37
+ },
38
+ });
39
+ }
40
+ export default analyticsPlugin;
package/src/options.js ADDED
@@ -0,0 +1,94 @@
1
+ export const PLAUSIBLE_DEFAULT_SRC = 'https://plausible.io/js/script.js';
2
+ const SERVICES = ['google', 'plausible', 'umami', 'cloudflare'];
3
+ const GOOGLE_ID_PATTERN = /^G-[A-Z0-9]+$/i;
4
+ /**
5
+ * Validates the options at config time. Every error names the option that is
6
+ * wrong, so a typo is fixed without reading the plugin source.
7
+ */
8
+ export function resolveAnalyticsOptions(options) {
9
+ if (!options || typeof options !== 'object') {
10
+ throw new Error('KawaPress Analytics: analyticsPlugin() needs at least one service, '
11
+ + 'for example analyticsPlugin({ plausible: { domain: "example.com" } }).');
12
+ }
13
+ const resolved = {
14
+ dev: resolveBoolean(options.dev, 'dev'),
15
+ };
16
+ if (options.google !== undefined) {
17
+ const section = requireSection(options.google, 'google');
18
+ const id = requireText(section.id, 'google.id', 'For example "G-XXXXXXX".');
19
+ if (/^UA-/i.test(id)) {
20
+ throw new Error('KawaPress Analytics: "google.id" looks like a Universal Analytics ID '
21
+ + `(${JSON.stringify(id)}), which Google no longer processes. Use the GA4 measurement ID that starts with "G-".`);
22
+ }
23
+ if (!GOOGLE_ID_PATTERN.test(id)) {
24
+ throw new Error(`KawaPress Analytics: "google.id" must be a GA4 measurement ID such as "G-XXXXXXX", got ${JSON.stringify(id)}.`);
25
+ }
26
+ resolved.google = { id };
27
+ }
28
+ if (options.plausible !== undefined) {
29
+ const section = requireSection(options.plausible, 'plausible');
30
+ const domain = requireText(section.domain, 'plausible.domain', 'For example "example.com".');
31
+ if (/[/\s]/.test(domain)) {
32
+ throw new Error(`KawaPress Analytics: "plausible.domain" must be a bare domain like "example.com", got ${JSON.stringify(domain)}.`);
33
+ }
34
+ resolved.plausible = {
35
+ domain,
36
+ src: section.src === undefined
37
+ ? PLAUSIBLE_DEFAULT_SRC
38
+ : requireUrl(section.src, 'plausible.src'),
39
+ };
40
+ }
41
+ if (options.umami !== undefined) {
42
+ const section = requireSection(options.umami, 'umami');
43
+ resolved.umami = {
44
+ websiteId: requireText(section.websiteId, 'umami.websiteId', 'Copy it from the Umami dashboard.'),
45
+ src: requireUrl(section.src, 'umami.src'),
46
+ };
47
+ }
48
+ if (options.cloudflare !== undefined) {
49
+ const section = requireSection(options.cloudflare, 'cloudflare');
50
+ resolved.cloudflare = {
51
+ token: requireText(section.token, 'cloudflare.token', 'Copy the site token from Cloudflare Web Analytics.'),
52
+ };
53
+ }
54
+ if (!SERVICES.some(service => resolved[service] !== undefined)) {
55
+ throw new Error('KawaPress Analytics: configure at least one of '
56
+ + `${SERVICES.map(service => `"${service}"`).join(', ')}.`);
57
+ }
58
+ return resolved;
59
+ }
60
+ function requireSection(value, name) {
61
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
62
+ throw new Error(`KawaPress Analytics: "${name}" must be an object, got ${JSON.stringify(value)}.`);
63
+ }
64
+ return value;
65
+ }
66
+ function requireText(value, name, hint) {
67
+ if (typeof value !== 'string' || value.trim() === '') {
68
+ throw new Error(`KawaPress Analytics: "${name}" is required and must be a non-empty string. ${hint}`);
69
+ }
70
+ return value.trim();
71
+ }
72
+ function requireUrl(value, name) {
73
+ const text = requireText(value, name, 'Use the full script URL, starting with https://.');
74
+ let url;
75
+ try {
76
+ url = new URL(text);
77
+ }
78
+ catch {
79
+ throw new Error(`KawaPress Analytics: "${name}" must be an absolute URL, got ${JSON.stringify(text)}.`);
80
+ }
81
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
82
+ throw new Error(`KawaPress Analytics: "${name}" must start with https://, got ${JSON.stringify(text)}.`);
83
+ }
84
+ return text;
85
+ }
86
+ function resolveBoolean(value, name) {
87
+ if (value === undefined) {
88
+ return false;
89
+ }
90
+ if (typeof value !== 'boolean') {
91
+ throw new TypeError(`KawaPress Analytics: "${name}" must be true or false, got ${JSON.stringify(value)}.`);
92
+ }
93
+ return value;
94
+ }
@@ -0,0 +1,3 @@
1
+ import options from "virtual:kawapress-analytics-options";
2
+ const runtimeOptions = options;
3
+ export default runtimeOptions;
@@ -0,0 +1,64 @@
1
+ import { defineRuntimePlugin } from "kawapress";
2
+ import options from "./runtime-options.js";
3
+ export default defineRuntimePlugin({
4
+ name: '@kawapress/plugin-analytics',
5
+ setup(api) {
6
+ // Only Google needs a route hook: Plausible and Umami watch the History
7
+ // API themselves and Cloudflare is told `spa: true`.
8
+ if (!options.google) {
9
+ return;
10
+ }
11
+ api.router((router) => {
12
+ // Per app. The router also runs the hook for a query or hash change and
13
+ // for the second `enter()` that adopts the requested URL; the path is
14
+ // what makes a page view.
15
+ let lastPath;
16
+ let first = true;
17
+ router.afterEach((to) => {
18
+ if (typeof window === 'undefined' || to.path === lastPath) {
19
+ return;
20
+ }
21
+ lastPath = to.path;
22
+ // Without the gtag snippet (`kawapress dev` unless `dev: true`) there is
23
+ // nothing to report to.
24
+ const gtag = window.gtag;
25
+ if (typeof gtag !== 'function') {
26
+ return;
27
+ }
28
+ const pageLocation = window.location.href;
29
+ const send = () => {
30
+ gtag('event', 'page_view', {
31
+ page_location: pageLocation,
32
+ page_title: document.title,
33
+ });
34
+ };
35
+ if (first) {
36
+ // The document title is already the title of this page.
37
+ first = false;
38
+ setTimeout(send, 0);
39
+ }
40
+ else {
41
+ sendWhenTitleChanges(send);
42
+ }
43
+ });
44
+ });
45
+ },
46
+ });
47
+ /** The head manager rewrites `document.title` a moment after the route commits. */
48
+ const TITLE_WAIT_MS = 300;
49
+ function sendWhenTitleChanges(send) {
50
+ let done = false;
51
+ const observer = new MutationObserver(() => finish());
52
+ const timer = setTimeout(finish, TITLE_WAIT_MS);
53
+ function finish() {
54
+ if (done) {
55
+ return;
56
+ }
57
+ done = true;
58
+ observer.disconnect();
59
+ clearTimeout(timer);
60
+ // One more tick: the title and the other head tags settle together.
61
+ setTimeout(send, 0);
62
+ }
63
+ observer.observe(document.head, { childList: true, subtree: true, characterData: true });
64
+ }
@@ -0,0 +1,22 @@
1
+ import { stringifyJson } from "kawapress";
2
+ export const ANALYTICS_OPTIONS_MODULE_ID = 'virtual:kawapress-analytics-options';
3
+ const RESOLVED_MODULE_ID = `\0${ANALYTICS_OPTIONS_MODULE_ID}`;
4
+ export function analyticsOptionsPlugin(options) {
5
+ return {
6
+ name: 'kawapress:analytics-options',
7
+ resolveId(id) {
8
+ if (id === ANALYTICS_OPTIONS_MODULE_ID) {
9
+ return RESOLVED_MODULE_ID;
10
+ }
11
+ },
12
+ load(id) {
13
+ if (id !== RESOLVED_MODULE_ID) {
14
+ return;
15
+ }
16
+ return `export default ${stringifyJson(options, {
17
+ label: 'options of @kawapress/plugin-analytics',
18
+ path: 'analyticsPlugin',
19
+ })}`;
20
+ },
21
+ };
22
+ }