@riebeckite/plugin-analytics 0.0.1

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Rerurate_514
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # @riebeckite/plugin-analytics
2
+
3
+ Provider analytics injection for Riebeckite sites: a static bootstrap endpoint
4
+ plus a browser entry that loads it.
5
+
6
+ [日本語](./README_ja.md)
7
+
8
+ ## Overview
9
+
10
+ `analytics()` registers:
11
+
12
+ - one GET endpoint (default `/_analytics.js`) that serves a small provider
13
+ bootstrap written in JavaScript, and
14
+ - one client entry, `initAnalytics`, that appends
15
+ `<script defer src="/_analytics.js">` to `document.head` exactly once.
16
+
17
+ The plugin is build-time only. It never executes provider code during the static
18
+ build.
19
+
20
+ ## Usage
21
+
22
+ ```ts
23
+ import { defineConfig } from "@riebeckite/core";
24
+ import { analytics } from "@riebeckite/plugin-analytics";
25
+
26
+ export default defineConfig({
27
+ // ...
28
+ plugins: [
29
+ analytics({ provider: "plausible", domain: "example.com" }),
30
+ ],
31
+ });
32
+ ```
33
+
34
+ Provider examples:
35
+
36
+ ```ts
37
+ analytics({ provider: "plausible", domain: "example.com" });
38
+ analytics({ provider: "umami", siteId: "xxxxxxxx-xxxx-xxxx" });
39
+ analytics({ provider: "umami", siteId: "…", domain: "example.com" });
40
+ analytics({ provider: "google-analytics", measurementId: "G-XXXXXXXXXX" });
41
+ analytics({ provider: "custom", scriptUrl: "https://cdn.example.com/a.js" });
42
+ analytics({ provider: "custom", snippet: "window.__analytics = true;" });
43
+ ```
44
+
45
+ ## Options
46
+
47
+ | Option | Type | Required | Description |
48
+ | ------ | ---- | -------- | ----------- |
49
+ | `provider` | `"plausible" \| "umami" \| "google-analytics" \| "custom"` | yes | Provider whose bootstrap is served |
50
+ | `domain` | `string` | Plausible; optional for Umami | Plausible `data-domain`, or Umami `data-domains` |
51
+ | `siteId` | `string` | Umami | Umami `data-website-id` |
52
+ | `measurementId` | `string` | google-analytics | GA measurement id (`G-…`) |
53
+ | `scriptUrl` | `string` | Provider default | Overrides the provider script URL; the custom script URL when no `snippet` is given |
54
+ | `snippet` | `string` | custom (with no `scriptUrl`) | Raw bootstrap JavaScript, served verbatim |
55
+ | `scriptPath` | `string` | `/_analytics.js` | Endpoint and client script path |
56
+
57
+ `validateOptions` reports missing or mistyped fields through the standard
58
+ Riebeckite config validation, so `riebeckite check` fails fast on a bad setup.
59
+
60
+ Provider script URL defaults:
61
+
62
+ | Provider | Default URL |
63
+ | -------- | ----------- |
64
+ | `plausible` | `https://plausible.io/js/script.js` |
65
+ | `umami` | `https://cloud.umami.is/script.js` |
66
+ | `google-analytics` | `https://www.googletagmanager.com/gtag/js` |
67
+
68
+ ## Endpoint contract
69
+
70
+ - `GET /_analytics.js`
71
+ - `200 OK`
72
+ - `Content-Type: application/javascript; charset=utf-8`
73
+ - `Cache-Control: public, max-age=3600`
74
+ - Body: a self-executing snippet that creates the provider `<script>` tag
75
+ (`async`/`defer` as appropriate). All configured values are JSON-encoded, so
76
+ they cannot break out of their string literals.
77
+
78
+ `google-analytics` also defines `window.dataLayer` and `window.gtag` before
79
+ configuring the measurement id. `custom` returns the `snippet` verbatim, or a
80
+ generic loader for `scriptUrl`.
81
+
82
+ ## Client behavior (`initAnalytics`)
83
+
84
+ - Runs on page load through `initRiebeckiteClient()`; no component or layout
85
+ change is required.
86
+ - Appends one `<script defer src="/_analytics.js" data-riebeckite-analytics>`
87
+ to `document.head`, and is a no-op if that tag already exists.
88
+
89
+ ## Privacy and trust boundary
90
+
91
+ - No analytics data is collected at build time; the endpoint only serves code.
92
+ - The `custom` provider's `snippet` (or any `scriptUrl`) is injected as-is into
93
+ visitors' pages. Treat it as trusted configuration, never as user input.
94
+ - Nothing is sanitized or proxied: whatever provider you configure receives the
95
+ requests directly from the browser, under the site's own origin and privacy
96
+ policy.
97
+
98
+ ## Verifiability
99
+
100
+ Static builds do not execute client JavaScript. To keep analytics verifiable in
101
+ built HTML, `onManifestCreated` appends functional tags to every entry:
102
+
103
+ ```html
104
+ <link rel="preload" as="script" href="/_analytics.js" />
105
+ <script defer src="/_analytics.js" data-riebeckite-analytics></script>
106
+ ```
107
+
108
+ These are the real tags the browser would load, so no fabricated marker is
109
+ inserted. The injection is idempotent (guarded by `data-riebeckite-analytics`)
110
+ and does not alter the surrounding document structure.
111
+
112
+ ## Limitations
113
+
114
+ - **Static client path.** The client entry receives no options, so it always
115
+ loads `/_analytics.js`. If you override `scriptPath`, mount the endpoint and
116
+ load it yourself with a custom client entry.
117
+ - **No SPA route tracking.** Client-side routed SPA navigations are not
118
+ reported automatically; configure the provider or send events manually.
119
+ - **Document lifecycle only.** The bootstrap runs once on initial load. Provide
120
+ your own `snippet` if you need a more involved lifecycle.
121
+ - **No consent management.** The plugin does not gate loading on user consent;
122
+ add that in a client entry if your jurisdiction requires it.
123
+
124
+ ## Exports
125
+
126
+ - `analytics(options)` / `analyticsPlugin(options)` — plugin factory
127
+ - `initAnalytics` — browser initializer (also via
128
+ `@riebeckite/plugin-analytics/client`)
129
+ - `buildAnalyticsScript(options)` — pure bootstrap builder
130
+ - `validateAnalyticsOptions(options)` — options validator
131
+ - Constants: `ANALYTICS_SCRIPT_PATH`, `ANALYTICS_SCRIPT_ATTRIBUTE`
132
+ - Types: `AnalyticsOptions`, `AnalyticsProvider`
133
+
134
+ ## See also
135
+
136
+ - [Plugin guide](../../docs/plugins_en.md)
package/README_ja.md ADDED
@@ -0,0 +1,113 @@
1
+ # @riebeckite/plugin-analytics
2
+
3
+ サイトに外部プロバイダの解析タグを挿入するプラグインです。静的なブートストラップ用エンドポイントと、それを読み込むクライアントエントリを提供します。
4
+
5
+ [English](./README.md)
6
+
7
+ ## 概要
8
+
9
+ `analytics()` は次の2つを登録します。
10
+
11
+ - プロバイダのブートストラップ JavaScript を返す GET エンドポイント(既定は `/_analytics.js`)
12
+ - `document.head` に `<script defer src="/_analytics.js">` を一度だけ追加するクライアントエントリ `initAnalytics`
13
+
14
+ このプラグインはビルド時に完結します。静的ビルド中にプロバイダのコードを実行することはありません。
15
+
16
+ ## 使い方
17
+
18
+ ```ts
19
+ import { defineConfig } from "@riebeckite/core";
20
+ import { analytics } from "@riebeckite/plugin-analytics";
21
+
22
+ export default defineConfig({
23
+ // ...
24
+ plugins: [
25
+ analytics({ provider: "plausible", domain: "example.com" }),
26
+ ],
27
+ });
28
+ ```
29
+
30
+ プロバイダごとの例:
31
+
32
+ ```ts
33
+ analytics({ provider: "plausible", domain: "example.com" });
34
+ analytics({ provider: "umami", siteId: "xxxxxxxx-xxxx-xxxx" });
35
+ analytics({ provider: "umami", siteId: "…", domain: "example.com" });
36
+ analytics({ provider: "google-analytics", measurementId: "G-XXXXXXXXXX" });
37
+ analytics({ provider: "custom", scriptUrl: "https://cdn.example.com/a.js" });
38
+ analytics({ provider: "custom", snippet: "window.__analytics = true;" });
39
+ ```
40
+
41
+ ## オプション
42
+
43
+ | 項目 | 型 | 必須 | 説明 |
44
+ | --- | --- | --- | --- |
45
+ | `provider` | `"plausible" \| "umami" \| "google-analytics" \| "custom"` | はい | 使用するプロバイダ |
46
+ | `domain` | `string` | Plausible では必須、Umami では任意 | Plausible の `data-domain`、または Umami の `data-domains` |
47
+ | `siteId` | `string` | Umami | Umami の `data-website-id` |
48
+ | `measurementId` | `string` | google-analytics | GA の測定 ID(`G-…`) |
49
+ | `scriptUrl` | `string` | プロバイダの既定値 | プロバイダのスクリプト URL を上書きします。`snippet` がない custom では読み込む URL |
50
+ | `snippet` | `string` | custom(`scriptUrl` がない場合) | そのまま配信される生のブートストラップ JavaScript |
51
+ | `scriptPath` | `string` | `/_analytics.js` | エンドポイント兼クライアントスクリプトのパス |
52
+
53
+ `validateOptions` は不足・型違いのフィールドを標準の設定検証として報告するため、設定ミスは `riebeckite check` で早い段階に失敗します。
54
+
55
+ プロバイダの既定スクリプト URL:
56
+
57
+ | プロバイダ | 既定 URL |
58
+ | --- | --- |
59
+ | `plausible` | `https://plausible.io/js/script.js` |
60
+ | `umami` | `https://cloud.umami.is/script.js` |
61
+ | `google-analytics` | `https://www.googletagmanager.com/gtag/js` |
62
+
63
+ ## エンドポイントの契約
64
+
65
+ - `GET /_analytics.js`
66
+ - `200 OK`
67
+ - `Content-Type: application/javascript; charset=utf-8`
68
+ - `Cache-Control: public, max-age=3600`
69
+ - 本文: プロバイダの `<script>` タグ(必要に応じて `async` / `defer`)を生成する即時実行スニペット。設定値はすべて JSON エンコードされるため、文字列リテラルを壊すことはできません。
70
+
71
+ `google-analytics` は測定 ID を設定する前に `window.dataLayer` と `window.gtag` を定義します。`custom` は `snippet` をそのまま返すか、`scriptUrl` 用の汎用ローダーを返します。
72
+
73
+ ## クライアントの挙動(`initAnalytics`)
74
+
75
+ - `initRiebeckiteClient()` 経由でページ読み込み時に実行されます。コンポーネントやレイアウトの変更は不要です。
76
+ - `<script defer src="/_analytics.js" data-riebeckite-analytics>` を `document.head` に1つ追加します。すでに存在する場合は何もしません。
77
+
78
+ ## プライバシーと信頼境界
79
+
80
+ - ビルド時に解析データを収集することはありません。エンドポイントはコードを返すだけです。
81
+ - `custom` の `snippet`(および任意の `scriptUrl`)は訪問者のページにそのまま挿入されます。信頼できる設定として扱い、ユーザー入力から組み立てないでください。
82
+ - 内容のサニタイズやプロキシは行いません。設定したプロバイダは、サイト自身のオリジンとプライバシー方針のもとでブラウザから直接リクエストを受け取ります。
83
+
84
+ ## 検証しやすさ
85
+
86
+ 静的ビルドではクライアント JavaScript を実行しません。そのため、`onManifestCreated` が全エントリの HTML に実際に機能するタグを付与します。
87
+
88
+ ```html
89
+ <link rel="preload" as="script" href="/_analytics.js" />
90
+ <script defer src="/_analytics.js" data-riebeckite-analytics></script>
91
+ ```
92
+
93
+ これはブラウザが実際に読み込むタグそのもので、検証用のダミーマーカーは挿入しません。付与は冪等(`data-riebeckite-analytics` で判定)で、周囲の HTML 構造を変えません。
94
+
95
+ ## 制限事項
96
+
97
+ - **クライアント側のパスは固定です。** クライアントエントリはオプションを受け取らないため、常に `/_analytics.js` を読み込みます。`scriptPath` を変更する場合は、エンドポイントのマウントと読み込みを独自のクライアントエントリで行ってください。
98
+ - **SPA のルート遷移には対応しません。** クライアントサイドのルーティングによる画面遷移は自動では計測されません。プロバイダ側で設定するか、手動でイベントを送信してください。
99
+ - **ドキュメントのライフサイクルは初回読み込みのみです。** より複雑なライフサイクルが必要な場合は独自の `snippet` を用意してください。
100
+ - **同意管理は行いません。** 法令上必要な場合は、クライアントエントリ側で同意を得るまで読み込みを止めてください。
101
+
102
+ ## 主なエクスポート
103
+
104
+ - `analytics(options)` / `analyticsPlugin(options)`: プラグインを作成する
105
+ - `initAnalytics`: クライアント側の初期化(`@riebeckite/plugin-analytics/client` からも利用可)
106
+ - `buildAnalyticsScript(options)`: ブートストラップを生成する純粋関数
107
+ - `validateAnalyticsOptions(options)`: オプションの検証
108
+ - 定数: `ANALYTICS_SCRIPT_PATH`、`ANALYTICS_SCRIPT_ATTRIBUTE`
109
+ - 型: `AnalyticsOptions`、`AnalyticsProvider`
110
+
111
+ ## 関連資料
112
+
113
+ - [プラグインガイド](../../../docs/ja/plugin-system.md)
@@ -0,0 +1,3 @@
1
+ export { ANALYTICS_SCRIPT_PATH } from "./src/constants.js";
2
+ export { initAnalytics } from "./src/init.js";
3
+ export type { AnalyticsProvider } from "./src/options.js";
package/dist/client.js ADDED
@@ -0,0 +1,18 @@
1
+ // src/constants.ts
2
+ var ANALYTICS_SCRIPT_PATH = "/_analytics.js";
3
+ var ANALYTICS_SCRIPT_ATTRIBUTE = "data-riebeckite-analytics";
4
+
5
+ // src/init.ts
6
+ function initAnalytics() {
7
+ if (typeof document === "undefined") return;
8
+ if (document.querySelector(`script[${ANALYTICS_SCRIPT_ATTRIBUTE}]`)) return;
9
+ const script = document.createElement("script");
10
+ script.defer = true;
11
+ script.src = ANALYTICS_SCRIPT_PATH;
12
+ script.setAttribute(ANALYTICS_SCRIPT_ATTRIBUTE, "");
13
+ document.head.appendChild(script);
14
+ }
15
+ export {
16
+ ANALYTICS_SCRIPT_PATH,
17
+ initAnalytics
18
+ };
@@ -0,0 +1,18 @@
1
+ import { type AnalyticsOptions } from "./src/options.js";
2
+ export { ANALYTICS_SCRIPT_ATTRIBUTE, ANALYTICS_SCRIPT_PATH, } from "./src/constants.js";
3
+ export { initAnalytics } from "./src/init.js";
4
+ export type { AnalyticsOptions, AnalyticsProvider } from "./src/options.js";
5
+ export { ANALYTICS_PROVIDERS, validateAnalyticsOptions } from "./src/options.js";
6
+ export { buildAnalyticsScript } from "./src/script.js";
7
+ /**
8
+ * Injects a provider analytics bootstrap into every page.
9
+ *
10
+ * The provider snippet is served from a static endpoint (`/_analytics.js` by
11
+ * default) and loaded by the `initAnalytics` client entry. Because client
12
+ * entries are static and receive no plugin options, the endpoint path is a
13
+ * compile-time constant; overriding `scriptPath` requires a custom client
14
+ * entry (see the README).
15
+ */
16
+ export declare function analytics(options: AnalyticsOptions): import("@riebeckite/core").RiebeckitePlugin<AnalyticsOptions>;
17
+ /** Alias kept for symmetry with the other `*Plugin` factories. */
18
+ export declare const analyticsPlugin: typeof analytics;
package/dist/index.js ADDED
@@ -0,0 +1,246 @@
1
+ // index.ts
2
+ import {
3
+ createClientEntry,
4
+ defineEndpoint,
5
+ definePlugin,
6
+ escapeHtmlAttribute
7
+ } from "@riebeckite/core";
8
+
9
+ // src/constants.ts
10
+ var ANALYTICS_SCRIPT_PATH = "/_analytics.js";
11
+ var ANALYTICS_SCRIPT_ATTRIBUTE = "data-riebeckite-analytics";
12
+
13
+ // src/options.ts
14
+ var ANALYTICS_PROVIDERS = [
15
+ "plausible",
16
+ "umami",
17
+ "google-analytics",
18
+ "custom"
19
+ ];
20
+ function validateAnalyticsOptions(options) {
21
+ const issues = [];
22
+ if (!options) {
23
+ issues.push({ path: "provider", message: providerMessage() });
24
+ return issues;
25
+ }
26
+ if (!isProvider(options.provider)) {
27
+ issues.push({ path: "provider", message: providerMessage() });
28
+ }
29
+ validateOptionalString(options.domain, "domain", issues);
30
+ validateOptionalString(options.siteId, "siteId", issues);
31
+ validateOptionalString(options.measurementId, "measurementId", issues);
32
+ validateOptionalString(options.scriptUrl, "scriptUrl", issues);
33
+ validateOptionalString(options.snippet, "snippet", issues);
34
+ if (options.provider === "plausible" && !hasText(options.domain)) {
35
+ issues.push({ path: "domain", message: "Plausible requires a domain." });
36
+ }
37
+ if (options.provider === "umami" && !hasText(options.siteId)) {
38
+ issues.push({ path: "siteId", message: "Umami requires a site id." });
39
+ }
40
+ if (options.provider === "google-analytics" && !hasText(options.measurementId)) {
41
+ issues.push({
42
+ path: "measurementId",
43
+ message: "google-analytics requires a measurement id."
44
+ });
45
+ }
46
+ if (options.provider === "custom" && !hasText(options.snippet) && !hasText(options.scriptUrl)) {
47
+ issues.push({
48
+ path: "snippet",
49
+ message: "custom requires a snippet or a scriptUrl."
50
+ });
51
+ }
52
+ if (options.scriptPath !== void 0 && !isStaticPath(options.scriptPath)) {
53
+ issues.push({
54
+ path: "scriptPath",
55
+ message: 'Expected a static path starting with "/".'
56
+ });
57
+ }
58
+ return issues;
59
+ }
60
+ function isProvider(value) {
61
+ return typeof value === "string" && ANALYTICS_PROVIDERS.includes(value);
62
+ }
63
+ function providerMessage() {
64
+ return `Expected one of: ${ANALYTICS_PROVIDERS.join(", ")}.`;
65
+ }
66
+ function hasText(value) {
67
+ return typeof value === "string" && value.trim().length > 0;
68
+ }
69
+ function validateOptionalString(value, path, issues) {
70
+ if (value !== void 0 && typeof value !== "string") {
71
+ issues.push({ path, message: "Expected a string." });
72
+ }
73
+ }
74
+ function isStaticPath(value) {
75
+ return value.startsWith("/") && value.length > 1 && !/[\s?#:]/.test(value) && !value.includes("//") && value !== "/assets" && !value.startsWith("/assets/");
76
+ }
77
+
78
+ // src/script.ts
79
+ var PLAUSIBLE_SCRIPT_URL = "https://plausible.io/js/script.js";
80
+ var UMAMI_SCRIPT_URL = "https://cloud.umami.is/script.js";
81
+ var GOOGLE_ANALYTICS_SCRIPT_URL = "https://www.googletagmanager.com/gtag/js";
82
+ function buildAnalyticsScript(options) {
83
+ switch (options.provider) {
84
+ case "plausible":
85
+ return buildPlausibleScript(options);
86
+ case "umami":
87
+ return buildUmamiScript(options);
88
+ case "google-analytics":
89
+ return buildGoogleAnalyticsScript(options);
90
+ case "custom":
91
+ return buildCustomScript(options);
92
+ default:
93
+ return "/* @riebeckite/plugin-analytics: unsupported provider */\n";
94
+ }
95
+ }
96
+ function buildPlausibleScript(options) {
97
+ const domain = options.domain ?? "";
98
+ const url = options.scriptUrl ?? PLAUSIBLE_SCRIPT_URL;
99
+ return [
100
+ "/* @riebeckite/plugin-analytics: plausible */",
101
+ "(function () {",
102
+ ' var script = document.createElement("script");',
103
+ " script.defer = true;",
104
+ ` script.setAttribute("data-domain", ${jsString(domain)});`,
105
+ ` script.src = ${jsString(url)};`,
106
+ " document.head.appendChild(script);",
107
+ "})();",
108
+ ""
109
+ ].join("\n");
110
+ }
111
+ function buildUmamiScript(options) {
112
+ const siteId = options.siteId ?? "";
113
+ const domain = options.domain;
114
+ const url = options.scriptUrl ?? UMAMI_SCRIPT_URL;
115
+ const lines = [
116
+ "/* @riebeckite/plugin-analytics: umami */",
117
+ "(function () {",
118
+ ' var script = document.createElement("script");',
119
+ " script.defer = true;",
120
+ ` script.setAttribute("data-website-id", ${jsString(siteId)});`
121
+ ];
122
+ if (domain) {
123
+ lines.push(` script.setAttribute("data-domains", ${jsString(domain)});`);
124
+ }
125
+ lines.push(
126
+ ` script.src = ${jsString(url)};`,
127
+ " document.head.appendChild(script);",
128
+ "})();",
129
+ ""
130
+ );
131
+ return lines.join("\n");
132
+ }
133
+ function buildGoogleAnalyticsScript(options) {
134
+ const measurementId = options.measurementId ?? "";
135
+ const base = options.scriptUrl ?? GOOGLE_ANALYTICS_SCRIPT_URL;
136
+ const source = `${base}?id=${encodeURIComponent(measurementId)}`;
137
+ return [
138
+ "/* @riebeckite/plugin-analytics: google-analytics */",
139
+ "(function () {",
140
+ ` var id = ${jsString(measurementId)};`,
141
+ ' var script = document.createElement("script");',
142
+ " script.async = true;",
143
+ ` script.src = ${jsString(source)};`,
144
+ " document.head.appendChild(script);",
145
+ " window.dataLayer = window.dataLayer || [];",
146
+ " function gtag() { window.dataLayer.push(arguments); }",
147
+ " window.gtag = gtag;",
148
+ ' gtag("js", new Date());',
149
+ ' gtag("config", id);',
150
+ "})();",
151
+ ""
152
+ ].join("\n");
153
+ }
154
+ function buildCustomScript(options) {
155
+ if (options.snippet?.trim()) {
156
+ return `${options.snippet.trimEnd()}
157
+ `;
158
+ }
159
+ const url = options.scriptUrl ?? "";
160
+ return [
161
+ "/* @riebeckite/plugin-analytics: custom */",
162
+ "(function () {",
163
+ ' var script = document.createElement("script");',
164
+ " script.defer = true;",
165
+ ` script.src = ${jsString(url)};`,
166
+ " document.head.appendChild(script);",
167
+ "})();",
168
+ ""
169
+ ].join("\n");
170
+ }
171
+ function jsString(value) {
172
+ const encoded = JSON.stringify(value);
173
+ return encoded === void 0 ? '""' : encoded;
174
+ }
175
+
176
+ // src/init.ts
177
+ function initAnalytics() {
178
+ if (typeof document === "undefined") return;
179
+ if (document.querySelector(`script[${ANALYTICS_SCRIPT_ATTRIBUTE}]`)) return;
180
+ const script = document.createElement("script");
181
+ script.defer = true;
182
+ script.src = ANALYTICS_SCRIPT_PATH;
183
+ script.setAttribute(ANALYTICS_SCRIPT_ATTRIBUTE, "");
184
+ document.head.appendChild(script);
185
+ }
186
+
187
+ // index.ts
188
+ function analytics(options) {
189
+ const scriptPath = options.scriptPath ?? ANALYTICS_SCRIPT_PATH;
190
+ const tracked = /* @__PURE__ */ new Map();
191
+ return definePlugin({
192
+ name: "analytics",
193
+ options,
194
+ validateOptions: validateAnalyticsOptions,
195
+ endpoints: [
196
+ defineEndpoint(
197
+ scriptPath,
198
+ () => ({
199
+ headers: {
200
+ "content-type": "application/javascript; charset=utf-8"
201
+ },
202
+ body: buildAnalyticsScript(options)
203
+ }),
204
+ { cacheControl: "public, max-age=3600" }
205
+ )
206
+ ],
207
+ clientEntries: [createClientEntry("analytics", "initAnalytics")],
208
+ onPostProcessed: (context) => {
209
+ tracked.set(context.slug, context.content);
210
+ },
211
+ onManifestCreated: (context) => {
212
+ const tags = buildAnalyticsTags(scriptPath);
213
+ for (const entry of context.manifest.entries) {
214
+ appendAnalyticsTags(entry, tracked.get(entry.slug), tags);
215
+ }
216
+ }
217
+ });
218
+ }
219
+ var analyticsPlugin = analytics;
220
+ function buildAnalyticsTags(scriptPath) {
221
+ const href = escapeHtmlAttribute(scriptPath);
222
+ return [
223
+ `<link rel="preload" as="script" href="${href}" />`,
224
+ `<script defer src="${href}" ${ANALYTICS_SCRIPT_ATTRIBUTE}></script>`
225
+ ].join("\n");
226
+ }
227
+ function appendAnalyticsTags(entry, content, tags) {
228
+ if (!entry.html.includes(ANALYTICS_SCRIPT_ATTRIBUTE)) {
229
+ entry.html = `${entry.html}
230
+ ${tags}`;
231
+ }
232
+ if (content && !content.html.includes(ANALYTICS_SCRIPT_ATTRIBUTE)) {
233
+ content.html = `${content.html}
234
+ ${tags}`;
235
+ }
236
+ }
237
+ export {
238
+ ANALYTICS_PROVIDERS,
239
+ ANALYTICS_SCRIPT_ATTRIBUTE,
240
+ ANALYTICS_SCRIPT_PATH,
241
+ analytics,
242
+ analyticsPlugin,
243
+ buildAnalyticsScript,
244
+ initAnalytics,
245
+ validateAnalyticsOptions
246
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Default path of the analytics bootstrap endpoint and of the `<script>` tag
3
+ * the client entry injects.
4
+ *
5
+ * Client entries are static — they receive no plugin options — so the built-in
6
+ * `initAnalytics` always loads this exact path. Overriding `scriptPath` mounts
7
+ * the endpoint elsewhere and requires a custom client entry; the default is
8
+ * kept here so both sides share one compile-time constant.
9
+ */
10
+ export declare const ANALYTICS_SCRIPT_PATH = "/_analytics.js";
11
+ /**
12
+ * `data-*` attribute that marks the analytics `<script>` tag.
13
+ *
14
+ * The server-side injection (`onManifestCreated`) and the browser initializer
15
+ * (`initAnalytics`) both carry this attribute, so a built page can be verified
16
+ * from its real output and the initializer stays idempotent.
17
+ */
18
+ export declare const ANALYTICS_SCRIPT_ATTRIBUTE = "data-riebeckite-analytics";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Injects the analytics bootstrap `<script>` into `document.head` exactly once.
3
+ * The bootstrap endpoint then loads the configured provider script.
4
+ *
5
+ * This initializer is static: it always loads `ANALYTICS_SCRIPT_PATH`. It has
6
+ * no SPA route awareness — see the README for the documented limitations.
7
+ */
8
+ export declare function initAnalytics(): void;
@@ -0,0 +1,32 @@
1
+ import type { ConfigValidationIssue } from "@riebeckite/core";
2
+ /** Analytics providers supported by the built-in bootstrap. */
3
+ export declare const ANALYTICS_PROVIDERS: readonly ["plausible", "umami", "google-analytics", "custom"];
4
+ export type AnalyticsProvider = (typeof ANALYTICS_PROVIDERS)[number];
5
+ export type AnalyticsOptions = {
6
+ /** Provider whose bootstrap is served. */
7
+ provider: AnalyticsProvider;
8
+ /** Plausible domain, or optional Umami `data-domains` value. */
9
+ domain?: string;
10
+ /** Umami website id (`data-website-id`). */
11
+ siteId?: string;
12
+ /** Google Analytics measurement id (`G-XXXXXXX`). */
13
+ measurementId?: string;
14
+ /**
15
+ * Overrides the provider's default script URL. For `provider: "custom"` this
16
+ * is the script URL loaded when no `snippet` is given.
17
+ */
18
+ scriptUrl?: string;
19
+ /**
20
+ * Raw bootstrap JavaScript for `provider: "custom"`. This value is trusted:
21
+ * it is served verbatim from the endpoint. Do not build it from untrusted
22
+ * input.
23
+ */
24
+ snippet?: string;
25
+ /**
26
+ * Endpoint and client script path. Defaults to `ANALYTICS_SCRIPT_PATH`
27
+ * (`/_analytics.js`). The built-in client entry always uses the default, so
28
+ * changing this requires a matching custom client entry.
29
+ */
30
+ scriptPath?: string;
31
+ };
32
+ export declare function validateAnalyticsOptions(options: AnalyticsOptions | undefined): readonly ConfigValidationIssue[];
@@ -0,0 +1,10 @@
1
+ import type { AnalyticsOptions } from "./options.js";
2
+ /**
3
+ * Builds the JavaScript served from the analytics endpoint.
4
+ *
5
+ * Every configured value is JSON-encoded before it is embedded, so a value can
6
+ * never break out of the string literal that holds it. The one exception is
7
+ * `provider: "custom"` with a `snippet`, which is intentionally trusted and
8
+ * returned verbatim.
9
+ */
10
+ export declare function buildAnalyticsScript(options: AnalyticsOptions): string;
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@riebeckite/plugin-analytics",
3
+ "version": "0.0.1",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "source": "./index.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./client": {
16
+ "types": "./dist/client.d.ts",
17
+ "import": "./dist/client.js",
18
+ "source": "./client.ts",
19
+ "default": "./dist/client.js"
20
+ }
21
+ },
22
+ "dependencies": {
23
+ "@riebeckite/core": "0.0.1"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "files": [
29
+ "LICENSE",
30
+ "README.md",
31
+ "README_ja.md",
32
+ "dist"
33
+ ],
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/Rerurate514/riebeckite.git",
37
+ "directory": "packages/plugins/analytics"
38
+ },
39
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
42
+ },
43
+ "description": "Analytics provider integration for Riebeckite sites.",
44
+ "keywords": [
45
+ "riebeckite",
46
+ "plugin",
47
+ "analytics",
48
+ "web-analytics"
49
+ ],
50
+ "engines": {
51
+ "node": "^20.19.0 || >=22.12.0"
52
+ },
53
+ "sideEffects": false,
54
+ "scripts": {
55
+ "build": "node ../../../scripts/build_package.mjs"
56
+ }
57
+ }